forge
Explore
Log in

Don't you dare go Hollow

Lane-palette recon -- full stage-1 palette-Y implementation plan, no code landed (budget spent deriving the algorithm against libaom)

Browse files at this commit

e76206dc359cd3e6cbc266e1eca3235e32b7a5a6Ahmet Kaan GümüşParent: e23b762
  • docs
    • lane-palette recon -- full stage-1 palette-Y implementation plan, no code landed (budget spent deriving the algorithm against libaom)
Show full message
docs(av1): lane-palette recon -- full stage-1 palette-Y implementation plan, no code landed (budget spent deriving the algorithm against libaom)
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).