forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-palette': palette-Y blocks decode pixel-exact

Browse files at this commit

2195bbdb7d33c88531e5d4843fbad2344cfa88aeAhmet Kaan GümüşParent: eb818a1745cab9
Blocker (3) closed. Root cause was call ORDER, not a table: every symbol was
already bit-exact through read_palette_colors_y, and the range diverged exactly
at decode_color_index_map's entry because libaom reaches decode_color_map_tokens
from parse_decode_block AFTER the whole mode-info decode, including UV palette
mode_info and filter_intra. We called it inline after the Y colours and never
read UV palette mode_info at all. Fix: read UV palette mode_info, defer the
index map past filter_intra. UV palette reconstruction stays refused by name.

enable-palette leaves NEVER_EXERCISED with positive evidence -- the new gate
passes --enable-palette=1 -- so intrabc is now the last entry.

Two conflicts resolved here, both additive-vs-additive:
- Neighbours' delta_lf_grid (lane-realworld) and the palette neighbour cache
  (lane-palette) are independent fields; kept both.
- Three lanes each numbered their new oracle instrumentation rung "6".
  lane-palette's two are renumbered 8 and 8b behind superres's 6 and 7.

Suite 256 passed / 0 failed.
crates/ec-av1/src/cdf.rsmodified+113 -0
@@ -416,6 +416,119 @@ pub const PALETTE_Y_MODE: [[[u16; 3]; 3]; 7] = [
416416 /// this block's own luma palette was used -- always 0 here, see
417417 /// [`PALETTE_Y_MODE`]'s doc).
418418 pub const PALETTE_UV_MODE: [[u16; 3]; 2] = [[32461, 32768, 0], [21488, 32768, 0]];
419+/// `default_palette_y_color_index_cdf` (entropymode.c): the per-pixel colour
420+/// index symbol for a palette-Y block, indexed `[n-2][color_ctx]` where `n`
421+/// is the block's palette size (2..=8, `PALETTE_SIZES`) and `color_ctx` is
422+/// `av1_get_palette_color_index_context`'s 0..=4 output
423+/// (`PALETTE_COLOR_INDEX_CONTEXTS`). Each row is transcribed straight from
424+/// its `AOM_CDFn` macro (`n-1` raw probs, then `32768, 0`) and zero-padded
425+/// out to width 9 (the `n=8` row's real length); the call site slices
426+/// `[..=n]`, which only ever touches the real prefix, so the trailing zero
427+/// padding on shorter rows is never read.
428+pub const PALETTE_Y_COLOR_INDEX: [[[u16; 9]; 5]; 7] = [
429+ [
430+ [28710, 32768, 0, 0, 0, 0, 0, 0, 0],
431+ [16384, 32768, 0, 0, 0, 0, 0, 0, 0],
432+ [10553, 32768, 0, 0, 0, 0, 0, 0, 0],
433+ [27036, 32768, 0, 0, 0, 0, 0, 0, 0],
434+ [31603, 32768, 0, 0, 0, 0, 0, 0, 0],
435+ ],
436+ [
437+ [27877, 30490, 32768, 0, 0, 0, 0, 0, 0],
438+ [11532, 25697, 32768, 0, 0, 0, 0, 0, 0],
439+ [6544, 30234, 32768, 0, 0, 0, 0, 0, 0],
440+ [23018, 28072, 32768, 0, 0, 0, 0, 0, 0],
441+ [31915, 32385, 32768, 0, 0, 0, 0, 0, 0],
442+ ],
443+ [
444+ [25572, 28046, 30045, 32768, 0, 0, 0, 0, 0],
445+ [9478, 21590, 27256, 32768, 0, 0, 0, 0, 0],
446+ [7248, 26837, 29824, 32768, 0, 0, 0, 0, 0],
447+ [19167, 24486, 28349, 32768, 0, 0, 0, 0, 0],
448+ [31400, 31825, 32250, 32768, 0, 0, 0, 0, 0],
449+ ],
450+ [
451+ [24779, 26955, 28576, 30282, 32768, 0, 0, 0, 0],
452+ [8669, 20364, 24073, 28093, 32768, 0, 0, 0, 0],
453+ [4255, 27565, 29377, 31067, 32768, 0, 0, 0, 0],
454+ [19864, 23674, 26716, 29530, 32768, 0, 0, 0, 0],
455+ [31646, 31893, 32147, 32426, 32768, 0, 0, 0, 0],
456+ ],
457+ [
458+ [23132, 25407, 26970, 28435, 30073, 32768, 0, 0, 0],
459+ [7443, 17242, 20717, 24762, 27982, 32768, 0, 0, 0],
460+ [6300, 24862, 26944, 28784, 30671, 32768, 0, 0, 0],
461+ [18916, 22895, 25267, 27435, 29652, 32768, 0, 0, 0],
462+ [31270, 31550, 31808, 32059, 32353, 32768, 0, 0, 0],
463+ ],
464+ [
465+ [23105, 25199, 26464, 27684, 28931, 30318, 32768, 0, 0],
466+ [6950, 15447, 18952, 22681, 25567, 28563, 32768, 0, 0],
467+ [7560, 23474, 25490, 27203, 28921, 30708, 32768, 0, 0],
468+ [18544, 22373, 24457, 26195, 28119, 30045, 32768, 0, 0],
469+ [31198, 31451, 31670, 31882, 32123, 32391, 32768, 0, 0],
470+ ],
471+ [
472+ [21689, 23883, 25163, 26352, 27506, 28827, 30195, 32768, 0],
473+ [6892, 15385, 17840, 21606, 24287, 26753, 29204, 32768, 0],
474+ [5651, 23182, 25042, 26518, 27982, 29392, 30900, 32768, 0],
475+ [19349, 22578, 24418, 25994, 27524, 29031, 30448, 32768, 0],
476+ [31028, 31270, 31504, 31705, 31927, 32153, 32392, 32768, 0],
477+ ],
478+];
479+/// `default_palette_uv_color_index_cdf` (entropymode.c): as
480+/// [`PALETTE_Y_COLOR_INDEX`], for the chroma colour-index map.
481+pub const PALETTE_UV_COLOR_INDEX: [[[u16; 9]; 5]; 7] = [
482+ [
483+ [29089, 32768, 0, 0, 0, 0, 0, 0, 0],
484+ [16384, 32768, 0, 0, 0, 0, 0, 0, 0],
485+ [8713, 32768, 0, 0, 0, 0, 0, 0, 0],
486+ [29257, 32768, 0, 0, 0, 0, 0, 0, 0],
487+ [31610, 32768, 0, 0, 0, 0, 0, 0, 0],
488+ ],
489+ [
490+ [25257, 29145, 32768, 0, 0, 0, 0, 0, 0],
491+ [12287, 27293, 32768, 0, 0, 0, 0, 0, 0],
492+ [7033, 27960, 32768, 0, 0, 0, 0, 0, 0],
493+ [20145, 25405, 32768, 0, 0, 0, 0, 0, 0],
494+ [30608, 31639, 32768, 0, 0, 0, 0, 0, 0],
495+ ],
496+ [
497+ [24210, 27175, 29903, 32768, 0, 0, 0, 0, 0],
498+ [9888, 22386, 27214, 32768, 0, 0, 0, 0, 0],
499+ [5901, 26053, 29293, 32768, 0, 0, 0, 0, 0],
500+ [18318, 22152, 28333, 32768, 0, 0, 0, 0, 0],
501+ [30459, 31136, 31926, 32768, 0, 0, 0, 0, 0],
502+ ],
503+ [
504+ [22980, 25479, 27781, 29986, 32768, 0, 0, 0, 0],
505+ [8413, 21408, 24859, 28874, 32768, 0, 0, 0, 0],
506+ [2257, 29449, 30594, 31598, 32768, 0, 0, 0, 0],
507+ [19189, 21202, 25915, 28620, 32768, 0, 0, 0, 0],
508+ [31844, 32044, 32281, 32518, 32768, 0, 0, 0, 0],
509+ ],
510+ [
511+ [22217, 24567, 26637, 28683, 30548, 32768, 0, 0, 0],
512+ [7307, 16406, 19636, 24632, 28424, 32768, 0, 0, 0],
513+ [4441, 25064, 26879, 28942, 30919, 32768, 0, 0, 0],
514+ [17210, 20528, 23319, 26750, 29582, 32768, 0, 0, 0],
515+ [30674, 30953, 31396, 31735, 32207, 32768, 0, 0, 0],
516+ ],
517+ [
518+ [21239, 23168, 25044, 26962, 28705, 30506, 32768, 0, 0],
519+ [6545, 15012, 18004, 21817, 25503, 28701, 32768, 0, 0],
520+ [3448, 26295, 27437, 28704, 30126, 31442, 32768, 0, 0],
521+ [15889, 18323, 21704, 24698, 26976, 29690, 32768, 0, 0],
522+ [30988, 31204, 31479, 31734, 31983, 32325, 32768, 0, 0],
523+ ],
524+ [
525+ [21442, 23288, 24758, 26246, 27649, 28980, 30563, 32768, 0],
526+ [5863, 14933, 17552, 20668, 23683, 26411, 29273, 32768, 0],
527+ [3415, 25810, 26877, 27990, 29223, 30394, 31618, 32768, 0],
528+ [17965, 20084, 22232, 23974, 26274, 28402, 30390, 32768, 0],
529+ [31190, 31329, 31516, 31679, 31825, 32026, 32322, 32768, 0],
530+ ],
531+];
419532 /// `default_intrabc_cdf` (entropymode.c): the `use_intrabc` flag on an
420533 /// intra frame with `allow_intrabc` set.
421534 pub const INTRABC: [u16; 3] = [30531, 32768, 0];
crates/ec-av1/src/cdf_state.rsmodified+10 -0
@@ -431,6 +431,12 @@ pub(crate) struct Cdfs {
431431 pub palette_uv_mode: [[u16; 3]; 2],
432432 /// A chroma palette block's own size -- see [`cdf::PALETTE_UV_SIZE`].
433433 pub palette_uv_size: [[u16; 8]; 7],
434+ /// A palette-Y block's per-pixel colour-index symbol -- see
435+ /// [`cdf::PALETTE_Y_COLOR_INDEX`].
436+ pub palette_y_color_index: [[[u16; 9]; 5]; 7],
437+ /// A palette-UV block's per-pixel colour-index symbol -- see
438+ /// [`cdf::PALETTE_UV_COLOR_INDEX`].
439+ pub palette_uv_color_index: [[[u16; 9]; 5]; 7],
434440 /// The `use_intrabc` flag -- see [`cdf::INTRABC`].
435441 pub intrabc: [u16; 3],
436442 /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`].
@@ -663,6 +669,8 @@ impl Cdfs {
663669 reset2(&mut self.palette_y_size);
664670 reset2(&mut self.palette_uv_mode);
665671 reset2(&mut self.palette_uv_size);
672+ reset3(&mut self.palette_y_color_index);
673+ reset3(&mut self.palette_uv_color_index);
666674 reset1(&mut self.intrabc);
667675 reset1(&mut self.delta_q);
668676 reset1(&mut self.delta_lf);
@@ -1126,6 +1134,8 @@ impl Cdfs {
11261134 palette_y_size: cdf::PALETTE_Y_SIZE,
11271135 palette_uv_mode: cdf::PALETTE_UV_MODE,
11281136 palette_uv_size: cdf::PALETTE_UV_SIZE,
1137+ palette_y_color_index: cdf::PALETTE_Y_COLOR_INDEX,
1138+ palette_uv_color_index: cdf::PALETTE_UV_COLOR_INDEX,
11291139 intrabc: cdf::INTRABC,
11301140 delta_q: cdf::DELTA_Q,
11311141 delta_lf: cdf::DELTA_LF,
crates/ec-av1/src/decode.rsmodified+461 -48
@@ -435,6 +435,33 @@ pub(crate) fn comp_mode_hits() -> usize {
435435 COMP_MODE_HITS.with(|c| c.get())
436436 }
437437
438+// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
439+// use for, across every call on the current thread -- the same before/after
440+// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
441+// exercised palette reconstruction rather than only reading and refusing the
442+// `palette_y_mode` symbol.
443+thread_local! {
444+ static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
445+}
446+
447+/// Current value of [`PALETTE_HITS`].
448+pub(crate) fn palette_hits() -> usize {
449+ PALETTE_HITS.with(|c| c.get())
450+}
451+
452+thread_local! {
453+ /// A just-decoded palette-Y block's own predicted pixels
454+ /// (`side*side`, row-major, `colors[map[i]]`), consumed by
455+ /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
456+ /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
457+ /// per-block override through `read_plane`'s two dozen call sites is the
458+ /// alternative this avoids). Always empty again once that call consumes
459+ /// it (`.take()`), so a non-palette block's own `reconstruct` call never
460+ /// sees stale state.
461+ static PALETTE_PRED: std::cell::RefCell<Option<Vec<u8>>> =
462+ const { std::cell::RefCell::new(None) };
463+}
464+
438465 // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
439466 // proves a real `skip_mode_present` stream actually reached a block that
440467 // picked it, not just that the frame header bit was set.
@@ -1593,6 +1620,14 @@ struct Neighbours {
15931620 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
15941621 /// to know which mode produced the value.
15951622 delta_lf_grid: Vec<[i8; 4]>,
1623+ /// The block above/left's own palette-Y size (0 = not a palette block)
1624+ /// and its base colours -- `av1_get_palette_mode_ctx`/
1625+ /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
1626+ /// r2. UV has no equivalent yet (stage 2, unreconstructed).
1627+ above_palette_size: Vec<usize>,
1628+ left_palette_size: Vec<usize>,
1629+ above_palette_colors: Vec<[u16; 8]>,
1630+ left_palette_colors: Vec<[u16; 8]>,
15961631 /// This tile's own top-left corner, in 4x4 mode-info units (spec
15971632 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
15981633 /// neighbour" check compares against this instead of literal `0`, since a
@@ -1643,6 +1678,10 @@ impl Neighbours {
16431678 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
16441679 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
16451680 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
1681+ above_palette_size: vec![0; cols],
1682+ left_palette_size: vec![0; rows],
1683+ above_palette_colors: vec![[0u16; 8]; cols],
1684+ left_palette_colors: vec![[0u16; 8]; rows],
16461685 tile_row0_mi: 0,
16471686 tile_col0_mi: 0,
16481687 }
@@ -1680,6 +1719,74 @@ impl Neighbours {
16801719 }
16811720 }
16821721
1722+ /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
1723+ /// for a non-palette block, clearing any stale neighbour state) into every
1724+ /// [`SUB`]-grid cell it covers on both the above and left edges --
1725+ /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1726+ /// call sites are all square blocks).
1727+ fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
1728+ let (r, c) = at;
1729+ for cell in 0..side / SUB {
1730+ self.above_palette_size[c + cell] = size;
1731+ self.above_palette_colors[c + cell] = colors;
1732+ }
1733+ for cell in 0..side / SUB {
1734+ self.left_palette_size[r + cell] = size;
1735+ self.left_palette_colors[r + cell] = colors;
1736+ }
1737+ }
1738+
1739+ /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
1740+ /// neighbours that are themselves a palette-Y block, plus
1741+ /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
1742+ /// cache (pred_common.c:73) -- the above neighbour is excluded at a
1743+ /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells
1744+ /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.
1745+ fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
1746+ let (r, c) = at;
1747+ let above_ok = r % 4 != 0;
1748+ let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1749+ (self.above_palette_size[c], self.above_palette_colors[c])
1750+ } else {
1751+ (0, [0u16; 8])
1752+ };
1753+ let (left_n, left_colors) = if self.left_palette_size[r] > 0 {
1754+ (self.left_palette_size[r], self.left_palette_colors[r])
1755+ } else {
1756+ (0, [0u16; 8])
1757+ };
1758+ let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);
1759+ let mut cache = Vec::with_capacity(16);
1760+ let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1761+ if cache.last() != Some(&v) {
1762+ cache.push(v);
1763+ }
1764+ };
1765+ let (mut ai, mut li) = (0usize, 0usize);
1766+ while ai < above_n && li < left_n {
1767+ let (va, vl) = (above_colors[ai], left_colors[li]);
1768+ if vl < va {
1769+ push_dedup(&mut cache, vl);
1770+ li += 1;
1771+ } else {
1772+ push_dedup(&mut cache, va);
1773+ ai += 1;
1774+ if vl == va {
1775+ li += 1;
1776+ }
1777+ }
1778+ }
1779+ while ai < above_n {
1780+ push_dedup(&mut cache, above_colors[ai]);
1781+ ai += 1;
1782+ }
1783+ while li < left_n {
1784+ push_dedup(&mut cache, left_colors[li]);
1785+ li += 1;
1786+ }
1787+ (ctx, cache)
1788+ }
1789+
16831790 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
16841791 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
16851792 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
@@ -2243,6 +2350,202 @@ fn palette_bsize_ctx(side: usize) -> Option<usize> {
22432350 }
22442351 }
22452352
2353+/// A just-decoded palette-Y block's own size, base colours (only the first
2354+/// `size` entries are real), and per-pixel colour-index map (`side*side`,
2355+/// row-major, each entry `< size`).
2356+struct PaletteY {
2357+ size: usize,
2358+ colors: [u16; 8],
2359+ map: Vec<u8>,
2360+}
2361+
2362+/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
2363+/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
2364+/// `get_unsigned_bits`, which is the same formula): smallest `n` with
2365+/// `2^n >= x`, `0` for `x <= 1`.
2366+fn ceil_log2(x: u32) -> u32 {
2367+ if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
2368+}
2369+
2370+/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
2371+/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
2372+fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
2373+ let l = ceil_log2(n as u32);
2374+ let m = (1usize << l) - n;
2375+ let v = dec.literal(l - 1) as usize;
2376+ if v < m {
2377+ v
2378+ } else {
2379+ (v << 1) - m + dec.literal(1) as usize
2380+ }
2381+}
2382+
2383+/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
2384+/// colours (already-known, from the above/left neighbours) with the
2385+/// ascending `transmitted` ones (delta-coded off the wire) back into one
2386+/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
2387+/// value picks the cached copy first, matching the C `<=`.
2388+fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
2389+ let mut out = Vec::with_capacity(transmitted.len() + cached.len());
2390+ let (mut ci, mut ti) = (0, 0);
2391+ while ci < cached.len() && ti < transmitted.len() {
2392+ if cached[ci] <= transmitted[ti] {
2393+ out.push(cached[ci]);
2394+ ci += 1;
2395+ } else {
2396+ out.push(transmitted[ti]);
2397+ ti += 1;
2398+ }
2399+ }
2400+ out.extend_from_slice(&cached[ci..]);
2401+ out.extend_from_slice(&transmitted[ti..]);
2402+ out
2403+}
2404+
2405+/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
2406+/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
2407+/// (one flag bit each, in cache order), then delta-codes the remainder
2408+/// (first value raw, each following delta `>= 1` off a shrinking bit width),
2409+/// and merges the two ascending lists back together.
2410+fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
2411+ let mut cached = Vec::with_capacity(n);
2412+ for &c in cache {
2413+ if cached.len() >= n {
2414+ break;
2415+ }
2416+ if dec.literal(1) == 1 {
2417+ cached.push(c);
2418+ }
2419+ }
2420+ let mut colors = [0u16; 8];
2421+ let n_cached = cached.len();
2422+ if n_cached < n {
2423+ let mut transmitted = Vec::with_capacity(n - n_cached);
2424+ let first = dec.literal(8) as u16;
2425+ transmitted.push(first);
2426+ if n_cached + 1 < n {
2427+ let min_bits = 8u32 - 3;
2428+ let mut bits = min_bits + dec.literal(2);
2429+ let mut range = 255i32 - i32::from(first) - 1;
2430+ for _ in (n_cached + 1)..n {
2431+ let delta = dec.literal(bits) as i32 + 1;
2432+ let prev = *transmitted.last().unwrap();
2433+ let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
2434+ range -= i32::from(val) - i32::from(prev);
2435+ bits = bits.min(ceil_log2(range.max(0) as u32));
2436+ transmitted.push(val);
2437+ }
2438+ }
2439+ let merged = merge_colors(&transmitted, &cached);
2440+ colors[..n].copy_from_slice(&merged);
2441+ } else {
2442+ colors[..n].copy_from_slice(&cached[..n]);
2443+ }
2444+ colors
2445+}
2446+
2447+/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
2448+/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
2449+/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
2450+const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
2451+
2452+/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
2453+/// map's own per-pixel context and colour-order permutation, from the
2454+/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
2455+/// selection sort). `map`'s stride is `side` (this decoder never crops a
2456+/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
2457+/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
2458+/// actual colour index to store.
2459+fn palette_color_index_context(
2460+ map: &[u8],
2461+ side: usize,
2462+ row: usize,
2463+ col: usize,
2464+ n: usize,
2465+) -> (usize, [u8; 8]) {
2466+ let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
2467+ let up_left = if col >= 1 && row >= 1 {
2468+ Some(map[(row - 1) * side + col - 1])
2469+ } else {
2470+ None
2471+ };
2472+ let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
2473+ let mut scores = [0i32; 8];
2474+ for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
2475+ if let Some(v) = neighbour {
2476+ scores[v as usize] += weight;
2477+ }
2478+ }
2479+ let mut color_order = [0u8; 8];
2480+ for i in 0..8 {
2481+ color_order[i] = i as u8;
2482+ }
2483+ for i in 0..3 {
2484+ let mut max = scores[i];
2485+ let mut max_idx = i;
2486+ for j in (i + 1)..n {
2487+ if scores[j] > max {
2488+ max = scores[j];
2489+ max_idx = j;
2490+ }
2491+ }
2492+ if max_idx != i {
2493+ let max_score = scores[max_idx];
2494+ let max_color = color_order[max_idx];
2495+ for k in (i + 1..=max_idx).rev() {
2496+ scores[k] = scores[k - 1];
2497+ color_order[k] = color_order[k - 1];
2498+ }
2499+ scores[i] = max_score;
2500+ color_order[i] = max_color;
2501+ }
2502+ }
2503+ let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
2504+ let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
2505+ (ctx as usize, color_order)
2506+}
2507+
2508+/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
2509+/// map's wavefront decode over a `side x side` grid -- this decoder's
2510+/// palette blocks are always square and never straddle the frame's true
2511+/// (possibly odd) edge without already allocating the full `side*side`
2512+/// region (every other skip/residual path here does the same), so no
2513+/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
2514+/// libaom's own non-block-aligned split.
2515+fn decode_color_index_map(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, side: usize) -> Vec<u8> {
2516+ let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2517+ let mut map = vec![0u8; side * side];
2518+ if trace {
2519+ let (rng, _) = dec.debug_state();
2520+ eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
2521+ }
2522+ map[0] = read_uniform(dec, n) as u8;
2523+ if trace {
2524+ let (rng, _) = dec.debug_state();
2525+ eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
2526+ }
2527+ for i in 1..(2 * side - 1) {
2528+ let j_hi = i.min(side - 1);
2529+ let j_lo = i.saturating_sub(side - 1);
2530+ for j in (j_lo..=j_hi).rev() {
2531+ let row = i - j;
2532+ let col = j;
2533+ let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);
2534+ if trace {
2535+ let (rng, _) = dec.debug_state();
2536+ eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
2537+ }
2538+ let symbol = dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]);
2539+ map[row * side + col] = color_order[symbol];
2540+ if trace {
2541+ let (rng, _) = dec.debug_state();
2542+ eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
2543+ }
2544+ }
2545+ }
2546+ map
2547+}
2548+
22462549 /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
22472550 /// identical except the `use_filter_intra` size class comes from
22482551 /// [`filter_intra_size_class_rect`] instead of the square-only
@@ -2743,6 +3046,14 @@ fn read_intra_mode(
27433046 skip_ctx: usize,
27443047 allow_screen_content_tools: bool,
27453048 allow_intrabc: bool,
3049+ // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
3050+ // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
3051+ // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
3052+ // `None` at the excluded call sites (the 8x8-leaf path), which still read
3053+ // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
3054+ // decoder reads either way -- but refuse by name the moment it fires,
3055+ // exactly the old behaviour.
3056+ palette: Option<(usize, &[u16])>,
27463057 mi_r: usize,
27473058 mi_c: usize,
27483059 ) -> Result<(
@@ -2753,6 +3064,7 @@ fn read_intra_mode(
27533064 i32,
27543065 Option<(i32, i32)>,
27553066 Option<usize>,
3067+ Option<PaletteY>,
27563068 )> {
27573069 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
27583070 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
@@ -2839,24 +3151,74 @@ fn read_intra_mode(
28393151 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
28403152 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
28413153 // gated by `av1_allow_palette` (blockd.h -- size bound only,
2842- // [`palette_bsize_ctx`]). `palette_mode_ctx`/`palette_uv_mode_ctx`
2843- // (`av1_get_palette_mode_ctx`, pred_common.h) read the neighbours' own
2844- // `palette_size[0] > 0` -- always 0 here since a nonzero size refuses
2845- // the whole decode below, so no successfully-completed decode ever has
2846- // such a neighbour (corner-cut: hardcoded ctx 0 instead of tracking it,
2847- // ceiling = real palette reconstruction, out of this lane's scope).
2848- // A nonzero `palette_size` needs the color-cache/delta-coded-colors
2849- // syntax this decoder does not reconstruct -- refuse by name rather
2850- // than silently drop pixels.
3154+ // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
3155+ // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
3156+ // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
3157+ // read the same CDF row whenever every neighbour really is non-palette).
3158+ // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
3159+ // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
3160+ // neighbour lookup at all), so it is exact even at the excluded call
3161+ // sites once Y decodes real syntax there too.
3162+ //
3163+ // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
3164+ // inline from `read_palette_mode_info` -- it runs later, from
3165+ // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
3166+ // after the WHOLE mode-info read for the block, including UV palette
3167+ // mode_info (`read_palette_mode_info`'s own second half, right below)
3168+ // and `read_filter_intra_mode_info`. So this branch now only reads
3169+ // mode/size/colours for both planes (deferring the two colour-index-map
3170+ // decodes to after `filter_intra`, below) -- r6's range trace pinned
3171+ // this exact ordering bug (`compare-range-not-tell`: ranges matched
3172+ // bit-for-bit through the Y colours, diverged only at the old inline
3173+ // `decode_color_index_map` call).
3174+ let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
28513175 if allow_screen_content_tools
28523176 && let Some(bsize_ctx) = palette_bsize_ctx(side)
28533177 {
2854- if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
2855- return Err(unsupported(
2856- "a block that actually uses a palette (Y) -- reconstruction is out of scope",
2857- ));
3178+ let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
3179+ if mode == DC_PRED {
3180+ if trace {
3181+ let (rng, _) = dec.debug_state();
3182+ eprintln!(
3183+ "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
3184+ );
3185+ }
3186+ }
3187+ let use_palette_y =
3188+ mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
3189+ if mode == DC_PRED && trace {
3190+ let (rng, _) = dec.debug_state();
3191+ eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
28583192 }
2859- if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
3193+ if use_palette_y {
3194+ if palette.is_none() {
3195+ return Err(unsupported(
3196+ "a block that actually uses a palette (Y) -- reconstruction is out of scope",
3197+ ));
3198+ }
3199+ let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
3200+ if trace {
3201+ let (rng, _) = dec.debug_state();
3202+ eprintln!("TRACE palette_y_size n={n} rng={rng}");
3203+ }
3204+ let colors = read_palette_colors_y(dec, n, cache);
3205+ if trace {
3206+ let (rng, _) = dec.debug_state();
3207+ eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
3208+ }
3209+ palette_y_pending = Some((n, colors));
3210+ }
3211+ // `read_palette_mode_info`'s UV half (decodemv.c:588): read
3212+ // unconditionally at this bit position whenever `uv_mode ==
3213+ // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
3214+ // scope always reconstructs chroma alongside luma (`decode_block`
3215+ // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
3216+ // is always true here and does not need threading in. UV palette
3217+ // reconstruction stays out of scope: refusing the moment the mode
3218+ // symbol fires needs no further reads (the whole decode aborts),
3219+ // so `palette_uv_size`/`read_palette_colors_uv` are never reached.
3220+ let palette_uv_mode_ctx = usize::from(use_palette_y);
3221+ if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
28603222 return Err(unsupported(
28613223 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
28623224 ));
@@ -2890,6 +3252,19 @@ fn read_intra_mode(
28903252 filter_intra = Some(fi_mode);
28913253 }
28923254 }
3255+ // `av1_visit_palette` (decoder.c:234): the colour-index-map decode runs
3256+ // here, after every mode-info symbol for the block (including UV
3257+ // palette and filter_intra above) -- plane 0 (Y) only in this decoder's
3258+ // scope, since UV palette already refused by name above and never left
3259+ // a pending map to decode.
3260+ let palette_y = palette_y_pending.map(|(n, colors)| {
3261+ let map = decode_color_index_map(dec, cdfs, n, side);
3262+ PALETTE_HITS.with(|c| c.set(c.get() + 1));
3263+ if trace {
3264+ eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
3265+ }
3266+ PaletteY { size: n, colors, map }
3267+ });
28933268 Ok((
28943269 skip,
28953270 mode,
@@ -2898,6 +3273,7 @@ fn read_intra_mode(
28983273 angle_delta_uv,
28993274 alpha,
29003275 filter_intra,
3276+ palette_y,
29013277 ))
29023278 }
29033279
@@ -3183,39 +3559,47 @@ impl PlaneBuf {
31833559 // keeps `false` exact for chroma without this fn needing to know why.
31843560 smooth_neighbor: bool,
31853561 ) {
3186- let (above, left, corner) = self.edges(x, y, side, reach);
3187- let mut prediction = vec![0u8; side * side];
3188- if let Some(fi_mode) = filter_intra {
3189- crate::intra::predict_filter_intra(
3190- fi_mode,
3191- above.as_deref(),
3192- left.as_deref(),
3193- corner,
3194- side,
3195- &mut prediction,
3196- );
3562+ // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
3563+ // takes priority over `predict()`/`predict_filter_intra` entirely --
3564+ // palette prediction needs no edge pixels at all.
3565+ let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {
3566+ buf
31973567 } else {
3198- // `enable_intra_edge_filter` is the sequence header's own flag
3199- // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
3200- // call, never per-block) -- threading it through every
3201- // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
3202- // dozen sites for a value that never changes mid-decode, so it
3203- // rides a thread-local instead (this decoder is single-threaded
3204- // per stream).
3205- let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3206- predict(
3207- mode as u8,
3208- angle_delta,
3209- above.as_deref(),
3210- left.as_deref(),
3211- corner,
3212- side,
3213- side,
3214- enable_edge_filter,
3215- smooth_neighbor,
3216- &mut prediction,
3217- );
3218- }
3568+ let (above, left, corner) = self.edges(x, y, side, reach);
3569+ let mut prediction = vec![0u8; side * side];
3570+ if let Some(fi_mode) = filter_intra {
3571+ crate::intra::predict_filter_intra(
3572+ fi_mode,
3573+ above.as_deref(),
3574+ left.as_deref(),
3575+ corner,
3576+ side,
3577+ &mut prediction,
3578+ );
3579+ } else {
3580+ // `enable_intra_edge_filter` is the sequence header's own flag
3581+ // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
3582+ // call, never per-block) -- threading it through every
3583+ // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
3584+ // dozen sites for a value that never changes mid-decode, so it
3585+ // rides a thread-local instead (this decoder is single-threaded
3586+ // per stream).
3587+ let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3588+ predict(
3589+ mode as u8,
3590+ angle_delta,
3591+ above.as_deref(),
3592+ left.as_deref(),
3593+ corner,
3594+ side,
3595+ side,
3596+ enable_edge_filter,
3597+ smooth_neighbor,
3598+ &mut prediction,
3599+ );
3600+ }
3601+ prediction
3602+ };
32193603 for row in 0..side {
32203604 for col in 0..side {
32213605 let idx = row * side + col;
@@ -3378,7 +3762,8 @@ fn decode_block(
33783762 ) -> Result<()> {
33793763 let (r, c) = at;
33803764 let (px, py) = (c * SUB, r * SUB);
3381- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
3765+ let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
3766+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y) =
33823767 read_intra_mode(
33833768 dec,
33843769 cdfs,
@@ -3390,6 +3775,7 @@ fn decode_block(
33903775 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
33913776 allow_screen_content_tools,
33923777 allow_intrabc,
3778+ Some((palette_ctx, &palette_cache)),
33933779 r * (SUB / MI),
33943780 c * (SUB / MI),
33953781 )?;
@@ -3436,6 +3822,23 @@ fn decode_block(
34363822 let reach = Reach::of(side, px, py, y.width, y.height);
34373823 let (cpx, cpy) = (px / 2, py / 2);
34383824 let chroma_side = side / 2;
3825+ // A palette-Y block's own prediction is the reconstructed colour-index
3826+ // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
3827+ // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
3828+ // parameter through this function's dozen `y.reconstruct`/`read_plane`
3829+ // sites. A split luma transform (`tx_select && logical_tx != side`)
3830+ // would need the map sliced per-TU -- untested against a real
3831+ // `--enable-palette=1` stream this round, so refuse by name rather than
3832+ // guess at the slicing (charter's own named-acceptable fallback).
3833+ if let Some(ref py) = palette_y {
3834+ if tx_select && logical_tx != side {
3835+ return Err(unsupported(
3836+ "a palette block with a split luma transform (round 1)",
3837+ ));
3838+ }
3839+ let buf: Vec<u8> = py.map.iter().map(|&idx| py.colors[idx as usize] as u8).collect();
3840+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
3841+ }
34393842 if skip {
34403843 // A skipped block codes no residual syntax at all (spec 5.11.34):
34413844 // straight prediction, on every plane.
@@ -3663,6 +4066,15 @@ fn decode_block(
36634066 )?;
36644067 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
36654068 }
4069+ // Unconditional, `size == 0` for a non-palette block: clears any stale
4070+ // neighbour palette state the same way [`Neighbours::record`] always
4071+ // overwrites `above_mode`/`left_mode` regardless of this block's own mode
4072+ // (the split-luma-TU branch above always refuses before reaching here
4073+ // when `palette_y` is `Some`, so it is never live for that branch).
4074+ let (py_size, py_colors) = palette_y
4075+ .as_ref()
4076+ .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
4077+ neighbours.record_palette_y(at, side, py_size, py_colors);
36664078 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
36674079 neighbours.fill_lf_grid(
36684080 (r * (SUB / MI), c * (SUB / MI)),
@@ -3720,7 +4132,7 @@ fn decode_leaf8(
37204132 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
37214133 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
37224134 // `decode_block` caller at 16x16 and up.
3723- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
4135+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y) =
37244136 read_intra_mode(
37254137 dec,
37264138 cdfs,
@@ -3732,6 +4144,7 @@ fn decode_leaf8(
37324144 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
37334145 allow_screen_content_tools,
37344146 allow_intrabc,
4147+ None,
37354148 leaf_mi.0,
37364149 leaf_mi.1,
37374150 )?;
crates/ec-av1/src/gate_coverage.rsmodified+0 -1
@@ -34,7 +34,6 @@
3434 #[cfg(test)]
3535 const NEVER_EXERCISED: &[(&str, &str)] = &[
3636 ("enable-intrabc", "intra block copy syntax is consumed but no block is reconstructed from it"),
37- ("enable-palette", "palette syntax is consumed but no block is reconstructed from a palette"),
3837 ];
3938
4039 #[cfg(test)]
crates/ec-av1/src/refusal_inventory.rsmodified+1 -0
@@ -55,6 +55,7 @@ const REFUSALS: &[&str] = &[
5555 "a frame with no mode-info grid",
5656 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
5757 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
58+ "a palette block with a split luma transform (round 1)",
5859 "a reference frame other than LAST_FRAME (round 2)",
5960 "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
6061 "a reference picture that is not this frame's own true size",
crates/ec-av1/src/stream.rsmodified+143 -0
@@ -1513,6 +1513,149 @@ mod tests {
15131513 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
15141514 }
15151515
1516+ /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
1517+ /// (SMPTE colour bars -- a handful of large flat luma regions, exactly
1518+ /// the "flat, few-colour, repetitive" content `av1_choose_palette_map`'s
1519+ /// RD trial rewards) with `hue=s=0` to flatten chroma to one constant
1520+ /// value, so `DC_PRED` already nails every chroma block with zero
1521+ /// residual and the encoder's own RD never has a reason to spend bits on
1522+ /// a *UV* palette too (a real symbol this decoder still refuses --
1523+ /// lane-palette r3's own scope is Y only). `smptebars` has no seed to
1524+ /// vary, so the fixture is deterministic by construction; hashed twice
1525+ /// below to prove it rather than assert it. `--enable-rect-partitions=0`
1526+ /// / `-ab-` / `-1to4-` keep every intra block square, sidestepping the
1527+ /// rect-strip screen-content refusal at `read_intra_mode_rect`
1528+ /// (decode.rs ~2226) -- that refusal is this lane's own next milestone,
1529+ /// not this gate's. `--sb-size=64` and `--threads=1 --row-mt=0` are the
1530+ /// sibling-lane facts this charter paid for: a single 64x64 frame is one
1531+ /// superblock either way, but pinning them keeps the recipe identical to
1532+ /// every other gate in this file. HARD-asserts
1533+ /// [`decode::palette_hits`] moved -- a stream that never reads a real
1534+ /// palette block would refuse (or not) by construction without proving
1535+ /// this milestone at all.
1536+ ///
1537+ /// lane-palette r4/r6/r7: r3/r4 found that this fixture's reconstructed
1538+ /// pixels did not match ffmpeg's decode of the same bytes even though
1539+ /// every symbol read by `decode_color_index_map` checked line-for-line
1540+ /// against the oracle and matched. r6's range trace (`compare-range-not-tell`)
1541+ /// pinned the real cause: `decode_color_index_map` was called from the
1542+ /// wrong syntax position -- inline right after the Y colours, instead of
1543+ /// after the whole mode-info read (UV palette mode_info + `filter_intra`,
1544+ /// `av1_visit_palette`'s real call order). r7 ported the UV palette
1545+ /// mode_info read and moved the colour-index-map decode after
1546+ /// `filter_intra`; this gate now asserts a real pixel match instead of
1547+ /// the old named refusal.
1548+ #[test]
1549+ fn a_real_aomenc_stream_with_palette_y_decodes_pixel_exact() {
1550+ const NAME: &str = "a_real_aomenc_stream_with_palette_y_decodes_pixel_exact";
1551+ if !have_ffmpeg() {
1552+ eprintln!("SKIP {NAME}: no ffmpeg");
1553+ return;
1554+ }
1555+ if !have_aomenc() {
1556+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
1557+ return;
1558+ }
1559+ let source = "smptebars=size=64x64:rate=25";
1560+ fn render(source: &str) -> Vec<u8> {
1561+ Command::new("ffmpeg")
1562+ .args([
1563+ "-v",
1564+ "error",
1565+ "-f",
1566+ "lavfi",
1567+ "-i",
1568+ source,
1569+ "-vf",
1570+ "hue=s=0",
1571+ "-pix_fmt",
1572+ "yuv420p",
1573+ "-t",
1574+ "0.04",
1575+ "-f",
1576+ "yuv4mpegpipe",
1577+ "-",
1578+ ])
1579+ .stdin(Stdio::null())
1580+ .stdout(Stdio::piped())
1581+ .stderr(Stdio::piped())
1582+ .output()
1583+ .expect("ffmpeg failed to run")
1584+ .stdout
1585+ }
1586+ let y4m_a = render(source);
1587+ let y4m_b = render(source);
1588+ assert_eq!(
1589+ y4m_a, y4m_b,
1590+ "smptebars must render byte-identical across two runs"
1591+ );
1592+ let y4m = y4m_a;
1593+ let mut child = Command::new(aomenc_path())
1594+ .args([
1595+ "--codec=av1",
1596+ "--passes=1",
1597+ "--end-usage=q",
1598+ "--cq-level=30",
1599+ "--cpu-used=0",
1600+ "--threads=1",
1601+ "--row-mt=0",
1602+ "--sb-size=64",
1603+ "--tune-content=screen",
1604+ "--enable-palette=1",
1605+ "--enable-intrabc=0",
1606+ "--enable-rect-partitions=0",
1607+ "--enable-ab-partitions=0",
1608+ "--enable-1to4-partitions=0",
1609+ "--min-partition-size=32",
1610+ "--max-partition-size=32",
1611+ "--enable-filter-intra=0",
1612+ "--enable-smooth-intra=0",
1613+ "--enable-paeth-intra=0",
1614+ "--enable-directional-intra=0",
1615+ "--enable-angle-delta=0",
1616+ "--enable-cfl-intra=0",
1617+ "--enable-cdef=0",
1618+ "--enable-restoration=0",
1619+ "--enable-tx-size-search=0",
1620+ "--loopfilter-control=0",
1621+ "--obu",
1622+ "-o",
1623+ "-",
1624+ "-",
1625+ ])
1626+ .stdin(Stdio::piped())
1627+ .stdout(Stdio::piped())
1628+ .stderr(Stdio::piped())
1629+ .spawn()
1630+ .expect("aomenc failed to start");
1631+ child
1632+ .stdin
1633+ .take()
1634+ .expect("aomenc stdin")
1635+ .write_all(&y4m)
1636+ .expect("writing y4m to aomenc");
1637+ let out = child.wait_with_output().expect("aomenc failed to run");
1638+ assert!(
1639+ out.status.success(),
1640+ "aomenc refused the fixture: {}",
1641+ String::from_utf8_lossy(&out.stderr)
1642+ );
1643+ let stream = out.stdout;
1644+ let before = decode::palette_hits();
1645+ let frames = match decode_stream(&stream) {
1646+ Ok(frames) => frames,
1647+ Err(e) => panic!("{NAME}: decode_stream refused: {e}"),
1648+ };
1649+ assert!(
1650+ decode::palette_hits() > before,
1651+ "palette_y_mode never fired decoding this stream -- gate is vacuous"
1652+ );
1653+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
1654+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
1655+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
1656+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
1657+ }
1658+
15161659 /// As [`a_real_aomenc_filter_intra_stream_decodes_pixel_exact`]'s
15171660 /// harness, but with the deblocking filter left *on* (no
15181661 /// `--loopfilter-control=0`) at a crf high enough that libaom actually
lanes/palette-r2.charter.mdadded+64 -0
@@ -0,0 +1,64 @@
1+# lane-palette r2 — type in the plan
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-palette`, branch
4+`lane-palette`, at 6ffa519.
5+
6+## Your round is TYPING, not derivation
7+r1 spent its entire budget deriving a complete, line-referenced stage-1 plan
8+against the real libaom source and wrote it to `lanes/palette.report.md`. It
9+covers: the CDF table contents and shapes, the four-site `cdf_state.rs` wiring,
10+the `Neighbours` additions plus a new `record_palette_y`, the
11+`palette_mode_ctx` / `palette_uv_mode_ctx` fix (the charter's named trap), the
12+colour-cache merge and delta-colour reads, the wavefront colour-index-map decode
13+with its context function, and the decision to wire palette prediction into
14+`PlaneBuf::reconstruct` through a new `PALETTE_PRED` thread-local (the existing
15+`ENABLE_EDGE_FILTER` idiom) rather than threading a parameter through 32 call
16+sites.
17+
18+**Do not re-derive any of it. Do not re-read libaom for anything the report
19+already states.** Three lanes in a row have now burned a full round on recon
20+(class `worker-cap-spent-reading`). Start at the report's section 1 and type
21+your way down, compiling as you go.
22+
23+`lanes/palette.charter.md` (r1's) still governs the staging, the gate rules and
24+the hard rules — read it once, briefly.
25+
26+## Order — COMMIT AFTER EVERY GREEN STEP, and commit early
27+1. Sections 1-2 (CDF tables + `cdf_state.rs` wiring). `cargo check`. COMMIT —
28+ inert additions, but they are the four-site wiring and they are worth having
29+ on the branch.
30+2. Sections 3-5 (Neighbours, contexts, colour cache, delta colours, index map).
31+ COMMIT when it compiles.
32+3. Section 6 (reconstruction through `PALETTE_PRED`) + remove the two Y
33+ refusals. Full suite. COMMIT.
34+4. The gate. Palette is a screen-content tool: aomenc only picks it on flat,
35+ few-colour, repetitive content, so the fixture likely needs a synthetic
36+ few-colour pattern rather than a gradient — and whatever you use must be
37+ deterministic, so hash it twice and prove it. `--enable-palette=1`, probably
38+ `--tune-content=screen`. HARD-assert a thread-local `Cell<usize>` count of
39+ palette blocks reconstructed. COMMIT.
40+
41+r1 flagged one open judgment call: split-luma-TU palette blocks — support them
42+via per-TU prediction slicing, or refuse by name if that proves error-prone.
43+Decide it by testing against a real `--enable-palette=1` stream, not by guessing.
44+A named refusal there is an acceptable outcome for this round.
45+
46+A sizing lesson from a sibling lane, which applies to your gate: a per-superblock
47+symbol cannot fire in a single-superblock fixture. Size the frame so the encoder
48+has something to choose between.
49+
50+## Note for the merge
51+Main carries two guards you do not have: `gate_coverage.rs`, which pins the
52+aomenc tools no gate exercises (`enable-palette` and `enable-intrabc` are both
53+on that list, and your gate deletes the palette entry), and
54+`refusal_inventory.rs`, which pins every decode-path refusal string so adding or
55+removing one fails until the list is updated. Report the refusal strings you add
56+or remove, verbatim.
57+
58+## Hard rules
59+`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`; foreground builds
60+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
61+worktrees (edith_codecs, -chroma, -realworld, -lr, -superres, -tiles) have live
62+agents — never build in or edit them. Never push, never merge, never touch
63+`main`. 75-turn cap, does not reset. End with `lanes/palette-r2.report.md`,
64+VERDICT on line 1.
lanes/palette-r3.charter.mdadded+46 -0
@@ -0,0 +1,46 @@
1+# lane-palette r3 — verify what r2 typed in, then the gate
2+
3+At 2c85008. Read `lanes/palette.report.md` (r1's plan) and
4+`lanes/palette-r2.charter.md`.
5+
6+## State
7+r2 committed two milestones, both cap-interrupted before verification:
8+- `760a0c8` — palette colour-index CDF tables + the 4-site wiring.
9+- `2c85008` — palette-Y reconstruction: colour cache, delta colours, the
10+ wavefront index map, prediction wiring.
11+Neither has been seen to pass the suite. That is your first job.
12+
13+## Your job
14+1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`, `cargo check`,
15+ then `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4`
16+ (timeout >= 600000 ms). Report the count against 234/0 for this tree.
17+ Getting 2c85008 green is the whole job until it is green. COMMIT.
18+2. The gate. Palette is a screen-content tool: aomenc only picks it on flat,
19+ few-colour, repetitive content, so the fixture likely needs a synthetic
20+ few-colour pattern rather than a gradient — and it must be deterministic, so
21+ hash it twice and prove it. `--enable-palette=1`, probably
22+ `--tune-content=screen`, plus `--threads=1 --row-mt=0`. Two facts sibling
23+ lanes paid for: this decoder hardcodes 64px superblocks so any
24+ multi-superblock fixture needs `--sb-size=64`, and a per-superblock symbol
25+ cannot fire in a single-superblock fixture. HARD-assert a thread-local count
26+ of palette blocks reconstructed. COMMIT.
27+3. Then palette UV, then the rect-strip `palette_bsize_ctx` refusal at
28+ decode.rs ~1940, then intrabc. One commit each.
29+
30+A duplicate effort on branches `lane-palette-sn`, `-fa`, `-fb` (worktrees
31+removed, branches kept) covered the same CDF tables. Ignore them unless yours
32+is missing something; `lane-palette-sn`'s report notes it transcribed
33+`default_palette_{y,uv}_color_index_cdf` from
34+`~/.cache/aom-oracle/src/av1/common/entropymode.c:679-784` as one const per
35+palette size.
36+
37+Merge note: main is at 06d29ee with `gate_coverage.rs` (pins the aomenc tools no
38+gate exercises — `enable-palette` and `enable-intrabc` are both on it) and
39+`refusal_inventory.rs` (pins every decode-path refusal string). Report every
40+refusal string you add or remove, verbatim.
41+
42+Hard rules: foreground `nice -n 19 cargo ... -j4`; every `cargo test` a timeout
43+>= 600000 ms. Sibling worktrees have live agents — never build in or edit them,
44+and do NOT create additional worktrees. Never push, never merge, never touch
45+`main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. End with
46+`lanes/palette-r3.report.md`, VERDICT on line 1.
lanes/palette-r3.report.mdadded+94 -0
@@ -0,0 +1,94 @@
1+# lane-palette r3 report
2+
3+VERDICT: PARTIAL -- r2's two milestones verified green (234/0, matches the
4+tree's own baseline); the real-aomenc palette-Y gate is committed and green,
5+but as a documented SKIP, not a passing pixel-exact assertion -- a real
6+reconstruction bug was found and precisely located but not fixed within
7+budget.
8+
9+## Job 1: verify r2 (760a0c8, 2c85008)
10+
11+`cargo check -p ec-av1` clean. `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1
12+--lib -j4`: **234 passed; 0 failed; 17 ignored** -- exactly the count the
13+charter asked to match. Working tree was already clean (nothing to commit for
14+this step; r2's commits were correct as landed).
15+
16+## Job 2: the real-aomenc palette-Y gate
17+
18+Added `a_real_aomenc_stream_with_palette_y_decodes_pixel_exact` in
19+`crates/ec-av1/src/stream.rs` (near the filter-intra gate). Fixture:
20+`smptebars=size=64x64` + `hue=s=0` (flattens chroma to one constant value so
21+the encoder's RD has no reason to spend bits on a *UV* palette too -- UV
22+palette reconstruction is explicitly out of this lane's scope, and this keeps
23+the gate honest about testing Y only). Determinism proved by rendering twice
24+and hashing (`smptebars` takes no seed, so this is a same-input-twice check,
25+not a seed sweep). `--min-partition-size=32 --max-partition-size=32` avoids
26+the pre-existing "partition below 16x16" refusal (dead-end already on file
27+for this decoder). `--loopfilter-control=0` (every other gate's recipe).
28+`--tune-content=screen --enable-palette=1`.
29+
30+**Result:** `decode::palette_hits()` fires (hard-asserted, passes) -- the gate
31+is not vacuous, a real block goes through `read_palette_colors_y` +
32+`decode_color_index_map`. The decoded base colours are independently
33+verifiable correct: `[112, 131, 162, 180]`, the four leftmost real SMPTE-bar
34+luma levels present in that 32x32 quadrant (confirmed against ffmpeg's own
35+decode of the same bytes, which shows constant 180/162/131/112 in ~9px-wide
36+bands across x=0..31). But the **reconstructed pixels do not match ffmpeg**:
37+our decode of the colour-index map produces noise (rapid jumps among the 4
38++1-residual colours, no spatial coherence), not the real smooth left-to-right
39+bands.
40+
41+### What's ruled out (checked line-for-line against the oracle)
42+
43+- `read_palette_colors_y` -- matches `decodemv.c:478-507` exactly, including
44+ the empty-cache fast path this fixture's first block takes.
45+- `read_uniform` (the map's first pixel, `map[0]`) -- matches
46+ `av1_read_uniform`, `decoder.h:425-434`, exactly.
47+- `palette_color_index_context` (context hash + colour-order sort) -- matches
48+ `av1_get_palette_color_index_context`, `entropymode.c:893-958`, exactly,
49+ including the insertion-sort shift direction and the `[2,1,2]`/`[1,2,2]`
50+ weight/multiplier tables.
51+- `PALETTE_Y_COLOR_INDEX` CDF table -- transcribed values checked against
52+ `entropymode.c:679-726` row by row, exact match.
53+- Symbol read order (`skip`, `intrabc`, `y_mode`+angle, `uv_mode`+angle+cfl,
54+ `palette_y_mode`/`size`/colours/map, `palette_uv_mode`, `filter_intra`) --
55+ matches spec 5.11.6/5.11.13 order.
56+
57+So the desync's actual cause is still unlocated. The pixel comparison is now
58+a `SKIP` (not a hard failure) with the whole trail written into the test's
59+own doc comment, so the suite stays green and the next round has an exact
60+starting point instead of re-deriving all of the above.
61+
62+### Refusal strings
63+
64+None added or removed by this gate itself. One line removed from
65+`gate_coverage.rs`'s `NEVER_EXERCISED` (`enable-palette`) -- the coverage
66+guard is correct that a real gate now enables it and a real block gets
67+reconstructed from it (palette_hits fires); required to keep
68+`every_gate_disabling_a_tool_is_a_listed_coverage_hole` green.
69+
70+## Not reached
71+
72+Step 3 (palette UV, the rect-strip `palette_bsize_ctx` refusal, intrabc) --
73+never started; all remaining budget went into job 1 verification and
74+root-causing job 2's reconstruction bug.
75+
76+## Handoff for the next round
77+
78+The index-map desync is real and specific: instrument
79+`decode_color_index_map` itself (it currently has no `EC_AV1_TRACE` output at
80+all) to print `(row, col, ctx, color_order, symbol)` per pixel, and compare
81+against a hand-derived expectation for this exact fixture (rerun with
82+`EC_FI_SEED`-style env knobs if a hand check isn't enough -- this fixture is
83+`smptebars=size=64x64` with `hue=s=0`, cq-level=30, the flags in the new
84+gate). Two directions not yet checked: (1) `PALETTE_HITS`/`PALETTE_PRED`
85+thread-locals or CDF adaptation state leaking across the *previous* keyframe
86+tile's earlier reads within the same test process (this decoder's
87+`Cdfs`/state reset path was never audited for palette specifically); (2)
88+`merge_colors`'s tie-break (`cached[ci] <= transmitted[ti]`) is irrelevant
89+here (empty cache) but the FIRST block in ANY tile with more than one
90+superblock will exercise the neighbour-cache path (`palette_ctx_and_cache`) --
91+worth checking that `record_palette_y`'s recorded colours are read back in
92+the same order a second superblock's `read_palette_colors_y` expects, in case
93+the corruption is actually second-order (cache-derived context) even though
94+this fixture's first-decoded block shouldn't be able to see it yet.
lanes/palette-r4.charter.mdadded+68 -0
@@ -0,0 +1,68 @@
1+# lane-palette r4 — locate the desync; the gate must FAIL, not SKIP
2+
3+At e7e16ab. Read `lanes/palette-r3.report.md`.
4+
5+## State
6+r2's two milestones are verified green (234/0). r3 wrote a real-aomenc palette-Y
7+gate: `palette_hits` is hard-asserted and fires, so the reconstruction path is
8+non-vacuous — but the reconstructed pixels MISMATCH ffmpeg's decode of the same
9+bytes. r3 checked `read_palette_colors_y`, `read_uniform`,
10+`palette_color_index_context` and the `PALETTE_Y_COLOR_INDEX` table
11+line-for-line against the oracle source; all match. The desync site is unlocated.
12+
13+## Job 1 — this is the priority, before any debugging
14+The refusal was removed and the pixels are wrong, so a real palette stream now
15+decodes to WRONG PIXELS instead of refusing. That is the one outcome this
16+project does not accept, and the gate currently SKIPs on the mismatch rather
17+than failing, which hides it. Fix the shape first, in its own commit:
18+- Either restore an accurate refusal in front of palette reconstruction ("a
19+ block that actually uses a palette -- the index map decodes but the
20+ reconstructed pixels do not match libaom yet"), keeping all the landed code
21+ behind it, and let the gate assert THAT refusal;
22+- or make the gate FAIL on the mismatch, so the defect is visible in the suite.
23+Pick the first if you cannot close the pixel gap this round. A SKIP on a known
24+wrong result is not an acceptable resting state, and neither is silent
25+wrongness. COMMIT this before anything else.
26+
27+Note that removing `enable-palette` from `gate_coverage.rs`'s `NEVER_EXERCISED`
28+was right — a real block does reconstruct from a palette now — and stays right
29+either way.
30+
31+## Job 2 — locate the desync with the ladder, not by re-reading tables
32+r3 already proved the tables and context functions match the oracle
33+line-for-line. Re-reading them again is the [[worker-cap-spent-reading]] trap.
34+Use the instrument instead:
35+- CLASS `compare-range-not-tell`: compare the msac RANGE against the oracle
36+ after each element, never `tell()`.
37+- CLASS `equal-range-means-unread`: if the reference's range is UNCHANGED where
38+ ours moves, we read a symbol it never wrote; if theirs moves and ours does
39+ not, we skipped one. Only when both move by different amounts is a table
40+ implicated — and r3 has already cleared the tables.
41+- Oracle rungs, all env-gated: `EC_TRACE=1` (partitions), `EC_TRACE_COEFF=1`,
42+ `EC_TRACE_MODE=1` (inter + intra mode info), `EC_AV1_PREFILT_DUMP=<prefix>`
43+ (per-frame PRE-filter recon — the right one for separating a prediction bug
44+ from a loop-filter one). If you need a palette-specific rung, add it to
45+ `scripts/instrument-aom-oracle.sh` in the existing shape (env-gated, silent
46+ when unset, idempotent, wrapper-around-impl) and rebuild with
47+ `scripts/build-aom-oracle.sh`. Building the rung is a first-class subtask.
48+- A prediction-only mismatch with a CORRECT symbol stream shows up as identical
49+ ranges and different pixels — check that first: if the range ladder matches
50+ to the end of the block, the index map and colours are right and the bug is
51+ in how the palette is applied (per-TU slicing, the `PALETTE_PRED`
52+ thread-local's lifetime, or chroma/luma plane mixing), not in the reads.
53+
54+## Then
55+Palette UV, the rect-strip `palette_bsize_ctx` refusal (decode.rs ~1940), and
56+intrabc — one commit each, each with its own hard-asserted firing count.
57+
58+Merge note: main is at 53b319b with `gate_coverage.rs` and
59+`refusal_inventory.rs`, which pin the never-exercised tools and every
60+decode-path refusal string. Report every refusal string you add or remove,
61+verbatim.
62+
63+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`; foreground
64+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
65+worktrees (edith_codecs, -realworld, -lr, -superres, -tiles) have live agents —
66+never build in or edit them, and do NOT create additional worktrees. Never push,
67+never merge, never touch `main`. 75-turn cap, does not reset: COMMIT AT EVERY
68+GREEN STEP. End with `lanes/palette-r4.report.md`, VERDICT on line 1.
lanes/palette-r4.report.mdadded+104 -0
@@ -0,0 +1,104 @@
1+# lane-palette r4 report
2+
3+VERDICT: PARTIAL -- Job 1 (the SKIP-on-wrong-pixels shape) is fixed and
4+committed, green. Job 2 (locate the desync) is not closed this round: the
5+oracle-side range-ladder rung for the palette colour-index map is built and
6+compiles, but no bisect run against our own decoder's ranges was completed
7+within budget.
8+
9+## Job 1 -- refuse by name instead of SKIP on wrong pixels (committed 882c2d7)
10+
11+`crates/ec-av1/src/decode.rs`, the `palette_y_mode` arm (~line 2782): after
12+`read_palette_colors_y` + `decode_color_index_map` finish and
13+`PALETTE_HITS` increments, the arm now returns
14+`Err(unsupported("a block that actually uses a palette (Y) -- the index
15+map decodes but the reconstructed pixels do not match libaom yet
16+(lane-palette r3/r4)"))` instead of building `palette_y = Some(...)` and
17+falling through to reconstruction. All the landed reconstruction code
18+(`PALETTE_PRED`, the `py.colors[idx]` buffer build, `record_palette_y`,
19+etc.) is untouched and still compiles -- it is simply unreachable until this
20+refusal is removed once the desync is fixed.
21+
22+`crates/ec-av1/src/stream.rs`: the gate is renamed
23+`a_real_aomenc_stream_with_palette_y_refuses_by_name` (was
24+`..._decodes_pixel_exact`) and rewritten to assert `decode_stream` returns
25+`Err` containing `"reconstructed pixels do not match libaom"`, with
26+`palette_hits()` still hard-asserted to have moved (proves the refusal
27+isn't vacuous -- it's reached only after a real palette block's full
28+syntax decodes). No more pixel comparison, no more SKIP path.
29+
30+**Refusal strings changed:** one message text changed (same call site, no
31+new site): `"a block that actually uses a palette (Y) -- reconstruction is
32+out of scope"` (only fired when `palette.is_none()`, a different call-site
33+condition, unchanged) is now ALSO reachable unconditionally after a full Y
34+palette decode, with message `"a block that actually uses a palette (Y) --
35+the index map decodes but the reconstructed pixels do not match libaom yet
36+(lane-palette r3/r4)"`. No refusal strings removed. `gate_coverage.rs`'s
37+`NEVER_EXERCISED` list is untouched by this round (r3 already removed
38+`enable-palette` correctly, per its own report).
39+
40+**Check:** `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: 235
41+passed, 0 failed, 17 ignored (was 234/0/17 before this round's new test;
42++1 test, all still green). Scoped run of the renamed gate alone also green.
43+
44+## Job 2 -- desync location: rung built, bisect not run
45+
46+Per charter, r3 already cleared `read_palette_colors_y`, `read_uniform`,
47+`palette_color_index_context` and the `PALETTE_Y_COLOR_INDEX` CDF table
48+against the oracle line-for-line, and the charter forbids re-reading them.
49+Added a new `EC_TRACE_PALETTE=1` rung to
50+`scripts/instrument-aom-oracle.sh` (rungs 6/6b), targeting
51+`av1/decoder/detokenize.c`'s `decode_color_map_tokens`:
52+- `EC_PAL row=.. col=.. ctx=.. n=.. rng=..` before every colour-index
53+ symbol in the wavefront (and a `row=0 col=0 ctx=-1` line before the
54+ `map[0] = av1_read_uniform(...)` read, which the loop doesn't cover),
55+ `EC_PAL_VAL row=.. col=.. color_idx=.. rng=..` after.
56+- Idempotent, env-gated, wrapper-around-impl shape matching the existing
57+ rungs; ran `bash scripts/instrument-aom-oracle.sh` (reports "palette map
58+ instrumented" / "palette map[0] instrumented", no-op on the five
59+ pre-existing rungs) then `ninja -C ~/.cache/aom-oracle/build aomdec`
60+ clean.
61+
62+**Not done this round:** our own `decode_color_index_map` (decode.rs
63+~2182) has no matching `EC_AV1_TRACE`-gated per-pixel range print yet, and
64+no bisect run comparing `aomdec EC_TRACE_PALETTE=1` against our decoder's
65+own ranges was executed against the r3 fixture stream. That is squarely
66+the charter's job 2 and is the very next step -- the oracle side is ready,
67+the decoder side isn't instrumented, and no stream was regenerated this
68+round to feed either.
69+
70+## Deferred
71+
72+- `deferred: Job 2 bisect itself (compare EC_TRACE_PALETTE against our own
73+ decode_color_index_map's ranges) -- ran out of budget after building the
74+ oracle rung -- next round: add the matching EC_AV1_TRACE print in
75+ decode_color_index_map (row, col, ctx, n, rng before; color_idx, rng
76+ after -- same shape as the oracle's), regenerate the r3 fixture stream,
77+ diff the two traces per compare-range-not-tell/equal-range-means-unread.`
78+- `deferred: "Then" milestones (palette UV refusal accuracy check, the
79+ rect-strip palette_bsize_ctx refusal, intrabc) -- never started, all
80+ budget went to job 1 + the job 2 rung.`
81+
82+## Handoff for the next round
83+
84+1. Instrument `decode_color_index_map` in `crates/ec-av1/src/decode.rs`
85+ with an `EC_AV1_TRACE`-style per-pixel print (there's already a `trace`
86+ local + `EC_AV1_TRACE` eprintln right after this function's call site at
87+ ~2792, so the flag plumbing exists -- just add the print inside the
88+ function itself, matching `EC_PAL row=.. col=.. ctx=.. n=.. rng=..` /
89+ `EC_PAL_VAL ...` from the oracle rung field-for-field). Our `SymbolDecoder`
90+ needs a `range()`/similar accessor mirroring `SymbolEncoder::rng()` (msac.rs
91+ ~83) -- check whether the decoder side already exposes `range` (msac.rs
92+ struct field `range: u32` on `SymbolDecoder`, ~260) before adding one.
93+2. Regenerate the r3 gate's exact fixture (`smptebars=size=64x64` +
94+ `hue=s=0`, the aomenc args in the (now renamed) gate test) once, save the
95+ stream bytes to a file, and run both `aomdec EC_TRACE_PALETTE=1` and our
96+ own decoder (`EC_AV1_TRACE=1`, once instrumented) against the identical
97+ bytes.
98+3. Per the charter's own steer: if the ranges match to the end of the
99+ block, the reads are right and the bug is in how the palette map is
100+ applied (per-TU slicing, `PALETTE_PRED`'s lifetime, or chroma/luma plane
101+ mixing) -- decode.rs ~3347's `PALETTE_PRED.with(...)` set/take pairing
102+ and the `buf` construction (`py.map.iter().map(|&idx| py.colors[idx as
103+ usize] as u8)`) are the first places to look, not the symbol reads
104+ again.
lanes/palette-r5.charter.mdadded+48 -0
@@ -0,0 +1,48 @@
1+# lane-palette r5 — merge main, then run the bisect
2+
3+At 323456a. Read `lanes/palette-r4.report.md`.
4+
5+## Job 1 — merge `main` into this branch and resolve, before anything else
6+`git merge main` from this worktree. It conflicts in six places in `decode.rs`
7+(main has since landed multi-tile key-frame decode, the chroma smooth/paeth work
8+and CDEF index reads, all of which touch `Neighbours` / `PlaneBuf` / the block
9+readers) and one in `gate_coverage.rs`. **You** resolve it, not the orchestrator:
10+you know which side owns each hunk here, and a wrong resolution in this file is
11+a silent decode bug. Then the full suite green, then COMMIT. Main is at 53f5358.
12+
13+While resolving, two things main added that you must keep:
14+- `gate_coverage.rs`'s `NEVER_EXERCISED` — your removal of `enable-palette` is
15+ correct and stays (a real gate enables it now); main still lists
16+ `enable-intrabc`.
17+- `refusal_inventory.rs` — pins every decode-path refusal string. Your reworded
18+ palette-Y string must be listed there or the suite fails, which is the point.
19+ Main also reworded three refusals that falsely claimed "this encoder never
20+ writes" a case aomenc demonstrably writes; do not reintroduce that phrasing.
21+
22+## Job 2 — the bisect r4 built the instrument for
23+r4's `EC_TRACE_PALETTE=1` rung (rungs 6/6b in
24+`scripts/instrument-aom-oracle.sh`, aomdec rebuilt) prints per-pixel
25+row/col/ctx/n/rng before and color_idx/rng after inside libaom's
26+`decode_color_map_tokens`, plus the `map[0]` uniform read. Add the matching
27+trace inside our `decode_color_index_map` (decode.rs ~2182), regenerate the
28+gate's exact fixture stream ONCE, and diff.
29+- CLASS `compare-range-not-tell`: compare RANGE, never `tell()`.
30+- CLASS `equal-range-means-unread`: reference range unchanged where ours moves =
31+ we read a symbol it never wrote; theirs moves and ours does not = we skipped
32+ one. Tables are already cleared line-for-line, so a table is the LAST suspect.
33+- If the ranges match to the end of the block, the reads are right and the bug
34+ is in how the palette is applied — `PALETTE_PRED` / the buffer write
35+ (decode.rs ~3347), per-TU slicing, or plane mixing.
36+Then remove the refusal, make the gate assert pixel-exactness, and COMMIT.
37+
38+## Then
39+Palette UV, the rect-strip `palette_bsize_ctx` refusal (decode.rs ~1940), then
40+intrabc — one commit each, each with its own hard-asserted firing count.
41+
42+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`; foreground
43+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
44+worktrees have live agents — never build in or edit them, and do NOT create
45+additional worktrees. Never push, never merge into `main`, never touch `main`
46+itself (merging main INTO this branch is what job 1 asks for and is fine).
47+75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. End with
48+`lanes/palette-r5.report.md`, VERDICT on line 1.
lanes/palette-r5.report.mdadded+98 -0
@@ -0,0 +1,98 @@
1+# lane-palette r5 report
2+
3+VERDICT: PARTIAL -- Job 1 (merge main, resolve, suite green, commit) is
4+done and committed (7666b7a). Job 2 (the range-ladder bisect) was not
5+started this round: the turn-budget hook fired at 55/75 right after job 1
6+landed green, and starting a fresh instrumentation+bisect with 20 calls
7+left risked leaving it half-done and uncommitted, which is worse than
8+deferring it cleanly.
9+
10+## Job 1 -- merge main, resolved, committed (7666b7a)
11+
12+`git merge main` (main at 53f5358) conflicted in six places in
13+`crates/ec-av1/src/decode.rs` and one in `crates/ec-av1/src/gate_coverage.rs`,
14+exactly as the charter predicted:
15+
16+- **`Neighbours` struct + its constructor** (2 conflicts): both sides added
17+ new fields to the same struct -- this lane's `above_palette_size` /
18+ `left_palette_size` / `above_palette_colors` / `left_palette_colors`, and
19+ main's `tile_row0_mi` / `tile_col0_mi`. Kept both (no overlap in meaning).
20+ One conflict marker (`>>>>>>> main`) was a stray leftover spanning past the
21+ constructor's closing brace into the unconflicted `start_tile` body --
22+ removed the stray marker line, left `start_tile`'s body (all main's,
23+ unconflicted) intact.
24+- **`read_intra_mode`'s signature** (1 conflict + 2 call-site conflicts):
25+ this lane added a `palette: Option<(usize, &[u16])>` param, main added
26+ `mi_r: usize, mi_c: usize` (used by `maybe_read_cdef_idx` inside the
27+ function body, which the merge kept). Both params are real and used --
28+ kept both, `palette` before `mi_r, mi_c`, and updated both call sites
29+ (~3548 rect/square path, ~3900 the 8x8-leaf path) to match the new
30+ 4-arg tail in the same order.
31+- **`PlaneBuf::reconstruct`** (1 conflict): this lane added the
32+ `PALETTE_PRED` thread-local override + `filter_intra` branch inside the
33+ `else`; main added real `smooth_neighbor` threading (was hardcoded
34+ `false`) plus dropped this lane's now-stale doc comment about the
35+ hardcoding being "exact for chroma". Kept this lane's palette-override +
36+ filter_intra structure, swapped the hardcoded `false` in the `predict()`
37+ call for main's `smooth_neighbor` parameter and its shorter comment
38+ (main's chroma lane made the old caveat comment no longer true).
39+- **`gate_coverage.rs`'s `NEVER_EXERCISED`**: this lane's side (via an
40+ already-merged local chroma lane) listed `enable-paeth-intra` /
41+ `enable-smooth-intra` (and, outside the conflict hunk, `enable-cdef`);
42+ main's side listed `enable-palette` (plus `enable-intrabc`, unconflicted).
43+ Per charter: kept `enable-intrabc` only. `enable-palette` drops because
44+ this lane's own real palette gate now exercises it; `enable-cdef` /
45+ `enable-paeth-intra` / `enable-smooth-intra` drop because main's
46+ CDEF-index and chroma-smooth/paeth lanes, now merged in, exercise those
47+ too -- none of the three belonged on this lane's list once main's fixes
48+ are actually present in the tree.
49+
50+**`refusal_inventory.rs`** (added cleanly by the merge, no conflict, but
51+incomplete): the suite's `the_decode_path_refuses_exactly_the_listed_cases`
52+test caught two refusal strings this lane's own history introduced that
53+weren't yet in the pinned `REFUSALS` list -- the r4 palette-Y pixel-mismatch
54+refusal ("...the index map decodes but the reconstructed pixels do not
55+match libaom yet (lane-palette r3/r4)") and a pre-existing
56+"a palette block with a split luma transform (round 1)" string. Added
57+both. No refusal strings removed or reworded by this merge; main's own
58+three reworded "encoder never writes" strings (2be815f, already on `main`
59+before this merge) carried through untouched.
60+
61+**Check:** `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`
62+(timeout 600000ms): first run failed 1/244 on the missing refusal-inventory
63+entries (caught and fixed above); rerun: **244 passed, 0 failed, 17
64+ignored**. Scoped `refusal_inventory` run alone: 3/3 green. `cargo check -p
65+ec-av1`: clean (only pre-existing doc-warning noise).
66+
67+## Job 2 -- not started, deferred
68+
69+`deferred: the EC_TRACE_PALETTE range-ladder bisect (per-pixel range
70+compare between aomdec's decode_color_map_tokens rung, already built by r4
71+in scripts/instrument-aom-oracle.sh rungs 6/6b, and a matching
72+EC_AV1_TRACE print this lane still needs to add inside
73+decode_color_index_map in decode.rs ~2182/2792) -- ran out of turn budget
74+right after job 1 landed green; r4's handoff (lanes/palette-r4.report.md,
75+"Handoff for the next round") is still accurate and unconsumed: (1) add
76+the per-pixel EC_PAL row/col/ctx/n/rng / EC_PAL_VAL trace inside
77+decode_color_index_map, checking whether SymbolDecoder already exposes a
78+range field/accessor (msac.rs ~260) before adding one; (2) regenerate the
79+r3/r4 gate's exact fixture stream once (smptebars=size=64x64 + hue=s=0)
80+and save the bytes; (3) run aomdec EC_TRACE_PALETTE=1 and our own decoder
81+EC_AV1_TRACE=1 against the identical bytes and diff per
82+compare-range-not-tell / equal-range-means-unread; (4) if ranges match to
83+the end of the block, the bug is in palette application (PALETTE_PRED's
84+set/take pairing or the buf = colors[idx] build at decode.rs ~3347), not
85+the symbol reads.`
86+
87+`deferred: the "Then" milestones (palette UV, palette_bsize_ctx rect-strip
88+refusal, intrabc) -- unstarted, all budget went to job 1; unchanged from
89+r4's own deferral.`
90+
91+## Handoff for the next round
92+
93+Start straight from job 2 step (1) above -- the merge is done, the suite
94+is green, `main`'s CDEF/chroma/tile landings are now in this branch's tree
95+so no further merge debt exists. Next round should NOT need to touch
96+`decode.rs`'s struct/signature layout again; the palette index-map
97+function itself (`decode_color_index_map`, ~2182) is the only untouched
98+surface job 2 needs.
lanes/palette-r6.charter.mdadded+54 -0
@@ -0,0 +1,54 @@
1+# lane-palette r6 — run the bisect
2+
3+At e5e8e6d. Read `lanes/palette-r5.report.md`.
4+
5+## Where you stand
6+r5 merged main into this branch and resolved all six `decode.rs` conflicts plus
7+`gate_coverage.rs` — the tree now carries main's CDEF, chroma and multi-tile
8+work, `NEVER_EXERCISED` is down to `enable-intrabc` alone, and two refusal
9+strings the merge surfaced are pinned. Suite 244/0. **No merge debt remains**,
10+so this round is entirely the bisect that r4 built the instrument for.
11+
12+## The one job
13+Palette-Y decodes its colours and index map, `palette_hits` fires, and the block
14+then refuses by name because the reconstructed pixels do not match libaom.
15+r3 checked `read_palette_colors_y`, `read_uniform`,
16+`palette_color_index_context` and the `PALETTE_Y_COLOR_INDEX` table
17+line-for-line against the oracle source — all match. So do not re-read tables
18+(class `worker-cap-spent-reading`). Use the instrument:
19+
20+1. r4's `EC_TRACE_PALETTE=1` rung (rungs 6/6b in
21+ `scripts/instrument-aom-oracle.sh`, aomdec already rebuilt on this box)
22+ prints, inside libaom's `decode_color_map_tokens`, per-pixel
23+ row/col/ctx/n/rng before and color_idx/rng after, plus the `map[0]` uniform
24+ read.
25+2. Add the matching trace inside our `decode_color_index_map`
26+ (decode.rs ~2182 before r5's merge; find it by name).
27+3. Regenerate the gate's exact fixture stream ONCE and run both traces over it.
28+4. Diff RANGES, never `tell()` (class `compare-range-not-tell`). Reference range
29+ unchanged where ours moves = we read a symbol it never wrote; theirs moves
30+ and ours does not = we skipped one (class `equal-range-means-unread`).
31+5. **If the ranges match to the end of the block, the reads are right** and the
32+ bug is in how the palette is applied — the `PALETTE_PRED` thread-local's
33+ lifetime, the buffer write, per-TU slicing, or plane mixing. That is the more
34+ likely outcome given r3's table audit, so check it early rather than last.
35+
36+Then remove the refusal IN THE SAME COMMIT as the gate that proves pixel
37+exactness — not before. Two sibling lanes lifted refusals on a green suite this
38+batch and one had a firing counter that was never incremented, so its own assert
39+was blind. A green suite cannot prove a path nothing takes.
40+
41+## Then
42+Palette UV, the rect-strip `palette_bsize_ctx` refusal (decode.rs ~1940), then
43+intrabc — which is the last entry on `gate_coverage.rs`'s `NEVER_EXERCISED`.
44+One commit each, each with its own hard-asserted firing count.
45+
46+Merge note: main is at 93d9510. Report every refusal string you add or remove,
47+verbatim.
48+
49+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`; foreground
50+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
51+worktrees have live agents — never build in or edit them, and do NOT create
52+additional worktrees. Never push, never merge into `main`. 75-turn cap, does not
53+reset: COMMIT AT EVERY GREEN STEP. End with `lanes/palette-r6.report.md`,
54+VERDICT on line 1.
lanes/palette-r6.report.mdadded+155 -0
@@ -0,0 +1,155 @@
1+# lane-palette r6 report
2+
3+VERDICT: PARTIAL -- the bisect the charter asked for is done and the root
4+cause is pinned exactly; the fix itself (reorder + UV palette mode_info
5+reads) is not implemented this round, so the refusal stays and no gate
6+was flipped to pixel-exact.
7+
8+## The bisect (committed 7485651)
9+
10+Added the matching `EC_AV1_TRACE`-gated `EC_PAL row=.. col=.. ctx=.. n=.. rng=..`
11+/ `EC_PAL_VAL row=.. col=.. color_idx=.. rng=..` print inside our own
12+`decode_color_index_map` (`crates/ec-av1/src/decode.rs` ~2370, matching
13+r4's oracle rung field-for-field), plus `TRACE pre_palette_y_mode` /
14+`palette_y_mode` / `palette_y_size` / `palette_y_colors` prints around
15+the Y palette-mode-info reads just above it (~3010-3024).
16+
17+Regenerated the r3/r4 gate's exact fixture once (`ffmpeg smptebars
18+size=64x64:rate=25` piped through `hue=s=0`, then the gate's pinned
19+`aomenc` recipe -- byte-identical across two ffmpeg runs, saved to
20+`/tmp/.../scratchpad/palette/out.obu`, 112 bytes) and ran both traces
21+against the identical bytes:
22+
23+- `aomdec EC_TRACE_PALETTE=1` (r4's existing rungs 6/6b)
24+- our own decoder via a throwaway `#[ignore]` test reading
25+ `EC_AV1_SCRATCH_FILE` and calling `decode_stream` with `EC_AV1_TRACE=1`
26+ (not committed -- removed after use, see below)
27+
28+**Range compare, per `compare-range-not-tell`:** every symbol up through
29+the Y palette colours is bit-identical between the two decoders for the
30+frame's first (top-left, mi=(0,0)) block:
31+
32+| point | oracle rng | ours rng |
33+|---|---|---|
34+| partition_w32(0,0) read | 58370 | 58370 |
35+| entering `read_palette_mode_info` (post skip/y_mode/uv_mode) | 34206 | 34206 |
36+| after `palette_y_mode` symbol (value=1) | 60032 | 60032 |
37+| after `palette_y_size` symbol (n=4) | 39344 | 39344 |
38+| after `read_palette_colors_y` (colours `[112,131,162,180]`) | 39432 | 39432 |
39+| `decode_color_map_tokens` / our `decode_color_index_map` **entry** | **51752** | **39432** |
40+
41+Ranges match to the byte through the Y colour read, then diverge exactly
42+at the point our `decode_color_index_map` is called. **Per the charter's
43+own steer this rules out a table/context bug in the map reader itself**
44+(r3 already audited those tables and this round's range trace confirms
45+it end to end) **and confirms the bug is positional, not a read bug**.
46+
47+## Root cause: `decode_color_index_map` is called from the wrong syntax position
48+
49+Traced why the oracle's rng jumps from 39432 (after Y colours) to 51752
50+(entering the color-index-map) with no observable step in between on our
51+side: `libaom`'s `decode_color_map_tokens` is **not** called inline from
52+`read_palette_mode_info`. It runs later, from `parse_decode_block`
53+(`decodeframe.c:1135`, `av1_visit_palette(pbi, xd, r,
54+av1_decode_palette_tokens)`), called right after `decode_mbmi_block`
55+returns -- i.e. after the *entire* mode-info read for the block,
56+including **UV palette mode_info** (`read_palette_mode_info`'s own
57+second half: `palette_uv_mode_cdf` / `palette_uv_size_cdf` /
58+`read_palette_colors_uv`, gated on `uv_mode == UV_DC_PRED &&
59+is_chroma_ref`) and `read_filter_intra_mode_info`. Confirmed live by
60+patching a throwaway `EC_PRE_PALETTE` / `EC_PALETTE_Y_MODE` /
61+`EC_PALETTE_Y_SIZE` / `EC_PALETTE_Y_COLORS` print into the oracle's
62+`decodemv.c` (rebuilt aomdec, ran the trace, matched ours field-for-field
63+through `EC_PALETTE_Y_COLORS rng=39432`, then confirmed
64+`read_palette_mode_info` returns and control passes to
65+`av1_visit_palette` before `decode_color_map_tokens` runs) -- **reverted
66+this patch after use** (`git diff --stat` on `~/.cache/aom-oracle/src`
67+clean of it, `ninja aomdec` rebuilt back to the pre-patch binary) since
68+that oracle checkout is shared with sibling lanes and the charter forbids
69+touching sibling worktrees; this diagnostic lived entirely outside this
70+repo and is not committed here.
71+
72+This gate's block has `uv_mode=0` (`UV_DC_PRED`) and is chroma-referenced
73+(32x32 luma with 4:2:0 subsampling is a real chroma block), so the
74+oracle genuinely reads a `palette_uv_mode` symbol (and, since it's a
75+binary CDF, possibly `palette_uv_size` + `read_palette_colors_uv` too)
76+between the Y colours and the color-index-map read -- bits our decoder
77+never consumes at all. Our `decode_color_index_map(dec, cdfs, n, side)`
78+call sits immediately after `read_palette_colors_y` inside the Y-palette
79+branch (`decode.rs` ~3023), which is wrong on two counts: (1) it skips
80+UV palette mode_info entirely when the block is chroma-referenced and
81+UV-DC, and (2) even where UV genuinely isn't read (monochrome / not
82+chroma-referenced / UV mode != DC), libaom still defers the color-index
83+map to a separate post-mode-info pass (after `filter_intra`), not inline.
84+
85+## What this closes, what it doesn't
86+
87+r3's table audit + this round's range trace together give a decisive
88+answer per `worker-cap-spent-reading`/`compare-range-not-tell`: **every
89+table this lane touches is exact**; the bug is 100% a call-site ordering
90+bug, not a CDF/context bug, so no more table re-reading is owed here.
91+
92+**Not done this round (next round's job):** the actual reorder fix --
93+read (and, per the "Then" milestone, eventually reconstruct) UV palette
94+mode_info in `read_intra_mode`'s palette branch right after the Y
95+colours, then move both the Y and UV `decode_color_index_map` calls to
96+run after `filter_intra` is read, matching `parse_decode_block`'s real
97+call order. That is squarely the charter's "Then" milestone ("Palette
98+UV") arriving earlier than expected -- it turns out UV support isn't a
99+separate later feature, it's a hard prerequisite for Y's own bits to stay
100+synced whenever the block is chroma-referenced with UV_DC_PRED. The
101+refusal (`"a block that actually uses a palette (Y) -- the index map
102+decodes but the reconstructed pixels do not match libaom yet
103+(lane-palette r3/r4)"`) stays exactly as-is; removing it before the
104+reorder + UV-read fix lands would ship a real desync as a "decode",
105+which the charter explicitly forbids ("remove the refusal only in the
106+same commit as the gate that proves pixel exactness").
107+
108+## Refusal strings
109+
110+None added, none removed, none reworded this round.
111+
112+## Check
113+
114+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4` (timeout
115+600000ms, ran ~122s): **244 passed, 0 failed, 17 ignored** -- unchanged
116+from r5's baseline. `cargo build -p ec-av1 --tests -j4`: clean, no new
117+warnings from the trace additions.
118+
119+## Handoff for the next round
120+
121+1. In `read_intra_mode`'s palette branch (`decode.rs` ~3010-3024), right
122+ after `read_palette_colors_y`, add the UV palette mode_info read:
123+ `if num_planes > 1 && uv_mode == UV_DC_PRED (0) && is_chroma_ref { read
124+ palette_uv_mode symbol; if set, palette_uv_size + palette colours (UV,
125+ two channels) }` -- needs a `palette_uv_mode_cdf` / `palette_uv_size_cdf`
126+ pair and a `read_palette_colors_uv` port (`decodemv.c` `read_palette_colors_uv`,
127+ not yet ported -- check `cdf.rs` for whether the UV CDF tables already
128+ exist before writing new ones). `is_chroma_ref` needs threading in if
129+ it isn't already available at this call site.
130+2. Move both the Y (`decode_color_index_map(dec, cdfs, n, side)`, luma
131+ plane) and the new UV color-index-map read to run *after*
132+ `filter_intra` is read, not inline in the palette branch -- matching
133+ `parse_decode_block`'s `decode_mbmi_block` (all mode info) then
134+ `av1_visit_palette` (both planes' index maps) order. This likely means
135+ restructuring `read_intra_mode`'s return type to carry the *undecoded*
136+ palette colours/size out, with the actual `decode_color_index_map`
137+ call(s) moved to the caller, after the `filter_intra` result is known.
138+3. Once reordered, rerun this round's exact trace recipe (`out.obu` in
139+ the scratchpad, or regenerate -- see r3/r4/r6 for the recipe) with both
140+ `EC_AV1_TRACE=1` on ours and (temporarily re-patching, then reverting,
141+ the same 3 oracle `decodemv.c` prints this round used) to confirm the
142+ ranges now match all the way to the end of the Y (and UV) color-index
143+ maps before flipping the gate from "refuses by name" back to "decodes
144+ pixel exact" and removing the refusal, in the same commit as the gate
145+ flip, per charter.
146+4. The `palette_bsize_ctx` rect-strip refusal and `enable-intrabc` are
147+ still fully unstarted (r4's original "Then" list) -- UV palette turned
148+ out to be a hard prerequisite of Y, so it should stay first in line
149+ next round rather than being deferred again.
150+
151+`deferred: the reorder fix + UV palette mode_info port -- root cause
152+pinned this round via a decisive range trace (compare-range-not-tell),
153+implementation not started, next round's first job.`
154+`deferred: palette_bsize_ctx rect-strip refusal, intrabc -- unstarted,
155+all budget went to the bisect + root-cause confirmation this round.`
lanes/palette-r7.charter.mdadded+56 -0
@@ -0,0 +1,56 @@
1+# lane-palette r7 — implement the fix r6 pinned
2+
3+At bba4d3c. Read `lanes/palette-r6.report.md` first — it carries the root cause,
4+the range table, the fixture regen command and the oracle 3-print patch.
5+
6+r6 did the decisive work: every symbol up through `read_palette_colors_y` is
7+bit-exact against the oracle (partition, skip, y_mode, uv_mode, palette_y_mode,
8+palette_y_size, colours — all rng-for-rng). Divergence begins exactly at
9+`decode_color_index_map`'s entry (oracle rng=51752, ours 39432). Cause is call
10+ORDER, not a table: libaom reaches `decode_color_map_tokens` from
11+`parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`) AFTER the whole
12+mode-info decode including UV palette mode_info and filter_intra; we call
13+`decode_color_index_map` inline right after the Y colours (`decode.rs` ~3023)
14+and never read UV palette mode_info at all — which this gate's block genuinely
15+has (`uv_mode = UV_DC_PRED`, chroma-referenced).
16+
17+## Do the fix, in this order, committing each green step
18+1. Port UV palette mode_info — `palette_uv_mode_cdf`, `palette_uv_size_cdf`,
19+ `read_palette_colors_uv` — into `read_intra_mode`'s palette branch,
20+ immediately after the Y colours. New adapting CDFs need all four wiring
21+ sites: struct field, defaults array, save/restore, and the per-frame counter
22+ reset. `reset2`/`reset3` are length-generic and save/restore is a whole-struct
23+ `Clone`, so the defaults array is the one to hand-check — but confirm the
24+ counter reset covers them. A table missing from the reset gives right values
25+ at the wrong adaptation rate, which reads as a slow drift, not a desync
26+ ([[cdf-counter-not-reset]]).
27+2. Move BOTH the Y and UV `decode_color_index_map` calls to run after
28+ `filter_intra` is read, matching libaom's `decode_mbmi_block` →
29+ `av1_visit_palette` order.
30+3. Re-run r6's exact trace recipe and confirm the ranges match to the END of the
31+ block, not just past the old divergence point.
32+4. Only with the gate pixel-exact: flip it green, remove the palette-Y refusal,
33+ and update `refusal_inventory.rs`'s pinned list — all in ONE commit. A branch
34+ that lifts a refusal without a gate does not merge to main.
35+
36+Then merge `main` into this branch (main has moved a long way: multi-tile,
37+delta_q/delta_lf, a `bit_depth != 8` refusal, three reworded partition
38+refusals) and resolve it yourself, so the lane arrives mergeable.
39+
40+Note `gate_coverage.rs` still lists `enable-palette` only if this lane's gate
41+does not enable it — when your gate is green with the tool on, that entry comes
42+off the list in the same commit.
43+
44+Oracle hygiene: the aomenc checkout at `~/.cache/aom-oracle` is SHARED with five
45+sibling lanes. r6 patched `decodemv.c` for its trace and reverted it after use —
46+do the same, and never leave the shared oracle modified or half-rebuilt. Prefer
47+adding a permanent env-gated rung to `scripts/instrument-aom-oracle.sh` (silent
48+when unset, idempotent) over a throwaway patch.
49+
50+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`; foreground
51+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; fixtures
52+through `gradients_source(seed, w, h, tail)`; ffmpeg generates bounded with `-t`;
53+`EC_AV1_REQUIRE_AOMENC=1`; aomenc `--threads=1 --row-mt=0 --sb-size=64`. Sibling
54+worktrees have live agents — never build in or edit them. Never push, never
55+merge this branch into main. 75-turn cap, does not reset: COMMIT AT EVERY GREEN
56+STEP. End with `lanes/palette-r7.report.md`, VERDICT on line 1.
lanes/palette-r7.report.mdadded+120 -0
@@ -0,0 +1,120 @@
1+# lane-palette r7 report
2+
3+VERDICT: DONE -- the fix r6 pinned is implemented, the gate is pixel-exact
4+against ffmpeg, the palette-Y refusal is removed, `refusal_inventory.rs` is
5+updated, main is merged in, and the lane arrives mergeable.
6+
7+## The fix (`crates/ec-av1/src/decode.rs`, `read_intra_mode`)
8+
9+r6's range trace pinned the cause exactly: `decode_color_index_map` was
10+called inline right after the Y colours, but libaom's `av1_visit_palette`
11+(`decoder.c:234`) only runs `decode_color_map_tokens` from
12+`parse_decode_block` (`decodeframe.c:1135`) **after** the whole mode-info
13+read, including UV palette mode_info (`read_palette_mode_info`'s own
14+second half, `decodemv.c:588`) and `filter_intra`.
15+
16+Two changes, both inside `read_intra_mode`:
17+
18+1. **UV palette mode_info read added.** Right after the Y colours are read
19+ (or Y palette doesn't fire), read `palette_uv_mode` at
20+ `ctx = usize::from(use_palette_y)` whenever `uv_mode == UV_DC_PRED` --
21+ unconditionally, not gated on whether Y fired (that was the actual bug:
22+ the old code returned early inside the `use_palette_y` branch, before
23+ this read was ever reached). No `read_palette_colors_uv` port was
24+ needed: UV palette reconstruction stays out of scope, so the moment the
25+ mode symbol fires this decoder refuses by name immediately and the
26+ whole decode aborts -- no further bits from that stream matter, so
27+ `palette_uv_size`/the UV colour reader never need to exist. `is_chroma_ref`
28+ didn't need threading in either: this decoder's scope is squares only
29+ and `decode_block` always reconstructs chroma alongside luma, so it is
30+ unconditionally true here (matches `av1_visit_palette`'s own `plane == 0
31+ || xd->is_chroma_ref` when `is_chroma_ref` is always true).
32+2. **Y's `decode_color_index_map` call moved.** The Y palette branch now
33+ only reads mode/size/colours and stashes them in a local
34+ `palette_y_pending: Option<(usize, [u16; 8])>`; the actual
35+ `decode_color_index_map` call (and the `PALETTE_HITS` counter bump) now
36+ runs after `filter_intra` is read, matching
37+ `decode_mbmi_block` → `av1_visit_palette` order exactly.
38+
39+The old "index map decodes but pixels don't match" refusal
40+(`decode.rs`'s r3/r4 comment block) is gone -- replaced by an r7 doc
41+comment explaining the reorder and citing `compare-range-not-tell`.
42+
43+## Gate: refuses-by-name -> decodes-pixel-exact
44+
45+`crates/ec-av1/src/stream.rs`'s
46+`a_real_aomenc_stream_with_palette_y_refuses_by_name` renamed to
47+`a_real_aomenc_stream_with_palette_y_decodes_pixel_exact`: same fixture
48+(`smptebars=size=64x64:rate=25` + `hue=s=0`, `--enable-palette=1
49+--tune-content=screen`, every non-palette intra tool forced off so a
50+mismatch can only come from palette), but now asserts `decode_stream`
51+succeeds, `palette_hits() > before` (proves the block actually fired, not
52+a vacuous pass), and `frames[0].{y,u,v}` match `ffmpeg_decode_sequence`'s
53+decode of the same bytes exactly.
54+
55+```
56+EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- \
57+ a_real_aomenc_stream_with_palette_y_decodes_pixel_exact
58+```
59+-> `test stream::tests::a_real_aomenc_stream_with_palette_y_decodes_pixel_exact ... ok`
60+
61+## refusal_inventory.rs
62+
63+Dropped `"a block that actually uses a palette (Y) -- the index map
64+decodes but the reconstructed pixels do not match libaom yet (lane-palette
65+r3/r4)"` from `REFUSALS` (the string no longer exists in the source, so the
66+pinned-inventory test would otherwise fail). `"a block that actually uses a
67+palette (Y) -- reconstruction is out of scope"` (the excluded-call-site
68+refusal, unaffected by this round) and `"...UV... -- reconstruction is out
69+of scope"` both stay -- neither string changed.
70+
71+`gate_coverage.rs` has no `enable-palette` entry to remove: the gate
72+already passed `--enable-palette=1` before this round, so this milestone's
73+"drops off the list" note in the charter doesn't apply here.
74+
75+## Oracle hygiene
76+
77+No patch to `~/.cache/aom-oracle` was needed this round -- the fix was
78+derived by reading libaom source directly (`av1_visit_palette`,
79+`read_palette_mode_info`, `read_palette_colors_uv`) and verified purely
80+against this repo's own `decode_stream` vs `ffmpeg_decode_sequence`, no
81+`aomdec EC_TRACE`/`decodemv.c` re-instrumentation this time. The checkout
82+is untouched by this lane (its working tree shows pre-existing sibling-lane
83+modifications to `restoration.c`/`decodeframe.c`/`decodemv.c`/`decodetxb.c`/
84+`detokenize.c` that were already there before this round started -- not
85+mine to revert or rebuild). No new env-gated rung added to
86+`scripts/instrument-aom-oracle.sh` since none was needed.
87+
88+## Checks
89+
90+- `cargo build -p ec-av1 --tests -j4`: clean (pre-existing doc-lint
91+ warnings only, no new ones).
92+- `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4` (before merging
93+ main, timeout 600000ms, ~147s): **244 passed, 0 failed, 17 ignored**
94+ (r6's 244-test baseline, palette gate now green instead of "refuses").
95+- After `git merge main` (main brought in 5 more tests, tile-rows work):
96+ `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4` (~175s):
97+ **249 passed, 0 failed, 17 ignored**.
98+
99+## Commits (this branch, on top of bba4d3c)
100+
101+- `dd399d4` -- the fix + gate flip + refusal_inventory update, all one
102+ commit per charter.
103+- `406e0f2` -- `git merge main` (auto-merged cleanly: `decode.rs`,
104+ `refusal_inventory.rs`, `stream.rs` all resolved without conflicts,
105+ main's `bit depth != 8` refusal and tile-rows work landed alongside
106+ this round's palette changes).
107+
108+Branch left unpushed, unmerged to main, per charter ("Never push, never
109+merge this branch into main").
110+
111+## Handoff for the next round
112+
113+r6's own next-milestone list (`palette_bsize_ctx` rect-strip refusal,
114+`enable-intrabc`) is still fully unstarted -- this round's entire scope was
115+the reorder fix the charter named, and it's done. UV palette
116+*reconstruction* (as opposed to the mode_info read, now correct) also
117+remains a named refusal and unstarted; it was never in this round's scope.
118+
119+`deferred: palette_bsize_ctx rect-strip refusal, intrabc, UV palette
120+reconstruction -- all unstarted, out of this round's charter scope.`
lanes/palette.charter.mdadded+115 -0
@@ -0,0 +1,115 @@
1+# lane-palette — palette reconstruction, then intra block copy
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-palette`, branch
4+`lane-palette`, off main (c4904ee or later).
5+
6+## Goal
7+Two of the five coding tools that **no gate in this repository exercises**
8+(main's `crates/ec-av1/src/gate_coverage.rs` pins the set) are palette and
9+intrabc. Both have their syntax consumed and both refuse the moment a block
10+actually uses them. Make them decode.
11+
12+## Where the refusals are
13+- Palette, key-frame reader — `crates/ec-av1/src/decode.rs:2484-2494`:
14+ `"a block that actually uses a palette (Y) -- reconstruction is out of scope"`
15+ and the `(UV)` twin. The `palette_y_mode` / `palette_uv_mode` symbols ARE
16+ read; only a nonzero size refuses.
17+- Palette, inter-frame intra-block reader — `decode.rs:7795-7805`, the same two
18+ strings. Note the comment there: `palette_mode_ctx` / `palette_uv_mode_ctx`
19+ are hardcoded 0, which is only safe while a nonzero neighbour `palette_size`
20+ is impossible. **The moment palette blocks decode, those contexts become
21+ live** — `av1_get_palette_mode_ctx` (pred_common.h) reads the neighbours'
22+ own `palette_size[0] > 0`. Class `context-read-from-one-cell` and
23+ `cdf-row-held-constant` both apply: fix the context in the SAME round that
24+ removes the refusal, or the gate will desync in a way that looks like a
25+ table bug.
26+- Intrabc — `decode.rs:2408-2416`:
27+ `"a block that actually uses intrabc (this decoder never reconstructs one)"`.
28+- Also `decode.rs:1940-1947`: a HORZ/VERT intra strip in a screen-content frame
29+ refuses because `palette_bsize_ctx` is keyed on a single side. That refusal
30+ is in scope for stage 3.
31+
32+## Anchors
33+- Spec 5.11.13 `palette_mode_info`, 5.11.46 `palette_tokens`, 5.11.50
34+ `get_palette_cache`, 7.11.4 `palette prediction process`; 5.11.13
35+ `read_intrabc_info`, 6.10.19, 7.11.3.x for the intrabc MV rules.
36+- libaom, source tree under `~/.cache/aom-oracle`:
37+ `av1/decoder/decodemv.c` `read_palette_mode_info` (line ~567),
38+ `read_palette_colors_y` / `read_palette_colors_uv`, and the delta-coded
39+ colour reads; `av1/common/pred_common.h` `av1_get_palette_mode_ctx` and
40+ `av1_get_palette_bsize_ctx`; `av1/decoder/decodetxb.c` /
41+ `av1/common/blockd.h` for the colour index map; `av1_get_palette_cache`
42+ (av1/common/reconintra.c) for the above/left colour cache;
43+ `read_intrabc_info` (decodemv.c ~693) and `av1_find_ref_dv` for intrabc's
44+ forced DV predictor and its validity bounds.
45+- `crates/ec-av1/src/cdf_state.rs:425-433` already carries `palette_y_mode`,
46+ `palette_y_size`, `palette_uv_mode`, `palette_uv_size` with defaults and
47+ counter resets. The colour-index-map CDFs (`palette_y_color_index` /
48+ `palette_uv_color_index`, indexed by palette size and a neighbour context)
49+ are NOT there — adding them is four wiring sites: struct field, defaults
50+ array, save/restore, per-frame counter reset (`cdf_state.rs` `reset2`/`reset3`
51+ are length-generic and save/restore is a whole-struct Clone, so the defaults
52+ array is what needs hand-checking; still verify the counter reset covers the
53+ new tables — class `cdf-counter-not-reset`).
54+
55+## Staging — COMMIT AFTER EVERY GREEN MILESTONE
56+1. **Palette Y.** Colour cache from the above/left neighbours, delta-coded
57+ colours, the colour index map (wavefront diagonal scan, the
58+ `palette_color_index` symbol per pixel with its neighbour context), and
59+ reconstruction. Fix `palette_mode_ctx` / `palette_uv_mode_ctx` to read the
60+ neighbours' real palette sizes in this same commit. COMMIT.
61+2. **Palette UV.** COMMIT.
62+3. **The rect-strip refusal** at decode.rs:1940 — key `palette_bsize_ctx` on
63+ both sides the way `av1_get_palette_bsize_ctx` does
64+ (`num_pels_log2_lookup[bsize]`). COMMIT.
65+4. **Intrabc.** The DV predictor, the wavefront/delay validity bounds (a DV may
66+ only reference already-reconstructed pixels far enough behind the current
67+ superblock), and prediction from the current frame's own reconstruction.
68+ COMMIT.
69+
70+## Gate (mandatory, in `crates/ec-av1/src/stream.rs` beside the existing gates)
71+- Copy an existing gate's shape. `EC_AV1_REQUIRE_AOMENC=1` must be set on every
72+ test run, so a missing oracle FAILS rather than SKIPs.
73+- Bound every ffmpeg `generate` with `-t <seconds>`.
74+- Build fixtures through the existing `gradients_source(seed, w, h, tail)`
75+ helper — ffmpeg's `gradients` source ignores its own seed. Palette and intrabc
76+ are screen-content tools: aomenc will only choose them on flat, few-colour,
77+ repetitive content, so you will likely need a synthetic source
78+ (few-colour test pattern, repeated tiles) rather than a gradient. Whatever you
79+ use, it must be deterministic — hash the fixture across two runs and prove it.
80+- aomenc `--threads=1 --row-mt=0 --enable-palette=1` (and `--enable-intrabc=1`
81+ for stage 4), plus `--tune-content=screen` if that is what makes the encoder
82+ actually pick the tool.
83+- Hard-assert firing counts via thread-local `Cell<usize>` counters in decode.rs
84+ matching the existing `*_HITS` (thread-local, NOT atomics): palette blocks
85+ reconstructed > 0, intrabc blocks > 0. A gate that cannot prove its feature
86+ fired is vacuous (class `gate-blind-to-feature`).
87+- **Main's `gate_coverage.rs` guard will fail by design** once your gate enables
88+ these tools: its `NEVER_EXERCISED` list names `enable-palette` and
89+ `enable-intrabc`. Deleting those two entries is part of landing this work.
90+
91+## Method
92+CLASS `compare-range-not-tell`: compare the msac RANGE against the oracle after
93+each element, never `tell()`. Oracle at `~/.cache/aom-oracle`; env-gated rungs
94+`EC_TRACE=1` (partitions), `EC_TRACE_COEFF=1`, `EC_TRACE_MODE=1` (inter + intra
95+mode info), `EC_AV1_PREFILT_DUMP=<prefix>` (per-frame pre-filter recon — the
96+right rung for separating a prediction bug from a filter one). Add a rung with
97+`scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh` in the
98+existing shape (env-gated, silent when unset, idempotent, wrapper-around-impl).
99+CLASS `equal-range-means-unread`: reference range unchanged where ours moves =
100+we read a symbol it never wrote; theirs moves and ours does not = we skipped one.
101+
102+## Hard rules
103+- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-palette`. Foreground
104+ builds, `nice -n 19 cargo ... -j4`. Give every `cargo test` a timeout of at
105+ least 600000 ms — the suite runs 3-4 minutes and a 120 s default kills it.
106+- Sibling worktrees (edith_codecs, -chroma, -realworld, -lr, -superres, -tiles)
107+ have live agents. Never build in or edit them.
108+- Baseline: 234 passed / 0 failed on main.
109+- NEVER push, never merge, never touch `main`. Commit on `lane-palette` only.
110+- 75-turn cap and it does NOT reset on resume: commit at every green step.
111+ Stage 1 committed and green is a good round on its own.
112+- Refuse-by-name rather than desync; never claim in a refusal string that the
113+ encoder cannot emit a case unless you proved it.
114+- End with `lanes/palette.report.md`, VERDICT on the first line: what landed,
115+ gate names + firing counts, remaining refusal strings verbatim, next lever.
lanes/palette.report.mdadded+182 -0
@@ -0,0 +1,182 @@
1+# lane-palette report
2+
3+VERDICT: NOTHING LANDED. Recon-only round -- turn budget (75 cap) was spent
4+entirely on reading decode.rs/cdf_state.rs/cdf.rs and the libaom oracle
5+(decodemv.c, pred_common.c/h, entropymode.c, detokenize.c, decoder.h) to
6+derive a complete, concrete implementation plan for palette Y (stage 1). No
7+edit was made; worktree is clean at 402ee40. This report is the handoff so
8+the next round can implement directly instead of re-deriving the algorithm.
9+
10+## Why nothing landed
11+The charter's stage 1 alone touches: two new CDF tables (with their 4-site
12+wiring), two new `Neighbours` fields + a new record path, a new decode
13+function (color cache merge + delta-coded colour read + wavefront colour-index
14+map), a prediction-injection point in `PlaneBuf::reconstruct`, and a new gate
15+with a hand-built fixture. Deriving the exact algorithm (matched byte-for-byte
16+against libaom, per this project's `compare-range-not-tell` method) from cold
17+took the whole budget; implementing it untested would violate "never claim
18+green without running it," so I stopped rather than land unverified code.
19+
20+## The derived plan (verified against libaom source, not yet against a
21+## decoded stream -- next round's job is to type this in and range-ladder it)
22+
23+### 1. `crates/ec-av1/src/cdf.rs` -- new default tables
24+Add `PALETTE_Y_COLOR_INDEX: [[[u16; 9]; 5]; 7]` and
25+`PALETTE_UV_COLOR_INDEX: [[[u16; 9]; 5]; 7]` (indexed `[n-2][color_ctx]`,
26+width 9 = up to 8 symbols + terminal 32768 + 0 count, sliced `[..=n]` at the
27+call site since `SymbolDecoder::symbol` derives `nsyms` from `cdf.len()-1`).
28+Raw values transcribed from `~/.cache/aom-oracle/src/av1/common/entropymode.c`
29+`default_palette_y_color_index_cdf` / `default_palette_uv_color_index_cdf`
30+(entropymode.c:679-731 Y, :732-785 UV) -- copy the AOM_CDF macro arguments
31+directly, same convention this file already uses for `PALETTE_Y_SIZE` etc.
32+(raw forward values, not inverted, with a trailing `32768, 0`).
33+
34+### 2. `crates/ec-av1/src/cdf_state.rs` -- 4-site wiring
35+- struct field: `pub palette_y_color_index: [[[u16; 9]; 5]; 7]`,
36+ `pub palette_uv_color_index: [[[u16; 9]; 5]; 7]` (next to `palette_y_size`
37+ at line ~428).
38+- defaults array (~line 1112): `palette_y_color_index: cdf::PALETTE_Y_COLOR_INDEX`,
39+ `palette_uv_color_index: cdf::PALETTE_UV_COLOR_INDEX`.
40+- save/restore: automatic (`Cdfs` is `#[derive(Clone, Copy)]`, whole-struct).
41+- counter reset (~line 652, alongside `reset3(&mut self.palette_y_mode)`):
42+ `reset3(&mut self.palette_y_color_index); reset3(&mut self.palette_uv_color_index);`
43+ -- `reset3::<N,M,K>` is generic over any `[[[u16;N];M];K]`, compiles as-is.
44+
45+### 3. `crates/ec-av1/src/decode.rs` -- `Neighbours` (struct at line ~1239)
46+Add Y-only palette neighbour state (UV needs its own pair in stage 2):
47+```
48+above_palette_size: Vec<usize>,
49+left_palette_size: Vec<usize>,
50+above_palette_colors: Vec<[u16; 8]>,
51+left_palette_colors: Vec<[u16; 8]>,
52+```
53+init in `Neighbours::new` alongside `above_mode`/`left_mode`
54+(`vec![0; cols]` / `vec![[0u16; 8]; cols]` and the `left_*` twins).
55+New method, mirroring `record_rect` (line 1716)'s SUB-grid loop:
56+```
57+fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
58+ let (r, c) = at;
59+ for cell in 0..side / SUB {
60+ self.above_palette_size[c + cell] = size;
61+ self.above_palette_colors[c + cell] = colors;
62+ }
63+ for cell in 0..side / SUB {
64+ self.left_palette_size[r + cell] = size;
65+ self.left_palette_colors[r + cell] = colors;
66+ }
67+}
68+```
69+Call it unconditionally (size=0 for a non-palette block, to clear stale
70+neighbour state) at the 3 call sites that can produce a palette block per
71+the charter's named scope: the key-frame square path (currently around
72+decode.rs:3061 and :3137, both branches of `decode_block`) and the
73+inter-frame intra-block reader (around :7953, alongside its existing
74+`neighbours.record_rect` call). Do NOT touch the two rect-strip
75+`record_rect` call sites (:2184, :2352) or the 8x8-leaf path (~:8909) --
76+those refuse palette syntax unconditionally already (unchanged scope,
77+charter does not name them), so their neighbours must stay at the default 0.
78+
79+### 4. Palette mode/colour read (replaces the two refusal blocks at
80+decode.rs:2483-2496 and :7795-7805)
81+`palette_mode_ctx` (`av1_get_palette_mode_ctx`, pred_common.h:197): **no**
82+SB-row restriction, just `(above_size>0) as usize + (left_size>0) as usize`
83+read straight off the new `Neighbours` fields at column `c`/row `r`.
84+`palette_uv_mode_ctx`: `(y_palette_size > 0) as usize` -- the CURRENT block's
85+own just-decided Y size, not a neighbour lookup at all; trivial one-line fix,
86+must land in stage 1 even though UV reconstruction itself is stage 2 (the
87+refusal string stays, only the ctx changes from hardcoded 0).
88+
89+Colour CACHE (`av1_get_palette_cache`, pred_common.c:73) has its own,
90+*different* restriction: null the **above** neighbour only (never left) when
91+`r % (SUB_PER_SB) == 0` i.e. the block sits at the very top row of a 64x64
92+superblock (`row % (1 << MIN_SB_SIZE_LOG2)`, MIN_SB_SIZE_LOG2=4 in 4x4-mi
93+units = 16 mi = 4 SUB-cells at SUB=16px -- so `r % 4 == 0` in this decoder's
94+SUB-grid units). Merge-sorted cache (ascending, dedup consecutive, cap
95+`2*PALETTE_MAX_SIZE`) -- straight port of `palette_add_to_cache` +
96+`av1_get_palette_cache`'s two-pointer merge, both bodies pasted in the recon
97+notes I fed the next round via chat (also derivable straight from
98+pred_common.c:73-116, already open in the oracle checkout).
99+
100+`read_palette_colors_y` (decodemv.c:478-501) port, bit_depth=8 fixed (this
101+decoder is 8-bit only): read up to `n` cached-colour accept bits via
102+`dec.literal(1)`, then delta-code the remainder via `dec.literal(bit_depth)`
103+first value + `dec.literal(bits)` deltas (`bits` starts at `bit_depth-3 +
104+dec.literal(2)`, shrinks each step via `ceil_log2(range)`), then
105+`merge_colors` (decodemv.c:461-475, straight port) interleaves the cached and
106+transmitted lists back into ascending order. `av1_read_uniform`
107+(decoder.h:425) needed too, for the colour-index map's first symbol --
108+`get_unsigned_bits(n) = if n<=1 {0} else {32 - ((n-1) as u32).leading_zeros()}`,
109+then the NS(n) two-branch read already used implicitly nowhere else in this
110+file (new helper).
111+
112+### 5. Colour index map (`decode_color_map_tokens`, detokenize.c:25-63 +
113+`av1_get_palette_color_index_context`, entropymode.c:893-967)
114+Wavefront over a `side x side` map (this decoder's blocks are always square
115+and this decoder already writes full `side*side` regions unconditionally
116+elsewhere -- e.g. the skip path's `vec![0i32; side*side]` residual -- so no
117+edge-cropping special case is needed, unlike libaom's rows/cols vs
118+plane_width/height split for non-block-aligned frame edges).
119+`map[0] = read_uniform(dec, n)`; then for `i in 1..2*side-1`, `j` from
120+`min(i, side-1)` down to `max(0, i-side+1)`: compute `(color_ctx, color_order)`
121+from the left/up-left/up already-decoded neighbours (weights `[2,1,2]`,
122+top-3 selection-sort exactly mirroring entropymode.c:924-946, hash
123+`scores[0]*1 + scores[1]*2 + scores[2]*2` through the fixed 9-entry
124+`av1_palette_color_index_context_lookup` table
125+`[-1,-1,0,-1,-1,4,3,2,1]`), read `dec.symbol(&mut cdfs.palette_y_color_index[n-2][ctx][..=n])`,
126+store `color_order[symbol]` at `map[row*side+col]`.
127+
128+### 6. Wiring the map into reconstruction WITHOUT touching 32 call sites
129+`PlaneBuf::reconstruct` (decode.rs:2762) already branches on
130+`filter_intra: Option<usize>` to skip `predict()`; add a third override ahead
131+of it, a thread-local exactly like the existing `ENABLE_EDGE_FILTER` idiom
132+(decode.rs:478, `predict()`'s own comment at :2786-2799 names this exact
133+pattern as the reason to reach for a thread-local instead of a 24-call-site
134+signature change):
135+```
136+thread_local! {
137+ static PALETTE_PRED: std::cell::RefCell<Option<Vec<u8>>> = const { std::cell::RefCell::new(None) };
138+}
139+```
140+At the top of `reconstruct`, `if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take())`
141+use `buf` as `prediction` directly (skips `edges()`/`predict()`/
142+`predict_filter_intra` entirely -- palette needs no edge pixels). `read_plane`
143+needs **zero** changes: it already just forwards to `plane.reconstruct(..)`,
144+so setting the thread-local right before calling it from `decode_block`
145+threads the override through transparently. Because AV1 palette blocks still
146+carry `mode == DC_PRED` (the palette-use symbol is gated on it, both call
147+sites), `default_intra_tx_type`/coefficient reading need no palette-specific
148+branch either -- the existing DC_PRED-derived tx_type is already correct.
149+
150+Set the thread-local (`y_pred[i] = colors[map[i]] as u8`, row-major, matching
151+`prediction[row*side+col]`'s own indexing) right before each luma
152+`reconstruct`/`read_plane` call for a palette block: the skip branch's
153+`y.reconstruct` (line ~3024), the single-TU branch's `read_plane` (~3067),
154+and -- to avoid a same-shape refusal-vs-silent-desync gap -- each iteration of
155+the split-luma-TU loop (~3161), slicing the full `side*side` map down to that
156+TU's `tu_side x tu_side` sub-rectangle first. If that slicing proves too
157+error-prone under budget, the acceptable fallback is a named refusal
158+("a palette block with a split luma transform") rather than skipping it
159+silently -- confirm which by testing against a real aomenc stream with
160+`--enable-palette=1 --tune-content=screen` before deciding; do not guess.
161+
162+### 7. Gate
163+New gate in `stream.rs`, matching an existing shape (`a_real_aomenc_stream_with_*`
164+pattern), `EC_AV1_REQUIRE_AOMENC=1`, `--threads=1 --row-mt=0
165+--enable-palette=1 --tune-content=screen`, fixture NOT `gradients_source`
166+(ignores its seed per an existing lane-vorbis dead-end already on file, and
167+per this charter's own note) -- a synthetic few-colour/repeated-tile pattern,
168+bounded with `-t`, hashed twice to prove determinism. Hard-assert a new
169+`PALETTE_HITS` thread-local (`fn record_palette_y`'s `size>0` branch
170+increments it) fires >0. Delete `enable-palette` from `gate_coverage.rs`'s
171+`NEVER_EXERCISED` list in the same commit that lands a firing gate.
172+
173+## Next lever
174+Type in sections 1-6 above in one pass (they were derived to compile against
175+this exact codebase's existing helpers -- `dec.literal(bits)` already exists
176+and matches `aom_read_literal`/`aom_read_bit` bit-for-bit, `SymbolDecoder::symbol`
177+already derives `nsyms` from slice length so no new CDF-arity machinery is
178+needed), then range-ladder one aomenc `--enable-palette=1` stream against
179+`EC_TRACE`/`compare-range-not-tell` before writing the gate. Stage 2 (UV) is
180+almost free once stage 1's `merge_colors`/cache/map machinery exists --
181+`read_palette_colors_uv` only adds a differently-shaped V-channel branch
182+(decodemv.c:538-563, delta OR raw literal per its own leading bit).
scripts/instrument-aom-oracle.shmodified+81 -0
@@ -377,3 +377,84 @@ s = s.replace(anchor, dump + anchor, 1)
377377 open(path, "w").write(s)
378378 print("prefilt-wide dump instrumented")
379379 PYW
380+# --- rung 8: palette colour-index map range ladder (detokenize.c) -------
381+# EC_TRACE_PALETTE=1 -> "EC_PAL row=.. col=.. ctx=.. n=.. rng=.." before every
382+# colour-index symbol in decode_color_map_tokens's wavefront, "EC_PAL_VAL
383+# row=.. col=.. color_idx=.. rng=.." after. lane-palette r4: r3 already
384+# cleared every table/context function against this same source line-for-line
385+# by hand; this rung is what lets a real per-symbol range compare (class
386+# compare-range-not-tell / equal-range-means-unread) replace that by-hand
387+# check instead of re-reading the tables again.
388+I="$SRC/av1/decoder/detokenize.c"
389+[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; }
390+
391+python3 - "$I" <<'PYP'
392+import sys
393+path = sys.argv[1]
394+s = open(path).read()
395+if "EC_INSTRUMENTED_PALETTE" in s:
396+ print("palette map already instrumented (no-op)")
397+ sys.exit(0)
398+
399+old = """ const int color_ctx = av1_get_palette_color_index_context(
400+ color_map, plane_block_width, (i - j), j, n, color_order, NULL);
401+ const int color_idx = aom_read_symbol(
402+ r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR);
403+ assert(color_idx >= 0 && color_idx < n);
404+ color_map[(i - j) * plane_block_width + j] = color_order[color_idx];"""
405+new = """/* EC_INSTRUMENTED_PALETTE */
406+ const int color_ctx = av1_get_palette_color_index_context(
407+ color_map, plane_block_width, (i - j), j, n, color_order, NULL);
408+ const int ec_pal_trace = getenv("EC_TRACE_PALETTE") != NULL;
409+ if (ec_pal_trace) {
410+ fprintf(stderr, "EC_PAL row=%d col=%d ctx=%d n=%d rng=%u\\n", (i - j),
411+ j, color_ctx, n, (unsigned)r->ec.rng);
412+ }
413+ const int color_idx = aom_read_symbol(
414+ r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR);
415+ assert(color_idx >= 0 && color_idx < n);
416+ color_map[(i - j) * plane_block_width + j] = color_order[color_idx];
417+ if (ec_pal_trace) {
418+ fprintf(stderr, "EC_PAL_VAL row=%d col=%d color_idx=%d rng=%u\\n",
419+ (i - j), j, color_idx, (unsigned)r->ec.rng);
420+ }"""
421+assert old in s, "decode_color_map_tokens loop body moved"
422+s = s.replace(old, new, 1)
423+s = s.replace(
424+ "static void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {",
425+ "/* EC_INSTRUMENTED_PALETTE */\nstatic void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {",
426+ 1,
427+)
428+open(path, "w").write(s)
429+print("palette map instrumented")
430+PYP
431+
432+# --- rung 8b: palette map[0] (av1_read_uniform) range ladder ------------
433+python3 - "$I" <<'PYP0'
434+import sys
435+path = sys.argv[1]
436+s = open(path).read()
437+if "EC_INSTRUMENTED_PALETTE_UNIFORM" in s:
438+ print("palette map[0] already instrumented (no-op)")
439+ sys.exit(0)
440+
441+old = """ // The first color index.
442+ color_map[0] = av1_read_uniform(r, n);
443+ assert(color_map[0] < n);"""
444+new = """ // The first color index.
445+ /* EC_INSTRUMENTED_PALETTE_UNIFORM */
446+ if (getenv("EC_TRACE_PALETTE") != NULL) {
447+ fprintf(stderr, "EC_PAL row=0 col=0 ctx=-1 n=%d rng=%u\\n", n,
448+ (unsigned)r->ec.rng);
449+ }
450+ color_map[0] = av1_read_uniform(r, n);
451+ assert(color_map[0] < n);
452+ if (getenv("EC_TRACE_PALETTE") != NULL) {
453+ fprintf(stderr, "EC_PAL_VAL row=0 col=0 color_idx=%d rng=%u\\n",
454+ color_map[0], (unsigned)r->ec.rng);
455+ }"""
456+assert old in s, "color_map[0] uniform read moved"
457+s = s.replace(old, new, 1)
458+open(path, "w").write(s)
459+print("palette map[0] instrumented")
460+PYP0