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(
2338 /// The largest distinct-colour count a block may hold and still be offered a2338 /// The largest distinct-colour count a block may hold and still be offered a
2339 /// palette candidate at all: past it the k-means quantisation costs more2339 /// palette candidate at all: past it the k-means quantisation costs more
2340 /// error than the map saves rate, and every trial is wasted wall.2340 /// 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).
2341 /// `EC_AV1_PAL_MAXCOLORS`.2350 /// `EC_AV1_PAL_MAXCOLORS`.
2342 fn palette_max_colors() -> usize {2351 fn palette_max_colors() -> usize {
2343 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();2352 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
@@ -2345,7 +2354,7 @@ fn palette_max_colors() -> usize {
2345 std::env::var("EC_AV1_PAL_MAXCOLORS")2354 std::env::var("EC_AV1_PAL_MAXCOLORS")
2346 .ok()2355 .ok()
2347 .and_then(|v| v.parse().ok())2356 .and_then(|v| v.parse().ok())
2348- .unwrap_or(32)2357+ .unwrap_or(128)
2349 })2358 })
2350 }2359 }
2351 2360
@@ -2546,7 +2555,7 @@ fn code_square(
2546 2555
2547 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both2556 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
2548 // planes; what it costs still counts towards the partition decision.2557 // 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) =
2550 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);2559 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
2551 cost += chroma_cost;2560 cost += chroma_cost;
2552 (2561 (
@@ -2558,6 +2567,7 @@ fn code_square(
2558 uv_mode,2567 uv_mode,
2559 tx_depth,2568 tx_depth,
2560 palette,2569 palette,
2570+ palette_uv,
2561 ..BlockCoeffs::default()2571 ..BlockCoeffs::default()
2562 },2572 },
2563 cost,2573 cost,
@@ -2647,7 +2657,7 @@ fn search_chroma(
2647 search: &Search,2657 search: &Search,
2648 luma_mode: u8,2658 luma_mode: u8,
2649 fctx: &crate::decode::FrameCtx,2659 fctx: &crate::decode::FrameCtx,
2650-) -> ([Vec<Coeff>; 2], u8, f64) {2660+) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
2651 let at = At {2661 let at = At {
2652 x: x / 2,2662 x: x / 2,
2653 y: y / 2,2663 y: y / 2,
@@ -2695,7 +2705,79 @@ fn search_chroma(
2695 best = Some((cost, mode, u, v));2705 best = Some((cost, mode, u, v));
2696 }2706 }
2697 }2707 }
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+ }
2699 if census_on() {2781 if census_on() {
2700 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]2782 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2701 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);2783 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -2707,6 +2789,7 @@ fn search_chroma(
2707 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],2789 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
2708 mode,2790 mode,
2709 cost,2791 cost,
2792+ palette_uv,
2710 )2793 )
2711 }2794 }
2712 2795
@@ -2955,6 +3038,7 @@ fn code_square_inter(
2955 skip: skip_new,3038 skip: skip_new,
2956 eight: None,3039 eight: None,
2957 palette: None,3040 palette: None,
3041+ palette_uv: None,
2958 tx_depth,3042 tx_depth,
2959 inter: Some(InterInfo {3043 inter: Some(InterInfo {
2960 ref1: None,3044 ref1: None,
@@ -2992,6 +3076,7 @@ fn code_square_inter(
2992 skip,3076 skip,
2993 eight: None,3077 eight: None,
2994 palette: None,3078 palette: None,
3079+ palette_uv: None,
2995 tx_depth,3080 tx_depth,
2996 inter: Some(InterInfo {3081 inter: Some(InterInfo {
2997 ref1: None,3082 ref1: None,
@@ -5299,6 +5384,7 @@ fn search_inter_block(
5299 inter: best.inter,5384 inter: best.inter,
5300 eight: None,5385 eight: None,
5301 palette: None,5386 palette: None,
5387+ palette_uv: None,
5302 tx_depth: 0,5388 tx_depth: 0,
5303 },5389 },
5304 best.cost,5390 best.cost,
@@ -6693,11 +6779,18 @@ mod tests {
6693 picture.y[y * width + x] = INK[cell * 2 + bar];6779 picture.y[y * width + x] = INK[cell * 2 + bar];
6694 }6780 }
6695 }6781 }
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];
6696 for y in 0..height / 2 {6789 for y in 0..height / 2 {
6697 for x in 0..width / 2 {6790 for x in 0..width / 2 {
6698- let cell = (x / 12 + y / 12) % 2;6791+ let cell = (x / 12 + 2 * (y / 12)) % 4;
6699- picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 };6792+ picture.u[y * (width / 2) + x] = CHROMA_U[cell];
6700- picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 };6793+ picture.v[y * (width / 2) + x] = CHROMA_V[cell];
6701 }6794 }
6702 }6795 }
6703 picture6796 picture
@@ -6723,6 +6816,23 @@ mod tests {
6723 let hits = crate::tile::take_palette_hits();6816 let hits = crate::tile::take_palette_hits();
6724 assert!(hits[0] > 0, "no block took a palette: {hits:?}");6817 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
6725 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);6818 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+ );
6726 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();6836 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
6727 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");6837 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
6728 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");6838 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
@@ -6759,12 +6869,19 @@ mod tests {
6759 })6869 })
6760 .collect();6870 .collect();
6761 let _ = crate::tile::take_palette_hits();6871 let _ = crate::tile::take_palette_hits();
6872+ let _ = crate::tile::take_palette_uv_hits();
6762 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();6873 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
6763 let gop_hits = crate::tile::take_palette_hits();6874 let gop_hits = crate::tile::take_palette_hits();
6875+ let gop_uv_hits = crate::tile::take_palette_uv_hits();
6764 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();6876 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
6765 eprintln!(6877 eprintln!(
6766- "GOP: {} frames with screen tools after the key frame, {} palette blocks",6878+ "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
6767- inter_screen, gop_hits[0]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:?}"
6768 );6885 );
6769 assert!(6886 assert!(
6770 inter_screen > 0,6887 inter_screen > 0,
@@ -6826,6 +6943,7 @@ mod tests {
6826 skip: false,6943 skip: false,
6827 eight: None,6944 eight: None,
6828 palette: None,6945 palette: None,
6946+ palette_uv: None,
6829 tx_depth: 0,6947 tx_depth: 0,
6830 inter: Some(InterInfo {6948 inter: Some(InterInfo {
6831 ref1: None,6949 ref1: None,
@@ -9655,6 +9773,16 @@ mod tests {
9655 .collect::<Vec<_>>()9773 .collect::<Vec<_>>()
9656 .join(" ")9774 .join(" ")
9657 );9775 );
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+ );
9658 let uv = take_uv_mode_hits();9786 let uv = take_uv_mode_hits();
9659 let uv_total: usize = uv.iter().sum();9787 let uv_total: usize = uv.iter().sum();
9660 eprintln!(9788 eprintln!(
crates/ec-av1/src/tile.rsmodified+280 -2
@@ -1166,6 +1166,11 @@ pub struct BlockCoeffs {
1166 /// `tx_depth` to zero (the whole block is one transform over the1166 /// `tx_depth` to zero (the whole block is one transform over the
1167 /// palette's own prediction).1167 /// palette's own prediction).
1168 pub palette: Option<PaletteY>,1168 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>,
1169 /// How many times this block's luma transform is halved under1174 /// How many times this block's luma transform is halved under
1170 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole1175 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
1171 /// block). Read only by the writers a `tx_select` frame calls; a1176 /// block). Read only by the writers a `tx_select` frame calls; a
@@ -1189,6 +1194,27 @@ pub struct PaletteY {
1189 pub map: Vec<u8>,1194 pub map: Vec<u8>,
1190 }1195 }
1191 1196
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+
1192 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole1218 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
1193 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by1219 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
1194 /// [`write_inter_mode`] with the decoder's own contexts.1220 /// [`write_inter_mode`] with the decoder's own contexts.
@@ -1455,6 +1481,15 @@ struct Neighbours {
1455 pending_palette: Option<(u8, [u16; 8])>,1481 pending_palette: Option<(u8, [u16; 8])>,
1456 /// The colours beside [`Self::above_palette_size`].1482 /// The colours beside [`Self::above_palette_size`].
1457 above_palette_colors: Vec<[u16; 8]>,1483 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])>,
1458 /// The same, down the left edge.1493 /// The same, down the left edge.
1459 left_palette_colors: Vec<[u16; 8]>,1494 left_palette_colors: Vec<[u16; 8]>,
1460 /// Whether the neighbour was coded inter, for the `is_inter` context.1495 /// Whether the neighbour was coded inter, for the `is_inter` context.
@@ -1546,6 +1581,11 @@ impl Neighbours {
1546 left_palette_size: vec![0; rows * (SUB / MI)],1581 left_palette_size: vec![0; rows * (SUB / MI)],
1547 pending_palette: None,1582 pending_palette: None,
1548 above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],1583 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,
1549 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],1589 left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
1550 mi_cols,1590 mi_cols,
1551 mi_rows,1591 mi_rows,
@@ -1584,6 +1624,8 @@ impl Neighbours {
1584 self.left_tx.iter_mut().for_each(|t| *t = 0);1624 self.left_tx.iter_mut().for_each(|t| *t = 0);
1585 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);1625 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
1586 self.left_palette_size.iter_mut().for_each(|s| *s = 0);1626 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]);
1587 }1629 }
1588 1630
1589 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from1631 /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
@@ -1641,6 +1683,80 @@ impl Neighbours {
1641 (ctx, cache)1683 (ctx, cache)
1642 }1684 }
1643 1685
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+
1644 /// What a just-written block leaves in the palette bands (decode.rs1760 /// What a just-written block leaves in the palette bands (decode.rs
1645 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it1761 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
1646 /// spans, `0` for a block that took no palette.1762 /// spans, `0` for a block that took no palette.
@@ -1809,6 +1925,8 @@ impl Neighbours {
1809 if screen_armed() {1925 if screen_armed() {
1810 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));1926 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
1811 self.record_palette_y(at_mi, side, size, colors);1927 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);
1812 }1930 }
1813 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));1931 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1814 let side_mi = side / MI;1932 let side_mi = side / MI;
@@ -2581,6 +2699,72 @@ fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]
2581 }2699 }
2582 }2700 }
2583 2701
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+
2584 /// `write_palette_color_map` (bitstream.c), the write side of2768 /// `write_palette_color_map` (bitstream.c), the write side of
2585 /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,2769 /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
2586 /// each symbol written as the position its colour takes in the neighbour2770 /// 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 {
2630 enc.bits()2814 enc.bits()
2631 }2815 }
2632 2816
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+
2633 /// Writes everything a key frame's block carries before its coefficients: the2836 /// Writes everything a key frame's block carries before its coefficients: the
2634 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,2837 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2635 /// the angle a directional mode is steered by, and its chroma mode. Hands back2838 /// the angle a directional mode is steered by, and its chroma mode. Hands back
@@ -2680,7 +2883,17 @@ fn write_intra_mode(
2680 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer2883 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
2681 // codes none -- exactly the ctx-0 read the decoder does under the same2884 // codes none -- exactly the ctx-0 read the decoder does under the same
2682 // condition.2885 // 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+ );
2684 mode2897 mode
2685 }2898 }
2686 2899
@@ -2703,6 +2916,7 @@ fn write_palette_syntax(
2703 cdfs: &mut Cdfs,2916 cdfs: &mut Cdfs,
2704 neighbours: &mut Neighbours,2917 neighbours: &mut Neighbours,
2705 palette: Option<&PaletteY>,2918 palette: Option<&PaletteY>,
2919+ palette_uv: Option<&PaletteUv>,
2706 mode: usize,2920 mode: usize,
2707 uv_mode: usize,2921 uv_mode: usize,
2708 mi: (usize, usize),2922 mi: (usize, usize),
@@ -2712,8 +2926,10 @@ fn write_palette_syntax(
2712 return;2926 return;
2713 }2927 }
2714 let palette = palette.filter(|_| mode == DC_PRED);2928 let palette = palette.filter(|_| mode == DC_PRED);
2929+ let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED);
2715 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {2930 if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
2716 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);2931 let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2932+ let uv_cache = neighbours.palette_uv_cache(mi);
2717 if mode == DC_PRED {2933 if mode == DC_PRED {
2718 enc.symbol(2934 enc.symbol(
2719 usize::from(palette.is_some()),2935 usize::from(palette.is_some()),
@@ -2726,15 +2942,45 @@ fn write_palette_syntax(
2726 write_palette_colors_y(enc, &pal.colors[..n], &cache);2942 write_palette_colors_y(enc, &pal.colors[..n], &cache);
2727 }2943 }
2728 if uv_mode == DC_PRED {2944 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);
2730 }2954 }
2955+ // Both colour-index maps come after BOTH colour lists, in plane order
2956+ // (`av1_visit_palette` runs from the caller, past `filter_intra`).
2731 if let Some(pal) = palette {2957 if let Some(pal) = palette {
2732 let n = usize::from(pal.size);2958 let n = usize::from(pal.size);
2733 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);2959 write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
2734 note_palette(n);2960 note_palette(n);
2735 }2961 }
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+ }
2736 }2973 }
2737 neighbours.pending_palette = palette.map(|p| (p.size, p.colors));2974 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)
2738 }2984 }
2739 2985
2740 /// How many blocks took a palette, and of what size -- the fire count a gate2986 /// How many blocks took a palette, and of what size -- the fire count a gate
@@ -2749,6 +2995,35 @@ fn note_palette(n: usize) {
2749 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);2995 PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2750 }2996 }
2751 2997
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+
2752 /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to3027 /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
2753 /// its own encode.3028 /// its own encode.
2754 #[cfg(test)]3029 #[cfg(test)]
@@ -4672,6 +4947,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4672 &mut cdfs,4947 &mut cdfs,
4673 &mut neighbours,4948 &mut neighbours,
4674 block.palette.as_ref(),4949 block.palette.as_ref(),
4950+ block.palette_uv.as_ref(),
4675 mode,4951 mode,
4676 uv_mode,4952 uv_mode,
4677 (mi_row, mi_col),4953 (mi_row, mi_col),
@@ -4895,6 +5171,7 @@ fn write_inter_frame_leaf(
4895 cdfs,5171 cdfs,
4896 neighbours,5172 neighbours,
4897 block.palette.as_ref(),5173 block.palette.as_ref(),
5174+ block.palette_uv.as_ref(),
4898 mode,5175 mode,
4899 uv_mode,5176 uv_mode,
4900 (mi_row, mi_col),5177 (mi_row, mi_col),
@@ -5124,6 +5401,7 @@ fn write_inter_frame_leaf8(
5124 cdfs,5401 cdfs,
5125 neighbours,5402 neighbours,
5126 block.palette.as_ref(),5403 block.palette.as_ref(),
5404+ block.palette_uv.as_ref(),
5127 mode,5405 mode,
5128 uv_mode,5406 uv_mode,
5129 leaf_mi,5407 leaf_mi,