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(
2555 2555
2556 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both2556 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
2557 // planes; what it costs still counts towards the partition decision.2557 // 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) =
2559 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);2559 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
2560 cost += chroma_cost;2560 cost += chroma_cost;
2561 (2561 (
@@ -2567,6 +2567,7 @@ fn code_square(
2567 uv_mode,2567 uv_mode,
2568 tx_depth,2568 tx_depth,
2569 palette,2569 palette,
2570+ palette_uv,
2570 ..BlockCoeffs::default()2571 ..BlockCoeffs::default()
2571 },2572 },
2572 cost,2573 cost,
@@ -2656,7 +2657,7 @@ fn search_chroma(
2656 search: &Search,2657 search: &Search,
2657 luma_mode: u8,2658 luma_mode: u8,
2658 fctx: &crate::decode::FrameCtx,2659 fctx: &crate::decode::FrameCtx,
2659-) -> ([Vec<Coeff>; 2], u8, f64) {2660+) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
2660 let at = At {2661 let at = At {
2661 x: x / 2,2662 x: x / 2,
2662 y: y / 2,2663 y: y / 2,
@@ -2704,7 +2705,79 @@ fn search_chroma(
2704 best = Some((cost, mode, u, v));2705 best = Some((cost, mode, u, v));
2705 }2706 }
2706 }2707 }
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+ }
2708 if census_on() {2781 if census_on() {
2709 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]2782 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2710 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);2783 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -2716,6 +2789,7 @@ fn search_chroma(
2716 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],2789 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
2717 mode,2790 mode,
2718 cost,2791 cost,
2792+ palette_uv,
2719 )2793 )
2720 }2794 }
2721 2795
@@ -2963,6 +3037,7 @@ fn code_square_inter(
2963 skip: skip_new,3037 skip: skip_new,
2964 eight: None,3038 eight: None,
2965 palette: None,3039 palette: None,
3040+ palette_uv: None,
2966 tx_depth,3041 tx_depth,
2967 inter: Some(InterInfo {3042 inter: Some(InterInfo {
2968 ref1: None,3043 ref1: None,
@@ -3000,6 +3075,7 @@ fn code_square_inter(
3000 skip,3075 skip,
3001 eight: None,3076 eight: None,
3002 palette: None,3077 palette: None,
3078+ palette_uv: None,
3003 tx_depth,3079 tx_depth,
3004 inter: Some(InterInfo {3080 inter: Some(InterInfo {
3005 ref1: None,3081 ref1: None,
@@ -5054,6 +5130,7 @@ fn search_inter_block(
5054 inter: best.inter,5130 inter: best.inter,
5055 eight: None,5131 eight: None,
5056 palette: None,5132 palette: None,
5133+ palette_uv: None,
5057 tx_depth: 0,5134 tx_depth: 0,
5058 },5135 },
5059 best.cost,5136 best.cost,
@@ -6397,11 +6474,18 @@ mod tests {
6397 picture.y[y * width + x] = INK[cell * 2 + bar];6474 picture.y[y * width + x] = INK[cell * 2 + bar];
6398 }6475 }
6399 }6476 }
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];
6400 for y in 0..height / 2 {6484 for y in 0..height / 2 {
6401 for x in 0..width / 2 {6485 for x in 0..width / 2 {
6402- let cell = (x / 12 + y / 12) % 2;6486+ let cell = (x / 12 + 2 * (y / 12)) % 4;
6403- picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 };6487+ picture.u[y * (width / 2) + x] = CHROMA_U[cell];
6404- picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 };6488+ picture.v[y * (width / 2) + x] = CHROMA_V[cell];
6405 }6489 }
6406 }6490 }
6407 picture6491 picture
@@ -6427,6 +6511,23 @@ mod tests {
6427 let hits = crate::tile::take_palette_hits();6511 let hits = crate::tile::take_palette_hits();
6428 assert!(hits[0] > 0, "no block took a palette: {hits:?}");6512 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
6429 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);6513 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+ );
6430 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();6531 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
6431 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");6532 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
6432 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");6533 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
@@ -6463,12 +6564,19 @@ mod tests {
6463 })6564 })
6464 .collect();6565 .collect();
6465 let _ = crate::tile::take_palette_hits();6566 let _ = crate::tile::take_palette_hits();
6567+ let _ = crate::tile::take_palette_uv_hits();
6466 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();6568 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
6467 let gop_hits = crate::tile::take_palette_hits();6569 let gop_hits = crate::tile::take_palette_hits();
6570+ let gop_uv_hits = crate::tile::take_palette_uv_hits();
6468 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();6571 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
6469 eprintln!(6572 eprintln!(
6470- "GOP: {} frames with screen tools after the key frame, {} palette blocks",6573+ "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
6471- inter_screen, gop_hits[0]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:?}"
6472 );6580 );
6473 assert!(6581 assert!(
6474 inter_screen > 0,6582 inter_screen > 0,
@@ -6530,6 +6638,7 @@ mod tests {
6530 skip: false,6638 skip: false,
6531 eight: None,6639 eight: None,
6532 palette: None,6640 palette: None,
6641+ palette_uv: None,
6533 tx_depth: 0,6642 tx_depth: 0,
6534 inter: Some(InterInfo {6643 inter: Some(InterInfo {
6535 ref1: None,6644 ref1: None,
@@ -9354,6 +9463,16 @@ mod tests {
9354 .collect::<Vec<_>>()9463 .collect::<Vec<_>>()
9355 .join(" ")9464 .join(" ")
9356 );9465 );
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+ );
9357 let uv = take_uv_mode_hits();9476 let uv = take_uv_mode_hits();
9358 let uv_total: usize = uv.iter().sum();9477 let uv_total: usize = uv.iter().sum();
9359 eprintln!(9478 eprintln!(
crates/ec-av1/src/tile.rsmodified+280 -2
@@ -1120,6 +1120,11 @@ pub struct BlockCoeffs {
1120 /// `tx_depth` to zero (the whole block is one transform over the1120 /// `tx_depth` to zero (the whole block is one transform over the
1121 /// palette's own prediction).1121 /// palette's own prediction).
1122 pub palette: Option<PaletteY>,1122 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>,
1123 /// How many times this block's luma transform is halved under1128 /// How many times this block's luma transform is halved under
1124 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole1129 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
1125 /// block). Read only by the writers a `tx_select` frame calls; a1130 /// block). Read only by the writers a `tx_select` frame calls; a
@@ -1143,6 +1148,27 @@ pub struct PaletteY {
1143 pub map: Vec<u8>,1148 pub map: Vec<u8>,
1144 }1149 }
1145 1150
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+
1146 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole1172 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
1147 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by1173 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
1148 /// [`write_inter_mode`] with the decoder's own contexts.1174 /// [`write_inter_mode`] with the decoder's own contexts.
@@ -1396,6 +1422,15 @@ struct Neighbours {
1396 pending_palette: Option<(u8, [u16; 8])>,1422 pending_palette: Option<(u8, [u16; 8])>,
1397 /// The colours beside [`Self::above_palette_size`].1423 /// The colours beside [`Self::above_palette_size`].
1398 above_palette_colors: Vec<[u16; 8]>,1424 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])>,
1399 /// The same, down the left edge.1434 /// The same, down the left edge.
1400 left_palette_colors: Vec<[u16; 8]>,1435 left_palette_colors: Vec<[u16; 8]>,
1401 /// Whether the neighbour was coded inter, for the `is_inter` context.1436 /// Whether the neighbour was coded inter, for the `is_inter` context.
@@ -1487,6 +1522,11 @@ impl Neighbours {
1487 left_palette_size: vec![0; rows * (SUB / MI)],1522 left_palette_size: vec![0; rows * (SUB / MI)],
1488 pending_palette: None,1523 pending_palette: None,
1489 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],1524 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,
1490 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],1530 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
1491 mi_cols,1531 mi_cols,
1492 mi_rows,1532 mi_rows,
@@ -1525,6 +1565,8 @@ impl Neighbours {
1525 self.left_tx.iter_mut().for_each(|t| *t = 0);1565 self.left_tx.iter_mut().for_each(|t| *t = 0);
1526 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);1566 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
1527 self.left_palette_size.iter_mut().for_each(|s| *s = 0);1567 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]);
1528 }1570 }
1529 1571
1530 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from1572 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
@@ -1582,6 +1624,80 @@ impl Neighbours {
1582 (ctx, cache)1624 (ctx, cache)
1583 }1625 }
1584 1626
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+
1585 /// What a just-written block leaves in the palette bands (decode.rs1701 /// What a just-written block leaves in the palette bands (decode.rs
1586 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it1702 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
1587 /// spans, `0` for a block that took no palette.1703 /// spans, `0` for a block that took no palette.
@@ -1750,6 +1866,8 @@ impl Neighbours {
1750 if screen_armed() {1866 if screen_armed() {
1751 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));1867 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
1752 self.record_palette_y(at_mi, side, size, colors);1868 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);
1753 }1871 }
1754 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));1872 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1755 let side_mi = side / MI;1873 let side_mi = side / MI;
@@ -2522,6 +2640,72 @@ fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]
2522 }2640 }
2523 }2641 }
2524 2642
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+
2525 /// `write_palette_color_map` (bitstream.c), the write side of2709 /// `write_palette_color_map` (bitstream.c), the write side of
2526 /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,2710 /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
2527 /// each symbol written as the position its colour takes in the neighbour2711 /// 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 {
2571 enc.bits()2755 enc.bits()
2572 }2756 }
2573 2757
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+
2574 /// Writes everything a key frame's block carries before its coefficients: the2777 /// Writes everything a key frame's block carries before its coefficients: the
2575 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,2778 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2576 /// the angle a directional mode is steered by, and its chroma mode. Hands back2779 /// the angle a directional mode is steered by, and its chroma mode. Hands back
@@ -2621,7 +2824,17 @@ fn write_intra_mode(
2621 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer2824 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
2622 // codes none -- exactly the ctx-0 read the decoder does under the same2825 // codes none -- exactly the ctx-0 read the decoder does under the same
2623 // condition.2826 // 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+ );
2625 mode2838 mode
2626 }2839 }
2627 2840
@@ -2644,6 +2857,7 @@ fn write_palette_syntax(
2644 cdfs: &mut Cdfs,2857 cdfs: &mut Cdfs,
2645 neighbours: &mut Neighbours,2858 neighbours: &mut Neighbours,
2646 palette: Option<&PaletteY>,2859 palette: Option<&PaletteY>,
2860+ palette_uv: Option<&PaletteUv>,
2647 mode: usize,2861 mode: usize,
2648 uv_mode: usize,2862 uv_mode: usize,
2649 mi: (usize, usize),2863 mi: (usize, usize),
@@ -2653,8 +2867,10 @@ fn write_palette_syntax(
2653 return;2867 return;
2654 }2868 }
2655 let palette = palette.filter(|_| mode == DC_PRED);2869 let palette = palette.filter(|_| mode == DC_PRED);
2870+ let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
2656 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {2871 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
2657 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);2872 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2873+ let uv_cache = neighbours.palette_uv_cache(mi);
2658 if mode == DC_PRED {2874 if mode == DC_PRED {
2659 enc.symbol(2875 enc.symbol(
2660 usize::from(palette.is_some()),2876 usize::from(palette.is_some()),
@@ -2667,15 +2883,45 @@ fn write_palette_syntax(
2667 write_palette_colors_y(enc, &pal.colors[..n], &cache);2883 write_palette_colors_y(enc, &pal.colors[..n], &cache);
2668 }2884 }
2669 if uv_mode == DC_PRED {2885 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);
2671 }2895 }
2896+ // Both colour-index maps come after BOTH colour lists, in plane order
2897+ // (`av1_visit_palette` runs from the caller, past `filter_intra`).
2672 if let Some(pal) = palette {2898 if let Some(pal) = palette {
2673 let n = usize::from(pal.size);2899 let n = usize::from(pal.size);
2674 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);2900 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
2675 note_palette(n);2901 note_palette(n);
2676 }2902 }
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+ }
2677 }2914 }
2678 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));2915 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)
2679 }2925 }
2680 2926
2681 /// How many blocks took a palette, and of what size -- the fire count a gate2927 /// How many blocks took a palette, and of what size -- the fire count a gate
@@ -2690,6 +2936,35 @@ fn note_palette(n: usize) {
2690 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);2936 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2691 }2937 }
2692 2938
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+
2693 /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to2968 /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
2694 /// its own encode.2969 /// its own encode.
2695 #[cfg(test)]2970 #[cfg(test)]
@@ -4613,6 +4888,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4613 &mut cdfs,4888 &mut cdfs,
4614 &mut neighbours,4889 &mut neighbours,
4615 block.palette.as_ref(),4890 block.palette.as_ref(),
4891+ block.palette_uv.as_ref(),
4616 mode,4892 mode,
4617 uv_mode,4893 uv_mode,
4618 (mi_row, mi_col),4894 (mi_row, mi_col),
@@ -4836,6 +5112,7 @@ fn write_inter_frame_leaf(
4836 cdfs,5112 cdfs,
4837 neighbours,5113 neighbours,
4838 block.palette.as_ref(),5114 block.palette.as_ref(),
5115+ block.palette_uv.as_ref(),
4839 mode,5116 mode,
4840 uv_mode,5117 uv_mode,
4841 (mi_row, mi_col),5118 (mi_row, mi_col),
@@ -5065,6 +5342,7 @@ fn write_inter_frame_leaf8(
5065 cdfs,5342 cdfs,
5066 neighbours,5343 neighbours,
5067 block.palette.as_ref(),5344 block.palette.as_ref(),
5345+ block.palette_uv.as_ref(),
5068 mode,5346 mode,
5069 uv_mode,5347 uv_mode,
5070 leaf_mi,5348 leaf_mi,