forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-palw' (a0db417a): the palette colour-index map writer codes the on-screen corner of a block cut by the frame edge; encoder FrameCtx publishes the frame mi dims; 16/16 size sweep exact through ffmpeg

Browse files at this commit

c20003926eb63c0e515073af36c2592226b4b2dbAhmet Kaan GümüşParent: c8912d0efa6308
crates/ec-av1/src/decode.rsmodified+31 -16
@@ -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`, 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 }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) {
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+ })
2967 .collect()2977 .collect()
2968 }2978 }
2969 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)
2985+ .collect()
2986+ }
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);
lanes/palw.report.mdadded+125 -0
@@ -0,0 +1,125 @@
1+# lane-palw — the palette colour-index map WRITTEN past the frame edge
2+
3+Class: **writer-phantom-units-past-edge** (previous instance: the residual
4+transform-unit writer coding TUs past the right frame edge, lane-av1straddle).
5+The reader half was lane-svtinter's `map-read-past-frame-edge`; this is its
6+mirror on our own encoder.
7+
8+## Defect
9+
10+Spec 5.11.50 `palette_tokens` codes a block's colour-index map over its
11+`onscreenWidth x onscreenHeight` corner ONLY and replicates the last on-screen
12+column/row outward (detokenize.c:71). `tile::write_color_index_map` walked the
13+full `side x side` grid, so every palette block our encoder coded straddling
14+the frame's right/bottom mi edge carried symbols a conformant decoder never
15+reads: libaom/dav1d/ffmpeg desync from that block on. Our own trial decode
16+agreed with itself because `FrameCtx::for_encoder` never runs
17+`set_segmentation`, so `decode::palette_onscreen` read `(0, 0)` mi dims and
18+took the `corner-cut:` branch that mirrored the unclamped writer.
19+
20+## Fix (commit `16f7d271`)
21+
22+* `encode.rs` (both frame encoders, beside their `true_width`/`true_height`):
23+ publish the header's `(mi_rows, mi_cols)` onto the encoder's `FrameCtx` and
24+ arm them on every tile writer (`tile::arm_frame_mi_dims`, beside
25+ `arm_screen`).
26+* `encode.rs` palette search, luma and chroma: the searched map is folded to
27+ the on-screen corner through the decoder's own
28+ `decode::palette_replicate` before it is priced, predicted from and
29+ committed -- so the map priced, the map reconstructed and the map written
30+ are one map. The colour search itself still runs over the full block.
31+* `tile.rs`: `write_color_index_map` takes `(onscreenWidth, onscreenHeight)`
32+ and walks the wavefront over that corner at the full-block stride;
33+ `palette_bits`/`palette_uv_bits` price the same corner;
34+ `write_palette_syntax` derives it with `decode::palette_onscreen_dims` (the
35+ reader's own function) and `decode::palette_onscreen_uv` for chroma.
36+ Counter `palette_cut_maps_written()`.
37+* `decode.rs`: the `corner-cut:` mirror-the-writer branch is GONE -- both
38+ sides now clamp everywhere. `palette_onscreen_dims`/`palette_replicate` are
39+ shared by the two sides so they cannot drift.
40+
41+## Witness
42+
43+`encoder::tests::a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg`
44+(encoder.rs). Drives the ENTRY SURFACE (`Av1Encoder`, what the editor's export
45+calls) on a 384x152 8-px two-tone screen card: 152 rows = 38 mi, so the bottom
46+superblock row's 16x16 blocks at y=144 and 32x32 blocks at y=128 hang off the
47+mi grid. Asserts `tile::palette_cut_maps_written() > 0` (12 here), decodes
48+through `decode_stream` AND ffmpeg and compares EVERY plane of every frame.
49+
50+* RED (`write_color_index_map` forced back to the full grid, everything else
51+ as shipped): `our decoder: Unsupported { what: "AV1 tile", why: "a Golomb
52+ tail longer than this decoder reads" }` -- `test result: FAILED. 0 passed;
53+ 1 failed`.
54+* GREEN: `test result: ok. 1 passed`, `12 cut colour-index maps written`.
55+
56+`screen_card`'s 4-px bands were tried first and fire 9 palettes, NONE of them
57+cut (`cut 0`) -- the row would have passed blind (class gate-blind-to-feature),
58+which is what the counter assert catches.
59+
60+## Conformance sweep (our encoder -> ffmpeg, all three planes, 3 frames)
61+
62+Two screen sources, four sizes whose mi grid cuts blocks, two quantizers.
63+`cut maps` is `palette_cut_maps_written()` for that point: every row really
64+exercises the fixed path.
65+
66+Checkerboard card (8-px two-tone):
67+
68+| size | q | bytes | cut maps | ours vs ffmpeg |
69+|---|---|---|---|---|
70+| 384x152 | 60 | 286 | 12 | EXACT |
71+| 384x152 | 150 | 288 | 12 | EXACT |
72+| 320x184 | 60 | 256 | 5 | EXACT |
73+| 320x184 | 150 | 257 | 5 | EXACT |
74+| 640x366 | 60 | 706 | 10 | EXACT |
75+| 640x366 | 150 | 707 | 10 | EXACT |
76+| 1000x562 | 60 | 1499 | 24 | EXACT |
77+| 1000x562 | 150 | 1500 | 24 | EXACT |
78+
79+`smptebars=s=WxH,drawgrid=w=8:h=8:t=1:c=black` (lavfi):
80+
81+| size | q | bytes | cut maps | ours vs ffmpeg |
82+|---|---|---|---|---|
83+| 384x152 | 60 | 1398 | 2 | EXACT |
84+| 384x152 | 150 | 1397 | 6 | EXACT |
85+| 320x184 | 60 | 1488 | 1 | EXACT |
86+| 320x184 | 150 | 1406 | 2 | EXACT |
87+| 640x366 | 60 | 2708 | 2 | EXACT |
88+| 640x366 | 150 | 2596 | 0 | EXACT |
89+| 1000x562 | 60 | 3924 | 6 | EXACT |
90+| 1000x562 | 150 | 3731 | 2 | EXACT |
91+
92+Before the fix, the same recipe refuses (the RED run above is 384x152 of the
93+first table).
94+
95+## Same-shape sweep, WRITER side
96+
97+Every per-cell syntax family this writer emits, at a block cut by the mi grid:
98+
99+| family | writer site | state |
100+|---|---|---|
101+| palette colour-index map, luma + chroma | tile.rs `write_color_index_map` | **fixed here** |
102+| residual transform units, luma | tile.rs:4367 `tu_mi.0 >= neighbours.mi_rows \|\| tu_mi.1 >= neighbours.mi_cols` | clipped (lane-av1straddle) |
103+| residual transform units, chroma | tile.rs:2612 `bound_h`/`bound_w` with libaom's `ROUND_POWER_OF_TWO` round-up | clipped |
104+| var-tx split units | tile.rs:4520 -- the encoder only picks depth 1 for a block wholly inside the frame, `debug_assert`ed per unit | clipped |
105+| partition | tile.rs:184 / 2972 / 3052 `has_cols`/`has_rows` inferred split at 128, 64 and 32 | clipped |
106+| segment ids | none: this encoder writes no segmentation map (`write_segment_id` exists only in decode.rs) | n/a |
107+| CfL, intrabc | one alpha pair / one vector per block, no per-cell loop | n/a |
108+
109+## Gates
110+
111+| gate | result |
112+|---|---|
113+| witness (RED / GREEN) | Golomb-tail refusal / `ok. 1 passed`, 12 cut maps |
114+| `encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins` (default) | ok -- pins UNMOVED, the pin clip cuts no palette block |
115+| same, `EC_AV1_SPEED=6` | ok -- unmoved |
116+| `--ignored --exact encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders` | ok (presets 0/3/6/10, 32045/30867/35517/92817 bytes) |
117+| `EC_AV1_NATIVE_SCREEN=1 ... bd_rate_screen_native` | +14.6% vs libaom / -33.2% vs rav1e -- the control to the digit (the 1920x1024 crop is superblock-aligned: "0 on a superblock the frame edge cuts") |
118+| s1 `--skip stream::` | ok. 343 passed; 0 failed; 33 ignored (394 s, RC=0) |
119+| s2 `stream:: --skip 10bit` | ok. 202 passed; 0 failed; 15 ignored (602 s, RC=0) |
120+| s3 `10bit` | ok. 42 passed; 0 failed; 1 ignored (51 s, RC=0) |
121+| `cargo check --workspace --all-targets -j4` | RC=0, 0 errors, 0 ec-av1 warnings (22 pre-existing in ec-opus/ec-vorbis) |
122+
123+The sweep tables above were produced by a scratch `examples/palw_sweep.rs`
124+(encode_sequence -> decode_stream + ffmpeg over the size x q grid), deleted
125+before the lane closed; the witness row covers the same path in-suite.