forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1pal2' (be1937b0): chroma palette and a 128-colour palette bound

Browse files at this commit

691f69e6f708a70d7fea0b9f1b1b843d6bd9d556Ahmet Kaan GümüşParent: d4248c3f5fa526
Screen BD vs libaom +66.4 -> +55.1, vs rav1e +10.3 -> +1.1; both film
clips byte-identical. The 32-colour bound was an unswept constant (-9.5
points on its own). Screen tools forced on for film measured worse on 1080p
and non-monotone, so the detector stays; the 32x32 palette arm was dead
work and is not in.
crates/ec-av1/src/encode.rsmodified+137 -9
@@ -2338,6 +2338,15 @@ fn commit_inter_luma(
23382338 /// The largest distinct-colour count a block may hold and still be offered a
23392339 /// palette candidate at all: past it the k-means quantisation costs more
23402340 /// error than the map saves rate, and every trial is wasted wall.
2341+///
2342+/// Swept on the gate's own screen capture (lane-av1pal2, the
2343+/// `unswept-decision-constants` class): 32 (the value this lane inherited)
2344+/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
2345+/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
2346+/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
2347+/// binds on nothing this content holds. 128 ships: best BD against both
2348+/// references and no wall cost at all (6.1s, the same as at 32, because the
2349+/// blocks it newly admits are ones the RD then keeps).
23412350 /// `EC_AV1_PAL_MAXCOLORS`.
23422351 fn palette_max_colors() -> usize {
23432352 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
@@ -2345,7 +2354,7 @@ fn palette_max_colors() -> usize {
23452354 std::env::var("EC_AV1_PAL_MAXCOLORS")
23462355 .ok()
23472356 .and_then(|v| v.parse().ok())
2348- .unwrap_or(32)
2357+ .unwrap_or(128)
23492358 })
23502359 }
23512360
@@ -2546,7 +2555,7 @@ fn code_square(
25462555
25472556 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
25482557 // planes; what it costs still counts towards the partition decision.
2549- let ([u, v], uv_mode, chroma_cost) =
2558+ let ([u, v], uv_mode, chroma_cost, palette_uv) =
25502559 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
25512560 cost += chroma_cost;
25522561 (
@@ -2558,6 +2567,7 @@ fn code_square(
25582567 uv_mode,
25592568 tx_depth,
25602569 palette,
2570+ palette_uv,
25612571 ..BlockCoeffs::default()
25622572 },
25632573 cost,
@@ -2647,7 +2657,7 @@ fn search_chroma(
26472657 search: &Search,
26482658 luma_mode: u8,
26492659 fctx: &crate::decode::FrameCtx,
2650-) -> ([Vec<Coeff>; 2], u8, f64) {
2660+) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
26512661 let at = At {
26522662 x: x / 2,
26532663 y: y / 2,
@@ -2695,7 +2705,79 @@ fn search_chroma(
26952705 best = Some((cost, mode, u, v));
26962706 }
26972707 }
2698- 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+ }
26992781 if census_on() {
27002782 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
27012783 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -2707,6 +2789,7 @@ fn search_chroma(
27072789 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
27082790 mode,
27092791 cost,
2792+ palette_uv,
27102793 )
27112794 }
27122795
@@ -2955,6 +3038,7 @@ fn code_square_inter(
29553038 skip: skip_new,
29563039 eight: None,
29573040 palette: None,
3041+ palette_uv: None,
29583042 tx_depth,
29593043 inter: Some(InterInfo {
29603044 ref1: None,
@@ -2992,6 +3076,7 @@ fn code_square_inter(
29923076 skip,
29933077 eight: None,
29943078 palette: None,
3079+ palette_uv: None,
29953080 tx_depth,
29963081 inter: Some(InterInfo {
29973082 ref1: None,
@@ -5299,6 +5384,7 @@ fn search_inter_block(
52995384 inter: best.inter,
53005385 eight: None,
53015386 palette: None,
5387+ palette_uv: None,
53025388 tx_depth: 0,
53035389 },
53045390 best.cost,
@@ -6693,11 +6779,18 @@ mod tests {
66936779 picture.y[y * width + x] = INK[cell * 2 + bar];
66946780 }
66956781 }
6782+ // Four chroma colours, not two: a two-colour chroma block only ever
6783+ // codes a `PaletteSizeUV` of 2, which leaves
6784+ // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
6785+ // deltas and the neighbour cache flags, exercised only when
6786+ // neighbouring blocks share colours) unproven by the ffmpeg oracle.
6787+ const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
6788+ const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
66966789 for y in 0..height / 2 {
66976790 for x in 0..width / 2 {
6698- let cell = (x / 12 + y / 12) % 2;
6699- picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 };
6700- picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 };
6791+ let cell = (x / 12 + 2 * (y / 12)) % 4;
6792+ picture.u[y * (width / 2) + x] = CHROMA_U[cell];
6793+ picture.v[y * (width / 2) + x] = CHROMA_V[cell];
67016794 }
67026795 }
67036796 picture
@@ -6723,6 +6816,23 @@ mod tests {
67236816 let hits = crate::tile::take_palette_hits();
67246817 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
67256818 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
6819+ // The chroma half is a claim about the plane-1 syntax only if some
6820+ // block really took a chroma palette (`gate-blind-to-feature`): every
6821+ // exactness assert below passes on a stream that codes
6822+ // `palette_uv_mode == 0` everywhere.
6823+ let uv_hits = crate::tile::take_palette_uv_hits();
6824+ assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
6825+ let uv_cached = crate::tile::take_palette_uv_cache_hits();
6826+ eprintln!(
6827+ "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
6828+ uv_hits[0],
6829+ &uv_hits[2..]
6830+ );
6831+ assert!(
6832+ uv_cached > 0,
6833+ "no chroma base colour came out of the neighbour cache -- \
6834+ `write_palette_colors_uv`'s cache half is unproven by the oracle below"
6835+ );
67266836 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
67276837 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
67286838 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
@@ -6759,12 +6869,19 @@ mod tests {
67596869 })
67606870 .collect();
67616871 let _ = crate::tile::take_palette_hits();
6872+ let _ = crate::tile::take_palette_uv_hits();
67626873 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
67636874 let gop_hits = crate::tile::take_palette_hits();
6875+ let gop_uv_hits = crate::tile::take_palette_uv_hits();
67646876 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
67656877 eprintln!(
6766- "GOP: {} frames with screen tools after the key frame, {} palette blocks",
6767- inter_screen, gop_hits[0]
6878+ "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
6879+ {} chroma palette blocks",
6880+ inter_screen, gop_hits[0], gop_uv_hits[0]
6881+ );
6882+ assert!(
6883+ gop_uv_hits[0] > 0,
6884+ "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
67686885 );
67696886 assert!(
67706887 inter_screen > 0,
@@ -6826,6 +6943,7 @@ mod tests {
68266943 skip: false,
68276944 eight: None,
68286945 palette: None,
6946+ palette_uv: None,
68296947 tx_depth: 0,
68306948 inter: Some(InterInfo {
68316949 ref1: None,
@@ -9655,6 +9773,16 @@ mod tests {
96559773 .collect::<Vec<_>>()
96569774 .join(" ")
96579775 );
9776+ let palette_uv = crate::tile::take_palette_uv_hits();
9777+ eprintln!(
9778+ "{name}: chroma palette blocks {} sizes {}",
9779+ palette_uv[0],
9780+ (2..=8)
9781+ .filter(|&n| palette_uv[n] > 0)
9782+ .map(|n| format!("{n}={}", palette_uv[n]))
9783+ .collect::<Vec<_>>()
9784+ .join(" ")
9785+ );
96589786 let uv = take_uv_mode_hits();
96599787 let uv_total: usize = uv.iter().sum();
96609788 eprintln!(
crates/ec-av1/src/tile.rsmodified+280 -2
@@ -1166,6 +1166,11 @@ pub struct BlockCoeffs {
11661166 /// `tx_depth` to zero (the whole block is one transform over the
11671167 /// palette's own prediction).
11681168 pub palette: Option<PaletteY>,
1169+ /// The chroma palette this block's two chroma planes are predicted with
1170+ /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a
1171+ /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry
1172+ /// one; it is independent of [`Self::palette`] (either, both or neither).
1173+ pub palette_uv: Option<PaletteUv>,
11691174 /// How many times this block's luma transform is halved under
11701175 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
11711176 /// block). Read only by the writers a `tx_select` frame calls; a
@@ -1189,6 +1194,27 @@ pub struct PaletteY {
11891194 pub map: Vec<u8>,
11901195 }
11911196
1197+/// As [`PaletteY`], for a block's chroma palette -- one colour-index map
1198+/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes
1199+/// are co-located after 4:2:0 subsampling) plus each plane's own base
1200+/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of
1201+/// the stream.
1202+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1203+pub struct PaletteUv {
1204+ /// How many base colours, 2..=8 (spec `PaletteSizeUV`).
1205+ pub size: u8,
1206+ /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv`
1207+ /// merges the cached and transmitted lists as two ascending runs, and its
1208+ /// delta form only ever steps upwards.
1209+ pub u_colors: [u16; 8],
1210+ /// V's base colours, in the same cluster order as [`Self::u_colors`] --
1211+ /// the shared map indexes both, and V's own coding needs no ordering.
1212+ pub v_colors: [u16; 8],
1213+ /// Which colour each chroma pixel takes, row-major over the subsampled
1214+ /// block's own `(side / 2).max(4)` side.
1215+ pub map: Vec<u8>,
1216+}
1217+
11921218 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
11931219 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
11941220 /// [`write_inter_mode`] with the decoder's own contexts.
@@ -1455,6 +1481,15 @@ struct Neighbours {
14551481 pending_palette: Option<(u8, [u16; 8])>,
14561482 /// The colours beside [`Self::above_palette_size`].
14571483 above_palette_colors: Vec<[u16; 8]>,
1484+ /// The chroma (U-channel) halves of the three bands above --
1485+ /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the
1486+ /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`.
1487+ above_palette_uv_size: Vec<u8>,
1488+ left_palette_uv_size: Vec<u8>,
1489+ above_palette_uv_colors: Vec<[u16; 8]>,
1490+ left_palette_uv_colors: Vec<[u16; 8]>,
1491+ /// [`Self::pending_palette`] for the chroma palette.
1492+ pending_palette_uv: Option<(u8, [u16; 8])>,
14581493 /// The same, down the left edge.
14591494 left_palette_colors: Vec<[u16; 8]>,
14601495 /// Whether the neighbour was coded inter, for the `is_inter` context.
@@ -1546,6 +1581,11 @@ impl Neighbours {
15461581 left_palette_size: vec![0; rows * (SUB / MI)],
15471582 pending_palette: None,
15481583 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
1584+ above_palette_uv_size: vec![0; cols * (SUB / MI)],
1585+ left_palette_uv_size: vec![0; rows * (SUB / MI)],
1586+ above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)],
1587+ left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)],
1588+ pending_palette_uv: None,
15491589 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
15501590 mi_cols,
15511591 mi_rows,
@@ -1584,6 +1624,8 @@ impl Neighbours {
15841624 self.left_tx.iter_mut().for_each(|t| *t = 0);
15851625 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
15861626 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
1627+ self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
1628+ self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
15871629 }
15881630
15891631 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
@@ -1641,6 +1683,80 @@ impl Neighbours {
16411683 (ctx, cache)
16421684 }
16431685
1686+ /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel
1687+ /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's
1688+ /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no
1689+ /// neighbour lookup at all (it is this block's own just-decided Y palette
1690+ /// use), so only the cache is wanted here.
1691+ fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec<u16> {
1692+ let above_ok = r % 16 != 0;
1693+ let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
1694+ (
1695+ usize::from(self.above_palette_uv_size[c]),
1696+ self.above_palette_uv_colors[c],
1697+ )
1698+ } else {
1699+ (0, [0u16; 8])
1700+ };
1701+ let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 {
1702+ (
1703+ usize::from(self.left_palette_uv_size[r]),
1704+ self.left_palette_uv_colors[r],
1705+ )
1706+ } else {
1707+ (0, [0u16; 8])
1708+ };
1709+ let mut cache = Vec::with_capacity(16);
1710+ let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1711+ if cache.last() != Some(&v) {
1712+ cache.push(v);
1713+ }
1714+ };
1715+ let (mut ai, mut li) = (0usize, 0usize);
1716+ while ai < above_n && li < left_n {
1717+ let (va, vl) = (above_colors[ai], left_colors[li]);
1718+ if vl < va {
1719+ push_dedup(&mut cache, vl);
1720+ li += 1;
1721+ } else {
1722+ push_dedup(&mut cache, va);
1723+ ai += 1;
1724+ if vl == va {
1725+ li += 1;
1726+ }
1727+ }
1728+ }
1729+ while ai < above_n {
1730+ push_dedup(&mut cache, above_colors[ai]);
1731+ ai += 1;
1732+ }
1733+ while li < left_n {
1734+ push_dedup(&mut cache, left_colors[li]);
1735+ li += 1;
1736+ }
1737+ cache
1738+ }
1739+
1740+ /// [`Self::record_palette_y`] for the chroma bands (decode.rs
1741+ /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
1742+ /// way, and the span is in LUMA pixels for both planes' bands alike.
1743+ fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
1744+ for cell in 0..(side / MI).max(1) {
1745+ if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
1746+ *e = size;
1747+ if size > 0 {
1748+ self.above_palette_uv_colors[c + cell] = colors;
1749+ }
1750+ }
1751+ if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
1752+ *e = size;
1753+ if size > 0 {
1754+ self.left_palette_uv_colors[r + cell] = colors;
1755+ }
1756+ }
1757+ }
1758+ }
1759+
16441760 /// What a just-written block leaves in the palette bands (decode.rs
16451761 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
16461762 /// spans, `0` for a block that took no palette.
@@ -1809,6 +1925,8 @@ impl Neighbours {
18091925 if screen_armed() {
18101926 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
18111927 self.record_palette_y(at_mi, side, size, colors);
1928+ let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
1929+ self.record_palette_uv(at_mi, side, uv_size, uv_colors);
18121930 }
18131931 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
18141932 let side_mi = side / MI;
@@ -2581,6 +2699,72 @@ fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]
25812699 }
25822700 }
25832701
2702+/// `write_palette_colors_uv` (bitstream.c:1236), the write side of
2703+/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is
2704+/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two
2705+/// documented differences -- the shrinking range starts at `256 - first`
2706+/// (not `255 - first`) and each delta is written unbiased (no `-1`).
2707+///
2708+/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n`
2709+/// 8-bit literals) rather than its first-value-plus-signed-deltas form.
2710+/// Ceiling: about `n` bits per chroma-palette block more than the delta form
2711+/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer
2712+/// below sees, so it only ever makes the encoder take FEWER chroma palettes
2713+/// than it should -- never a wrong stream. Upgrade path: price both forms
2714+/// here and write the cheaper one under its own leading bit.
2715+fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) {
2716+ let n = u_colors.len();
2717+ let mut cached: Vec<u16> = Vec::with_capacity(n);
2718+ for &c in cache {
2719+ if cached.len() >= n {
2720+ break;
2721+ }
2722+ let take = u_colors.contains(&c);
2723+ enc.literal(u32::from(take), 1);
2724+ if take {
2725+ PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2726+ cached.push(c);
2727+ }
2728+ }
2729+ let transmitted: Vec<u16> = u_colors
2730+ .iter()
2731+ .copied()
2732+ .filter(|c| !cached.contains(c))
2733+ .collect();
2734+ if !transmitted.is_empty() {
2735+ enc.literal(u32::from(transmitted[0]), 8);
2736+ if transmitted.len() > 1 {
2737+ let fits = |extra: u32| -> bool {
2738+ let mut bits = 5 + extra;
2739+ let mut range = 256i32 - i32::from(transmitted[0]);
2740+ for w in transmitted.windows(2) {
2741+ let delta = i32::from(w[1]) - i32::from(w[0]);
2742+ if delta >= (1i32 << bits) {
2743+ return false;
2744+ }
2745+ range -= delta;
2746+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2747+ }
2748+ true
2749+ };
2750+ let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
2751+ enc.literal(extra, 2);
2752+ let mut bits = 5 + extra;
2753+ let mut range = 256i32 - i32::from(transmitted[0]);
2754+ for w in transmitted.windows(2) {
2755+ let delta = i32::from(w[1]) - i32::from(w[0]);
2756+ enc.literal(delta as u32, bits);
2757+ range -= delta;
2758+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2759+ }
2760+ }
2761+ }
2762+ enc.literal(0, 1);
2763+ for &v in v_colors {
2764+ enc.literal(u32::from(v), 8);
2765+ }
2766+}
2767+
25842768 /// `write_palette_color_map` (bitstream.c), the write side of
25852769 /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
25862770 /// each symbol written as the position its colour takes in the neighbour
@@ -2630,6 +2814,25 @@ pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
26302814 enc.bits()
26312815 }
26322816
2817+/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the
2818+/// size symbol, both colour lists and the shared colour-index map, priced
2819+/// through the very writers above (empty cache, which only over-prices).
2820+pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 {
2821+ let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2822+ return f64::INFINITY;
2823+ };
2824+ let n = usize::from(pal.size);
2825+ let mut enc = SymbolEncoder::pricer();
2826+ let mut mode_cdf = cdf::PALETTE_UV_MODE[0];
2827+ enc.symbol(1, &mut mode_cdf);
2828+ let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx];
2829+ enc.symbol(n - 2, &mut size_cdf);
2830+ write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]);
2831+ let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2];
2832+ write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n);
2833+ enc.bits()
2834+}
2835+
26332836 /// Writes everything a key frame's block carries before its coefficients: the
26342837 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
26352838 /// the angle a directional mode is steered by, and its chroma mode. Hands back
@@ -2680,7 +2883,17 @@ fn write_intra_mode(
26802883 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
26812884 // codes none -- exactly the ctx-0 read the decoder does under the same
26822885 // condition.
2683- write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side);
2886+ write_palette_syntax(
2887+ enc,
2888+ cdfs,
2889+ neighbours,
2890+ block.palette.as_ref(),
2891+ block.palette_uv.as_ref(),
2892+ mode,
2893+ uv_mode,
2894+ mi,
2895+ side,
2896+ );
26842897 mode
26852898 }
26862899
@@ -2703,6 +2916,7 @@ fn write_palette_syntax(
27032916 cdfs: &mut Cdfs,
27042917 neighbours: &mut Neighbours,
27052918 palette: Option<&PaletteY>,
2919+ palette_uv: Option<&PaletteUv>,
27062920 mode: usize,
27072921 uv_mode: usize,
27082922 mi: (usize, usize),
@@ -2712,8 +2926,10 @@ fn write_palette_syntax(
27122926 return;
27132927 }
27142928 let palette = palette.filter(|_| mode == DC_PRED);
2929+ let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
27152930 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
27162931 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2932+ let uv_cache = neighbours.palette_uv_cache(mi);
27172933 if mode == DC_PRED {
27182934 enc.symbol(
27192935 usize::from(palette.is_some()),
@@ -2726,15 +2942,45 @@ fn write_palette_syntax(
27262942 write_palette_colors_y(enc, &pal.colors[..n], &cache);
27272943 }
27282944 if uv_mode == DC_PRED {
2729- enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]);
2945+ enc.symbol(
2946+ usize::from(palette_uv.is_some()),
2947+ &mut cdfs.palette_uv_mode[usize::from(palette.is_some())],
2948+ );
2949+ }
2950+ if let Some(pal) = palette_uv {
2951+ let n = usize::from(pal.size);
2952+ enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]);
2953+ write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache);
27302954 }
2955+ // Both colour-index maps come after BOTH colour lists, in plane order
2956+ // (`av1_visit_palette` runs from the caller, past `filter_intra`).
27312957 if let Some(pal) = palette {
27322958 let n = usize::from(pal.size);
27332959 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
27342960 note_palette(n);
27352961 }
2962+ if let Some(pal) = palette_uv {
2963+ let n = usize::from(pal.size);
2964+ write_color_index_map(
2965+ enc,
2966+ &mut cdfs.palette_uv_color_index[n - 2],
2967+ &pal.map,
2968+ palette_uv_side(side),
2969+ n,
2970+ );
2971+ note_palette_uv(n);
2972+ }
27362973 }
27372974 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
2975+ neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors));
2976+}
2977+
2978+/// The side of a chroma palette's shared colour-index map for a square luma
2979+/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at
2980+/// the 4-px transform, NOT a plain halving (decode.rs reads the map at
2981+/// exactly this size).
2982+pub(crate) fn palette_uv_side(side: usize) -> usize {
2983+ (side / 2).max(4)
27382984 }
27392985
27402986 /// How many blocks took a palette, and of what size -- the fire count a gate
@@ -2749,6 +2995,35 @@ fn note_palette(n: usize) {
27492995 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
27502996 }
27512997
2998+/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can
2999+/// print the share of each plane's palette separately.
3000+static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] =
3001+ [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
3002+
3003+fn note_palette_uv(n: usize) {
3004+ PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3005+ PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3006+}
3007+
3008+/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than
3009+/// the stream -- the half of `write_palette_colors_uv` a test cannot see from
3010+/// the block counts alone, and the one that desyncs the tile if this writer's
3011+/// cache ever disagrees with the decoder's (`gate-blind-to-feature`).
3012+static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize =
3013+ std::sync::atomic::AtomicUsize::new(0);
3014+
3015+/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it.
3016+#[cfg(test)]
3017+pub(crate) fn take_palette_uv_cache_hits() -> usize {
3018+ PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
3019+}
3020+
3021+/// [`take_palette_hits`] for the chroma palette.
3022+#[cfg(test)]
3023+pub(crate) fn take_palette_uv_hits() -> [usize; 9] {
3024+ std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
3025+}
3026+
27523027 /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
27533028 /// its own encode.
27543029 #[cfg(test)]
@@ -4672,6 +4947,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
46724947 &mut cdfs,
46734948 &mut neighbours,
46744949 block.palette.as_ref(),
4950+ block.palette_uv.as_ref(),
46754951 mode,
46764952 uv_mode,
46774953 (mi_row, mi_col),
@@ -4895,6 +5171,7 @@ fn write_inter_frame_leaf(
48955171 cdfs,
48965172 neighbours,
48975173 block.palette.as_ref(),
5174+ block.palette_uv.as_ref(),
48985175 mode,
48995176 uv_mode,
49005177 (mi_row, mi_col),
@@ -5124,6 +5401,7 @@ fn write_inter_frame_leaf8(
51245401 cdfs,
51255402 neighbours,
51265403 block.palette.as_ref(),
5404+ block.palette_uv.as_ref(),
51275405 mode,
51285406 uv_mode,
51295407 leaf_mi,