forge
Explore
Log in

Don't you dare go Hollow

Palette-coded luma intra blocks on a screen-content key frame

Browse files at this commit

f2eac79bf67570ee4db34a7d53ff674b0f60b3ecAhmet Kaan GümüşParent: 3136cbe
  • feat
    • palette-coded luma intra blocks on a screen-content key frame
Show full message
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.rsmodified+2 -2
@@ -8385,7 +8385,7 @@ struct PaletteUv {
8385 /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s8385 /// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
8386 /// `get_unsigned_bits`, which is the same formula): smallest `n` with8386 /// `get_unsigned_bits`, which is the same formula): smallest `n` with
8387 /// `2^n >= x`, `0` for `x <= 1`.8387 /// `2^n >= x`, `0` for `x <= 1`.
8388-fn ceil_log2(x: u32) -> u32 {8388+pub(crate) fn ceil_log2(x: u32) -> u32 {
8389 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }8389 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
8390 }8390 }
8391 8391
@@ -8559,7 +8559,7 @@ const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2
8559 /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s8559 /// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
8560 /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the8560 /// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
8561 /// actual colour index to store.8561 /// actual colour index to store.
8562-fn palette_color_index_context(8562+pub(crate) fn palette_color_index_context(
8563 map: &[u8],8563 map: &[u8],
8564 side: usize,8564 side: usize,
8565 row: usize,8565 row: usize,
crates/ec-av1/src/encode.rsmodified+242 -0
@@ -2288,6 +2288,105 @@ fn commit_inter_luma(
2288 (flat.levels.clone(), 0, 0.0)2288 (flat.levels.clone(), 0, 0.0)
2289 }2289 }
2290 2290
2291+/// The largest distinct-colour count a block may hold and still be offered a
2292+/// palette candidate at all: past it the k-means quantisation costs more
2293+/// error than the map saves rate, and every trial is wasted wall.
2294+/// `EC_AV1_PAL_MAXCOLORS`.
2295+fn palette_max_colors() -> usize {
2296+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2297+ *N.get_or_init(|| {
2298+ std::env::var("EC_AV1_PAL_MAXCOLORS")
2299+ .ok()
2300+ .and_then(|v| v.parse().ok())
2301+ .unwrap_or(32)
2302+ })
2303+}
2304+
2305+/// The palettes worth trying for one block's luma, in the shape libaom's
2306+/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
2307+/// distinct colours takes them ALL (the prediction is then exact and the
2308+/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
2309+/// one-dimensional Lloyd iteration seeded evenly across its range -- both
2310+/// offered, because which wins is an RD question the caller answers.
2311+/// `block` is `side*side` source samples, row-major.
2312+fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2313+ let mut histogram = [0u32; 256];
2314+ for &v in block {
2315+ histogram[usize::from(v)] += 1;
2316+ }
2317+ let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
2318+ if present.len() < 2 {
2319+ return Vec::new();
2320+ }
2321+ let exact = |colors: &[u16]| -> crate::tile::PaletteY {
2322+ let mut base = [0u16; 8];
2323+ base[..colors.len()].copy_from_slice(colors);
2324+ let map = block
2325+ .iter()
2326+ .map(|&v| {
2327+ colors
2328+ .iter()
2329+ .enumerate()
2330+ .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
2331+ .map(|(i, _)| i as u8)
2332+ .expect("a palette holds at least two colours")
2333+ })
2334+ .collect();
2335+ crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
2336+ };
2337+ if present.len() <= 8 {
2338+ return vec![exact(&present)];
2339+ }
2340+ if present.len() > palette_max_colors() {
2341+ return Vec::new();
2342+ }
2343+ let (lo, hi) = (
2344+ i32::from(present[0]),
2345+ i32::from(present[present.len() - 1]),
2346+ );
2347+ let mut out = Vec::with_capacity(2);
2348+ for n in [8usize, 4] {
2349+ // Even seeding across the block's own range, then four Lloyd passes
2350+ // over the histogram (256 bins, not `side*side` pixels).
2351+ let mut centres: Vec<f64> = (0..n)
2352+ .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
2353+ .collect();
2354+ for _ in 0..4 {
2355+ let mut sums = vec![0f64; n];
2356+ let mut counts = vec![0u32; n];
2357+ for (v, &count) in histogram.iter().enumerate() {
2358+ if count == 0 {
2359+ continue;
2360+ }
2361+ let k = (0..n)
2362+ .min_by(|&a, &b| {
2363+ (centres[a] - v as f64)
2364+ .abs()
2365+ .total_cmp(&(centres[b] - v as f64).abs())
2366+ })
2367+ .expect("n >= 2");
2368+ sums[k] += (v as u32 * count) as f64;
2369+ counts[k] += count;
2370+ }
2371+ for k in 0..n {
2372+ if counts[k] > 0 {
2373+ centres[k] = sums[k] / f64::from(counts[k]);
2374+ }
2375+ }
2376+ }
2377+ let mut colors: Vec<u16> = centres
2378+ .iter()
2379+ .map(|&c| c.round().clamp(0.0, 255.0) as u16)
2380+ .collect();
2381+ colors.sort_unstable();
2382+ colors.dedup();
2383+ if colors.len() >= 2 {
2384+ out.push(exact(&colors));
2385+ }
2386+ }
2387+ out
2388+}
2389+
2291 #[allow(clippy::too_many_arguments)]2390 #[allow(clippy::too_many_arguments)]
2292 fn code_square(2391 fn code_square(
2293 luma: &mut Plane,2392 luma: &mut Plane,
@@ -2349,6 +2448,55 @@ fn code_square(
2349 luma_coeffs = best.3;2448 luma_coeffs = best.3;
2350 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);2449 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2351 }2450 }
2451+ // The palette candidate is priced against the mode the luma search (and
2452+ // its transform-depth search) already settled on, so a block only takes
2453+ // one when it beats the best ordinary intra coding of the same pixels.
2454+ // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
2455+ // prediction is the colour map, not the DC of its neighbours.
2456+ let mut mode = mode;
2457+ let mut palette = None;
2458+ if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2459+ let source: Vec<u8> = (y..y + side)
2460+ .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
2461+ .collect();
2462+ let kept = luma.snapshot(x, y, side);
2463+ for pal in palette_candidates(&source) {
2464+ let n = usize::from(pal.size);
2465+ let prediction: Vec<u8> = pal
2466+ .map
2467+ .iter()
2468+ .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
2469+ .collect();
2470+ let trial = luma.code_from_prediction(
2471+ x,
2472+ y,
2473+ side,
2474+ &prediction,
2475+ false,
2476+ search.base_q_idx,
2477+ search.deadzone,
2478+ luma_set,
2479+ );
2480+ let cost_p = trial.sse
2481+ + search.lambda
2482+ * (trial.bits
2483+ + mode_bits[DC_PRED as usize]
2484+ + crate::tile::palette_bits(&pal, side)
2485+ + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
2486+ if cost_p < cost {
2487+ cost = cost_p;
2488+ mode = DC_PRED as u8;
2489+ tx_depth = 0;
2490+ luma_coeffs = coeffs(&trial.levels, side);
2491+ luma.commit(x, y, side, &trial);
2492+ palette = Some(pal);
2493+ }
2494+ }
2495+ if palette.is_none() {
2496+ luma.restore(x, y, side, &kept);
2497+ }
2498+ }
2499+
2352 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both2500 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
2353 // planes; what it costs still counts towards the partition decision.2501 // planes; what it costs still counts towards the partition decision.
2354 let ([u, v], uv_mode, chroma_cost) =2502 let ([u, v], uv_mode, chroma_cost) =
@@ -2362,6 +2510,7 @@ fn code_square(
2362 mode,2510 mode,
2363 uv_mode,2511 uv_mode,
2364 tx_depth,2512 tx_depth,
2513+ palette,
2365 ..BlockCoeffs::default()2514 ..BlockCoeffs::default()
2366 },2515 },
2367 cost,2516 cost,
@@ -2757,6 +2906,7 @@ fn code_square_inter(
2757 uv_mode: DC_PRED,2906 uv_mode: DC_PRED,
2758 skip: skip_new,2907 skip: skip_new,
2759 eight: None,2908 eight: None,
2909+ palette: None,
2760 tx_depth,2910 tx_depth,
2761 inter: Some(InterInfo {2911 inter: Some(InterInfo {
2762 ref_frame: crate::mvstack::LAST_FRAME,2912 ref_frame: crate::mvstack::LAST_FRAME,
@@ -2791,6 +2941,7 @@ fn code_square_inter(
2791 uv_mode: DC_PRED,2941 uv_mode: DC_PRED,
2792 skip,2942 skip,
2793 eight: None,2943 eight: None,
2944+ palette: None,
2794 tx_depth,2945 tx_depth,
2795 inter: Some(InterInfo {2946 inter: Some(InterInfo {
2796 ref_frame: crate::mvstack::LAST_FRAME,2947 ref_frame: crate::mvstack::LAST_FRAME,
@@ -2906,6 +3057,9 @@ fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
2906 3057
2907 /// What the luma mode search picks between, and under what terms.3058 /// What the luma mode search picks between, and under what terms.
2908 struct Search<'a> {3059 struct Search<'a> {
3060+ /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
3061+ /// luma search then offers a palette candidate beside the intra modes.
3062+ screen: bool,
2909 base_q_idx: u8,3063 base_q_idx: u8,
2910 deadzone: f64,3064 deadzone: f64,
2911 lambda: f64,3065 lambda: f64,
@@ -3257,6 +3411,7 @@ pub(crate) fn encode_key_frame_inner(
3257 lambda: lambda_scale() * step * step,3411 lambda: lambda_scale() * step * step,
3258 modes,3412 modes,
3259 top_k: prune_top_k(),3413 top_k: prune_top_k(),
3414+ screen,
3260 };3415 };
3261 3416
3262 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s3417 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
@@ -4446,6 +4601,7 @@ fn search_inter_block(
4446 skip: best.skip,4601 skip: best.skip,
4447 inter: best.inter,4602 inter: best.inter,
4448 eight: None,4603 eight: None,
4604+ palette: None,
4449 tx_depth: 0,4605 tx_depth: 0,
4450 },4606 },
4451 best.cost,4607 best.cost,
@@ -4618,6 +4774,9 @@ pub(crate) fn encode_inter_frame(
4618 lambda: lambda_scale() * step * step,4774 lambda: lambda_scale() * step * step,
4619 modes: &KEY_FRAME_MODES,4775 modes: &KEY_FRAME_MODES,
4620 top_k: prune_top_k_inter(),4776 top_k: prune_top_k_inter(),
4777+ // An inter frame never sets `allow_screen_content_tools` yet, so its
4778+ // intra blocks code no palette syntax (deferred, see the lane report).
4779+ screen: false,
4621 };4780 };
4622 let mode_bits_table = inter_mode_bits();4781 let mode_bits_table = inter_mode_bits();
4623 4782
@@ -5667,6 +5826,68 @@ mod tests {
5667 );5826 );
5668 }5827 }
5669 5828
5829+ /// A synthetic screen-content picture -- a few flat colours in a grid of
5830+ /// boxes with hard edges and text-like bars, the shape a desktop capture
5831+ /// has -- so the palette path is exercised on content it is for.
5832+ #[cfg(test)]
5833+ fn screen_card(width: usize, height: usize) -> Picture {
5834+ const INK: [u16; 4] = [16, 90, 180, 235];
5835+ let mut picture = Picture::grey(width, height);
5836+ for y in 0..height {
5837+ for x in 0..width {
5838+ let cell = (x / 24 + y / 24) % 2;
5839+ let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
5840+ picture.y[y * width + x] = INK[cell * 2 + bar];
5841+ }
5842+ }
5843+ for y in 0..height / 2 {
5844+ for x in 0..width / 2 {
5845+ let cell = (x / 12 + y / 12) % 2;
5846+ picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 };
5847+ picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 };
5848+ }
5849+ }
5850+ picture
5851+ }
5852+
5853+ /// The lane's own end-to-end check: on screen content the detector fires,
5854+ /// blocks really take a palette (fire count, class
5855+ /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
5856+ /// symbol this lane writes -- reconstructs exactly what the encoder did.
5857+ /// The film-shaped `test_card` must NOT trip the detector, which is what
5858+ /// keeps every non-screen stream byte-identical.
5859+ #[test]
5860+ fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
5861+ let fctx = &crate::decode::FrameCtx::new();
5862+ let (width, height) = (192usize, 96usize);
5863+ let _ = crate::tile::take_palette_hits();
5864+ let picture = screen_card(width, height);
5865+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
5866+ assert!(
5867+ encoded.screen,
5868+ "the detector did not fire on screen content -- no palette syntax was coded at all"
5869+ );
5870+ let hits = crate::tile::take_palette_hits();
5871+ assert!(hits[0] > 0, "no block took a palette: {hits:?}");
5872+ eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
5873+ let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
5874+ assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
5875+ assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
5876+ assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
5877+ if !have_ffmpeg() {
5878+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
5879+ return;
5880+ }
5881+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
5882+ assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
5883+ assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
5884+ assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
5885+ // The other half of the keep rule: film-shaped content leaves the
5886+ // detector (and so the whole sequence header) alone.
5887+ let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
5888+ assert!(!film.screen, "the detector fired on the film-shaped test card");
5889+ }
5890+
5670 /// The minimal repro that isolated the inter-residual desync: a key frame5891 /// The minimal repro that isolated the inter-residual desync: a key frame
5671 /// followed by one inter frame whose single superblock carries one5892 /// followed by one inter frame whose single superblock carries one
5672 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma5893 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
@@ -5703,6 +5924,7 @@ mod tests {
5703 uv_mode: 0,5924 uv_mode: 0,
5704 skip: false,5925 skip: false,
5705 eight: None,5926 eight: None,
5927+ palette: None,
5706 tx_depth: 0,5928 tx_depth: 0,
5707 inter: Some(InterInfo {5929 inter: Some(InterInfo {
5708 ref_frame: crate::mvstack::LAST_FRAME,5930 ref_frame: crate::mvstack::LAST_FRAME,
@@ -8289,6 +8511,10 @@ mod tests {
8289 let fctx = &crate::decode::FrameCtx::new();8511 let fctx = &crate::decode::FrameCtx::new();
8290 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);8512 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
8291 let _ = take_partition_hits();8513 let _ = take_partition_hits();
8514+ let _ = crate::tile::take_palette_hits();
8515+ SCREEN_FRAMES.iter().for_each(|c| {
8516+ c.store(0, std::sync::atomic::Ordering::Relaxed);
8517+ });
8292 let _ = take_uv_mode_hits();8518 let _ = take_uv_mode_hits();
8293 let _ = crate::tile::take_inter_mode_hits();8519 let _ = crate::tile::take_inter_mode_hits();
8294 let _ = crate::tile::take_drl_hits();8520 let _ = crate::tile::take_drl_hits();
@@ -8408,6 +8634,22 @@ mod tests {
8408 // Which chroma modes the search actually wins with, against the8634 // Which chroma modes the search actually wins with, against the
8409 // unconditional DC_PRED that was the only outcome before8635 // unconditional DC_PRED that was the only outcome before
8410 // (gate-blind-to-feature).8636 // (gate-blind-to-feature).
8637+ // Screen-content detection and the palette it turns on
8638+ // (gate-blind-to-feature): how many frames set
8639+ // `allow_screen_content_tools`, how many blocks took a palette,
8640+ // and of what size. A film clip must print `screen frames on=0`.
8641+ let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
8642+ let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
8643+ let palette = crate::tile::take_palette_hits();
8644+ eprintln!(
8645+ "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
8646+ palette[0],
8647+ (2..=8)
8648+ .filter(|&n| palette[n] > 0)
8649+ .map(|n| format!("{n}={}", palette[n]))
8650+ .collect::<Vec<_>>()
8651+ .join(" ")
8652+ );
8411 let uv = take_uv_mode_hits();8653 let uv = take_uv_mode_hits();
8412 let uv_total: usize = uv.iter().sum();8654 let uv_total: usize = uv.iter().sum();
8413 eprintln!(8655 eprintln!(
crates/ec-av1/src/tile.rsmodified+298 -8
@@ -673,6 +673,13 @@ pub struct BlockCoeffs {
673 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s673 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
674 /// per-quadrant fields are unused.674 /// per-quadrant fields are unused.
675 pub eight: Option<Vec<BlockCoeffs>>,675 pub eight: Option<Vec<BlockCoeffs>>,
676+ /// The luma palette this block is predicted with (spec 5.11.46
677+ /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
678+ /// `DC_PRED` block on a frame whose header set
679+ /// `allow_screen_content_tools` may carry one, and it forces
680+ /// `tx_depth` to zero (the whole block is one transform over the
681+ /// palette's own prediction).
682+ pub palette: Option<PaletteY>,
676 /// How many times this block's luma transform is halved under683 /// How many times this block's luma transform is halved under
677 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole684 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
678 /// block). Read only by the writers a `tx_select` frame calls; a685 /// block). Read only by the writers a `tx_select` frame calls; a
@@ -682,6 +689,20 @@ pub struct BlockCoeffs {
682 pub tx_depth: u8,689 pub tx_depth: u8,
683 }690 }
684 691
692+/// A block's luma palette: its base colours (ascending, only the first
693+/// `size` entries are real) and the per-pixel colour-index map, `side*side`
694+/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
695+/// out of the stream.
696+#[derive(Clone, Debug, Default, PartialEq, Eq)]
697+pub struct PaletteY {
698+ /// How many base colours, 2..=8 (spec `PaletteSizeY`).
699+ pub size: u8,
700+ /// The base colours, ascending.
701+ pub colors: [u16; 8],
702+ /// Which colour each pixel takes, row-major over the block's own side.
703+ pub map: Vec<u8>,
704+}
705+
685 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole706 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
686 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by707 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
687 /// [`write_inter_mode`] with the decoder's own contexts.708 /// [`write_inter_mode`] with the decoder's own contexts.
@@ -878,6 +899,20 @@ struct Neighbours {
878 above_txfm: Vec<u8>,899 above_txfm: Vec<u8>,
879 /// The same, down the left edge (transform HEIGHT).900 /// The same, down the left edge (transform HEIGHT).
880 left_txfm: Vec<u8>,901 left_txfm: Vec<u8>,
902+ /// The palette size each 4x4 mode-info column last left behind, and its
903+ /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
904+ /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
905+ /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
906+ /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
907+ /// frame writes them, `0` when it took no palette, so a stale size never
908+ /// survives into the next block's context.
909+ above_palette_size: Vec<u8>,
910+ /// The same, down the left edge.
911+ left_palette_size: Vec<u8>,
912+ /// The colours beside [`Self::above_palette_size`].
913+ above_palette_colors: Vec<[u16; 8]>,
914+ /// The same, down the left edge.
915+ left_palette_colors: Vec<[u16; 8]>,
881 /// Whether the neighbour was coded inter, for the `is_inter` context.916 /// Whether the neighbour was coded inter, for the `is_inter` context.
882 /// Unused by the key frame writers.917 /// Unused by the key frame writers.
883 above_inter: Vec<bool>,918 above_inter: Vec<bool>,
@@ -938,6 +973,10 @@ impl Neighbours {
938 left_tx: vec![0; rows * (SUB / MI)],973 left_tx: vec![0; rows * (SUB / MI)],
939 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],974 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
940 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],975 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
976+ above_palette_size: vec![0; cols * (SUB / MI)],
977+ left_palette_size: vec![0; rows * (SUB / MI)],
978+ above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
979+ left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
941 mi_cols,980 mi_cols,
942 mi_rows,981 mi_rows,
943 }982 }
@@ -954,6 +993,82 @@ impl Neighbours {
954 self.left_ref.iter_mut().for_each(|r| *r = -1);993 self.left_ref.iter_mut().for_each(|r| *r = -1);
955 self.left_tx.iter_mut().for_each(|t| *t = 0);994 self.left_tx.iter_mut().for_each(|t| *t = 0);
956 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);995 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
996+ self.left_palette_size.iter_mut().for_each(|s| *s = 0);
997+ }
998+
999+ /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
1000+ /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
1001+ /// `palette_y_mode` context (how many of the two neighbours took a
1002+ /// palette) and the ascending, deduplicated colour cache the neighbours
1003+ /// offer. `mi` is the block's own position in 4x4 units; this writer
1004+ /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
1005+ /// availability terms read against.
1006+ fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
1007+ // `av1_get_palette_cache` drops the above neighbour on a 64-px
1008+ // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
1009+ // not, which is why the two terms below are asked separately.
1010+ let above_ok = r % 16 != 0;
1011+ let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
1012+ let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1013+ (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
1014+ } else {
1015+ (0, [0u16; 8])
1016+ };
1017+ let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
1018+ (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
1019+ } else {
1020+ (0, [0u16; 8])
1021+ };
1022+ let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
1023+ let mut cache = Vec::with_capacity(16);
1024+ let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1025+ if cache.last() != Some(&v) {
1026+ cache.push(v);
1027+ }
1028+ };
1029+ let (mut ai, mut li) = (0usize, 0usize);
1030+ while ai < above_n && li < left_n {
1031+ let (va, vl) = (above_colors[ai], left_colors[li]);
1032+ if vl < va {
1033+ push_dedup(&mut cache, vl);
1034+ li += 1;
1035+ } else {
1036+ push_dedup(&mut cache, va);
1037+ ai += 1;
1038+ if vl == va {
1039+ li += 1;
1040+ }
1041+ }
1042+ }
1043+ while ai < above_n {
1044+ push_dedup(&mut cache, above_colors[ai]);
1045+ ai += 1;
1046+ }
1047+ while li < left_n {
1048+ push_dedup(&mut cache, left_colors[li]);
1049+ li += 1;
1050+ }
1051+ (ctx, cache)
1052+ }
1053+
1054+ /// What a just-written block leaves in the palette bands (decode.rs
1055+ /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
1056+ /// spans, `0` for a block that took no palette.
1057+ fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
1058+ for cell in 0..(side / MI).max(1) {
1059+ if let Some(e) = self.above_palette_size.get_mut(c + cell) {
1060+ *e = size;
1061+ if size > 0 {
1062+ self.above_palette_colors[c + cell] = colors;
1063+ }
1064+ }
1065+ if let Some(e) = self.left_palette_size.get_mut(r + cell) {
1066+ *e = size;
1067+ if size > 0 {
1068+ self.left_palette_colors[r + cell] = colors;
1069+ }
1070+ }
1071+ }
957 }1072 }
958 1073
959 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block1074 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
@@ -1721,6 +1836,130 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
1721 Ok(enc.finish())1836 Ok(enc.finish())
1722 }1837 }
1723 1838
1839+/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
1840+/// which the palette colour-index map's first (context-free) symbol is coded
1841+/// with.
1842+fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
1843+ let l = crate::decode::ceil_log2(n as u32);
1844+ let m = (1usize << l) - n;
1845+ if value < m {
1846+ enc.literal(value as u32, l - 1);
1847+ } else {
1848+ enc.literal(((value + m) >> 1) as u32, l - 1);
1849+ enc.literal(((value + m) & 1) as u32, 1);
1850+ }
1851+}
1852+
1853+/// `write_palette_colors_y` (bitstream.c:1178), the write side of
1854+/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
1855+/// entry (taken when this palette holds that colour, in cache order, stopping
1856+/// once `n` are cached), then the colours the cache did not supply -- the
1857+/// first raw, the rest as deltas off a bit width that shrinks with the range
1858+/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
1859+/// of the two ascending lists puts it back exactly.
1860+fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
1861+ let n = colors.len();
1862+ let mut cached: Vec<u16> = Vec::with_capacity(n);
1863+ for &c in cache {
1864+ if cached.len() >= n {
1865+ break;
1866+ }
1867+ let take = colors.contains(&c);
1868+ enc.literal(u32::from(take), 1);
1869+ if take {
1870+ cached.push(c);
1871+ }
1872+ }
1873+ let transmitted: Vec<u16> = colors
1874+ .iter()
1875+ .copied()
1876+ .filter(|c| !cached.contains(c))
1877+ .collect();
1878+ if transmitted.is_empty() {
1879+ return;
1880+ }
1881+ enc.literal(u32::from(transmitted[0]), 8);
1882+ if transmitted.len() == 1 {
1883+ return;
1884+ }
1885+ // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
1886+ // under which every delta still fits its (shrinking) width. `extra == 3`
1887+ // always works -- a delta can never exceed the range left -- so the
1888+ // search below always finds one.
1889+ let fits = |extra: u32| -> bool {
1890+ let mut bits = 5 + extra;
1891+ let mut range = 255i32 - i32::from(transmitted[0]);
1892+ for w in transmitted.windows(2) {
1893+ let delta = i32::from(w[1]) - i32::from(w[0]);
1894+ if delta - 1 >= (1i32 << bits) {
1895+ return false;
1896+ }
1897+ range -= delta;
1898+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
1899+ }
1900+ true
1901+ };
1902+ let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
1903+ enc.literal(extra, 2);
1904+ let mut bits = 5 + extra;
1905+ let mut range = 255i32 - i32::from(transmitted[0]);
1906+ for w in transmitted.windows(2) {
1907+ let delta = i32::from(w[1]) - i32::from(w[0]);
1908+ enc.literal((delta - 1) as u32, bits);
1909+ range -= delta;
1910+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
1911+ }
1912+}
1913+
1914+/// `write_palette_color_map` (bitstream.c), the write side of
1915+/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
1916+/// each symbol written as the position its colour takes in the neighbour
1917+/// ordering `av1_get_palette_color_index_context` hands back.
1918+fn write_color_index_map(
1919+ enc: &mut SymbolEncoder,
1920+ idx_cdfs: &mut [[u16; 9]; 5],
1921+ map: &[u8],
1922+ side: usize,
1923+ n: usize,
1924+) {
1925+ write_uniform(enc, usize::from(map[0]), n);
1926+ for i in 1..(2 * side - 1) {
1927+ for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() {
1928+ let (row, col) = (i - j, j);
1929+ let (ctx, color_order) =
1930+ crate::decode::palette_color_index_context(map, side, row, col, n);
1931+ let want = map[row * side + col];
1932+ let symbol = color_order[..n]
1933+ .iter()
1934+ .position(|&c| c == want)
1935+ .expect("every colour index is in the block\'s own palette");
1936+ enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
1937+ }
1938+ }
1939+}
1940+
1941+/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
1942+/// the size symbol, the colours and the whole colour-index map, priced
1943+/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
1944+/// search reads the rate the tile will really spend, not an estimate of it.
1945+/// The neighbour cache is taken as empty (the search runs before the tile
1946+/// knows what its neighbours will be), which only ever over-prices.
1947+pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
1948+ let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
1949+ return f64::INFINITY;
1950+ };
1951+ let n = usize::from(pal.size);
1952+ let mut enc = SymbolEncoder::pricer();
1953+ let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
1954+ enc.symbol(1, &mut mode_cdf);
1955+ let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
1956+ enc.symbol(n - 2, &mut size_cdf);
1957+ write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
1958+ let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
1959+ write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n);
1960+ enc.bits()
1961+}
1962+
1724 /// Writes everything a key frame's block carries before its coefficients: the1963 /// Writes everything a key frame's block carries before its coefficients: the
1725 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,1964 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
1726 /// the angle a directional mode is steered by, and its chroma mode. Hands back1965 /// 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(
1728 fn write_intra_mode(1967 fn write_intra_mode(
1729 enc: &mut SymbolEncoder,1968 enc: &mut SymbolEncoder,
1730 cdfs: &mut Cdfs,1969 cdfs: &mut Cdfs,
1970+ neighbours: &mut Neighbours,
1731 block: &BlockCoeffs,1971 block: &BlockCoeffs,
1732 above_mode: usize,1972 above_mode: usize,
1733 left_mode: usize,1973 left_mode: usize,
@@ -1770,19 +2010,67 @@ fn write_intra_mode(
1770 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer2010 // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
1771 // codes none -- exactly the ctx-0 read the decoder does under the same2011 // codes none -- exactly the ctx-0 read the decoder does under the same
1772 // condition.2012 // condition.
1773- if screen_armed()2013+ if screen_armed() {
1774- && let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side)2014+ let palette = block.palette.as_ref().filter(|_| mode == DC_PRED);
1775- {2015+ if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
2016+ let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
1776 if mode == DC_PRED {2017 if mode == DC_PRED {
1777- enc.symbol(0, &mut cdfs.palette_y_mode[bsize_ctx][0]);2018+ enc.symbol(
2019+ usize::from(palette.is_some()),
2020+ &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
2021+ );
1778 }2022 }
2023+ if let Some(pal) = palette {
2024+ let n = usize::from(pal.size);
2025+ enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
2026+ write_palette_colors_y(enc, &pal.colors[..n], &cache);
2027+ }
2028+ // `read_palette_mode_info`'s UV half sits between the luma
2029+ // colours and the luma colour-index map: libaom defers both maps
2030+ // to `av1_visit_palette`, after the whole mode info.
1779 if uv_mode == DC_PRED {2031 if uv_mode == DC_PRED {
1780- enc.symbol(0, &mut cdfs.palette_uv_mode[0]);2032+ enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]);
2033+ }
2034+ if let Some(pal) = palette {
2035+ let n = usize::from(pal.size);
2036+ write_color_index_map(
2037+ enc,
2038+ &mut cdfs.palette_y_color_index[n - 2],
2039+ &pal.map,
2040+ side,
2041+ n,
2042+ );
2043+ note_palette(n);
2044+ }
1781 }2045 }
2046+ // Every block of a screen-content frame publishes its (possibly zero)
2047+ // palette state, or a neighbour column keeps an earlier block's size
2048+ // and reads a context the decoder does not.
2049+ let (size, colors) =
2050+ palette.map_or((0, [0u16; 8]), |p| (p.size, p.colors));
2051+ neighbours.record_palette_y(mi, side, size, colors);
1782 }2052 }
1783 mode2053 mode
1784 }2054 }
1785 2055
2056+/// How many blocks took a palette, and of what size -- the fire count a gate
2057+/// prints so that "palette is on" is a measurement rather than a claim
2058+/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
2059+/// per-size histogram.
2060+static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
2061+ [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
2062+
2063+fn note_palette(n: usize) {
2064+ PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2065+ PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2066+}
2067+
2068+/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
2069+/// its own encode.
2070+pub(crate) fn take_palette_hits() -> [usize; 9] {
2071+ std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2072+}
2073+
1786 /// Writes one coded block: its mode, its three transform blocks, and what it2074 /// Writes one coded block: its mode, its three transform blocks, and what it
1787 /// leaves behind for the blocks beside it. Its partition symbol is already2075 /// leaves behind for the blocks beside it. Its partition symbol is already
1788 /// written, because only the caller knows what tree led here.2076 /// written, because only the caller knows what tree led here.
@@ -1807,12 +2095,14 @@ fn write_block(
1807 ) -> Result<()> {2095 ) -> Result<()> {
1808 let (r, c) = at;2096 let (r, c) = at;
1809 let at_mi = (r * (SUB / MI), c * (SUB / MI));2097 let at_mi = (r * (SUB / MI), c * (SUB / MI));
2098+ let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
1810 let mode = write_intra_mode(2099 let mode = write_intra_mode(
1811 enc,2100 enc,
1812 cdfs,2101 cdfs,
2102+ neighbours,
1813 block,2103 block,
1814- neighbours.above_mode[c],2104+ above_mode,
1815- neighbours.left_mode[r],2105+ left_mode,
1816 cfl,2106 cfl,
1817 at_mi,2107 at_mi,
1818 side,2108 side,
@@ -1890,7 +2180,7 @@ fn write_leaf8(
1890 // true first divergence (a differently-sized alphabet under the same2180 // true first divergence (a differently-sized alphabet under the same
1891 // DC_PRED decision desyncs the coder even though the decoded mode is2181 // DC_PRED decision desyncs the coder even though the decoded mode is
1892 // unchanged).2182 // unchanged).
1893- let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi, 8);2183+ let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8);
1894 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];2184 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
1895 let split = if tx_select {2185 let split = if tx_select {
1896 let tx = write_luma_select(2186 let tx = write_luma_select(