forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-palette2': palette Y/UV incl. rect strips and split transforms; above-right/below-left reach decided per transform unit (D203 wedge under VERT_A)

Browse files at this commit

5b07c138f49aabc00ee0553ba4127b0ae8786ad4Ahmet Kaan GümüşParent: 776f14bf567222
Conflicts: kept lane-palette2's rect-capable Reach::of_tu(bw,bh,col_off,row_off,tx,block)
and deleted lane-ab16's square-only one, retargeting ab16's two call sites and porting
its vert-AB test to the surviving signature; decode_leaf_rect8's per-TU reach moved off
Reach::of(4,..) onto of_tu (same class); main's decode_block_rect4 wired to the new
read_intra_mode_rect signature and refuses a 1:4 strip that actually uses a palette.

17 changed files +1949 -182

crates/ec-av1/src/decode.rsmodified+565 -131
@@ -1118,9 +1118,30 @@ pub(crate) fn palette_rect_hits() -> usize {
1118 PALETTE_RECT_HITS.with(|c| c.get())1118 PALETTE_RECT_HITS.with(|c| c.get())
1119 }1119 }
1120 1120
1121-// lane-palette2 r1: how many palette-Y blocks decoded with a split luma1121+// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1122-// transform (`tx_select && logical_tx != side`) -- proves the per-TU index-map1122+// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1123-// slicing actually ran, not just that the whole-block path stayed exact.1123+// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1124+// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1125+// RD, almost always refused-on-use because the block doesn't end up USING a
1126+// palette -- see r5's report). This is the site the removed refusal
1127+// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1128+// fired here whether or not the block picked a palette, so this is the
1129+// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1130+// never observes.
1131+thread_local! {
1132+ static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1133+}
1134+
1135+/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1136+pub(crate) fn rect_screen_content_hits() -> usize {
1137+ RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1138+}
1139+
1140+// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1141+// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1142+// windowing actually ran, not just that the whole-block path stayed exact.
1143+// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1144+// first actually incremented in r7, when the refusal it guarded was lifted.
1124 thread_local! {1145 thread_local! {
1125 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };1146 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1126 }1147 }
@@ -1143,6 +1164,38 @@ thread_local! {
1143 const { std::cell::RefCell::new(None) };1164 const { std::cell::RefCell::new(None) };
1144 }1165 }
1145 1166
1167+
1168+/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1169+/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1170+/// site whose reconstruct never runs would be picked up by the NEXT block's
1171+/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1172+/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1173+#[track_caller]
1174+fn set_palette_pred(buf: Vec<u16>) {
1175+ if std::env::var_os("EC_DEBUG_PAL").is_some() {
1176+ let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1177+ eprintln!(
1178+ "PALSET len={} stale={stale} at {}",
1179+ buf.len(),
1180+ std::panic::Location::caller()
1181+ );
1182+ }
1183+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1184+}
1185+
1186+#[track_caller]
1187+fn take_palette_pred() -> Option<Vec<u16>> {
1188+ let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1189+ if std::env::var_os("EC_DEBUG_PAL").is_some() {
1190+ eprintln!(
1191+ "PALTAKE len={:?} at {}",
1192+ got.as_ref().map(Vec::len),
1193+ std::panic::Location::caller()
1194+ );
1195+ }
1196+ got
1197+}
1198+
1146 thread_local! {1199 thread_local! {
1147 /// The current frame's `mi` grid, kept only while a frame header set1200 /// The current frame's `mi` grid, kept only while a frame header set
1148 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary1201 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
@@ -3302,12 +3355,36 @@ impl Neighbours {
3302 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's3355 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
3303 /// call sites are all square blocks).3356 /// call sites are all square blocks).
3304 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {3357 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3358+ self.record_palette_y_rect(at, side, side, size, colors);
3359+ }
3360+
3361+ /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
3362+ /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
3363+ /// [`Self::record`]): a true rect strip's above/left neighbour spans
3364+ /// differ.
3365+ fn record_palette_y_rect(
3366+ &mut self,
3367+ at: (usize, usize),
3368+ w: usize,
3369+ h: usize,
3370+ size: usize,
3371+ colors: [u16; 8],
3372+ ) {
3305 let (r, c) = at;3373 let (r, c) = at;
3306- for cell in 0..side / SUB {3374+ // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain
3375+ // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the
3376+ // next block read a long-dead palette out of the above/left arrays
3377+ // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps
3378+ // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a
3379+ // sub-16 leaf stamps its whole containing cell -- safe today because
3380+ // every sub-16 leaf path refuses palette outright (so it can only
3381+ // ever stamp `size == 0`, and its cell holds no palette sibling).
3382+ // Upgrade path: widen the palette arrays to mi granularity.
3383+ for cell in 0..(w / SUB).max(1) {
3307 self.above_palette_size[c + cell] = size;3384 self.above_palette_size[c + cell] = size;
3308 self.above_palette_colors[c + cell] = colors;3385 self.above_palette_colors[c + cell] = colors;
3309 }3386 }
3310- for cell in 0..side / SUB {3387+ for cell in 0..(h / SUB).max(1) {
3311 self.left_palette_size[r + cell] = size;3388 self.left_palette_size[r + cell] = size;
3312 self.left_palette_colors[r + cell] = colors;3389 self.left_palette_colors[r + cell] = colors;
3313 }3390 }
@@ -3316,12 +3393,22 @@ impl Neighbours {
3316 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left3393 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
3317 /// neighbours that are themselves a palette-Y block, plus3394 /// neighbours that are themselves a palette-Y block, plus
3318 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour3395 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
3319- /// cache (pred_common.c:73) -- the above neighbour is excluded at a3396+ /// cache (pred_common.c:73).
3320- /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells3397+ ///
3321- /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.3398+ /// The SB-top-row exclusion of the above neighbour (`row % 64` in
3399+ /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
3400+ /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
3401+ /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
3402+ /// the ctx too made every superblock in the frame's second SB row read
3403+ /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
3404+ /// palette block decoded as "no palette" and the tile desynced from
3405+ /// there (class [[cdf-row-held-constant]]).
3322 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {3406 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
3323 let (r, c) = at;3407 let (r, c) = at;
3324 let above_ok = r % 4 != 0;3408 let above_ok = r % 4 != 0;
3409+ // `xd->above_mbmi` exists for every row but the tile's own first.
3410+ let above_is_palette =
3411+ r * (SUB / MI) > self.tile_row0_mi && self.above_palette_size[c] > 0;
3325 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {3412 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
3326 (self.above_palette_size[c], self.above_palette_colors[c])3413 (self.above_palette_size[c], self.above_palette_colors[c])
3327 } else {3414 } else {
@@ -3338,7 +3425,7 @@ impl Neighbours {
3338 } else {3425 } else {
3339 (0, [0u16; 8])3426 (0, [0u16; 8])
3340 };3427 };
3341- let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);3428+ let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
3342 let mut cache = Vec::with_capacity(16);3429 let mut cache = Vec::with_capacity(16);
3343 let push_dedup = |cache: &mut Vec<u16>, v: u16| {3430 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
3344 if cache.last() != Some(&v) {3431 if cache.last() != Some(&v) {
@@ -3374,12 +3461,28 @@ impl Neighbours {
3374 /// (U-channel) palette size/colours -- `size == 0` clears stale state the3461 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
3375 /// same way (lane-palette2 r1).3462 /// same way (lane-palette2 r1).
3376 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {3463 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
3464+ self.record_palette_uv_rect(at, side, side, size, colors);
3465+ }
3466+
3467+ /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
3468+ /// extents, in LUMA pixels (lane-palette2 r4, same convention as
3469+ /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
3470+ /// luma resolution regardless of which plane the recorded state is for).
3471+ fn record_palette_uv_rect(
3472+ &mut self,
3473+ at: (usize, usize),
3474+ w: usize,
3475+ h: usize,
3476+ size: usize,
3477+ colors: [u16; 8],
3478+ ) {
3377 let (r, c) = at;3479 let (r, c) = at;
3378- for cell in 0..side / SUB {3480+ // See [`Self::record_palette_y_rect`] for the `.max(1)`.
3481+ for cell in 0..(w / SUB).max(1) {
3379 self.above_palette_uv_size[c + cell] = size;3482 self.above_palette_uv_size[c + cell] = size;
3380 self.above_palette_uv_colors[c + cell] = colors;3483 self.above_palette_uv_colors[c + cell] = colors;
3381 }3484 }
3382- for cell in 0..side / SUB {3485+ for cell in 0..(h / SUB).max(1) {
3383 self.left_palette_uv_size[r + cell] = size;3486 self.left_palette_uv_size[r + cell] = size;
3384 self.left_palette_uv_colors[r + cell] = colors;3487 self.left_palette_uv_colors[r + cell] = colors;
3385 }3488 }
@@ -4212,17 +4315,20 @@ fn palette_bsize_ctx(side: usize) -> Option<usize> {
4212 }4315 }
4213 4316
4214 /// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip4317 /// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
4215-/// (lane-palette2 r1) -- the same `log2(bw*bh) - 6` formula, this decoder's4318+/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
4216-/// square call sites are just `bw == bh`.4319+/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
4320+/// for ANY bsize, not just the square ones a hand-picked table happened to
4321+/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
4322+/// row breaks the moment its indexing field moves off the diagonal, and a
4323+/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
4324+/// block dimension is a power of two, so `bw*bh` always is too and
4325+/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
4326+/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
4217 fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {4327 fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
4218- match (bw, bh) {4328+ if !(8..=64).contains(&bw) || !(8..=64).contains(&bh) {
4219- (8, 8) => Some(0),4329+ return None;
4220- (16, 16) => Some(2),
4221- (32, 16) | (16, 32) => Some(3),
4222- (32, 32) => Some(4),
4223- (64, 64) => Some(6),
4224- _ => None,
4225 }4330 }
4331+ Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
4226 }4332 }
4227 4333
4228 /// A just-decoded palette-Y block's own size, base colours (only the first4334 /// A just-decoded palette-Y block's own size, base colours (only the first
@@ -4472,9 +4578,25 @@ fn decode_color_index_map(
4472 n: usize,4578 n: usize,
4473 side: usize,4579 side: usize,
4474 uv: bool,4580 uv: bool,
4581+) -> Vec<u8> {
4582+ decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
4583+}
4584+
4585+/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
4586+/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
4587+/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
4588+/// independently rather than one shared `side` -- the square call above is
4589+/// just `bw == bh`.
4590+fn decode_color_index_map_wh(
4591+ dec: &mut SymbolDecoder,
4592+ cdfs: &mut Cdfs,
4593+ n: usize,
4594+ bw: usize,
4595+ bh: usize,
4596+ uv: bool,
4475 ) -> Vec<u8> {4597 ) -> Vec<u8> {
4476 let trace = std::env::var_os("EC_AV1_TRACE").is_some();4598 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
4477- let mut map = vec![0u8; side * side];4599+ let mut map = vec![0u8; bw * bh];
4478 if trace {4600 if trace {
4479 let (rng, _) = dec.debug_state();4601 let (rng, _) = dec.debug_state();
4480 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");4602 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
@@ -4484,13 +4606,13 @@ fn decode_color_index_map(
4484 let (rng, _) = dec.debug_state();4606 let (rng, _) = dec.debug_state();
4485 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);4607 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
4486 }4608 }
4487- for i in 1..(2 * side - 1) {4609+ for i in 1..(bw + bh - 1) {
4488- let j_hi = i.min(side - 1);4610+ let j_hi = i.min(bw - 1);
4489- let j_lo = i.saturating_sub(side - 1);4611+ let j_lo = i.saturating_sub(bh - 1);
4490 for j in (j_lo..=j_hi).rev() {4612 for j in (j_lo..=j_hi).rev() {
4491 let row = i - j;4613 let row = i - j;
4492 let col = j;4614 let col = j;
4493- let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);4615+ let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
4494 if trace {4616 if trace {
4495 let (rng, _) = dec.debug_state();4617 let (rng, _) = dec.debug_state();
4496 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");4618 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
@@ -4500,7 +4622,7 @@ fn decode_color_index_map(
4500 } else {4622 } else {
4501 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])4623 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
4502 };4624 };
4503- map[row * side + col] = color_order[symbol];4625+ map[row * bw + col] = color_order[symbol];
4504 if trace {4626 if trace {
4505 let (rng, _) = dec.debug_state();4627 let (rng, _) = dec.debug_state();
4506 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");4628 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
@@ -4510,12 +4632,14 @@ fn decode_color_index_map(
4510 map4632 map
4511 }4633 }
4512 4634
4513-/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):4635+/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
4514-/// identical except the `use_filter_intra` size class comes from4636+/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
4515-/// [`filter_intra_size_class_rect`] instead of the square-only4637+/// size class comes from [`filter_intra_size_class_rect`] instead of the
4516-/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,4638+/// square-only [`filter_intra_size_class`], and the palette read (when
4517-/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or4639+/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
4518-/// neighbour state, never by block size.4640+/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
4641+/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
4642+/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
4519 #[allow(clippy::too_many_arguments)]4643 #[allow(clippy::too_many_arguments)]
4520 fn read_intra_mode_rect(4644 fn read_intra_mode_rect(
4521 dec: &mut SymbolDecoder,4645 dec: &mut SymbolDecoder,
@@ -4528,6 +4652,11 @@ fn read_intra_mode_rect(
4528 enable_filter_intra: bool,4652 enable_filter_intra: bool,
4529 skip_ctx: usize,4653 skip_ctx: usize,
4530 allow_screen_content_tools: bool,4654 allow_screen_content_tools: bool,
4655+ // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
4656+ // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
4657+ // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
4658+ palette: Option<(usize, &[u16])>,
4659+ palette_uv_cache: &[u16],
4531 mi_r: usize,4660 mi_r: usize,
4532 mi_c: usize,4661 mi_c: usize,
4533 ) -> Result<(4662 ) -> Result<(
@@ -4538,17 +4667,9 @@ fn read_intra_mode_rect(
4538 i32,4667 i32,
4539 Option<(i32, i32)>,4668 Option<(i32, i32)>,
4540 Option<usize>,4669 Option<usize>,
4670+ Option<PaletteY>,
4671+ Option<PaletteUv>,
4541 )> {4672 )> {
4542- // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
4543- // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
4544- // screen-content frame would therefore skip symbols the encoder wrote and
4545- // desync the tile, so refuse it by name rather than decode it wrong.
4546- if allow_screen_content_tools {
4547- return Err(unsupported(
4548- "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
4549- is consumed for square blocks only)",
4550- ));
4551- }
4552 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();4673 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
4553 macro_rules! istep {4674 macro_rules! istep {
4554 ($name:literal, $val:expr) => {4675 ($name:literal, $val:expr) => {
@@ -4613,6 +4734,42 @@ fn read_intra_mode_rect(
4613 if angle_delta_uv != 0 {4734 if angle_delta_uv != 0 {
4614 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));4735 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
4615 }4736 }
4737+ // `read_palette_mode_info` (spec 5.11.13), rect-generalised
4738+ // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
4739+ // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
4740+ // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
4741+ // colours only here, the colour-index maps deferred past `filter_intra`
4742+ // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
4743+ // runs from the caller, after the whole mode-info read).
4744+ let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
4745+ let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
4746+ if allow_screen_content_tools
4747+ && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
4748+ {
4749+ // r6: this is the exact site the removed blanket refusal used to
4750+ // guard -- reached for EVERY rect strip in a screen-content frame,
4751+ // independent of whether the block ends up using a palette.
4752+ RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
4753+ let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
4754+ let use_palette_y =
4755+ mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
4756+ if use_palette_y {
4757+ if palette.is_none() {
4758+ return Err(unsupported(
4759+ "a block that actually uses a palette (Y) -- reconstruction is out of scope",
4760+ ));
4761+ }
4762+ let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
4763+ let colors = read_palette_colors_y(dec, n, cache);
4764+ palette_y_pending = Some((n, colors));
4765+ }
4766+ let palette_uv_mode_ctx = usize::from(use_palette_y);
4767+ if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
4768+ let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
4769+ let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
4770+ palette_uv_pending = Some((n, u_colors, v_colors));
4771+ }
4772+ }
4616 let mut filter_intra = None;4773 let mut filter_intra = None;
4617 if std::env::var_os("EC_AV1_TRACE").is_some() {4774 if std::env::var_os("EC_AV1_TRACE").is_some() {
4618 let (rng, _) = dec.debug_state();4775 let (rng, _) = dec.debug_state();
@@ -4623,8 +4780,11 @@ fn read_intra_mode_rect(
4623 filter_intra_size_class_rect(bw, bh)4780 filter_intra_size_class_rect(bw, bh)
4624 );4781 );
4625 }4782 }
4783+ // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
4784+ // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
4626 if mode == DC_PRED4785 if mode == DC_PRED
4627 && enable_filter_intra4786 && enable_filter_intra
4787+ && palette_y_pending.is_none()
4628 && let Some(class) = filter_intra_size_class_rect(bw, bh)4788 && let Some(class) = filter_intra_size_class_rect(bw, bh)
4629 {4789 {
4630 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;4790 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
@@ -4637,6 +4797,19 @@ fn read_intra_mode_rect(
4637 filter_intra = Some(fi_mode);4797 filter_intra = Some(fi_mode);
4638 }4798 }
4639 }4799 }
4800+ // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
4801+ // same order as [`read_intra_mode`]'s own square path.
4802+ let palette_y = palette_y_pending.map(|(n, colors)| {
4803+ let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
4804+ PALETTE_HITS.with(|c| c.set(c.get() + 1));
4805+ PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
4806+ PaletteY { size: n, colors, map }
4807+ });
4808+ let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
4809+ let map = decode_color_index_map_wh(dec, cdfs, n, bw / 2, bh / 2, true);
4810+ PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
4811+ PaletteUv { size: n, u_colors, v_colors, map }
4812+ });
4640 Ok((4813 Ok((
4641 skip,4814 skip,
4642 mode,4815 mode,
@@ -4645,6 +4818,8 @@ fn read_intra_mode_rect(
4645 angle_delta_uv,4818 angle_delta_uv,
4646 alpha,4819 alpha,
4647 filter_intra,4820 filter_intra,
4821+ palette_y,
4822+ palette_uv,
4648 ))4823 ))
4649 }4824 }
4650 4825
@@ -4700,6 +4875,15 @@ struct RectStripModes {
4700 filter_intra: Option<usize>,4875 filter_intra: Option<usize>,
4701 smooth_neighbor: bool,4876 smooth_neighbor: bool,
4702 smooth_neighbor_uv: bool,4877 smooth_neighbor_uv: bool,
4878+ /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
4879+ /// mapped through the colour table), sliced per transform unit below --
4880+ /// palette prediction reads no edge pixels, so a unit's slice of the
4881+ /// whole-block map IS its prediction. Without this a palette strip whose
4882+ /// transform splits predicted DC and came out flat grey while the entropy
4883+ /// stream stayed in sync (the coefficients are read either way).
4884+ palette_y: Option<Vec<u16>>,
4885+ /// As `palette_y`, for the un-split chroma transform (U, V).
4886+ palette_uv: Option<(Vec<u16>, Vec<u16>)>,
4703 }4887 }
4704 4888
4705 /// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma4889 /// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
@@ -4795,20 +4979,17 @@ fn decode_rect_split(
4795 // (`row_off + tx_high < plane_bh`) they are the left4979 // (`row_off + tx_high < plane_bh`) they are the left
4796 // neighbour's, already reconstructed; the last row falls back4980 // neighbour's, already reconstructed; the last row falls back
4797 // to the block-level answer.4981 // to the block-level answer.
4798- let tu_reach = Reach {4982+ let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx, block_reach);
4799- above_right: if col_off + tx < bw {4983+ // The unit's own window on the block's palette prediction.
4800- true4984+ if let Some(buf) = &m.palette_y {
4801- } else {4985+ let tu_buf: Vec<u16> = (0..tx)
4802- row_off == 0 && block_reach.above_right4986+ .flat_map(|i| {
4803- },4987+ let base = (row_off + i) * bw + col_off;
4804- below_left: if col_off > 0 {4988+ buf[base..base + tx].iter().copied()
4805- false4989+ })
4806- } else if row_off + tx < bh {4990+ .collect();
4807- true4991+ set_palette_pred(tu_buf);
4808- } else {4992+ }
4809- block_reach.below_left
4810- },
4811- };
4812 if m.skip {4993 if m.skip {
4813 y.reconstruct(4994 y.reconstruct(
4814 tu_px,4995 tu_px,
@@ -4860,10 +5041,16 @@ fn decode_rect_split(
4860 let reach = block_reach;5041 let reach = block_reach;
4861 let (u_grid, v_grid) = if m.skip {5042 let (u_grid, v_grid) = if m.skip {
4862 let zero = vec![0i32; chroma_w * chroma_h];5043 let zero = vec![0i32; chroma_w * chroma_h];
5044+ if let Some((ub, _)) = &m.palette_uv {
5045+ set_palette_pred(ub.clone());
5046+ }
4863 u.reconstruct_rect(5047 u.reconstruct_rect(
4864 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,5048 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
4865 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,5049 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
4866 );5050 );
5051+ if let Some((_, vb)) = &m.palette_uv {
5052+ set_palette_pred(vb.clone());
5053+ }
4867 v.reconstruct_rect(5054 v.reconstruct_rect(
4868 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,5055 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
4869 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,5056 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
@@ -4917,6 +5104,10 @@ fn decode_rect_split(
4917 .zip(ac.as_deref())5104 .zip(ac.as_deref())
4918 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));5105 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
4919 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };5106 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
5107+ if let Some((ub, vb)) = &m.palette_uv {
5108+ let buf = if plane_idx == 1 { ub } else { vb };
5109+ set_palette_pred(buf.clone());
5110+ }
4920 plane.reconstruct_rect(5111 plane.reconstruct_rect(
4921 cpx,5112 cpx,
4922 cpy,5113 cpy,
@@ -4977,7 +5168,9 @@ fn decode_block_rect(
4977 let (r, c) = at;5168 let (r, c) = at;
4978 let (px, py) = (c * SUB, r * SUB);5169 let (px, py) = (c * SUB, r * SUB);
4979 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);5170 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
4980- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =5171+ let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
5172+ let palette_uv_cache = neighbours.palette_uv_cache(at);
5173+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
4981 read_intra_mode_rect(5174 read_intra_mode_rect(
4982 dec,5175 dec,
4983 cdfs,5176 cdfs,
@@ -4989,6 +5182,8 @@ fn decode_block_rect(
4989 enable_filter_intra,5182 enable_filter_intra,
4990 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),5183 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
4991 allow_screen_content_tools,5184 allow_screen_content_tools,
5185+ Some((palette_ctx, &palette_cache)),
5186+ &palette_uv_cache,
4992 r * (SUB / MI),5187 r * (SUB / MI),
4993 c * (SUB / MI),5188 c * (SUB / MI),
4994 )?;5189 )?;
@@ -5053,10 +5248,34 @@ fn decode_block_rect(
5053 filter_intra,5248 filter_intra,
5054 smooth_neighbor,5249 smooth_neighbor,
5055 smooth_neighbor_uv,5250 smooth_neighbor_uv,
5251+ palette_y: palette_y
5252+ .as_ref()
5253+ .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
5254+ palette_uv: palette_uv.as_ref().map(|p| {
5255+ (
5256+ p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
5257+ p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
5258+ )
5259+ }),
5056 };5260 };
5261+ if palette_y.is_some() || palette_uv.is_some() {
5262+ PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
5263+ }
5057 decode_rect_split(5264 decode_rect_split(
5058 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,5265 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
5059 )?;5266 )?;
5267+ // This early return skips this fn's own tail, so the palette
5268+ // neighbour state has to be stamped HERE too: without it a split-tx
5269+ // strip left the above/left palette arrays holding a DEAD block's
5270+ // colours, and the next block's colour cache
5271+ // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
5272+ // wrong VALUE -- same bit count, so the entropy stream stayed in sync
5273+ // and only those pixels were wrong (lane-palette2 r10).
5274+ let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5275+ neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5276+ let (puv_size, puv_colors) =
5277+ palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5278+ neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5060 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));5279 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5061 return Ok(());5280 return Ok(());
5062 }5281 }
@@ -5072,6 +5291,19 @@ fn decode_block_rect(
5072 skip as i325291 skip as i32
5073 );5292 );
5074 }5293 }
5294+ // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
5295+ // block's prediction is the reconstructed colour-index map, set fresh
5296+ // right before each `reconstruct_rect` call below (lane-palette2 r4).
5297+ if let Some(ref pyv) = palette_y {
5298+ let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
5299+ set_palette_pred(buf);
5300+ }
5301+ let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
5302+ (
5303+ puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
5304+ puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5305+ )
5306+ });
5075 if skip {5307 if skip {
5076 y.reconstruct_rect(5308 y.reconstruct_rect(
5077 px,5309 px,
@@ -5087,6 +5319,9 @@ fn decode_block_rect(
5087 smooth_neighbor,5319 smooth_neighbor,
5088 );5320 );
5089 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));5321 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5322+ if let Some((ub, _)) = &palette_uv_bufs {
5323+ set_palette_pred(ub.clone());
5324+ }
5090 u.reconstruct_rect(5325 u.reconstruct_rect(
5091 cpx,5326 cpx,
5092 cpy,5327 cpy,
@@ -5100,6 +5335,9 @@ fn decode_block_rect(
5100 None,5335 None,
5101 smooth_neighbor_uv,5336 smooth_neighbor_uv,
5102 );5337 );
5338+ if let Some((_, vb)) = &palette_uv_bufs {
5339+ set_palette_pred(vb.clone());
5340+ }
5103 v.reconstruct_rect(5341 v.reconstruct_rect(
5104 cpx,5342 cpx,
5105 cpy,5343 cpy,
@@ -5211,6 +5449,9 @@ fn decode_block_rect(
5211 smooth_neighbor,5449 smooth_neighbor,
5212 );5450 );
5213 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));5451 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
5452+ if let Some((ub, _)) = &palette_uv_bufs {
5453+ set_palette_pred(ub.clone());
5454+ }
5214 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);5455 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5215 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);5456 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
5216 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);5457 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
@@ -5251,6 +5492,9 @@ fn decode_block_rect(
5251 None,5492 None,
5252 smooth_neighbor_uv,5493 smooth_neighbor_uv,
5253 );5494 );
5495+ if let Some((_, vb)) = &palette_uv_bufs {
5496+ set_palette_pred(vb.clone());
5497+ }
5254 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);5498 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
5255 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);5499 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
5256 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);5500 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
@@ -5295,6 +5539,11 @@ fn decode_block_rect(
5295 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));5539 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
5296 }5540 }
5297 }5541 }
5542+ let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5543+ neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
5544+ let (puv_size, puv_colors) =
5545+ palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5546+ neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5298 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);5547 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
5299 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);5548 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
5300 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));5549 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
@@ -5374,7 +5623,16 @@ fn decode_leaf_rect(
5374 if smooth_neighbor {5623 if smooth_neighbor {
5375 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));5624 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5376 }5625 }
5377- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =5626+ // The palette-Y mode CDF row is picked by the neighbours' palette use
5627+ // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
5628+ // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
5629+ // a palette narrows the wrong interval and desyncs the tile even when the
5630+ // decoded bit is the same. The cell is the 16px-SUB cell containing the
5631+ // leaf (the palette neighbour arrays have no finer granularity).
5632+ let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
5633+ let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(pal_at);
5634+ let palette_uv_cache = neighbours.palette_uv_cache(pal_at);
5635+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5378 read_intra_mode_rect(5636 read_intra_mode_rect(
5379 dec,5637 dec,
5380 cdfs,5638 cdfs,
@@ -5386,9 +5644,19 @@ fn decode_leaf_rect(
5386 enable_filter_intra,5644 enable_filter_intra,
5387 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),5645 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
5388 allow_screen_content_tools,5646 allow_screen_content_tools,
5647+ Some((palette_ctx, &palette_cache)),
5648+ &palette_uv_cache,
5389 leaf_mi.0,5649 leaf_mi.0,
5390 leaf_mi.1,5650 leaf_mi.1,
5391 )?;5651 )?;
5652+ if palette_y.is_some() || palette_uv.is_some() {
5653+ // Symbols (mode/size/colours/index map) are all read above, so the
5654+ // tile stays in sync; only the *pixel* reconstruction of a palette on
5655+ // a below-16x16 strip is unported and ungated (lane-palette2 r7).
5656+ return Err(unsupported(
5657+ "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
5658+ ));
5659+ }
5392 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {5660 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
5393 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");5661 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
5394 }5662 }
@@ -5512,6 +5780,12 @@ fn decode_leaf_rect(
5512 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);5780 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
5513 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);5781 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
5514 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);5782 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
5783+ // This leaf is necessarily non-palette (a palette one refused above), so
5784+ // it must CLEAR the above/left palette state over its own span -- without
5785+ // this the next block's `palette_y_mode` ctx and colour cache were read
5786+ // off whatever block last covered the cell (lane-palette2 r8).
5787+ neighbours.record_palette_y_rect(pal_at, bw, bh, 0, [0u16; 8]);
5788+ neighbours.record_palette_uv_rect(pal_at, bw, bh, 0, [0u16; 8]);
5515 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and5789 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
5516 // rows -- record the whole span, not one cell.5790 // rows -- record the whole span, not one cell.
5517 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);5791 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
@@ -5569,21 +5843,42 @@ fn decode_block_rect4(
5569 left_mode = pmode;5843 left_mode = pmode;
5570 }5844 }
5571 }5845 }
5572- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =5846+ let (
5573- read_intra_mode_rect(5847+ skip,
5574- dec,5848+ mode,
5575- cdfs,5849+ angle_delta_y,
5576- above_mode,5850+ uv_mode,
5577- left_mode,5851+ angle_delta_uv,
5578- true,5852+ alpha,
5579- bw,5853+ filter_intra,
5580- bh,5854+ palette_y,
5581- enable_filter_intra,5855+ palette_uv,
5582- neighbours.skip_txfm_ctx(mi_r, mi_c),5856+ ) = read_intra_mode_rect(
5583- allow_screen_content_tools,5857+ dec,
5584- mi_r,5858+ cdfs,
5585- mi_c,5859+ above_mode,
5586- )?;5860+ left_mode,
5861+ true,
5862+ bw,
5863+ bh,
5864+ enable_filter_intra,
5865+ neighbours.skip_txfm_ctx(mi_r, mi_c),
5866+ allow_screen_content_tools,
5867+ None,
5868+ &[],
5869+ mi_r,
5870+ mi_c,
5871+ )?;
5872+ // Merge of lane-palette2: `read_intra_mode_rect` now reads the palette
5873+ // syntax for every rect strip, but this 1:4 decoder has no palette
5874+ // reconstruction path (its caller never passes a cache). The symbols are
5875+ // still read, so the stream stays in sync; a strip that ACTUALLY uses a
5876+ // palette is refused rather than reconstructed wrong.
5877+ if palette_y.is_some() || palette_uv.is_some() {
5878+ return Err(unsupported(
5879+ "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)",
5880+ ));
5881+ }
5587 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);5882 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
5588 if smooth_neighbor {5883 if smooth_neighbor {
5589 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));5884 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
@@ -5788,7 +6083,7 @@ fn decode_block_rect4(
5788 None,6083 None,
5789 smooth_neighbor_uv,6084 smooth_neighbor_uv,
5790 );6085 );
5791- neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels, u_levels, v_levels]);6086+ neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
5792 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);6087 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
5793 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);6088 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
5794 if bw > bh {6089 if bw > bh {
@@ -5836,7 +6131,9 @@ fn decode_block_rect64(
5836 let (r, c) = at;6131 let (r, c) = at;
5837 let (px, py) = (c * SUB, r * SUB);6132 let (px, py) = (c * SUB, r * SUB);
5838 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);6133 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
5839- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =6134+ let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
6135+ let palette_uv_cache = neighbours.palette_uv_cache(at);
6136+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5840 read_intra_mode_rect(6137 read_intra_mode_rect(
5841 dec,6138 dec,
5842 cdfs,6139 cdfs,
@@ -5855,9 +6152,23 @@ fn decode_block_rect64(
5855 enable_filter_intra,6152 enable_filter_intra,
5856 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),6153 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5857 allow_screen_content_tools,6154 allow_screen_content_tools,
6155+ Some((palette_ctx, &palette_cache)),
6156+ &palette_uv_cache,
5858 r * (SUB / MI),6157 r * (SUB / MI),
5859 c * (SUB / MI),6158 c * (SUB / MI),
5860 )?;6159 )?;
6160+ if (palette_y.is_some() || palette_uv.is_some()) && !skip {
6161+ // The luma coefficient path here is the corner-cropped 32x32 real
6162+ // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
6163+ // own doc comment) -- a real (non-skip) palette block's residual
6164+ // needs the plain, uncropped rect reader [`decode_block_rect`] already
6165+ // has, not this one's truncation. `skip` (no residual at all) is
6166+ // still supported below (lane-palette2 r4).
6167+ return Err(unsupported(
6168+ "a palette block with a real transform on a superblock-level HORZ/VERT \
6169+ strip (corner-cropped luma coefficients not ported for palette)",
6170+ ));
6171+ }
5861 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);6172 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
5862 if smooth_neighbor {6173 if smooth_neighbor {
5863 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));6174 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
@@ -5917,10 +6228,31 @@ fn decode_block_rect64(
5917 filter_intra,6228 filter_intra,
5918 smooth_neighbor,6229 smooth_neighbor,
5919 smooth_neighbor_uv,6230 smooth_neighbor_uv,
6231+ palette_y: palette_y
6232+ .as_ref()
6233+ .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
6234+ palette_uv: palette_uv.as_ref().map(|p| {
6235+ (
6236+ p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
6237+ p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
6238+ )
6239+ }),
5920 };6240 };
6241+ if palette_y.is_some() || palette_uv.is_some() {
6242+ PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6243+ }
5921 decode_rect_split(6244 decode_rect_split(
5922 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,6245 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
5923 )?;6246 )?;
6247+ // Same early-return palette stamp as [`decode_block_rect`]'s split arm
6248+ // (lane-palette2 r10): this return skips the fn's own tail, so a
6249+ // split-tx superblock strip would otherwise leave the above/left
6250+ // palette arrays holding a dead block's colours.
6251+ let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6252+ neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6253+ let (puv_size, puv_colors) =
6254+ palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6255+ neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
5924 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));6256 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
5925 return Ok(());6257 return Ok(());
5926 }6258 }
@@ -5928,6 +6260,16 @@ fn decode_block_rect64(
5928 let (cpx, cpy) = (px / 2, py / 2);6260 let (cpx, cpy) = (px / 2, py / 2);
5929 let (chroma_w, chroma_h) = (bw / 2, bh / 2);6261 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
5930 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);6262 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6263+ if let Some(ref pyv) = palette_y {
6264+ let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
6265+ set_palette_pred(buf);
6266+ }
6267+ let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
6268+ (
6269+ puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
6270+ puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
6271+ )
6272+ });
5931 if skip {6273 if skip {
5932 y.reconstruct_rect(6274 y.reconstruct_rect(
5933 px,6275 px,
@@ -5943,6 +6285,9 @@ fn decode_block_rect64(
5943 smooth_neighbor,6285 smooth_neighbor,
5944 );6286 );
5945 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));6287 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6288+ if let Some((ub, _)) = &palette_uv_bufs {
6289+ set_palette_pred(ub.clone());
6290+ }
5946 u.reconstruct_rect(6291 u.reconstruct_rect(
5947 cpx,6292 cpx,
5948 cpy,6293 cpy,
@@ -5956,6 +6301,9 @@ fn decode_block_rect64(
5956 None,6301 None,
5957 smooth_neighbor_uv,6302 smooth_neighbor_uv,
5958 );6303 );
6304+ if let Some((_, vb)) = &palette_uv_bufs {
6305+ set_palette_pred(vb.clone());
6306+ }
5959 v.reconstruct_rect(6307 v.reconstruct_rect(
5960 cpx,6308 cpx,
5961 cpy,6309 cpy,
@@ -6215,6 +6563,11 @@ fn decode_block_rect64(
6215 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);6563 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
6216 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));6564 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
6217 }6565 }
6566+ let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
6567+ neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
6568+ let (puv_size, puv_colors) =
6569+ palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
6570+ neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
6218 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);6571 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
6219 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);6572 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6220 SB_RECT_HITS.with(|c| c.set(c.get() + 1));6573 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
@@ -6790,42 +7143,50 @@ impl PlaneBuf {
6790 filter_intra: Option<usize>,7143 filter_intra: Option<usize>,
6791 smooth_neighbor: bool,7144 smooth_neighbor: bool,
6792 ) {7145 ) {
6793- let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);7146+ // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
6794- if std::env::var_os("EC_DEBUG_EDGES").is_some() {7147+ // (lane-palette2 r4): a palette block's prediction is the
6795- eprintln!(7148+ // reconstructed colour-index map, needing no edge pixels at all.
6796- "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",7149+ let prediction = if let Some(buf) = take_palette_pred() {
6797- above.as_ref().map(|a| (a.len(), a[0])),7150+ buf
6798- left.as_ref().map(|l| l.len()),
6799- left.as_ref().map(|l| l[0]),
6800- self.tile_x0, self.tile_y0, self.true_width, self.true_height
6801- );
6802- }
6803- let mut prediction = vec![0u16; bw * bh];
6804- if let Some(fi_mode) = filter_intra {
6805- crate::intra::predict_filter_intra(
6806- fi_mode,
6807- above.as_deref(),
6808- left.as_deref(),
6809- corner,
6810- bw,
6811- bh,
6812- &mut prediction,
6813- );
6814 } else {7151 } else {
6815- let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);7152+ let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
6816- predict(7153+ if std::env::var_os("EC_DEBUG_EDGES").is_some() {
6817- mode as u8,7154+ eprintln!(
6818- angle_delta,7155+ "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
6819- above.as_deref(),7156+ above.as_ref().map(|a| (a.len(), a[0])),
6820- left.as_deref(),7157+ left.as_ref().map(|l| l.len()),
6821- corner,7158+ left.as_ref().map(|l| l[0]),
6822- bw,7159+ self.tile_x0, self.tile_y0, self.true_width, self.true_height
6823- bh,7160+ );
6824- enable_edge_filter,7161+ }
6825- smooth_neighbor,7162+ let mut prediction = vec![0u16; bw * bh];
6826- &mut prediction,7163+ if let Some(fi_mode) = filter_intra {
6827- );7164+ crate::intra::predict_filter_intra(
6828- }7165+ fi_mode,
7166+ above.as_deref(),
7167+ left.as_deref(),
7168+ corner,
7169+ bw,
7170+ bh,
7171+ &mut prediction,
7172+ );
7173+ } else {
7174+ let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
7175+ predict(
7176+ mode as u8,
7177+ angle_delta,
7178+ above.as_deref(),
7179+ left.as_deref(),
7180+ corner,
7181+ bw,
7182+ bh,
7183+ enable_edge_filter,
7184+ smooth_neighbor,
7185+ &mut prediction,
7186+ );
7187+ }
7188+ prediction
7189+ };
6829 for row in 0..bh {7190 for row in 0..bh {
6830 for col in 0..bw {7191 for col in 0..bw {
6831 let idx = row * bw + col;7192 let idx = row * bw + col;
@@ -6869,7 +7230,7 @@ impl PlaneBuf {
6869 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)7230 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
6870 // takes priority over `predict()`/`predict_filter_intra` entirely --7231 // takes priority over `predict()`/`predict_filter_intra` entirely --
6871 // palette prediction needs no edge pixels at all.7232 // palette prediction needs no edge pixels at all.
6872- let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {7233+ let prediction = if let Some(buf) = take_palette_pred() {
6873 buf7234 buf
6874 } else {7235 } else {
6875 let (above, left, corner) = self.edges(x, y, side, reach);7236 let (above, left, corner) = self.edges(x, y, side, reach);
@@ -7197,7 +7558,7 @@ fn decode_block(
7197 (yb, ub, vb)7558 (yb, ub, vb)
7198 });7559 });
7199 if let Some((yb, _, _)) = &intrabc_bufs {7560 if let Some((yb, _, _)) = &intrabc_bufs {
7200- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(yb.clone()));7561+ set_palette_pred(yb.clone());
7201 }7562 }
7202 // A palette-Y block's own prediction is the reconstructed colour-index7563 // A palette-Y block's own prediction is the reconstructed colour-index
7203 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it7564 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
@@ -7207,18 +7568,21 @@ fn decode_block(
7207 // would need the map sliced per-TU -- untested against a real7568 // would need the map sliced per-TU -- untested against a real
7208 // `--enable-palette=1` stream this round, so refuse by name rather than7569 // `--enable-palette=1` stream this round, so refuse by name rather than
7209 // guess at the slicing (charter's own named-acceptable fallback).7570 // guess at the slicing (charter's own named-acceptable fallback).
7210- if let Some(ref py) = palette_y {7571+ let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
7211- if tx_select && logical_tx != side {7572+ py.map
7212- return Err(unsupported(
7213- "a palette block with a split luma transform (round 1)",
7214- ));
7215- }
7216- let buf: Vec<u16> = py
7217- .map
7218 .iter()7573 .iter()
7219 .map(|&idx| py.colors[idx as usize])7574 .map(|&idx| py.colors[idx as usize])
7220- .collect();7575+ .collect()
7221- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));7576+ });
7577+ // With one luma transform unit the whole `side`x`side` map is the
7578+ // prediction; with several (`logical_tx != side`) each unit takes its own
7579+ // `logical_tx`-sized window of that same map, set fresh inside the TU loop
7580+ // below (lane-palette2 r7) -- setting the full-block buffer here would be
7581+ // taken by the FIRST unit and indexed at the wrong stride.
7582+ if let Some(buf) = &palette_y_buf
7583+ && logical_tx == side
7584+ {
7585+ set_palette_pred(buf.clone());
7222 }7586 }
7223 // A UV-palette block's own chroma prediction override (lane-palette2 r1),7587 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
7224 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each7588 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
@@ -7255,7 +7619,7 @@ fn decode_block(
7255 );7619 );
7256 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));7620 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7257 if let Some((ub, _)) = &palette_uv_bufs {7621 if let Some((ub, _)) = &palette_uv_bufs {
7258- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));7622+ set_palette_pred(ub.clone());
7259 }7623 }
7260 u.reconstruct(7624 u.reconstruct(
7261 cpx,7625 cpx,
@@ -7270,7 +7634,7 @@ fn decode_block(
7270 smooth_neighbor_uv,7634 smooth_neighbor_uv,
7271 );7635 );
7272 if let Some((_, vb)) = &palette_uv_bufs {7636 if let Some((_, vb)) = &palette_uv_bufs {
7273- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));7637+ set_palette_pred(vb.clone());
7274 }7638 }
7275 v.reconstruct(7639 v.reconstruct(
7276 cpx,7640 cpx,
@@ -7317,7 +7681,7 @@ fn decode_block(
7317 )?;7681 )?;
7318 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));7682 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7319 if let Some((ub, _)) = &palette_uv_bufs {7683 if let Some((ub, _)) = &palette_uv_bufs {
7320- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));7684+ set_palette_pred(ub.clone());
7321 }7685 }
7322 let u_grid = read_plane(7686 let u_grid = read_plane(
7323 dec,7687 dec,
@@ -7348,7 +7712,7 @@ fn decode_block(
7348 );7712 );
7349 }7713 }
7350 if let Some((_, vb)) = &palette_uv_bufs {7714 if let Some((_, vb)) = &palette_uv_bufs {
7351- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));7715+ set_palette_pred(vb.clone());
7352 }7716 }
7353 let v_grid = read_plane(7717 let v_grid = read_plane(
7354 dec,7718 dec,
@@ -7390,12 +7754,34 @@ fn decode_block(
7390 let tu_px = px + tu_col * logical_tx;7754 let tu_px = px + tu_col * logical_tx;
7391 let tu_py = py + tu_row * logical_tx;7755 let tu_py = py + tu_row * logical_tx;
7392 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];7756 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
7393- let tu_reach = Reach::of_tu(side, logical_tx, tu_px, tu_py, y.width, y.height);7757+ // A transform unit inside a block is NOT a block at that
7758+ // position (lane-palette2 r12): `Reach::of` granted the
7759+ // top-right 8x8 unit of a 16x16 D203 block bottom-left
7760+ // pixels libaom refuses outright (`col_off > 0`), which is
7761+ // the diagonal wedge seed 46 reconstructed wrong.
7762+ let tu_reach = Reach::of_tu(
7763+ side,
7764+ side,
7765+ tu_col * logical_tx,
7766+ tu_row * logical_tx,
7767+ logical_tx,
7768+ reach,
7769+ );
7394 // This transform unit's own bsize (`logical_tx`) is smaller7770 // This transform unit's own bsize (`logical_tx`) is smaller
7395 // than the block it sits in (`side`), so `txb_skip_ctx` is7771 // than the block it sits in (`side`), so `txb_skip_ctx` is
7396 // the neighbour-magnitude table, not the lone-TU 0 (spec7772 // the neighbour-magnitude table, not the lone-TU 0 (spec
7397 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).7773 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
7398 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);7774 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
7775+ if let Some(buf) = &palette_y_buf {
7776+ PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7777+ let mut window = vec![0u16; logical_tx * logical_tx];
7778+ for row in 0..logical_tx {
7779+ let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
7780+ window[row * logical_tx..][..logical_tx]
7781+ .copy_from_slice(&buf[src..][..logical_tx]);
7782+ }
7783+ set_palette_pred(window);
7784+ }
7399 let tu_grid = read_plane(7785 let tu_grid = read_plane(
7400 dec,7786 dec,
7401 cdfs,7787 cdfs,
@@ -7432,7 +7818,7 @@ fn decode_block(
7432 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));7818 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
7433 let chroma_around = neighbours.around(at, side);7819 let chroma_around = neighbours.around(at, side);
7434 if let Some((ub, _)) = &palette_uv_bufs {7820 if let Some((ub, _)) = &palette_uv_bufs {
7435- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));7821+ set_palette_pred(ub.clone());
7436 }7822 }
7437 let u_grid = read_plane(7823 let u_grid = read_plane(
7438 dec,7824 dec,
@@ -7457,7 +7843,7 @@ fn decode_block(
7457 smooth_neighbor_uv,7843 smooth_neighbor_uv,
7458 )?;7844 )?;
7459 if let Some((_, vb)) = &palette_uv_bufs {7845 if let Some((_, vb)) = &palette_uv_bufs {
7460- PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));7846+ set_palette_pred(vb.clone());
7461 }7847 }
7462 let v_grid = read_plane(7848 let v_grid = read_plane(
7463 dec,7849 dec,
@@ -7765,7 +8151,7 @@ fn decode_leaf8(
7765 if crate::encode::Reach::in_vert_ab() {8151 if crate::encode::Reach::in_vert_ab() {
7766 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));8152 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
7767 }8153 }
7768- let tu_reach = Reach::of_tu(8, 4, tu_px, tu_py, y.width, y.height);8154+ let tu_reach = Reach::of_tu(8, 8, tu_col * 4, tu_row * 4, 4, reach);
7769 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);8155 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
7770 let tu_grid = read_plane(8156 let tu_grid = read_plane(
7771 dec,8157 dec,
@@ -7878,12 +8264,28 @@ fn decode_leaf8(
7878 neighbours.above[leaf_mi.1 + cell][2] = v_state;8264 neighbours.above[leaf_mi.1 + cell][2] = v_state;
7879 }8265 }
7880 }8266 }
8267+ // Non-palette 8x8 leaf (this path never reads a palette): clear the
8268+ // above/left palette state over its own cell so the next block's ctx and
8269+ // colour cache do not read a previous block's palette (lane-palette2 r8).
8270+ {
8271+ let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
8272+ neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
8273+ neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
8274+ }
7881 neighbours.fill_skip_grid(leaf_mi, 2, skip);8275 neighbours.fill_skip_grid(leaf_mi, 2, skip);
7882 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);8276 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
7883 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);8277 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
7884 return Ok(mode);8278 return Ok(mode);
7885 }8279 }
7886 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);8280 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
8281+ // Non-palette 8x8 leaf (this path never reads a palette): clear the
8282+ // above/left palette state over its own cell so the next block's ctx and
8283+ // colour cache do not read a previous block's palette (lane-palette2 r8).
8284+ {
8285+ let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
8286+ neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
8287+ neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
8288+ }
7887 neighbours.fill_skip_grid(leaf_mi, 2, skip);8289 neighbours.fill_skip_grid(leaf_mi, 2, skip);
7888 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);8290 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
7889 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);8291 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
@@ -8293,7 +8695,12 @@ fn decode_leaf_rect8(
8293 };8695 };
8294 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);8696 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
8295 let tu_around = neighbours.around_mi(tu_mi, 4)[0];8697 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
8296- let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);8698+ // Same per-TU rule as every other split-transform site
8699+ // (lane-palette2 r12): a transform unit inside a block is not
8700+ // a block at that position, so its reach comes from the
8701+ // block's own row, offset by the unit's position.
8702+ let tu_reach =
8703+ Reach::of_tu(bw, bh, tu_px - px, tu_py - py, 4, reach);
8297 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);8704 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
8298 if skip {8705 if skip {
8299 // A skipped leaf still predicts per transform unit: the8706 // A skipped leaf still predicts per transform unit: the
@@ -18847,6 +19254,33 @@ mod tests {
18847 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));19254 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
18848 }19255 }
18849 19256
19257+ /// A below-16px leaf must clear the palette neighbour state over its own
19258+ /// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops
19259+ /// ran zero times for any sub-16 span, so `decode_leaf_rect` /
19260+ /// `decode_leaf8` left a previous block's palette size and colours in the
19261+ /// above/left arrays and the NEXT block read `palette_y_mode` off the
19262+ /// wrong CDF row with a stale colour cache (class
19263+ /// [[cdf-row-held-constant]]).
19264+ #[test]
19265+ fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() {
19266+ let mut n = Neighbours::new(4, 4, 16, 16);
19267+ // A real 16x16 palette block covering SUB cell (1, 1).
19268+ n.record_palette_y_rect((1, 1), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
19269+ let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
19270+ assert_eq!(ctx, 2, "the palette block itself must be visible");
19271+ assert_eq!(cache, vec![7, 9]);
19272+ // An 8x8 non-palette leaf in that same cell.
19273+ n.record_palette_y_rect((1, 1), 8, 8, 0, [0u16; 8]);
19274+ let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
19275+ assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell");
19276+ assert!(cache.is_empty(), "and its stale colour cache with it");
19277+ // Same for the chroma half.
19278+ n.record_palette_uv_rect((1, 1), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]);
19279+ assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]);
19280+ n.record_palette_uv_rect((1, 1), 8, 8, 0, [0u16; 8]);
19281+ assert!(n.palette_uv_cache((1, 1)).is_empty());
19282+ }
19283+
18850 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's19284 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
18851 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):19285 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
18852 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`19286 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
crates/ec-av1/src/encode.rsmodified+120 -49
@@ -1008,7 +1008,7 @@ struct At {
1008 /// block whose transform covers it whole, whether the samples above its right1008 /// block whose transform covers it whole, whether the samples above its right
1009 /// (or below its left) are decoded depends only on where the block sits inside1009 /// (or below its left) are decoded depends only on where the block sits inside
1010 /// its 64x64 superblock, which is a pinned table per block size.1010 /// its 64x64 superblock, which is a pinned table per block size.
1011-#[derive(Clone, Copy)]1011+#[derive(Clone, Copy, Debug)]
1012 pub(crate) struct Reach {1012 pub(crate) struct Reach {
1013 pub(crate) above_right: bool,1013 pub(crate) above_right: bool,
1014 pub(crate) below_left: bool,1014 pub(crate) below_left: bool,
@@ -1215,6 +1215,44 @@ fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
1215 }1215 }
1216 1216
1217 impl Reach {1217 impl Reach {
1218+ /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
1219+ /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
1220+ /// own answer is `block` -- a different rule from the standalone-block
1221+ /// tables, because a unit's neighbours are mostly its own block's
1222+ /// already-reconstructed units:
1223+ /// * top-right: available while the unit to the right is still inside
1224+ /// the block (`col_off + tx < bw`); otherwise only the block's top row
1225+ /// of units reaches past it, through the block-level answer
1226+ /// (libaom's `row_off > 0` branch returns exactly
1227+ /// `col_off + txw < plane_bw`).
1228+ /// * bottom-left: a unit outside the block's left column has none
1229+ /// (libaom returns 0 for `col_off > 0`); inside the block
1230+ /// (`row_off + tx < bh`) they are the left unit's, already
1231+ /// reconstructed; the bottom row falls back to the block-level answer.
1232+ pub(crate) fn of_tu(
1233+ bw: usize,
1234+ bh: usize,
1235+ col_off: usize,
1236+ row_off: usize,
1237+ tx: usize,
1238+ block: Self,
1239+ ) -> Self {
1240+ Self {
1241+ above_right: if col_off + tx < bw {
1242+ true
1243+ } else {
1244+ row_off == 0 && block.above_right
1245+ },
1246+ below_left: if col_off > 0 {
1247+ false
1248+ } else if row_off + tx < bh {
1249+ true
1250+ } else {
1251+ block.below_left
1252+ },
1253+ }
1254+ }
1255+
1218 /// What a block of `side` samples at `(x, y)` may read past its own edges,1256 /// What a block of `side` samples at `(x, y)` may read past its own edges,
1219 /// in a frame of `width` by `height`.1257 /// in a frame of `width` by `height`.
1220 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {1258 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {
@@ -1254,29 +1292,7 @@ impl Reach {
1254 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX41292 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
1255 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a1293 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
1256 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).1294 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
1257- pub(crate) fn of_tu(1295+ /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
1258- block: usize,
1259- tx: usize,
1260- x: usize,
1261- y: usize,
1262- width: usize,
1263- height: usize,
1264- ) -> Self {
1265- let (row_off, col_off) = ((y % block) / tx, (x % block) / tx);
1266- let n = block / tx;
1267- let (bx, by) = (x - col_off * tx, y - row_off * tx);
1268- Self {
1269- above_right: y > 0
1270- && x + tx < width
1271- && (col_off + 1 < n || (row_off == 0 && Self::top_right(block, bx, by))),
1272- below_left: x > 0
1273- && y + tx < height
1274- && col_off == 0
1275- && (row_off + 1 < n || Self::bottom_left(block, bx, by)),
1276- }
1277- }
1278-
1279- /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
1280 /// the transform covering the whole block, luma): everything before the1296 /// the transform covering the whole block, luma): everything before the
1281 /// table lookup is that function's own early-exit ladder.1297 /// table lookup is that function's own early-exit ladder.
1282 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {1298 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool {
@@ -3841,33 +3857,28 @@ mod tests {
3841 /// upper right, which a vertical AB partition codes AFTER it3857 /// upper right, which a vertical AB partition codes AFTER it
3842 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).3858 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
3843 #[test]3859 #[test]
3844- fn of_tu_keeps_the_ordinary_answer_and_uses_the_block_row_under_vert_ab() {3860+ fn of_tu_follows_the_block_row_including_under_vert_ab() {
3845- let (w, h) = (SUPERBLOCK * 2, SUPERBLOCK * 2);3861+ // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
3846- for y in (0..h).step_by(4) {3862+ // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
3847- for x in (0..w).step_by(4) {3863+ // above-right answer is the BLOCK's, which is the whole reason a unit
3848- let tu = Reach::of_tu(8, 4, x, y, w, h);3864+ // asks the block instead of looking itself up (the
3849- let as_block = Reach::of(4, x, y, w, h);3865+ // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
3850- assert_eq!(3866+ let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK);
3851- (tu.above_right, tu.below_left),3867+ assert_eq!(
3852- (as_block.above_right, as_block.below_left),3868+ Reach::of_tu(8, 8, 4, 0, 4, plain).above_right,
3853- "of_tu(8, 4) at ({x}, {y}) differs from the unit-as-block answer"3869+ plain.above_right,
3854- );3870+ "ordinary table: the top-right TX4 unit takes the block's row"
3855- // (2): under the vert tables the same lookup must answer at
3856- // all rather than index a row that does not exist.
3857- let _guard = Reach::vert_ab_partition();
3858- let _ = Reach::of_tu(8, 4, x, y, w, h);
3859- }
3860- }
3861- // (3): the disagreeing cell, both ways round.
3862- let (x, y) = (4, 8);
3863- assert!(
3864- Reach::of_tu(8, 4, x, y, SUPERBLOCK, SUPERBLOCK).above_right,
3865- "ordinary table: the 8x8 above-right of the block at sb row 1 col 0 is coded first"
3866 );3871 );
3867 let guard = Reach::vert_ab_partition();3872 let guard = Reach::vert_ab_partition();
3868- assert!(3873+ let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK);
3869- !Reach::of_tu(8, 4, x, y, SUPERBLOCK, SUPERBLOCK).above_right,3874+ assert_eq!(
3870- "vert AB: that 8x8 is the partition's own later-coded right half"3875+ Reach::of_tu(8, 8, 4, 0, 4, vert).above_right,
3876+ vert.above_right,
3877+ "vert AB: the unit follows the vert row the block just picked"
3878+ );
3879+ assert_ne!(
3880+ plain.above_right, vert.above_right,
3881+ "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
3871 );3882 );
3872 drop(guard);3883 drop(guard);
3873 }3884 }
@@ -3963,6 +3974,66 @@ mod tests {
3963 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every3974 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
3964 /// stream that partitions that small first hits the still-refused3975 /// stream that partitions that small first hits the still-refused
3965 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).3976 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
3977+ /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
3978+ /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
3979+ /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
3980+ /// pixels -- lane-palette2 r12: the square multi-TU path used the
3981+ /// standalone-block tables instead of this rule and granted a 16x16
3982+ /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
3983+ #[test]
3984+ fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
3985+ // libaom, in MI units: bw_unit/bh_unit = block size / 4,
3986+ // *_count_unit = tx size / 4.
3987+ fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
3988+ let (plane_bw_unit, count) = (bw / 4, tx / 4);
3989+ let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
3990+ let _ = bh;
3991+ if row_off_u > 0 {
3992+ col_off_u + count < plane_bw_unit
3993+ } else if col_off_u + count < plane_bw_unit {
3994+ true
3995+ } else {
3996+ blk
3997+ }
3998+ }
3999+ fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
4000+ let (plane_bh_unit, count) = (bh / 4, tx / 4);
4001+ let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
4002+ let _ = bw;
4003+ if col_off_u > 0 {
4004+ false
4005+ } else if row_off_u + count < plane_bh_unit {
4006+ true
4007+ } else {
4008+ blk
4009+ }
4010+ }
4011+ for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
4012+ for &tx in &[4usize, 8, 16, 32] {
4013+ if tx > bw.min(bh) {
4014+ continue;
4015+ }
4016+ for row_off in (0..bh).step_by(tx) {
4017+ for col_off in (0..bw).step_by(tx) {
4018+ for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
4019+ let got = Reach::of_tu(bw, bh, col_off, row_off, tx, blk);
4020+ assert_eq!(
4021+ got.above_right,
4022+ libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
4023+ "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
4024+ );
4025+ assert_eq!(
4026+ got.below_left,
4027+ libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
4028+ "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
4029+ );
4030+ }
4031+ }
4032+ }
4033+ }
4034+ }
4035+ }
4036+
3966 #[test]4037 #[test]
3967 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {4038 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
3968 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);4039 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
crates/ec-av1/src/refusal_inventory.rsmodified+3 -2
@@ -35,6 +35,7 @@ const REFUSALS: &[&str] = &[
35 "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)",35 "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)",
36 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",36 "an inter partition below 8x8 (this decoder codes no inter leaf smaller than 8x8; lane-sub8 scoped to intra)",
37 "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)",37 "a 1:4 partition below 16x16 (PARTITION_HORZ_4/VERT_4, four 16x4/4x16 strips -- this decoder codes NONE, HORZ, VERT, the four AB arms and a clean split at 16x16)",
38+ "a 1:4 rect strip that actually uses a palette (reconstruction is not ported at this shape)",
38 "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",39 "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
39 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",40 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
40 "a 32x32 partition type this decoder does not code (value={part32})",41 "a 32x32 partition type this decoder does not code (value={part32})",
@@ -43,7 +44,8 @@ const REFUSALS: &[&str] = &[
43 "a tx_type symbol outside its CDF's own set: {t}",44 "a tx_type symbol outside its CDF's own set: {t}",
44 "an INTER 32x32 partition type this decoder does not code (value={part32})",45 "an INTER 32x32 partition type this decoder does not code (value={part32})",
45 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",46 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
46- "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)",47+ "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction not ported)",
48+ "a palette block with a real transform on a superblock-level HORZ/VERT strip (corner-cropped luma coefficients not ported for palette)",
47 "a block that actually uses a palette (UV) -- reconstruction is out of scope",49 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
48 "a block that actually uses a palette (Y) -- reconstruction is out of scope",50 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
49 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",51 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
@@ -54,7 +56,6 @@ const REFUSALS: &[&str] = &[
54 "a frame with no mode-info grid",56 "a frame with no mode-info grid",
55 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",57 "a frame whose segmentation enables SEG_LVL_REF_FRAME/SKIP/GLOBALMV (this decoder reads segment_id but never lets a segment override a block's reference, skip or mode)",
56 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",58 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
57- "a palette block with a split luma transform (round 1)",
58 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",59 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
59 "a reference picture whose height does not match this frame's own true size",60 "a reference picture whose height does not match this frame's own true size",
60 "a show_existing_frame header naming an empty reference slot",61 "a show_existing_frame header naming an empty reference slot",
crates/ec-av1/src/stream.rsmodified+344 -0
@@ -3261,6 +3261,350 @@ mod tests {
3261 }3261 }
3262 }3262 }
3263 3263
3264+ /// A real `aomenc` fixture that lands palette syntax on a HORZ/VERT
3265+ /// intra strip (lane-palette2 r5, gating r4's `read_intra_mode_rect`
3266+ /// wiring). `smptebars`/`rgbtestsrc` at plain default settings both hit a
3267+ /// SQUARE palette refusal or an unrelated 32x32 `HORZ_A`/`VERT_A`/etc
3268+ /// partition FIRST on every size/cq combo probed -- `--enable-ab-
3269+ /// partitions=0` measurably does not stop aomenc choosing one at this
3270+ /// screen-content tune (byte-identical output with `=0` vs `=1`, same
3271+ /// aomenc quirk as `[[lane-sbpart-r2]]`'s SB-level AB). Forcing
3272+ /// `--min/max-partition-size=64` sidesteps that whole 32x32-level code
3273+ /// path: the only choices left at the (single, key-frame) superblock are
3274+ /// NONE/SPLIT/HORZ/VERT/AB/1to4 straight from [`decode_block_rect64`],
3275+ /// and a size/cq sweep (measured live this round) reliably lands
3276+ /// PARTITION_HORZ/VERT with a real (non-split-tx) palette block on both
3277+ /// sources. Drives `decode_stream` directly (below any refusal) and
3278+ /// HARD-asserts [`decode::palette_rect_hits`] moved on every attempt that
3279+ /// didn't refuse, before comparing pixels ([[gate-blind-to-feature]]) --
3280+ /// a decode that never lands a rect palette block is not a match.
3281+ #[test]
3282+ fn a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact() {
3283+ const NAME: &str = "a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact";
3284+ let _gate_lock = lock_gate_counters();
3285+ if !have_ffmpeg() {
3286+ eprintln!("SKIP {NAME}: no ffmpeg");
3287+ return;
3288+ }
3289+ if !have_aomenc() {
3290+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3291+ return;
3292+ }
3293+ let mut matched = 0u32;
3294+ let mut uncounted_exact = 0u32;
3295+ let mut named_refusals = 0u32;
3296+ let mut attempts = 0u32;
3297+ let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
3298+ let cqs = [5u32, 15, 25, 35, 45, 55, 63];
3299+ for src_name in ["smptebars", "rgbtestsrc"] {
3300+ for (width, height) in sizes {
3301+ for cq in cqs {
3302+ attempts += 1;
3303+ let source = format!("{src_name}=size={width}x{height}:rate=25");
3304+ let y4m = Command::new("ffmpeg")
3305+ .args([
3306+ "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
3307+ "-t", "0.04", "-f", "yuv4mpegpipe", "-",
3308+ ])
3309+ .stdin(Stdio::null())
3310+ .stdout(Stdio::piped())
3311+ .stderr(Stdio::piped())
3312+ .output()
3313+ .expect("ffmpeg failed to run");
3314+ assert!(
3315+ y4m.status.success(),
3316+ "ffmpeg fixture: {}",
3317+ String::from_utf8_lossy(&y4m.stderr)
3318+ );
3319+ let cq_arg = format!("--cq-level={cq}");
3320+ let mut child = Command::new(aomenc_path())
3321+ .args([
3322+ "--codec=av1",
3323+ "--passes=1",
3324+ "--end-usage=q",
3325+ &cq_arg,
3326+ "--cpu-used=4",
3327+ "--threads=1",
3328+ "--row-mt=0",
3329+ "--sb-size=64",
3330+ "--enable-palette=1",
3331+ "--min-partition-size=16",
3332+ "--max-partition-size=64",
3333+ "--obu",
3334+ "-o",
3335+ "-",
3336+ "-",
3337+ ])
3338+ .stdin(Stdio::piped())
3339+ .stdout(Stdio::piped())
3340+ .stderr(Stdio::piped())
3341+ .spawn()
3342+ .expect("aomenc failed to start");
3343+ child
3344+ .stdin
3345+ .take()
3346+ .expect("aomenc stdin")
3347+ .write_all(&y4m.stdout)
3348+ .expect("writing y4m to aomenc");
3349+ let out = child.wait_with_output().expect("aomenc failed to run");
3350+ assert!(
3351+ out.status.success(),
3352+ "aomenc refused the fixture ({source} cq={cq}): {}",
3353+ String::from_utf8_lossy(&out.stderr)
3354+ );
3355+ let stream = out.stdout;
3356+ let before = crate::decode::palette_rect_hits();
3357+ let frames = match decode_stream(&stream) {
3358+ Err(e) => {
3359+ let msg = e.to_string();
3360+ assert!(
3361+ msg.contains("unsupported"),
3362+ "{NAME} failed outright, not a named refusal \
3363+ ({source} cq={cq}): {msg}"
3364+ );
3365+ named_refusals += 1;
3366+ eprintln!("{source} cq={cq}: refusal: {msg}");
3367+ continue;
3368+ }
3369+ Ok(frames) => frames,
3370+ };
3371+ // A successful decode is ALWAYS pixel-compared; the hit
3372+ // counter only decides whether the attempt counts toward
3373+ // the hit-asserting total (class
3374+ // [[gate-skips-on-its-own-failure]]: the old `continue`
3375+ // here let 16/70 decoded attempts past without any pixel
3376+ // check at all).
3377+ let counted = crate::decode::palette_rect_hits() != before;
3378+ if !counted {
3379+ eprintln!(
3380+ "{NAME}: {source} cq={cq} decoded without ever landing a rect \
3381+ palette block (palette_rect_hits unchanged) -- pixel-compared, \
3382+ not counted toward the hit assertion"
3383+ );
3384+ }
3385+ let frame_count = frames.len();
3386+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3387+ if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
3388+ got.y != want.y || got.u != want.u || got.v != want.v
3389+ }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
3390+ {
3391+ std::fs::write(&path, &stream).expect("writing pinned stream");
3392+ eprintln!(
3393+ "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
3394+ );
3395+ }
3396+ for i in 0..frame_count {
3397+ assert_eq!(
3398+ frames[i].y, ffmpeg_frames[i].y,
3399+ "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
3400+ );
3401+ assert_eq!(
3402+ frames[i].u, ffmpeg_frames[i].u,
3403+ "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
3404+ );
3405+ assert_eq!(
3406+ frames[i].v, ffmpeg_frames[i].v,
3407+ "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
3408+ );
3409+ }
3410+ if counted {
3411+ matched += 1;
3412+ } else {
3413+ uncounted_exact += 1;
3414+ }
3415+ }
3416+ }
3417+ }
3418+ assert!(
3419+ matched > 0,
3420+ "{NAME}: no attempt out of {attempts} ever landed a matching rect palette \
3421+ block ({named_refusals} named refusals) -- palette_rect_hits never proven \
3422+ pixel-exact"
3423+ );
3424+ eprintln!(
3425+ "{NAME}: {matched}/{attempts} attempts matched pixel-exact, \
3426+ {uncounted_exact} decoded-and-pixel-exact but uncounted, {named_refusals} \
3427+ named refusals, palette_rect_hits={}",
3428+ crate::decode::palette_rect_hits()
3429+ );
3430+ }
3431+
3432+ /// The BROAD case (lane-palette2 r6, per its charter): a HORZ/VERT intra
3433+ /// strip in a screen-content-tools frame that does NOT necessarily use a
3434+ /// palette. This is what the refusal r4 removed actually guarded --
3435+ /// [`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`] above
3436+ /// gates the rarer "and picks a palette" case, which r5 measured RD
3437+ /// almost never chooses -- 39/70 of that same sweep DID land here (a
3438+ /// clean rect-strip decode with `palette_rect_hits` unchanged), just
3439+ /// uncounted by r5's narrower assertion. Same `--min/max-partition-size=64`
3440+ /// recipe r5 measured live to dodge the 32x32-level AB-partition quirk
3441+ /// ([[lane-sbpart-r2]]), single key frame, size/cq sweep. HARD-asserts
3442+ /// [`decode::rect_screen_content_hits`] moved -- proof this stream
3443+ /// actually ran [`read_intra_mode_rect`]'s screen-content-tools branch --
3444+ /// before comparing pixels.
3445+ #[test]
3446+ fn a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact() {
3447+ const NAME: &str = "a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact";
3448+ let _gate_lock = lock_gate_counters();
3449+ if !have_ffmpeg() {
3450+ eprintln!("SKIP {NAME}: no ffmpeg");
3451+ return;
3452+ }
3453+ if !have_aomenc() {
3454+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
3455+ return;
3456+ }
3457+ let mut matched = 0u32;
3458+ // Blocks that reconstructed a palette-Y prediction through a SPLIT
3459+ // luma transform (lane-palette2 r7's lifted refusal): the same
3460+ // screen-content streams exercise it, so this gate proves both.
3461+ let mut split_palette_matched = 0u32;
3462+ let mut uncounted_exact = 0u32;
3463+ let mut named_refusals = 0u32;
3464+ let mut attempts = 0u32;
3465+ let sizes = [(64, 128), (128, 64), (128, 128), (128, 192), (192, 192)];
3466+ let cqs = [5u32, 15, 25, 35, 45, 55, 63];
3467+ for src_name in ["smptebars", "rgbtestsrc"] {
3468+ for (width, height) in sizes {
3469+ for cq in cqs {
3470+ attempts += 1;
3471+ let source = format!("{src_name}=size={width}x{height}:rate=25");
3472+ let y4m = Command::new("ffmpeg")
3473+ .args([
3474+ "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p",
3475+ "-t", "0.04", "-f", "yuv4mpegpipe", "-",
3476+ ])
3477+ .stdin(Stdio::null())
3478+ .stdout(Stdio::piped())
3479+ .stderr(Stdio::piped())
3480+ .output()
3481+ .expect("ffmpeg failed to run");
3482+ assert!(
3483+ y4m.status.success(),
3484+ "ffmpeg fixture: {}",
3485+ String::from_utf8_lossy(&y4m.stderr)
3486+ );
3487+ let cq_arg = format!("--cq-level={cq}");
3488+ let mut child = Command::new(aomenc_path())
3489+ .args([
3490+ "--codec=av1",
3491+ "--passes=1",
3492+ "--end-usage=q",
3493+ &cq_arg,
3494+ "--cpu-used=4",
3495+ "--threads=1",
3496+ "--row-mt=0",
3497+ "--sb-size=64",
3498+ "--enable-palette=1",
3499+ "--min-partition-size=16",
3500+ "--max-partition-size=64",
3501+ "--obu",
3502+ "-o",
3503+ "-",
3504+ "-",
3505+ ])
3506+ .stdin(Stdio::piped())
3507+ .stdout(Stdio::piped())
3508+ .stderr(Stdio::piped())
3509+ .spawn()
3510+ .expect("aomenc failed to start");
3511+ child
3512+ .stdin
3513+ .take()
3514+ .expect("aomenc stdin")
3515+ .write_all(&y4m.stdout)
3516+ .expect("writing y4m to aomenc");
3517+ let out = child.wait_with_output().expect("aomenc failed to run");
3518+ assert!(
3519+ out.status.success(),
3520+ "aomenc refused the fixture ({source} cq={cq}): {}",
3521+ String::from_utf8_lossy(&out.stderr)
3522+ );
3523+ let stream = out.stdout;
3524+ let before = crate::decode::rect_screen_content_hits();
3525+ let split_before = crate::decode::palette_split_tx_hits();
3526+ let frames = match decode_stream(&stream) {
3527+ Err(e) => {
3528+ let msg = e.to_string();
3529+ assert!(
3530+ msg.contains("unsupported"),
3531+ "{NAME} failed outright, not a named refusal \
3532+ ({source} cq={cq}): {msg}"
3533+ );
3534+ named_refusals += 1;
3535+ eprintln!("{source} cq={cq}: refusal: {msg}");
3536+ continue;
3537+ }
3538+ Ok(frames) => frames,
3539+ };
3540+ // Same integrity rule as the palette gate above: decoded
3541+ // means pixel-compared, counter or no counter.
3542+ let counted = crate::decode::rect_screen_content_hits() != before;
3543+ if !counted {
3544+ eprintln!(
3545+ "{NAME}: {source} cq={cq} decoded without ever running the rect \
3546+ screen-content path (rect_screen_content_hits unchanged) -- \
3547+ pixel-compared, not counted toward the hit assertion"
3548+ );
3549+ }
3550+ let frame_count = frames.len();
3551+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
3552+ if frames.iter().zip(&ffmpeg_frames).any(|(got, want)| {
3553+ got.y != want.y || got.u != want.u || got.v != want.v
3554+ }) && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
3555+ {
3556+ std::fs::write(&path, &stream).expect("writing pinned stream");
3557+ eprintln!(
3558+ "EC_AV1_GATE_DUMP: wrote mismatching stream ({source} cq={cq}) to {path}"
3559+ );
3560+ }
3561+ for i in 0..frame_count {
3562+ assert_eq!(
3563+ frames[i].y, ffmpeg_frames[i].y,
3564+ "{NAME}: {source} cq={cq} frame {i} luma vs ffmpeg"
3565+ );
3566+ assert_eq!(
3567+ frames[i].u, ffmpeg_frames[i].u,
3568+ "{NAME}: {source} cq={cq} frame {i} U vs ffmpeg"
3569+ );
3570+ assert_eq!(
3571+ frames[i].v, ffmpeg_frames[i].v,
3572+ "{NAME}: {source} cq={cq} frame {i} V vs ffmpeg"
3573+ );
3574+ }
3575+ if counted {
3576+ matched += 1;
3577+ } else {
3578+ uncounted_exact += 1;
3579+ }
3580+ if counted && crate::decode::palette_split_tx_hits() > split_before {
3581+ split_palette_matched += 1;
3582+ }
3583+ }
3584+ }
3585+ }
3586+ assert!(
3587+ split_palette_matched > 0,
3588+ "{NAME}: no pixel-exact attempt ever reconstructed a palette block with a \
3589+ split luma transform -- the lifted refusal is ungated"
3590+ );
3591+ assert!(
3592+ matched > 0,
3593+ "{NAME}: no attempt out of {attempts} ever landed a matching rect \
3594+ screen-content block ({named_refusals} named refusals) -- \
3595+ rect_screen_content_hits never proven pixel-exact"
3596+ );
3597+ eprintln!(
3598+ "{NAME}: {matched}/{attempts} attempts matched pixel-exact \
3599+ ({split_palette_matched} of them through a split-transform palette block), \
3600+ {uncounted_exact} decoded-and-pixel-exact but uncounted, \
3601+ {named_refusals} named refusals, rect_screen_content_hits={}, \
3602+ palette_split_tx_hits={}",
3603+ crate::decode::rect_screen_content_hits(),
3604+ crate::decode::palette_split_tx_hits()
3605+ );
3606+ }
3607+
3264 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s3608 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
3265 /// harness, but with the deblocking filter left *on* (no3609 /// harness, but with the deblocking filter left *on* (no
3266 /// `--loopfilter-control=0`) at a crf high enough that libaom actually3610 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
lanes/COMMON-20260901.mdmodified+7 -0
@@ -93,3 +93,10 @@ name you started). `pkill -f`/`killall` on cargo/ec_av1 patterns is forbidden.
93 ## NEVER `cargo fmt` IN A LANE (3 lanes lost their diffs to it on 2026-09-02)93 ## NEVER `cargo fmt` IN A LANE (3 lanes lost their diffs to it on 2026-09-02)
94 main is not rustfmt-clean (~6000 lines of churn). Hand-indent; `cargo test --no-run` is the check.94 main is not rustfmt-clean (~6000 lines of churn). Hand-indent; `cargo test --no-run` is the check.
95 If you ran it: extract your own hunks, `git checkout -- crates/`, re-apply.95 If you ran it: extract your own hunks, `git checkout -- crates/`, re-apply.
96+
97+## MEMORY (user order 2026-09-02: an unsteady box fails the job)
98+30 GB box shared by ~10 agents. Every decode/encode/probe invocation runs under
99+`systemd-run --user --scope -q -p MemoryMax=6G <cmd>`; suites under a unit with `-p MemoryMax=10G`;
100+never two suites per lane; film extracts ≤2 s; a watchdog (`ec-memwatch` user unit, log
101+`$HOME/.cache/ec-memwatch.log`) SIGKILLs any codec/test process above 6 GiB RSS or the largest one
102+when MemAvailable < 3 GiB — a killed run means YOUR command exceeded the budget: bound it, do not retry as-is.
lanes/palette2-r10.report.mdadded+113 -0
@@ -0,0 +1,113 @@
1+# lane-palette2 r10 — merged main 06d856d, fixed the U-plane palette defect; full suite finds ONE lane regression
2+
3+VERDICT: AMBER (corrected after the full suite ran; the first draft said GREEN off a 6-test
4+filter run). The chartered work is done — the failing cell decodes pixel-exact and both palette
5+gates, split_transform, tx_select, refusal_inventory and gate_coverage pass — but the full
6+`cargo test -p ec-av1 --lib` is 294 passed / 2 failed / 27 ignored, and one of those two
7+failures is a gate this lane REGRESSES. See STEP 4.
8+
9+## STEP 1 — merge main 06d856d (commit 29bbbcd)
10+Two conflicts, resolved exactly as chartered:
11+- `crates/ec-av1/src/decode.rs` `reconstruct_rect` (~5892): kept this lane's `PALETTE_PRED`
12+ override wrapper; main's `EC_DEBUG_EDGES` eprintln moved inside the `else`, after
13+ `edges_rect` (it needs `above`/`left`, which only exist there).
14+- `crates/ec-av1/src/refusal_inventory.rs` (~50): main's list, minus
15+ `"a HORZ/VERT intra strip in a screen-content frame ..."` (this lane lifted it; auto-merge had
16+ already dropped `"a palette block with a split luma transform (round 1)"`), plus this lane's two
17+ palette strings; main's `"a superblock-level 1:4 partition ..."` kept, the lane's stale
18+ `"other than NONE or SPLIT"` copy dropped.
19+`cargo check -p ec-av1` clean.
20+
21+## STEP 2 — the defect (class [[refusal-hides-a-defect]]), root-caused and fixed
22+Reproduced on the merged tree exactly as chartered (aomenc `--cq-level=45 --cpu-used=4
23+--sb-size=64 --min-partition-size=16 --max-partition-size=64 --enable-palette=1`,
24+smptebars 192x192, sha256 `d1baf950...`): **U 512 bytes wrong, x48..55 y0..63 chroma
25+(max |d| 28), Y and V exact.**
26+
27+The charter's suspect (a stale `PALETTE_PRED` thread-local) was DISPROVED first:
28+`EC_DEBUG_PAL=1` counted 32 arms and 32 consumptions, `stale=false` on every arm.
29+
30+Real root cause, `crates/ec-av1/src/decode.rs:4486` — `decode_block_rect`'s split-transform arm
31+(`depth != 0`) calls `decode_rect_split` and then `return Ok(())`, **before** the fn's tail that
32+stamps `record_palette_y_rect` / `record_palette_uv_rect`. So a split-tx rect strip left the
33+above/left palette arrays holding a DEAD block's size+colours. Traced live: the 32x16 strip at
34+luma (64,0) never recorded, so the next block (32x32 at luma (96,0), chroma 16x16 at (48,0))
35+read `palette_uv_cache = [44, 156]` — the palette of the block at luma (48,0), three blocks back —
36+where libaom's cache starts at 72. Cache LENGTH matched, so the same `literal(1)` hit bits and the
37+same 8-bit literal were read: **the entropy stream stayed in sync and only the pixels of that
38+palette block were wrong** (colour 0 = 44 instead of 72, hence exactly one 8x64 chroma column, and
39+its vertical propagation down the column). V is exact because V colours are never cached.
40+
41+FIX (decode.rs:4482..4497): stamp the same two palette records at the early return.
42+Sweep for the same shape: `4486` is the ONLY `return Ok(())` in any `decode_block*` /
43+`decode_leaf*` fn (`grep -n 'return Ok(())' decode.rs` over 3800..7100 → one hit), so this is the
44+whole class here.
45+
46+Instrument kept (charter's set/take symmetry ask): all 20 `PALETTE_PRED` set sites and both take
47+sites now go through `set_palette_pred` / `take_palette_pred` (decode.rs ~1052), which under
48+`EC_DEBUG_PAL=1` print every arm (with `#[track_caller]` location and a `stale=` flag showing an
49+unconsumed predecessor) and every consumption. That is what disproved the stale-thread-local
50+hypothesis in one run; ad-hoc probes were removed.
51+
52+## STEP 3 — gates (EC_AV1_REQUIRE_AOMENC=1, --test-threads=1)
53+```
54+cd /home/user/Documents/Code/Rust/edith_codecs-palette2
55+export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1
56+cargo test -p ec-av1 --lib -j3 -- --test-threads=1 \
57+ a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \
58+ a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact \
59+ refusal_inventory gate_coverage split_transform tx_select
60+```
61+→ **14 passed, 0 failed, 1 ignored** (133.29s). The ignored one is main's own
62+`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`
63+(lane-rectsplit r3 RED at seed 50, not this lane's).
64+- `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`: **40/70 matched pixel-exact**
65+ (r9: 17/70), 30 decoded-and-pixel-exact but uncounted, **0 named refusals** (r9: 32),
66+ `palette_rect_hits=142`.
67+- `a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`: **47/70 matched**
68+ (31 through a split-transform palette block), 23 uncounted-exact, 0 named refusals,
69+ `rect_screen_content_hits=355`, `palette_split_tx_hits=627`.
70+- All 70 attempts per gate now decode AND are pixel-compared; 0 mismatches.
71+
72+## EVIDENCE
73+EVIDENCE: scratchpad/r10.obu (211 B, sha256 d1baf9503c5787d1005d358d36767195279c36c12255d10e25af106ee5849545) + r10.yuv vs ff.yuv | `decode_probe` dump vs `ffmpeg -f obu -i r10.obu -f rawvideo -pix_fmt yuv420p`, before and after the fix | before: U 512 px wrong (x48..55, y0..63, max |d| 28), Y+V exact; after: `cmp -l` = 0 bytes
74+EVIDENCE: scratchpad/pal.log (EC_DEBUG_PAL=1 trace of the same stream) | 32 PALSET / 32 PALTAKE lines | every arm `stale=false` — the charter's stale-thread-local suspect disproved, not patched around
75+EVIDENCE: scratchpad/pal4.log + pal5.log | per-block `palette_uv_cache` and palette-record trace | block r=0 c=6 (luma 96,0) read cache [44,156] stamped by luma (48,0); the strip at luma (64,0) has NO record line — the missing stamp
76+EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1), 6 filters | full 70-attempt sweep on both palette gates | 14 passed, 0 failed, 1 ignored, 133.29s
77+
78+
79+## STEP 4 — full suite on the merged tree (the r10 restart's only new work)
80+```
81+cd /home/user/Documents/Code/Rust/edith_codecs-palette2
82+EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j3 -- --test-threads=1
83+# log: $HOME/.cache/palette2-suite.log
84+```
85+→ **294 passed; 2 failed; 27 ignored** (1390.10s).
86+
87+Both failures were attributed against the merge base by building 06d856d in a detached
88+worktree (own CARGO_TARGET_DIR) and running the same two test names there:
89+
90+1. `decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule` — **INHERITED, not this lane.**
91+ FAILS identically at 06d856d (`32x64 nz_map offset at display (row 0, col 2) left: 6 right: 11`).
92+ `git diff 06d856d HEAD` touches neither `cdf.rs` (0 lines) nor this test. Diagnosis: the test
93+ reads `table[col][row]` while the live consumer (`decode.rs:1804`) reads
94+ `table[row.min(4)][col.min(4)]`; commit 44e8768 transposed the two tables and left the test on
95+ the old layout, so **the test is the stale half** — 24 of the 50 cells disagree, exactly a
96+ transposition. NOT fixed here: this lane owns neither the table nor the orientation question
97+ (decode.rs:1785-1795 records the orientation as still unproven), and flipping the test to
98+ `[row][col]` would only pin the current storage. `deferred: nz_map test/consumer layout —
99+ inherited from main, orientation itself unproven — needs the lane that owns the rect nz_map
100+ orientation`.
101+2. `stream::tests::a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact`
102+ — **THIS LANE REGRESSES IT.** PASSES at 06d856d, FAILS on lane-palette2 HEAD:
103+ `seed 46 first luma mismatch at (188, 62) ours=116 ffmpeg=115 -- 2242 mismatching samples,
104+ bbox x 135..=191 y 62..=127` (stream.rs:12360). Values differ by 1 over a contiguous region =
105+ a prediction/reconstruction difference, not an entropy desync. The gate is new on main
106+ (lane-fistrip), so it never ran against this lane's rect-strip work until the r10 merge; the
107+ suspects are the lane's `read_intra_mode_rect` / `decode_block_rect` / `reconstruct_rect`
108+ changes (492 inserted lines vs the base), starting with the merge-resolved `PALETTE_PRED`
109+ override wrapper in `reconstruct_rect` and the r7 per-TU palette window.
110+ `fix-now: r11 — do not merge this lane into main until seed 46 is exact.`
111+
112+EVIDENCE: $HOME/.cache/palette2-suite.log | `EC_AV1_REQUIRE_AOMENC=1 ec_av1 --test-threads=1` on lane-palette2 HEAD (merged tree) | test result: FAILED. 294 passed; 2 failed; 27 ignored; 1390.10s
113+EVIDENCE: detached worktree at 06d856d (scratchpad/base06d, CARGO_TARGET_DIR=~/.cache/cargo-target-palette2-base) | same binary run with the two failing test names | `nz_map... FAILED` (identical message) + `filter_intra_on_a_horz_vert_strip ... ok` — 1 passed; 1 failed
lanes/palette2-r11.report.mdadded+112 -0
@@ -0,0 +1,112 @@
1+# lane-palette2 r11 -- merged main 096f4b8; the "regression" is a pre-existing defect the lifted refusal was hiding, localized to one block
2+
3+VERDICT: AMBER. STEP 1 (merge) done and committed. STEP 2 (seed 46) NOT fixed:
4+root cause is *not* the lane's palette code -- the entropy stream of seed 46 is
5+bit-exact against libaom for every symbol of the frame, and the mismatch is a
6+pure reconstruction defect in the last superblock of a screen-content frame,
7+which main never decodes because it refuses that frame class outright. The gate
8+stays RED; the lane must not merge until it is green.
9+
10+## STEP 1 -- merge main 096f4b8 (commit eb9472d)
11+`git merge --no-commit --no-ff main` -> one conflict only (`refusal_inventory.rs`);
12+`decode.rs`/`stream.rs`/`cdf.rs` auto-merged.
13+- `cdf.rs`: `git diff main -- crates/ec-av1/src/cdf.rs` = EMPTY, so main's NZ_MAP
14+ tables are byte-for-byte; main's deletion of
15+ `nz_map_ctx_offset_tables_match_the_rect_rule` taken (only
16+ `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
17+ remains, and it passes).
18+- `refusal_inventory.rs`: kept main's `"a superblock-level partition value
19+ outside PARTITION_NONE..PARTITION_VERT_4"` + the lane's two palette strings;
20+ dropped three strings no longer emitted by any `unsupported(` site (the
21+ superblock 1:4 partition, `LAST_FRAME (round 2)`, `palette block with a split
22+ luma transform (round 1)`) and main's screen-content strip string (the lane
23+ lifted it; only a comment mentions it now). `refusal_inventory` +
24+ `gate_coverage` green.
25+- `decode.rs` fix required by the merge (`decode_block_rect64`, main's SB-level
26+ 1:4/HORZ-VERT path, ~decode.rs:5265): main's `RectStripModes` literal there
27+ lacked the lane's `palette_y`/`palette_uv` fields (compile error), and its
28+ split-tx early return had no palette neighbour stamp -- the SAME shape r10
29+ root-caused in `decode_block_rect`. Both applied, plus the
30+ `PALETTE_SPLIT_TX_HITS` bump, so the class is closed at both sites (`grep -n
31+ 'return Ok(())'` in the rect decoders: 2 hits, both stamped).
32+- NOTE: main moved to `5d33392` (lane-sub8merge, mi-granular y/uv mode maps)
33+ WHILE this round ran. This lane is merged with 096f4b8, not 5d33392.
34+ `deferred: merge main 5d33392 -- appeared mid-round -- next round's STEP 1`.
35+
36+## STEP 2 -- seed 46: what it actually is
37+Regenerated exactly (aomenc recipe copied from the gate, seed 46 gradients):
38+`s46.obu` 146 B, sha256 `a109adab439706035728f9348aba0801e06afa1f571540ce433a103a94377421`.
39+
40+1. **The entropy stream is exact.** `EC_TRACE_MODE_STEP=1` ladders from ours and
41+ from the instrumented aomdec, aligned symbol by symbol (284 aomdec ISTEP
42+ lines vs our 270 -- the 14-line gap is only the 8 rect strips, whose
43+ `use_filter_intra`/`tx_depth` we print under `TRACE_RECT_*` instead):
44+ **every common (name, value, range) triple matches**, including the rect
45+ strips' own values read back from `TRACE_RECT_IMODE` (e.g. mi(8,40)
46+ tx_depth rng=50787 on both sides). So the lifted screen-content refusal did
47+ NOT introduce a desync: our rect palette syntax reads consume exactly what
48+ libaom consumes (8 strips, all `allow_screen_content_tools=1`, all
49+ `use_palette=0`).
50+2. **It is reconstruction, and it is not the loop filter.** `EC_AV1_PREFILT_DUMP`
51+ ours vs aomdec: 2165 luma samples already wrong before filtering (post-filter
52+ 2242), bbox x136..191 y64..127 -- i.e. exactly the FRAME'S LAST SUPERBLOCK
53+ (128,64). Every other superblock, including the right-edge SB(128,0) and the
54+ bottom-row SB(0,64)/(64,64), is byte-exact.
55+3. **First wrong block pinned.** In decode order the first defective block is the
56+ TL 16x16 of a 32x32 `PARTITION_VERT_A` at px(128,64) (aomdec
57+ `EC_IMODE mi_row=16 mi_col=32 bsize=6`, mode 7 = D203_PRED, uv 7, skip=0,
58+ tx_depth=0). Its error is a 25-pixel diagonal wedge in rows 68..71,
59+ x136..143, deltas +7..-116; the two 16x16 above it and everything left of
60+ x128 are exact. The wedge then propagates: 16x32 strip at (144,64) 246/512,
61+ 16x16 (160,64) 141/256, (176,64) 194/256, 32x16 (160,80) 512/512, 32x32
62+ (160,96) 1024/1024; the 32x32 at (128,96) is 0/1024.
63+4. Suspects RULED OUT this round: the `PALETTE_PRED` override wrapper and the
64+ per-TU palette window (no block in this stream uses a palette -- every
65+ `palette_y_mode`/`palette_uv_mode` symbol reads 0, so `set_palette_pred` is
66+ never called); filter intra (`use_filter_intra` = 0 on every strip here);
67+ any entropy-side cause (point 1); the loop filter (point 2). Availability was
68+ checked by hand against `has_bottom_left` in the oracle source
69+ (`~/.cache/aom-oracle/src/av1/common/reconintra.c`): for that TL block
70+ `blk_col_in_sb == 0`, so libaom takes the leftmost-column branch
71+ (`row_off_in_sb + 4 < 16` -> available) and never reaches the
72+ partition-keyed `has_bl_table`; our `Reach::bottom_left`'s `col == 0` branch
73+ returns the same, so the `VERT_AB_PARTITION` guard is NOT implicated for
74+ this block.
75+ `fix-now: r12 -- next step is to dump the TL block's prediction and residual
76+ separately (EC_DEBUG_EDGES + EC_TRACE_COEFF) against libaom's; the wedge
77+ shape with the entropy stream exact points at the inverse transform's
78+ tx_type/scan for a D203 16x16 in the corner superblock, or at the intra edge
79+ filter/upsample decision, not at availability.`
80+
81+## Files changed
82+- `crates/ec-av1/src/decode.rs` -- `decode_block_rect64` split-tx arm: palette
83+ prediction fields + palette neighbour stamp at the early return.
84+- `crates/ec-av1/src/refusal_inventory.rs` -- merge resolution (list above).
85+
86+## EVIDENCE
87+EVIDENCE: scratchpad/s46.obu (146 B, sha256 a109adab4397...) + aomstep.log/ourstep.log | `EC_TRACE_MODE_STEP=1` on instrumented aomdec and on `decode_probe`, aligned by (mi_row, mi_col, name) | every common triple identical; only the 14 rect-path lines we print under other names are missing -- entropy exact
88+EVIDENCE: scratchpad/ourpre.yuv.f0 vs aompre.yuv.f0 | `EC_AV1_PREFILT_DUMP` both decoders, same stream | 2165 luma samples differ, bbox x136..191 y64..127 (the last superblock only); post-filter 2242, so the loop filter is not the source
89+EVIDENCE: scratchpad (per-block diff map) | counted prefilter diffs inside every block aomdec reported for SB(128,64) | first defective block = TL 16x16 at px(128,64) of a 32x32 VERT_A, 25/256 wrong, wedge rows 68..71
90+
91+## STEP 3 -- full suite on the merged tree
92+```
93+systemd-run --user --unit=palette2-suite-r11-1788310477 -p MemoryMax=10G --same-dir \
94+ bash -lc 'EC_NOMEMGUARD=1 EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 \
95+ nice -n 10 cargo test -p ec-av1 --lib -j3 -- --test-threads=1 \
96+ > $HOME/.cache/palette2-suite-r11.log 2>&1'
97+```
98+-> **306 passed; 1 failed; 26 ignored** (735.05s). r10 was 294/2/27.
99+The ONE failure is this lane's known red gate,
100+`stream::tests::a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact`
101+(seed 46, message unchanged). r10's second failure,
102+`decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule`, is gone: main deleted that
103+stale test and the merge took the deletion. Both palette gates, `filter_intra_*`,
104+`split_transform_*`, `superblock_level_*`, the tiny sweep, `tx_select`, `refusal_inventory`,
105+`gate_coverage` and `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
106+all pass inside that run.
107+
108+`fix-now: r12 -- the lane does not merge into main until seed 46 is pixel-exact (see STEP 2
109+for the localization; it is a reconstruction defect behind the refusal this lane lifted, not
110+an entropy or palette defect).`
111+
112+EVIDENCE: $HOME/.cache/palette2-suite-r11.log | full `cargo test -p ec-av1 --lib -- --test-threads=1` under systemd unit palette2-suite-r11-1788310477 on the merged tree (b79b698) | test result: FAILED. 306 passed; 1 failed; 26 ignored; 735.05s -- the single failure is the seed-46 gate
lanes/palette2-r12.report.mdadded+90 -0
@@ -0,0 +1,90 @@
1+# lane-palette2 r12 -- root cause of seed 46: a transform unit inside a block used the standalone-block reach tables
2+
3+VERDICT: GREEN on the defect. Merge with main `4a29b4e` committed (`ed07bdc`),
4+seed-46 gate RED -> GREEN (`e8cc1c2`), full-suite totals below.
5+
6+## STEP 1 -- merge main 4a29b4e (commit ed07bdc)
7+`git merge --no-commit --no-ff main` -> 5 conflicts, all in `decode.rs`
8+(`refusal_inventory.rs`/`stream.rs`/`cdf.rs` auto-merged clean).
9+All five are the same shape: main's sub8merge mi-granular neighbour maps
10+(`modes_above_left`, `record_mode_mi`, `record_uv_mode_mi`) against the lane's
11+palette reads/refusals/stamps in `decode_block_rect` and `decode_block_rect64`.
12+Resolution: BOTH sides at every hunk -- main's `modes_above_left(r, c)` replaces
13+the lane's `above_mode[c]`/`left_mode[r]` cell reads (that is exactly the
14+mi-granular fix), the lane's palette ctx/cache + refusals + neighbour stamps
15+kept, main's `EC_AV1_RECTX_TRACE` print kept.
16+`refusal_inventory` 3/3 and `gate_coverage` 9/9 green on the merged tree.
17+
18+## STEP 2 -- seed 46 root cause (commit e8cc1c2)
19+Premise re-measured, not inherited: regenerated `s46.obu` from the gate recipe
20+(seed 46 gradients, sha256 `a109adab4397...`, 146 B, same hash as r11) and
21+re-ran the gate on the merged tree -- still RED, same 2242 samples.
22+
23+r11 had ruled out entropy, the loop filter, palette and filter intra, and had
24+verified block-level `has_bottom_left` by hand. What it could not see is that
25+the block is NOT predicted as one 16x16: added an `EC_PRED` rung to the oracle
26+(`~/.cache/aom-oracle/src/av1/common/reconintra.c`, printing
27+`mi_row/mi_col/plane/row_off/col_off/txw/txh/mode/p_angle/have_*/n_top/n_left/n_tr/n_bl/bsize/partition`)
28+and aomdec reports the TL 16x16 as FOUR 8x8 luma TUs:
29+
30+ EC_PRED mi_row=16 mi_col=32 plane=0 row_off=0 col_off=0 txw=8 txh=8 mode=7 p_angle=200 n_top=8 n_left=8 n_tr=-1 n_bl=8 bsize=6 part=6
31+ EC_PRED mi_row=16 mi_col=32 plane=0 row_off=0 col_off=2 ... n_bl=0
32+ EC_PRED mi_row=16 mi_col=32 plane=0 row_off=2 col_off=0 ... n_bl=8
33+ EC_PRED mi_row=16 mi_col=32 plane=0 row_off=2 col_off=2 ... n_bl=0
34+
35+`n_bl=0` for both `col_off > 0` units: libaom's `has_bottom_left` returns 0
36+outright there. Our `decode_block` multi-TU branch built the unit's reach with
37+`Reach::of(logical_tx, tu_px, tu_py, ..)` -- the STANDALONE-BLOCK tables at the
38+unit's position (with `VERT_AB_PARTITION` set, `has_bl_vert_8x8` bit 1 = 1), so
39+the top-right 8x8 unit read 8 bottom-left samples libaom never gives it. That
40+is the 25-pixel diagonal wedge at rows 68..71 x136..143 (D203 = zone 3, reads
41+down-left), which then propagated across the last superblock.
42+
43+FIX: `Reach::of_tu(bw, bh, col_off, row_off, tx, block_reach)` in `encode.rs`
44+(the TU branches of both libaom functions, one place), used at all three
45+per-TU sites:
46+- `decode.rs` `decode_block` multi-TU branch (the defect),
47+- `decode.rs` `decode_leaf8`'s 2x2 grid of 4x4 TUs (same shape, same fix),
48+- `decode.rs` `decode_rect_split` (had the rule inline since lane-rectsplit r1;
49+ now shares it -- one transcription, not three).
50+CLASS SWEEP: every other `Reach::of(...)` in `decode.rs` is a whole block or a
51+whole chroma block (4x4 leaf, 8x8 chroma group), not a unit inside one -- those
52+are correct and untouched.
53+
54+## Files changed
55+- `crates/ec-av1/src/encode.rs` -- `Reach::of_tu` + `Debug` on `Reach`; new test
56+ `of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit`.
57+- `crates/ec-av1/src/decode.rs` -- three per-TU reach sites through `of_tu`;
58+ merge resolution in `decode_block_rect`/`decode_block_rect64`.
59+- `crates/ec-av1/src/refusal_inventory.rs` -- merge (auto).
60+
61+## Gates
62+- `a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact`
63+ (seed 46 is the regression pin): `cargo test -p ec-av1 --lib filter_intra_on_a_horz_vert_strip`
64+ -> `ok. 1 passed` (was FAILED with 2242 mismatching samples).
65+- `encode::tests::of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit`:
66+ enumerates 10 block shapes x tx in {4,8,16,32} x every (row_off, col_off) x both
67+ block-level answers against an MI-unit transcription of libaom's
68+ `has_top_right`/`has_bottom_left` -> ok.
69+
70+## EVIDENCE
71+EVIDENCE: scratchpad/aompred.log (EC_PRED rung added to reconintra.c) | `EC_PRED=1 aomdec s46.obu`, grep `mi_row=16 mi_col=32` | the 16x16 D203 block is four 8x8 luma TUs with n_bl = 8,0,8,0 -- the two `col_off>0` units get NO bottom-left
72+EVIDENCE: scratchpad/s46.obu (146 B, sha256 a109adab4397...) | regenerated from the gate recipe, `cargo test -p ec-av1 --lib filter_intra_on_a_horz_vert_strip` before/after the `of_tu` change | 2242 mismatching luma samples -> 0, test FAILED -> ok
73+
74+## Full suite (merged tree, after the fix)
75+`systemd-run --user --unit=palette2-suite-r12-1788311147 ... cargo test -p ec-av1 --lib`
76+-> `$HOME/.cache/palette2-suite-r12.log`:
77+`test result: ok. 314 passed; 0 failed; 27 ignored; 0 measured; finished in 317.39s`
78+(r11 on the pre-merge tree: 306 passed / 1 failed / 26 ignored). Siblings named in
79+the charter -- both palette gates, superblock_level_ab, ab_partition,
80+split_transform_*, the tiny sweep, refusal_inventory, gate_coverage,
81+base_ctx_rect_offsets -- are all inside that run and all pass.
82+
83+## Residue
84+- `deferred: a dedicated directional-mode AB-partition gate arm (D203/D157/D67 at SB
85+ column 0, --enable-ab-partitions=1, 8/10-bit) -- the seed-46 stream already pins the
86+ exact fixed path (VERT_A + D203 + split-TU at SB column 0) as a real-aomenc pixel gate
87+ and the new enumeration test covers the rule over its whole domain, so a second stream
88+ would add cost, not coverage -- unblocks by a round with budget for a new gate recipe`.
89+- `accepted: the EC_PRED rung now lives in ~/.cache/aom-oracle/src (oracle tree, not this
90+ repo); scripts/instrument-aom-oracle.sh does not yet install it`.
lanes/palette2-r3.report.mdadded+3 -0
@@ -0,0 +1,3 @@
1+# see lanes/palette2-r7.report.md
2+
3+The charter labelled this round "r3"; the branch was already at r6, so the report is filed as r7.
lanes/palette2-r4.charter.mdadded+52 -0
@@ -0,0 +1,52 @@
1+# lane-palette2 r4 — palette on a rectangular strip, from a clean base
2+
3+At main (8440024). **I reset this branch to main.** r3's in-flight edits are
4+preserved at tag `palette2-r3-wip` if you want to look, but they conflicted with
5+the u16 sample widen that has since landed, and they were mid-mechanical-edit
6+(threading `allow_intrabc` through four call sites) rather than hard-won
7+knowledge. Start fresh; re-doing that plumbing on top of the widen is cheaper
8+than untangling it.
9+
10+Read `lanes/palette2-r1.charter.md` for the lane's scope. Step 1 (UV palette) is
11+CLOSED and merged. This round is step 2:
12+
13+ "a HORZ/VERT intra strip in a screen-content frame
14+ (palette syntax is consumed for square blocks only)"
15+
16+`smptebars` and `rgbtestsrc` at plain default aomenc settings both stop exactly
17+there — that is measured, not assumed, so a real gate is easy to build.
18+
19+`palette_bsize_ctx` and the palette size/context derivation assume a square
20+block; libaom derives both from width AND height. Check what it actually does
21+for a rect block before adapting the square path. Two classes apply: a table
22+narrowed to a pinned row breaks when its indexing field moves
23+([[cdf-row-held-constant]]), and a neighbour context read from ONE cell is right
24+only under uniform block size — a strip needs a gathered span
25+([[context-read-from-one-cell]]).
26+
27+Note what a sibling lane just found in the same neighbourhood: libaom indexes
28+`av1_nz_map_ctx_offset` by the RAW, un-adjusted `tx_size`, and the 32x64/64x32
29+tables genuinely differ from the square one. If your rect-strip work touches a
30+size-indexed table, check whether libaom indexes it by the raw or the adjusted
31+size before assuming.
32+
33+Order: gate FIRST below `decode_stream`, hard-asserting the rect-strip palette
34+path fired; then the implementation; then lift the refusal and update
35+`refusal_inventory.rs` in the SAME commit. Declare every new refusal string you
36+add — `refusal_inventory`'s own test fails the build otherwise, and r3 left two
37+undeclared for me to clean up.
38+
39+Step 3 ("a palette block with a split luma transform", reached by `life`) only
40+if step 2 is committed green with budget to spare.
41+
42+## Budget discipline
43+75 turns, no reset on resume. At about turn 55, stop starting new work: commit
44+what is green and write your report.
45+
46+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`; foreground
47+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg
48+generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc
49+`--threads=1 --row-mt=0 --sb-size=64`. Oracle rung 12 is yours; the oracle is
50+SHARED, env-gated rungs only. Sibling worktrees have live agents — never build in
51+or edit them. Never push, never merge into main; I handle merges. End with
52+`lanes/palette2-r4.report.md`, VERDICT on line 1.
lanes/palette2-r5.charter.mdadded+41 -0
@@ -0,0 +1,41 @@
1+# lane-palette2 r5 — write the gate
2+
3+At 05f6db8. r4 implemented the rect-strip palette path and hit its cap with
4+"compiles clean, now let's write the gate test". I committed its tree verbatim;
5+**it compiles but is otherwise unverified by me, and it has NO gate**, which
6+means right now it is exactly the thing this project refuses to ship: a
7+capability claim with nothing behind it.
8+
9+## The job, in one sentence
10+Write the gate for what r4 built, and let it tell you whether r4 is right.
11+
12+Specifics:
13+- `smptebars` and `rgbtestsrc` at plain default aomenc settings both reach the
14+ rect-strip palette case — that is measured, so no fixture hunting is needed.
15+ Add `--enable-palette=1` explicitly: `gate_coverage.rs` only counts a tool as
16+ exercised on a positive flag.
17+- Drive the tile decode BELOW `decode_stream` so a surviving refusal cannot
18+ short-circuit the code you are measuring
19+ ([[refusal-short-circuits-its-own-code]]).
20+- Hard-assert that the rect-strip palette path actually fired before comparing
21+ pixels ([[gate-blind-to-feature]]) — a hit counter, not just a pixel match.
22+- Pixel-exact vs ffmpeg. If it mismatches, that is r4's implementation being
23+ wrong, which is a perfectly good outcome for this round: bisect it with a
24+ range ladder against the oracle (rung 12 is yours), and say so plainly.
25+- Only with the gate green: lift the refusal and update `refusal_inventory.rs`
26+ in the SAME commit. Check what r4 already changed in that file — it edited it
27+ without a gate, so treat its edits as unverified too.
28+
29+Do not start step 3 (palette with a split luma transform) this round.
30+
31+## Budget discipline
32+75 turns, no reset on resume. At about turn 55, stop starting new work: commit
33+what is green and write your report.
34+
35+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`; foreground
36+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg
37+generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc
38+`--threads=1 --row-mt=0 --sb-size=64`. The oracle is SHARED — env-gated rungs
39+only. Sibling worktrees have live agents — never build in or edit them. Never
40+push, never merge into main; I handle merges. End with
41+`lanes/palette2-r5.report.md`, VERDICT on line 1.
lanes/palette2-r5.report.mdadded+76 -0
@@ -0,0 +1,76 @@
1+VERDICT: BLOCKED — gate written and hard-asserting, but real aomenc RD never lands a rect-strip
2+palette block across the whole sweep; r4's implementation is neither confirmed nor refuted this
3+round, and the refusal is NOT lifted.
4+
5+## What I did
6+Wrote `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact` in
7+`crates/ec-av1/src/stream.rs` (after the existing square palette-Y/UV gates). It drives
8+`decode_stream` directly (below any refusal), hard-asserts `decode::palette_rect_hits()` moved
9+before comparing any pixels, and requires pixel-exactness vs `ffmpeg` on any attempt that both
10+decoded and fired the counter — exactly the charter's shape.
11+
12+## What the gate found, measured live this round
13+`smptebars`/`rgbtestsrc` at plain default aomenc settings (r1's measured recipe) do NOT reach a
14+clean rect-strip palette decode: every attempt hits an unrelated named refusal FIRST, almost
15+always a 32x32-level `HORZ_A`/`HORZ_B`/`VERT_A`/`VERT_B` partition (this decoder codes only
16+`NONE`/`SPLIT`/`HORZ`/`VERT` at that level) or filter-intra-on-a-strip. Confirmed live that
17+`--enable-ab-partitions=0` is INERT for this content/tune combo — two encodes differing only in
18+that flag produced byte-identical output (`md5sum` match) — the same aomenc quirk already
19+recorded in the ledger for SB-level AB
20+([[lane-sbpart-r2]]: "AB-at-64 not gated by that flag"), here reproduced one level down at 32x32.
21+
22+Forcing `--min-partition-size=64 --max-partition-size=64` sidesteps that 32x32-level code path
23+entirely (only `NONE`/`SPLIT`/`HORZ`/`VERT`/AB/1:4 remain, straight from `decode_block_rect64`),
24+and does produce many clean `OK` decodes across a 70-attempt sweep (2 sources x 5 sizes x 7 cq
25+levels, single key frame each, `--enable-palette=1`). But `palette_rect_hits` stayed at its
26+`before` value on every single one of them — the encoder's RD always prefers `PARTITION_NONE`
27+(whole-SB square palette, already gated by the existing `palette_y`/`palette_uv` tests) over a
28+`HORZ`/`VERT` split when palette is in play at this scale. The remaining ~31 attempts hit named
29+refusals, dominated by "a palette block with a split luma transform (round 1)" — r1's own
30+already-refused square case, not this round's.
31+
32+So the gate is real, hard, and currently RED for the right reason: it never got to compare a
33+single pixel because the capability it is meant to prove never actually fires against real
34+content, not because of a code defect it caught. This is different from a "mismatch to bisect"
35+outcome the charter anticipated — there is nothing to range-ladder yet because nothing decoded
36+through the rect-palette path to disagree with ffmpeg on.
37+
38+## Why I did not lift the refusal
39+The charter is explicit: "Only with the gate green: lift the refusal." The gate is not green — it
40+never observed a genuine attempt. Lifting on an unfired gate would be exactly the "refusal lifted
41+without a gate" class this project forbids. r4's `read_intra_mode_rect`/`decode_block_rect64`
42+palette wiring (the diff in 05f6db8) is therefore STILL unverified — neither confirmed correct nor
43+caught wrong. I left it in place (it compiles, does not regress any other gate) and left r4's
44+`refusal_inventory.rs` edit (narrowing the refusal to "palette block with a real transform on a
45+rect strip") as-is, also still unverified, per the charter's own note to treat it that way.
46+
47+## State committed
48+- `crates/ec-av1/src/stream.rs`: the new gate test only. No other file touched.
49+- `refusal_inventory.rs`: unchanged from r4's commit (still unverified, not touched further).
50+- The suite has one new RED test (`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`).
51+ I did not silence or ignore it — a red gate that has never fired is the honest state, not a
52+ green one that never proved anything.
53+
54+## Next round should try
55+- Content specifically constructed to make a `PARTITION_HORZ`/`VERT` split cheaper than `NONE`
56+ for a palette block — e.g. two very different flat-colour halves stacked so the whole-SB
57+ palette needs 2x the base colours a half-SB one would, biasing RD toward the split. Plain
58+ `smptebars`/`rgbtestsrc` don't do this (their bands are much finer than a 64px SB).
59+ `gradients_source` (used by the free-partition gate) is NOT screen content and won't turn on
60+ palette at all.
61+ - `aomenc --partition-info-path` (seen in `--help`) may let a fixture force a specific partition
62+ outright rather than depending on RD luck — worth trying before another blind cq/size sweep.
63+- If a firing stream is found and it MISMATCHES ffmpeg, rung 12 of the range ladder is still open
64+ and unclaimed — use it then.
65+
66+## Commands run
67+`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2; export EC_AV1_REQUIRE_AOMENC=1`
68+`nice -n 19 cargo test -p ec-av1 --lib -j4 a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact -- --nocapture`
69+(timeout 600000ms; result: 1 failed, as reported above — 0 passed, 31 named refusals, 39 decoded
70+with `palette_rect_hits` unchanged, 0 matched out of 70 attempts)
71+
72+## Budget
73+Spent the bulk of the round on live aomenc probing (`decode_probe` example + manual `aomenc`
74+sweeps) to characterise exactly where real content stops, per the charter's own instruction to let
75+the gate (and probes) tell the truth rather than guess flags. Stopped adding new sweep dimensions
76+at turn ~55 per budget discipline; committing the gate as the round's deliverable.
lanes/palette2-r6.charter.mdadded+63 -0
@@ -0,0 +1,63 @@
1+# lane-palette2 r6 — gate the case that actually occurs
2+
3+At the r5 commit. Read `lanes/palette2-r5.report.md`. r5 did good work and
4+reported an honest RED: its gate hard-asserts `palette_rect_hits()` and 70
5+aomenc attempts never moved that counter, so r4's implementation is still
6+unverified.
7+
8+## What I think went wrong, from my own measurement
9+The counter is too narrow. The refusal r4 removed was:
10+
11+ "a HORZ/VERT intra strip in a screen-content frame
12+ (palette syntax is consumed for square blocks only)"
13+
14+That fires on a rect strip in a frame with screen-content tools enabled —
15+whether or not that particular block ends up USING a palette. r5 searched for a
16+block that both is a rect strip and codes a palette, which RD apparently almost
17+never picks. But the broad case is common: **I hit that exact refusal on main
18+with plain default settings**, no flag hunting:
19+
20+ ffmpeg -v error -f lavfi -i "smptebars=size=192x128:rate=30" -t 0.2 \
21+ -pix_fmt yuv420p in.y4m -y
22+ aomenc --codec=av1 --ivf --threads=1 --row-mt=0 --sb-size=64 --limit=3 \
23+ --cpu-used=4 --end-usage=q --cq-level=32 -o out.ivf in.y4m
24+ ffmpeg -v error -i out.ivf -c:v copy -f obu out.obu -y
25+ cargo run -p ec-av1 --example decode_probe -- out.obu
26+
27+On main that prints the refusal above. `rgbtestsrc` does the same. On THIS
28+branch the refusal is gone, so the same stream now runs through r4's code — and
29+that is the thing to gate.
30+
31+## The job
32+1. Reproduce the above on main first, so you are gating a case you have watched
33+ occur rather than one you hope occurs.
34+2. Add a counter at the site r4 actually changed — the rect-strip-in-a-
35+ screen-content-frame path — not a palette-specific one. Then gate: this
36+ stream, through `decode_stream`, pixel-exact vs ffmpeg, with that counter
37+ hard-asserted to have moved.
38+3. If pixels match, the lift is earned: keep r4's narrower refusal
39+ ("a palette block with a real transform on a superblock-level HORZ/VERT
40+ strip...") and update `refusal_inventory.rs` so the lists agree.
41+4. If pixels mismatch, that is r4's implementation being wrong — bisect with a
42+ range ladder against the oracle (rung 12 is yours) and say so.
43+
44+**Right now this branch has removed a refusal with no gate behind it**
45+([[refusal-lifted-without-a-gate]]), which is the one state that cannot merge.
46+Closing that is this round's whole point.
47+
48+Keep r5's gate too if you can make it fire, but do not spend the round on it —
49+its own report says the honest next lever is `aomenc --partition-info-path` or a
50+fixture with two very different flat-colour halves, and that is a later problem.
51+
52+## Budget discipline
53+75 turns, no reset on resume. At about turn 55, stop starting new work: commit
54+what you have — red included, named as such — and write your report. Landing red
55+on this branch is fine; only merging red is forbidden, and I do the merges.
56+
57+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`; foreground
58+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; ffmpeg
59+generates bounded with `-t`; `EC_AV1_REQUIRE_AOMENC=1`; aomenc
60+`--threads=1 --row-mt=0 --sb-size=64`. The oracle is SHARED — env-gated rungs
61+only. Sibling worktrees have live agents — never build in or edit them. Never
62+push, never merge into main. End with `lanes/palette2-r6.report.md`, VERDICT on
63+line 1.
lanes/palette2-r6.report.mdadded+105 -0
@@ -0,0 +1,105 @@
1+VERDICT: RED — the broad gate the charter asked for now fires (proof the removed-refusal case
2+actually occurs), and it caught a real pixel mismatch. The defect is NOT r4's palette wiring: it
3+traces to a pre-existing, already-tracked bug in `decode_block_rect64` (ledger
4+[[lane-sbpart-r9]]), newly reachable now that the blanket screen-content refusal is gone. The
5+refusal is intentionally NOT restored — the charter's own instruction on mismatch is to bisect and
6+report, not revert.
7+
8+## What I did
9+1. Confirmed on `main` (HEAD `8440024`, textually — did not build there, see below) that the
10+ blanket refusal `"a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed
11+ for square blocks only)"` is still present verbatim (`decode.rs:2857`), so this branch really is
12+ the only place that case can be observed decoding.
13+2. Added `decode::rect_screen_content_hits()` — a `thread_local` counter incremented at the exact
14+ site the removed refusal used to guard, inside `read_intra_mode_rect` (`decode.rs`, right after
15+ `allow_screen_content_tools && palette_bsize_ctx_wh(bw, bh).is_some()`), independent of whether
16+ the block goes on to use a palette. This is the counter the charter asked for: it fires on the
17+ *common* case (r5's own sweep found 39/70 attempts reached this branch without ever using a
18+ palette — those were invisible to r5's `palette_rect_hits`).
19+3. Wrote `a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact` in `stream.rs`,
20+ modeled on r5's gate: same `--min/max-partition-size=64` recipe (r5 measured live that this
21+ dodges the 32x32-level AB-partition quirk, [[lane-sbpart-r2]]), same size/cq sweep, drives
22+ `decode_stream` directly, hard-asserts `rect_screen_content_hits()` moved before comparing any
23+ pixels.
24+
25+## What the gate found
26+First attempt through this recipe that actually fired the counter (`smptebars=size=128x128:rate=25
27+cq=15`) **mismatched ffmpeg**: rows 0-63 (the frame's top two 64x64 superblocks) match exactly;
28+rows 64-127 (the bottom two superblocks) are wrong wholesale (~117-128/128 pixels differ per row,
29+uniformly, not a scattered handful).
30+
31+I bisected with `EC_AV1_TRACE`:
32+- The 4 palette-Y/UV blocks visible in the trace (`EC_PAL`/`EC_PAL_VAL`) are all 64x64 luma /
33+ 32x32 chroma — **square**, going through the pre-existing, already-verified square palette path
34+ (`decode_block`), not the new rect one. Both top SBs decode this way and both match ffmpeg.
35+- `TRACE_RECT64_END mi_row=16 mi_col=16 bw=32 bh=64` and `mi_row=16 mi_col=24 bw=32 bh=64` are the
36+ two bottom SBs — real `VERT` splits at the superblock level, going through
37+ `decode_block_rect64`. Neither shows an `EC_PAL` trace inside it — **this is not a palette block
38+ at all**, just ordinary intra reconstruction on a genuine rect strip.
39+- So `rect_screen_content_hits` incremented correctly (the syntax-reading branch it counts ran),
40+ but the corruption is downstream of it, in `decode_block_rect64`'s own reconstruction of a real
41+ (non-skip) VERT-split block — the counter did its job; the block it counted is where the bug
42+ lives, just not in the code r4 added.
43+
44+This matches an existing ledger dead-end verbatim:
45+`dead-end|lane-sbpart r9 ... root cause is a sibling function (decode_block_rect64) ... do not
46+re-attempt part32 AB until decode_block_rect64 real-residual TX_32X64/64X32 truncation is fixed and
47+gated`. That defect was never closed. What's new this round is that it was previously
48+UNREACHABLE under `allow_screen_content_tools=true` (the blanket refusal short-circuited it
49+first, [[refusal-short-circuits-its-own-code]]) — removing that refusal exposed it for the first
50+time in this configuration, on a stream that doesn't even use palette.
51+
52+## Why I did not restore the refusal
53+The charter is explicit: on mismatch, bisect and say so — restoring the refusal was not asked for
54+and this branch's whole point is closing "refusal removed, no gate behind it"
55+([[refusal-lifted-without-a-gate]]) with an honest RED, not a silent revert back to green. The gate
56+itself is the safety net now: it is red, hard-asserting, and will stay red until
57+`decode_block_rect64`'s real-residual defect is actually fixed — exactly the state the charter
58+wants landed.
59+
60+## r4's `refusal_inventory.rs` / palette reconstruction — still unverified
61+Nothing this round exercised palette reconstruction through the rect path (every genuine rect-strip
62+decode I observed had zero palette use; every palette use I observed was square). r4's actual new
63+code (palette-Y/UV symbol reading and reconstruction generalized to `bw`x`bh`) is therefore
64+*still* neither confirmed nor refuted — same state r5 left it in. I left `refusal_inventory.rs`
65+untouched.
66+
67+## What I did NOT do
68+- Did not build or run anything in `/home/user/Documents/Code/Rust/edith_codecs` (main repo,
69+ not a worktree) — it had another agent's uncommitted staged changes when I checked; I only read
70+ the committed `HEAD` text to confirm the refusal's wording, never compiled there.
71+- Did not attempt to fix `decode_block_rect64`'s residual truncation — out of this round's charter
72+ (gate r4's work), and the ledger already flags it as open for whichever lane owns `sbpart`/rect64
73+ residuals next.
74+- Did not touch r5's `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact` gate; it is
75+ unchanged and still red for its own reason (never observes a genuine palette-on-rect attempt).
76+
77+## Commands run
78+```
79+export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2
80+export EC_AV1_REQUIRE_AOMENC=1
81+nice -n 19 cargo build -p ec-av1 --tests -j4 # clean
82+nice -n 19 cargo test -p ec-av1 --lib -j4 \
83+ a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact -- --nocapture
84+ # FAILED: assertion `left == right` ... frame 0 luma vs ffmpeg (the mismatch above)
85+```
86+(cargo test timeout was 600000ms; actual run finished in ~1-17s per invocation, well under)
87+
88+## State committed
89+`d427e19` on `lane-palette2` (HEAD): `decode.rs` (+23, new counter),
90+`stream.rs` (+153, new gate). Compiles clean (`cargo build -p ec-av1 --tests`). Two red gates now
91+exist for this lane's unverified surface (r5's palette-on-rect, r6's broad rect-screen-content) —
92+both honest, neither silenced.
93+
94+## Next round should
95+- Fix `decode_block_rect64`'s real-residual VERT/HORZ-split reconstruction (the actual root cause,
96+ tracked since [[lane-sbpart-r9]]) — this gate will go green once that's fixed and no sooner.
97+- Once green, re-run `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact` too: with
98+ `decode_block_rect64` fixed, more attempts may reach a genuine palette-on-rect block and finally
99+ give r4's actual new code its first real test.
100+
101+## Budget
102+~55 turns spent: charter/report reading, main-HEAD text confirmation, counter + gate authoring,
103+two build/test cycles (first hit a broken-pipe harness bug from `--limit=3` racing piped stdin,
104+fixed by dropping it and matching r5's proven recipe), then bisection via `EC_AV1_TRACE` to
105+localize the mismatch to `decode_block_rect64`. Stopped there per budget discipline and committed.
lanes/palette2-r7.report.mdadded+83 -0
@@ -0,0 +1,83 @@
1+# lane-palette2 r7 report
2+
3+(The charter for this round was labelled "round 3"; the branch was already at r6 — this is r7.
4+The charter's own step numbering is kept below.)
5+
6+VERDICT: GREEN. Both charter steps are implemented AND gated pixel-exact against real aomenc.
7+The r6 report's RED is resolved: it was NOT the `decode_block_rect64` residual defect, it was
8+`--min-partition-size=64` in the gate recipe forcing SB-level VERT-64 blocks through
9+`decode_block_rect64`. At `--min-partition-size=16` the gate reaches real rect strips
10+(16x16..64x64) and is pixel-exact.
11+
12+## What changed (commit 5d67fd7 on `lane-palette2`)
13+
14+- `crates/ec-av1/src/decode.rs` `decode_block` (~5056, ~5241) — palette-Y prediction is now
15+ windowed PER TRANSFORM UNIT: with `logical_tx != side`, each TU copies its own
16+ `logical_tx`x`logical_tx` window out of the block's index map right before `read_plane`,
17+ instead of the whole-block buffer (which the FIRST unit consumed at the wrong stride).
18+ Residual is added per TU over that prediction. Refusal
19+ **"a palette block with a split luma transform (round 1)" LIFTED** (charter step 3).
20+- `decode.rs` `read_intra_mode` (~4415) and `read_intra_mode_rect` (~3153) — a palette-Y block
21+ gets NO `use_filter_intra` symbol (`av1_filter_intra_allowed`, reconintra.h:77). We read one,
22+ consuming a bit the encoder never wrote, and desynced from every palette block <=32x32
23+ (class `symbol-consumption-gap`).
24+- `decode.rs` `Neighbours::palette_ctx_and_cache` (~2005) — the SB-top-row exclusion of the above
25+ neighbour belongs to the colour CACHE only (pred_common.c:76); `av1_get_palette_mode_ctx`
26+ (pred_common.h:197) reads plain `xd->above_mbmi`. Applying it to the ctx too made every SB in
27+ the frame's second SB row read `palette_y_mode` off CDF row 0 while libaom used row 1
28+ (class `cdf-row-held-constant`).
29+- `decode.rs` `decode_leaf_rect` (~3674) — sub-16x16 rect leaves now read palette syntax with
30+ their own real ctx/cache (previously row 0); RECONSTRUCTION on a sub-16x16 strip stays refused
31+ by name: **new refusal "a palette block on a HORZ/VERT intra strip below 16x16 (reconstruction
32+ not ported)"**.
33+- `crates/ec-av1/src/stream.rs` (~2129, ~2285) — both palette gates' aomenc recipe
34+ `--min-partition-size=64` -> `16`; r6's gate additionally asserts
35+ `palette_split_tx_hits()` moved on a pixel-exact attempt.
36+- `crates/ec-av1/src/refusal_inventory.rs` — split-transform refusal removed, sub-16x16 rect
37+ palette refusal added. `gate_coverage.rs` already lists only `enable-intrabc`; palette is
38+ covered by an explicit `--enable-palette=1` in both gates. Both meta-tests green.
39+
40+## Gates
41+
42+Command (worktree, `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2`, `EC_AV1_REQUIRE_AOMENC=1`):
43+
44+ cargo test -p ec-av1 --lib -j3 -- --nocapture \
45+ stream::tests::a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact \
46+ stream::tests::a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \
47+ refusal_inventory gate_coverage
48+ # test result: ok. 7 passed; 0 failed; 0 ignored
49+
50+aomenc line in both (CORRECTED r8 -- r7 wrote `--tune-content=screen
51+--enable-rect-partitions=1`, which the code at stream.rs ~2118-2135 / ~2274-2291 passes
52+NEITHER of; the actual argv is): `--codec=av1 --passes=1 --end-usage=q --cq-level=<cq>
53+--cpu-used=4 --threads=1 --row-mt=0 --sb-size=64 --enable-palette=1 --min-partition-size=16
54+--max-partition-size=64 --obu -o - -`,
55+70 attempts (5 sizes x 7 cq x smptebars/rgbtestsrc), pixel-compared against ffmpeg's decode.
56+
57+EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/palette2-r7-gates.txt | 70 real-aomenc screen-content encodes decoded and pixel-compared vs ffmpeg | a_real_aomenc_stream_with_rect_screen_content: 14/70 pixel-exact, 13 of them through a split-transform palette block, rect_screen_content_hits=169, palette_split_tx_hits=356
58+EVIDENCE: same file | same sweep, r5's narrower gate | a_real_aomenc_stream_with_rect_palette: 14/70 pixel-exact, palette_rect_hits=78 rect-strip palette blocks reconstructed
59+EVIDENCE: full lib suite `cargo test -p ec-av1 --lib -j3` | whole ec-av1 lib | 269 passed, 0 failed, 23 ignored (510s)
60+
61+## Charter steps
62+
63+- Step 2 (palette on HORZ/VERT rect strips, >=16x16 both dims): DONE, gated
64+ (`palette_rect_hits=78`, pixel-exact). The blanket refusal "a HORZ/VERT intra strip in a
65+ screen-content frame (palette syntax is consumed for square blocks only)" is gone and now has
66+ a gate behind it.
67+- Step 3 (palette + split luma transform): DONE, gated (`palette_split_tx_hits=356`).
68+- Step 2's inter-frame 8x8-leaf palette refusals (decode.rs ~10652, ~11748): NOT attempted —
69+ deferred. Measured, not assumed: a 10-frame `rgbtestsrc` screen-content encode at cq 15/35/55
70+ through `decode_probe` stops at "a 32x32 partition type this decoder does not code (value=4)"
71+ and "filter intra on a HORZ/VERT strip", never at a palette refusal. Those paths are
72+ unreachable behind other lanes' refusals, so no gate could prove a lift today
73+ (class `refusal-lifted-without-a-gate`).
74+
75+## Residue
76+
77+- deferred: inter-frame palette reconstruction (decode.rs ~10652 intra-in-inter, ~11748 8x8 leaf)
78+ — unblocked by lane-part32 (32x32 partition types) and the filter-intra-on-rect-strip lane;
79+ once those land, screen-content inter frames become reachable and a gate is possible.
80+- deferred: sub-16x16 rect-strip palette reconstruction — refused by name, syntax read correctly;
81+ unblocked by a rect (4x8/8x4) transform primitive, same ceiling as `lane-sub8`.
82+- accepted: the `decode_block_rect64` real-residual defect (ledger lane-sbpart-r9) is untouched
83+ and still open; this lane's gates simply no longer route through it. It is NOT a palette defect.
lanes/palette2-r8.report.mdadded+82 -0
@@ -0,0 +1,82 @@
1+# lane-palette2 r8 — verifier findings closed; both gates now RED on a real defect they used to hide
2+
3+VERDICT: RED (honest). The two gate-integrity fixes the verifier asked for turned 2 previously
4+"green" gates red: 16/70 attempts per gate decoded successfully and were never pixel-compared,
5+and one of them (`rgbtestsrc=size=128x128:rate=25 cq=55`) mismatches ffmpeg on chroma. That
6+mismatch is PRE-EXISTING, not caused by this round's decoder change (proved by stashing the
7+decode.rs diff and re-running: same panic, same attempt, same plane).
8+
9+## What changed
10+- `crates/ec-av1/src/stream.rs` ~2170-2210 (`a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`)
11+ and ~2335-2375 (`a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`) — the
12+ hit-counter check no longer `continue`s past the pixel comparison. Every successfully decoded
13+ attempt is compared and a mismatch panics; the counter now only decides whether the attempt
14+ counts toward the hit-asserting total (`matched` vs new `uncounted_exact`). Class
15+ [[gate-skips-on-its-own-failure]].
16+- `crates/ec-av1/src/decode.rs` ~1986-2010 / ~2084-2105 (`record_palette_y_rect`,
17+ `record_palette_uv_rect`) — `for cell in 0..(w / SUB).max(1)` (both axes). The plain
18+ `w / SUB` loop was a NO-OP for every sub-16px span, so a sub-16 leaf could not clear the
19+ above/left palette state at all. Corner-cut comment names the ceiling: our grid is 16px
20+ where libaom keeps `palette_size` per 4px mi cell; safe today because every sub-16 leaf
21+ path refuses palette outright, so it can only ever stamp `size == 0`. Upgrade path:
22+ widen the palette arrays to mi granularity.
23+- `crates/ec-av1/src/decode.rs` ~3803-3810 (`decode_leaf_rect`, before `Ok(mode)`) and
24+ ~5703/~5721 (`decode_leaf8`, both exits) — each sub-16 leaf now records its own palette
25+ state (size 0, since both paths refuse palette) over its own cell, so the next block's
26+ `palette_y_mode` ctx and colour cache no longer read a previous block's palette. Class
27+ [[cdf-row-held-constant]].
28+- `crates/ec-av1/src/decode.rs` (tests) — new unit test
29+ `a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero`: a 16x16 palette block gives
30+ ctx 2 + cache [7,9]; an 8x8 non-palette leaf in the same cell must take it to ctx 0 and an
31+ empty cache (Y and UV halves). Fails before this round's fix, passes after.
32+- `lanes/palette2-r7.report.md` line 50 — CORRECTED. r7 claimed the aomenc line carried
33+ `--tune-content=screen --enable-rect-partitions=1`; the code passes NEITHER. Real argv:
34+ `--codec=av1 --passes=1 --end-usage=q --cq-level=<cq> --cpu-used=4 --threads=1 --row-mt=0
35+ --sb-size=64 --enable-palette=1 --min-partition-size=16 --max-partition-size=64 --obu -o - -`.
36+ The recipe itself is unchanged.
37+
38+## Gate results (EC_AV1_REQUIRE_AOMENC=1)
39+```
40+cd <worktree>; export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 EC_AV1_REQUIRE_AOMENC=1
41+cargo test -p ec-av1 --lib -j3 -- --test-threads=1 --nocapture \
42+ a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \
43+ a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact
44+```
45+Buckets over the same 70-attempt sweep (5 sizes x 7 cq x smptebars/rgbtestsrc), per gate:
46+- named refusal: 54/70 (32x32 partition value=4..7, filter-intra-on-strip, split-transform strip)
47+- decoded, counter fired, pixel-compared: was 14/70 in r7 — not re-reached this round, the run
48+ aborts at the first mismatch, which is an uncounted attempt earlier in the sweep.
49+- decoded, counter did NOT fire, now pixel-compared (r7 skipped these entirely): 2 reached
50+ before the abort — `rgbtestsrc 128x64 cq=63` (exact) and `rgbtestsrc 128x128 cq=55` (MISMATCH).
51+`refusal_inventory` (3 tests) + `gate_coverage` (2 tests): 5 passed, 0 failed.
52+
53+## The defect the integrity fix exposed
54+`rgbtestsrc=size=128x128:rate=25 cq=55`, single key frame: luma bit-exact, V exact, **U plane
55+30 pixels wrong by +-1 / +-2**, all inside chroma rows 38-50 x cols 28-50 (luma 76-100 x 56-100).
56+Shape matches the open residual chroma-only defect already noted on main (`1a89ed9` "residual
57+chroma-only defect open") and memory `[[lane-tiny r4]]`: chroma-only +-1 with luma exact is a
58+post-recon (filter) defect — dump prefilt/postdeblock stages first, do NOT open a symbol trace.
59+Pinned stream (118 bytes, sha256
60+`807e5d434b035e626548d0ec3dc166b959622ed64b59dfa049a16d0e5a35c297`):
61+`/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/palette2-r8-mismatch.obu`
62+(not committed: `crates/ec-av1/fixtures` is under `.gitignore:2 fixtures`; regenerate with
63+`EC_AV1_GATE_DUMP=<path>` on either gate).
64+
65+## EVIDENCE
66+EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/palette2-r8-mismatch.obu | both palette gates re-run under EC_AV1_REQUIRE_AOMENC=1 with the counter-`continue` removed | 2 previously-unchecked decoded attempts now compared; 1 exact, 1 mismatching (U plane, 30 px, max |d| = 2)
67+EVIDENCE: stash-and-rerun of the decode.rs diff (`git stash push crates/ec-av1/src/decode.rs`, gate re-run, `git stash pop`) | same gate, r8 stream.rs only | identical panic at stream.rs:2200, same attempt, same plane -- the chroma defect is pre-existing, not this round's regression
68+EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1) | whole ec-av1 lib | 268 passed, 2 failed (the two palette gates above), 23 ignored, 514.71s
69+EVIDENCE: cargo test -p ec-av1 --lib -j3 a_sub16_leaf_after_a_palette_block | new unit test | 1 passed
70+
71+## Residue
72+- fix-now(next round, blocks merge): the chroma-only U mismatch above. Both gates stay RED until
73+ it is fixed or its stream is proven to hit a legal named refusal instead.
74+- deferred(concurrent lanes own these gates): 8 sibling sites in stream.rs carry the SAME shape --
75+ a successful decode whose hit counter did not move `continue`s/`never_fired += 1` before any
76+ pixel compare: lines ~2662 (`tx_depth_hits`), ~3781 (`non_last_ref_hits`), ~3959
77+ (`ref_hits(target_ref)`), ~4159 (`comp_mode_hits`), ~4354 (`skip_mode_hits`), ~4530
78+ (`obmc_hits`), ~7222 (`tmv_hits`), ~7495 (`tx_class1_hits`). Same one-line transform applies
79+ (compare pixels, then decide whether to count). NOT changed here: they belong to lanes running
80+ concurrently in this batch on the same file (merge-conflict cost), and each needs its own
81+ aomenc sweep to validate. Unblocked by: this batch's merge, then one mechanical sweep round.
82+- accepted: the 16px palette-neighbour grid (corner-cut comment in `record_palette_y_rect`).
lanes/palette2-r9.report.mdadded+90 -0
@@ -0,0 +1,90 @@
1+# lane-palette2 r9 — GREEN: both palette gates pass after the main merge + one real defect fix
2+
3+VERDICT: GREEN. Both gates decode-and-pixel-compare every successful attempt, 0 mismatches.
4+
5+## STEP 1 — merge main f31a2c5 (as chartered)
6+`git merge f31a2c5` into lane-palette2 (commit `4f30677`). Two conflicts:
7+- `crates/ec-av1/src/decode.rs` `reconstruct_rect` (~5517): kept this lane's `PALETTE_PRED`
8+ override branch, and took main's rect filter-intra call signature (`bw, bh` — lane-rectsplit
9+ widened `predict_filter_intra` to a rectangle). Keeping only one side would have either
10+ dropped palette prediction on rect strips or failed to compile.
11+- `crates/ec-av1/src/refusal_inventory.rs` (~51): union of both sides, then the two strings the
12+ merge made unreachable were deleted (the inventory test named them):
13+ `"a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square
14+ blocks only)"` (lifted by this lane) and `"a HORZ/VERT intra strip with a split transform
15+ (per-unit rect prediction is not ported)"` (lifted by main's lane-rectsplit).
16+
17+The r8 blocker — the chroma-only U mismatch on `rgbtestsrc 128x128 cq=55` (30 px, max |d| 2,
18+luma+V exact) — is GONE after the merge, exactly as the charter predicted: main `9b1297a`
19+(deblocker chroma tx size = block span/2, not luma_tx/2). That attempt now decodes pixel-exact.
20+
21+## STEP 2 — the merge created a new defect, root-caused and fixed
22+The merge did NOT leave the gates green: they failed on a *different*, larger mismatch
23+(`smptebars 192x192 cq=35`), which main alone refuses outright
24+(`decode_probe` on f31a2c5: "REFUSED: ... a HORZ/VERT intra strip in a screen-content frame"),
25+so the case only exists in the merged tree.
26+
27+Measured shape: luma x0..63, y0..127 entirely wrong (8192 px, max |d| 52), the rest of the frame
28+exact; ours flat 128 there = DC prediction with no edges. `EC_TRACE_MODE_STEP` showed mi(0,0) =
29+32x16 strip, `mode=0`/`uv_mode=0` (the palette signature) with a split transform.
30+
31+ROOT CAUSE: `decode_rect_split` (`crates/ec-av1/src/decode.rs:3780`, from main's lane-rectsplit)
32+knows nothing about palette. The palette wiring at the call site
33+(`decode_block_rect`, decode.rs ~4113) sets `PALETTE_PRED` *after* the `depth != 0` early return,
34+so every transform unit of a split-transform palette strip predicted DC. The coefficients are
35+still read, so the entropy stream stayed in sync and only those pixels were wrong — class
36+[[parsed-then-discarded]] applied to the *prediction* rather than to a header field.
37+
38+FIX (decode.rs):
39+- `RectStripModes` (~3747) gains `palette_y: Option<Vec<u16>>` and
40+ `palette_uv: Option<(Vec<u16>, Vec<u16>)>` — the block's colour-mapped maps.
41+- `decode_rect_split` luma TU loop (~3857): before each unit's `read_plane`/`reconstruct`, sets
42+ `PALETTE_PRED` to that unit's `tx`x`tx` window of the block map. Palette prediction reads no
43+ edge pixels, so a unit's window on the whole-block map IS its prediction — no ordering subtlety.
44+- `decode_rect_split` chroma (~3905/~3960): sets `PALETTE_PRED` per plane before each
45+ `reconstruct_rect` (skip and coded arms); the chroma transform is never split by luma's depth.
46+- call site (~4130): builds the maps into `RectStripModes` and bumps `PALETTE_SPLIT_TX_HITS`, the
47+ counter the screen-content gate already HARD-asserts (`split_palette_matched > 0`,
48+ stream.rs:2655), so this new path is gated, not merely exercised.
49+
50+## Gate results (EC_AV1_REQUIRE_AOMENC=1, --test-threads=1)
51+```
52+cd /home/user/Documents/Code/Rust/edith_codecs-palette2
53+export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette2 EC_AV1_REQUIRE_AOMENC=1
54+cargo test -p ec-av1 --lib -j3 -- --test-threads=1 --nocapture \
55+ a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact \
56+ a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact
57+```
58+- `a_real_aomenc_stream_with_rect_palette_decodes_pixel_exact`: 17/70 matched pixel-exact,
59+ 21 decoded-and-pixel-exact but uncounted, 32 named refusals, `palette_rect_hits=92`.
60+- `a_real_aomenc_stream_with_rect_screen_content_decodes_pixel_exact`: 19/70 matched
61+ (14 of them through a split-transform palette block), 19 decoded-and-pixel-exact but uncounted,
62+ 32 named refusals.
63+- 38 successful decodes per gate, ALL pixel-compared (r8's integrity fix stands), 0 mismatches.
64+- `refusal_inventory` (3) + `gate_coverage` (2): 5 passed, 0 failed.
65+
66+## EVIDENCE
67+EVIDENCE: /tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/b6d8a07f-96a4-4bbb-b378-af9ae25cf7c9/scratchpad/r9-mismatch.obu (196 B, sha256 1f9bcc87138c39bbca9a38f95e5db09de0f84afdefeeaab2a7288e22b9c91068) | decode_probe dump vs `ffmpeg -f obu -f rawvideo -pix_fmt yuv420p`, before and after the fix | before: Y 8192 px wrong (x0..63, y0..127, max |d| 52), U 640 px, V 640 px; after: Y exact, U exact, V exact
68+EVIDENCE: git worktree at f31a2c5 (main), `cargo run -p ec-av1 --example decode_probe -- r9-mismatch.obu` | same stream on unmerged main | "REFUSED: unsupported: AV1 tile (a HORZ/VERT intra strip in a screen-content frame ...)" — the defect is a merge-created combination, not a main regression
69+EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1), two palette gates | full 70-attempt sweep each | 2 passed, 0 failed; counters above
70+EVIDENCE: cargo test -p ec-av1 --lib -j3 (EC_AV1_REQUIRE_AOMENC=1) | whole ec-av1 lib on 4f30677 | 277 passed, 0 failed, 23 ignored, 1748.98s
71+
72+## Refusals
73+Lifted this round: none newly lifted by this lane. Two strings LEFT the inventory as an
74+arithmetic consequence of the merge (each was already lifted with its own gate on one of the two
75+sides): "a HORZ/VERT intra strip in a screen-content frame ..." (this lane's, gated by the two
76+palette gates above) and "a HORZ/VERT intra strip with a split transform ..." (main's
77+lane-rectsplit, gated there). The palette-on-split-tx path added here is gated by the existing
78+HARD assert `split_palette_matched > 0` (stream.rs:2655), now 14.
79+
80+## Residue
81+- deferred(this batch's merge, then one mechanical sweep): the 8 sibling `stream.rs` sites listed
82+ in r8 that still `continue` past the pixel compare when their hit counter did not move
83+ (~2662, ~3781, ~3959, ~4159, ~4354, ~4530, ~7222, ~7495). Untouched here for the same reason as
84+ r8 — concurrent lanes own those gates and each needs its own aomenc sweep.
85+- accepted: the 16px palette-neighbour grid corner-cut (`record_palette_y_rect`), ceiling named in
86+ the code; libaom keeps `palette_size` per 4px mi cell.
87+- accepted: `PALETTE_SPLIT_TX_HITS` is bumped by both the square split path (decode.rs ~6159) and
88+ the new rect-strip path, so the gate's assert does not distinguish them; the gate's own recipe
89+ (`--min-partition-size=16`, rect strips present) plus this round's before/after pixel evidence
90+ covers the rect case.