diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index da177b90..3975b3cf 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1455,6 +1455,18 @@ thread_local! { static PALETTE_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } +thread_local! { + /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the + /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves + /// (16x8/8x16), the two shapes the lifted refusals named. + static RECT4_PALETTE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT4_PALETTE_HITS`]. +pub(crate) fn rect4_palette_hits() -> usize { + RECT4_PALETTE_HITS.with(|c| c.get()) +} + /// Current value of [`PALETTE_SPLIT_TX_HITS`]. pub(crate) fn palette_split_tx_hits() -> usize { PALETTE_SPLIT_TX_HITS.with(|c| c.get()) @@ -3998,11 +4010,21 @@ impl Neighbours { /// 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) { + self.palette_ctx_and_cache_mi(at, at.0 * (SUB / MI)) + } + + /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a + /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache` + /// drops the above neighbour on a 64-px superblock boundary + /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the + /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the + /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of + /// every strip in an SB's top cell row, which libaom does not do. + fn palette_ctx_and_cache_mi(&self, at: (usize, usize), mi_r: usize) -> (usize, Vec) { let (r, c) = at; - let above_ok = r % 4 != 0; + let above_ok = mi_r % 16 != 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_is_palette = mi_r > 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 { @@ -4088,8 +4110,14 @@ impl Neighbours { /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`), /// so only the cache is wanted here. fn palette_uv_cache(&self, at: (usize, usize)) -> Vec { + self.palette_uv_cache_mi(at, at.0 * (SUB / MI)) + } + + /// [`Self::palette_uv_cache`] with the block's real mi row -- see + /// [`Self::palette_ctx_and_cache_mi`]. + fn palette_uv_cache_mi(&self, at: (usize, usize), mi_r: usize) -> Vec { let (r, c) = at; - let above_ok = r % 4 != 0; + let above_ok = mi_r % 16 != 0; let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 { (self.above_palette_uv_size[c], self.above_palette_uv_colors[c]) } else { @@ -5666,7 +5694,13 @@ fn read_intra_mode_rect( 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); + // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a + // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to + // BLOCK_4X8, both floored at the 4-px transform. Halving the short + // axis to 2 read HALF the colour-index symbols of a 1:4 strip's + // chroma palette and desynced the tile from there. + let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4)); + let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true); PALETTE_UV_HITS.with(|c| c.set(c.get() + 1)); PaletteUv { size: n, u_colors, v_colors, map } }); @@ -5683,6 +5717,48 @@ fn read_intra_mode_rect( )) } +/// Stamps a 1:4 strip's palette state into the coarse above/left arrays. +/// `av1_get_palette_cache` reads `xd->above_mbmi`/`xd->left_mbmi`, and inside +/// a HORZ_4 (VERT_4) the next strip's ABOVE (LEFT) neighbour is this strip +/// while its LEFT (ABOVE) neighbour is still the parent block's. The coarse +/// [`SUB`]-cell arrays alias all four strips onto one entry, so writing BOTH +/// axes after every strip would hand strip i+1 this strip's colours on the +/// wrong axis too -- a wrong cache costs the same bits, so the tile stays in +/// sync and only the pixels are wrong (class [[cdf-row-held-constant]]). +/// Only the split axis is written until the closing strip, which stamps both +/// for whatever follows the parent block. +#[allow(clippy::too_many_arguments)] +fn record_strip_palette( + n: &mut Neighbours, + at: (usize, usize), + bw: usize, + bh: usize, + y_size: usize, + y_colors: [u16; 8], + uv_size: usize, + uv_colors: [u16; 8], + last: bool, +) { + let (r, c) = at; + let horz = bw > bh; + if horz || last { + for cell in 0..(bw / SUB).max(1) { + n.above_palette_size[c + cell] = y_size; + n.above_palette_colors[c + cell] = y_colors; + n.above_palette_uv_size[c + cell] = uv_size; + n.above_palette_uv_colors[c + cell] = uv_colors; + } + } + if !horz || last { + for cell in 0..(bh / SUB).max(1) { + n.left_palette_size[r + cell] = y_size; + n.left_palette_colors[r + cell] = y_colors; + n.left_palette_uv_size[r + cell] = uv_size; + n.left_palette_uv_colors[r + cell] = uv_colors; + } + } +} + /// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1): /// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour /// above against this block's own *width* and the neighbour to the left @@ -6881,8 +6957,11 @@ fn decode_leaf_rect( // 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); + // lane-kf900 r4: the leaf's REAL mi row -- the second leaf of a 16x8 pair + // sits 8 px into the cell, so the cache's superblock-top-row exclusion + // must not be read off the cell (see [`Neighbours::palette_ctx_and_cache_mi`]). + let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at, leaf_mi.0); + let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at, leaf_mi.0); let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) = read_intra_mode_rect( dec, @@ -6901,14 +6980,31 @@ fn decode_leaf_rect( leaf_mi.0, leaf_mi.1, )?; + // lane-kf900 r4: palette prediction on this shape, the same colour-index + // map -> base colours buffer [`decode_block_rect`] hands each + // `reconstruct_rect` through [`set_palette_pred`]. 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)", - )); + RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1)); } + let palette_y_buf: Option> = palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); + let palette_uv_bufs: Option<(Vec, Vec)> = 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(), + ) + }); + let (pal_y_size, pal_y_colors) = + palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + let (pal_uv_size, pal_uv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + // The closing leaf of the pair -- see [`record_strip_palette`]. + let pal_last = if bw > bh { + leaf_mi.0 % 4 == 2 + } else { + leaf_mi.1 % 4 == 2 + }; 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}"); } @@ -6967,11 +7063,12 @@ fn decode_leaf_rect( // the unsplit arm below passes the real neighbour answer -- chroma // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type. smooth_neighbor_uv, - // Both callers refuse a palette on this shape above (pixel - // reconstruction is unported here), so the split units carry none. - palette_y: None, - palette_uv: None, + palette_y: palette_y_buf.clone(), + palette_uv: palette_uv_bufs.clone(), }; + 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, @@ -6988,6 +7085,10 @@ fn decode_leaf_rect( base_q_idx, reduced_tx_set, )?; + record_strip_palette( + neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, + pal_last, + ); return Ok(mode); } let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); @@ -6999,15 +7100,24 @@ fn decode_leaf_rect( luma_levels = vec![0i32; bw * bh]; u_levels = vec![0i32; chroma_w * chroma_h]; v_levels = vec![0i32; chroma_w * chroma_h]; + if let Some(b) = &palette_y_buf { + set_palette_pred(b.clone()); + } y.reconstruct_rect( px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra, 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, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels, alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, ); + if let Some((_, vb)) = &palette_uv_bufs { + set_palette_pred(vb.clone()); + } v.reconstruct_rect( cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels, alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, @@ -7043,6 +7153,9 @@ fn decode_leaf_rect( &luma_levels, bw, bh, crate::decode::bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type, ); + if let Some(b) = &palette_y_buf { + set_palette_pred(b.clone()); + } y.reconstruct_rect( px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra, smooth_neighbor, @@ -7060,6 +7173,9 @@ fn decode_leaf_rect( &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type, ); + if let Some((ub, _)) = &palette_uv_bufs { + set_palette_pred(ub.clone()); + } u.reconstruct_rect( cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual, alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, @@ -7076,6 +7192,9 @@ fn decode_leaf_rect( &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(), CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type, ); + if let Some((_, vb)) = &palette_uv_bufs { + set_palette_pred(vb.clone()); + } v.reconstruct_rect( cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual, alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, @@ -7085,12 +7204,15 @@ 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]); + // The leaf's own palette state (`0` clears, as this site always did + // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT + // AXIS only until the pair's closing leaf: the coarse cell holds one + // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the + // real left neighbour leaf 1 reads (lane-kf900 r4). + record_strip_palette( + neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, + pal_last, + ); // 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); @@ -7154,6 +7276,14 @@ fn decode_block_rect4( // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell. let (above_mode, left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode)); + // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache. + // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every + // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count, + // wrong interval, so a screen-content tile desynced at the first strip + // whose neighbour used a palette (class [[cdf-row-held-constant]]). + let pal_at = (mi_r / (SUB / MI), mi_c / (SUB / MI)); + let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at, mi_r); + let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at, mi_r); let ( skip, mode, @@ -7176,21 +7306,35 @@ fn decode_block_rect4( enable_filter_intra, neighbours.skip_txfm_ctx(mi_r, mi_c), allow_screen_content_tools, - None, - &[], + Some((palette_ctx, &palette_cache)), + &palette_uv_cache, 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. + // lane-kf900 r4: palette prediction on this shape, exactly as + // [`decode_block_rect`] does one aspect ratio up -- the colour-index map + // mapped through the base colours IS the prediction (it reads no edge + // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`]. 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)", - )); + RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1)); } + let palette_y_buf: Option> = palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); + let palette_uv_bufs: Option<(Vec, Vec)> = 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(), + ) + }); + // `last`: strip 3 of the parent 32x32's HORZ_4 (VERT_4), the only one + // whose colours a block outside the parent sees -- see + // [`record_strip_palette`]. + let pal_last = if bw > bh { mi_r % 8 == 6 } else { mi_c % 8 == 6 }; + let (pal_y_size, pal_y_colors) = + palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + let (pal_uv_size, pal_uv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); 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)); @@ -7250,11 +7394,12 @@ fn decode_block_rect4( filter_intra, smooth_neighbor, smooth_neighbor_uv, - // Both callers refuse a palette on this shape above (pixel - // reconstruction is unported here), so the split units carry none. - palette_y: None, - palette_uv: None, + palette_y: palette_y_buf.clone(), + palette_uv: palette_uv_bufs.clone(), }; + 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, @@ -7271,6 +7416,10 @@ fn decode_block_rect4( base_q_idx, false, )?; + record_strip_palette( + neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, + pal_uv_colors, pal_last, + ); if bw > bh { RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1)); } else { @@ -7362,6 +7511,9 @@ fn decode_block_rect4( plane_q_delta(0).1, luma_tx_type, ); + if let Some(b) = &palette_y_buf { + set_palette_pred(b.clone()); + } y.reconstruct_rect( px, py, @@ -7390,6 +7542,9 @@ fn decode_block_rect4( plane_q_delta(plane).1, tx_type, ); + if let Some((ub, vb)) = &palette_uv_bufs { + set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }); + } buf.reconstruct_rect( cpx, cpy, @@ -7414,6 +7569,10 @@ fn decode_block_rect4( ); 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); + record_strip_palette( + neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, + pal_uv_colors, pal_last, + ); if bw > bh { RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1)); } else { @@ -7421,6 +7580,9 @@ fn decode_block_rect4( } return Ok((mode, uv_predict_mode)); }; + if let Some(b) = &palette_y_buf { + set_palette_pred(b.clone()); + } y.reconstruct_rect( px, py, @@ -7435,6 +7597,9 @@ fn decode_block_rect4( 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, @@ -7448,6 +7613,9 @@ fn decode_block_rect4( None, smooth_neighbor_uv, ); + if let Some((_, vb)) = &palette_uv_bufs { + set_palette_pred(vb.clone()); + } v.reconstruct_rect( cpx, cpy, @@ -7464,6 +7632,10 @@ fn decode_block_rect4( 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); + record_strip_palette( + neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, + pal_last, + ); if bw > bh { RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1)); } else { @@ -7543,6 +7715,12 @@ fn decode_rect4_16( } let (above_mode, left_mode) = neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode)); + // lane-kf900 r4: the strip's real palette ctx + colour cache (see + // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode` + // off CDF row 0 and every cache hit off an empty cache. + let (palette_ctx, palette_cache) = + neighbours.palette_ctx_and_cache_mi(at16, lmi.0); + let palette_uv_cache = neighbours.palette_uv_cache_mi(at16, lmi.0); let ( skip, mode, @@ -7565,16 +7743,26 @@ fn decode_rect4_16( enable_filter_intra, neighbours.skip_txfm_ctx(lmi.0, lmi.1), allow_screen_content_tools, - None, - &[], + Some((palette_ctx, &palette_cache)), + &palette_uv_cache, lmi.0, lmi.1, )?; 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)", - )); - } + RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1)); + } + // The colour-index map through the base colours IS the prediction. + // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one + // chroma transform this closing strip codes. + let palette_y_buf: Option> = palette_y + .as_ref() + .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); + let palette_uv_bufs: Option<(Vec, Vec)> = 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(), + ) + }); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); if smooth_neighbor { SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1)); @@ -7622,6 +7810,15 @@ fn decode_rect4_16( tx_h, reach, ); + if let Some(b) = &palette_y_buf { + let tu_buf: Vec = (0..tx_h) + .flat_map(|i| { + let base = (tu_row * tx_h + i) * bw + tu_col * tx_w; + b[base..base + tx_w].iter().copied() + }) + .collect(); + set_palette_pred(tu_buf); + } if skip { y.reconstruct_rect( tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu, @@ -7705,6 +7902,9 @@ fn decode_rect4_16( } else { let levels = if skip { let zeros = vec![0i32; bw * bh]; + if let Some(b) = &palette_y_buf { + set_palette_pred(b.clone()); + } y.reconstruct_rect( px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra, smooth_neighbor, @@ -7741,6 +7941,9 @@ fn decode_rect4_16( plane_q_delta(0).1, tx_type, ); + if let Some(b) = &palette_y_buf { + set_palette_pred(b.clone()); + } y.reconstruct_rect( px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra, smooth_neighbor, @@ -7801,6 +8004,9 @@ fn decode_rect4_16( CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1)); } for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] { + if let Some((ub, vb)) = &palette_uv_bufs { + set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }); + } buf.reconstruct_rect( cpx, cpy, @@ -7856,6 +8062,9 @@ fn decode_rect4_16( plane_q_delta(plane).1, tx_type, ); + if let Some((ub, vb)) = &palette_uv_bufs { + set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }); + } buf.reconstruct_rect( cpx, cpy, @@ -7906,6 +8115,14 @@ fn decode_rect4_16( } else { RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1)); } + let (pal_y_size, pal_y_colors) = + palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + let (pal_uv_size, pal_uv_colors) = + palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); + record_strip_palette( + neighbours, at16, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors, + i == 3, + ); last_mode = mode; prev = Some((lmi, mode)); } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 4ab1f2c6..5b269c10 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -34,7 +34,6 @@ const REFUSALS: &[&str] = &[ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)", - "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})", @@ -45,7 +44,6 @@ const REFUSALS: &[&str] = &[ "a 128x128 superblock HORZ/VERT or AB partition (only SPLIT and NONE are decoded at the 128 root)", "a 128x128 superblock PARTITION_NONE root on an inter frame (only the key-frame path codes a whole 128x128 block)", "intrabc under a 128x128 superblock (libaom's av1_is_dv_valid derives the block-vector delay from sb_size, which this decoder hardcodes to 64)", - "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", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8d98156b..3312974a 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2713,6 +2713,211 @@ mod tests { } } + /// lane-kf900 r4, the gate for the two lifted palette refusals ("a 1:4 + /// rect strip that actually uses a palette (reconstruction is not ported + /// at this shape)" and "a palette block on a HORZ/VERT intra strip below + /// 16x16 (reconstruction not ported)"): real `aomenc` streams that put a + /// palette on a RECT strip, decoded whole-frame pixel-exact against + /// ffmpeg's own decode of the identical bytes, at 8 AND 10 bit. + /// + /// Arm 0 is the stream lane-kf900 r3 pinned and stopped on -- `testsrc2` + /// 256x192, `--cq-level=59 --cpu-used=0 --min-partition-size=8 + /// --enable-rect-partitions=1 --enable-tx-size-search=1`, md5 + /// `e5f033d8fe34e4418d8cca3ac9d2b595` at 10 bit. Arms 1-2 force the shape + /// on screen-like content with `--tune-content=screen --enable-palette=1 + /// --enable-1to4-partitions=1`. + /// + /// An attempt whose decode never hit a rect-strip palette block proves + /// nothing about the lift, so it is counted OUT OF SCOPE rather than + /// silently passing -- but a mismatch on one is still a failure + /// (`out_of_scope_mismatch == 0`), and at least one attempt must fire the + /// counter or the gate is vacuous. + #[test] + fn a_real_aomenc_rect_strip_palette_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_rect_strip_palette_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (256usize, 192usize); + let screen: &[&str] = &[ + "--tune-content=screen", + "--enable-palette=1", + "--enable-1to4-partitions=1", + "--min-partition-size=8", + ]; + let arms: [(&str, String, &[&str]); 3] = [ + ("testsrc2-pinned", "testsrc2=s=256x192:r=25".to_string(), &[]), + ("testsrc2-screen", "testsrc2=s=256x192:r=25".to_string(), screen), + ("smptebars-screen", "smptebars=size=256x192:rate=25".to_string(), screen), + ]; + let (mut fired_arms, mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32, 0u32); + let mut refused = 0u32; + let mut fired_at_depth = [0u32; 2]; + let mut frames_compared = 0usize; + for (arm, src, extra) in &arms { + for depth in [8usize, 10] { + let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let render = || { + let out = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", src.as_str(), "-t", "0.2", + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(out.status.success(), "{NAME}: ffmpeg failed for {arm}"); + out.stdout + }; + let y4m_a = render(); + let y4m_b = render(); + assert_eq!( + y4m_a, y4m_b, + "{NAME}: {arm} must render byte-identical across two runs at {depth}-bit" + ); + let y4m = y4m_a; + let depth_arg = format!("--bit-depth={depth}"); + let in_depth_arg = format!("--input-bit-depth={depth}"); + let mut child = Command::new(aomenc_path()) + .args(["--codec=av1"]) + .args([&depth_arg, &in_depth_arg]) + .args([ + "--passes=1", + "--end-usage=q", + "--cq-level=59", + "--cpu-used=0", + "--lag-in-frames=0", + "--kf-max-dist=1", + "--limit=1", + "--threads=1", + "--tile-columns=0", + "--enable-tx-size-search=1", + "--min-partition-size=8", + "--enable-rect-partitions=1", + ]) + // Per-arm overrides go AFTER the base recipe: aomenc keeps + // the LAST occurrence of a repeated flag. + .args(*extra) + // The 8-bit twin of the pinned recipe picks a 128-root + // HORZ partition, which this decoder still refuses by name + // ("a 128x128 superblock HORZ/VERT or AB partition") -- + // an open refusal of another lane, unrelated to palette. + // Pinning the superblock to 64 keeps the 8-bit arm on the + // shape this gate is about; the 10-bit arms are the + // untouched pinned recipe. + .args(if depth == 8 { &["--sb-size=64"][..] } else { &[][..] }) + .args(["--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) + .or_else(|e| match e.kind() { + // aomenc rejecting the input closes the pipe before we + // finish writing; its own stderr below is the report. + std::io::ErrorKind::BrokenPipe => Ok(()), + _ => Err(e), + }) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "{NAME}: aomenc refused {arm} at {depth}-bit: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::rect4_palette_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + // A NAMED refusal is another lane's open shape (here: a + // palette on an 8x8 SQUARE leaf, still out of scope), never + // a pass -- the attempt is counted out of scope and the + // per-depth firing assert below keeps the gate honest. + Err(e) if e.to_string().contains("unsupported") => { + eprintln!("{NAME}: {arm} {depth}-bit REFUSED: {e}"); + refused += 1; + continue; + } + Err(e) => panic!("{NAME}: decode failed on {arm} at {depth}-bit: {e}"), + }; + let fired = decode::rect4_palette_hits() - before; + let ffmpeg_frames = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames.len()) + }; + assert_eq!( + frames.len(), + ffmpeg_frames.len(), + "{NAME}: {arm} at {depth}-bit -- frame count" + ); + assert!(!frames.is_empty(), "{NAME}: {arm} at {depth}-bit decoded no frame"); + // EVERY decode-order frame, all three planes. + let mut exact = true; + for (i, (ours, theirs)) in frames.iter().zip(ffmpeg_frames.iter()).enumerate() { + if ours.y != theirs.y || ours.u != theirs.u || ours.v != theirs.v { + exact = false; + eprintln!("{NAME}: {arm} {depth}-bit frame {i} differs"); + } + frames_compared += 1; + } + if fired > 0 { + fired_arms += 1; + fired_at_depth[usize::from(depth == 10)] += 1; + assert!( + exact, + "{NAME}: {arm} at {depth}-bit has {fired} rect-strip palette block(s) \ + and does NOT decode pixel-exact" + ); + } else { + out_of_scope += 1; + if !exact { + out_of_scope_mismatch += 1; + } + } + } + } + eprintln!( + "{NAME}: {fired_arms} attempt(s) with a rect-strip palette block, \ + {out_of_scope} out of scope ({out_of_scope_mismatch} mismatched), \ + {refused} refused, {frames_compared} frames compared, \ + fired 8-bit={} 10-bit={}", + fired_at_depth[0], fired_at_depth[1] + ); + // MEASURED 2026-09-02, every 8-bit attempt of these recipes: aomenc + // puts its palettes on SQUARE blocks at 8 bit and every 8-bit stream + // that reaches a rect strip with one lands on a palette shape still + // out of scope (8x8 square leaf, or a 64x32/32x64 superblock strip + // with a real transform). So the 8-bit arms here prove the DECODE + // path, not the lift -- `fired_at_depth[0] == 0` is a known, reported + // coverage gap and not a silent pass: the counter is printed. + assert!( + fired_at_depth[1] > 0, + "{NAME}: no attempt put a palette on a rect strip \ + (8-bit={}, 10-bit={}) -- gate is vacuous", + fired_at_depth[0], + fired_at_depth[1] + ); + assert!(fired_arms > 0, "{NAME}: gate is vacuous"); + assert_eq!( + out_of_scope_mismatch, 0, + "{NAME}: {out_of_scope_mismatch} attempt(s) without a rect-strip palette block \ + still mismatched -- an unrelated defect, not a SKIP" + ); + } + /// lane-hbd r5: a real `aomenc --bit-depth=10` stream, decoded through /// this crate's own 10-bit planes (`Picture` widened to `u16` in an /// earlier round) and checked pixel-exact against ffmpeg's own decode of diff --git a/lanes/kf900-r4.report.md b/lanes/kf900-r4.report.md new file mode 100644 index 00000000..998ac829 --- /dev/null +++ b/lanes/kf900-r4.report.md @@ -0,0 +1,70 @@ +# lane-kf900 r4 report -- rect-strip palette reconstruction + +## What changed (all in `crates/ec-av1/`) + +| path:line (post-change) | why | +| --- | --- | +| `src/decode.rs` `Neighbours::palette_ctx_and_cache_mi` / `palette_uv_cache_mi` | `av1_get_palette_cache` drops the above neighbour on a 64-px SB boundary keyed on the block's own PIXEL row (`pred_common.c:76`). The old code read `at.0 % 4` off the 16-px `SUB` cell, so strip 1 of a HORZ_4 (8 px into the cell) wrongly excluded strip 0 from its cache in every SB-top cell row. Old entry points kept, delegating. | +| `src/decode.rs` `read_intra_mode_rect`, chroma colour-index map | the map is `av1_get_plane_block_size(bsize,1,1)` (`ss_size_lookup`), not a plain halving: BLOCK_16X4 -> BLOCK_8X4, BLOCK_4X16 -> BLOCK_4X8. `(bw/2, bh/2)` read HALF the colour-index symbols of a 1:4 strip's chroma palette. Now `((bw/2).max(4), (bh/2).max(4))`. | +| `src/decode.rs` `record_strip_palette` (new) | the coarse `SUB`-cell palette arrays alias all four strips of a HORZ_4/VERT_4 (and both leaves of a 16x8/8x16 pair) onto one entry, so stamping BOTH axes after every strip hands strip i+1 strip i's colours on the WRONG axis too. Writes the split axis until the closing strip, both on it. | +| `src/decode.rs` `decode_block_rect4` (32x8/8x32) | was `palette: None, &[]` -> real ctx + cache; palette-Y/UV prediction wired into the split-tx walk (`RectStripModes`), the coded arm and the skip arm; palette state stamped on all three exits. Refusal dropped. | +| `src/decode.rs` `decode_rect4_16` (16x4/4x16) | same, per strip, incl. the inlined per-TU split walk (window of the block's palette buffer per unit) and the pair's chroma. Refusal dropped. | +| `src/decode.rs` `decode_leaf_rect` (16x8/8x16) | sibling refusal "a palette block on a HORZ/VERT intra strip below 16x16" dropped the same way; its zero-clear of the palette arrays became `record_strip_palette`, which also fixes leaf 0 of a pair zeroing the LEFT entry leaf 1 legitimately reads. | +| `src/decode.rs` `RECT4_PALETTE_HITS` / `rect4_palette_hits()` | the gate's counter: rect intra strips that ACTUALLY use a palette. | +| `src/refusal_inventory.rs` | both lifted strings removed (47 -> 45). | +| `src/stream.rs` `a_real_aomenc_rect_strip_palette_decodes_pixel_exact` | the gate. | + +libaom sites cited: `decodemv.c` `read_palette_mode_info` (`av1_allow_palette`, `av1_get_palette_bsize_ctx`, `av1_get_palette_mode_ctx`), `read_palette_colors_y` (`decodemv.c:478`) / `read_palette_colors_uv` (`:509`), `pred_common.c:73` `av1_get_palette_cache`, `decodeframe.c` `decode_color_map_tokens` via `av1_visit_palette` (map read AFTER all mode info -- unchanged, already correct here). + +## Refusals lifted (2) + +1. `a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)` +2. `a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)` + +## Gate + +`crates/ec-av1/src/stream.rs::a_real_aomenc_rect_strip_palette_decodes_pixel_exact` +3 arms x 2 depths. Arm 0 IS the r3 pinned stream: `testsrc2=s=256x192:r=25`, `--cq-level=59 +--cpu-used=0 --lag-in-frames=0 --kf-max-dist=1 --limit=1 --threads=1 --tile-columns=0 +--enable-tx-size-search=1 --min-partition-size=8 --enable-rect-partitions=1`, and the encoder +invocation inside the test reproduces md5 `e5f033d8fe34e4418d8cca3ac9d2b595` byte for byte at +10-bit. Arms 1-2 add `--tune-content=screen --enable-palette=1 --enable-1to4-partitions=1 +--min-partition-size=8` on testsrc2 / smptebars. Every decode-order frame, all three planes, +compared against ffmpeg's decode of the identical bytes. Hard asserts: a rect-strip palette +block fired (`rect4_palette_hits()` delta), `out_of_scope_mismatch == 0`, sources render +byte-identical twice. A NAMED (`unsupported`) refusal is counted and printed, never a pass. + +``` +cargo test -p ec-av1 --lib a_real_aomenc_rect_strip_palette_decodes_pixel_exact -- --nocapture +``` + +EVIDENCE: $HOME/.cache/kf900/sweep/g.obu + gate stdout | aomenc pinned recipe -> decode_stream -> ffmpeg compare, 3 arms x {8,10} bit | 2 attempts with a rect-strip palette block, both whole-frame pixel-exact (Y+U+V), 0 out-of-scope mismatches, 4 named refusals on other shapes, md5 of the test's own 10-bit arm-0 stream == e5f033d8fe34e4418d8cca3ac9d2b595 +EVIDENCE: decode_probe on $HOME/.cache/kf900/sweep/g.obu | before/after this commit | `REFUSED: ... a 1:4 rect strip that actually uses a palette` -> `OK: 1 frames decoded, 256x192`, rect4_32 horz=8 vert=0 -> horz=12 vert=16 + +## Corrected premises (both stated as fact in the charter/handoff) + +- **`skip_split_tx` does NOT fire on the pinned stream.** `decode_probe` on the fully decoded + stream prints `skip_split_tx: 0`. The r3 handoff's "fires skip_split_tx AND reaches that + refusal" is half wrong, so the gate asserts the palette counter and does not assert + `skip_split_tx`; asserting it would have been a vacuous/failing gate. +- **64x16/16x64 needed no work.** `decode_block_rect64` already passes the real ctx/cache and + reconstructs palette; its only palette refusal is the separate corner-cropped-luma one. + +## Open residue + +- **deferred(8-bit rect-strip palette coverage)** -- `fired 8-bit=0, 10-bit=2`. At 8 bit aomenc + puts its palettes on SQUARE blocks; every 8-bit recipe tried that reaches a rect strip with a + palette lands on a shape still out of scope (`a block that actually uses a palette (Y)` on an + 8x8 square leaf, or `a palette block with a real transform on a superblock-level HORZ/VERT + strip`). Unblocked by lifting either of those two refusals. The 8-bit arms still run and prove + the decode path; the counter is printed, not hidden. +- **fix-now-elsewhere: a NEW pre-existing 8-bit 1:4 pixel mismatch, unrelated to palette.** + Recipe: `testsrc2=s=256x192:r=25`, 8-bit, base recipe above plus + `--tune-content=screen --enable-palette=1 --enable-1to4-partitions=1 --max-partition-size=32 + --sb-size=64`. Decodes `OK: 1 frames decoded` with `rect4_32: horz=8 vert=8 coded=16` and + frame 0 differs from ffmpeg. Proved unrelated to this round: the stream reads ZERO palette + symbols (`EC_AV1_TRACE=1 decode_probe | grep -c "^EC_PAL "` == 0), so every change in this + commit is inert on it. Needs its own lane. +- **accepted**: `a palette block with a real transform on a superblock-level HORZ/VERT strip` + and `a block that actually uses a palette (Y/UV)` (8x8 square leaf) remain -- out of this + lane's charter (both are square/SB-level, not rect strips).