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(
8834 bh: usize,8834 bh: usize,
8835 fctx: &crate::decode::FrameCtx,8835 fctx: &crate::decode::FrameCtx,
8836 ) -> (usize, usize) {8836 ) -> (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.
8837 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());8842 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 the8843+ palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
8839- // ENCODER's own in-process reconstruct (`FrameCtx::for_encoder`, where8844+}
8840- // `set_segmentation` never runs), whose writer half8845+
8841- // (`tile::write_color_index_map`) is unclamped too -- the two mirror each8846+/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
8842- // other, and clamping only one of them read every map as 1x1. Ceiling:8847+/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
8843- // our encoder still writes a full map for a palette block cut by the8848+/// compute the same on-screen extent or the decoder reads a different number
8844- // frame edge, which a conformant decoder reads short. Upgrade path: clamp8849+/// of symbols than the encoder wrote.
8845- // the writer, publish the mi dims on the encoder's ctx, drop this branch.8850+pub(crate) fn palette_onscreen_dims(
8846- if mi_rows == 0 || mi_cols == 0 {8851+ mi_r: usize,
8847- return (bw, bh);8852+ mi_c: usize,
8848- }8853+ bw: usize,
8854+ bh: usize,
8855+ (mi_rows, mi_cols): (usize, usize),
8856+) -> (usize, usize) {
8849 (8857 (
8850 bw.min(mi_cols.saturating_sub(mi_c) * MI),8858 bw.min(mi_cols.saturating_sub(mi_c) * MI),
8851 bh.min(mi_rows.saturating_sub(mi_r) * MI),8859 bh.min(mi_rows.saturating_sub(mi_r) * MI),
@@ -8856,7 +8864,7 @@ fn palette_onscreen(
8856 /// the SAME sub-8 bump the caller's own `(bw / 2).max(4)` applies to the block8864 /// the SAME sub-8 bump the caller's own `(bw / 2).max(4)` applies to the block
8857 /// dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move together8865 /// dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move together
8858 /// or a cut 8-wide block reads its chroma map at the wrong width.8866 /// 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(
8860 luma: (usize, usize),8868 luma: (usize, usize),
8861 on: (usize, usize),8869 on: (usize, usize),
8862 chroma: (usize, usize),8870 chroma: (usize, usize),
@@ -8939,10 +8947,18 @@ fn decode_color_index_map_wh(
8939 }8947 }
8940 }8948 }
8941 }8949 }
8942- // `decode_color_map_tokens`'s own two extension loops (detokenize.c:71):8950+ palette_replicate(&mut map, bw, bh, on);
8943- // the last on-screen column then the last on-screen row are replicated8951+ map
8944- // over the off-screen remainder, so the prediction still covers the whole8952+}
8945- // block.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));
8946 for row in 0..on_bh {8962 for row in 0..on_bh {
8947 let last = map[row * bw + on_bw - 1];8963 let last = map[row * bw + on_bw - 1];
8948 map[row * bw + on_bw..row * bw + bw].fill(last);8964 map[row * bw + on_bw..row * bw + bw].fill(last);
@@ -8950,7 +8966,6 @@ fn decode_color_index_map_wh(
8950 for row in on_bh..bh {8966 for row in on_bh..bh {
8951 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);8967 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
8952 }8968 }
8953- map
8954 }8969 }
8955 8970
8956 /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,8971 /// [`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(
5616 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())5616 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
5617 .collect();5617 .collect();
5618 let kept = luma.snapshot(x, y, side);5618 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) {
5620 let n = usize::from(pal.size);5630 let n = usize::from(pal.size);
5631+ crate::decode::palette_replicate(&mut pal.map, side, side, on);
5621 let prediction: Vec<u8> = pal5632 let prediction: Vec<u8> = pal
5622 .map5633 .map
5623 .iter()5634 .iter()
@@ -5637,7 +5648,7 @@ fn code_square(
5637 + search.lambda5648 + search.lambda
5638 * (trial.bits5649 * (trial.bits
5639 + mode_bits[DC_PRED as usize]5650 + mode_bits[DC_PRED as usize]
5640- + crate::tile::palette_bits(&pal, side)5651+ + crate::tile::palette_bits(&pal, side, on)
5641 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });5652 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
5642 if cost_p < cost {5653 if cost_p < cost {
5643 cost = cost_p;5654 cost = cost_p;
@@ -6056,8 +6067,19 @@ fn search_chroma(
6056 .collect()6067 .collect()
6057 };6068 };
6058 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));6069 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) {
6060 let n = usize::from(pal.size);6081 let n = usize::from(pal.size);
6082+ crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6061 // V's base colour per cluster: the mean of the samples the shared6083 // V's base colour per cluster: the mean of the samples the shared
6062 // map assigns to it (an empty cluster cannot happen -- every6084 // map assigns to it (an empty cluster cannot happen -- every
6063 // colour `palette_candidates` returns is some pixel's nearest).6085 // colour `palette_candidates` returns is some pixel's nearest).
@@ -6101,7 +6123,7 @@ fn search_chroma(
6101 + search.lambda6123 + search.lambda
6102 * (u_trial.bits6124 * (u_trial.bits
6103 + v_trial.bits6125 + v_trial.bits
6104- + crate::tile::palette_uv_bits(&candidate, side));6126+ + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6105 if cost_p < cost {6127 if cost_p < cost {
6106 cost = cost_p;6128 cost = cost_p;
6107 mode = DC_PRED;6129 mode = DC_PRED;
@@ -7881,6 +7903,14 @@ pub(crate) fn encode_key_frame_inner(
7881 // Prediction reads no further than this, in each plane's own units --7903 // Prediction reads no further than this, in each plane's own units --
7882 // see `Plane::true_width`/`true_height`.7904 // see `Plane::true_width`/`true_height`.
7883 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);7905 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);
7884 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's7914 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
7885 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by7915 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
7886 // design (see `intra_predict_u8`'s doc comment), so narrow the source7916 // design (see `intra_predict_u8`'s doc comment), so narrow the source
@@ -8351,6 +8381,7 @@ pub(crate) fn encode_key_frame_inner(
8351 crate::tile::arm_sb128(sb128_on());8381 crate::tile::arm_sb128(sb128_on());
8352 let mut cdfs = start_cdfs.0.clone();8382 let mut cdfs = start_cdfs.0.clone();
8353 crate::tile::arm_screen(screen);8383 crate::tile::arm_screen(screen);
8384+ crate::tile::arm_frame_mi_dims(frame_mi_dims);
8354 crate::tile::arm_filter_intra(filter_intra_on());8385 crate::tile::arm_filter_intra(filter_intra_on());
8355 crate::tile::arm_intrabc(allow_intrabc);8386 crate::tile::arm_intrabc(allow_intrabc);
8356 crate::tile::arm_pricing_cdfs(None, false);8387 crate::tile::arm_pricing_cdfs(None, false);
@@ -11453,6 +11484,14 @@ pub(crate) fn encode_inter_frame(
11453 }11484 }
11454 11485
11455 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);11486 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);
11456 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once11495 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
11457 // here (see `encode_key_frame_inner`).11496 // here (see `encode_key_frame_inner`).
11458 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();11497 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
@@ -12385,6 +12424,7 @@ pub(crate) fn encode_inter_frame(
12385 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);12424 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
12386 crate::tile::arm_high_precision_mv(hp_mv);12425 crate::tile::arm_high_precision_mv(hp_mv);
12387 crate::tile::arm_screen(screen);12426 crate::tile::arm_screen(screen);
12427+ crate::tile::arm_frame_mi_dims(frame_mi_dims);
12388 crate::tile::arm_filter_intra(filter_intra_on());12428 crate::tile::arm_filter_intra(filter_intra_on());
12389 let mut cdfs = start_cdfs.0.clone();12429 let mut cdfs = start_cdfs.0.clone();
12390 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);12430 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
crates/ec-av1/src/encoder.rsmodified+107 -2
@@ -2940,7 +2940,11 @@ mod tests {
2940 /// entry per coded frame, in order — this facade's own equivalent of2940 /// entry per coded frame, in order — this facade's own equivalent of
2941 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a2941 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
2942 /// PSNR check needs the decoded pixels, not just the coded byte count.2942 /// 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>)> {
2944 let path = std::env::temp_dir().join(format!(2948 let path = std::env::temp_dir().join(format!(
2945 "ec-av1-facade-rate-decode-{}-{}.obu",2949 "ec-av1-facade-rate-decode-{}-{}.obu",
2946 std::process::id(),2950 std::process::id(),
@@ -2963,10 +2967,111 @@ mod tests {
2963 let frame_len = luma + 2 * chroma;2967 let frame_len = luma + 2 * chroma;
2964 out.stdout2968 out.stdout
2965 .chunks_exact(frame_len)2969 .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)
2967 .collect()2985 .collect()
2968 }2986 }
2969 2987
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+
2970 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each3075 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
2971 /// mini-GOP is coded before the leaves that precede it in display order,3076 /// mini-GOP is coded before the leaves that precede it in display order,
2972 /// and a `show_existing_frame` header puts it back. This pins the shape3077 /// 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) {
469 SCREEN.with(|c| c.set(on));469 SCREEN.with(|c| c.set(on));
470 }470 }
471 471
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+
472 fn screen_armed() -> bool {497 fn screen_armed() -> bool {
473 SCREEN.with(std::cell::Cell::get)498 SCREEN.with(std::cell::Cell::get)
474 }499 }
@@ -3460,10 +3485,18 @@ fn write_color_index_map(
3460 map: &[u8],3485 map: &[u8],
3461 side: usize,3486 side: usize,
3462 n: usize,3487 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),
3463 ) {3495 ) {
3496+ let (on_w, on_h) = (on.0.clamp(1, side), on.1.clamp(1, side));
3464 write_uniform(enc, usize::from(map[0]), n);3497 write_uniform(enc, usize::from(map[0]), n);
3465- for i in 1..(2 * side - 1) {3498+ for i in 1..(on_w + on_h - 1) {
3466- for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() {3499+ for j in (i.saturating_sub(on_h - 1)..=i.min(on_w - 1)).rev() {
3467 let (row, col) = (i - j, j);3500 let (row, col) = (i - j, j);
3468 let (ctx, color_order) =3501 let (ctx, color_order) =
3469 crate::decode::palette_color_index_context(map, side, row, col, n);3502 crate::decode::palette_color_index_context(map, side, row, col, n);
@@ -3483,7 +3516,7 @@ fn write_color_index_map(
3483 /// search reads the rate the tile will really spend, not an estimate of it.3516 /// search reads the rate the tile will really spend, not an estimate of it.
3484 /// The neighbour cache is taken as empty (the search runs before the tile3517 /// The neighbour cache is taken as empty (the search runs before the tile
3485 /// knows what its neighbours will be), which only ever over-prices.3518 /// 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 {
3487 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {3520 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
3488 return f64::INFINITY;3521 return f64::INFINITY;
3489 };3522 };
@@ -3495,14 +3528,14 @@ pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
3495 enc.symbol(n - 2, &mut size_cdf);3528 enc.symbol(n - 2, &mut size_cdf);
3496 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);3529 write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
3497 let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];3530 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);
3499 enc.bits()3532 enc.bits()
3500 }3533 }
3501 3534
3502 /// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the3535 /// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
3503 /// size symbol, both colour lists and the shared colour-index map, priced3536 /// size symbol, both colour lists and the shared colour-index map, priced
3504 /// through the very writers above (empty cache, which only over-prices).3537 /// 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 {
3506 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {3539 let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
3507 return f64::INFINITY;3540 return f64::INFINITY;
3508 };3541 };
@@ -3514,7 +3547,7 @@ pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
3514 enc.symbol(n - 2, &mut size_cdf);3547 enc.symbol(n - 2, &mut size_cdf);
3515 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);3548 write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
3516 let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];3549 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);
3518 enc.bits()3551 enc.bits()
3519 }3552 }
3520 3553
@@ -3903,19 +3936,34 @@ fn write_palette_syntax(
3903 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);3936 write_filter_intra(enc, cdfs, mode, side, palette.is_some(), filter_intra);
3904 // Both colour-index maps come after BOTH colour lists, in plane order3937 // Both colour-index maps come after BOTH colour lists, in plane order
3905 // (`av1_visit_palette` runs from the caller, past `filter_intra`).3938 // (`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+ }
3906 if let Some(pal) = palette {3945 if let Some(pal) = palette {
3907 let n = usize::from(pal.size);3946 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+ );
3909 note_palette(n);3955 note_palette(n);
3910 }3956 }
3911 if let Some(pal) = palette_uv {3957 if let Some(pal) = palette_uv {
3912 let n = usize::from(pal.size);3958 let n = usize::from(pal.size);
3959+ let uv_side = palette_uv_side(side);
3913 write_color_index_map(3960 write_color_index_map(
3914 enc,3961 enc,
3915 &mut cdfs.palette_uv_color_index[n - 2],3962 &mut cdfs.palette_uv_color_index[n - 2],
3916 &pal.map,3963 &pal.map,
3917- palette_uv_side(side),3964+ uv_side,
3918 n,3965 n,
3966+ crate::decode::palette_onscreen_uv((side, side), on, (uv_side, uv_side)),
3919 );3967 );
3920 note_palette_uv(n);3968 note_palette_uv(n);
3921 }3969 }
@@ -3943,6 +3991,23 @@ pub(crate) fn palette_uv_side(side: usize) -> usize {
3943 static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =3991 static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
3944 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];3992 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
3945 3993
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+
3946 fn note_palette(n: usize) {4011 fn note_palette(n: usize) {
3947 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);4012 PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3948 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);4013 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);