forge
Explore
Log in

Don't you dare go Hollow

Write a cut palette block's colour-index map over its on-screen part only

Browse files at this commit

254b9086d6ed682fc73fc898574d3b5622b13a1aAhmet Kaan GümüşParent: c8912d0
  • fix
    • write a cut palette block's colour-index map over its on-screen part only
Show full message
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.rsmodified+32 -17
@@ -8834,18 +8834,26 @@ fn palette_onscreen(
88348834 bh: usize,
88358835 fctx: &crate::decode::FrameCtx,
88368836 ) -> (usize, usize) {
8837+ // lane-palw: the ENCODER's own in-process reconstruct runs on a
8838+ // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
8839+ // frame encoders publish the header's mi dims onto it themselves
8840+ // (`encode.rs`, beside their `true_width`/`true_height`) so that this
8841+ // clamp and `tile::write_color_index_map`'s now agree there too.
88378842 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
8838- // corner-cut: no mi dims means this is not a real frame decode but the
8839- // ENCODER's own in-process reconstruct (`FrameCtx::for_encoder`, where
8840- // `set_segmentation` never runs), whose writer half
8841- // (`tile::write_color_index_map`) is unclamped too -- the two mirror each
8842- // other, and clamping only one of them read every map as 1x1. Ceiling:
8843- // our encoder still writes a full map for a palette block cut by the
8844- // frame edge, which a conformant decoder reads short. Upgrade path: clamp
8845- // the writer, publish the mi dims on the encoder's ctx, drop this branch.
8846- if mi_rows == 0 || mi_cols == 0 {
8847- return (bw, bh);
8848- }
8843+ palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
8844+}
8845+
8846+/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
8847+/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
8848+/// compute the same on-screen extent or the decoder reads a different number
8849+/// of symbols than the encoder wrote.
8850+pub(crate) fn palette_onscreen_dims(
8851+ mi_r: usize,
8852+ mi_c: usize,
8853+ bw: usize,
8854+ bh: usize,
8855+ (mi_rows, mi_cols): (usize, usize),
8856+) -> (usize, usize) {
88498857 (
88508858 bw.min(mi_cols.saturating_sub(mi_c) * MI),
88518859 bh.min(mi_rows.saturating_sub(mi_r) * MI),
@@ -8856,7 +8864,7 @@ fn palette_onscreen(
88568864 /// the SAME sub-8 bump the caller's own `(bw / 2).max(4)` applies to the block
88578865 /// dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move together
88588866 /// or a cut 8-wide block reads its chroma map at the wrong width.
8859-fn palette_onscreen_uv(
8867+pub(crate) fn palette_onscreen_uv(
88608868 luma: (usize, usize),
88618869 on: (usize, usize),
88628870 chroma: (usize, usize),
@@ -8939,10 +8947,18 @@ fn decode_color_index_map_wh(
89398947 }
89408948 }
89418949 }
8942- // `decode_color_map_tokens`'s own two extension loops (detokenize.c:71):
8943- // the last on-screen column then the last on-screen row are replicated
8944- // over the off-screen remainder, so the prediction still covers the whole
8945- // block.
8950+ palette_replicate(&mut map, bw, bh, on);
8951+ map
8952+}
8953+
8954+/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
8955+/// last on-screen column then the last on-screen row are replicated over the
8956+/// off-screen remainder, so the prediction still covers the whole block. The
8957+/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
8958+/// so the pixels it prices and reconstructs are the ones the on-screen
8959+/// symbols it writes really decode to.
8960+pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
8961+ let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
89468962 for row in 0..on_bh {
89478963 let last = map[row * bw + on_bw - 1];
89488964 map[row * bw + on_bw..row * bw + bw].fill(last);
@@ -8950,7 +8966,6 @@ fn decode_color_index_map_wh(
89508966 for row in on_bh..bh {
89518967 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
89528968 }
8953- map
89548969 }
89558970
89568971 /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
crates/ec-av1/src/encode.rsmodified+44 -4
@@ -5616,8 +5616,19 @@ fn code_square(
56165616 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
56175617 .collect();
56185618 let kept = luma.snapshot(x, y, side);
5619- for pal in palette_candidates(&source) {
5619+ // spec 5.11.50: a block cut by the frame's right/bottom edge codes
5620+ // its map over the ON-SCREEN corner only and the decoder replicates
5621+ // that outward, so the searched map is folded the same way here --
5622+ // the prediction priced, the reconstruction committed and the symbols
5623+ // `write_color_index_map` writes are then one and the same map
5624+ // (lane-palw).
5625+ let on = (
5626+ side.min(luma.true_width.saturating_sub(x)),
5627+ side.min(luma.true_height.saturating_sub(y)),
5628+ );
5629+ for mut pal in palette_candidates(&source) {
56205630 let n = usize::from(pal.size);
5631+ crate::decode::palette_replicate(&mut pal.map, side, side, on);
56215632 let prediction: Vec<u8> = pal
56225633 .map
56235634 .iter()
@@ -5637,7 +5648,7 @@ fn code_square(
56375648 + search.lambda
56385649 * (trial.bits
56395650 + mode_bits[DC_PRED as usize]
5640- + crate::tile::palette_bits(&pal, side)
5651+ + crate::tile::palette_bits(&pal, side, on)
56415652 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
56425653 if cost_p < cost {
56435654 cost = cost_p;
@@ -6056,8 +6067,19 @@ fn search_chroma(
60566067 .collect()
60576068 };
60586069 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6059- for pal in palette_candidates(&u_source) {
6070+ // The luma on-screen extent carried into this plane exactly as the
6071+ // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6072+ let on_uv = crate::decode::palette_onscreen_uv(
6073+ (side, side),
6074+ (
6075+ side.min(luma.true_width.saturating_sub(x)),
6076+ side.min(luma.true_height.saturating_sub(y)),
6077+ ),
6078+ (at.side, at.side),
6079+ );
6080+ for mut pal in palette_candidates(&u_source) {
60606081 let n = usize::from(pal.size);
6082+ crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
60616083 // V's base colour per cluster: the mean of the samples the shared
60626084 // map assigns to it (an empty cluster cannot happen -- every
60636085 // colour `palette_candidates` returns is some pixel's nearest).
@@ -6101,7 +6123,7 @@ fn search_chroma(
61016123 + search.lambda
61026124 * (u_trial.bits
61036125 + v_trial.bits
6104- + crate::tile::palette_uv_bits(&candidate, side));
6126+ + crate::tile::palette_uv_bits(&candidate, side, on_uv));
61056127 if cost_p < cost {
61066128 cost = cost_p;
61076129 mode = DC_PRED;
@@ -7881,6 +7903,14 @@ pub(crate) fn encode_key_frame_inner(
78817903 // Prediction reads no further than this, in each plane's own units --
78827904 // see `Plane::true_width`/`true_height`.
78837905 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
7906+ // lane-palw: the encoder's own in-process reconstruct reads its palette
7907+ // colour-index maps back through `decode::palette_onscreen`, which takes
7908+ // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
7909+ // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
7910+ // them here so the reconstruct clamps a block cut by the frame edge
7911+ // exactly as the writer now does.
7912+ let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
7913+ fctx.seg_mi_dims.set(frame_mi_dims);
78847914 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
78857915 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
78867916 // design (see `intra_predict_u8`'s doc comment), so narrow the source
@@ -8351,6 +8381,7 @@ pub(crate) fn encode_key_frame_inner(
83518381 crate::tile::arm_sb128(sb128_on());
83528382 let mut cdfs = start_cdfs.0.clone();
83538383 crate::tile::arm_screen(screen);
8384+ crate::tile::arm_frame_mi_dims(frame_mi_dims);
83548385 crate::tile::arm_filter_intra(filter_intra_on());
83558386 crate::tile::arm_intrabc(allow_intrabc);
83568387 crate::tile::arm_pricing_cdfs(None, false);
@@ -11453,6 +11484,14 @@ pub(crate) fn encode_inter_frame(
1145311484 }
1145411485
1145511486 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
11487+ // lane-palw: the encoder's own in-process reconstruct reads its palette
11488+ // colour-index maps back through `decode::palette_onscreen`, which takes
11489+ // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
11490+ // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
11491+ // them here so the reconstruct clamps a block cut by the frame edge
11492+ // exactly as the writer now does.
11493+ let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
11494+ fctx.seg_mi_dims.set(frame_mi_dims);
1145611495 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
1145711496 // here (see `encode_key_frame_inner`).
1145811497 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
@@ -12385,6 +12424,7 @@ pub(crate) fn encode_inter_frame(
1238512424 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
1238612425 crate::tile::arm_high_precision_mv(hp_mv);
1238712426 crate::tile::arm_screen(screen);
12427+ crate::tile::arm_frame_mi_dims(frame_mi_dims);
1238812428 crate::tile::arm_filter_intra(filter_intra_on());
1238912429 let mut cdfs = start_cdfs.0.clone();
1239012430 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
crates/ec-av1/src/encoder.rsmodified+107 -2
@@ -2940,7 +2940,11 @@ mod tests {
29402940 /// entry per coded frame, in order — this facade's own equivalent of
29412941 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
29422942 /// PSNR check needs the decoded pixels, not just the coded byte count.
2943- fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
2943+ fn ffmpeg_decode_planes(
2944+ stream: &[u8],
2945+ width: usize,
2946+ height: usize,
2947+ ) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
29442948 let path = std::env::temp_dir().join(format!(
29452949 "ec-av1-facade-rate-decode-{}-{}.obu",
29462950 std::process::id(),
@@ -2963,10 +2967,111 @@ mod tests {
29632967 let frame_len = luma + 2 * chroma;
29642968 out.stdout
29652969 .chunks_exact(frame_len)
2966- .map(|f| f[..luma].to_vec())
2970+ .map(|f| {
2971+ (
2972+ f[..luma].to_vec(),
2973+ f[luma..luma + chroma].to_vec(),
2974+ f[luma + chroma..].to_vec(),
2975+ )
2976+ })
2977+ .collect()
2978+ }
2979+
2980+ /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare.
2981+ fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
2982+ ffmpeg_decode_planes(stream, width, height)
2983+ .into_iter()
2984+ .map(|(y, _, _)| y)
29672985 .collect()
29682986 }
29692987
2988+ /// lane-palw: OUR encoder's own witness for the writer half of the
2989+ /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall,
2990+ /// so the bottom superblock row's palette blocks hang 8 luma rows off the
2991+ /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN
2992+ /// corner only and replicates it outward, and the writer used to code the
2993+ /// full block grid -- symbols a conformant decoder never reads, so
2994+ /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode
2995+ /// (unclamped on both sides) agreed with itself. Class
2996+ /// `writer-phantom-units-past-edge`.
2997+ ///
2998+ /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's
2999+ /// export calls), and compared on EVERY plane -- a chroma palette map is
3000+ /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero
3001+ /// so the row cannot pass on a stream that cuts no palette map (class
3002+ /// gate-blind-to-feature).
3003+ #[test]
3004+ fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {
3005+ const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";
3006+ let _knobs = crate::speed::knob_read();
3007+ let _gate_lock = crate::stream::tests::lock_gate_counters();
3008+ let (width, height) = (384usize, 152usize);
3009+ // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at
3010+ // most two luma values, so the palette arm wins across the WHOLE
3011+ // frame -- including the bottom superblock row, whose 16x16 blocks at
3012+ // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid.
3013+ // `screen_card`'s 4-px bands fire only 9 palettes here and none of
3014+ // them at the cut edge (class gate-blind-to-feature).
3015+ let card = |shift: usize| -> Picture {
3016+ let mut picture = Picture::grey(width, height);
3017+ for y in 0..height {
3018+ for x in 0..width {
3019+ let cell = ((x + shift) / 8 + y / 8) % 2;
3020+ picture.y[y * width + x] = if cell == 0 { 40 } else { 200 };
3021+ }
3022+ }
3023+ picture
3024+ };
3025+ let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect();
3026+ let config = EncoderConfig {
3027+ width,
3028+ height,
3029+ base_q_idx: 60,
3030+ gop: 2,
3031+ colour: Colour::Bt709Limited,
3032+ tile_cols_log2: 0,
3033+ tile_rows_log2: 0,
3034+ };
3035+ let mut enc = Av1Encoder::new(config).unwrap();
3036+ crate::tile::reset_palette_cut_maps_written();
3037+ let mut stream = Vec::new();
3038+ for packet in encode_all(&mut enc, &sources) {
3039+ stream.extend_from_slice(&packet.data);
3040+ }
3041+ eprintln!("{NAME}: {} cut colour-index maps written", crate::tile::palette_cut_maps_written());
3042+ assert!(
3043+ crate::tile::palette_cut_maps_written() > 0,
3044+ "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
3045+ );
3046+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3047+ assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
3048+ if !have_ffmpeg() {
3049+ eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg");
3050+ return;
3051+ }
3052+ let theirs = ffmpeg_decode_planes(&stream, width, height);
3053+ assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
3054+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3055+ for (plane, got, want) in [
3056+ ("luma", &a.y, &b.0),
3057+ ("U", &a.u, &b.1),
3058+ ("V", &a.v, &b.2),
3059+ ] {
3060+ let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
3061+ if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
3062+ let w = if plane == "luma" { width } else { width / 2 };
3063+ panic!(
3064+ "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}",
3065+ at % w,
3066+ at / w,
3067+ got[at],
3068+ want[at],
3069+ );
3070+ }
3071+ }
3072+ }
3073+ }
3074+
29703075 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
29713076 /// mini-GOP is coded before the leaves that precede it in display order,
29723077 /// and a `show_existing_frame` header puts it back. This pins the shape
crates/ec-av1/src/tile.rsmodified+73 -8
@@ -469,6 +469,31 @@ pub(crate) fn arm_screen(on: bool) {
469469 SCREEN.with(|c| c.set(on));
470470 }
471471
472+thread_local! {
473+ /// This frame's `(mi_rows, mi_cols)` (spec `compute_image_size`), armed
474+ /// beside [`SCREEN`] by both frame encoders: a palette block cut by the
475+ /// frame's right/bottom mi edge codes its colour-index map over the
476+ /// ON-SCREEN part only, so the writer needs the same dims the decoder's
477+ /// `palette_onscreen` reads off its `FrameCtx` (lane-palw). `(0, 0)`
478+ /// -- an unarmed writer, i.e. a unit test coding one block -- clamps
479+ /// nothing, which is what every stream without a cut palette block codes.
480+ static FRAME_MI_DIMS: std::cell::Cell<(usize, usize)> =
481+ const { std::cell::Cell::new((0, 0)) };
482+}
483+
484+/// Arms the next tile write with this frame's `(mi_rows, mi_cols)`.
485+pub(crate) fn arm_frame_mi_dims(dims: (usize, usize)) {
486+ FRAME_MI_DIMS.with(|c| c.set(dims));
487+}
488+
489+/// The armed `(mi_rows, mi_cols)`, or a grid big enough to clamp nothing.
490+fn frame_mi_dims() -> (usize, usize) {
491+ match FRAME_MI_DIMS.with(std::cell::Cell::get) {
492+ (0, 0) => (usize::MAX / 8, usize::MAX / 8),
493+ dims => dims,
494+ }
495+}
496+
472497 fn screen_armed() -> bool {
473498 SCREEN.with(std::cell::Cell::get)
474499 }
@@ -3460,10 +3485,18 @@ fn write_color_index_map(
34603485 map: &[u8],
34613486 side: usize,
34623487 n: usize,
3488+ // spec 5.11.50 `onscreenWidth`/`onscreenHeight` in this map's own units:
3489+ // a block cut by the frame's right/bottom mi edge codes ONLY this corner
3490+ // and the decoder replicates it outward (`decode::palette_replicate`).
3491+ // Writing the full grid spent symbols a conformant decoder never reads,
3492+ // desyncing the rest of the tile (lane-palw, class
3493+ // writer-phantom-units-past-edge).
3494+ on: (usize, usize),
34633495 ) {
3496+ let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side));
34643497 write_uniform(enc, usize::from(map[0]), n);
3465- for i in 1..(2 * side - 1) {
3466- for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() {
3498+ for i in 1..(on_w + on_h - 1) {
3499+ for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() {
34673500 let (row, col) = (i - j, j);
34683501 let (ctx, color_order) =
34693502 crate::decode::palette_color_index_context(map, side, row, col, n);
@@ -3483,7 +3516,7 @@ fn write_color_index_map(
34833516 /// search reads the rate the tile will really spend, not an estimate of it.
34843517 /// The neighbour cache is taken as empty (the search runs before the tile
34853518 /// knows what its neighbours will be), which only ever over-prices.
3486-pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
3519+pub(crate) fn palette_bits(pal: &PaletteY, side: usize, on: (usize, usize)) -> f64 {
34873520 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
34883521 return f64::INFINITY;
34893522 };
@@ -3495,14 +3528,14 @@ pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
34953528 enc.symbol(n - 2, &mut size_cdf);
34963529 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
34973530 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
3498- write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n);
3531+ write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n, on);
34993532 enc.bits()
35003533 }
35013534
35023535 /// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
35033536 /// size symbol, both colour lists and the shared colour-index map, priced
35043537 /// through the very writers above (empty cache, which only over-prices).
3505-pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
3538+pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize, on: (usize, usize)) -> f64 {
35063539 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
35073540 return f64::INFINITY;
35083541 };
@@ -3514,7 +3547,7 @@ pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
35143547 enc.symbol(n - 2, &mut size_cdf);
35153548 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
35163549 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
3517- write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n);
3550+ write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n, on);
35183551 enc.bits()
35193552 }
35203553
@@ -3903,19 +3936,34 @@ fn write_palette_syntax(
39033936 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);
39043937 // Both colour-index maps come after BOTH colour lists, in plane order
39053938 // (`av1_visit_palette` runs from the caller, past `filter_intra`).
3939+ // The on-screen extent of THIS block, from the frame mi dims armed
3940+ // for this tile write -- the decoder's `palette_onscreen` half.
3941+ let on = crate::decode::palette_onscreen_dims(mi.0, mi.1, side, side, frame_mi_dims());
3942+ if (on.0 < side || on.1 < side) && (palette.is_some() || palette_uv.is_some()) {
3943+ PALETTE_CUT_MAPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3944+ }
39063945 if let Some(pal) = palette {
39073946 let n = usize::from(pal.size);
3908- write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
3947+ write_color_index_map(
3948+ enc,
3949+ &mut cdfs.palette_y_color_index[n - 2],
3950+ &pal.map,
3951+ side,
3952+ n,
3953+ on,
3954+ );
39093955 note_palette(n);
39103956 }
39113957 if let Some(pal) = palette_uv {
39123958 let n = usize::from(pal.size);
3959+ let uv_side = palette_uv_side(side);
39133960 write_color_index_map(
39143961 enc,
39153962 &mut cdfs.palette_uv_color_index[n - 2],
39163963 &pal.map,
3917- palette_uv_side(side),
3964+ uv_side,
39183965 n,
3966+ crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side)),
39193967 );
39203968 note_palette_uv(n);
39213969 }
@@ -3943,6 +3991,23 @@ pub(crate) fn palette_uv_side(side: usize) -> usize {
39433991 static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
39443992 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
39453993
3994+/// lane-palw: colour-index maps written over the ON-SCREEN corner only,
3995+/// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
3996+/// A gate asserts it non-zero so it cannot pass on a stream that never cuts
3997+/// one (class `gate-blind-to-feature`).
3998+static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize =
3999+ std::sync::atomic::AtomicUsize::new(0);
4000+
4001+/// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
4002+pub fn palette_cut_maps_written() -> usize {
4003+ PALETTE_CUT_MAPS.load(std::sync::atomic::Ordering::Relaxed)
4004+}
4005+
4006+/// Zeroes [`PALETTE_CUT_MAPS`] before a gate's own encode.
4007+pub fn reset_palette_cut_maps_written() {
4008+ PALETTE_CUT_MAPS.store(0, std::sync::atomic::Ordering::Relaxed);
4009+}
4010+
39464011 fn note_palette(n: usize) {
39474012 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
39484013 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);