From f2eac79bf67570ee4db34a7d53ff674b0f60b3ec 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 11:20:01 +0300 Subject: [PATCH] feat(av1): palette-coded luma intra blocks on a screen-content key frame The whole spec 5.11.46 chain, mirrored symbol for symbol from this crate's own decoder: `palette_y_mode` off the real `av1_get_palette_mode_ctx` neighbour bands, `palette_y_size`, the colours coded against the above/left colour cache `av1_get_palette_cache` builds (`palette_ctx_and_cache`, the decoder's own merge and dedup), and the colour-index map on `decode_color_map_tokens`' wavefront diagonal with `av1_get_palette_color_index_context`'s ordering. The candidate palettes are libaom `av1_k_means`-shaped: a block with at most 8 distinct colours takes them all (exact prediction), a busier one is quantised to 8 and to 4 by a histogram Lloyd iteration, and each is priced through the very writers the tile uses (`palette_bits` on a `SymbolEncoder::pricer`) against the mode the intra search already settled. Check: encode::tests::a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly -- 48 palette blocks (sizes 2/3/4, 16 each) on a 192x96 screen card, ffmpeg and our own decoder both reconstruct the encoder's picture exactly, and the film-shaped test card leaves the detector off. --- crates/ec-av1/src/decode.rs | 4 +- crates/ec-av1/src/encode.rs | 242 ++++++++++++++++++++++++++++ crates/ec-av1/src/tile.rs | 312 ++++++++++++++++++++++++++++++++++-- 3 files changed, 545 insertions(+), 13 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a6eb5eca..93f7a44c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -8385,7 +8385,7 @@ struct PaletteUv { /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s /// `get_unsigned_bits`, which is the same formula): smallest `n` with /// `2^n >= x`, `0` for `x <= 1`. -fn ceil_log2(x: u32) -> u32 { +pub(crate) fn ceil_log2(x: u32) -> u32 { if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() } } @@ -8559,7 +8559,7 @@ const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2 /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the /// actual colour index to store. -fn palette_color_index_context( +pub(crate) fn palette_color_index_context( map: &[u8], side: usize, row: usize, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 63f1bc1d..93ae2525 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -2288,6 +2288,105 @@ fn commit_inter_luma( (flat.levels.clone(), 0, 0.0) } +/// The largest distinct-colour count a block may hold and still be offered a +/// palette candidate at all: past it the k-means quantisation costs more +/// error than the map saves rate, and every trial is wasted wall. +/// `EC_AV1_PAL_MAXCOLORS`. +fn palette_max_colors() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("EC_AV1_PAL_MAXCOLORS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(32) + }) +} + +/// The palettes worth trying for one block's luma, in the shape libaom's +/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE` +/// distinct colours takes them ALL (the prediction is then exact and the +/// residual empty), and a busier one is quantised to 8 and to 4 colours by a +/// one-dimensional Lloyd iteration seeded evenly across its range -- both +/// offered, because which wins is an RD question the caller answers. +/// `block` is `side*side` source samples, row-major. +fn palette_candidates(block: &[u8]) -> Vec { + let mut histogram = [0u32; 256]; + for &v in block { + histogram[usize::from(v)] += 1; + } + let present: Vec = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect(); + if present.len() < 2 { + return Vec::new(); + } + let exact = |colors: &[u16]| -> crate::tile::PaletteY { + let mut base = [0u16; 8]; + base[..colors.len()].copy_from_slice(colors); + let map = block + .iter() + .map(|&v| { + colors + .iter() + .enumerate() + .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) + .map(|(i, _)| i as u8) + .expect("a palette holds at least two colours") + }) + .collect(); + crate::tile::PaletteY { size: colors.len() as u8, colors: base, map } + }; + if present.len() <= 8 { + return vec![exact(&present)]; + } + if present.len() > palette_max_colors() { + return Vec::new(); + } + let (lo, hi) = ( + i32::from(present[0]), + i32::from(present[present.len() - 1]), + ); + let mut out = Vec::with_capacity(2); + for n in [8usize, 4] { + // Even seeding across the block's own range, then four Lloyd passes + // over the histogram (256 bins, not `side*side` pixels). + let mut centres: Vec = (0..n) + .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) + .collect(); + for _ in 0..4 { + let mut sums = vec![0f64; n]; + let mut counts = vec![0u32; n]; + for (v, &count) in histogram.iter().enumerate() { + if count == 0 { + continue; + } + let k = (0..n) + .min_by(|&a, &b| { + (centres[a] - v as f64) + .abs() + .total_cmp(&(centres[b] - v as f64).abs()) + }) + .expect("n >= 2"); + sums[k] += (v as u32 * count) as f64; + counts[k] += count; + } + for k in 0..n { + if counts[k] > 0 { + centres[k] = sums[k] / f64::from(counts[k]); + } + } + } + let mut colors: Vec = centres + .iter() + .map(|&c| c.round().clamp(0.0, 255.0) as u16) + .collect(); + colors.sort_unstable(); + colors.dedup(); + if colors.len() >= 2 { + out.push(exact(&colors)); + } + } + out +} + #[allow(clippy::too_many_arguments)] fn code_square( luma: &mut Plane, @@ -2349,6 +2448,55 @@ fn code_square( luma_coeffs = best.3; TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } + // The palette candidate is priced against the mode the luma search (and + // its transform-depth search) already settled on, so a block only takes + // one when it beats the best ordinary intra coding of the same pixels. + // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its + // prediction is the colour map, not the DC of its neighbours. + let mut mode = mode; + let mut palette = None; + if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { + let source: Vec = (y..y + side) + .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) + .collect(); + let kept = luma.snapshot(x, y, side); + for pal in palette_candidates(&source) { + let n = usize::from(pal.size); + let prediction: Vec = pal + .map + .iter() + .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) + .collect(); + let trial = luma.code_from_prediction( + x, + y, + side, + &prediction, + false, + search.base_q_idx, + search.deadzone, + luma_set, + ); + let cost_p = trial.sse + + search.lambda + * (trial.bits + + mode_bits[DC_PRED as usize] + + crate::tile::palette_bits(&pal, side) + + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); + if cost_p < cost { + cost = cost_p; + mode = DC_PRED as u8; + tx_depth = 0; + luma_coeffs = coeffs(&trial.levels, side); + luma.commit(x, y, side, &trial); + palette = Some(pal); + } + } + if palette.is_none() { + luma.restore(x, y, side, &kept); + } + } + // 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) = @@ -2362,6 +2510,7 @@ fn code_square( mode, uv_mode, tx_depth, + palette, ..BlockCoeffs::default() }, cost, @@ -2757,6 +2906,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip: skip_new, eight: None, + palette: None, tx_depth, inter: Some(InterInfo { ref_frame: crate::mvstack::LAST_FRAME, @@ -2791,6 +2941,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip, eight: None, + palette: None, tx_depth, inter: Some(InterInfo { ref_frame: crate::mvstack::LAST_FRAME, @@ -2906,6 +3057,9 @@ fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { /// What the luma mode search picks between, and under what terms. struct Search<'a> { + /// This frame's `allow_screen_content_tools` ([`screen_content`]): the + /// luma search then offers a palette candidate beside the intra modes. + screen: bool, base_q_idx: u8, deadzone: f64, lambda: f64, @@ -3257,6 +3411,7 @@ pub(crate) fn encode_key_frame_inner( lambda: lambda_scale() * step * step, modes, top_k: prune_top_k(), + screen, }; // The block grid this frame is coded over: [`crate::tile::block_grid`]'s @@ -4446,6 +4601,7 @@ fn search_inter_block( skip: best.skip, inter: best.inter, eight: None, + palette: None, tx_depth: 0, }, best.cost, @@ -4618,6 +4774,9 @@ pub(crate) fn encode_inter_frame( lambda: lambda_scale() * step * step, modes: &KEY_FRAME_MODES, top_k: prune_top_k_inter(), + // An inter frame never sets `allow_screen_content_tools` yet, so its + // intra blocks code no palette syntax (deferred, see the lane report). + screen: false, }; let mode_bits_table = inter_mode_bits(); @@ -5667,6 +5826,68 @@ mod tests { ); } + /// A synthetic screen-content picture -- a few flat colours in a grid of + /// boxes with hard edges and text-like bars, the shape a desktop capture + /// has -- so the palette path is exercised on content it is for. + #[cfg(test)] + fn screen_card(width: usize, height: usize) -> Picture { + const INK: [u16; 4] = [16, 90, 180, 235]; + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let cell = (x / 24 + y / 24) % 2; + let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); + picture.y[y * width + x] = INK[cell * 2 + bar]; + } + } + 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 }; + } + } + picture + } + + /// The lane's own end-to-end check: on screen content the detector fires, + /// blocks really take a palette (fire count, class + /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every + /// symbol this lane writes -- reconstructs exactly what the encoder did. + /// The film-shaped `test_card` must NOT trip the detector, which is what + /// keeps every non-screen stream byte-identical. + #[test] + fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { + let fctx = &crate::decode::FrameCtx::new(); + let (width, height) = (192usize, 96usize); + let _ = crate::tile::take_palette_hits(); + let picture = screen_card(width, height); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + assert!( + encoded.screen, + "the detector did not fire on screen content -- no palette syntax was coded at all" + ); + 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..]); + 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"); + assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half: no ffmpeg"); + return; + } + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); + // The other half of the keep rule: film-shaped content leaves the + // detector (and so the whole sequence header) alone. + let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); + assert!(!film.screen, "the detector fired on the film-shaped test card"); + } + /// The minimal repro that isolated the inter-residual desync: a key frame /// followed by one inter frame whose single superblock carries one /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma @@ -5703,6 +5924,7 @@ mod tests { uv_mode: 0, skip: false, eight: None, + palette: None, tx_depth: 0, inter: Some(InterInfo { ref_frame: crate::mvstack::LAST_FRAME, @@ -8289,6 +8511,10 @@ mod tests { let fctx = &crate::decode::FrameCtx::new(); let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); let _ = take_partition_hits(); + let _ = crate::tile::take_palette_hits(); + SCREEN_FRAMES.iter().for_each(|c| { + c.store(0, std::sync::atomic::Ordering::Relaxed); + }); let _ = take_uv_mode_hits(); let _ = crate::tile::take_inter_mode_hits(); let _ = crate::tile::take_drl_hits(); @@ -8408,6 +8634,22 @@ mod tests { // Which chroma modes the search actually wins with, against the // unconditional DC_PRED that was the only outcome before // (gate-blind-to-feature). + // Screen-content detection and the palette it turns on + // (gate-blind-to-feature): how many frames set + // `allow_screen_content_tools`, how many blocks took a palette, + // and of what size. A film clip must print `screen frames on=0`. + let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); + let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); + let palette = crate::tile::take_palette_hits(); + eprintln!( + "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", + palette[0], + (2..=8) + .filter(|&n| palette[n] > 0) + .map(|n| format!("{n}={}", palette[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 b570a8c7..821d9597 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -673,6 +673,13 @@ pub struct BlockCoeffs { /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s /// per-quadrant fields are unused. pub eight: Option>, + /// The luma palette this block is predicted with (spec 5.11.46 + /// `palette_mode_info`), or `None` for an ordinary intra block. Only a + /// `DC_PRED` block on a frame whose header set + /// `allow_screen_content_tools` may carry one, and it forces + /// `tx_depth` to zero (the whole block is one transform over the + /// palette's own prediction). + pub palette: 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 @@ -682,6 +689,20 @@ pub struct BlockCoeffs { pub tx_depth: u8, } +/// A block's luma palette: its base colours (ascending, only the first +/// `size` entries are real) and the per-pixel colour-index map, `side*side` +/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back +/// out of the stream. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PaletteY { + /// How many base colours, 2..=8 (spec `PaletteSizeY`). + pub size: u8, + /// The base colours, ascending. + pub colors: [u16; 8], + /// Which colour each pixel takes, row-major over the block's own 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. @@ -878,6 +899,20 @@ struct Neighbours { above_txfm: Vec, /// The same, down the left edge (transform HEIGHT). left_txfm: Vec, + /// The palette size each 4x4 mode-info column last left behind, and its + /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and + /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's + /// own `above_palette_size`/`above_palette_colors` bands (decode.rs + /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content + /// frame writes them, `0` when it took no palette, so a stale size never + /// survives into the next block's context. + above_palette_size: Vec, + /// The same, down the left edge. + left_palette_size: Vec, + /// The colours beside [`Self::above_palette_size`]. + above_palette_colors: Vec<[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. /// Unused by the key frame writers. above_inter: Vec, @@ -938,6 +973,10 @@ impl Neighbours { left_tx: vec![0; rows * (SUB / MI)], above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], + above_palette_size: vec![0; cols * (SUB / MI)], + left_palette_size: vec![0; rows * (SUB / MI)], + above_palette_colors: vec![[0; 8]; cols * (SUB / MI)], + left_palette_colors: vec![[0; 8]; rows * (SUB / MI)], mi_cols, mi_rows, } @@ -954,6 +993,82 @@ impl Neighbours { self.left_ref.iter_mut().for_each(|r| *r = -1); 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); + } + + /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from + /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the + /// `palette_y_mode` context (how many of the two neighbours took a + /// palette) and the ascending, deduplicated colour cache the neighbours + /// offer. `mi` is the block's own position in 4x4 units; this writer + /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0` + /// availability terms read against. + fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec) { + // `av1_get_palette_cache` drops the above neighbour on a 64-px + // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does + // not, which is why the two terms below are asked separately. + let above_ok = r % 16 != 0; + let above_is_palette = r > 0 && self.above_palette_size[c] > 0; + let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 { + (usize::from(self.above_palette_size[c]), self.above_palette_colors[c]) + } else { + (0, [0u16; 8]) + }; + let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 { + (usize::from(self.left_palette_size[r]), self.left_palette_colors[r]) + } else { + (0, [0u16; 8]) + }; + let ctx = usize::from(above_is_palette) + usize::from(left_n > 0); + 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; + } + (ctx, cache) + } + + /// 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. + fn record_palette_y(&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_size.get_mut(c + cell) { + *e = size; + if size > 0 { + self.above_palette_colors[c + cell] = colors; + } + } + if let Some(e) = self.left_palette_size.get_mut(r + cell) { + *e = size; + if size > 0 { + self.left_palette_colors[r + cell] = colors; + } + } + } } /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block @@ -1721,6 +1836,130 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( Ok(enc.finish()) } +/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`, +/// which the palette colour-index map's first (context-free) symbol is coded +/// with. +fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) { + let l = crate::decode::ceil_log2(n as u32); + let m = (1usize << l) - n; + if value < m { + enc.literal(value as u32, l - 1); + } else { + enc.literal(((value + m) >> 1) as u32, l - 1); + enc.literal(((value + m) & 1) as u32, 1); + } +} + +/// `write_palette_colors_y` (bitstream.c:1178), the write side of +/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache +/// entry (taken when this palette holds that colour, in cache order, stopping +/// once `n` are cached), then the colours the cache did not supply -- the +/// first raw, the rest as deltas off a bit width that shrinks with the range +/// left. `colors` is ascending and distinct, so the decoder's `merge_colors` +/// of the two ascending lists puts it back exactly. +fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) { + let n = colors.len(); + let mut cached: Vec = Vec::with_capacity(n); + for &c in cache { + if cached.len() >= n { + break; + } + let take = colors.contains(&c); + enc.literal(u32::from(take), 1); + if take { + cached.push(c); + } + } + let transmitted: Vec = colors + .iter() + .copied() + .filter(|c| !cached.contains(c)) + .collect(); + if transmitted.is_empty() { + return; + } + enc.literal(u32::from(transmitted[0]), 8); + if transmitted.len() == 1 { + return; + } + // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one + // under which every delta still fits its (shrinking) width. `extra == 3` + // always works -- a delta can never exceed the range left -- so the + // search below always finds one. + let fits = |extra: u32| -> bool { + let mut bits = 5 + extra; + let mut range = 255i32 - i32::from(transmitted[0]); + for w in transmitted.windows(2) { + let delta = i32::from(w[1]) - i32::from(w[0]); + if delta - 1 >= (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 = 255i32 - i32::from(transmitted[0]); + for w in transmitted.windows(2) { + let delta = i32::from(w[1]) - i32::from(w[0]); + enc.literal((delta - 1) as u32, bits); + range -= delta; + bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32)); + } +} + +/// `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 +/// ordering `av1_get_palette_color_index_context` hands back. +fn write_color_index_map( + enc: &mut SymbolEncoder, + idx_cdfs: &mut [[u16; 9]; 5], + map: &[u8], + side: usize, + n: usize, +) { + write_uniform(enc, usize::from(map[0]), n); + for i in 1..(2 * side - 1) { + for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() { + let (row, col) = (i - j, j); + let (ctx, color_order) = + crate::decode::palette_color_index_context(map, side, row, col, n); + let want = map[row * side + col]; + let symbol = color_order[..n] + .iter() + .position(|&c| c == want) + .expect("every colour index is in the block\'s own palette"); + enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]); + } + } +} + +/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag, +/// the size symbol, the colours and the whole colour-index map, priced +/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the +/// search reads the rate the tile will really spend, not an estimate of it. +/// The neighbour cache is taken as empty (the search runs before the tile +/// knows what its neighbours will be), which only ever over-prices. +pub(crate) fn palette_bits(pal: &PaletteY, 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_Y_MODE[bsize_ctx][0]; + enc.symbol(1, &mut mode_cdf); + let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx]; + enc.symbol(n - 2, &mut size_cdf); + write_palette_colors_y(&mut enc, &pal.colors[..n], &[]); + let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2]; + write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, 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 @@ -1728,6 +1967,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( fn write_intra_mode( enc: &mut SymbolEncoder, cdfs: &mut Cdfs, + neighbours: &mut Neighbours, block: &BlockCoeffs, above_mode: usize, left_mode: usize, @@ -1770,19 +2010,67 @@ 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. - if screen_armed() - && let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) - { - if mode == DC_PRED { - enc.symbol(0, &mut cdfs.palette_y_mode[bsize_ctx][0]); - } - if uv_mode == DC_PRED { - enc.symbol(0, &mut cdfs.palette_uv_mode[0]); + if screen_armed() { + let palette = block.palette.as_ref().filter(|_| mode == DC_PRED); + if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) { + let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi); + if mode == DC_PRED { + enc.symbol( + usize::from(palette.is_some()), + &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx], + ); + } + if let Some(pal) = palette { + let n = usize::from(pal.size); + enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]); + write_palette_colors_y(enc, &pal.colors[..n], &cache); + } + // `read_palette_mode_info`'s UV half sits between the luma + // colours and the luma colour-index map: libaom defers both maps + // to `av1_visit_palette`, after the whole mode info. + if uv_mode == DC_PRED { + enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]); + } + 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); + } } + // Every block of a screen-content frame publishes its (possibly zero) + // palette state, or a neighbour column keeps an earlier block's size + // and reads a context the decoder does not. + let (size, colors) = + palette.map_or((0, [0u16; 8]), |p| (p.size, p.colors)); + neighbours.record_palette_y(mi, side, size, colors); } mode } +/// How many blocks took a palette, and of what size -- the fire count a gate +/// prints so that "palette is on" is a measurement rather than a claim +/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the +/// per-size histogram. +static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; + +fn note_palette(n: usize) { + PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to +/// its own encode. +pub(crate) fn take_palette_hits() -> [usize; 9] { + std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// Writes one coded block: its mode, its three transform blocks, and what it /// leaves behind for the blocks beside it. Its partition symbol is already /// written, because only the caller knows what tree led here. @@ -1807,12 +2095,14 @@ fn write_block( ) -> Result<()> { let (r, c) = at; let at_mi = (r * (SUB / MI), c * (SUB / MI)); + let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]); let mode = write_intra_mode( enc, cdfs, + neighbours, block, - neighbours.above_mode[c], - neighbours.left_mode[r], + above_mode, + left_mode, cfl, at_mi, side, @@ -1890,7 +2180,7 @@ fn write_leaf8( // true first divergence (a differently-sized alphabet under the same // DC_PRED decision desyncs the coder even though the decoded mode is // unchanged). - let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi, 8); + let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8); let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; let split = if tx_select { let tx = write_luma_select(