forge
Explore
Log in

Don't you dare go Hollow

Palette-Y reconstruction (colour cache, delta colours, wavefront index map, prediction wiring)

Browse files at this commit

c2f121e8335b7dadf4400ec3e207f1ac53f08f40Ahmet Kaan GümüşParent: 28f95f6
  • feat
    • palette-Y reconstruction (colour cache, delta colours, wavefront index map, prediction wiring)
Show full message
feat(av1): palette-Y reconstruction (colour cache, delta colours, wavefront index map, prediction wiring)

Types in report sections 3-6: Neighbours above/left_palette_size/colors +
record_palette_y + palette_ctx_and_cache (av1_get_palette_mode_ctx +
av1_get_palette_cache, SB-row-boundary above-null rule); read_palette_colors_y
(cache-accept bits + delta-coded remainder + merge_colors), read_uniform,
palette_color_index_context (weighted neighbour score + selection sort +
hash lookup table), decode_color_index_map (wavefront diagonal scan).
read_intra_mode gains a `palette: Option<(ctx, cache)>` param: Some at
decode_block's key-frame path (real decode), None at decode_leaf8 (old
refuse-unconditionally behaviour preserved bit-for-bit). Palette prediction
reaches PlaneBuf::reconstruct through a PALETTE_PRED thread-local (the
existing ENABLE_EDGE_FILTER idiom). A palette block under a split luma
transform refuses by name (untested against a real stream this round).
palette_uv_mode still refuses (UV reconstruction is stage 2) but its context
is now the block's own real just-decided Y palette use.

Refusal strings changed:
- REMOVED: "a block that actually uses a palette (Y) -- reconstruction is
  out of scope" from decode_block's key-frame path (still present,
  unreachable-changed, at decode_leaf8's excluded call site).
- ADDED: "a palette block with a split luma transform (round 1)".
- UNCHANGED (still present): the UV palette refusal string, verbatim.

cargo check -p ec-av1 --tests: clean. Full suite not run this round (turn
budget) -- next round's first job.
crates/ec-av1/src/decode.rsmodified+399 -54
@@ -197,6 +197,33 @@ pub(crate) fn comp_mode_hits() -> usize {
197 COMP_MODE_HITS.with(|c| c.get())197 COMP_MODE_HITS.with(|c| c.get())
198 }198 }
199 199
200+// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
201+// use for, across every call on the current thread -- the same before/after
202+// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
203+// exercised palette reconstruction rather than only reading and refusing the
204+// `palette_y_mode` symbol.
205+thread_local! {
206+ static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
207+}
208+
209+/// Current value of [`PALETTE_HITS`].
210+pub(crate) fn palette_hits() -> usize {
211+ PALETTE_HITS.with(|c| c.get())
212+}
213+
214+thread_local! {
215+ /// A just-decoded palette-Y block's own predicted pixels
216+ /// (`side*side`, row-major, `colors[map[i]]`), consumed by
217+ /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
218+ /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
219+ /// per-block override through `read_plane`'s two dozen call sites is the
220+ /// alternative this avoids). Always empty again once that call consumes
221+ /// it (`.take()`), so a non-palette block's own `reconstruct` call never
222+ /// sees stale state.
223+ static PALETTE_PRED: std::cell::RefCell<Option<Vec<u8>>> =
224+ const { std::cell::RefCell::new(None) };
225+}
226+
200 // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --227 // How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
201 // proves a real `skip_mode_present` stream actually reached a block that228 // proves a real `skip_mode_present` stream actually reached a block that
202 // picked it, not just that the frame header bit was set.229 // picked it, not just that the frame header bit was set.
@@ -1329,6 +1356,14 @@ struct Neighbours {
1329 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`1356 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
1330 /// reference onto `LAST_FRAME`'s own delta).1357 /// reference onto `LAST_FRAME`'s own delta).
1331 ref_grid: Vec<i8>,1358 ref_grid: Vec<i8>,
1359+ /// The block above/left's own palette-Y size (0 = not a palette block)
1360+ /// and its base colours -- `av1_get_palette_mode_ctx`/
1361+ /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
1362+ /// r2. UV has no equivalent yet (stage 2, unreconstructed).
1363+ above_palette_size: Vec<usize>,
1364+ left_palette_size: Vec<usize>,
1365+ above_palette_colors: Vec<[u16; 8]>,
1366+ left_palette_colors: Vec<[u16; 8]>,
1332 }1367 }
1333 1368
1334 impl Neighbours {1369 impl Neighbours {
@@ -1367,7 +1402,79 @@ impl Neighbours {
1367 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],1402 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1368 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],1403 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1369 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],1404 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1405+ above_palette_size: vec![0; cols],
1406+ left_palette_size: vec![0; rows],
1407+ above_palette_colors: vec![[0u16; 8]; cols],
1408+ left_palette_colors: vec![[0u16; 8]; rows],
1409+ }
1410+ }
1411+
1412+ /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
1413+ /// for a non-palette block, clearing any stale neighbour state) into every
1414+ /// [`SUB`]-grid cell it covers on both the above and left edges --
1415+ /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1416+ /// call sites are all square blocks).
1417+ fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
1418+ let (r, c) = at;
1419+ for cell in 0..side / SUB {
1420+ self.above_palette_size[c + cell] = size;
1421+ self.above_palette_colors[c + cell] = colors;
1422+ }
1423+ for cell in 0..side / SUB {
1424+ self.left_palette_size[r + cell] = size;
1425+ self.left_palette_colors[r + cell] = colors;
1426+ }
1427+ }
1428+
1429+ /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
1430+ /// neighbours that are themselves a palette-Y block, plus
1431+ /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
1432+ /// cache (pred_common.c:73) -- the above neighbour is excluded at a
1433+ /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells
1434+ /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.
1435+ fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
1436+ let (r, c) = at;
1437+ let above_ok = r % 4 != 0;
1438+ let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1439+ (self.above_palette_size[c], self.above_palette_colors[c])
1440+ } else {
1441+ (0, [0u16; 8])
1442+ };
1443+ let (left_n, left_colors) = if self.left_palette_size[r] > 0 {
1444+ (self.left_palette_size[r], self.left_palette_colors[r])
1445+ } else {
1446+ (0, [0u16; 8])
1447+ };
1448+ let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);
1449+ let mut cache = Vec::with_capacity(16);
1450+ let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1451+ if cache.last() != Some(&v) {
1452+ cache.push(v);
1453+ }
1454+ };
1455+ let (mut ai, mut li) = (0usize, 0usize);
1456+ while ai < above_n && li < left_n {
1457+ let (va, vl) = (above_colors[ai], left_colors[li]);
1458+ if vl < va {
1459+ push_dedup(&mut cache, vl);
1460+ li += 1;
1461+ } else {
1462+ push_dedup(&mut cache, va);
1463+ ai += 1;
1464+ if vl == va {
1465+ li += 1;
1466+ }
1467+ }
1468+ }
1469+ while ai < above_n {
1470+ push_dedup(&mut cache, above_colors[ai]);
1471+ ai += 1;
1370 }1472 }
1473+ while li < left_n {
1474+ push_dedup(&mut cache, left_colors[li]);
1475+ li += 1;
1476+ }
1477+ (ctx, cache)
1371 }1478 }
1372 1479
1373 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own1480 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
@@ -1910,6 +2017,185 @@ fn palette_bsize_ctx(side: usize) -> Option<usize> {
1910 }2017 }
1911 }2018 }
1912 2019
2020+/// A just-decoded palette-Y block's own size, base colours (only the first
2021+/// `size` entries are real), and per-pixel colour-index map (`side*side`,
2022+/// row-major, each entry `< size`).
2023+struct PaletteY {
2024+ size: usize,
2025+ colors: [u16; 8],
2026+ map: Vec<u8>,
2027+}
2028+
2029+/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
2030+/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
2031+/// `get_unsigned_bits`, which is the same formula): smallest `n` with
2032+/// `2^n >= x`, `0` for `x <= 1`.
2033+fn ceil_log2(x: u32) -> u32 {
2034+ if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
2035+}
2036+
2037+/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
2038+/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
2039+fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
2040+ let l = ceil_log2(n as u32);
2041+ let m = (1usize << l) - n;
2042+ let v = dec.literal(l - 1) as usize;
2043+ if v < m {
2044+ v
2045+ } else {
2046+ (v << 1) - m + dec.literal(1) as usize
2047+ }
2048+}
2049+
2050+/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
2051+/// colours (already-known, from the above/left neighbours) with the
2052+/// ascending `transmitted` ones (delta-coded off the wire) back into one
2053+/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
2054+/// value picks the cached copy first, matching the C `<=`.
2055+fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
2056+ let mut out = Vec::with_capacity(transmitted.len() + cached.len());
2057+ let (mut ci, mut ti) = (0, 0);
2058+ while ci < cached.len() && ti < transmitted.len() {
2059+ if cached[ci] <= transmitted[ti] {
2060+ out.push(cached[ci]);
2061+ ci += 1;
2062+ } else {
2063+ out.push(transmitted[ti]);
2064+ ti += 1;
2065+ }
2066+ }
2067+ out.extend_from_slice(&cached[ci..]);
2068+ out.extend_from_slice(&transmitted[ti..]);
2069+ out
2070+}
2071+
2072+/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
2073+/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
2074+/// (one flag bit each, in cache order), then delta-codes the remainder
2075+/// (first value raw, each following delta `>= 1` off a shrinking bit width),
2076+/// and merges the two ascending lists back together.
2077+fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
2078+ let mut cached = Vec::with_capacity(n);
2079+ for &c in cache {
2080+ if cached.len() >= n {
2081+ break;
2082+ }
2083+ if dec.literal(1) == 1 {
2084+ cached.push(c);
2085+ }
2086+ }
2087+ let mut colors = [0u16; 8];
2088+ let n_cached = cached.len();
2089+ if n_cached < n {
2090+ let mut transmitted = Vec::with_capacity(n - n_cached);
2091+ let first = dec.literal(8) as u16;
2092+ transmitted.push(first);
2093+ if n_cached + 1 < n {
2094+ let min_bits = 8u32 - 3;
2095+ let mut bits = min_bits + dec.literal(2);
2096+ let mut range = 255i32 - i32::from(first) - 1;
2097+ for _ in (n_cached + 1)..n {
2098+ let delta = dec.literal(bits) as i32 + 1;
2099+ let prev = *transmitted.last().unwrap();
2100+ let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
2101+ range -= i32::from(val) - i32::from(prev);
2102+ bits = bits.min(ceil_log2(range.max(0) as u32));
2103+ transmitted.push(val);
2104+ }
2105+ }
2106+ let merged = merge_colors(&transmitted, &cached);
2107+ colors[..n].copy_from_slice(&merged);
2108+ } else {
2109+ colors[..n].copy_from_slice(&cached[..n]);
2110+ }
2111+ colors
2112+}
2113+
2114+/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
2115+/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
2116+/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
2117+const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
2118+
2119+/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
2120+/// map's own per-pixel context and colour-order permutation, from the
2121+/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
2122+/// selection sort). `map`'s stride is `side` (this decoder never crops a
2123+/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
2124+/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
2125+/// actual colour index to store.
2126+fn palette_color_index_context(
2127+ map: &[u8],
2128+ side: usize,
2129+ row: usize,
2130+ col: usize,
2131+ n: usize,
2132+) -> (usize, [u8; 8]) {
2133+ let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
2134+ let up_left = if col >= 1 && row >= 1 {
2135+ Some(map[(row - 1) * side + col - 1])
2136+ } else {
2137+ None
2138+ };
2139+ let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
2140+ let mut scores = [0i32; 8];
2141+ for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
2142+ if let Some(v) = neighbour {
2143+ scores[v as usize] += weight;
2144+ }
2145+ }
2146+ let mut color_order = [0u8; 8];
2147+ for i in 0..8 {
2148+ color_order[i] = i as u8;
2149+ }
2150+ for i in 0..3 {
2151+ let mut max = scores[i];
2152+ let mut max_idx = i;
2153+ for j in (i + 1)..n {
2154+ if scores[j] > max {
2155+ max = scores[j];
2156+ max_idx = j;
2157+ }
2158+ }
2159+ if max_idx != i {
2160+ let max_score = scores[max_idx];
2161+ let max_color = color_order[max_idx];
2162+ for k in (i + 1..=max_idx).rev() {
2163+ scores[k] = scores[k - 1];
2164+ color_order[k] = color_order[k - 1];
2165+ }
2166+ scores[i] = max_score;
2167+ color_order[i] = max_color;
2168+ }
2169+ }
2170+ let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
2171+ let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
2172+ (ctx as usize, color_order)
2173+}
2174+
2175+/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
2176+/// map's wavefront decode over a `side x side` grid -- this decoder's
2177+/// palette blocks are always square and never straddle the frame's true
2178+/// (possibly odd) edge without already allocating the full `side*side`
2179+/// region (every other skip/residual path here does the same), so no
2180+/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
2181+/// libaom's own non-block-aligned split.
2182+fn decode_color_index_map(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, n: usize, side: usize) -> Vec<u8> {
2183+ let mut map = vec![0u8; side * side];
2184+ map[0] = read_uniform(dec, n) as u8;
2185+ for i in 1..(2 * side - 1) {
2186+ let j_hi = i.min(side - 1);
2187+ let j_lo = i.saturating_sub(side - 1);
2188+ for j in (j_lo..=j_hi).rev() {
2189+ let row = i - j;
2190+ let col = j;
2191+ let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);
2192+ let symbol = dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]);
2193+ map[row * side + col] = color_order[symbol];
2194+ }
2195+ }
2196+ map
2197+}
2198+
1913 /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):2199 /// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
1914 /// identical except the `use_filter_intra` size class comes from2200 /// identical except the `use_filter_intra` size class comes from
1915 /// [`filter_intra_size_class_rect`] instead of the square-only2201 /// [`filter_intra_size_class_rect`] instead of the square-only
@@ -2382,6 +2668,14 @@ fn read_intra_mode(
2382 skip_ctx: usize,2668 skip_ctx: usize,
2383 allow_screen_content_tools: bool,2669 allow_screen_content_tools: bool,
2384 allow_intrabc: bool,2670 allow_intrabc: bool,
2671+ // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
2672+ // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
2673+ // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
2674+ // `None` at the excluded call sites (the 8x8-leaf path), which still read
2675+ // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
2676+ // decoder reads either way -- but refuse by name the moment it fires,
2677+ // exactly the old behaviour.
2678+ palette: Option<(usize, &[u16])>,
2385 ) -> Result<(2679 ) -> Result<(
2386 bool,2680 bool,
2387 usize,2681 usize,
@@ -2390,6 +2684,7 @@ fn read_intra_mode(
2390 i32,2684 i32,
2391 Option<(i32, i32)>,2685 Option<(i32, i32)>,
2392 Option<usize>,2686 Option<usize>,
2687+ Option<PaletteY>,
2393 )> {2688 )> {
2394 let trace = std::env::var_os("EC_AV1_TRACE").is_some();2689 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
2395 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;2690 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
@@ -2471,24 +2766,36 @@ fn read_intra_mode(
2471 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called2766 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
2472 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):2767 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
2473 // gated by `av1_allow_palette` (blockd.h -- size bound only,2768 // gated by `av1_allow_palette` (blockd.h -- size bound only,
2474- // [`palette_bsize_ctx`]). `palette_mode_ctx`/`palette_uv_mode_ctx`2769+ // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
2475- // (`av1_get_palette_mode_ctx`, pred_common.h) read the neighbours' own2770+ // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
2476- // `palette_size[0] > 0` -- always 0 here since a nonzero size refuses2771+ // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
2477- // the whole decode below, so no successfully-completed decode ever has2772+ // read the same CDF row whenever every neighbour really is non-palette).
2478- // such a neighbour (corner-cut: hardcoded ctx 0 instead of tracking it,2773+ // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
2479- // ceiling = real palette reconstruction, out of this lane's scope).2774+ // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
2480- // A nonzero `palette_size` needs the color-cache/delta-coded-colors2775+ // neighbour lookup at all), so it is exact even at the excluded call
2481- // syntax this decoder does not reconstruct -- refuse by name rather2776+ // sites once Y decodes real syntax there too.
2482- // than silently drop pixels.2777+ let mut palette_y = None;
2483 if allow_screen_content_tools2778 if allow_screen_content_tools
2484 && let Some(bsize_ctx) = palette_bsize_ctx(side)2779 && let Some(bsize_ctx) = palette_bsize_ctx(side)
2485 {2780 {
2486- if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {2781+ let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
2487- return Err(unsupported(2782+ if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0 {
2488- "a block that actually uses a palette (Y) -- reconstruction is out of scope",2783+ if palette.is_none() {
2489- ));2784+ return Err(unsupported(
2785+ "a block that actually uses a palette (Y) -- reconstruction is out of scope",
2786+ ));
2787+ }
2788+ let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
2789+ let colors = read_palette_colors_y(dec, n, cache);
2790+ let map = decode_color_index_map(dec, cdfs, n, side);
2791+ PALETTE_HITS.with(|c| c.set(c.get() + 1));
2792+ if trace {
2793+ eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
2794+ }
2795+ palette_y = Some(PaletteY { size: n, colors, map });
2490 }2796 }
2491- if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {2797+ let palette_uv_mode_ctx = usize::from(palette_y.is_some());
2798+ if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
2492 return Err(unsupported(2799 return Err(unsupported(
2493 "a block that actually uses a palette (UV) -- reconstruction is out of scope",2800 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
2494 ));2801 ));
@@ -2530,6 +2837,7 @@ fn read_intra_mode(
2530 angle_delta_uv,2837 angle_delta_uv,
2531 alpha,2838 alpha,
2532 filter_intra,2839 filter_intra,
2840+ palette_y,
2533 ))2841 ))
2534 }2842 }
2535 2843
@@ -2771,45 +3079,53 @@ impl PlaneBuf {
2771 cfl: Option<(i32, &[i32])>,3079 cfl: Option<(i32, &[i32])>,
2772 filter_intra: Option<usize>,3080 filter_intra: Option<usize>,
2773 ) {3081 ) {
2774- let (above, left, corner) = self.edges(x, y, side, reach);3082+ // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
2775- let mut prediction = vec![0u8; side * side];3083+ // takes priority over `predict()`/`predict_filter_intra` entirely --
2776- if let Some(fi_mode) = filter_intra {3084+ // palette prediction needs no edge pixels at all.
2777- crate::intra::predict_filter_intra(3085+ let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {
2778- fi_mode,3086+ buf
2779- above.as_deref(),
2780- left.as_deref(),
2781- corner,
2782- side,
2783- &mut prediction,
2784- );
2785 } else {3087 } else {
2786- // `enable_intra_edge_filter` is the sequence header's own flag3088+ let (above, left, corner) = self.edges(x, y, side, reach);
2787- // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`3089+ let mut prediction = vec![0u8; side * side];
2788- // call, never per-block) -- threading it through every3090+ if let Some(fi_mode) = filter_intra {
2789- // `read_plane`/`decode_block`/`decode_leaf8` call would touch two3091+ crate::intra::predict_filter_intra(
2790- // dozen sites for a value that never changes mid-decode, so it3092+ fi_mode,
2791- // rides a thread-local instead (this decoder is single-threaded3093+ above.as_deref(),
2792- // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)3094+ left.as_deref(),
2793- // is left `false`: exact for chroma here (a smooth `uv_mode` is3095+ corner,
2794- // refused before decode reaches this call) and a corner-cut for3096+ side,
2795- // luma -- ceiling is one wrong filter-strength bucket on a block3097+ &mut prediction,
2796- // whose real neighbour predicted smooth; upgrade path is3098+ );
2797- // threading `Neighbours::above_mode`/`left_mode`'s3099+ } else {
2798- // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.3100+ // `enable_intra_edge_filter` is the sequence header's own flag
2799- let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);3101+ // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
2800- predict(3102+ // call, never per-block) -- threading it through every
2801- mode as u8,3103+ // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
2802- angle_delta,3104+ // dozen sites for a value that never changes mid-decode, so it
2803- above.as_deref(),3105+ // rides a thread-local instead (this decoder is single-threaded
2804- left.as_deref(),3106+ // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)
2805- corner,3107+ // is left `false`: exact for chroma here (a smooth `uv_mode` is
2806- side,3108+ // refused before decode reaches this call) and a corner-cut for
2807- side,3109+ // luma -- ceiling is one wrong filter-strength bucket on a block
2808- enable_edge_filter,3110+ // whose real neighbour predicted smooth; upgrade path is
2809- false,3111+ // threading `Neighbours::above_mode`/`left_mode`'s
2810- &mut prediction,3112+ // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.
2811- );3113+ let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
2812- }3114+ predict(
3115+ mode as u8,
3116+ angle_delta,
3117+ above.as_deref(),
3118+ left.as_deref(),
3119+ corner,
3120+ side,
3121+ side,
3122+ enable_edge_filter,
3123+ false,
3124+ &mut prediction,
3125+ );
3126+ }
3127+ prediction
3128+ };
2813 for row in 0..side {3129 for row in 0..side {
2814 for col in 0..side {3130 for col in 0..side {
2815 let idx = row * side + col;3131 let idx = row * side + col;
@@ -2969,7 +3285,8 @@ fn decode_block(
2969 ) -> Result<()> {3285 ) -> Result<()> {
2970 let (r, c) = at;3286 let (r, c) = at;
2971 let (px, py) = (c * SUB, r * SUB);3287 let (px, py) = (c * SUB, r * SUB);
2972- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =3288+ let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
3289+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y) =
2973 read_intra_mode(3290 read_intra_mode(
2974 dec,3291 dec,
2975 cdfs,3292 cdfs,
@@ -2981,6 +3298,7 @@ fn decode_block(
2981 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),3298 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2982 allow_screen_content_tools,3299 allow_screen_content_tools,
2983 allow_intrabc,3300 allow_intrabc,
3301+ Some((palette_ctx, &palette_cache)),
2984 )?;3302 )?;
2985 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`3303 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
2986 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the3304 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
@@ -3018,6 +3336,23 @@ fn decode_block(
3018 let reach = Reach::of(side, px, py, y.width, y.height);3336 let reach = Reach::of(side, px, py, y.width, y.height);
3019 let (cpx, cpy) = (px / 2, py / 2);3337 let (cpx, cpy) = (px / 2, py / 2);
3020 let chroma_side = side / 2;3338 let chroma_side = side / 2;
3339+ // A palette-Y block's own prediction is the reconstructed colour-index
3340+ // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
3341+ // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
3342+ // parameter through this function's dozen `y.reconstruct`/`read_plane`
3343+ // sites. A split luma transform (`tx_select && logical_tx != side`)
3344+ // would need the map sliced per-TU -- untested against a real
3345+ // `--enable-palette=1` stream this round, so refuse by name rather than
3346+ // guess at the slicing (charter's own named-acceptable fallback).
3347+ if let Some(ref py) = palette_y {
3348+ if tx_select && logical_tx != side {
3349+ return Err(unsupported(
3350+ "a palette block with a split luma transform (round 1)",
3351+ ));
3352+ }
3353+ let buf: Vec<u8> = py.map.iter().map(|&idx| py.colors[idx as usize] as u8).collect();
3354+ PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
3355+ }
3021 if skip {3356 if skip {
3022 // A skipped block codes no residual syntax at all (spec 5.11.34):3357 // A skipped block codes no residual syntax at all (spec 5.11.34):
3023 // straight prediction, on every plane.3358 // straight prediction, on every plane.
@@ -3236,6 +3571,15 @@ fn decode_block(
3236 )?;3571 )?;
3237 neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]);3572 neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]);
3238 }3573 }
3574+ // Unconditional, `size == 0` for a non-palette block: clears any stale
3575+ // neighbour palette state the same way [`Neighbours::record`] always
3576+ // overwrites `above_mode`/`left_mode` regardless of this block's own mode
3577+ // (the split-luma-TU branch above always refuses before reaching here
3578+ // when `palette_y` is `Some`, so it is never live for that branch).
3579+ let (py_size, py_colors) = palette_y
3580+ .as_ref()
3581+ .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
3582+ neighbours.record_palette_y(at, side, py_size, py_colors);
3239 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);3583 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
3240 neighbours.fill_lf_grid(3584 neighbours.fill_lf_grid(
3241 (r * (SUB / MI), c * (SUB / MI)),3585 (r * (SUB / MI), c * (SUB / MI)),
@@ -3287,7 +3631,7 @@ fn decode_leaf8(
3287 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec3631 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
3288 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other3632 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
3289 // `decode_block` caller at 16x16 and up.3633 // `decode_block` caller at 16x16 and up.
3290- let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =3634+ let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y) =
3291 read_intra_mode(3635 read_intra_mode(
3292 dec,3636 dec,
3293 cdfs,3637 cdfs,
@@ -3299,6 +3643,7 @@ fn decode_leaf8(
3299 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),3643 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
3300 allow_screen_content_tools,3644 allow_screen_content_tools,
3301 allow_intrabc,3645 allow_intrabc,
3646+ None,
3302 )?;3647 )?;
3303 let uv_predict_mode = if uv_mode == UV_CFL_PRED {3648 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3304 DC_PRED3649 DC_PRED