forge
Explore
Log in

Don't you dare go Hollow

Chroma palette -- palette_uv_mode, the U cache/delta colours, V, and the shared index map

Browse files at this commit

ace59f52e1621f7627b3dd50fd4ea8eb4bc546cbAhmet Kaan GümüşParent: 7aa0792
  • feat
    • chroma palette -- palette_uv_mode, the U cache/delta colours, V, and the shared index map
Show full message
feat(av1): chroma palette -- palette_uv_mode, the U cache/delta colours, V, and the shared index map

The decoder read every one of these symbols already; the encoder wrote
palette_uv_mode == 0 unconditionally. Now search_chroma prices a chroma
palette arm against the best ordinary chroma mode: one 1-D k-means over U
(the same palette_candidates the luma arm uses, which is what keeps
u_colors ascending and distinct for read_palette_colors_uv's merge), V
taken as each cluster's mean, one index map shared by both planes at
(side/2).max(4) -- av1_get_plane_block_size, not a plain halving.

Mirrored from the decoder: read_palette_colors_uv (U's range starts at
256-first and its deltas are unbiased, both unlike Y), palette_uv_cache_mi
and record_palette_uv_rect (new above/left uv bands in tile.rs Neighbours,
drained through record_mi_planes so a block that takes no chroma palette
clears its column), and the plane order -- both colour lists, then both
index maps.

corner-cut: V's colours take the reader's raw form (leading bit 0, n 8-bit
literals) instead of the signed-delta form; ceiling ~n bits per block, and
the RD pricer sees it, so it can only make the encoder take fewer chroma
palettes than it should.

Screen clip: +56.9%/+2.3% -> +55.1%/+1.1% vs libaom/rav1e, 126 chroma
palette blocks, 6.1s -> 6.4s. Film clips do not set the header bit and are
byte-unchanged. The oracle test now proves size-2 and size-4 chroma
palettes AND 36 colours taken from the neighbour cache.
crates/ec-av1/src/encode.rsmodified+127 -8
@@ -2555,7 +2555,7 @@ fn code_square(
25552555
25562556 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
25572557 // planes; what it costs still counts towards the partition decision.
2558- let ([u, v], uv_mode, chroma_cost) =
2558+ let ([u, v], uv_mode, chroma_cost, palette_uv) =
25592559 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
25602560 cost += chroma_cost;
25612561 (
@@ -2567,6 +2567,7 @@ fn code_square(
25672567 uv_mode,
25682568 tx_depth,
25692569 palette,
2570+ palette_uv,
25702571 ..BlockCoeffs::default()
25712572 },
25722573 cost,
@@ -2656,7 +2657,7 @@ fn search_chroma(
26562657 search: &Search,
26572658 luma_mode: u8,
26582659 fctx: &crate::decode::FrameCtx,
2659-) -> ([Vec<Coeff>; 2], u8, f64) {
2660+) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
26602661 let at = At {
26612662 x: x / 2,
26622663 y: y / 2,
@@ -2704,7 +2705,79 @@ fn search_chroma(
27042705 best = Some((cost, mode, u, v));
27052706 }
27062707 }
2707- let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty");
2708+ let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
2709+ // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
2710+ // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
2711+ // what keeps `u_colors` ascending and distinct the way
2712+ // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
2713+ // each cluster's own mean, since the colour-index map is SHARED by the
2714+ // two planes. Priced against the best ordinary chroma mode above, so a
2715+ // block only takes one when it beats it; a palette block's chroma mode is
2716+ // `UV_DC_PRED` by construction.
2717+ let mut palette_uv = None;
2718+ if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2719+ debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
2720+ let plane_source = |p: &Plane| -> Vec<u8> {
2721+ (at.y..at.y + at.side)
2722+ .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
2723+ .collect()
2724+ };
2725+ let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
2726+ for pal in palette_candidates(&u_source) {
2727+ let n = usize::from(pal.size);
2728+ // V's base colour per cluster: the mean of the samples the shared
2729+ // map assigns to it (an empty cluster cannot happen -- every
2730+ // colour `palette_candidates` returns is some pixel's nearest).
2731+ let mut sums = [0u32; 8];
2732+ let mut counts = [0u32; 8];
2733+ for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
2734+ let k = usize::from(i).min(n - 1);
2735+ sums[k] += u32::from(sample);
2736+ counts[k] += 1;
2737+ }
2738+ let mut v_colors = [0u16; 8];
2739+ for k in 0..n {
2740+ v_colors[k] = if counts[k] > 0 {
2741+ ((sums[k] + counts[k] / 2) / counts[k]) as u16
2742+ } else {
2743+ 0
2744+ };
2745+ }
2746+ let candidate = crate::tile::PaletteUv {
2747+ size: pal.size,
2748+ u_colors: pal.colors,
2749+ v_colors,
2750+ map: pal.map,
2751+ };
2752+ let predict = |colors: &[u16; 8]| -> Vec<u8> {
2753+ candidate
2754+ .map
2755+ .iter()
2756+ .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
2757+ .collect()
2758+ };
2759+ let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
2760+ let u_trial = chroma[0].code_from_prediction(
2761+ at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
2762+ );
2763+ let v_trial = chroma[1].code_from_prediction(
2764+ at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
2765+ );
2766+ let cost_p = u_trial.sse
2767+ + v_trial.sse
2768+ + search.lambda
2769+ * (u_trial.bits
2770+ + v_trial.bits
2771+ + crate::tile::palette_uv_bits(&candidate, side));
2772+ if cost_p < cost {
2773+ cost = cost_p;
2774+ mode = DC_PRED;
2775+ u = u_trial;
2776+ v = v_trial;
2777+ palette_uv = Some(candidate);
2778+ }
2779+ }
2780+ }
27082781 if census_on() {
27092782 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
27102783 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -2716,6 +2789,7 @@ fn search_chroma(
27162789 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
27172790 mode,
27182791 cost,
2792+ palette_uv,
27192793 )
27202794 }
27212795
@@ -2963,6 +3037,7 @@ fn code_square_inter(
29633037 skip: skip_new,
29643038 eight: None,
29653039 palette: None,
3040+ palette_uv: None,
29663041 tx_depth,
29673042 inter: Some(InterInfo {
29683043 ref1: None,
@@ -3000,6 +3075,7 @@ fn code_square_inter(
30003075 skip,
30013076 eight: None,
30023077 palette: None,
3078+ palette_uv: None,
30033079 tx_depth,
30043080 inter: Some(InterInfo {
30053081 ref1: None,
@@ -5054,6 +5130,7 @@ fn search_inter_block(
50545130 inter: best.inter,
50555131 eight: None,
50565132 palette: None,
5133+ palette_uv: None,
50575134 tx_depth: 0,
50585135 },
50595136 best.cost,
@@ -6397,11 +6474,18 @@ mod tests {
63976474 picture.y[y * width + x] = INK[cell * 2 + bar];
63986475 }
63996476 }
6477+ // Four chroma colours, not two: a two-colour chroma block only ever
6478+ // codes a `PaletteSizeUV` of 2, which leaves
6479+ // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
6480+ // deltas and the neighbour cache flags, exercised only when
6481+ // neighbouring blocks share colours) unproven by the ffmpeg oracle.
6482+ const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
6483+ const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
64006484 for y in 0..height / 2 {
64016485 for x in 0..width / 2 {
6402- let cell = (x / 12 + y / 12) % 2;
6403- picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 };
6404- picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 };
6486+ let cell = (x / 12 + 2 * (y / 12)) % 4;
6487+ picture.u[y * (width / 2) + x] = CHROMA_U[cell];
6488+ picture.v[y * (width / 2) + x] = CHROMA_V[cell];
64056489 }
64066490 }
64076491 picture
@@ -6427,6 +6511,23 @@ mod tests {
64276511 let hits = crate::tile::take_palette_hits();
64286512 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
64296513 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
6514+ // The chroma half is a claim about the plane-1 syntax only if some
6515+ // block really took a chroma palette (`gate-blind-to-feature`): every
6516+ // exactness assert below passes on a stream that codes
6517+ // `palette_uv_mode == 0` everywhere.
6518+ let uv_hits = crate::tile::take_palette_uv_hits();
6519+ assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
6520+ let uv_cached = crate::tile::take_palette_uv_cache_hits();
6521+ eprintln!(
6522+ "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
6523+ uv_hits[0],
6524+ &uv_hits[2..]
6525+ );
6526+ assert!(
6527+ uv_cached > 0,
6528+ "no chroma base colour came out of the neighbour cache -- \
6529+ `write_palette_colors_uv`'s cache half is unproven by the oracle below"
6530+ );
64306531 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
64316532 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
64326533 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
@@ -6463,12 +6564,19 @@ mod tests {
64636564 })
64646565 .collect();
64656566 let _ = crate::tile::take_palette_hits();
6567+ let _ = crate::tile::take_palette_uv_hits();
64666568 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
64676569 let gop_hits = crate::tile::take_palette_hits();
6570+ let gop_uv_hits = crate::tile::take_palette_uv_hits();
64686571 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
64696572 eprintln!(
6470- "GOP: {} frames with screen tools after the key frame, {} palette blocks",
6471- inter_screen, gop_hits[0]
6573+ "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
6574+ {} chroma palette blocks",
6575+ inter_screen, gop_hits[0], gop_uv_hits[0]
6576+ );
6577+ assert!(
6578+ gop_uv_hits[0] > 0,
6579+ "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
64726580 );
64736581 assert!(
64746582 inter_screen > 0,
@@ -6530,6 +6638,7 @@ mod tests {
65306638 skip: false,
65316639 eight: None,
65326640 palette: None,
6641+ palette_uv: None,
65336642 tx_depth: 0,
65346643 inter: Some(InterInfo {
65356644 ref1: None,
@@ -9354,6 +9463,16 @@ mod tests {
93549463 .collect::<Vec<_>>()
93559464 .join(" ")
93569465 );
9466+ let palette_uv = crate::tile::take_palette_uv_hits();
9467+ eprintln!(
9468+ "{name}: chroma palette blocks {} sizes {}",
9469+ palette_uv[0],
9470+ (2..=8)
9471+ .filter(|&n| palette_uv[n] > 0)
9472+ .map(|n| format!("{n}={}", palette_uv[n]))
9473+ .collect::<Vec<_>>()
9474+ .join(" ")
9475+ );
93579476 let uv = take_uv_mode_hits();
93589477 let uv_total: usize = uv.iter().sum();
93599478 eprintln!(
crates/ec-av1/src/tile.rsmodified+280 -2
@@ -1120,6 +1120,11 @@ pub struct BlockCoeffs {
11201120 /// `tx_depth` to zero (the whole block is one transform over the
11211121 /// palette's own prediction).
11221122 pub palette: Option<PaletteY>,
1123+ /// The chroma palette this block's two chroma planes are predicted with
1124+ /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
1125+ /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
1126+ /// one; it is independent of [`Self::palette`] (either, both or neither).
1127+ pub palette_uv: Option<PaletteUv>,
11231128 /// How many times this block's luma transform is halved under
11241129 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
11251130 /// block). Read only by the writers a `tx_select` frame calls; a
@@ -1143,6 +1148,27 @@ pub struct PaletteY {
11431148 pub map: Vec<u8>,
11441149 }
11451150
1151+/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
1152+/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
1153+/// are co-located after 4:2:0 subsampling) plus each plane's own base
1154+/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
1155+/// the stream.
1156+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1157+pub struct PaletteUv {
1158+ /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
1159+ pub size: u8,
1160+ /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
1161+ /// merges the cached and transmitted lists as two ascending runs, and its
1162+ /// delta form only ever steps upwards.
1163+ pub u_colors: [u16; 8],
1164+ /// V's base colours, in the same cluster order as [`Self::u_colors`] --
1165+ /// the shared map indexes both, and V's own coding needs no ordering.
1166+ pub v_colors: [u16; 8],
1167+ /// Which colour each chroma pixel takes, row-major over the subsampled
1168+ /// block's own `(side / 2).max(4)` side.
1169+ pub map: Vec<u8>,
1170+}
1171+
11461172 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
11471173 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
11481174 /// [`write_inter_mode`] with the decoder's own contexts.
@@ -1396,6 +1422,15 @@ struct Neighbours {
13961422 pending_palette: Option<(u8, [u16; 8])>,
13971423 /// The colours beside [`Self::above_palette_size`].
13981424 above_palette_colors: Vec<[u16; 8]>,
1425+ /// The chroma (U-channel) halves of the three bands above --
1426+ /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
1427+ /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
1428+ above_palette_uv_size: Vec<u8>,
1429+ left_palette_uv_size: Vec<u8>,
1430+ above_palette_uv_colors: Vec<[u16; 8]>,
1431+ left_palette_uv_colors: Vec<[u16; 8]>,
1432+ /// [`Self::pending_palette`] for the chroma palette.
1433+ pending_palette_uv: Option<(u8, [u16; 8])>,
13991434 /// The same, down the left edge.
14001435 left_palette_colors: Vec<[u16; 8]>,
14011436 /// Whether the neighbour was coded inter, for the `is_inter` context.
@@ -1487,6 +1522,11 @@ impl Neighbours {
14871522 left_palette_size: vec![0; rows * (SUB / MI)],
14881523 pending_palette: None,
14891524 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
1525+ above_palette_uv_size: vec![0; cols * (SUB / MI)],
1526+ left_palette_uv_size: vec![0; rows * (SUB / MI)],
1527+ above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
1528+ left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
1529+ pending_palette_uv: None,
14901530 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
14911531 mi_cols,
14921532 mi_rows,
@@ -1525,6 +1565,8 @@ impl Neighbours {
15251565 self.left_tx.iter_mut().for_each(|t| *t = 0);
15261566 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
15271567 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
1568+ self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
1569+ self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
15281570 }
15291571
15301572 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
@@ -1582,6 +1624,80 @@ impl Neighbours {
15821624 (ctx, cache)
15831625 }
15841626
1627+ /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
1628+ /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
1629+ /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
1630+ /// neighbour lookup at all (it is this block's own just-decided Y palette
1631+ /// use), so only the cache is wanted here.
1632+ fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
1633+ let above_ok = r % 16 != 0;
1634+ let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
1635+ (
1636+ usize::from(self.above_palette_uv_size[c]),
1637+ self.above_palette_uv_colors[c],
1638+ )
1639+ } else {
1640+ (0, [0u16; 8])
1641+ };
1642+ let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
1643+ (
1644+ usize::from(self.left_palette_uv_size[r]),
1645+ self.left_palette_uv_colors[r],
1646+ )
1647+ } else {
1648+ (0, [0u16; 8])
1649+ };
1650+ let mut cache = Vec::with_capacity(16);
1651+ let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1652+ if cache.last() != Some(&v) {
1653+ cache.push(v);
1654+ }
1655+ };
1656+ let (mut ai, mut li) = (0usize, 0usize);
1657+ while ai < above_n && li < left_n {
1658+ let (va, vl) = (above_colors[ai], left_colors[li]);
1659+ if vl < va {
1660+ push_dedup(&mut cache, vl);
1661+ li += 1;
1662+ } else {
1663+ push_dedup(&mut cache, va);
1664+ ai += 1;
1665+ if vl == va {
1666+ li += 1;
1667+ }
1668+ }
1669+ }
1670+ while ai < above_n {
1671+ push_dedup(&mut cache, above_colors[ai]);
1672+ ai += 1;
1673+ }
1674+ while li < left_n {
1675+ push_dedup(&mut cache, left_colors[li]);
1676+ li += 1;
1677+ }
1678+ cache
1679+ }
1680+
1681+ /// [`Self::record_palette_y`] for the chroma bands (decode.rs
1682+ /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
1683+ /// way, and the span is in LUMA pixels for both planes' bands alike.
1684+ fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
1685+ for cell in 0..(side / MI).max(1) {
1686+ if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
1687+ *e = size;
1688+ if size > 0 {
1689+ self.above_palette_uv_colors[c + cell] = colors;
1690+ }
1691+ }
1692+ if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
1693+ *e = size;
1694+ if size > 0 {
1695+ self.left_palette_uv_colors[r + cell] = colors;
1696+ }
1697+ }
1698+ }
1699+ }
1700+
15851701 /// What a just-written block leaves in the palette bands (decode.rs
15861702 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
15871703 /// spans, `0` for a block that took no palette.
@@ -1750,6 +1866,8 @@ impl Neighbours {
17501866 if screen_armed() {
17511867 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
17521868 self.record_palette_y(at_mi, side, size, colors);
1869+ let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
1870+ self.record_palette_uv(at_mi, side, uv_size, uv_colors);
17531871 }
17541872 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
17551873 let side_mi = side / MI;
@@ -2522,6 +2640,72 @@ fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]
25222640 }
25232641 }
25242642
2643+/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
2644+/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
2645+/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
2646+/// documented differences -- the shrinking range starts at `256 - first`
2647+/// (not `255 - first`) and each delta is written unbiased (no `-1`).
2648+///
2649+/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
2650+/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
2651+/// Ceiling: about `n` bits per chroma-palette block more than the delta form
2652+/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
2653+/// below sees, so it only ever makes the encoder take FEWER chroma palettes
2654+/// than it should -- never a wrong stream. Upgrade path: price both forms
2655+/// here and write the cheaper one under its own leading bit.
2656+fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) {
2657+ let n = u_colors.len();
2658+ let mut cached: Vec<u16> = Vec::with_capacity(n);
2659+ for &c in cache {
2660+ if cached.len() >= n {
2661+ break;
2662+ }
2663+ let take = u_colors.contains(&c);
2664+ enc.literal(u32::from(take), 1);
2665+ if take {
2666+ PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2667+ cached.push(c);
2668+ }
2669+ }
2670+ let transmitted: Vec<u16> = u_colors
2671+ .iter()
2672+ .copied()
2673+ .filter(|c| !cached.contains(c))
2674+ .collect();
2675+ if !transmitted.is_empty() {
2676+ enc.literal(u32::from(transmitted[0]), 8);
2677+ if transmitted.len() > 1 {
2678+ let fits = |extra: u32| -> bool {
2679+ let mut bits = 5 + extra;
2680+ let mut range = 256i32 - i32::from(transmitted[0]);
2681+ for w in transmitted.windows(2) {
2682+ let delta = i32::from(w[1]) - i32::from(w[0]);
2683+ if delta >= (1i32 << bits) {
2684+ return false;
2685+ }
2686+ range -= delta;
2687+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2688+ }
2689+ true
2690+ };
2691+ let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
2692+ enc.literal(extra, 2);
2693+ let mut bits = 5 + extra;
2694+ let mut range = 256i32 - i32::from(transmitted[0]);
2695+ for w in transmitted.windows(2) {
2696+ let delta = i32::from(w[1]) - i32::from(w[0]);
2697+ enc.literal(delta as u32, bits);
2698+ range -= delta;
2699+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2700+ }
2701+ }
2702+ }
2703+ enc.literal(0, 1);
2704+ for &v in v_colors {
2705+ enc.literal(u32::from(v), 8);
2706+ }
2707+}
2708+
25252709 /// `write_palette_color_map` (bitstream.c), the write side of
25262710 /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
25272711 /// each symbol written as the position its colour takes in the neighbour
@@ -2571,6 +2755,25 @@ pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
25712755 enc.bits()
25722756 }
25732757
2758+/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
2759+/// size symbol, both colour lists and the shared colour-index map, priced
2760+/// through the very writers above (empty cache, which only over-prices).
2761+pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
2762+ let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2763+ return f64::INFINITY;
2764+ };
2765+ let n = usize::from(pal.size);
2766+ let mut enc = SymbolEncoder::pricer();
2767+ let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
2768+ enc.symbol(1, &mut mode_cdf);
2769+ let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
2770+ enc.symbol(n - 2, &mut size_cdf);
2771+ write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
2772+ let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
2773+ write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n);
2774+ enc.bits()
2775+}
2776+
25742777 /// Writes everything a key frame's block carries before its coefficients: the
25752778 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
25762779 /// the angle a directional mode is steered by, and its chroma mode. Hands back
@@ -2621,7 +2824,17 @@ fn write_intra_mode(
26212824 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
26222825 // codes none -- exactly the ctx-0 read the decoder does under the same
26232826 // condition.
2624- write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side);
2827+ write_palette_syntax(
2828+ enc,
2829+ cdfs,
2830+ neighbours,
2831+ block.palette.as_ref(),
2832+ block.palette_uv.as_ref(),
2833+ mode,
2834+ uv_mode,
2835+ mi,
2836+ side,
2837+ );
26252838 mode
26262839 }
26272840
@@ -2644,6 +2857,7 @@ fn write_palette_syntax(
26442857 cdfs: &mut Cdfs,
26452858 neighbours: &mut Neighbours,
26462859 palette: Option<&PaletteY>,
2860+ palette_uv: Option<&PaletteUv>,
26472861 mode: usize,
26482862 uv_mode: usize,
26492863 mi: (usize, usize),
@@ -2653,8 +2867,10 @@ fn write_palette_syntax(
26532867 return;
26542868 }
26552869 let palette = palette.filter(|_| mode == DC_PRED);
2870+ let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
26562871 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
26572872 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2873+ let uv_cache = neighbours.palette_uv_cache(mi);
26582874 if mode == DC_PRED {
26592875 enc.symbol(
26602876 usize::from(palette.is_some()),
@@ -2667,15 +2883,45 @@ fn write_palette_syntax(
26672883 write_palette_colors_y(enc, &pal.colors[..n], &cache);
26682884 }
26692885 if uv_mode == DC_PRED {
2670- enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]);
2886+ enc.symbol(
2887+ usize::from(palette_uv.is_some()),
2888+ &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
2889+ );
2890+ }
2891+ if let Some(pal) = palette_uv {
2892+ let n = usize::from(pal.size);
2893+ enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
2894+ write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
26712895 }
2896+ // Both colour-index maps come after BOTH colour lists, in plane order
2897+ // (`av1_visit_palette` runs from the caller, past `filter_intra`).
26722898 if let Some(pal) = palette {
26732899 let n = usize::from(pal.size);
26742900 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
26752901 note_palette(n);
26762902 }
2903+ if let Some(pal) = palette_uv {
2904+ let n = usize::from(pal.size);
2905+ write_color_index_map(
2906+ enc,
2907+ &mut cdfs.palette_uv_color_index[n - 2],
2908+ &pal.map,
2909+ palette_uv_side(side),
2910+ n,
2911+ );
2912+ note_palette_uv(n);
2913+ }
26772914 }
26782915 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
2916+ neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
2917+}
2918+
2919+/// The side of a chroma palette's shared colour-index map for a square luma
2920+/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
2921+/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
2922+/// exactly this size).
2923+pub(crate) fn palette_uv_side(side: usize) -> usize {
2924+ (side / 2).max(4)
26792925 }
26802926
26812927 /// How many blocks took a palette, and of what size -- the fire count a gate
@@ -2690,6 +2936,35 @@ fn note_palette(n: usize) {
26902936 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
26912937 }
26922938
2939+/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
2940+/// print the share of each plane's palette separately.
2941+static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
2942+ [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
2943+
2944+fn note_palette_uv(n: usize) {
2945+ PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2946+ PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2947+}
2948+
2949+/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
2950+/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
2951+/// the block counts alone, and the one that desyncs the tile if this writer's
2952+/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
2953+static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
2954+ std::sync::atomic::AtomicUsize::new(0);
2955+
2956+/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
2957+#[cfg(test)]
2958+pub(crate) fn take_palette_uv_cache_hits() -> usize {
2959+ PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
2960+}
2961+
2962+/// [`take_palette_hits`] for the chroma palette.
2963+#[cfg(test)]
2964+pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
2965+ std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2966+}
2967+
26932968 /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
26942969 /// its own encode.
26952970 #[cfg(test)]
@@ -4613,6 +4888,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
46134888 &mut cdfs,
46144889 &mut neighbours,
46154890 block.palette.as_ref(),
4891+ block.palette_uv.as_ref(),
46164892 mode,
46174893 uv_mode,
46184894 (mi_row, mi_col),
@@ -4836,6 +5112,7 @@ fn write_inter_frame_leaf(
48365112 cdfs,
48375113 neighbours,
48385114 block.palette.as_ref(),
5115+ block.palette_uv.as_ref(),
48395116 mode,
48405117 uv_mode,
48415118 (mi_row, mi_col),
@@ -5065,6 +5342,7 @@ fn write_inter_frame_leaf8(
50655342 cdfs,
50665343 neighbours,
50675344 block.palette.as_ref(),
5345+ block.palette_uv.as_ref(),
50685346 mode,
50695347 uv_mode,
50705348 leaf_mi,