diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index c003f465..d4e361ff 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1118,9 +1118,30 @@ pub(crate) fn palette_rect_hits() -> usize { PALETTE_RECT_HITS.with(|c| c.get()) } -// lane-palette2 r1: how many palette-Y blocks decoded with a split luma -// transform (`tx_select && logical_tx != side`) -- proves the per-TU index-map -// slicing actually ran, not just that the whole-block path stayed exact. +// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the +// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] -- +// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in +// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per +// RD, almost always refused-on-use because the block doesn't end up USING a +// palette -- see r5's report). This is the site the removed refusal +// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it +// fired here whether or not the block picked a palette, so this is the +// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost +// never observes. +thread_local! { + static RECT_SCREEN_CONTENT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT_SCREEN_CONTENT_HITS`]. +pub(crate) fn rect_screen_content_hits() -> usize { + RECT_SCREEN_CONTENT_HITS.with(|c| c.get()) +} + +// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a +// split luma transform (`logical_tx != side`) -- proves the per-TU index-map +// windowing actually ran, not just that the whole-block path stayed exact. +// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16); +// first actually incremented in r7, when the refusal it guarded was lifted. thread_local! { static PALETTE_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -1143,6 +1164,38 @@ thread_local! { const { std::cell::RefCell::new(None) }; } + +/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct` +/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a +/// site whose reconstruct never runs would be picked up by the NEXT block's +/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so +/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site. +#[track_caller] +fn set_palette_pred(buf: Vec) { + if std::env::var_os("EC_DEBUG_PAL").is_some() { + let stale = PALETTE_PRED.with(|c| c.borrow().is_some()); + eprintln!( + "PALSET len={} stale={stale} at {}", + buf.len(), + std::panic::Location::caller() + ); + } + PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf)); +} + +#[track_caller] +fn take_palette_pred() -> Option> { + let got = PALETTE_PRED.with(|c| c.borrow_mut().take()); + if std::env::var_os("EC_DEBUG_PAL").is_some() { + eprintln!( + "PALTAKE len={:?} at {}", + got.as_ref().map(Vec::len), + std::panic::Location::caller() + ); + } + got +} + thread_local! { /// The current frame's `mi` grid, kept only while a frame header set /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary @@ -3302,12 +3355,36 @@ impl Neighbours { /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's /// call sites are all square blocks). fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { + self.record_palette_y_rect(at, side, side, size, colors); + } + + /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`) + /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs + /// [`Self::record`]): a true rect strip's above/left neighbour spans + /// differ. + fn record_palette_y_rect( + &mut self, + at: (usize, usize), + w: usize, + h: usize, + size: usize, + colors: [u16; 8], + ) { let (r, c) = at; - for cell in 0..side / SUB { + // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain + // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the + // next block read a long-dead palette out of the above/left arrays + // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps + // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a + // sub-16 leaf stamps its whole containing cell -- safe today because + // every sub-16 leaf path refuses palette outright (so it can only + // ever stamp `size == 0`, and its cell holds no palette sibling). + // Upgrade path: widen the palette arrays to mi granularity. + for cell in 0..(w / SUB).max(1) { self.above_palette_size[c + cell] = size; self.above_palette_colors[c + cell] = colors; } - for cell in 0..side / SUB { + for cell in 0..(h / SUB).max(1) { self.left_palette_size[r + cell] = size; self.left_palette_colors[r + cell] = colors; } @@ -3316,12 +3393,22 @@ impl Neighbours { /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left /// neighbours that are themselves a palette-Y block, plus /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour - /// cache (pred_common.c:73) -- the above neighbour is excluded at a - /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells - /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is. + /// cache (pred_common.c:73). + /// + /// The SB-top-row exclusion of the above neighbour (`row % 64` in + /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to + /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain + /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to + /// the ctx too made every superblock in the frame's second SB row read + /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real + /// palette block decoded as "no palette" and the tile desynced from + /// there (class [[cdf-row-held-constant]]). fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec) { let (r, c) = at; let above_ok = r % 4 != 0; + // `xd->above_mbmi` exists for every row but the tile's own first. + let above_is_palette = + r * (SUB / MI) > self.tile_row0_mi && self.above_palette_size[c] > 0; let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 { (self.above_palette_size[c], self.above_palette_colors[c]) } else { @@ -3338,7 +3425,7 @@ impl Neighbours { } else { (0, [0u16; 8]) }; - let ctx = usize::from(above_n > 0) + usize::from(left_n > 0); + let ctx = usize::from(above_is_palette) + usize::from(left_n > 0); let mut cache = Vec::with_capacity(16); let push_dedup = |cache: &mut Vec, v: u16| { if cache.last() != Some(&v) { @@ -3374,12 +3461,28 @@ impl Neighbours { /// (U-channel) palette size/colours -- `size == 0` clears stale state the /// same way (lane-palette2 r1). fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { + self.record_palette_uv_rect(at, side, side, size, colors); + } + + /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`) + /// extents, in LUMA pixels (lane-palette2 r4, same convention as + /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at + /// luma resolution regardless of which plane the recorded state is for). + fn record_palette_uv_rect( + &mut self, + at: (usize, usize), + w: usize, + h: usize, + size: usize, + colors: [u16; 8], + ) { let (r, c) = at; - for cell in 0..side / SUB { + // See [`Self::record_palette_y_rect`] for the `.max(1)`. + for cell in 0..(w / SUB).max(1) { self.above_palette_uv_size[c + cell] = size; self.above_palette_uv_colors[c + cell] = colors; } - for cell in 0..side / SUB { + for cell in 0..(h / SUB).max(1) { self.left_palette_uv_size[r + cell] = size; self.left_palette_uv_colors[r + cell] = colors; } @@ -4212,17 +4315,20 @@ fn palette_bsize_ctx(side: usize) -> Option { } /// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip -/// (lane-palette2 r1) -- the same `log2(bw*bh) - 6` formula, this decoder's -/// square call sites are just `bw == bh`. +/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's +/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes +/// for ANY bsize, not just the square ones a hand-picked table happened to +/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned +/// row breaks the moment its indexing field moves off the diagonal, and a +/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1 +/// block dimension is a power of two, so `bw*bh` always is too and +/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own +/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`). fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option { - match (bw, bh) { - (8, 8) => Some(0), - (16, 16) => Some(2), - (32, 16) | (16, 32) => Some(3), - (32, 32) => Some(4), - (64, 64) => Some(6), - _ => None, + if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) { + return None; } + Some(((bw * bh) as u32).trailing_zeros() as usize - 6) } /// A just-decoded palette-Y block's own size, base colours (only the first @@ -4472,9 +4578,25 @@ fn decode_color_index_map( n: usize, side: usize, uv: bool, +) -> Vec { + decode_color_index_map_wh(dec, cdfs, n, side, side, uv) +} + +/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip +/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal +/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh` +/// independently rather than one shared `side` -- the square call above is +/// just `bw == bh`. +fn decode_color_index_map_wh( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + n: usize, + bw: usize, + bh: usize, + uv: bool, ) -> Vec { let trace = std::env::var_os("EC_AV1_TRACE").is_some(); - let mut map = vec![0u8; side * side]; + let mut map = vec![0u8; bw * bh]; if trace { let (rng, _) = dec.debug_state(); eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}"); @@ -4484,13 +4606,13 @@ fn decode_color_index_map( let (rng, _) = dec.debug_state(); eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]); } - for i in 1..(2 * side - 1) { - let j_hi = i.min(side - 1); - let j_lo = i.saturating_sub(side - 1); + for i in 1..(bw + bh - 1) { + let j_hi = i.min(bw - 1); + let j_lo = i.saturating_sub(bh - 1); for j in (j_lo..=j_hi).rev() { let row = i - j; let col = j; - let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n); + let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n); if trace { let (rng, _) = dec.debug_state(); eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}"); @@ -4500,7 +4622,7 @@ fn decode_color_index_map( } else { dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]) }; - map[row * side + col] = color_order[symbol]; + map[row * bw + col] = color_order[symbol]; if trace { let (rng, _) = dec.debug_state(); eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}"); @@ -4510,12 +4632,14 @@ fn decode_color_index_map( map } -/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1): -/// identical except the `use_filter_intra` size class comes from -/// [`filter_intra_size_class_rect`] instead of the square-only -/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`, -/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or -/// neighbour state, never by block size. +/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1, +/// palette wired lane-palette2 r4): identical except the `use_filter_intra` +/// size class comes from [`filter_intra_size_class_rect`] instead of the +/// square-only [`filter_intra_size_class`], and the palette read (when +/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/ +/// [`decode_color_index_map_wh`] instead of their square-only counterparts -- +/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`, +/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size. #[allow(clippy::too_many_arguments)] fn read_intra_mode_rect( dec: &mut SymbolDecoder, @@ -4528,6 +4652,11 @@ fn read_intra_mode_rect( enable_filter_intra: bool, skip_ctx: usize, allow_screen_content_tools: bool, + // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params: + // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y + // block here, `None` still reads (and refuses on use) the symbol at ctx 0. + palette: Option<(usize, &[u16])>, + palette_uv_cache: &[u16], mi_r: usize, mi_c: usize, ) -> Result<( @@ -4538,17 +4667,9 @@ fn read_intra_mode_rect( i32, Option<(i32, i32)>, Option, + Option, + Option, )> { - // lane-screen consumes palette/intrabc syntax in the SQUARE reader only - // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a - // screen-content frame would therefore skip symbols the encoder wrote and - // desync the tile, so refuse it by name rather than decode it wrong. - 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 ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some(); macro_rules! istep { ($name:literal, $val:expr) => { @@ -4613,6 +4734,42 @@ fn read_intra_mode_rect( if angle_delta_uv != 0 { UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1)); } + // `read_palette_mode_info` (spec 5.11.13), rect-generalised + // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`], + // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only + // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/ + // colours only here, the colour-index maps deferred past `filter_intra` + // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette` + // runs from the caller, after the whole mode-info read). + let mut palette_y_pending: Option<(usize, [u16; 8])> = None; + let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; + if allow_screen_content_tools + && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) + { + // r6: this is the exact site the removed blanket refusal used to + // guard -- reached for EVERY rect strip in a screen-content frame, + // independent of whether the block ends up using a palette. + RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1)); + let (mode_ctx, cache) = palette.unwrap_or((0, &[])); + let use_palette_y = + mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; + if use_palette_y { + if palette.is_none() { + return Err(unsupported( + "a block that actually uses a palette (Y) -- reconstruction is out of scope", + )); + } + let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); + let colors = read_palette_colors_y(dec, n, cache); + palette_y_pending = Some((n, colors)); + } + let palette_uv_mode_ctx = usize::from(use_palette_y); + if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 { + let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); + let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache); + palette_uv_pending = Some((n, u_colors, v_colors)); + } + } let mut filter_intra = None; if std::env::var_os("EC_AV1_TRACE").is_some() { let (rng, _) = dec.debug_state(); @@ -4623,8 +4780,11 @@ fn read_intra_mode_rect( filter_intra_size_class_rect(bw, bh) ); } + // As the square path: `av1_filter_intra_allowed` excludes a palette-Y + // block (reconintra.h:77), so no `use_filter_intra` symbol exists there. if mode == DC_PRED && enable_filter_intra + && palette_y_pending.is_none() && let Some(class) = filter_intra_size_class_rect(bw, bh) { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; @@ -4637,6 +4797,19 @@ fn read_intra_mode_rect( filter_intra = Some(fi_mode); } } + // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map), + // same order as [`read_intra_mode`]'s own square path. + let palette_y = palette_y_pending.map(|(n, colors)| { + let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false); + PALETTE_HITS.with(|c| c.set(c.get() + 1)); + PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1)); + PaletteY { size: n, colors, map } + }); + let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| { + let map = decode_color_index_map_wh(dec, cdfs, n, bw / 2, bh / 2, true); + PALETTE_UV_HITS.with(|c| c.set(c.get() + 1)); + PaletteUv { size: n, u_colors, v_colors, map } + }); Ok(( skip, mode, @@ -4645,6 +4818,8 @@ fn read_intra_mode_rect( angle_delta_uv, alpha, filter_intra, + palette_y, + palette_uv, )) } @@ -4700,6 +4875,15 @@ struct RectStripModes { filter_intra: Option, smooth_neighbor: bool, smooth_neighbor_uv: bool, + /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already + /// mapped through the colour table), sliced per transform unit below -- + /// palette prediction reads no edge pixels, so a unit's slice of the + /// whole-block map IS its prediction. Without this a palette strip whose + /// transform splits predicted DC and came out flat grey while the entropy + /// stream stayed in sync (the coefficients are read either way). + palette_y: Option>, + /// As `palette_y`, for the un-split chroma transform (U, V). + palette_uv: Option<(Vec, Vec)>, } /// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma @@ -4795,20 +4979,17 @@ fn decode_rect_split( // (`row_off + tx_high < plane_bh`) they are the left // neighbour's, already reconstructed; the last row falls back // to the block-level answer. - let tu_reach = Reach { - above_right: if col_off + tx < bw { - true - } else { - row_off == 0 && block_reach.above_right - }, - below_left: if col_off > 0 { - false - } else if row_off + tx < bh { - true - } else { - block_reach.below_left - }, - }; + let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx, block_reach); + // The unit's own window on the block's palette prediction. + if let Some(buf) = &m.palette_y { + let tu_buf: Vec = (0..tx) + .flat_map(|i| { + let base = (row_off + i) * bw + col_off; + buf[base..base + tx].iter().copied() + }) + .collect(); + set_palette_pred(tu_buf); + } if m.skip { y.reconstruct( tu_px, @@ -4860,10 +5041,16 @@ fn decode_rect_split( let reach = block_reach; let (u_grid, v_grid) = if m.skip { let zero = vec![0i32; chroma_w * chroma_h]; + if let Some((ub, _)) = &m.palette_uv { + set_palette_pred(ub.clone()); + } u.reconstruct_rect( cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, ); + if let Some((_, vb)) = &m.palette_uv { + set_palette_pred(vb.clone()); + } v.reconstruct_rect( cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, @@ -4917,6 +5104,10 @@ fn decode_rect_split( .zip(ac.as_deref()) .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; + if let Some((ub, vb)) = &m.palette_uv { + let buf = if plane_idx == 1 { ub } else { vb }; + set_palette_pred(buf.clone()); + } plane.reconstruct_rect( cpx, cpy, @@ -4977,7 +5168,9 @@ fn decode_block_rect( let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); - let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = + let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); + let palette_uv_cache = neighbours.palette_uv_cache(at); + let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, @@ -4989,6 +5182,8 @@ fn decode_block_rect( enable_filter_intra, neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, + Some((palette_ctx, &palette_cache)), + &palette_uv_cache, r * (SUB / MI), c * (SUB / MI), )?; @@ -5053,10 +5248,34 @@ fn decode_block_rect( filter_intra, smooth_neighbor, smooth_neighbor_uv, + palette_y: palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), + palette_uv: palette_uv.as_ref().map(|p| { + ( + p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), + p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), + ) + }), }; + if palette_y.is_some() || palette_uv.is_some() { + PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + } decode_rect_split( dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set, )?; + // This early return skips this fn's own tail, so the palette + // neighbour state has to be stamped HERE too: without it a split-tx + // strip left the above/left palette arrays holding a DEAD block's + // colours, and the next block's colour cache + // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the + // wrong VALUE -- same bit count, so the entropy stream stayed in sync + // and only those pixels were wrong (lane-palette2 r10). + let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors); + let (puv_size, puv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors); RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); return Ok(()); } @@ -5072,6 +5291,19 @@ fn decode_block_rect( skip as i32 ); } + // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV + // block's prediction is the reconstructed colour-index map, set fresh + // right before each `reconstruct_rect` call below (lane-palette2 r4). + if let Some(ref pyv) = palette_y { + let buf: Vec = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect(); + set_palette_pred(buf); + } + let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|puv| { + ( + puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), + puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), + ) + }); if skip { y.reconstruct_rect( px, @@ -5087,6 +5319,9 @@ fn decode_block_rect( smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + if let Some((ub, _)) = &palette_uv_bufs { + set_palette_pred(ub.clone()); + } u.reconstruct_rect( cpx, cpy, @@ -5100,6 +5335,9 @@ fn decode_block_rect( None, smooth_neighbor_uv, ); + if let Some((_, vb)) = &palette_uv_bufs { + set_palette_pred(vb.clone()); + } v.reconstruct_rect( cpx, cpy, @@ -5211,6 +5449,9 @@ fn decode_block_rect( smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + if let Some((ub, _)) = &palette_uv_bufs { + set_palette_pred(ub.clone()); + } let u_default_tx = default_intra_tx_type(uv_predict_mode as u8); let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1); let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); @@ -5251,6 +5492,9 @@ fn decode_block_rect( None, smooth_neighbor_uv, ); + if let Some((_, vb)) = &palette_uv_bufs { + set_palette_pred(vb.clone()); + } let v_default_tx = default_intra_tx_type(uv_predict_mode as u8); let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1); let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode); @@ -5295,6 +5539,11 @@ fn decode_block_rect( RECT_COEFF_HITS.with(|c| c.set(c.get() + 1)); } } + let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors); + let (puv_size, puv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0); RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); @@ -5374,7 +5623,16 @@ fn decode_leaf_rect( if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); } - let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = + // The palette-Y mode CDF row is picked by the neighbours' palette use + // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real + // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use + // a palette narrows the wrong interval and desyncs the tile even when the + // decoded bit is the same. The cell is the 16px-SUB cell containing the + // leaf (the palette neighbour arrays have no finer granularity). + let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI)); + let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(pal_at); + let palette_uv_cache = neighbours.palette_uv_cache(pal_at); + let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, @@ -5386,9 +5644,19 @@ fn decode_leaf_rect( enable_filter_intra, neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1), allow_screen_content_tools, + Some((palette_ctx, &palette_cache)), + &palette_uv_cache, leaf_mi.0, leaf_mi.1, )?; + if palette_y.is_some() || palette_uv.is_some() { + // Symbols (mode/size/colours/index map) are all read above, so the + // tile stays in sync; only the *pixel* reconstruction of a palette on + // a below-16x16 strip is unported and ungated (lane-palette2 r7). + return Err(unsupported( + "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)", + )); + } if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() { eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}"); } @@ -5512,6 +5780,12 @@ fn decode_leaf_rect( neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]); neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip); neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0); + // This leaf is necessarily non-palette (a palette one refused above), so + // it must CLEAR the above/left palette state over its own span -- without + // this the next block's `palette_y_mode` ctx and colour cache were read + // off whatever block last covered the cell (lane-palette2 r8). + neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]); + neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]); // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and // rows -- record the whole span, not one cell. neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode); @@ -5569,21 +5843,42 @@ fn decode_block_rect4( left_mode = pmode; } } - let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = - read_intra_mode_rect( - dec, - cdfs, - above_mode, - left_mode, - true, - bw, - bh, - enable_filter_intra, - neighbours.skip_txfm_ctx(mi_r, mi_c), - allow_screen_content_tools, - mi_r, - mi_c, - )?; + let ( + skip, + mode, + angle_delta_y, + uv_mode, + angle_delta_uv, + alpha, + filter_intra, + palette_y, + palette_uv, + ) = read_intra_mode_rect( + dec, + cdfs, + above_mode, + left_mode, + true, + bw, + bh, + enable_filter_intra, + neighbours.skip_txfm_ctx(mi_r, mi_c), + allow_screen_content_tools, + None, + &[], + mi_r, + mi_c, + )?; + // Merge of lane-palette2: `read_intra_mode_rect` now reads the palette + // syntax for every rect strip, but this 1:4 decoder has no palette + // reconstruction path (its caller never passes a cache). The symbols are + // still read, so the stream stays in sync; a strip that ACTUALLY uses a + // palette is refused rather than reconstructed wrong. + if palette_y.is_some() || palette_uv.is_some() { + return Err(unsupported( + "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", + )); + } let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); @@ -5788,7 +6083,7 @@ fn decode_block_rect4( None, smooth_neighbor_uv, ); - neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels, u_levels, v_levels]); + neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]); neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0); if bw > bh { @@ -5836,7 +6131,9 @@ fn decode_block_rect64( let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); - let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = + let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); + let palette_uv_cache = neighbours.palette_uv_cache(at); + let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, cdfs, @@ -5855,9 +6152,23 @@ fn decode_block_rect64( enable_filter_intra, neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)), allow_screen_content_tools, + Some((palette_ctx, &palette_cache)), + &palette_uv_cache, r * (SUB / MI), c * (SUB / MI), )?; + if (palette_y.is_some() || palette_uv.is_some()) && !skip { + // The luma coefficient path here is the corner-cropped 32x32 real + // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s + // own doc comment) -- a real (non-skip) palette block's residual + // needs the plain, uncropped rect reader [`decode_block_rect`] already + // has, not this one's truncation. `skip` (no residual at all) is + // still supported below (lane-palette2 r4). + return Err(unsupported( + "a palette block with a real transform on a superblock-level HORZ/VERT \ + strip (corner-cropped luma coefficients not ported for palette)", + )); + } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); @@ -5917,10 +6228,31 @@ fn decode_block_rect64( filter_intra, smooth_neighbor, smooth_neighbor_uv, + palette_y: palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()), + palette_uv: palette_uv.as_ref().map(|p| { + ( + p.map.iter().map(|&i| p.u_colors[i as usize]).collect(), + p.map.iter().map(|&i| p.v_colors[i as usize]).collect(), + ) + }), }; + if palette_y.is_some() || palette_uv.is_some() { + PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + } decode_rect_split( dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set, )?; + // Same early-return palette stamp as [`decode_block_rect`]'s split arm + // (lane-palette2 r10): this return skips the fn's own tail, so a + // split-tx superblock strip would otherwise leave the above/left + // palette arrays holding a dead block's colours. + let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors); + let (puv_size, puv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors); RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); return Ok(()); } @@ -5928,6 +6260,16 @@ fn decode_block_rect64( let (cpx, cpy) = (px / 2, py / 2); let (chroma_w, chroma_h) = (bw / 2, bh / 2); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + if let Some(ref pyv) = palette_y { + let buf: Vec = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect(); + set_palette_pred(buf); + } + let palette_uv_bufs: Option<(Vec, Vec)> = palette_uv.as_ref().map(|puv| { + ( + puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(), + puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(), + ) + }); if skip { y.reconstruct_rect( px, @@ -5943,6 +6285,9 @@ fn decode_block_rect64( smooth_neighbor, ); let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + if let Some((ub, _)) = &palette_uv_bufs { + set_palette_pred(ub.clone()); + } u.reconstruct_rect( cpx, cpy, @@ -5956,6 +6301,9 @@ fn decode_block_rect64( None, smooth_neighbor_uv, ); + if let Some((_, vb)) = &palette_uv_bufs { + set_palette_pred(vb.clone()); + } v.reconstruct_rect( cpx, cpy, @@ -6215,6 +6563,11 @@ fn decode_block_rect64( neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]); RECT_COEFF_HITS.with(|c| c.set(c.get() + 1)); } + let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors); + let (puv_size, puv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors); neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip); neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0); SB_RECT_HITS.with(|c| c.set(c.get() + 1)); @@ -6790,42 +7143,50 @@ impl PlaneBuf { filter_intra: Option, smooth_neighbor: bool, ) { - let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); - if std::env::var_os("EC_DEBUG_EDGES").is_some() { - eprintln!( - "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}", - above.as_ref().map(|a| (a.len(), a[0])), - left.as_ref().map(|l| l.len()), - left.as_ref().map(|l| l[0]), - self.tile_x0, self.tile_y0, self.true_width, self.true_height - ); - } - let mut prediction = vec![0u16; bw * bh]; - if let Some(fi_mode) = filter_intra { - crate::intra::predict_filter_intra( - fi_mode, - above.as_deref(), - left.as_deref(), - corner, - bw, - bh, - &mut prediction, - ); + // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override + // (lane-palette2 r4): a palette block's prediction is the + // reconstructed colour-index map, needing no edge pixels at all. + let prediction = if let Some(buf) = take_palette_pred() { + buf } else { - let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get); - predict( - mode as u8, - angle_delta, - above.as_deref(), - left.as_deref(), - corner, - bw, - bh, - enable_edge_filter, - smooth_neighbor, - &mut prediction, - ); - } + let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); + if std::env::var_os("EC_DEBUG_EDGES").is_some() { + eprintln!( + "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}", + above.as_ref().map(|a| (a.len(), a[0])), + left.as_ref().map(|l| l.len()), + left.as_ref().map(|l| l[0]), + self.tile_x0, self.tile_y0, self.true_width, self.true_height + ); + } + let mut prediction = vec![0u16; bw * bh]; + if let Some(fi_mode) = filter_intra { + crate::intra::predict_filter_intra( + fi_mode, + above.as_deref(), + left.as_deref(), + corner, + bw, + bh, + &mut prediction, + ); + } else { + let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get); + predict( + mode as u8, + angle_delta, + above.as_deref(), + left.as_deref(), + corner, + bw, + bh, + enable_edge_filter, + smooth_neighbor, + &mut prediction, + ); + } + prediction + }; for row in 0..bh { for col in 0..bw { let idx = row * bw + col; @@ -6869,7 +7230,7 @@ impl PlaneBuf { // A palette block's own [`PALETTE_PRED`] override (lane-palette r2) // takes priority over `predict()`/`predict_filter_intra` entirely -- // palette prediction needs no edge pixels at all. - let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) { + let prediction = if let Some(buf) = take_palette_pred() { buf } else { let (above, left, corner) = self.edges(x, y, side, reach); @@ -7197,7 +7558,7 @@ fn decode_block( (yb, ub, vb) }); if let Some((yb, _, _)) = &intrabc_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(yb.clone())); + set_palette_pred(yb.clone()); } // A palette-Y block's own prediction is the reconstructed colour-index // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it @@ -7207,18 +7568,21 @@ fn decode_block( // would need the map sliced per-TU -- untested against a real // `--enable-palette=1` stream this round, so refuse by name rather than // guess at the slicing (charter's own named-acceptable fallback). - if let Some(ref py) = palette_y { - if tx_select && logical_tx != side { - return Err(unsupported( - "a palette block with a split luma transform (round 1)", - )); - } - let buf: Vec = py - .map + let palette_y_buf: Option> = palette_y.as_ref().map(|py| { + py.map .iter() .map(|&idx| py.colors[idx as usize]) - .collect(); - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf)); + .collect() + }); + // With one luma transform unit the whole `side`x`side` map is the + // prediction; with several (`logical_tx != side`) each unit takes its own + // `logical_tx`-sized window of that same map, set fresh inside the TU loop + // below (lane-palette2 r7) -- setting the full-block buffer here would be + // taken by the FIRST unit and indexed at the wrong stride. + if let Some(buf) = &palette_y_buf + && logical_tx == side + { + set_palette_pred(buf.clone()); } // A UV-palette block's own chroma prediction override (lane-palette2 r1), // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each @@ -7255,7 +7619,7 @@ fn decode_block( ); let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone())); + set_palette_pred(ub.clone()); } u.reconstruct( cpx, @@ -7270,7 +7634,7 @@ fn decode_block( smooth_neighbor_uv, ); if let Some((_, vb)) = &palette_uv_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone())); + set_palette_pred(vb.clone()); } v.reconstruct( cpx, @@ -7317,7 +7681,7 @@ fn decode_block( )?; let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone())); + set_palette_pred(ub.clone()); } let u_grid = read_plane( dec, @@ -7348,7 +7712,7 @@ fn decode_block( ); } if let Some((_, vb)) = &palette_uv_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone())); + set_palette_pred(vb.clone()); } let v_grid = read_plane( dec, @@ -7390,12 +7754,34 @@ fn decode_block( let tu_px = px + tu_col * logical_tx; let tu_py = py + tu_row * logical_tx; let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; - let tu_reach = Reach::of_tu(side, logical_tx, tu_px, tu_py, y.width, y.height); + // A transform unit inside a block is NOT a block at that + // position (lane-palette2 r12): `Reach::of` granted the + // top-right 8x8 unit of a 16x16 D203 block bottom-left + // pixels libaom refuses outright (`col_off > 0`), which is + // the diagonal wedge seed 46 reconstructed wrong. + let tu_reach = Reach::of_tu( + side, + side, + tu_col * logical_tx, + tu_row * logical_tx, + logical_tx, + reach, + ); // This transform unit's own bsize (`logical_tx`) is smaller // than the block it sits in (`side`), so `txb_skip_ctx` is // the neighbour-magnitude table, not the lone-TU 0 (spec // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch). let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI); + if let Some(buf) = &palette_y_buf { + PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + let mut window = vec![0u16; logical_tx * logical_tx]; + for row in 0..logical_tx { + let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx; + window[row * logical_tx..][..logical_tx] + .copy_from_slice(&buf[src..][..logical_tx]); + } + set_palette_pred(window); + } let tu_grid = read_plane( dec, cdfs, @@ -7432,7 +7818,7 @@ fn decode_block( let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); let chroma_around = neighbours.around(at, side); if let Some((ub, _)) = &palette_uv_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone())); + set_palette_pred(ub.clone()); } let u_grid = read_plane( dec, @@ -7457,7 +7843,7 @@ fn decode_block( smooth_neighbor_uv, )?; if let Some((_, vb)) = &palette_uv_bufs { - PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone())); + set_palette_pred(vb.clone()); } let v_grid = read_plane( dec, @@ -7765,7 +8151,7 @@ fn decode_leaf8( if crate::encode::Reach::in_vert_ab() { VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1)); } - let tu_reach = Reach::of_tu(8, 4, tu_px, tu_py, y.width, y.height); + let tu_reach = Reach::of_tu(8, 8, tu_col * 4, tu_row * 4, 4, reach); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); let tu_grid = read_plane( dec, @@ -7878,12 +8264,28 @@ fn decode_leaf8( neighbours.above[leaf_mi.1 + cell][2] = v_state; } } + // Non-palette 8x8 leaf (this path never reads a palette): clear the + // above/left palette state over its own cell so the next block's ctx and + // colour cache do not read a previous block's palette (lane-palette2 r8). + { + let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI)); + neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]); + neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]); + } neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 4, 0); neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); return Ok(mode); } neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); + // Non-palette 8x8 leaf (this path never reads a palette): clear the + // above/left palette state over its own cell so the next block's ctx and + // colour cache do not read a previous block's palette (lane-palette2 r8). + { + let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI)); + neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]); + neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]); + } neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid(leaf_mi, 2, 8, 0); neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode); @@ -8293,7 +8695,12 @@ fn decode_leaf_rect8( }; let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); let tu_around = neighbours.around_mi(tu_mi, 4)[0]; - let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height); + // Same per-TU rule as every other split-transform site + // (lane-palette2 r12): a transform unit inside a block is not + // a block at that position, so its reach comes from the + // block's own row, offset by the unit's position. + let tu_reach = + Reach::of_tu(bw, bh, tu_px - px, tu_py - py, 4, reach); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); if skip { // A skipped leaf still predicts per transform unit: the @@ -18847,6 +19254,33 @@ mod tests { assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap())); } + /// A below-16px leaf must clear the palette neighbour state over its own + /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops + /// ran zero times for any sub-16 span, so `decode_leaf_rect` / + /// `decode_leaf8` left a previous block's palette size and colours in the + /// above/left arrays and the NEXT block read `palette_y_mode` off the + /// wrong CDF row with a stale colour cache (class + /// [[cdf-row-held-constant]]). + #[test] + fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() { + let mut n = Neighbours::new(4, 4, 16, 16); + // A real 16x16 palette block covering SUB cell (1, 1). + n.record_palette_y_rect((1, 1), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]); + let (ctx, cache) = n.palette_ctx_and_cache((1, 1)); + assert_eq!(ctx, 2, "the palette block itself must be visible"); + assert_eq!(cache, vec![7, 9]); + // An 8x8 non-palette leaf in that same cell. + n.record_palette_y_rect((1, 1), 8, 8, 0, [0u16; 8]); + let (ctx, cache) = n.palette_ctx_and_cache((1, 1)); + assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell"); + assert!(cache.is_empty(), "and its stale colour cache with it"); + // Same for the chroma half. + n.record_palette_uv_rect((1, 1), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]); + assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]); + n.record_palette_uv_rect((1, 1), 8, 8, 0, [0u16; 8]); + assert!(n.palette_uv_cache((1, 1)).is_empty()); + } + /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`): /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]` diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index e5094ff2..0a1da4e0 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1008,7 +1008,7 @@ struct At { /// block whose transform covers it whole, whether the samples above its right /// (or below its left) are decoded depends only on where the block sits inside /// its 64x64 superblock, which is a pinned table per block size. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] pub(crate) struct Reach { pub(crate) above_right: bool, pub(crate) below_left: bool, @@ -1215,6 +1215,44 @@ fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { } impl Reach { + /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a + /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose + /// own answer is `block` -- a different rule from the standalone-block + /// tables, because a unit's neighbours are mostly its own block's + /// already-reconstructed units: + /// * top-right: available while the unit to the right is still inside + /// the block (`col_off + tx < bw`); otherwise only the block's top row + /// of units reaches past it, through the block-level answer + /// (libaom's `row_off > 0` branch returns exactly + /// `col_off + txw < plane_bw`). + /// * bottom-left: a unit outside the block's left column has none + /// (libaom returns 0 for `col_off > 0`); inside the block + /// (`row_off + tx < bh`) they are the left unit's, already + /// reconstructed; the bottom row falls back to the block-level answer. + pub(crate) fn of_tu( + bw: usize, + bh: usize, + col_off: usize, + row_off: usize, + tx: usize, + block: Self, + ) -> Self { + Self { + above_right: if col_off + tx < bw { + true + } else { + row_off == 0 && block.above_right + }, + below_left: if col_off > 0 { + false + } else if row_off + tx < bh { + true + } else { + block.below_left + }, + } + } + /// What a block of `side` samples at `(x, y)` may read past its own edges, /// in a frame of `width` by `height`. pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self { @@ -1254,29 +1292,7 @@ impl Reach { /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a /// real `--enable-tx-size-search=1` stream (lane-ab16 r2). - pub(crate) fn of_tu( - block: usize, - tx: usize, - x: usize, - y: usize, - width: usize, - height: usize, - ) -> Self { - let (row_off, col_off) = ((y % block) / tx, (x % block) / tx); - let n = block / tx; - let (bx, by) = (x - col_off * tx, y - row_off * tx); - Self { - above_right: y > 0 - && x + tx < width - && (col_off + 1 < n || (row_off == 0 && Self::top_right(block, bx, by))), - below_left: x > 0 - && y + tx < height - && col_off == 0 - && (row_off + 1 < n || Self::bottom_left(block, bx, by)), - } - } - - /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0, + /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0, /// the transform covering the whole block, luma): everything before the /// table lookup is that function's own early-exit ladder. fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { @@ -3841,33 +3857,28 @@ mod tests { /// upper right, which a vertical AB partition codes AFTER it /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1). #[test] - fn of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab() { - let (w, h) = (SUPERBLOCK * 2, SUPERBLOCK * 2); - for y in (0..h).step_by(4) { - for x in (0..w).step_by(4) { - let tu = Reach::of_tu(8, 4, x, y, w, h); - let as_block = Reach::of(4, x, y, w, h); - assert_eq!( - (tu.above_right, tu.below_left), - (as_block.above_right, as_block.below_left), - "of_tu(8, 4) at ({x}, {y}) differs from the unit-as-block answer" - ); - // (2): under the vert tables the same lookup must answer at - // all rather than index a row that does not exist. - let _guard = Reach::vert_ab_partition(); - let _ = Reach::of_tu(8, 4, x, y, w, h); - } - } - // (3): the disagreeing cell, both ways round. - let (x, y) = (4, 8); - assert!( - Reach::of_tu(8, 4, x, y, SUPERBLOCK, SUPERBLOCK).above_right, - "ordinary table: the 8x8 above-right of the block at sb row 1 col 0 is coded first" + fn of_tu_follows_the_block_row_including_under_vert_ab() { + // The 8x8 square at superblock row 1, column 0, and the TX4 unit in + // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's + // above-right answer is the BLOCK's, which is the whole reason a unit + // asks the block instead of looking itself up (the + // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2). + let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK); + assert_eq!( + Reach::of_tu(8, 8, 4, 0, 4, plain).above_right, + plain.above_right, + "ordinary table: the top-right TX4 unit takes the block's row" ); let guard = Reach::vert_ab_partition(); - assert!( - !Reach::of_tu(8, 4, x, y, SUPERBLOCK, SUPERBLOCK).above_right, - "vert AB: that 8x8 is the partition's own later-coded right half" + let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK); + assert_eq!( + Reach::of_tu(8, 8, 4, 0, 4, vert).above_right, + vert.above_right, + "vert AB: the unit follows the vert row the block just picked" + ); + assert_ne!( + plain.above_right, vert.above_right, + "this position is the cell where the vert tables disagree; pick another if libaom's tables change" ); drop(guard); } @@ -3963,6 +3974,66 @@ mod tests { /// swept in r6 produced a decodable 16x16-level VERT_B stream (every /// stream that partitions that small first hits the still-refused /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms). + /// [`Reach::of_tu`] against a from-scratch transcription of libaom's + /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma, + /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in + /// pixels -- lane-palette2 r12: the square multi-TU path used the + /// standalone-block tables instead of this rule and granted a 16x16 + /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses. + #[test] + fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { + // libaom, in MI units: bw_unit/bh_unit = block size / 4, + // *_count_unit = tx size / 4. + fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { + let (plane_bw_unit, count) = (bw / 4, tx / 4); + let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); + let _ = bh; + if row_off_u > 0 { + col_off_u + count < plane_bw_unit + } else if col_off_u + count < plane_bw_unit { + true + } else { + blk + } + } + fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { + let (plane_bh_unit, count) = (bh / 4, tx / 4); + let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); + let _ = bw; + if col_off_u > 0 { + false + } else if row_off_u + count < plane_bh_unit { + true + } else { + blk + } + } + for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { + for &tx in &[4usize, 8, 16, 32] { + if tx > bw.min(bh) { + continue; + } + for row_off in (0..bh).step_by(tx) { + for col_off in (0..bw).step_by(tx) { + for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { + let got = Reach::of_tu(bw, bh, col_off, row_off, tx, blk); + assert_eq!( + got.above_right, + libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), + "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" + ); + assert_eq!( + got.below_left, + libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), + "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" + ); + } + } + } + } + } + } + #[test] fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 679aa828..cbf8d911 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -35,6 +35,7 @@ const REFUSALS: &[&str] = &[ "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)", "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)", + "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)", "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", "a 32x32 partition type this decoder does not code (value={part32})", @@ -43,7 +44,8 @@ const REFUSALS: &[&str] = &[ "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4", - "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", + "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)", + "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)", "a block that actually uses a palette (UV) -- reconstruction is out of scope", "a block that actually uses a palette (Y) -- reconstruction is out of scope", "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", @@ -54,7 +56,6 @@ const REFUSALS: &[&str] = &[ "a frame with no mode-info grid", "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)", "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", - "a palette block with a split luma transform (round 1)", "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it", "a reference picture whose height does not match this frame's own true size", "a show_existing_frame header naming an empty reference slot", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 253f9d9a..d27020fa 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3261,6 +3261,350 @@ mod tests { } } + /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT + /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect` + /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a + /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc + /// partition FIRST on every size/cq combo probed -- `--enable-ab- + /// partitions=0` measurably does not stop aomenc choosing one at this + /// screen-content tune (byte-identical output with `=0` vs `=1`, same + /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing + /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code + /// path: the only choices left at the (single, key-frame) superblock are + /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`], + /// and a size/cq sweep (measured live this round) reliably lands + /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both + /// sources. Drives `decode_stream` directly (below any refusal) and + /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that + /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) -- + /// a decode that never lands a rect palette block is not a match. + #[test] + fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_rect_palette_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 mut matched = 0u32; + let mut uncounted_exact = 0u32; + let mut named_refusals = 0u32; + let mut attempts = 0u32; + let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)]; + let cqs = [5u32, 15, 25, 35, 45, 55, 63]; + for src_name in ["smptebars", "rgbtestsrc"] { + for (width, height) in sizes { + for cq in cqs { + attempts += 1; + let source = format!("{src_name}=size={width}x{height}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", + "-t", "0.04", "-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) + ); + let cq_arg = format!("--cq-level={cq}"); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq_arg, + "--cpu-used=4", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-palette=1", + "--min-partition-size=16", + "--max-partition-size=64", + "--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 ({source} cq={cq}): {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = crate::decode::palette_rect_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal \ + ({source} cq={cq}): {msg}" + ); + named_refusals += 1; + eprintln!("{source} cq={cq}: refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + // A successful decode is ALWAYS pixel-compared; the hit + // counter only decides whether the attempt counts toward + // the hit-asserting total (class + // [[gate-skips-on-its-own-failure]]: the old `continue` + // here let 16/70 decoded attempts past without any pixel + // check at all). + let counted = crate::decode::palette_rect_hits() != before; + if !counted { + eprintln!( + "{NAME}: {source} cq={cq} decoded without ever landing a rect \ + palette block (palette_rect_hits unchanged) -- pixel-compared, \ + not counted toward the hit assertion" + ); + } + let frame_count = frames.len(); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| { + got.y != want.y || got.u != want.u || got.v != want.v + }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") + { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!( + "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}" + ); + } + for i in 0..frame_count { + assert_eq!( + frames[i].y, ffmpeg_frames[i].y, + "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg" + ); + assert_eq!( + frames[i].u, ffmpeg_frames[i].u, + "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg" + ); + assert_eq!( + frames[i].v, ffmpeg_frames[i].v, + "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg" + ); + } + if counted { + matched += 1; + } else { + uncounted_exact += 1; + } + } + } + } + assert!( + matched > 0, + "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \ + block ({named_refusals} named refusals) -- palette_rect_hits never proven \ + pixel-exact" + ); + eprintln!( + "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \ + {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \ + named refusals, palette_rect_hits={}", + crate::decode::palette_rect_hits() + ); + } + + /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra + /// strip in a screen-content-tools frame that does NOT necessarily use a + /// palette. This is what the refusal r4 removed actually guarded -- + /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above + /// gates the rarer "and picks a palette" case, which r5 measured RD + /// almost never chooses -- 39/70 of that same sweep DID land here (a + /// clean rect-strip decode with `palette_rect_hits` unchanged), just + /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64` + /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk + /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts + /// [`decode::rect_screen_content_hits`] moved -- proof this stream + /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch -- + /// before comparing pixels. + #[test] + fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_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 mut matched = 0u32; + // Blocks that reconstructed a palette-Y prediction through a SPLIT + // luma transform (lane-palette2 r7's lifted refusal): the same + // screen-content streams exercise it, so this gate proves both. + let mut split_palette_matched = 0u32; + let mut uncounted_exact = 0u32; + let mut named_refusals = 0u32; + let mut attempts = 0u32; + let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)]; + let cqs = [5u32, 15, 25, 35, 45, 55, 63]; + for src_name in ["smptebars", "rgbtestsrc"] { + for (width, height) in sizes { + for cq in cqs { + attempts += 1; + let source = format!("{src_name}=size={width}x{height}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", + "-t", "0.04", "-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) + ); + let cq_arg = format!("--cq-level={cq}"); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq_arg, + "--cpu-used=4", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-palette=1", + "--min-partition-size=16", + "--max-partition-size=64", + "--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 ({source} cq={cq}): {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = crate::decode::rect_screen_content_hits(); + let split_before = crate::decode::palette_split_tx_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal \ + ({source} cq={cq}): {msg}" + ); + named_refusals += 1; + eprintln!("{source} cq={cq}: refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + // Same integrity rule as the palette gate above: decoded + // means pixel-compared, counter or no counter. + let counted = crate::decode::rect_screen_content_hits() != before; + if !counted { + eprintln!( + "{NAME}: {source} cq={cq} decoded without ever running the rect \ + screen-content path (rect_screen_content_hits unchanged) -- \ + pixel-compared, not counted toward the hit assertion" + ); + } + let frame_count = frames.len(); + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| { + got.y != want.y || got.u != want.u || got.v != want.v + }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") + { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!( + "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}" + ); + } + for i in 0..frame_count { + assert_eq!( + frames[i].y, ffmpeg_frames[i].y, + "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg" + ); + assert_eq!( + frames[i].u, ffmpeg_frames[i].u, + "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg" + ); + assert_eq!( + frames[i].v, ffmpeg_frames[i].v, + "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg" + ); + } + if counted { + matched += 1; + } else { + uncounted_exact += 1; + } + if counted && crate::decode::palette_split_tx_hits() > split_before { + split_palette_matched += 1; + } + } + } + } + assert!( + split_palette_matched > 0, + "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \ + split luma transform -- the lifted refusal is ungated" + ); + assert!( + matched > 0, + "{NAME}: no attempt out of {attempts} ever landed a matching rect \ + screen-content block ({named_refusals} named refusals) -- \ + rect_screen_content_hits never proven pixel-exact" + ); + eprintln!( + "{NAME}: {matched}/{attempts} attempts matched pixel-exact \ + ({split_palette_matched} of them through a split-transform palette block), \ + {uncounted_exact} decoded-and-pixel-exact but uncounted, \ + {named_refusals} named refusals, rect_screen_content_hits={}, \ + palette_split_tx_hits={}", + crate::decode::rect_screen_content_hits(), + crate::decode::palette_split_tx_hits() + ); + } + /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s /// harness, but with the deblocking filter left *on* (no /// `--loopfilter-control=0`) at a crf high enough that libaom actually diff --git a/lanes/COMMON-20260901.md b/lanes/COMMON-20260901.md index 83fe2ce2..07c3a305 100644 --- a/lanes/COMMON-20260901.md +++ b/lanes/COMMON-20260901.md @@ -93,3 +93,10 @@ name you started). `pkill -f`/`killall` on cargo/ec_av1 patterns is forbidden. ## NEVER `cargo fmt` IN A LANE (3 lanes lost their diffs to it on 2026-09-02) main is not rustfmt-clean (~6000 lines of churn). Hand-indent; `cargo test --no-run` is the check. If you ran it: extract your own hunks, `git checkout -- crates/`, re-apply. + +## MEMORY (user order 2026-09-02: an unsteady box fails the job) +30 GB box shared by ~10 agents. Every decode/encode/probe invocation runs under +`systemd-run --user --scope -q -p MemoryMax=6G `; suites under a unit with `-p MemoryMax=10G`; +never two suites per lane; film extracts ≤2 s; a watchdog (`ec-memwatch` user unit, log +`$HOME/.cache/ec-memwatch.log`) SIGKILLs any codec/test process above 6 GiB RSS or the largest one +when MemAvailable < 3 GiB — a killed run means YOUR command exceeded the budget: bound it, do not retry as-is. diff --git a/lanes/palette2-r10.report.md b/lanes/palette2-r10.report.md new file mode 100644 index 00000000..f6e6f56e --- /dev/null +++ b/lanes/palette2-r10.report.md @@ -0,0 +1,113 @@ +# lane-palette2 r10 — merged main 06d856d, fixed the U-plane palette defect; full suite finds ONE lane regression + +VERDICT: AMBER (corrected after the full suite ran; the first draft said GREEN off a 6-test +filter run). The chartered work is done — the failing cell decodes pixel-exact and both palette +gates, split_transform, tx_select, refusal_inventory and gate_coverage pass — but the full +`cargo test -p ec-av1 --lib` is 294 passed / 2 failed / 27 ignored, and one of those two +failures is a gate this lane REGRESSES. See STEP 4. + +## STEP 1 — merge main 06d856d (commit 29bbbcd) +Two conflicts, resolved exactly as chartered: +- `crates/ec-av1/src/decode.rs` `reconstruct_rect` (~5892): kept this lane's `PALETTE_PRED` + override wrapper; main's `EC_DEBUG_EDGES` eprintln moved inside the `else`, after + `edges_rect` (it needs `above`/`left`, which only exist there). +- `crates/ec-av1/src/refusal_inventory.rs` (~50): main's list, minus + `"a HORZ/VERT intra strip in a screen-content frame ..."` (this lane lifted it; auto-merge had + already dropped `"a palette block with a split luma transform (round 1)"`), plus this lane's two + palette strings; main's `"a superblock-level 1:4 partition ..."` kept, the lane's stale + `"other than NONE or SPLIT"` copy dropped. +`cargo check -p ec-av1` clean. + +## STEP 2 — the defect (class [[refusal-hides-a-defect]]), root-caused and fixed +Reproduced on the merged tree exactly as chartered (aomenc `--cq-level=45 --cpu-used=4 +--sb-size=64 --min-partition-size=16 --max-partition-size=64 --enable-palette=1`, +smptebars 192x192, sha256 `d1baf950...`): **U 512 bytes wrong, x48..55 y0..63 chroma +(max |d| 28), Y and V exact.** + +The charter's suspect (a stale `PALETTE_PRED` thread-local) was DISPROVED first: +`EC_DEBUG_PAL=1` counted 32 arms and 32 consumptions, `stale=false` on every arm. + +Real root cause, `crates/ec-av1/src/decode.rs:4486` — `decode_block_rect`'s split-transform arm +(`depth != 0`) calls `decode_rect_split` and then `return Ok(())`, **before** the fn's tail that +stamps `record_palette_y_rect` / `record_palette_uv_rect`. So a split-tx rect strip left the +above/left palette arrays holding a DEAD block's size+colours. Traced live: the 32x16 strip at +luma (64,0) never recorded, so the next block (32x32 at luma (96,0), chroma 16x16 at (48,0)) +read `palette_uv_cache = [44, 156]` — the palette of the block at luma (48,0), three blocks back — +where libaom's cache starts at 72. Cache LENGTH matched, so the same `literal(1)` hit bits and the +same 8-bit literal were read: **the entropy stream stayed in sync and only the pixels of that +palette block were wrong** (colour 0 = 44 instead of 72, hence exactly one 8x64 chroma column, and +its vertical propagation down the column). V is exact because V colours are never cached. + +FIX (decode.rs:4482..4497): stamp the same two palette records at the early return. +Sweep for the same shape: `4486` is the ONLY `return Ok(())` in any `decode_block*` / +`decode_leaf*` fn (`grep -n 'return Ok(())' decode.rs` over 3800..7100 → one hit), so this is the +whole class here. + +Instrument kept (charter's set/take symmetry ask): all 20 `PALETTE_PRED` set sites and both take +sites now go through `set_palette_pred` / `take_palette_pred` (decode.rs ~1052), which under +`EC_DEBUG_PAL=1` print every arm (with `#[track_caller]` location and a `stale=` flag showing an +unconsumed predecessor) and every consumption. That is what disproved the stale-thread-local +hypothesis in one run; ad-hoc probes were removed. + +## STEP 3 — gates (EC_AV1_REQUIRE_AOMENC=1, --test-threads=1) +``` +cd /home/user/Documents/Code/Rust/edith_codecs-palette2 +export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 +cargo test -p ec-av1 --lib -j3 -- --test-threads=1 \ + a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \ + a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact \ + refusal_inventory gate_coverage split_transform tx_select +``` +→ **14 passed, 0 failed, 1 ignored** (133.29s). The ignored one is main's own +`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact` +(lane-rectsplit r3 RED at seed 50, not this lane's). +- `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`: **40/70 matched pixel-exact** + (r9: 17/70), 30 decoded-and-pixel-exact but uncounted, **0 named refusals** (r9: 32), + `palette_rect_hits=142`. +- `a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`: **47/70 matched** + (31 through a split-transform palette block), 23 uncounted-exact, 0 named refusals, + `rect_screen_content_hits=355`, `palette_split_tx_hits=627`. +- All 70 attempts per gate now decode AND are pixel-compared; 0 mismatches. + +## EVIDENCE +EVIDENCE: scratchpad/r10.obu (211 B, sha256 d1baf9503c5787d1005d358d36767195279c36c12255d10e25af106ee5849545) + r10.yuv vs ff.yuv | `decode_probe` dump vs `ffmpeg -f obu -i r10.obu -f rawvideo -pix_fmt yuv420p`, before and after the fix | before: U 512 px wrong (x48..55, y0..63, max |d| 28), Y+V exact; after: `cmp -l` = 0 bytes +EVIDENCE: scratchpad/pal.log (EC_DEBUG_PAL=1 trace of the same stream) | 32 PALSET / 32 PALTAKE lines | every arm `stale=false` — the charter's stale-thread-local suspect disproved, not patched around +EVIDENCE: scratchpad/pal4.log + pal5.log | per-block `palette_uv_cache` and palette-record trace | block r=0 c=6 (luma 96,0) read cache [44,156] stamped by luma (48,0); the strip at luma (64,0) has NO record line — the missing stamp +EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1), 6 filters | full 70-attempt sweep on both palette gates | 14 passed, 0 failed, 1 ignored, 133.29s + + +## STEP 4 — full suite on the merged tree (the r10 restart's only new work) +``` +cd /home/user/Documents/Code/Rust/edith_codecs-palette2 +EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3 -- --test-threads=1 +# log: $HOME/.cache/palette2-suite.log +``` +→ **294 passed; 2 failed; 27 ignored** (1390.10s). + +Both failures were attributed against the merge base by building 06d856d in a detached +worktree (own CARGO_TARGET_DIR) and running the same two test names there: + +1. `decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule` — **INHERITED, not this lane.** + FAILS identically at 06d856d (`32x64 nz_map offset at display (row 0, col 2) left: 6 right: 11`). + `git diff 06d856d HEAD` touches neither `cdf.rs` (0 lines) nor this test. Diagnosis: the test + reads `table[col][row]` while the live consumer (`decode.rs:1804`) reads + `table[row.min(4)][col.min(4)]`; commit 44e8768 transposed the two tables and left the test on + the old layout, so **the test is the stale half** — 24 of the 50 cells disagree, exactly a + transposition. NOT fixed here: this lane owns neither the table nor the orientation question + (decode.rs:1785-1795 records the orientation as still unproven), and flipping the test to + `[row][col]` would only pin the current storage. `deferred: nz_map test/consumer layout — + inherited from main, orientation itself unproven — needs the lane that owns the rect nz_map + orientation`. +2. `stream::tests::a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact` + — **THIS LANE REGRESSES IT.** PASSES at 06d856d, FAILS on lane-palette2 HEAD: + `seed 46 first luma mismatch at (188, 62) ours=116 ffmpeg=115 -- 2242 mismatching samples, + bbox x 135..=191 y 62..=127` (stream.rs:12360). Values differ by 1 over a contiguous region = + a prediction/reconstruction difference, not an entropy desync. The gate is new on main + (lane-fistrip), so it never ran against this lane's rect-strip work until the r10 merge; the + suspects are the lane's `read_intra_mode_rect` / `decode_block_rect` / `reconstruct_rect` + changes (492 inserted lines vs the base), starting with the merge-resolved `PALETTE_PRED` + override wrapper in `reconstruct_rect` and the r7 per-TU palette window. + `fix-now: r11 — do not merge this lane into main until seed 46 is exact.` + +EVIDENCE: $HOME/.cache/palette2-suite.log | `EC_AV1_REQUIRE_AOMENC=1 ec_av1 --test-threads=1` on lane-palette2 HEAD (merged tree) | test result: FAILED. 294 passed; 2 failed; 27 ignored; 1390.10s +EVIDENCE: detached worktree at 06d856d (scratchpad/base06d, CARGO_TARGET_DIR=~/.cache/cargo-target-palette2-base) | same binary run with the two failing test names | `nz_map... FAILED` (identical message) + `filter_intra_on_a_horz_vert_strip ... ok` — 1 passed; 1 failed diff --git a/lanes/palette2-r11.report.md b/lanes/palette2-r11.report.md new file mode 100644 index 00000000..b47b9de6 --- /dev/null +++ b/lanes/palette2-r11.report.md @@ -0,0 +1,112 @@ +# lane-palette2 r11 -- merged main 096f4b8; the "regression" is a pre-existing defect the lifted refusal was hiding, localized to one block + +VERDICT: AMBER. STEP 1 (merge) done and committed. STEP 2 (seed 46) NOT fixed: +root cause is *not* the lane's palette code -- the entropy stream of seed 46 is +bit-exact against libaom for every symbol of the frame, and the mismatch is a +pure reconstruction defect in the last superblock of a screen-content frame, +which main never decodes because it refuses that frame class outright. The gate +stays RED; the lane must not merge until it is green. + +## STEP 1 -- merge main 096f4b8 (commit eb9472d) +`git merge --no-commit --no-ff main` -> one conflict only (`refusal_inventory.rs`); +`decode.rs`/`stream.rs`/`cdf.rs` auto-merged. +- `cdf.rs`: `git diff main -- crates/ec-av1/src/cdf.rs` = EMPTY, so main's NZ_MAP + tables are byte-for-byte; main's deletion of + `nz_map_ctx_offset_tables_match_the_rect_rule` taken (only + `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` + remains, and it passes). +- `refusal_inventory.rs`: kept main's `"a superblock-level partition value + outside PARTITION_NONE..PARTITION_VERT_4"` + the lane's two palette strings; + dropped three strings no longer emitted by any `unsupported(` site (the + superblock 1:4 partition, `LAST_FRAME (round 2)`, `palette block with a split + luma transform (round 1)`) and main's screen-content strip string (the lane + lifted it; only a comment mentions it now). `refusal_inventory` + + `gate_coverage` green. +- `decode.rs` fix required by the merge (`decode_block_rect64`, main's SB-level + 1:4/HORZ-VERT path, ~decode.rs:5265): main's `RectStripModes` literal there + lacked the lane's `palette_y`/`palette_uv` fields (compile error), and its + split-tx early return had no palette neighbour stamp -- the SAME shape r10 + root-caused in `decode_block_rect`. Both applied, plus the + `PALETTE_SPLIT_TX_HITS` bump, so the class is closed at both sites (`grep -n + 'return Ok(())'` in the rect decoders: 2 hits, both stamped). +- NOTE: main moved to `5d33392` (lane-sub8merge, mi-granular y/uv mode maps) + WHILE this round ran. This lane is merged with 096f4b8, not 5d33392. + `deferred: merge main 5d33392 -- appeared mid-round -- next round's STEP 1`. + +## STEP 2 -- seed 46: what it actually is +Regenerated exactly (aomenc recipe copied from the gate, seed 46 gradients): +`s46.obu` 146 B, sha256 `a109adab439706035728f9348aba0801e06afa1f571540ce433a103a94377421`. + +1. **The entropy stream is exact.** `EC_TRACE_MODE_STEP=1` ladders from ours and + from the instrumented aomdec, aligned symbol by symbol (284 aomdec ISTEP + lines vs our 270 -- the 14-line gap is only the 8 rect strips, whose + `use_filter_intra`/`tx_depth` we print under `TRACE_RECT_*` instead): + **every common (name, value, range) triple matches**, including the rect + strips' own values read back from `TRACE_RECT_IMODE` (e.g. mi(8,40) + tx_depth rng=50787 on both sides). So the lifted screen-content refusal did + NOT introduce a desync: our rect palette syntax reads consume exactly what + libaom consumes (8 strips, all `allow_screen_content_tools=1`, all + `use_palette=0`). +2. **It is reconstruction, and it is not the loop filter.** `EC_AV1_PREFILT_DUMP` + ours vs aomdec: 2165 luma samples already wrong before filtering (post-filter + 2242), bbox x136..191 y64..127 -- i.e. exactly the FRAME'S LAST SUPERBLOCK + (128,64). Every other superblock, including the right-edge SB(128,0) and the + bottom-row SB(0,64)/(64,64), is byte-exact. +3. **First wrong block pinned.** In decode order the first defective block is the + TL 16x16 of a 32x32 `PARTITION_VERT_A` at px(128,64) (aomdec + `EC_IMODE mi_row=16 mi_col=32 bsize=6`, mode 7 = D203_PRED, uv 7, skip=0, + tx_depth=0). Its error is a 25-pixel diagonal wedge in rows 68..71, + x136..143, deltas +7..-116; the two 16x16 above it and everything left of + x128 are exact. The wedge then propagates: 16x32 strip at (144,64) 246/512, + 16x16 (160,64) 141/256, (176,64) 194/256, 32x16 (160,80) 512/512, 32x32 + (160,96) 1024/1024; the 32x32 at (128,96) is 0/1024. +4. Suspects RULED OUT this round: the `PALETTE_PRED` override wrapper and the + per-TU palette window (no block in this stream uses a palette -- every + `palette_y_mode`/`palette_uv_mode` symbol reads 0, so `set_palette_pred` is + never called); filter intra (`use_filter_intra` = 0 on every strip here); + any entropy-side cause (point 1); the loop filter (point 2). Availability was + checked by hand against `has_bottom_left` in the oracle source + (`~/.cache/aom-oracle/src/av1/common/reconintra.c`): for that TL block + `blk_col_in_sb == 0`, so libaom takes the leftmost-column branch + (`row_off_in_sb + 4 < 16` -> available) and never reaches the + partition-keyed `has_bl_table`; our `Reach::bottom_left`'s `col == 0` branch + returns the same, so the `VERT_AB_PARTITION` guard is NOT implicated for + this block. + `fix-now: r12 -- next step is to dump the TL block's prediction and residual + separately (EC_DEBUG_EDGES + EC_TRACE_COEFF) against libaom's; the wedge + shape with the entropy stream exact points at the inverse transform's + tx_type/scan for a D203 16x16 in the corner superblock, or at the intra edge + filter/upsample decision, not at availability.` + +## Files changed +- `crates/ec-av1/src/decode.rs` -- `decode_block_rect64` split-tx arm: palette + prediction fields + palette neighbour stamp at the early return. +- `crates/ec-av1/src/refusal_inventory.rs` -- merge resolution (list above). + +## EVIDENCE +EVIDENCE: scratchpad/s46.obu (146 B, sha256 a109adab4397...) + aomstep.log/ourstep.log | `EC_TRACE_MODE_STEP=1` on instrumented aomdec and on `decode_probe`, aligned by (mi_row, mi_col, name) | every common triple identical; only the 14 rect-path lines we print under other names are missing -- entropy exact +EVIDENCE: scratchpad/ourpre.yuv.f0 vs aompre.yuv.f0 | `EC_AV1_PREFILT_DUMP` both decoders, same stream | 2165 luma samples differ, bbox x136..191 y64..127 (the last superblock only); post-filter 2242, so the loop filter is not the source +EVIDENCE: scratchpad (per-block diff map) | counted prefilter diffs inside every block aomdec reported for SB(128,64) | first defective block = TL 16x16 at px(128,64) of a 32x32 VERT_A, 25/256 wrong, wedge rows 68..71 + +## STEP 3 -- full suite on the merged tree +``` +systemd-run --user --unit=palette2-suite-r11-1788310477 -p MemoryMax=10G --same-dir \ + bash -lc 'EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 \ + nice -n 10 cargo test -p ec-av1 --lib -j3 -- --test-threads=1 \ + > $HOME/.cache/palette2-suite-r11.log 2>&1' +``` +-> **306 passed; 1 failed; 26 ignored** (735.05s). r10 was 294/2/27. +The ONE failure is this lane's known red gate, +`stream::tests::a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact` +(seed 46, message unchanged). r10's second failure, +`decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule`, is gone: main deleted that +stale test and the merge took the deletion. Both palette gates, `filter_intra_*`, +`split_transform_*`, `superblock_level_*`, the tiny sweep, `tx_select`, `refusal_inventory`, +`gate_coverage` and `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` +all pass inside that run. + +`fix-now: r12 -- the lane does not merge into main until seed 46 is pixel-exact (see STEP 2 +for the localization; it is a reconstruction defect behind the refusal this lane lifted, not +an entropy or palette defect).` + +EVIDENCE: $HOME/.cache/palette2-suite-r11.log | full `cargo test -p ec-av1 --lib -- --test-threads=1` under systemd unit palette2-suite-r11-1788310477 on the merged tree (b79b698) | test result: FAILED. 306 passed; 1 failed; 26 ignored; 735.05s -- the single failure is the seed-46 gate diff --git a/lanes/palette2-r12.report.md b/lanes/palette2-r12.report.md new file mode 100644 index 00000000..eeada4db --- /dev/null +++ b/lanes/palette2-r12.report.md @@ -0,0 +1,90 @@ +# lane-palette2 r12 -- root cause of seed 46: a transform unit inside a block used the standalone-block reach tables + +VERDICT: GREEN on the defect. Merge with main `4a29b4e` committed (`ed07bdc`), +seed-46 gate RED -> GREEN (`e8cc1c2`), full-suite totals below. + +## STEP 1 -- merge main 4a29b4e (commit ed07bdc) +`git merge --no-commit --no-ff main` -> 5 conflicts, all in `decode.rs` +(`refusal_inventory.rs`/`stream.rs`/`cdf.rs` auto-merged clean). +All five are the same shape: main's sub8merge mi-granular neighbour maps +(`modes_above_left`, `record_mode_mi`, `record_uv_mode_mi`) against the lane's +palette reads/refusals/stamps in `decode_block_rect` and `decode_block_rect64`. +Resolution: BOTH sides at every hunk -- main's `modes_above_left(r, c)` replaces +the lane's `above_mode[c]`/`left_mode[r]` cell reads (that is exactly the +mi-granular fix), the lane's palette ctx/cache + refusals + neighbour stamps +kept, main's `EC_AV1_RECTX_TRACE` print kept. +`refusal_inventory` 3/3 and `gate_coverage` 9/9 green on the merged tree. + +## STEP 2 -- seed 46 root cause (commit e8cc1c2) +Premise re-measured, not inherited: regenerated `s46.obu` from the gate recipe +(seed 46 gradients, sha256 `a109adab4397...`, 146 B, same hash as r11) and +re-ran the gate on the merged tree -- still RED, same 2242 samples. + +r11 had ruled out entropy, the loop filter, palette and filter intra, and had +verified block-level `has_bottom_left` by hand. What it could not see is that +the block is NOT predicted as one 16x16: added an `EC_PRED` rung to the oracle +(`~/.cache/aom-oracle/src/av1/common/reconintra.c`, printing +`mi_row/mi_col/plane/row_off/col_off/txw/txh/mode/p_angle/have_*/n_top/n_left/n_tr/n_bl/bsize/partition`) +and aomdec reports the TL 16x16 as FOUR 8x8 luma TUs: + + EC_PRED mi_row=16 mi_col=32 plane=0 row_off=0 col_off=0 txw=8 txh=8 mode=7 p_angle=200 n_top=8 n_left=8 n_tr=-1 n_bl=8 bsize=6 part=6 + EC_PRED mi_row=16 mi_col=32 plane=0 row_off=0 col_off=2 ... n_bl=0 + EC_PRED mi_row=16 mi_col=32 plane=0 row_off=2 col_off=0 ... n_bl=8 + EC_PRED mi_row=16 mi_col=32 plane=0 row_off=2 col_off=2 ... n_bl=0 + +`n_bl=0` for both `col_off > 0` units: libaom's `has_bottom_left` returns 0 +outright there. Our `decode_block` multi-TU branch built the unit's reach with +`Reach::of(logical_tx, tu_px, tu_py, ..)` -- the STANDALONE-BLOCK tables at the +unit's position (with `VERT_AB_PARTITION` set, `has_bl_vert_8x8` bit 1 = 1), so +the top-right 8x8 unit read 8 bottom-left samples libaom never gives it. That +is the 25-pixel diagonal wedge at rows 68..71 x136..143 (D203 = zone 3, reads +down-left), which then propagated across the last superblock. + +FIX: `Reach::of_tu(bw, bh, col_off, row_off, tx, block_reach)` in `encode.rs` +(the TU branches of both libaom functions, one place), used at all three +per-TU sites: +- `decode.rs` `decode_block` multi-TU branch (the defect), +- `decode.rs` `decode_leaf8`'s 2x2 grid of 4x4 TUs (same shape, same fix), +- `decode.rs` `decode_rect_split` (had the rule inline since lane-rectsplit r1; + now shares it -- one transcription, not three). +CLASS SWEEP: every other `Reach::of(...)` in `decode.rs` is a whole block or a +whole chroma block (4x4 leaf, 8x8 chroma group), not a unit inside one -- those +are correct and untouched. + +## Files changed +- `crates/ec-av1/src/encode.rs` -- `Reach::of_tu` + `Debug` on `Reach`; new test + `of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit`. +- `crates/ec-av1/src/decode.rs` -- three per-TU reach sites through `of_tu`; + merge resolution in `decode_block_rect`/`decode_block_rect64`. +- `crates/ec-av1/src/refusal_inventory.rs` -- merge (auto). + +## Gates +- `a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact` + (seed 46 is the regression pin): `cargo test -p ec-av1 --lib filter_intra_on_a_horz_vert_strip` + -> `ok. 1 passed` (was FAILED with 2242 mismatching samples). +- `encode::tests::of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit`: + enumerates 10 block shapes x tx in {4,8,16,32} x every (row_off, col_off) x both + block-level answers against an MI-unit transcription of libaom's + `has_top_right`/`has_bottom_left` -> ok. + +## EVIDENCE +EVIDENCE: scratchpad/aompred.log (EC_PRED rung added to reconintra.c) | `EC_PRED=1 aomdec s46.obu`, grep `mi_row=16 mi_col=32` | the 16x16 D203 block is four 8x8 luma TUs with n_bl = 8,0,8,0 -- the two `col_off>0` units get NO bottom-left +EVIDENCE: scratchpad/s46.obu (146 B, sha256 a109adab4397...) | regenerated from the gate recipe, `cargo test -p ec-av1 --lib filter_intra_on_a_horz_vert_strip` before/after the `of_tu` change | 2242 mismatching luma samples -> 0, test FAILED -> ok + +## Full suite (merged tree, after the fix) +`systemd-run --user --unit=palette2-suite-r12-1788311147 ... cargo test -p ec-av1 --lib` +-> `$HOME/.cache/palette2-suite-r12.log`: +`test result: ok. 314 passed; 0 failed; 27 ignored; 0 measured; finished in 317.39s` +(r11 on the pre-merge tree: 306 passed / 1 failed / 26 ignored). Siblings named in +the charter -- both palette gates, superblock_level_ab, ab_partition, +split_transform_*, the tiny sweep, refusal_inventory, gate_coverage, +base_ctx_rect_offsets -- are all inside that run and all pass. + +## Residue +- `deferred: a dedicated directional-mode AB-partition gate arm (D203/D157/D67 at SB + column 0, --enable-ab-partitions=1, 8/10-bit) -- the seed-46 stream already pins the + exact fixed path (VERT_A + D203 + split-TU at SB column 0) as a real-aomenc pixel gate + and the new enumeration test covers the rule over its whole domain, so a second stream + would add cost, not coverage -- unblocks by a round with budget for a new gate recipe`. +- `accepted: the EC_PRED rung now lives in ~/.cache/aom-oracle/src (oracle tree, not this + repo); scripts/instrument-aom-oracle.sh does not yet install it`. diff --git a/lanes/palette2-r3.report.md b/lanes/palette2-r3.report.md new file mode 100644 index 00000000..57990c87 --- /dev/null +++ b/lanes/palette2-r3.report.md @@ -0,0 +1,3 @@ +# see lanes/palette2-r7.report.md + +The charter labelled this round "r3"; the branch was already at r6, so the report is filed as r7. diff --git a/lanes/palette2-r4.charter.md b/lanes/palette2-r4.charter.md new file mode 100644 index 00000000..99612334 --- /dev/null +++ b/lanes/palette2-r4.charter.md @@ -0,0 +1,52 @@ +# lane-palette2 r4 — palette on a rectangular strip, from a clean base + +At main (8440024). **I reset this branch to main.** r3's in-flight edits are +preserved at tag `palette2-r3-wip` if you want to look, but they conflicted with +the u16 sample widen that has since landed, and they were mid-mechanical-edit +(threading `allow_intrabc` through four call sites) rather than hard-won +knowledge. Start fresh; re-doing that plumbing on top of the widen is cheaper +than untangling it. + +Read `lanes/palette2-r1.charter.md` for the lane's scope. Step 1 (UV palette) is +CLOSED and merged. This round is step 2: + + "a HORZ/VERT intra strip in a screen-content frame + (palette syntax is consumed for square blocks only)" + +`smptebars` and `rgbtestsrc` at plain default aomenc settings both stop exactly +there — that is measured, not assumed, so a real gate is easy to build. + +`palette_bsize_ctx` and the palette size/context derivation assume a square +block; libaom derives both from width AND height. Check what it actually does +for a rect block before adapting the square path. Two classes apply: a table +narrowed to a pinned row breaks when its indexing field moves +([[cdf-row-held-constant]]), and a neighbour context read from ONE cell is right +only under uniform block size — a strip needs a gathered span +([[context-read-from-one-cell]]). + +Note what a sibling lane just found in the same neighbourhood: libaom indexes +`av1_nz_map_ctx_offset` by the RAW, un-adjusted `tx_size`, and the 32x64/64x32 +tables genuinely differ from the square one. If your rect-strip work touches a +size-indexed table, check whether libaom indexes it by the raw or the adjusted +size before assuming. + +Order: gate FIRST below `decode_stream`, hard-asserting the rect-strip palette +path fired; then the implementation; then lift the refusal and update +`refusal_inventory.rs` in the SAME commit. Declare every new refusal string you +add — `refusal_inventory`'s own test fails the build otherwise, and r3 left two +undeclared for me to clean up. + +Step 3 ("a palette block with a split luma transform", reached by `life`) only +if step 2 is committed green with budget to spare. + +## Budget discipline +75 turns, no reset on resume. At about turn 55, stop starting new work: commit +what is green and write your report. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg +generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc +`--threads=1 --row-mt=0 --sb-size=64`. Oracle rung 12 is yours; the oracle is +SHARED, env-gated rungs only. Sibling worktrees have live agents — never build in +or edit them. Never push, never merge into main; I handle merges. End with +`lanes/palette2-r4.report.md`, VERDICT on line 1. diff --git a/lanes/palette2-r5.charter.md b/lanes/palette2-r5.charter.md new file mode 100644 index 00000000..8018f011 --- /dev/null +++ b/lanes/palette2-r5.charter.md @@ -0,0 +1,41 @@ +# lane-palette2 r5 — write the gate + +At 05f6db8. r4 implemented the rect-strip palette path and hit its cap with +"compiles clean, now let's write the gate test". I committed its tree verbatim; +**it compiles but is otherwise unverified by me, and it has NO gate**, which +means right now it is exactly the thing this project refuses to ship: a +capability claim with nothing behind it. + +## The job, in one sentence +Write the gate for what r4 built, and let it tell you whether r4 is right. + +Specifics: +- `smptebars` and `rgbtestsrc` at plain default aomenc settings both reach the + rect-strip palette case — that is measured, so no fixture hunting is needed. + Add `--enable-palette=1` explicitly: `gate_coverage.rs` only counts a tool as + exercised on a positive flag. +- Drive the tile decode BELOW `decode_stream` so a surviving refusal cannot + short-circuit the code you are measuring + ([[refusal-short-circuits-its-own-code]]). +- Hard-assert that the rect-strip palette path actually fired before comparing + pixels ([[gate-blind-to-feature]]) — a hit counter, not just a pixel match. +- Pixel-exact vs ffmpeg. If it mismatches, that is r4's implementation being + wrong, which is a perfectly good outcome for this round: bisect it with a + range ladder against the oracle (rung 12 is yours), and say so plainly. +- Only with the gate green: lift the refusal and update `refusal_inventory.rs` + in the SAME commit. Check what r4 already changed in that file — it edited it + without a gate, so treat its edits as unverified too. + +Do not start step 3 (palette with a split luma transform) this round. + +## Budget discipline +75 turns, no reset on resume. At about turn 55, stop starting new work: commit +what is green and write your report. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg +generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc +`--threads=1 --row-mt=0 --sb-size=64`. The oracle is SHARED — env-gated rungs +only. Sibling worktrees have live agents — never build in or edit them. Never +push, never merge into main; I handle merges. End with +`lanes/palette2-r5.report.md`, VERDICT on line 1. diff --git a/lanes/palette2-r5.report.md b/lanes/palette2-r5.report.md new file mode 100644 index 00000000..5cf20c74 --- /dev/null +++ b/lanes/palette2-r5.report.md @@ -0,0 +1,76 @@ +VERDICT: BLOCKED — gate written and hard-asserting, but real aomenc RD never lands a rect-strip +palette block across the whole sweep; r4's implementation is neither confirmed nor refuted this +round, and the refusal is NOT lifted. + +## What I did +Wrote `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact` in +`crates/ec-av1/src/stream.rs` (after the existing square palette-Y/UV gates). It drives +`decode_stream` directly (below any refusal), hard-asserts `decode::palette_rect_hits()` moved +before comparing any pixels, and requires pixel-exactness vs `ffmpeg` on any attempt that both +decoded and fired the counter — exactly the charter's shape. + +## What the gate found, measured live this round +`smptebars`/`rgbtestsrc` at plain default aomenc settings (r1's measured recipe) do NOT reach a +clean rect-strip palette decode: every attempt hits an unrelated named refusal FIRST, almost +always a 32x32-level `HORZ_A`/`HORZ_B`/`VERT_A`/`VERT_B` partition (this decoder codes only +`NONE`/`SPLIT`/`HORZ`/`VERT` at that level) or filter-intra-on-a-strip. Confirmed live that +`--enable-ab-partitions=0` is INERT for this content/tune combo — two encodes differing only in +that flag produced byte-identical output (`md5sum` match) — the same aomenc quirk already +recorded in the ledger for SB-level AB +([[lane-sbpart-r2]]: "AB-at-64 not gated by that flag"), here reproduced one level down at 32x32. + +Forcing `--min-partition-size=64 --max-partition-size=64` sidesteps that 32x32-level code path +entirely (only `NONE`/`SPLIT`/`HORZ`/`VERT`/AB/1:4 remain, straight from `decode_block_rect64`), +and does produce many clean `OK` decodes across a 70-attempt sweep (2 sources x 5 sizes x 7 cq +levels, single key frame each, `--enable-palette=1`). But `palette_rect_hits` stayed at its +`before` value on every single one of them — the encoder's RD always prefers `PARTITION_NONE` +(whole-SB square palette, already gated by the existing `palette_y`/`palette_uv` tests) over a +`HORZ`/`VERT` split when palette is in play at this scale. The remaining ~31 attempts hit named +refusals, dominated by "a palette block with a split luma transform (round 1)" — r1's own +already-refused square case, not this round's. + +So the gate is real, hard, and currently RED for the right reason: it never got to compare a +single pixel because the capability it is meant to prove never actually fires against real +content, not because of a code defect it caught. This is different from a "mismatch to bisect" +outcome the charter anticipated — there is nothing to range-ladder yet because nothing decoded +through the rect-palette path to disagree with ffmpeg on. + +## Why I did not lift the refusal +The charter is explicit: "Only with the gate green: lift the refusal." The gate is not green — it +never observed a genuine attempt. Lifting on an unfired gate would be exactly the "refusal lifted +without a gate" class this project forbids. r4's `read_intra_mode_rect`/`decode_block_rect64` +palette wiring (the diff in 05f6db8) is therefore STILL unverified — neither confirmed correct nor +caught wrong. I left it in place (it compiles, does not regress any other gate) and left r4's +`refusal_inventory.rs` edit (narrowing the refusal to "palette block with a real transform on a +rect strip") as-is, also still unverified, per the charter's own note to treat it that way. + +## State committed +- `crates/ec-av1/src/stream.rs`: the new gate test only. No other file touched. +- `refusal_inventory.rs`: unchanged from r4's commit (still unverified, not touched further). +- The suite has one new RED test (`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`). + I did not silence or ignore it — a red gate that has never fired is the honest state, not a + green one that never proved anything. + +## Next round should try +- Content specifically constructed to make a `PARTITION_HORZ`/`VERT` split cheaper than `NONE` + for a palette block — e.g. two very different flat-colour halves stacked so the whole-SB + palette needs 2x the base colours a half-SB one would, biasing RD toward the split. Plain + `smptebars`/`rgbtestsrc` don't do this (their bands are much finer than a 64px SB). + `gradients_source` (used by the free-partition gate) is NOT screen content and won't turn on + palette at all. + - `aomenc --partition-info-path` (seen in `--help`) may let a fixture force a specific partition + outright rather than depending on RD luck — worth trying before another blind cq/size sweep. +- If a firing stream is found and it MISMATCHES ffmpeg, rung 12 of the range ladder is still open + and unclaimed — use it then. + +## Commands run +`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2; export EC_AV1_REQUIRE_AOMENC=1` +`nice -n 19 cargo test -p ec-av1 --lib -j4 a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact -- --nocapture` +(timeout 600000ms; result: 1 failed, as reported above — 0 passed, 31 named refusals, 39 decoded +with `palette_rect_hits` unchanged, 0 matched out of 70 attempts) + +## Budget +Spent the bulk of the round on live aomenc probing (`decode_probe` example + manual `aomenc` +sweeps) to characterise exactly where real content stops, per the charter's own instruction to let +the gate (and probes) tell the truth rather than guess flags. Stopped adding new sweep dimensions +at turn ~55 per budget discipline; committing the gate as the round's deliverable. diff --git a/lanes/palette2-r6.charter.md b/lanes/palette2-r6.charter.md new file mode 100644 index 00000000..15b8f8c6 --- /dev/null +++ b/lanes/palette2-r6.charter.md @@ -0,0 +1,63 @@ +# lane-palette2 r6 — gate the case that actually occurs + +At the r5 commit. Read `lanes/palette2-r5.report.md`. r5 did good work and +reported an honest RED: its gate hard-asserts `palette_rect_hits()` and 70 +aomenc attempts never moved that counter, so r4's implementation is still +unverified. + +## What I think went wrong, from my own measurement +The counter is too narrow. The refusal r4 removed was: + + "a HORZ/VERT intra strip in a screen-content frame + (palette syntax is consumed for square blocks only)" + +That fires on a rect strip in a frame with screen-content tools enabled — +whether or not that particular block ends up USING a palette. r5 searched for a +block that both is a rect strip and codes a palette, which RD apparently almost +never picks. But the broad case is common: **I hit that exact refusal on main +with plain default settings**, no flag hunting: + + ffmpeg -v error -f lavfi -i "smptebars=size=192x128:rate=30" -t 0.2 \ + -pix_fmt yuv420p in.y4m -y + aomenc --codec=av1 --ivf --threads=1 --row-mt=0 --sb-size=64 --limit=3 \ + --cpu-used=4 --end-usage=q --cq-level=32 -o out.ivf in.y4m + ffmpeg -v error -i out.ivf -c:v copy -f obu out.obu -y + cargo run -p ec-av1 --example decode_probe -- out.obu + +On main that prints the refusal above. `rgbtestsrc` does the same. On THIS +branch the refusal is gone, so the same stream now runs through r4's code — and +that is the thing to gate. + +## The job +1. Reproduce the above on main first, so you are gating a case you have watched + occur rather than one you hope occurs. +2. Add a counter at the site r4 actually changed — the rect-strip-in-a- + screen-content-frame path — not a palette-specific one. Then gate: this + stream, through `decode_stream`, pixel-exact vs ffmpeg, with that counter + hard-asserted to have moved. +3. If pixels match, the lift is earned: keep r4's narrower refusal + ("a palette block with a real transform on a superblock-level HORZ/VERT + strip...") and update `refusal_inventory.rs` so the lists agree. +4. If pixels mismatch, that is r4's implementation being wrong — bisect with a + range ladder against the oracle (rung 12 is yours) and say so. + +**Right now this branch has removed a refusal with no gate behind it** +([[refusal-lifted-without-a-gate]]), which is the one state that cannot merge. +Closing that is this round's whole point. + +Keep r5's gate too if you can make it fire, but do not spend the round on it — +its own report says the honest next lever is `aomenc --partition-info-path` or a +fixture with two very different flat-colour halves, and that is a later problem. + +## Budget discipline +75 turns, no reset on resume. At about turn 55, stop starting new work: commit +what you have — red included, named as such — and write your report. Landing red +on this branch is fine; only merging red is forbidden, and I do the merges. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg +generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc +`--threads=1 --row-mt=0 --sb-size=64`. The oracle is SHARED — env-gated rungs +only. Sibling worktrees have live agents — never build in or edit them. Never +push, never merge into main. End with `lanes/palette2-r6.report.md`, VERDICT on +line 1. diff --git a/lanes/palette2-r6.report.md b/lanes/palette2-r6.report.md new file mode 100644 index 00000000..3f0e4682 --- /dev/null +++ b/lanes/palette2-r6.report.md @@ -0,0 +1,105 @@ +VERDICT: RED — the broad gate the charter asked for now fires (proof the removed-refusal case +actually occurs), and it caught a real pixel mismatch. The defect is NOT r4's palette wiring: it +traces to a pre-existing, already-tracked bug in `decode_block_rect64` (ledger +[[lane-sbpart-r9]]), newly reachable now that the blanket screen-content refusal is gone. The +refusal is intentionally NOT restored — the charter's own instruction on mismatch is to bisect and +report, not revert. + +## What I did +1. Confirmed on `main` (HEAD `8440024`, textually — did not build there, see below) that the + blanket refusal `"a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed + for square blocks only)"` is still present verbatim (`decode.rs:2857`), so this branch really is + the only place that case can be observed decoding. +2. Added `decode::rect_screen_content_hits()` — a `thread_local` counter incremented at the exact + site the removed refusal used to guard, inside `read_intra_mode_rect` (`decode.rs`, right after + `allow_screen_content_tools && palette_bsize_ctx_wh(bw, bh).is_some()`), independent of whether + the block goes on to use a palette. This is the counter the charter asked for: it fires on the + *common* case (r5's own sweep found 39/70 attempts reached this branch without ever using a + palette — those were invisible to r5's `palette_rect_hits`). +3. Wrote `a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact` in `stream.rs`, + modeled on r5's gate: same `--min/max-partition-size=64` recipe (r5 measured live that this + dodges the 32x32-level AB-partition quirk, [[lane-sbpart-r2]]), same size/cq sweep, drives + `decode_stream` directly, hard-asserts `rect_screen_content_hits()` moved before comparing any + pixels. + +## What the gate found +First attempt through this recipe that actually fired the counter (`smptebars=size=128x128:rate=25 +cq=15`) **mismatched ffmpeg**: rows 0-63 (the frame's top two 64x64 superblocks) match exactly; +rows 64-127 (the bottom two superblocks) are wrong wholesale (~117-128/128 pixels differ per row, +uniformly, not a scattered handful). + +I bisected with `EC_AV1_TRACE`: +- The 4 palette-Y/UV blocks visible in the trace (`EC_PAL`/`EC_PAL_VAL`) are all 64x64 luma / + 32x32 chroma — **square**, going through the pre-existing, already-verified square palette path + (`decode_block`), not the new rect one. Both top SBs decode this way and both match ffmpeg. +- `TRACE_RECT64_END mi_row=16 mi_col=16 bw=32 bh=64` and `mi_row=16 mi_col=24 bw=32 bh=64` are the + two bottom SBs — real `VERT` splits at the superblock level, going through + `decode_block_rect64`. Neither shows an `EC_PAL` trace inside it — **this is not a palette block + at all**, just ordinary intra reconstruction on a genuine rect strip. +- So `rect_screen_content_hits` incremented correctly (the syntax-reading branch it counts ran), + but the corruption is downstream of it, in `decode_block_rect64`'s own reconstruction of a real + (non-skip) VERT-split block — the counter did its job; the block it counted is where the bug + lives, just not in the code r4 added. + +This matches an existing ledger dead-end verbatim: +`dead-end|lane-sbpart r9 ... root cause is a sibling function (decode_block_rect64) ... do not +re-attempt part32 AB until decode_block_rect64 real-residual TX_32X64/64X32 truncation is fixed and +gated`. That defect was never closed. What's new this round is that it was previously +UNREACHABLE under `allow_screen_content_tools=true` (the blanket refusal short-circuited it +first, [[refusal-short-circuits-its-own-code]]) — removing that refusal exposed it for the first +time in this configuration, on a stream that doesn't even use palette. + +## Why I did not restore the refusal +The charter is explicit: on mismatch, bisect and say so — restoring the refusal was not asked for +and this branch's whole point is closing "refusal removed, no gate behind it" +([[refusal-lifted-without-a-gate]]) with an honest RED, not a silent revert back to green. The gate +itself is the safety net now: it is red, hard-asserting, and will stay red until +`decode_block_rect64`'s real-residual defect is actually fixed — exactly the state the charter +wants landed. + +## r4's `refusal_inventory.rs` / palette reconstruction — still unverified +Nothing this round exercised palette reconstruction through the rect path (every genuine rect-strip +decode I observed had zero palette use; every palette use I observed was square). r4's actual new +code (palette-Y/UV symbol reading and reconstruction generalized to `bw`x`bh`) is therefore +*still* neither confirmed nor refuted — same state r5 left it in. I left `refusal_inventory.rs` +untouched. + +## What I did NOT do +- Did not build or run anything in `/home/user/Documents/Code/Rust/edith_codecs` (main repo, + not a worktree) — it had another agent's uncommitted staged changes when I checked; I only read + the committed `HEAD` text to confirm the refusal's wording, never compiled there. +- Did not attempt to fix `decode_block_rect64`'s residual truncation — out of this round's charter + (gate r4's work), and the ledger already flags it as open for whichever lane owns `sbpart`/rect64 + residuals next. +- Did not touch r5's `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact` gate; it is + unchanged and still red for its own reason (never observes a genuine palette-on-rect attempt). + +## Commands run +``` +export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 +export EC_AV1_REQUIRE_AOMENC=1 +nice -n 19 cargo build -p ec-av1 --tests -j4 # clean +nice -n 19 cargo test -p ec-av1 --lib -j4 \ + a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact -- --nocapture + # FAILED: assertion `left == right` ... frame 0 luma vs ffmpeg (the mismatch above) +``` +(cargo test timeout was 600000ms; actual run finished in ~1-17s per invocation, well under) + +## State committed +`d427e19` on `lane-palette2` (HEAD): `decode.rs` (+23, new counter), +`stream.rs` (+153, new gate). Compiles clean (`cargo build -p ec-av1 --tests`). Two red gates now +exist for this lane's unverified surface (r5's palette-on-rect, r6's broad rect-screen-content) — +both honest, neither silenced. + +## Next round should +- Fix `decode_block_rect64`'s real-residual VERT/HORZ-split reconstruction (the actual root cause, + tracked since [[lane-sbpart-r9]]) — this gate will go green once that's fixed and no sooner. +- Once green, re-run `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact` too: with + `decode_block_rect64` fixed, more attempts may reach a genuine palette-on-rect block and finally + give r4's actual new code its first real test. + +## Budget +~55 turns spent: charter/report reading, main-HEAD text confirmation, counter + gate authoring, +two build/test cycles (first hit a broken-pipe harness bug from `--limit=3` racing piped stdin, +fixed by dropping it and matching r5's proven recipe), then bisection via `EC_AV1_TRACE` to +localize the mismatch to `decode_block_rect64`. Stopped there per budget discipline and committed. diff --git a/lanes/palette2-r7.report.md b/lanes/palette2-r7.report.md new file mode 100644 index 00000000..975d62b5 --- /dev/null +++ b/lanes/palette2-r7.report.md @@ -0,0 +1,83 @@ +# lane-palette2 r7 report + +(The charter for this round was labelled "round 3"; the branch was already at r6 — this is r7. +The charter's own step numbering is kept below.) + +VERDICT: GREEN. Both charter steps are implemented AND gated pixel-exact against real aomenc. +The r6 report's RED is resolved: it was NOT the `decode_block_rect64` residual defect, it was +`--min-partition-size=64` in the gate recipe forcing SB-level VERT-64 blocks through +`decode_block_rect64`. At `--min-partition-size=16` the gate reaches real rect strips +(16x16..64x64) and is pixel-exact. + +## What changed (commit 5d67fd7 on `lane-palette2`) + +- `crates/ec-av1/src/decode.rs` `decode_block` (~5056, ~5241) — palette-Y prediction is now + windowed PER TRANSFORM UNIT: with `logical_tx != side`, each TU copies its own + `logical_tx`x`logical_tx` window out of the block's index map right before `read_plane`, + instead of the whole-block buffer (which the FIRST unit consumed at the wrong stride). + Residual is added per TU over that prediction. Refusal + **"a palette block with a split luma transform (round 1)" LIFTED** (charter step 3). +- `decode.rs` `read_intra_mode` (~4415) and `read_intra_mode_rect` (~3153) — a palette-Y block + gets NO `use_filter_intra` symbol (`av1_filter_intra_allowed`, reconintra.h:77). We read one, + consuming a bit the encoder never wrote, and desynced from every palette block <=32x32 + (class `symbol-consumption-gap`). +- `decode.rs` `Neighbours::palette_ctx_and_cache` (~2005) — the SB-top-row exclusion of the above + neighbour belongs to the colour CACHE only (pred_common.c:76); `av1_get_palette_mode_ctx` + (pred_common.h:197) reads plain `xd->above_mbmi`. Applying it to the ctx too made every SB in + the frame's second SB row read `palette_y_mode` off CDF row 0 while libaom used row 1 + (class `cdf-row-held-constant`). +- `decode.rs` `decode_leaf_rect` (~3674) — sub-16x16 rect leaves now read palette syntax with + their own real ctx/cache (previously row 0); RECONSTRUCTION on a sub-16x16 strip stays refused + by name: **new refusal "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction + not ported)"**. +- `crates/ec-av1/src/stream.rs` (~2129, ~2285) — both palette gates' aomenc recipe + `--min-partition-size=64` -> `16`; r6's gate additionally asserts + `palette_split_tx_hits()` moved on a pixel-exact attempt. +- `crates/ec-av1/src/refusal_inventory.rs` — split-transform refusal removed, sub-16x16 rect + palette refusal added. `gate_coverage.rs` already lists only `enable-intrabc`; palette is + covered by an explicit `--enable-palette=1` in both gates. Both meta-tests green. + +## Gates + +Command (worktree, `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`, `EC_AV1_REQUIRE_AOMENC=1`): + + cargo test -p ec-av1 --lib -j3 -- --nocapture \ + stream::tests::a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact \ + stream::tests::a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \ + refusal_inventory gate_coverage + # test result: ok. 7 passed; 0 failed; 0 ignored + +aomenc line in both (CORRECTED r8 -- r7 wrote `--tune-content=screen +--enable-rect-partitions=1`, which the code at stream.rs ~2118-2135 / ~2274-2291 passes +NEITHER of; the actual argv is): `--codec=av1 --passes=1 --end-usage=q --cq-level= +--cpu-used=4 --threads=1 --row-mt=0 --sb-size=64 --enable-palette=1 --min-partition-size=16 +--max-partition-size=64 --obu -o - -`, +70 attempts (5 sizes x 7 cq x smptebars/rgbtestsrc), pixel-compared against ffmpeg's decode. + +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/palette2-r7-gates.txt | 70 real-aomenc screen-content encodes decoded and pixel-compared vs ffmpeg | a_real_aomenc_stream_with_rect_screen_content: 14/70 pixel-exact, 13 of them through a split-transform palette block, rect_screen_content_hits=169, palette_split_tx_hits=356 +EVIDENCE: same file | same sweep, r5's narrower gate | a_real_aomenc_stream_with_rect_palette: 14/70 pixel-exact, palette_rect_hits=78 rect-strip palette blocks reconstructed +EVIDENCE: full lib suite `cargo test -p ec-av1 --lib -j3` | whole ec-av1 lib | 269 passed, 0 failed, 23 ignored (510s) + +## Charter steps + +- Step 2 (palette on HORZ/VERT rect strips, >=16x16 both dims): DONE, gated + (`palette_rect_hits=78`, pixel-exact). The blanket refusal "a HORZ/VERT intra strip in a + screen-content frame (palette syntax is consumed for square blocks only)" is gone and now has + a gate behind it. +- Step 3 (palette + split luma transform): DONE, gated (`palette_split_tx_hits=356`). +- Step 2's inter-frame 8x8-leaf palette refusals (decode.rs ~10652, ~11748): NOT attempted — + deferred. Measured, not assumed: a 10-frame `rgbtestsrc` screen-content encode at cq 15/35/55 + through `decode_probe` stops at "a 32x32 partition type this decoder does not code (value=4)" + and "filter intra on a HORZ/VERT strip", never at a palette refusal. Those paths are + unreachable behind other lanes' refusals, so no gate could prove a lift today + (class `refusal-lifted-without-a-gate`). + +## Residue + +- deferred: inter-frame palette reconstruction (decode.rs ~10652 intra-in-inter, ~11748 8x8 leaf) + — unblocked by lane-part32 (32x32 partition types) and the filter-intra-on-rect-strip lane; + once those land, screen-content inter frames become reachable and a gate is possible. +- deferred: sub-16x16 rect-strip palette reconstruction — refused by name, syntax read correctly; + unblocked by a rect (4x8/8x4) transform primitive, same ceiling as `lane-sub8`. +- accepted: the `decode_block_rect64` real-residual defect (ledger lane-sbpart-r9) is untouched + and still open; this lane's gates simply no longer route through it. It is NOT a palette defect. diff --git a/lanes/palette2-r8.report.md b/lanes/palette2-r8.report.md new file mode 100644 index 00000000..339a924e --- /dev/null +++ b/lanes/palette2-r8.report.md @@ -0,0 +1,82 @@ +# lane-palette2 r8 — verifier findings closed; both gates now RED on a real defect they used to hide + +VERDICT: RED (honest). The two gate-integrity fixes the verifier asked for turned 2 previously +"green" gates red: 16/70 attempts per gate decoded successfully and were never pixel-compared, +and one of them (`rgbtestsrc=size=128x128:rate=25 cq=55`) mismatches ffmpeg on chroma. That +mismatch is PRE-EXISTING, not caused by this round's decoder change (proved by stashing the +decode.rs diff and re-running: same panic, same attempt, same plane). + +## What changed +- `crates/ec-av1/src/stream.rs` ~2170-2210 (`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`) + and ~2335-2375 (`a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`) — the + hit-counter check no longer `continue`s past the pixel comparison. Every successfully decoded + attempt is compared and a mismatch panics; the counter now only decides whether the attempt + counts toward the hit-asserting total (`matched` vs new `uncounted_exact`). Class + [[gate-skips-on-its-own-failure]]. +- `crates/ec-av1/src/decode.rs` ~1986-2010 / ~2084-2105 (`record_palette_y_rect`, + `record_palette_uv_rect`) — `for cell in 0..(w / SUB).max(1)` (both axes). The plain + `w / SUB` loop was a NO-OP for every sub-16px span, so a sub-16 leaf could not clear the + above/left palette state at all. Corner-cut comment names the ceiling: our grid is 16px + where libaom keeps `palette_size` per 4px mi cell; safe today because every sub-16 leaf + path refuses palette outright, so it can only ever stamp `size == 0`. Upgrade path: + widen the palette arrays to mi granularity. +- `crates/ec-av1/src/decode.rs` ~3803-3810 (`decode_leaf_rect`, before `Ok(mode)`) and + ~5703/~5721 (`decode_leaf8`, both exits) — each sub-16 leaf now records its own palette + state (size 0, since both paths refuse palette) over its own cell, so the next block's + `palette_y_mode` ctx and colour cache no longer read a previous block's palette. Class + [[cdf-row-held-constant]]. +- `crates/ec-av1/src/decode.rs` (tests) — new unit test + `a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero`: a 16x16 palette block gives + ctx 2 + cache [7,9]; an 8x8 non-palette leaf in the same cell must take it to ctx 0 and an + empty cache (Y and UV halves). Fails before this round's fix, passes after. +- `lanes/palette2-r7.report.md` line 50 — CORRECTED. r7 claimed the aomenc line carried + `--tune-content=screen --enable-rect-partitions=1`; the code passes NEITHER. Real argv: + `--codec=av1 --passes=1 --end-usage=q --cq-level= --cpu-used=4 --threads=1 --row-mt=0 + --sb-size=64 --enable-palette=1 --min-partition-size=16 --max-partition-size=64 --obu -o - -`. + The recipe itself is unchanged. + +## Gate results (EC_AV1_REQUIRE_AOMENC=1) +``` +cd ; export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 EC_AV1_REQUIRE_AOMENC=1 +cargo test -p ec-av1 --lib -j3 -- --test-threads=1 --nocapture \ + a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \ + a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact +``` +Buckets over the same 70-attempt sweep (5 sizes x 7 cq x smptebars/rgbtestsrc), per gate: +- named refusal: 54/70 (32x32 partition value=4..7, filter-intra-on-strip, split-transform strip) +- decoded, counter fired, pixel-compared: was 14/70 in r7 — not re-reached this round, the run + aborts at the first mismatch, which is an uncounted attempt earlier in the sweep. +- decoded, counter did NOT fire, now pixel-compared (r7 skipped these entirely): 2 reached + before the abort — `rgbtestsrc 128x64 cq=63` (exact) and `rgbtestsrc 128x128 cq=55` (MISMATCH). +`refusal_inventory` (3 tests) + `gate_coverage` (2 tests): 5 passed, 0 failed. + +## The defect the integrity fix exposed +`rgbtestsrc=size=128x128:rate=25 cq=55`, single key frame: luma bit-exact, V exact, **U plane +30 pixels wrong by +-1 / +-2**, all inside chroma rows 38-50 x cols 28-50 (luma 76-100 x 56-100). +Shape matches the open residual chroma-only defect already noted on main (`1a89ed9` "residual +chroma-only defect open") and memory `[[lane-tiny r4]]`: chroma-only +-1 with luma exact is a +post-recon (filter) defect — dump prefilt/postdeblock stages first, do NOT open a symbol trace. +Pinned stream (118 bytes, sha256 +`807e5d434b035e626548d0ec3dc166b959622ed64b59dfa049a16d0e5a35c297`): +`/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/palette2-r8-mismatch.obu` +(not committed: `crates/ec-av1/fixtures` is under `.gitignore:2 fixtures`; regenerate with +`EC_AV1_GATE_DUMP=` on either gate). + +## EVIDENCE +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/palette2-r8-mismatch.obu | both palette gates re-run under EC_AV1_REQUIRE_AOMENC=1 with the counter-`continue` removed | 2 previously-unchecked decoded attempts now compared; 1 exact, 1 mismatching (U plane, 30 px, max |d| = 2) +EVIDENCE: stash-and-rerun of the decode.rs diff (`git stash push crates/ec-av1/src/decode.rs`, gate re-run, `git stash pop`) | same gate, r8 stream.rs only | identical panic at stream.rs:2200, same attempt, same plane -- the chroma defect is pre-existing, not this round's regression +EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1) | whole ec-av1 lib | 268 passed, 2 failed (the two palette gates above), 23 ignored, 514.71s +EVIDENCE: cargo test -p ec-av1 --lib -j3 a_sub16_leaf_after_a_palette_block | new unit test | 1 passed + +## Residue +- fix-now(next round, blocks merge): the chroma-only U mismatch above. Both gates stay RED until + it is fixed or its stream is proven to hit a legal named refusal instead. +- deferred(concurrent lanes own these gates): 8 sibling sites in stream.rs carry the SAME shape -- + a successful decode whose hit counter did not move `continue`s/`never_fired += 1` before any + pixel compare: lines ~2662 (`tx_depth_hits`), ~3781 (`non_last_ref_hits`), ~3959 + (`ref_hits(target_ref)`), ~4159 (`comp_mode_hits`), ~4354 (`skip_mode_hits`), ~4530 + (`obmc_hits`), ~7222 (`tmv_hits`), ~7495 (`tx_class1_hits`). Same one-line transform applies + (compare pixels, then decide whether to count). NOT changed here: they belong to lanes running + concurrently in this batch on the same file (merge-conflict cost), and each needs its own + aomenc sweep to validate. Unblocked by: this batch's merge, then one mechanical sweep round. +- accepted: the 16px palette-neighbour grid (corner-cut comment in `record_palette_y_rect`). diff --git a/lanes/palette2-r9.report.md b/lanes/palette2-r9.report.md new file mode 100644 index 00000000..03bb042d --- /dev/null +++ b/lanes/palette2-r9.report.md @@ -0,0 +1,90 @@ +# lane-palette2 r9 — GREEN: both palette gates pass after the main merge + one real defect fix + +VERDICT: GREEN. Both gates decode-and-pixel-compare every successful attempt, 0 mismatches. + +## STEP 1 — merge main f31a2c5 (as chartered) +`git merge f31a2c5` into lane-palette2 (commit `4f30677`). Two conflicts: +- `crates/ec-av1/src/decode.rs` `reconstruct_rect` (~5517): kept this lane's `PALETTE_PRED` + override branch, and took main's rect filter-intra call signature (`bw, bh` — lane-rectsplit + widened `predict_filter_intra` to a rectangle). Keeping only one side would have either + dropped palette prediction on rect strips or failed to compile. +- `crates/ec-av1/src/refusal_inventory.rs` (~51): union of both sides, then the two strings the + merge made unreachable were deleted (the inventory test named them): + `"a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square + blocks only)"` (lifted by this lane) and `"a HORZ/VERT intra strip with a split transform + (per-unit rect prediction is not ported)"` (lifted by main's lane-rectsplit). + +The r8 blocker — the chroma-only U mismatch on `rgbtestsrc 128x128 cq=55` (30 px, max |d| 2, +luma+V exact) — is GONE after the merge, exactly as the charter predicted: main `9b1297a` +(deblocker chroma tx size = block span/2, not luma_tx/2). That attempt now decodes pixel-exact. + +## STEP 2 — the merge created a new defect, root-caused and fixed +The merge did NOT leave the gates green: they failed on a *different*, larger mismatch +(`smptebars 192x192 cq=35`), which main alone refuses outright +(`decode_probe` on f31a2c5: "REFUSED: ... a HORZ/VERT intra strip in a screen-content frame"), +so the case only exists in the merged tree. + +Measured shape: luma x0..63, y0..127 entirely wrong (8192 px, max |d| 52), the rest of the frame +exact; ours flat 128 there = DC prediction with no edges. `EC_TRACE_MODE_STEP` showed mi(0,0) = +32x16 strip, `mode=0`/`uv_mode=0` (the palette signature) with a split transform. + +ROOT CAUSE: `decode_rect_split` (`crates/ec-av1/src/decode.rs:3780`, from main's lane-rectsplit) +knows nothing about palette. The palette wiring at the call site +(`decode_block_rect`, decode.rs ~4113) sets `PALETTE_PRED` *after* the `depth != 0` early return, +so every transform unit of a split-transform palette strip predicted DC. The coefficients are +still read, so the entropy stream stayed in sync and only those pixels were wrong — class +[[parsed-then-discarded]] applied to the *prediction* rather than to a header field. + +FIX (decode.rs): +- `RectStripModes` (~3747) gains `palette_y: Option>` and + `palette_uv: Option<(Vec, Vec)>` — the block's colour-mapped maps. +- `decode_rect_split` luma TU loop (~3857): before each unit's `read_plane`/`reconstruct`, sets + `PALETTE_PRED` to that unit's `tx`x`tx` window of the block map. Palette prediction reads no + edge pixels, so a unit's window on the whole-block map IS its prediction — no ordering subtlety. +- `decode_rect_split` chroma (~3905/~3960): sets `PALETTE_PRED` per plane before each + `reconstruct_rect` (skip and coded arms); the chroma transform is never split by luma's depth. +- call site (~4130): builds the maps into `RectStripModes` and bumps `PALETTE_SPLIT_TX_HITS`, the + counter the screen-content gate already HARD-asserts (`split_palette_matched > 0`, + stream.rs:2655), so this new path is gated, not merely exercised. + +## Gate results (EC_AV1_REQUIRE_AOMENC=1, --test-threads=1) +``` +cd /home/user/Documents/Code/Rust/edith_codecs-palette2 +export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 EC_AV1_REQUIRE_AOMENC=1 +cargo test -p ec-av1 --lib -j3 -- --test-threads=1 --nocapture \ + a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \ + a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact +``` +- `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`: 17/70 matched pixel-exact, + 21 decoded-and-pixel-exact but uncounted, 32 named refusals, `palette_rect_hits=92`. +- `a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`: 19/70 matched + (14 of them through a split-transform palette block), 19 decoded-and-pixel-exact but uncounted, + 32 named refusals. +- 38 successful decodes per gate, ALL pixel-compared (r8's integrity fix stands), 0 mismatches. +- `refusal_inventory` (3) + `gate_coverage` (2): 5 passed, 0 failed. + +## EVIDENCE +EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/r9-mismatch.obu (196 B, sha256 1f9bcc87138c39bbca9a38f95e5db09de0f84afdefeeaab2a7288e22b9c91068) | decode_probe dump vs `ffmpeg -f obu -f rawvideo -pix_fmt yuv420p`, before and after the fix | before: Y 8192 px wrong (x0..63, y0..127, max |d| 52), U 640 px, V 640 px; after: Y exact, U exact, V exact +EVIDENCE: git worktree at f31a2c5 (main), `cargo run -p ec-av1 --example decode_probe -- r9-mismatch.obu` | same stream on unmerged main | "REFUSED: unsupported: AV1 tile (a HORZ/VERT intra strip in a screen-content frame ...)" — the defect is a merge-created combination, not a main regression +EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1), two palette gates | full 70-attempt sweep each | 2 passed, 0 failed; counters above +EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1) | whole ec-av1 lib on 4f30677 | 277 passed, 0 failed, 23 ignored, 1748.98s + +## Refusals +Lifted this round: none newly lifted by this lane. Two strings LEFT the inventory as an +arithmetic consequence of the merge (each was already lifted with its own gate on one of the two +sides): "a HORZ/VERT intra strip in a screen-content frame ..." (this lane's, gated by the two +palette gates above) and "a HORZ/VERT intra strip with a split transform ..." (main's +lane-rectsplit, gated there). The palette-on-split-tx path added here is gated by the existing +HARD assert `split_palette_matched > 0` (stream.rs:2655), now 14. + +## Residue +- deferred(this batch's merge, then one mechanical sweep): the 8 sibling `stream.rs` sites listed + in r8 that still `continue` past the pixel compare when their hit counter did not move + (~2662, ~3781, ~3959, ~4159, ~4354, ~4530, ~7222, ~7495). Untouched here for the same reason as + r8 — concurrent lanes own those gates and each needs its own aomenc sweep. +- accepted: the 16px palette-neighbour grid corner-cut (`record_palette_y_rect`), ceiling named in + the code; libaom keeps `palette_size` per 4px mi cell. +- accepted: `PALETTE_SPLIT_TX_HITS` is bumped by both the square split path (decode.rs ~6159) and + the new rect-strip path, so the gate's assert does not distinguish them; the gate's own recipe + (`--min-partition-size=16`, rect strips present) plus this round's before/after pixel evidence + covers the rect case.