From ace59f52e1621f7627b3dd50fd4ea8eb4bc546cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 12:11:35 +0300 Subject: [PATCH] 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.rs | 135 ++++++++++++++++- crates/ec-av1/src/tile.rs | 282 +++++++++++++++++++++++++++++++++++- 2 files changed, 407 insertions(+), 10 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 151c1fb4..617aaa45 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -2555,7 +2555,7 @@ fn code_square( // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both // planes; what it costs still counts towards the partition decision. - let ([u, v], uv_mode, chroma_cost) = + let ([u, v], uv_mode, chroma_cost, palette_uv) = search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); cost += chroma_cost; ( @@ -2567,6 +2567,7 @@ fn code_square( uv_mode, tx_depth, palette, + palette_uv, ..BlockCoeffs::default() }, cost, @@ -2656,7 +2657,7 @@ fn search_chroma( search: &Search, luma_mode: u8, fctx: &crate::decode::FrameCtx, -) -> ([Vec; 2], u8, f64) { +) -> ([Vec; 2], u8, f64, Option) { let at = At { x: x / 2, y: y / 2, @@ -2704,7 +2705,79 @@ fn search_chroma( best = Some((cost, mode, u, v)); } } - let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty"); + let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); + // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over + // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is + // what keeps `u_colors` ascending and distinct the way + // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as + // each cluster's own mean, since the colour-index map is SHARED by the + // two planes. Priced against the best ordinary chroma mode above, so a + // block only takes one when it beats it; a palette block's chroma mode is + // `UV_DC_PRED` by construction. + let mut palette_uv = None; + if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { + debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); + let plane_source = |p: &Plane| -> Vec { + (at.y..at.y + at.side) + .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) + .collect() + }; + let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); + for pal in palette_candidates(&u_source) { + let n = usize::from(pal.size); + // V's base colour per cluster: the mean of the samples the shared + // map assigns to it (an empty cluster cannot happen -- every + // colour `palette_candidates` returns is some pixel's nearest). + let mut sums = [0u32; 8]; + let mut counts = [0u32; 8]; + for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { + let k = usize::from(i).min(n - 1); + sums[k] += u32::from(sample); + counts[k] += 1; + } + let mut v_colors = [0u16; 8]; + for k in 0..n { + v_colors[k] = if counts[k] > 0 { + ((sums[k] + counts[k] / 2) / counts[k]) as u16 + } else { + 0 + }; + } + let candidate = crate::tile::PaletteUv { + size: pal.size, + u_colors: pal.colors, + v_colors, + map: pal.map, + }; + let predict = |colors: &[u16; 8]| -> Vec { + candidate + .map + .iter() + .map(|&i| colors[usize::from(i).min(n - 1)] as u8) + .collect() + }; + let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); + let u_trial = chroma[0].code_from_prediction( + at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, + ); + let v_trial = chroma[1].code_from_prediction( + at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, + ); + let cost_p = u_trial.sse + + v_trial.sse + + search.lambda + * (u_trial.bits + + v_trial.bits + + crate::tile::palette_uv_bits(&candidate, side)); + if cost_p < cost { + cost = cost_p; + mode = DC_PRED; + u = u_trial; + v = v_trial; + palette_uv = Some(candidate); + } + } + } if census_on() { CHROMA_RANK[sad_rank(&ranking, mode).min(6)] .fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -2716,6 +2789,7 @@ fn search_chroma( [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], mode, cost, + palette_uv, ) } @@ -2963,6 +3037,7 @@ fn code_square_inter( skip: skip_new, eight: None, palette: None, + palette_uv: None, tx_depth, inter: Some(InterInfo { ref1: None, @@ -3000,6 +3075,7 @@ fn code_square_inter( skip, eight: None, palette: None, + palette_uv: None, tx_depth, inter: Some(InterInfo { ref1: None, @@ -5054,6 +5130,7 @@ fn search_inter_block( inter: best.inter, eight: None, palette: None, + palette_uv: None, tx_depth: 0, }, best.cost, @@ -6397,11 +6474,18 @@ mod tests { picture.y[y * width + x] = INK[cell * 2 + bar]; } } + // Four chroma colours, not two: a two-colour chroma block only ever + // codes a `PaletteSizeUV` of 2, which leaves + // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking + // deltas and the neighbour cache flags, exercised only when + // neighbouring blocks share colours) unproven by the ffmpeg oracle. + const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; + const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; for y in 0..height / 2 { for x in 0..width / 2 { - let cell = (x / 12 + y / 12) % 2; - picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 }; - picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 }; + let cell = (x / 12 + 2 * (y / 12)) % 4; + picture.u[y * (width / 2) + x] = CHROMA_U[cell]; + picture.v[y * (width / 2) + x] = CHROMA_V[cell]; } } picture @@ -6427,6 +6511,23 @@ mod tests { let hits = crate::tile::take_palette_hits(); assert!(hits[0] > 0, "no block took a palette: {hits:?}"); eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); + // The chroma half is a claim about the plane-1 syntax only if some + // block really took a chroma palette (`gate-blind-to-feature`): every + // exactness assert below passes on a stream that codes + // `palette_uv_mode == 0` everywhere. + let uv_hits = crate::tile::take_palette_uv_hits(); + assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}"); + let uv_cached = crate::tile::take_palette_uv_cache_hits(); + eprintln!( + "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", + uv_hits[0], + &uv_hits[2..] + ); + assert!( + uv_cached > 0, + "no chroma base colour came out of the neighbour cache -- \ + `write_palette_colors_uv`'s cache half is unproven by the oracle below" + ); let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); @@ -6463,12 +6564,19 @@ mod tests { }) .collect(); let _ = crate::tile::take_palette_hits(); + let _ = crate::tile::take_palette_uv_hits(); let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); let gop_hits = crate::tile::take_palette_hits(); + let gop_uv_hits = crate::tile::take_palette_uv_hits(); let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); eprintln!( - "GOP: {} frames with screen tools after the key frame, {} palette blocks", - inter_screen, gop_hits[0] + "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ + {} chroma palette blocks", + inter_screen, gop_hits[0], gop_uv_hits[0] + ); + assert!( + gop_uv_hits[0] > 0, + "no block of the GOP took a chroma palette: {gop_uv_hits:?}" ); assert!( inter_screen > 0, @@ -6530,6 +6638,7 @@ mod tests { skip: false, eight: None, palette: None, + palette_uv: None, tx_depth: 0, inter: Some(InterInfo { ref1: None, @@ -9354,6 +9463,16 @@ mod tests { .collect::>() .join(" ") ); + let palette_uv = crate::tile::take_palette_uv_hits(); + eprintln!( + "{name}: chroma palette blocks {} sizes {}", + palette_uv[0], + (2..=8) + .filter(|&n| palette_uv[n] > 0) + .map(|n| format!("{n}={}", palette_uv[n])) + .collect::>() + .join(" ") + ); let uv = take_uv_mode_hits(); let uv_total: usize = uv.iter().sum(); eprintln!( diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 431df26a..b8d13bd7 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -1120,6 +1120,11 @@ pub struct BlockCoeffs { /// `tx_depth` to zero (the whole block is one transform over the /// palette's own prediction). pub palette: Option, + /// The chroma palette this block's two chroma planes are predicted with + /// (spec 5.11.46 `palette_mode_info`'s plane-1 half), or `None`. Only a + /// `UV_DC_PRED` block of an `allow_screen_content_tools` frame may carry + /// one; it is independent of [`Self::palette`] (either, both or neither). + pub palette_uv: Option, /// How many times this block's luma transform is halved under /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole /// block). Read only by the writers a `tx_select` frame calls; a @@ -1143,6 +1148,27 @@ pub struct PaletteY { pub map: Vec, } +/// As [`PaletteY`], for a block's chroma palette -- one colour-index map +/// SHARED by U and V (spec `av1_visit_palette`'s plane-1 pass; the two planes +/// are co-located after 4:2:0 subsampling) plus each plane's own base +/// colours, exactly what [`crate::decode`]'s own `PaletteUv` carries out of +/// the stream. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PaletteUv { + /// How many base colours, 2..=8 (spec `PaletteSizeUV`). + pub size: u8, + /// U's base colours, ASCENDING and distinct -- `read_palette_colors_uv` + /// merges the cached and transmitted lists as two ascending runs, and its + /// delta form only ever steps upwards. + pub u_colors: [u16; 8], + /// V's base colours, in the same cluster order as [`Self::u_colors`] -- + /// the shared map indexes both, and V's own coding needs no ordering. + pub v_colors: [u16; 8], + /// Which colour each chroma pixel takes, row-major over the subsampled + /// block's own `(side / 2).max(4)` side. + pub map: Vec, +} + /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by /// [`write_inter_mode`] with the decoder's own contexts. @@ -1396,6 +1422,15 @@ struct Neighbours { pending_palette: Option<(u8, [u16; 8])>, /// The colours beside [`Self::above_palette_size`]. above_palette_colors: Vec<[u16; 8]>, + /// The chroma (U-channel) halves of the three bands above -- + /// `av1_get_palette_cache(xd, 1, cache)`'s source, mirrored from the + /// decoder's own `above_palette_uv_*`/`left_palette_uv_*`. + above_palette_uv_size: Vec, + left_palette_uv_size: Vec, + above_palette_uv_colors: Vec<[u16; 8]>, + left_palette_uv_colors: Vec<[u16; 8]>, + /// [`Self::pending_palette`] for the chroma palette. + pending_palette_uv: Option<(u8, [u16; 8])>, /// The same, down the left edge. left_palette_colors: Vec<[u16; 8]>, /// Whether the neighbour was coded inter, for the `is_inter` context. @@ -1487,6 +1522,11 @@ impl Neighbours { left_palette_size: vec![0; rows * (SUB / MI)], pending_palette: None, above_palette_colors: vec![[0; 8]; cols * (SUB / MI)], + above_palette_uv_size: vec![0; cols * (SUB / MI)], + left_palette_uv_size: vec![0; rows * (SUB / MI)], + above_palette_uv_colors: vec![[0; 8]; cols * (SUB / MI)], + left_palette_uv_colors: vec![[0; 8]; rows * (SUB / MI)], + pending_palette_uv: None, left_palette_colors: vec![[0; 8]; rows * (SUB / MI)], mi_cols, mi_rows, @@ -1525,6 +1565,8 @@ impl Neighbours { self.left_tx.iter_mut().for_each(|t| *t = 0); self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); self.left_palette_size.iter_mut().for_each(|s| *s = 0); + self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0); + self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]); } /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from @@ -1582,6 +1624,80 @@ impl Neighbours { (ctx, cache) } + /// [`Self::palette_ctx_and_cache`]'s cache half for the U channel + /// (`av1_get_palette_cache(xd, 1, cache)`), mirrored from the decoder's + /// `palette_uv_cache_mi`: the `palette_uv_mode` context needs no + /// neighbour lookup at all (it is this block's own just-decided Y palette + /// use), so only the cache is wanted here. + fn palette_uv_cache(&self, (r, c): (usize, usize)) -> Vec { + let above_ok = r % 16 != 0; + let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 { + ( + usize::from(self.above_palette_uv_size[c]), + self.above_palette_uv_colors[c], + ) + } else { + (0, [0u16; 8]) + }; + let (left_n, left_colors) = if c > 0 && self.left_palette_uv_size[r] > 0 { + ( + usize::from(self.left_palette_uv_size[r]), + self.left_palette_uv_colors[r], + ) + } else { + (0, [0u16; 8]) + }; + let mut cache = Vec::with_capacity(16); + let push_dedup = |cache: &mut Vec, v: u16| { + if cache.last() != Some(&v) { + cache.push(v); + } + }; + let (mut ai, mut li) = (0usize, 0usize); + while ai < above_n && li < left_n { + let (va, vl) = (above_colors[ai], left_colors[li]); + if vl < va { + push_dedup(&mut cache, vl); + li += 1; + } else { + push_dedup(&mut cache, va); + ai += 1; + if vl == va { + li += 1; + } + } + } + while ai < above_n { + push_dedup(&mut cache, above_colors[ai]); + ai += 1; + } + while li < left_n { + push_dedup(&mut cache, left_colors[li]); + li += 1; + } + cache + } + + /// [`Self::record_palette_y`] for the chroma bands (decode.rs + /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same + /// way, and the span is in LUMA pixels for both planes' bands alike. + fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { + for cell in 0..(side / MI).max(1) { + if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) { + *e = size; + if size > 0 { + self.above_palette_uv_colors[c + cell] = colors; + } + } + if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) { + *e = size; + if size > 0 { + self.left_palette_uv_colors[r + cell] = colors; + } + } + } + } + /// What a just-written block leaves in the palette bands (decode.rs /// `record_palette_y_rect`): its size and colours over every 4x4 unit it /// spans, `0` for a block that took no palette. @@ -1750,6 +1866,8 @@ impl Neighbours { if screen_armed() { let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8])); self.record_palette_y(at_mi, side, size, colors); + let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8])); + self.record_palette_uv(at_mi, side, uv_size, uv_colors); } let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); let side_mi = side / MI; @@ -2522,6 +2640,72 @@ fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16] } } +/// `write_palette_colors_uv` (bitstream.c:1236), the write side of +/// [`crate::decode`]'s `read_palette_colors_uv` at 8 bits. U is +/// [`write_palette_colors_y`]'s cache/delta scheme with the reader's two +/// documented differences -- the shrinking range starts at `256 - first` +/// (not `255 - first`) and each delta is written unbiased (no `-1`). +/// +/// corner-cut: V takes the reader's RAW form (the leading bit 0, then `n` +/// 8-bit literals) rather than its first-value-plus-signed-deltas form. +/// Ceiling: about `n` bits per chroma-palette block more than the delta form +/// would spend (8n against roughly 10 + (n-1)*(5..8)), which the RD pricer +/// below sees, so it only ever makes the encoder take FEWER chroma palettes +/// than it should -- never a wrong stream. Upgrade path: price both forms +/// here and write the cheaper one under its own leading bit. +fn write_palette_colors_uv(enc: &mut SymbolEncoder, u_colors: &[u16], v_colors: &[u16], cache: &[u16]) { + let n = u_colors.len(); + let mut cached: Vec = Vec::with_capacity(n); + for &c in cache { + if cached.len() >= n { + break; + } + let take = u_colors.contains(&c); + enc.literal(u32::from(take), 1); + if take { + PALETTE_UV_CACHE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + cached.push(c); + } + } + let transmitted: Vec = u_colors + .iter() + .copied() + .filter(|c| !cached.contains(c)) + .collect(); + if !transmitted.is_empty() { + enc.literal(u32::from(transmitted[0]), 8); + if transmitted.len() > 1 { + let fits = |extra: u32| -> bool { + let mut bits = 5 + extra; + let mut range = 256i32 - i32::from(transmitted[0]); + for w in transmitted.windows(2) { + let delta = i32::from(w[1]) - i32::from(w[0]); + if delta >= (1i32 << bits) { + return false; + } + range -= delta; + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); + } + true + }; + let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3); + enc.literal(extra, 2); + let mut bits = 5 + extra; + let mut range = 256i32 - i32::from(transmitted[0]); + for w in transmitted.windows(2) { + let delta = i32::from(w[1]) - i32::from(w[0]); + enc.literal(delta as u32, bits); + range -= delta; + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); + } + } + } + enc.literal(0, 1); + for &v in v_colors { + enc.literal(u32::from(v), 8); + } +} + /// `write_palette_color_map` (bitstream.c), the write side of /// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal, /// 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 { enc.bits() } +/// [`palette_bits`] for the chroma palette: the `palette_uv_mode` flag, the +/// size symbol, both colour lists and the shared colour-index map, priced +/// through the very writers above (empty cache, which only over-prices). +pub(crate) fn palette_uv_bits(pal: &PaletteUv, side: usize) -> f64 { + let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else { + return f64::INFINITY; + }; + let n = usize::from(pal.size); + let mut enc = SymbolEncoder::pricer(); + let mut mode_cdf = cdf::PALETTE_UV_MODE[0]; + enc.symbol(1, &mut mode_cdf); + let mut size_cdf = cdf::PALETTE_UV_SIZE[bsize_ctx]; + enc.symbol(n - 2, &mut size_cdf); + write_palette_colors_uv(&mut enc, &pal.u_colors[..n], &pal.v_colors[..n], &[]); + let mut idx_cdfs = cdf::PALETTE_UV_COLOR_INDEX[n - 2]; + write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, palette_uv_side(side), n); + enc.bits() +} + /// Writes everything a key frame's block carries before its coefficients: the /// skip flag, its luma intra mode against the CDF its neighbours' modes pick, /// the angle a directional mode is steered by, and its chroma mode. Hands back @@ -2621,7 +2824,17 @@ fn write_intra_mode( // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer // codes none -- exactly the ctx-0 read the decoder does under the same // condition. - write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side); + write_palette_syntax( + enc, + cdfs, + neighbours, + block.palette.as_ref(), + block.palette_uv.as_ref(), + mode, + uv_mode, + mi, + side, + ); mode } @@ -2644,6 +2857,7 @@ fn write_palette_syntax( cdfs: &mut Cdfs, neighbours: &mut Neighbours, palette: Option<&PaletteY>, + palette_uv: Option<&PaletteUv>, mode: usize, uv_mode: usize, mi: (usize, usize), @@ -2653,8 +2867,10 @@ fn write_palette_syntax( return; } let palette = palette.filter(|_| mode == DC_PRED); + let palette_uv = palette_uv.filter(|_| uv_mode == DC_PRED); if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) { let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi); + let uv_cache = neighbours.palette_uv_cache(mi); if mode == DC_PRED { enc.symbol( usize::from(palette.is_some()), @@ -2667,15 +2883,45 @@ fn write_palette_syntax( write_palette_colors_y(enc, &pal.colors[..n], &cache); } if uv_mode == DC_PRED { - enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]); + enc.symbol( + usize::from(palette_uv.is_some()), + &mut cdfs.palette_uv_mode[usize::from(palette.is_some())], + ); + } + if let Some(pal) = palette_uv { + let n = usize::from(pal.size); + enc.symbol(n - 2, &mut cdfs.palette_uv_size[bsize_ctx]); + write_palette_colors_uv(enc, &pal.u_colors[..n], &pal.v_colors[..n], &uv_cache); } + // Both colour-index maps come after BOTH colour lists, in plane order + // (`av1_visit_palette` runs from the caller, past `filter_intra`). if let Some(pal) = palette { let n = usize::from(pal.size); write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n); note_palette(n); } + if let Some(pal) = palette_uv { + let n = usize::from(pal.size); + write_color_index_map( + enc, + &mut cdfs.palette_uv_color_index[n - 2], + &pal.map, + palette_uv_side(side), + n, + ); + note_palette_uv(n); + } } neighbours.pending_palette = palette.map(|p| (p.size, p.colors)); + neighbours.pending_palette_uv = palette_uv.map(|p| (p.size, p.u_colors)); +} + +/// The side of a chroma palette's shared colour-index map for a square luma +/// block of `side` samples: `av1_get_plane_block_size(bsize, 1, 1)` floored at +/// the 4-px transform, NOT a plain halving (decode.rs reads the map at +/// exactly this size). +pub(crate) fn palette_uv_side(side: usize) -> usize { + (side / 2).max(4) } /// How many blocks took a palette, and of what size -- the fire count a gate @@ -2690,6 +2936,35 @@ fn note_palette(n: usize) { PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } +/// [`PALETTE_HITS`] for the chroma palette -- the same shape, so a gate can +/// print the share of each plane's palette separately. +static PALETTE_UV_HITS: [std::sync::atomic::AtomicUsize; 9] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; + +fn note_palette_uv(n: usize) { + PALETTE_UV_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + PALETTE_UV_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// How many chroma base colours came out of the NEIGHBOUR CACHE rather than +/// the stream -- the half of `write_palette_colors_uv` a test cannot see from +/// the block counts alone, and the one that desyncs the tile if this writer's +/// cache ever disagrees with the decoder's (`gate-blind-to-feature`). +static PALETTE_UV_CACHE_HITS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// Reads [`PALETTE_UV_CACHE_HITS`] and zeroes it. +#[cfg(test)] +pub(crate) fn take_palette_uv_cache_hits() -> usize { + PALETTE_UV_CACHE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + +/// [`take_palette_hits`] for the chroma palette. +#[cfg(test)] +pub(crate) fn take_palette_uv_hits() -> [usize; 9] { + std::array::from_fn(|i| PALETTE_UV_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to /// its own encode. #[cfg(test)] @@ -4613,6 +4888,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( &mut cdfs, &mut neighbours, block.palette.as_ref(), + block.palette_uv.as_ref(), mode, uv_mode, (mi_row, mi_col), @@ -4836,6 +5112,7 @@ fn write_inter_frame_leaf( cdfs, neighbours, block.palette.as_ref(), + block.palette_uv.as_ref(), mode, uv_mode, (mi_row, mi_col), @@ -5065,6 +5342,7 @@ fn write_inter_frame_leaf8( cdfs, neighbours, block.palette.as_ref(), + block.palette_uv.as_ref(), mode, uv_mode, leaf_mi,