diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index d7ba733a..fb589431 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -8334,7 +8334,7 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option { /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize] /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise. -fn palette_bsize_ctx(side: usize) -> Option { +pub(crate) fn palette_bsize_ctx(side: usize) -> Option { palette_bsize_ctx_wh(side, side) } @@ -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, @@ -32941,7 +32941,7 @@ pub(crate) fn decode_inter_frame_tile( data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, reference_select, tx_select, - &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, fctx, + &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, fctx, ) } @@ -32976,6 +32976,12 @@ pub(crate) fn decode_inter_frame_tile_lr( // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile // decode has to be told. sign_bias: crate::mvstack::SignBiasTable, + // This frame header's own `allow_screen_content_tools`: its intra blocks + // then carry the palette syntax (spec 5.11.46), which a raw tile decode + // that guessed `false` reads one symbol short of. Placed after + // `sign_bias` rather than beside the other bools on purpose (the + // `adjacent-same-typed-args` class). + allow_screen_content_tools: bool, fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { @@ -33003,6 +33009,7 @@ pub(crate) fn decode_inter_frame_tile_lr( lr, initial_cdfs, sign_bias, + allow_screen_content_tools, fctx, ) } @@ -33030,6 +33037,9 @@ pub(crate) fn decode_inter_frame_tiles_lr( lr: &LoopRestorationParams, initial_cdfs: Option, sign_bias: crate::mvstack::SignBiasTable, + // This frame header's own `allow_screen_content_tools` (see the + // single-tile wrapper): the palette syntax its intra blocks carry. + allow_screen_content_tools: bool, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_with_cdfs( @@ -33066,7 +33076,7 @@ pub(crate) fn decode_inter_frame_tiles_lr( tx_select, false, false, - false, + allow_screen_content_tools, DeltaParams::default(), // `enable_filter_intra`: this crate's own encoder never writes the // sequence bit (`encode.rs`), so no intra-in-inter block of a stream @@ -37563,7 +37573,9 @@ mod tests { &key.loop_filter, key.tx_select, true, - false, + // This key frame's own `allow_screen_content_tools`: its intra + // blocks carry the palette syntax under it (stale-header class). + key.screen, false, &key.loop_restoration, fctx, ) @@ -37610,6 +37622,9 @@ mod tests { &frame.loop_restoration, Some(frame.start_cdfs.0.clone()), NO_SIGN_BIAS, + // This frame's own `allow_screen_content_tools`, off the + // `Encoded` the encoder handed back (stale-header class). + frame.screen, fctx, ) .unwrap(); @@ -37898,7 +37913,9 @@ mod tests { &key.loop_filter, key.tx_select, true, - false, + // This key frame's own `allow_screen_content_tools`: its intra + // blocks carry the palette syntax under it (stale-header class). + key.screen, false, &key.loop_restoration, fctx, ) @@ -37934,6 +37951,9 @@ mod tests { &frame.loop_restoration, Some(frame.start_cdfs.0.clone()), NO_SIGN_BIAS, + // This frame's own `allow_screen_content_tools`, off the + // `Encoded` the encoder handed back (stale-header class). + frame.screen, fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index cf518159..918933ea 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -625,6 +625,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En mi_rows: encoded.mi_rows, base_q_idx: encoded.base_q_idx, tx_select: encoded.tx_select, + screen: encoded.screen, start_cdfs: encoded.start_cdfs.clone(), next_cdfs: encoded.next_cdfs.clone(), loop_filter: encoded.loop_filter, @@ -698,6 +699,11 @@ pub struct Encoded { /// This frame header's chosen CDEF parameters, threaded for the same /// reason as `loop_filter`. pub(crate) cdef: CdefParams, + /// This frame header's `allow_screen_content_tools` + /// ([`screen_content`]) -- every intra block of the tile carries the two + /// palette-mode symbols under it, so a raw tile decode that guessed + /// `false` would desync at the first block (same class as `tx_select`). + pub(crate) screen: bool, /// This frame header's chosen loop restoration parameters, threaded for /// the same reason as `loop_filter` -- and doubly so: the per-unit /// filters themselves are coded in `tile`, so a decode of it under a @@ -705,6 +711,121 @@ pub struct Encoded { pub(crate) loop_restoration: LoopRestorationParams, } +thread_local! { + /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence + /// header offers the per-frame `allow_screen_content_tools` bit at all. + /// Armed once by the key frame ([`encode_key_frame_inner`], from + /// [`screen_content`]) and read by every header builder after it, so that + /// the inter frames of a screen sequence lay their headers out the same + /// way the sequence header the key frame wrote says they do -- a per-call + /// parameter would have to thread through `inter_frame_headers`' four + /// public entry points and every hand-built-stream test that calls them. + /// A sequence with no screen content leaves this false and writes exactly + /// the bits it wrote before this lane. + static SEQ_SCREEN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +thread_local! { + /// Overrides [`screen_content`] for the calling thread, which is what the + /// intra-MODE ablations use: on a two-colour synthetic picture the palette + /// codes every block losslessly, so both arms of a mode ablation reach + /// infinite PSNR and the ablation measures nothing at all (the + /// `fixture-proves-the-symbol-not-the-signal` class). An environment + /// variable cannot do this -- the tests run in one process, in parallel. + static SCREEN_FORCE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(crate) fn force_screen(value: Option) { + SCREEN_FORCE.with(|c| c.set(value)); +} + +pub(crate) fn arm_seq_screen(on: bool) { + SEQ_SCREEN.with(|c| c.set(on)); +} + +fn seq_screen() -> bool { + SEQ_SCREEN.with(std::cell::Cell::get) +} + +/// How many distinct colours a 16x16 luma block may hold and still count as +/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own +/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a +/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect` +/// measures the share of 16x16 blocks under each bound on the gate's own +/// three clips, and only at 32 do the populations part -- film 20.3..21.9%, +/// his OBS capture 51.1..51.5%. +fn screen_colors() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("EC_AV1_SCREEN_COLORS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(32) + }) +} + +/// The reciprocal of the frame area those blocks must cover, in tenths -- +/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one +/// tenth). 3 (a third) is the midpoint of the two populations +/// `probe_screen_detect` measured at the colour bound above. +/// `EC_AV1_SCREEN_PCT`. +fn screen_pct() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("EC_AV1_SCREEN_PCT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(3) + }) +} + +/// How many frames [`screen_content`] said yes/no to, so a gate can print +/// whether the detector fired at all (class `gate-blind-to-feature`). +pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; + +/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count +/// the distinct colours of every 16x16 block and turn the screen-content +/// tools on when the blocks holding between 2 and [`screen_colors`] of them +/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's +/// stride, `true_*` the frame's real (decodable) extent. +fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool { + if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) { + SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return forced; + } + if let Ok(v) = std::env::var("EC_AV1_SCREEN") { + let on = v != "0"; + SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return on; + } + let (blk, limit) = (16usize, screen_colors()); + let mut counted = 0usize; + for by in (0..true_height).step_by(blk) { + for bx in (0..true_width).step_by(blk) { + let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk)); + let mut seen = [false; 256]; + let mut colors = 0usize; + for row in 0..h { + for col in 0..w { + let v = usize::from(y[(by + row) * width + bx + col]); + if !seen[v] { + seen[v] = true; + colors += 1; + } + } + } + if colors > 1 && colors <= limit { + counted += 1; + } + } + } + let on = counted * blk * blk * screen_pct() > true_width * true_height; + SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + on +} + /// The sequence and frame headers a picture of this size is coded under: one /// tile, one transform size per block, no in-loop filter parameters yet /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and @@ -788,7 +909,17 @@ pub(crate) fn key_frame_headers_colour( // CDEF simply carries zero strengths. enable_cdef: true, enable_restoration: true, - seq_force_screen_content_tools: 0, + // SELECT (2) when this sequence's key frame detected screen content + // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit + // is then coded in every frame header, and only the frames that want + // the palette syntax set it. 0 -- the forced-off form, no bit at all + // -- otherwise, which is what every non-screen stream this encoder + // writes still carries. + seq_force_screen_content_tools: if seq_screen() { + ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS + } else { + 0 + }, seq_force_integer_mv: 0, color_config, still_picture: false, @@ -2204,6 +2335,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, @@ -2265,6 +2495,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) = @@ -2278,6 +2557,7 @@ fn code_square( mode, uv_mode, tx_depth, + palette, ..BlockCoeffs::default() }, cost, @@ -2674,6 +2954,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip: skip_new, eight: None, + palette: None, tx_depth, inter: Some(InterInfo { ref1: None, @@ -2710,6 +2991,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip, eight: None, + palette: None, tx_depth, inter: Some(InterInfo { ref1: None, @@ -2841,6 +3123,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, @@ -3241,7 +3526,19 @@ pub(crate) fn encode_key_frame_inner( // `render_and_frame_size_different` is false and no render_size bits are // written, mirroring libaom/rav1e: the padded `picture` below is only the // internal coding surface, never what the header names. + // Screen-content detection runs on the SOURCE luma, before any header is + // built: it decides this sequence's `seq_force_screen_content_tools` (and + // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as + // this frame's own `allow_screen_content_tools`. + let screen = screen_content( + &picture.y.iter().map(|&v| v as u8).collect::>(), + picture.width, + (picture.width).min(render.0), + (picture.height).min(render.1), + ); + arm_seq_screen(screen); let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; + header.allow_screen_content_tools = screen; header.render_width = render.0 as u32; header.render_height = render.1 as u32; // `TxMode::Select`: every block codes a `tx_depth` symbol and may split @@ -3313,6 +3610,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 @@ -3566,6 +3864,7 @@ pub(crate) fn encode_key_frame_inner( crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); let mut cdfs = start_cdfs.0.clone(); + crate::tile::arm_screen(screen); let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, @@ -3645,6 +3944,7 @@ pub(crate) fn encode_key_frame_inner( mi_rows: header.mi_rows, base_q_idx, tx_select, + screen, next_cdfs: start_cdfs.clone(), start_cdfs, loop_filter: header.loop_filter, @@ -4836,6 +5136,7 @@ fn search_inter_block( skip: best.skip, inter: best.inter, eight: None, + palette: None, tx_depth: 0, }, best.cost, @@ -4994,6 +5295,14 @@ pub(crate) fn encode_inter_frame( let picture_y8: Vec = picture.y.iter().map(|&v| v as u8).collect(); let picture_u8: Vec = picture.u.iter().map(|&v| v as u8).collect(); let picture_v8: Vec = picture.v.iter().map(|&v| v as u8).collect(); + // This frame's own `allow_screen_content_tools`. It can only be set when + // the SEQUENCE offers the bit at all, which is the key frame's decision + // ([`SEQ_SCREEN`]): a frame header that contradicts + // `seq_force_screen_content_tools` is a corrupt stream, not a tighter + // encode. + let screen = seq_screen() + && screen_content(&picture_y8, picture.width, true_width, true_height); + header.allow_screen_content_tools = screen; let mut luma = Plane { source: &picture_y8, reconstruction: vec![128; picture_y8.len()], @@ -5040,6 +5349,7 @@ pub(crate) fn encode_inter_frame( lambda: lambda_scale() * step * step, modes: &KEY_FRAME_MODES, top_k: prune_top_k_inter(), + screen, }; let mode_bits_table = inter_mode_bits(); @@ -5533,6 +5843,7 @@ pub(crate) fn encode_inter_frame( // Thread-locals: every tile job arms its own worker. crate::tile::arm_reference_select(reference_select_bit); crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); + crate::tile::arm_screen(screen); let mut cdfs = start_cdfs.0.clone(); // Each tile's own MV grid: a candidate scan never reaches past // the tile's bounds, so a grid holding only this tile's own @@ -5655,6 +5966,7 @@ pub(crate) fn encode_inter_frame( // frame's `start_cdfs`), not from the defaults. Some(start_cdfs.0.clone()), sign_bias, + h.allow_screen_content_tools, fctx, ) }, @@ -5687,6 +5999,7 @@ pub(crate) fn encode_inter_frame( mi_rows: header.mi_rows, base_q_idx, tx_select, + screen, start_cdfs, next_cdfs, loop_filter: header.loop_filter, @@ -6159,6 +6472,116 @@ 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"); + // A whole GOP: the inter frames' own intra blocks carry the palette + // syntax too (the three intra arms of the inter writers), which only + // ffmpeg reading the frames back can prove. + let moved: Vec = (0..4) + .map(|f| { + let base = screen_card(width, height); + let mut out = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let sx = (x + f * 7) % width; + out.y[y * width + x] = base.y[y * width + sx]; + } + } + for y in 0..height / 2 { + for x in 0..width / 2 { + let sx = (x + f * 3) % (width / 2); + out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; + out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; + } + } + out + }) + .collect(); + let _ = crate::tile::take_palette_hits(); + let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); + let gop_hits = crate::tile::take_palette_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] + ); + assert!( + inter_screen > 0, + "no inter frame set allow_screen_content_tools" + ); + let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); + for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { + assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma"); + } + if have_ffmpeg() { + let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); + for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { + assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma"); + assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); + assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} 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 @@ -6195,6 +6618,7 @@ mod tests { uv_mode: 0, skip: false, eight: None, + palette: None, tx_depth: 0, inter: Some(InterInfo { ref1: None, @@ -7060,6 +7484,10 @@ mod tests { /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by /// fidelity. fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { + // A mode ablation measures the MODE search: the palette would code + // these synthetic two-colour pictures losslessly under every arm and + // leave nothing to compare (see [`force_screen`]). + force_screen(Some(false)); let mut points: Vec<(f64, f64)> = [110u8, 90, 70] .iter() .map(|&q| { @@ -7172,6 +7600,10 @@ mod tests { /// The mode picked by the most blocks of a picture, ignoring the first /// block, which has no neighbours to tell the modes apart with. fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { + // A mode ablation measures the MODE search: the palette would code + // these synthetic two-colour pictures losslessly under every arm and + // leave nothing to compare (see [`force_screen`]). + force_screen(Some(false)); let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); let blocks = &encoded.modes[1..]; let mut counts = [0usize; 13]; @@ -8655,6 +9087,71 @@ mod tests { } } + /// The sweep behind [`screen_content`]'s two constants + /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at + /// most N distinct colours, per gate clip, at the size the gate codes. + /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture` + #[test] + #[ignore = "reads the real library"] + fn probe_screen_detect() { + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); + let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); + for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] { + let path = fixtures.join("video").join(name); + if path.exists() { + clips.push((name.to_string(), path)); + } + } + if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) + && let Some(p) = manifest + .lines() + .skip(1) + .filter_map(|l| l.split('\t').next()) + .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) + { + clips.push(("screen".to_string(), std::path::PathBuf::from(p))); + } + let (width, height) = (640usize, 384usize); + for (name, path) in &clips { + let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4); + for (f, picture) in frames.iter().enumerate() { + let y: Vec = picture.y.iter().map(|&v| v as u8).collect(); + let mut hist = [0usize; 257]; + let mut blocks = 0usize; + for by in (0..height).step_by(16) { + for bx in (0..width).step_by(16) { + let mut seen = [false; 256]; + let mut colors = 0usize; + for row in 0..16 { + for col in 0..16 { + let v = usize::from(y[(by + row) * width + bx + col]); + if !seen[v] { + seen[v] = true; + colors += 1; + } + } + } + hist[colors] += 1; + blocks += 1; + } + } + let share = |limit: usize| { + 100.0 * hist[2..=limit.min(256)].iter().sum::() as f64 + / blocks.max(1) as f64 + }; + eprintln!( + "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%", + share(4), + share(8), + share(16), + share(32), + share(64), + share(128), + ); + } + } + } + /// The missing instrument: what this encoder costs against libaom and /// rav1e at matched fidelity, and how long it takes to get there. /// @@ -8793,6 +9290,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(); @@ -8931,6 +9432,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/stream.rs b/crates/ec-av1/src/stream.rs index 56316bde..bebdcd5d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -2999,7 +2999,12 @@ pub(crate) mod tests { encoded.tx_select, // Our own encoder always writes `reduced_tx_set: true`. true, - false, + // `allow_screen_content_tools` off the frame the encoder + // actually wrote: a screen-content picture codes two palette + // symbols per intra block, and a raw tile decode that guessed + // `false` desyncs at the first one (class: test asserts + // against a stale header). + encoded.screen, false, &encoded.loop_restoration, fctx, ) diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 866b467e..79db85df 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -304,6 +304,25 @@ pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) { SIGN_BIAS.with(|c| c.set(sign_bias)); } +thread_local! { + static SCREEN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Arms the next tile write with this frame's `allow_screen_content_tools` +/// (spec 5.9.2), which is what makes every intra block carry the +/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46 +/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/ +/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that +/// never detected screen content writes exactly the stream it wrote before +/// this lane. +pub(crate) fn arm_screen(on: bool) { + SCREEN.with(|c| c.set(on)); +} + +fn screen_armed() -> bool { + SCREEN.with(std::cell::Cell::get) +} + thread_local! { /// This frame header's own `reference_select` bit (spec 5.9.22), armed /// the same way `arm_sign_bias` arms the sign-bias table rather than @@ -661,6 +680,7 @@ impl Drop for CdefIdxGuard { CDEF_IDX.with(|c| *c.borrow_mut() = None); LR_PLAN.with(|c| *c.borrow_mut() = None); SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS)); + SCREEN.with(|c| c.set(false)); REFERENCE_SELECT.with(|c| c.set(false)); ORDER_HINTS.with(|c| c.set((7, 0, [0; 7]))); } @@ -1148,6 +1168,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 @@ -1157,6 +1184,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. @@ -1404,6 +1445,27 @@ 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, + /// What the block being written right now will leave in the two palette + /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY + /// block of either frame type passes through, so an inter block (or an + /// intra block that took no palette) clears the bands rather than letting + /// an earlier palette block's size stand (the neighbour-band hazard + /// lane-t900 r23 hit on the decoder side). + pending_palette: Option<(u8, [u16; 8])>, + /// 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, @@ -1489,6 +1551,11 @@ 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)], + pending_palette: None, + above_palette_colors: vec![[0; 8]; cols * (SUB / MI)], + left_palette_colors: vec![[0; 8]; rows * (SUB / MI)], mi_cols, mi_rows, } @@ -1525,6 +1592,82 @@ impl Neighbours { self.left_compound_idx.iter_mut().for_each(|r| *r = 0); 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 @@ -1672,6 +1815,10 @@ impl Neighbours { luma: bool, ) { let (mi_r, mi_c) = at_mi; + 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 states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); let side_mi = side / MI; for cell in 0..side_mi { @@ -2368,6 +2515,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 @@ -2375,6 +2646,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, @@ -2382,6 +2654,9 @@ fn write_intra_mode( // This block's own position in 4x4 mode-info units, for the `cdef_idx` // literal that follows the `skip` symbol (see [`write_cdef_idx`]). mi: (usize, usize), + // The block's side in samples, which gates the palette syntax below + // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]). + side: usize, ) -> usize { let mode = usize::from(block.mode); enc.symbol(0, &mut cdfs.skip[0]); @@ -2407,9 +2682,89 @@ fn write_intra_mode( if (V_PRED..=D67_PRED).contains(&uv_mode) { enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]); } + // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from + // the decoder's own read in `read_intra_mode`: on a frame whose header set + // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED` + // chroma pair each carry a use-palette flag. Both contexts are 0 here -- + // `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); mode } +/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for +/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose +/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a +/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette +/// then codes its size, its colours (against the neighbour colour cache) and +/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs +/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and +/// by the three intra arms of the inter-frame writers, which read the same +/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`. +/// +/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the +/// one point every block passes through), so a block that takes no palette +/// still clears what the column held. +#[allow(clippy::too_many_arguments)] +fn write_palette_syntax( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + palette: Option<&PaletteY>, + mode: usize, + uv_mode: usize, + mi: (usize, usize), + side: usize, +) { + if !screen_armed() { + return; + } + let palette = palette.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); + } + 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); + } + } + neighbours.pending_palette = palette.map(|p| (p.size, p.colors)); +} + +/// 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. +#[cfg(test)] +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. @@ -2434,14 +2789,17 @@ 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, ); let split = if tx_select { let tx = write_luma_select( @@ -2516,7 +2874,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); + 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( @@ -4318,6 +4676,16 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( // Intra: no vote, but still a coded cell -- mvstack's // extended-scan coverage must see it (module doc). let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); + write_palette_syntax( + &mut enc, + &mut cdfs, + &mut neighbours, + block.palette.as_ref(), + mode, + uv_mode, + (mi_row, mi_col), + BLOCK, + ); for dr in 0..8 { for dc in 0..8 { grid.set( @@ -4531,6 +4899,16 @@ fn write_inter_frame_leaf( // Intra: no vote, but still a coded cell -- mvstack's extended-scan // coverage must see it (module doc). let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + write_palette_syntax( + enc, + cdfs, + neighbours, + block.palette.as_ref(), + mode, + uv_mode, + (mi_row, mi_col), + SUB, + ); for dr in 0..SUB_MI as usize { for dc in 0..SUB_MI as usize { grid.set( @@ -4750,6 +5128,16 @@ fn write_inter_frame_leaf8( // Intra: no vote, but still a coded cell -- mvstack's extended-scan // coverage must see it (module doc). let (mi_row, mi_col) = leaf_mi; + write_palette_syntax( + enc, + cdfs, + neighbours, + block.palette.as_ref(), + mode, + uv_mode, + leaf_mi, + 8, + ); for dr in 0..2 { for dc in 0..2 { grid.set(