From 254b9086d6ed682fc73fc898574d3b5622b13a1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 14:16:05 +0300 Subject: [PATCH] fix(av1): write a cut palette block's colour-index map over its on-screen part only A palette block straddling the frame's right/bottom mi edge codes its map over spec 5.11.50's onscreenWidth x onscreenHeight corner and the decoder replicates it outward. The writer walked the full block grid, so every conformant decoder read the map short and desynced the rest of the tile; our own trial decode agreed with itself because the encoder-side FrameCtx carried no mi dims and the reader mirrored the writer there. Both frame encoders now publish the header's mi dims on that ctx, the palette search folds its searched map to the on-screen corner (so the priced, reconstructed and written map are one map), and the writer codes that corner only. The reader's mirror-the-writer branch is gone. Witness: encoder::tests::a_palette_block_cut_by_the_frame_edge_decodes_ exactly_through_ffmpeg -- our encoder at 384x152, 12 cut maps written, every plane of every frame equal to ffmpeg's decode. --- crates/ec-av1/src/decode.rs | 49 ++++++++++------ crates/ec-av1/src/encode.rs | 48 +++++++++++++-- crates/ec-av1/src/encoder.rs | 109 ++++++++++++++++++++++++++++++++++- crates/ec-av1/src/tile.rs | 81 +++++++++++++++++++++++--- 4 files changed, 256 insertions(+), 31 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 897f3397..88a5d4c8 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -8834,18 +8834,26 @@ fn palette_onscreen( bh: usize, fctx: &crate::decode::FrameCtx, ) -> (usize, usize) { + // lane-palw: the ENCODER's own in-process reconstruct runs on a + // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both + // frame encoders publish the header's mi dims onto it themselves + // (`encode.rs`, beside their `true_width`/`true_height`) so that this + // clamp and `tile::write_color_index_map`'s now agree there too. let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get()); - // corner-cut: no mi dims means this is not a real frame decode but the - // ENCODER's own in-process reconstruct (`FrameCtx::for_encoder`, where - // `set_segmentation` never runs), whose writer half - // (`tile::write_color_index_map`) is unclamped too -- the two mirror each - // other, and clamping only one of them read every map as 1x1. Ceiling: - // our encoder still writes a full map for a palette block cut by the - // frame edge, which a conformant decoder reads short. Upgrade path: clamp - // the writer, publish the mi dims on the encoder's ctx, drop this branch. - if mi_rows == 0 || mi_cols == 0 { - return (bw, bh); - } + palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols)) +} + +/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches +/// it (`tile::write_palette_syntax`, armed per frame): the two sides must +/// compute the same on-screen extent or the decoder reads a different number +/// of symbols than the encoder wrote. +pub(crate) fn palette_onscreen_dims( + mi_r: usize, + mi_c: usize, + bw: usize, + bh: usize, + (mi_rows, mi_cols): (usize, usize), +) -> (usize, usize) { ( bw.min(mi_cols.saturating_sub(mi_c) * MI), bh.min(mi_rows.saturating_sub(mi_r) * MI), @@ -8856,7 +8864,7 @@ fn palette_onscreen( /// the SAME sub-8 bump the caller's own `(bw / 2).max(4)` applies to the block /// dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move together /// or a cut 8-wide block reads its chroma map at the wrong width. -fn palette_onscreen_uv( +pub(crate) fn palette_onscreen_uv( luma: (usize, usize), on: (usize, usize), chroma: (usize, usize), @@ -8939,10 +8947,18 @@ fn decode_color_index_map_wh( } } } - // `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): - // the last on-screen column then the last on-screen row are replicated - // over the off-screen remainder, so the prediction still covers the whole - // block. + palette_replicate(&mut map, bw, bh, on); + map +} + +/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the +/// last on-screen column then the last on-screen row are replicated over the +/// off-screen remainder, so the prediction still covers the whole block. The +/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms), +/// so the pixels it prices and reconstructs are the ones the on-screen +/// symbols it writes really decode to. +pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) { + let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh)); for row in 0..on_bh { let last = map[row * bw + on_bw - 1]; map[row * bw + on_bw..row * bw + bw].fill(last); @@ -8950,7 +8966,6 @@ fn decode_color_index_map_wh( for row in on_bh..bh { map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw); } - map } /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index fb5e0693..889dc2ff 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -5616,8 +5616,19 @@ fn code_square( .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) .collect(); let kept = luma.snapshot(x, y, side); - for pal in palette_candidates(&source) { + // spec 5.11.50: a block cut by the frame's right/bottom edge codes + // its map over the ON-SCREEN corner only and the decoder replicates + // that outward, so the searched map is folded the same way here -- + // the prediction priced, the reconstruction committed and the symbols + // `write_color_index_map` writes are then one and the same map + // (lane-palw). + let on = ( + side.min(luma.true_width.saturating_sub(x)), + side.min(luma.true_height.saturating_sub(y)), + ); + for mut pal in palette_candidates(&source) { let n = usize::from(pal.size); + crate::decode::palette_replicate(&mut pal.map, side, side, on); let prediction: Vec = pal .map .iter() @@ -5637,7 +5648,7 @@ fn code_square( + search.lambda * (trial.bits + mode_bits[DC_PRED as usize] - + crate::tile::palette_bits(&pal, side) + + crate::tile::palette_bits(&pal, side, on) + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); if cost_p < cost { cost = cost_p; @@ -6056,8 +6067,19 @@ fn search_chroma( .collect() }; let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); - for pal in palette_candidates(&u_source) { + // The luma on-screen extent carried into this plane exactly as the + // reader does it (`decode::palette_onscreen_uv`); see the luma arm. + let on_uv = crate::decode::palette_onscreen_uv( + (side, side), + ( + side.min(luma.true_width.saturating_sub(x)), + side.min(luma.true_height.saturating_sub(y)), + ), + (at.side, at.side), + ); + for mut pal in palette_candidates(&u_source) { let n = usize::from(pal.size); + crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv); // V's base colour per cluster: the mean of the samples the shared // map assigns to it (an empty cluster cannot happen -- every // colour `palette_candidates` returns is some pixel's nearest). @@ -6101,7 +6123,7 @@ fn search_chroma( + search.lambda * (u_trial.bits + v_trial.bits - + crate::tile::palette_uv_bits(&candidate, side)); + + crate::tile::palette_uv_bits(&candidate, side, on_uv)); if cost_p < cost { cost = cost_p; mode = DC_PRED; @@ -7881,6 +7903,14 @@ pub(crate) fn encode_key_frame_inner( // Prediction reads no further than this, in each plane's own units -- // see `Plane::true_width`/`true_height`. let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); + // lane-palw: the encoder's own in-process reconstruct reads its palette + // colour-index maps back through `decode::palette_onscreen`, which takes + // the frame's mi dims off the `FrameCtx` -- a real decode gets them from + // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish + // them here so the reconstruct clamps a block cut by the frame edge + // exactly as the writer now does. + let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize); + fctx.seg_mi_dims.set(frame_mi_dims); // lane-hbd r4: `Picture.y/u/v` widened to `Vec` for the decoder's // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by // design (see `intra_predict_u8`'s doc comment), so narrow the source @@ -8351,6 +8381,7 @@ pub(crate) fn encode_key_frame_inner( crate::tile::arm_sb128(sb128_on()); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); + crate::tile::arm_frame_mi_dims(frame_mi_dims); crate::tile::arm_filter_intra(filter_intra_on()); crate::tile::arm_intrabc(allow_intrabc); crate::tile::arm_pricing_cdfs(None, false); @@ -11453,6 +11484,14 @@ pub(crate) fn encode_inter_frame( } let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); + // lane-palw: the encoder's own in-process reconstruct reads its palette + // colour-index maps back through `decode::palette_onscreen`, which takes + // the frame's mi dims off the `FrameCtx` -- a real decode gets them from + // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish + // them here so the reconstruct clamps a block cut by the frame edge + // exactly as the writer now does. + let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize); + fctx.seg_mi_dims.set(frame_mi_dims); // lane-hbd r4: encoder stays 8-bit by design; narrow the source once // here (see `encode_key_frame_inner`). let picture_y8: Vec = picture.y.iter().map(|&v| v as u8).collect(); @@ -12385,6 +12424,7 @@ pub(crate) fn encode_inter_frame( crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); crate::tile::arm_high_precision_mv(hp_mv); crate::tile::arm_screen(screen); + crate::tile::arm_frame_mi_dims(frame_mi_dims); crate::tile::arm_filter_intra(filter_intra_on()); let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_pricing_cdfs(Some(&cdfs), screen); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 4ab4141b..18414acb 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -2940,7 +2940,11 @@ mod tests { /// entry per coded frame, in order — this facade's own equivalent of /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a /// PSNR check needs the decoded pixels, not just the coded byte count. - fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec> { + fn ffmpeg_decode_planes( + stream: &[u8], + width: usize, + height: usize, + ) -> Vec<(Vec, Vec, Vec)> { let path = std::env::temp_dir().join(format!( "ec-av1-facade-rate-decode-{}-{}.obu", std::process::id(), @@ -2963,10 +2967,111 @@ mod tests { let frame_len = luma + 2 * chroma; out.stdout .chunks_exact(frame_len) - .map(|f| f[..luma].to_vec()) + .map(|f| { + ( + f[..luma].to_vec(), + f[luma..luma + chroma].to_vec(), + f[luma + chroma..].to_vec(), + ) + }) + .collect() + } + + /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare. + fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec> { + ffmpeg_decode_planes(stream, width, height) + .into_iter() + .map(|(y, _, _)| y) .collect() } + /// lane-palw: OUR encoder's own witness for the writer half of the + /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall, + /// so the bottom superblock row's palette blocks hang 8 luma rows off the + /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN + /// corner only and replicates it outward, and the writer used to code the + /// full block grid -- symbols a conformant decoder never reads, so + /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode + /// (unclamped on both sides) agreed with itself. Class + /// `writer-phantom-units-past-edge`. + /// + /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's + /// export calls), and compared on EVERY plane -- a chroma palette map is + /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero + /// so the row cannot pass on a stream that cuts no palette map (class + /// gate-blind-to-feature). + #[test] + fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() { + const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg"; + let _knobs = crate::speed::knob_read(); + let _gate_lock = crate::stream::tests::lock_gate_counters(); + let (width, height) = (384usize, 152usize); + // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at + // most two luma values, so the palette arm wins across the WHOLE + // frame -- including the bottom superblock row, whose 16x16 blocks at + // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid. + // `screen_card`'s 4-px bands fire only 9 palettes here and none of + // them at the cut edge (class gate-blind-to-feature). + let card = |shift: usize| -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let cell = ((x + shift) / 8 + y / 8) % 2; + picture.y[y * width + x] = if cell == 0 { 40 } else { 200 }; + } + } + picture + }; + let sources: Vec = (0..2).map(|t| card(t * 16)).collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 60, + gop: 2, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + crate::tile::reset_palette_cut_maps_written(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + eprintln!("{NAME}: {} cut colour-index maps written", crate::tile::palette_cut_maps_written()); + assert!( + crate::tile::palette_cut_maps_written() > 0, + "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind" + ); + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg"); + return; + } + let theirs = ffmpeg_decode_planes(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + for (plane, got, want) in [ + ("luma", &a.y, &b.0), + ("U", &a.u, &b.1), + ("V", &a.v, &b.2), + ] { + let got: Vec = got.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) { + let w = if plane == "luma" { width } else { width / 2 }; + panic!( + "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}", + at % w, + at / w, + got[at], + want[at], + ); + } + } + } + } + /// A pyramid stream reorders pictures: the hidden `ALTREF` of each /// mini-GOP is coded before the leaves that precede it in display order, /// and a `show_existing_frame` header puts it back. This pins the shape diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 58579a73..772058ab 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -469,6 +469,31 @@ pub(crate) fn arm_screen(on: bool) { SCREEN.with(|c| c.set(on)); } +thread_local! { + /// This frame's `(mi_rows, mi_cols)` (spec `compute_image_size`), armed + /// beside [`SCREEN`] by both frame encoders: a palette block cut by the + /// frame's right/bottom mi edge codes its colour-index map over the + /// ON-SCREEN part only, so the writer needs the same dims the decoder's + /// `palette_onscreen` reads off its `FrameCtx` (lane-palw). `(0, 0)` + /// -- an unarmed writer, i.e. a unit test coding one block -- clamps + /// nothing, which is what every stream without a cut palette block codes. + static FRAME_MI_DIMS: std::cell::Cell<(usize, usize)> = + const { std::cell::Cell::new((0, 0)) }; +} + +/// Arms the next tile write with this frame's `(mi_rows, mi_cols)`. +pub(crate) fn arm_frame_mi_dims(dims: (usize, usize)) { + FRAME_MI_DIMS.with(|c| c.set(dims)); +} + +/// The armed `(mi_rows, mi_cols)`, or a grid big enough to clamp nothing. +fn frame_mi_dims() -> (usize, usize) { + match FRAME_MI_DIMS.with(std::cell::Cell::get) { + (0, 0) => (usize::MAX / 8, usize::MAX / 8), + dims => dims, + } +} + fn screen_armed() -> bool { SCREEN.with(std::cell::Cell::get) } @@ -3460,10 +3485,18 @@ fn write_color_index_map( map: &[u8], side: usize, n: usize, + // spec 5.11.50 `onscreenWidth`/`onscreenHeight` in this map's own units: + // a block cut by the frame's right/bottom mi edge codes ONLY this corner + // and the decoder replicates it outward (`decode::palette_replicate`). + // Writing the full grid spent symbols a conformant decoder never reads, + // desyncing the rest of the tile (lane-palw, class + // writer-phantom-units-past-edge). + on: (usize, usize), ) { + let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side)); write_uniform(enc, usize::from(map[0]), n); - for i in 1..(2 * side - 1) { - for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() { + for i in 1..(on_w + on_h - 1) { + for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() { let (row, col) = (i - j, j); let (ctx, color_order) = crate::decode::palette_color_index_context(map, side, row, col, n); @@ -3483,7 +3516,7 @@ fn write_color_index_map( /// search reads the rate the tile will really spend, not an estimate of it. /// The neighbour cache is taken as empty (the search runs before the tile /// knows what its neighbours will be), which only ever over-prices. -pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 { +pub(crate) fn palette_bits(pal: &PaletteY, side: usize, on: (usize, usize)) -> f64 { let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { return f64::INFINITY; }; @@ -3495,14 +3528,14 @@ pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 { enc.symbol(n - 2, &mut size_cdf); write_palette_colors_y(&mut enc, &pal.colors[..n], &[]); let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2]; - write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n); + write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n, on); enc.bits() } /// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the /// size symbol, both colour lists and the shared colour-index map, priced /// through the very writers above (empty cache, which only over-prices). -pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 { +pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize, on: (usize, usize)) -> f64 { let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { return f64::INFINITY; }; @@ -3514,7 +3547,7 @@ pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 { enc.symbol(n - 2, &mut size_cdf); write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]); let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2]; - write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n); + write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n, on); enc.bits() } @@ -3903,19 +3936,34 @@ fn write_palette_syntax( write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra); // Both colour-index maps come after BOTH colour lists, in plane order // (`av1_visit_palette` runs from the caller, past `filter_intra`). + // The on-screen extent of THIS block, from the frame mi dims armed + // for this tile write -- the decoder's `palette_onscreen` half. + let on = crate::decode::palette_onscreen_dims(mi.0, mi.1, side, side, frame_mi_dims()); + if (on.0 < side || on.1 < side) && (palette.is_some() || palette_uv.is_some()) { + PALETTE_CUT_MAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } if let Some(pal) = palette { let n = usize::from(pal.size); - write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n); + write_color_index_map( + enc, + &mut cdfs.palette_y_color_index[n - 2], + &pal.map, + side, + n, + on, + ); note_palette(n); } if let Some(pal) = palette_uv { let n = usize::from(pal.size); + let uv_side = palette_uv_side(side); write_color_index_map( enc, &mut cdfs.palette_uv_color_index[n - 2], &pal.map, - palette_uv_side(side), + uv_side, n, + crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side)), ); note_palette_uv(n); } @@ -3943,6 +3991,23 @@ pub(crate) fn palette_uv_side(side: usize) -> usize { static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] = [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; +/// lane-palw: colour-index maps written over the ON-SCREEN corner only, +/// i.e. palette blocks this writer cut at the frame's right/bottom mi edge. +/// A gate asserts it non-zero so it cannot pass on a stream that never cuts +/// one (class `gate-blind-to-feature`). +static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps). +pub fn palette_cut_maps_written() -> usize { + PALETTE_CUT_MAPS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Zeroes [`PALETTE_CUT_MAPS`] before a gate's own encode. +pub fn reset_palette_cut_maps_written() { + PALETTE_CUT_MAPS.store(0, std::sync::atomic::Ordering::Relaxed); +} + fn note_palette(n: usize) { PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);