forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1pal' (0966e6d6): screen-content detection and luma palette coding on key and inter frames

Browse files at this commit

93f25fe6f2fa6efe13fb68fdc37e5458409db5bdAhmet Kaan GümüşParent: b58ff3fbd0a799
Screen BD vs libaom +73.0 -> +66.4, vs rav1e +13.7 -> +10.3; both film
clips byte-identical (detector off there; libaom's 4-colour bound separates
nothing on real material, 32 colours over a third of the frame does).
crates/ec-av1/src/decode.rsmodified+27 -7
@@ -8334,7 +8334,7 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
8334 /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]8334 /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
8335 /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past8335 /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
8336 /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.8336 /// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
8337-fn palette_bsize_ctx(side: usize) -> Option<usize> {8337+pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
8338 palette_bsize_ctx_wh(side, side)8338 palette_bsize_ctx_wh(side, side)
8339 }8339 }
8340 8340
@@ -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,
@@ -32941,7 +32941,7 @@ pub(crate) fn decode_inter_frame_tile(
32941 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,32941 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef,
32942 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,32942 loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed,
32943 enable_dual_filter, reference_select, tx_select,32943 enable_dual_filter, reference_select, tx_select,
32944- &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, fctx,32944+ &LoopRestorationParams::default(), initial_cdfs, NO_SIGN_BIAS, false, fctx,
32945 )32945 )
32946 }32946 }
32947 32947
@@ -32976,6 +32976,12 @@ pub(crate) fn decode_inter_frame_tile_lr(
32976 // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile32976 // as `tx_select`/`initial_cdfs` above: a header-derived value a raw tile
32977 // decode has to be told.32977 // decode has to be told.
32978 sign_bias: crate::mvstack::SignBiasTable,32978 sign_bias: crate::mvstack::SignBiasTable,
32979+ // This frame header's own `allow_screen_content_tools`: its intra blocks
32980+ // then carry the palette syntax (spec 5.11.46), which a raw tile decode
32981+ // that guessed `false` reads one symbol short of. Placed after
32982+ // `sign_bias` rather than beside the other bools on purpose (the
32983+ // `adjacent-same-typed-args` class).
32984+ allow_screen_content_tools: bool,
32979 fctx: &crate::decode::FrameCtx,32985 fctx: &crate::decode::FrameCtx,
32980 ) -> Result<Picture> {32986 ) -> Result<Picture> {
32981 let single_tile = TileInfo {32987 let single_tile = TileInfo {
@@ -33003,6 +33009,7 @@ pub(crate) fn decode_inter_frame_tile_lr(
33003 lr,33009 lr,
33004 initial_cdfs,33010 initial_cdfs,
33005 sign_bias,33011 sign_bias,
33012+ allow_screen_content_tools,
33006 fctx,33013 fctx,
33007 )33014 )
33008 }33015 }
@@ -33030,6 +33037,9 @@ pub(crate) fn decode_inter_frame_tiles_lr(
33030 lr: &LoopRestorationParams,33037 lr: &LoopRestorationParams,
33031 initial_cdfs: Option<Cdfs>,33038 initial_cdfs: Option<Cdfs>,
33032 sign_bias: crate::mvstack::SignBiasTable,33039 sign_bias: crate::mvstack::SignBiasTable,
33040+ // This frame header's own `allow_screen_content_tools` (see the
33041+ // single-tile wrapper): the palette syntax its intra blocks carry.
33042+ allow_screen_content_tools: bool,
33033 fctx: &crate::decode::FrameCtx,33043 fctx: &crate::decode::FrameCtx,
33034 ) -> Result<Picture> {33044 ) -> Result<Picture> {
33035 decode_inter_frame_tile_with_cdfs(33045 decode_inter_frame_tile_with_cdfs(
@@ -33066,7 +33076,7 @@ pub(crate) fn decode_inter_frame_tiles_lr(
33066 tx_select,33076 tx_select,
33067 false,33077 false,
33068 false,33078 false,
33069- false,33079+ allow_screen_content_tools,
33070 DeltaParams::default(),33080 DeltaParams::default(),
33071 // `enable_filter_intra`: this crate's own encoder never writes the33081 // `enable_filter_intra`: this crate's own encoder never writes the
33072 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream33082 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
@@ -37563,7 +37573,9 @@ mod tests {
37563 &key.loop_filter,37573 &key.loop_filter,
37564 key.tx_select,37574 key.tx_select,
37565 true,37575 true,
37566- false,37576+ // This key frame's own `allow_screen_content_tools`: its intra
37577+ // blocks carry the palette syntax under it (stale-header class).
37578+ key.screen,
37567 false,37579 false,
37568 &key.loop_restoration, fctx,37580 &key.loop_restoration, fctx,
37569 )37581 )
@@ -37610,6 +37622,9 @@ mod tests {
37610 &frame.loop_restoration,37622 &frame.loop_restoration,
37611 Some(frame.start_cdfs.0.clone()),37623 Some(frame.start_cdfs.0.clone()),
37612 NO_SIGN_BIAS,37624 NO_SIGN_BIAS,
37625+ // This frame's own `allow_screen_content_tools`, off the
37626+ // `Encoded` the encoder handed back (stale-header class).
37627+ frame.screen,
37613 fctx,37628 fctx,
37614 )37629 )
37615 .unwrap();37630 .unwrap();
@@ -37898,7 +37913,9 @@ mod tests {
37898 &key.loop_filter,37913 &key.loop_filter,
37899 key.tx_select,37914 key.tx_select,
37900 true,37915 true,
37901- false,37916+ // This key frame's own `allow_screen_content_tools`: its intra
37917+ // blocks carry the palette syntax under it (stale-header class).
37918+ key.screen,
37902 false,37919 false,
37903 &key.loop_restoration, fctx,37920 &key.loop_restoration, fctx,
37904 )37921 )
@@ -37934,6 +37951,9 @@ mod tests {
37934 &frame.loop_restoration,37951 &frame.loop_restoration,
37935 Some(frame.start_cdfs.0.clone()),37952 Some(frame.start_cdfs.0.clone()),
37936 NO_SIGN_BIAS,37953 NO_SIGN_BIAS,
37954+ // This frame's own `allow_screen_content_tools`, off the
37955+ // `Encoded` the encoder handed back (stale-header class).
37956+ frame.screen,
37937 fctx,37957 fctx,
37938 )37958 )
37939 .unwrap();37959 .unwrap();
crates/ec-av1/src/encode.rsmodified+518 -1
@@ -625,6 +625,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
625 mi_rows: encoded.mi_rows,625 mi_rows: encoded.mi_rows,
626 base_q_idx: encoded.base_q_idx,626 base_q_idx: encoded.base_q_idx,
627 tx_select: encoded.tx_select,627 tx_select: encoded.tx_select,
628+ screen: encoded.screen,
628 start_cdfs: encoded.start_cdfs.clone(),629 start_cdfs: encoded.start_cdfs.clone(),
629 next_cdfs: encoded.next_cdfs.clone(),630 next_cdfs: encoded.next_cdfs.clone(),
630 loop_filter: encoded.loop_filter,631 loop_filter: encoded.loop_filter,
@@ -698,6 +699,11 @@ pub struct Encoded {
698 /// This frame header's chosen CDEF parameters, threaded for the same699 /// This frame header's chosen CDEF parameters, threaded for the same
699 /// reason as `loop_filter`.700 /// reason as `loop_filter`.
700 pub(crate) cdef: CdefParams,701 pub(crate) cdef: CdefParams,
702+ /// This frame header's `allow_screen_content_tools`
703+ /// ([`screen_content`]) -- every intra block of the tile carries the two
704+ /// palette-mode symbols under it, so a raw tile decode that guessed
705+ /// `false` would desync at the first block (same class as `tx_select`).
706+ pub(crate) screen: bool,
701 /// This frame header's chosen loop restoration parameters, threaded for707 /// This frame header's chosen loop restoration parameters, threaded for
702 /// the same reason as `loop_filter` -- and doubly so: the per-unit708 /// the same reason as `loop_filter` -- and doubly so: the per-unit
703 /// filters themselves are coded in `tile`, so a decode of it under a709 /// filters themselves are coded in `tile`, so a decode of it under a
@@ -705,6 +711,121 @@ pub struct Encoded {
705 pub(crate) loop_restoration: LoopRestorationParams,711 pub(crate) loop_restoration: LoopRestorationParams,
706 }712 }
707 713
714+thread_local! {
715+ /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
716+ /// header offers the per-frame `allow_screen_content_tools` bit at all.
717+ /// Armed once by the key frame ([`encode_key_frame_inner`], from
718+ /// [`screen_content`]) and read by every header builder after it, so that
719+ /// the inter frames of a screen sequence lay their headers out the same
720+ /// way the sequence header the key frame wrote says they do -- a per-call
721+ /// parameter would have to thread through `inter_frame_headers`' four
722+ /// public entry points and every hand-built-stream test that calls them.
723+ /// A sequence with no screen content leaves this false and writes exactly
724+ /// the bits it wrote before this lane.
725+ static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
726+}
727+
728+thread_local! {
729+ /// Overrides [`screen_content`] for the calling thread, which is what the
730+ /// intra-MODE ablations use: on a two-colour synthetic picture the palette
731+ /// codes every block losslessly, so both arms of a mode ablation reach
732+ /// infinite PSNR and the ablation measures nothing at all (the
733+ /// `fixture-proves-the-symbol-not-the-signal` class). An environment
734+ /// variable cannot do this -- the tests run in one process, in parallel.
735+ static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
736+}
737+
738+#[cfg(test)]
739+pub(crate) fn force_screen(value: Option<bool>) {
740+ SCREEN_FORCE.with(|c| c.set(value));
741+}
742+
743+pub(crate) fn arm_seq_screen(on: bool) {
744+ SEQ_SCREEN.with(|c| c.set(on));
745+}
746+
747+fn seq_screen() -> bool {
748+ SEQ_SCREEN.with(std::cell::Cell::get)
749+}
750+
751+/// How many distinct colours a 16x16 luma block may hold and still count as
752+/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
753+/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a
754+/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect`
755+/// measures the share of 16x16 blocks under each bound on the gate's own
756+/// three clips, and only at 32 do the populations part -- film 20.3..21.9%,
757+/// his OBS capture 51.1..51.5%.
758+fn screen_colors() -> usize {
759+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
760+ *N.get_or_init(|| {
761+ std::env::var("EC_AV1_SCREEN_COLORS")
762+ .ok()
763+ .and_then(|v| v.parse().ok())
764+ .unwrap_or(32)
765+ })
766+}
767+
768+/// The reciprocal of the frame area those blocks must cover, in tenths --
769+/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one
770+/// tenth). 3 (a third) is the midpoint of the two populations
771+/// `probe_screen_detect` measured at the colour bound above.
772+/// `EC_AV1_SCREEN_PCT`.
773+fn screen_pct() -> usize {
774+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
775+ *N.get_or_init(|| {
776+ std::env::var("EC_AV1_SCREEN_PCT")
777+ .ok()
778+ .and_then(|v| v.parse().ok())
779+ .unwrap_or(3)
780+ })
781+}
782+
783+/// How many frames [`screen_content`] said yes/no to, so a gate can print
784+/// whether the detector fired at all (class `gate-blind-to-feature`).
785+pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
786+ [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
787+
788+/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
789+/// the distinct colours of every 16x16 block and turn the screen-content
790+/// tools on when the blocks holding between 2 and [`screen_colors`] of them
791+/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's
792+/// stride, `true_*` the frame's real (decodable) extent.
793+fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
794+ if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
795+ SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
796+ return forced;
797+ }
798+ if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
799+ let on = v != "0";
800+ SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
801+ return on;
802+ }
803+ let (blk, limit) = (16usize, screen_colors());
804+ let mut counted = 0usize;
805+ for by in (0..true_height).step_by(blk) {
806+ for bx in (0..true_width).step_by(blk) {
807+ let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
808+ let mut seen = [false; 256];
809+ let mut colors = 0usize;
810+ for row in 0..h {
811+ for col in 0..w {
812+ let v = usize::from(y[(by + row) * width + bx + col]);
813+ if !seen[v] {
814+ seen[v] = true;
815+ colors += 1;
816+ }
817+ }
818+ }
819+ if colors > 1 && colors <= limit {
820+ counted += 1;
821+ }
822+ }
823+ }
824+ let on = counted * blk * blk * screen_pct() > true_width * true_height;
825+ SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
826+ on
827+}
828+
708 /// The sequence and frame headers a picture of this size is coded under: one829 /// The sequence and frame headers a picture of this size is coded under: one
709 /// tile, one transform size per block, no in-loop filter parameters yet830 /// tile, one transform size per block, no in-loop filter parameters yet
710 /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and831 /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
@@ -788,7 +909,17 @@ pub(crate) fn key_frame_headers_colour(
788 // CDEF simply carries zero strengths.909 // CDEF simply carries zero strengths.
789 enable_cdef: true,910 enable_cdef: true,
790 enable_restoration: true,911 enable_restoration: true,
791- seq_force_screen_content_tools: 0,912+ // SELECT (2) when this sequence's key frame detected screen content
913+ // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
914+ // is then coded in every frame header, and only the frames that want
915+ // the palette syntax set it. 0 -- the forced-off form, no bit at all
916+ // -- otherwise, which is what every non-screen stream this encoder
917+ // writes still carries.
918+ seq_force_screen_content_tools: if seq_screen() {
919+ ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
920+ } else {
921+ 0
922+ },
792 seq_force_integer_mv: 0,923 seq_force_integer_mv: 0,
793 color_config,924 color_config,
794 still_picture: false,925 still_picture: false,
@@ -2204,6 +2335,105 @@ fn commit_inter_luma(
2204 (flat.levels.clone(), 0, 0.0)2335 (flat.levels.clone(), 0, 0.0)
2205 }2336 }
2206 2337
2338+/// The largest distinct-colour count a block may hold and still be offered a
2339+/// palette candidate at all: past it the k-means quantisation costs more
2340+/// error than the map saves rate, and every trial is wasted wall.
2341+/// `EC_AV1_PAL_MAXCOLORS`.
2342+fn palette_max_colors() -> usize {
2343+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2344+ *N.get_or_init(|| {
2345+ std::env::var("EC_AV1_PAL_MAXCOLORS")
2346+ .ok()
2347+ .and_then(|v| v.parse().ok())
2348+ .unwrap_or(32)
2349+ })
2350+}
2351+
2352+/// The palettes worth trying for one block's luma, in the shape libaom's
2353+/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
2354+/// distinct colours takes them ALL (the prediction is then exact and the
2355+/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
2356+/// one-dimensional Lloyd iteration seeded evenly across its range -- both
2357+/// offered, because which wins is an RD question the caller answers.
2358+/// `block` is `side*side` source samples, row-major.
2359+fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2360+ let mut histogram = [0u32; 256];
2361+ for &v in block {
2362+ histogram[usize::from(v)] += 1;
2363+ }
2364+ let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
2365+ if present.len() < 2 {
2366+ return Vec::new();
2367+ }
2368+ let exact = |colors: &[u16]| -> crate::tile::PaletteY {
2369+ let mut base = [0u16; 8];
2370+ base[..colors.len()].copy_from_slice(colors);
2371+ let map = block
2372+ .iter()
2373+ .map(|&v| {
2374+ colors
2375+ .iter()
2376+ .enumerate()
2377+ .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
2378+ .map(|(i, _)| i as u8)
2379+ .expect("a palette holds at least two colours")
2380+ })
2381+ .collect();
2382+ crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
2383+ };
2384+ if present.len() <= 8 {
2385+ return vec![exact(&present)];
2386+ }
2387+ if present.len() > palette_max_colors() {
2388+ return Vec::new();
2389+ }
2390+ let (lo, hi) = (
2391+ i32::from(present[0]),
2392+ i32::from(present[present.len() - 1]),
2393+ );
2394+ let mut out = Vec::with_capacity(2);
2395+ for n in [8usize, 4] {
2396+ // Even seeding across the block's own range, then four Lloyd passes
2397+ // over the histogram (256 bins, not `side*side` pixels).
2398+ let mut centres: Vec<f64> = (0..n)
2399+ .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
2400+ .collect();
2401+ for _ in 0..4 {
2402+ let mut sums = vec![0f64; n];
2403+ let mut counts = vec![0u32; n];
2404+ for (v, &count) in histogram.iter().enumerate() {
2405+ if count == 0 {
2406+ continue;
2407+ }
2408+ let k = (0..n)
2409+ .min_by(|&a, &b| {
2410+ (centres[a] - v as f64)
2411+ .abs()
2412+ .total_cmp(&(centres[b] - v as f64).abs())
2413+ })
2414+ .expect("n >= 2");
2415+ sums[k] += (v as u32 * count) as f64;
2416+ counts[k] += count;
2417+ }
2418+ for k in 0..n {
2419+ if counts[k] > 0 {
2420+ centres[k] = sums[k] / f64::from(counts[k]);
2421+ }
2422+ }
2423+ }
2424+ let mut colors: Vec<u16> = centres
2425+ .iter()
2426+ .map(|&c| c.round().clamp(0.0, 255.0) as u16)
2427+ .collect();
2428+ colors.sort_unstable();
2429+ colors.dedup();
2430+ if colors.len() >= 2 {
2431+ out.push(exact(&colors));
2432+ }
2433+ }
2434+ out
2435+}
2436+
2207 #[allow(clippy::too_many_arguments)]2437 #[allow(clippy::too_many_arguments)]
2208 fn code_square(2438 fn code_square(
2209 luma: &mut Plane,2439 luma: &mut Plane,
@@ -2265,6 +2495,55 @@ fn code_square(
2265 luma_coeffs = best.3;2495 luma_coeffs = best.3;
2266 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);2496 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2267 }2497 }
2498+ // The palette candidate is priced against the mode the luma search (and
2499+ // its transform-depth search) already settled on, so a block only takes
2500+ // one when it beats the best ordinary intra coding of the same pixels.
2501+ // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
2502+ // prediction is the colour map, not the DC of its neighbours.
2503+ let mut mode = mode;
2504+ let mut palette = None;
2505+ if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2506+ let source: Vec<u8> = (y..y + side)
2507+ .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
2508+ .collect();
2509+ let kept = luma.snapshot(x, y, side);
2510+ for pal in palette_candidates(&source) {
2511+ let n = usize::from(pal.size);
2512+ let prediction: Vec<u8> = pal
2513+ .map
2514+ .iter()
2515+ .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
2516+ .collect();
2517+ let trial = luma.code_from_prediction(
2518+ x,
2519+ y,
2520+ side,
2521+ &prediction,
2522+ false,
2523+ search.base_q_idx,
2524+ search.deadzone,
2525+ luma_set,
2526+ );
2527+ let cost_p = trial.sse
2528+ + search.lambda
2529+ * (trial.bits
2530+ + mode_bits[DC_PRED as usize]
2531+ + crate::tile::palette_bits(&pal, side)
2532+ + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
2533+ if cost_p < cost {
2534+ cost = cost_p;
2535+ mode = DC_PRED as u8;
2536+ tx_depth = 0;
2537+ luma_coeffs = coeffs(&trial.levels, side);
2538+ luma.commit(x, y, side, &trial);
2539+ palette = Some(pal);
2540+ }
2541+ }
2542+ if palette.is_none() {
2543+ luma.restore(x, y, side, &kept);
2544+ }
2545+ }
2546+
2268 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both2547 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
2269 // planes; what it costs still counts towards the partition decision.2548 // planes; what it costs still counts towards the partition decision.
2270 let ([u, v], uv_mode, chroma_cost) =2549 let ([u, v], uv_mode, chroma_cost) =
@@ -2278,6 +2557,7 @@ fn code_square(
2278 mode,2557 mode,
2279 uv_mode,2558 uv_mode,
2280 tx_depth,2559 tx_depth,
2560+ palette,
2281 ..BlockCoeffs::default()2561 ..BlockCoeffs::default()
2282 },2562 },
2283 cost,2563 cost,
@@ -2673,6 +2953,7 @@ fn code_square_inter(
2673 uv_mode: DC_PRED,2953 uv_mode: DC_PRED,
2674 skip: skip_new,2954 skip: skip_new,
2675 eight: None,2955 eight: None,
2956+ palette: None,
2676 tx_depth,2957 tx_depth,
2677 inter: Some(InterInfo {2958 inter: Some(InterInfo {
2678 ref1: None,2959 ref1: None,
@@ -2709,6 +2990,7 @@ fn code_square_inter(
2709 uv_mode: DC_PRED,2990 uv_mode: DC_PRED,
2710 skip,2991 skip,
2711 eight: None,2992 eight: None,
2993+ palette: None,
2712 tx_depth,2994 tx_depth,
2713 inter: Some(InterInfo {2995 inter: Some(InterInfo {
2714 ref1: None,2996 ref1: None,
@@ -2826,6 +3108,9 @@ fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
2826 3108
2827 /// What the luma mode search picks between, and under what terms.3109 /// What the luma mode search picks between, and under what terms.
2828 struct Search<'a> {3110 struct Search<'a> {
3111+ /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
3112+ /// luma search then offers a palette candidate beside the intra modes.
3113+ screen: bool,
2829 base_q_idx: u8,3114 base_q_idx: u8,
2830 deadzone: f64,3115 deadzone: f64,
2831 lambda: f64,3116 lambda: f64,
@@ -3226,7 +3511,19 @@ pub(crate) fn encode_key_frame_inner(
3226 // `render_and_frame_size_different` is false and no render_size bits are3511 // `render_and_frame_size_different` is false and no render_size bits are
3227 // written, mirroring libaom/rav1e: the padded `picture` below is only the3512 // written, mirroring libaom/rav1e: the padded `picture` below is only the
3228 // internal coding surface, never what the header names.3513 // internal coding surface, never what the header names.
3514+ // Screen-content detection runs on the SOURCE luma, before any header is
3515+ // built: it decides this sequence's `seq_force_screen_content_tools` (and
3516+ // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
3517+ // this frame's own `allow_screen_content_tools`.
3518+ let screen = screen_content(
3519+ &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
3520+ picture.width,
3521+ (picture.width).min(render.0),
3522+ (picture.height).min(render.1),
3523+ );
3524+ arm_seq_screen(screen);
3229 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;3525 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
3526+ header.allow_screen_content_tools = screen;
3230 header.render_width = render.0 as u32;3527 header.render_width = render.0 as u32;
3231 header.render_height = render.1 as u32;3528 header.render_height = render.1 as u32;
3232 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split3529 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
@@ -3298,6 +3595,7 @@ pub(crate) fn encode_key_frame_inner(
3298 lambda: lambda_scale() * step * step,3595 lambda: lambda_scale() * step * step,
3299 modes,3596 modes,
3300 top_k: prune_top_k(),3597 top_k: prune_top_k(),
3598+ screen,
3301 };3599 };
3302 3600
3303 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s3601 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
@@ -3551,6 +3849,7 @@ pub(crate) fn encode_key_frame_inner(
3551 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3849 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3552 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());3850 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3553 let mut cdfs = start_cdfs.0.clone();3851 let mut cdfs = start_cdfs.0.clone();
3852+ crate::tile::arm_screen(screen);
3554 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(3853 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
3555 mi_cols,3854 mi_cols,
3556 mi_rows,3855 mi_rows,
@@ -3630,6 +3929,7 @@ pub(crate) fn encode_key_frame_inner(
3630 mi_rows: header.mi_rows,3929 mi_rows: header.mi_rows,
3631 base_q_idx,3930 base_q_idx,
3632 tx_select,3931 tx_select,
3932+ screen,
3633 next_cdfs: start_cdfs.clone(),3933 next_cdfs: start_cdfs.clone(),
3634 start_cdfs,3934 start_cdfs,
3635 loop_filter: header.loop_filter,3935 loop_filter: header.loop_filter,
@@ -4744,6 +5044,7 @@ fn search_inter_block(
4744 skip: best.skip,5044 skip: best.skip,
4745 inter: best.inter,5045 inter: best.inter,
4746 eight: None,5046 eight: None,
5047+ palette: None,
4747 tx_depth: 0,5048 tx_depth: 0,
4748 },5049 },
4749 best.cost,5050 best.cost,
@@ -4896,6 +5197,14 @@ pub(crate) fn encode_inter_frame(
4896 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();5197 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
4897 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();5198 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
4898 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();5199 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
5200+ // This frame's own `allow_screen_content_tools`. It can only be set when
5201+ // the SEQUENCE offers the bit at all, which is the key frame's decision
5202+ // ([`SEQ_SCREEN`]): a frame header that contradicts
5203+ // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
5204+ // encode.
5205+ let screen = seq_screen()
5206+ && screen_content(&picture_y8, picture.width, true_width, true_height);
5207+ header.allow_screen_content_tools = screen;
4899 let mut luma = Plane {5208 let mut luma = Plane {
4900 source: &picture_y8,5209 source: &picture_y8,
4901 reconstruction: vec![128; picture_y8.len()],5210 reconstruction: vec![128; picture_y8.len()],
@@ -4942,6 +5251,7 @@ pub(crate) fn encode_inter_frame(
4942 lambda: lambda_scale() * step * step,5251 lambda: lambda_scale() * step * step,
4943 modes: &KEY_FRAME_MODES,5252 modes: &KEY_FRAME_MODES,
4944 top_k: prune_top_k_inter(),5253 top_k: prune_top_k_inter(),
5254+ screen,
4945 };5255 };
4946 let mode_bits_table = inter_mode_bits();5256 let mode_bits_table = inter_mode_bits();
4947 5257
@@ -5435,6 +5745,7 @@ pub(crate) fn encode_inter_frame(
5435 // Thread-locals: every tile job arms its own worker.5745 // Thread-locals: every tile job arms its own worker.
5436 crate::tile::arm_reference_select(reference_select_bit);5746 crate::tile::arm_reference_select(reference_select_bit);
5437 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);5747 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
5748+ crate::tile::arm_screen(screen);
5438 let mut cdfs = start_cdfs.0.clone();5749 let mut cdfs = start_cdfs.0.clone();
5439 // Each tile's own MV grid: a candidate scan never reaches past5750 // Each tile's own MV grid: a candidate scan never reaches past
5440 // the tile's bounds, so a grid holding only this tile's own5751 // the tile's bounds, so a grid holding only this tile's own
@@ -5557,6 +5868,7 @@ pub(crate) fn encode_inter_frame(
5557 // frame's `start_cdfs`), not from the defaults.5868 // frame's `start_cdfs`), not from the defaults.
5558 Some(start_cdfs.0.clone()),5869 Some(start_cdfs.0.clone()),
5559 sign_bias,5870 sign_bias,
5871+ h.allow_screen_content_tools,
5560 fctx,5872 fctx,
5561 )5873 )
5562 },5874 },
@@ -5589,6 +5901,7 @@ pub(crate) fn encode_inter_frame(
5589 mi_rows: header.mi_rows,5901 mi_rows: header.mi_rows,
5590 base_q_idx,5902 base_q_idx,
5591 tx_select,5903 tx_select,
5904+ screen,
5592 start_cdfs,5905 start_cdfs,
5593 next_cdfs,5906 next_cdfs,
5594 loop_filter: header.loop_filter,5907 loop_filter: header.loop_filter,
@@ -6061,6 +6374,116 @@ mod tests {
6061 );6374 );
6062 }6375 }
6063 6376
6377+ /// A synthetic screen-content picture -- a few flat colours in a grid of
6378+ /// boxes with hard edges and text-like bars, the shape a desktop capture
6379+ /// has -- so the palette path is exercised on content it is for.
6380+ #[cfg(test)]
6381+ fn screen_card(width: usize, height: usize) -> Picture {
6382+ const INK: [u16; 4] = [16, 90, 180, 235];
6383+ let mut picture = Picture::grey(width, height);
6384+ for y in 0..height {
6385+ for x in 0..width {
6386+ let cell = (x / 24 + y / 24) % 2;
6387+ let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
6388+ picture.y[y * width + x] = INK[cell * 2 + bar];
6389+ }
6390+ }
6391+ for y in 0..height / 2 {
6392+ for x in 0..width / 2 {
6393+ let cell = (x / 12 + y / 12) % 2;
6394+ picture.u[y * (width / 2) + x] = if cell == 0 { 110 } else { 145 };
6395+ picture.v[y * (width / 2) + x] = if cell == 0 { 140 } else { 108 };
6396+ }
6397+ }
6398+ picture
6399+ }
6400+
6401+ /// The lane's own end-to-end check: on screen content the detector fires,
6402+ /// blocks really take a palette (fire count, class
6403+ /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
6404+ /// symbol this lane writes -- reconstructs exactly what the encoder did.
6405+ /// The film-shaped `test_card` must NOT trip the detector, which is what
6406+ /// keeps every non-screen stream byte-identical.
6407+ #[test]
6408+ fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
6409+ let fctx = &crate::decode::FrameCtx::new();
6410+ let (width, height) = (192usize, 96usize);
6411+ let _ = crate::tile::take_palette_hits();
6412+ let picture = screen_card(width, height);
6413+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
6414+ assert!(
6415+ encoded.screen,
6416+ "the detector did not fire on screen content -- no palette syntax was coded at all"
6417+ );
6418+ let hits = crate::tile::take_palette_hits();
6419+ assert!(hits[0] > 0, "no block took a palette: {hits:?}");
6420+ eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
6421+ let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
6422+ assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
6423+ assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
6424+ assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
6425+ if !have_ffmpeg() {
6426+ eprintln!("SKIP the ffmpeg half: no ffmpeg");
6427+ return;
6428+ }
6429+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
6430+ assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
6431+ assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
6432+ assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
6433+ // A whole GOP: the inter frames' own intra blocks carry the palette
6434+ // syntax too (the three intra arms of the inter writers), which only
6435+ // ffmpeg reading the frames back can prove.
6436+ let moved: Vec<Picture> = (0..4)
6437+ .map(|f| {
6438+ let base = screen_card(width, height);
6439+ let mut out = Picture::grey(width, height);
6440+ for y in 0..height {
6441+ for x in 0..width {
6442+ let sx = (x + f * 7) % width;
6443+ out.y[y * width + x] = base.y[y * width + sx];
6444+ }
6445+ }
6446+ for y in 0..height / 2 {
6447+ for x in 0..width / 2 {
6448+ let sx = (x + f * 3) % (width / 2);
6449+ out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
6450+ out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
6451+ }
6452+ }
6453+ out
6454+ })
6455+ .collect();
6456+ let _ = crate::tile::take_palette_hits();
6457+ let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
6458+ let gop_hits = crate::tile::take_palette_hits();
6459+ let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
6460+ eprintln!(
6461+ "GOP: {} frames with screen tools after the key frame, {} palette blocks",
6462+ inter_screen, gop_hits[0]
6463+ );
6464+ assert!(
6465+ inter_screen > 0,
6466+ "no inter frame set allow_screen_content_tools"
6467+ );
6468+ let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
6469+ for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
6470+ assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
6471+ }
6472+ if have_ffmpeg() {
6473+ let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
6474+ for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
6475+ assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
6476+ assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
6477+ assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
6478+ }
6479+ }
6480+
6481+ // The other half of the keep rule: film-shaped content leaves the
6482+ // detector (and so the whole sequence header) alone.
6483+ let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
6484+ assert!(!film.screen, "the detector fired on the film-shaped test card");
6485+ }
6486+
6064 /// The minimal repro that isolated the inter-residual desync: a key frame6487 /// The minimal repro that isolated the inter-residual desync: a key frame
6065 /// followed by one inter frame whose single superblock carries one6488 /// followed by one inter frame whose single superblock carries one
6066 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma6489 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
@@ -6097,6 +6520,7 @@ mod tests {
6097 uv_mode: 0,6520 uv_mode: 0,
6098 skip: false,6521 skip: false,
6099 eight: None,6522 eight: None,
6523+ palette: None,
6100 tx_depth: 0,6524 tx_depth: 0,
6101 inter: Some(InterInfo {6525 inter: Some(InterInfo {
6102 ref1: None,6526 ref1: None,
@@ -6962,6 +7386,10 @@ mod tests {
6962 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by7386 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
6963 /// fidelity.7387 /// fidelity.
6964 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {7388 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
7389+ // A mode ablation measures the MODE search: the palette would code
7390+ // these synthetic two-colour pictures losslessly under every arm and
7391+ // leave nothing to compare (see [`force_screen`]).
7392+ force_screen(Some(false));
6965 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]7393 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
6966 .iter()7394 .iter()
6967 .map(|&q| {7395 .map(|&q| {
@@ -7074,6 +7502,10 @@ mod tests {
7074 /// The mode picked by the most blocks of a picture, ignoring the first7502 /// The mode picked by the most blocks of a picture, ignoring the first
7075 /// block, which has no neighbours to tell the modes apart with.7503 /// block, which has no neighbours to tell the modes apart with.
7076 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {7504 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
7505+ // A mode ablation measures the MODE search: the palette would code
7506+ // these synthetic two-colour pictures losslessly under every arm and
7507+ // leave nothing to compare (see [`force_screen`]).
7508+ force_screen(Some(false));
7077 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();7509 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
7078 let blocks = &encoded.modes[1..];7510 let blocks = &encoded.modes[1..];
7079 let mut counts = [0usize; 13];7511 let mut counts = [0usize; 13];
@@ -8553,6 +8985,71 @@ mod tests {
8553 }8985 }
8554 }8986 }
8555 8987
8988+ /// The sweep behind [`screen_content`]'s two constants
8989+ /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at
8990+ /// most N distinct colours, per gate clip, at the size the gate codes.
8991+ /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
8992+ #[test]
8993+ #[ignore = "reads the real library"]
8994+ fn probe_screen_detect() {
8995+ let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
8996+ let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
8997+ for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
8998+ let path = fixtures.join("video").join(name);
8999+ if path.exists() {
9000+ clips.push((name.to_string(), path));
9001+ }
9002+ }
9003+ if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
9004+ && let Some(p) = manifest
9005+ .lines()
9006+ .skip(1)
9007+ .filter_map(|l| l.split('\t').next())
9008+ .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
9009+ {
9010+ clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
9011+ }
9012+ let (width, height) = (640usize, 384usize);
9013+ for (name, path) in &clips {
9014+ let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4);
9015+ for (f, picture) in frames.iter().enumerate() {
9016+ let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
9017+ let mut hist = [0usize; 257];
9018+ let mut blocks = 0usize;
9019+ for by in (0..height).step_by(16) {
9020+ for bx in (0..width).step_by(16) {
9021+ let mut seen = [false; 256];
9022+ let mut colors = 0usize;
9023+ for row in 0..16 {
9024+ for col in 0..16 {
9025+ let v = usize::from(y[(by + row) * width + bx + col]);
9026+ if !seen[v] {
9027+ seen[v] = true;
9028+ colors += 1;
9029+ }
9030+ }
9031+ }
9032+ hist[colors] += 1;
9033+ blocks += 1;
9034+ }
9035+ }
9036+ let share = |limit: usize| {
9037+ 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64
9038+ / blocks.max(1) as f64
9039+ };
9040+ eprintln!(
9041+ "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%",
9042+ share(4),
9043+ share(8),
9044+ share(16),
9045+ share(32),
9046+ share(64),
9047+ share(128),
9048+ );
9049+ }
9050+ }
9051+ }
9052+
8556 /// The missing instrument: what this encoder costs against libaom and9053 /// The missing instrument: what this encoder costs against libaom and
8557 /// rav1e at matched fidelity, and how long it takes to get there.9054 /// rav1e at matched fidelity, and how long it takes to get there.
8558 ///9055 ///
@@ -8691,6 +9188,10 @@ mod tests {
8691 let fctx = &crate::decode::FrameCtx::new();9188 let fctx = &crate::decode::FrameCtx::new();
8692 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);9189 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
8693 let _ = take_partition_hits();9190 let _ = take_partition_hits();
9191+ let _ = crate::tile::take_palette_hits();
9192+ SCREEN_FRAMES.iter().for_each(|c| {
9193+ c.store(0, std::sync::atomic::Ordering::Relaxed);
9194+ });
8694 let _ = take_uv_mode_hits();9195 let _ = take_uv_mode_hits();
8695 let _ = crate::tile::take_inter_mode_hits();9196 let _ = crate::tile::take_inter_mode_hits();
8696 let _ = crate::tile::take_drl_hits();9197 let _ = crate::tile::take_drl_hits();
@@ -8828,6 +9329,22 @@ mod tests {
8828 // Which chroma modes the search actually wins with, against the9329 // Which chroma modes the search actually wins with, against the
8829 // unconditional DC_PRED that was the only outcome before9330 // unconditional DC_PRED that was the only outcome before
8830 // (gate-blind-to-feature).9331 // (gate-blind-to-feature).
9332+ // Screen-content detection and the palette it turns on
9333+ // (gate-blind-to-feature): how many frames set
9334+ // `allow_screen_content_tools`, how many blocks took a palette,
9335+ // and of what size. A film clip must print `screen frames on=0`.
9336+ let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
9337+ let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
9338+ let palette = crate::tile::take_palette_hits();
9339+ eprintln!(
9340+ "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
9341+ palette[0],
9342+ (2..=8)
9343+ .filter(|&n| palette[n] > 0)
9344+ .map(|n| format!("{n}={}", palette[n]))
9345+ .collect::<Vec<_>>()
9346+ .join(" ")
9347+ );
8831 let uv = take_uv_mode_hits();9348 let uv = take_uv_mode_hits();
8832 let uv_total: usize = uv.iter().sum();9349 let uv_total: usize = uv.iter().sum();
8833 eprintln!(9350 eprintln!(
crates/ec-av1/src/stream.rsmodified+6 -1
@@ -2999,7 +2999,12 @@ pub(crate) mod tests {
2999 encoded.tx_select,2999 encoded.tx_select,
3000 // Our own encoder always writes `reduced_tx_set: true`.3000 // Our own encoder always writes `reduced_tx_set: true`.
3001 true,3001 true,
3002- false,3002+ // `allow_screen_content_tools` off the frame the encoder
3003+ // actually wrote: a screen-content picture codes two palette
3004+ // symbols per intra block, and a raw tile decode that guessed
3005+ // `false` desyncs at the first one (class: test asserts
3006+ // against a stale header).
3007+ encoded.screen,
3003 false,3008 false,
3004 &encoded.loop_restoration, fctx,3009 &encoded.loop_restoration, fctx,
3005 )3010 )
crates/ec-av1/src/tile.rsmodified+391 -3
@@ -304,6 +304,25 @@ pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
304 SIGN_BIAS.with(|c| c.set(sign_bias));304 SIGN_BIAS.with(|c| c.set(sign_bias));
305 }305 }
306 306
307+thread_local! {
308+ static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
309+}
310+
311+/// Arms the next tile write with this frame's `allow_screen_content_tools`
312+/// (spec 5.9.2), which is what makes every intra block carry the
313+/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
314+/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
315+/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
316+/// never detected screen content writes exactly the stream it wrote before
317+/// this lane.
318+pub(crate) fn arm_screen(on: bool) {
319+ SCREEN.with(|c| c.set(on));
320+}
321+
322+fn screen_armed() -> bool {
323+ SCREEN.with(std::cell::Cell::get)
324+}
325+
307 thread_local! {326 thread_local! {
308 /// This frame header's own `reference_select` bit (spec 5.9.22), armed327 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
309 /// the same way `arm_sign_bias` arms the sign-bias table rather than328 /// the same way `arm_sign_bias` arms the sign-bias table rather than
@@ -606,6 +625,7 @@ impl Drop for CdefIdxGuard {
606 CDEF_IDX.with(|c| *c.borrow_mut() = None);625 CDEF_IDX.with(|c| *c.borrow_mut() = None);
607 LR_PLAN.with(|c| *c.borrow_mut() = None);626 LR_PLAN.with(|c| *c.borrow_mut() = None);
608 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));627 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
628+ SCREEN.with(|c| c.set(false));
609 REFERENCE_SELECT.with(|c| c.set(false));629 REFERENCE_SELECT.with(|c| c.set(false));
610 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));630 ORDER_HINTS.with(|c| c.set((7, 0, [0; 7])));
611 }631 }
@@ -1093,6 +1113,13 @@ pub struct BlockCoeffs {
1093 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s1113 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
1094 /// per-quadrant fields are unused.1114 /// per-quadrant fields are unused.
1095 pub eight: Option<Vec<BlockCoeffs>>,1115 pub eight: Option<Vec<BlockCoeffs>>,
1116+ /// The luma palette this block is predicted with (spec 5.11.46
1117+ /// `palette_mode_info`), or `None` for an ordinary intra block. Only a
1118+ /// `DC_PRED` block on a frame whose header set
1119+ /// `allow_screen_content_tools` may carry one, and it forces
1120+ /// `tx_depth` to zero (the whole block is one transform over the
1121+ /// palette's own prediction).
1122+ pub palette: Option<PaletteY>,
1096 /// How many times this block's luma transform is halved under1123 /// How many times this block's luma transform is halved under
1097 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole1124 /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
1098 /// block). Read only by the writers a `tx_select` frame calls; a1125 /// block). Read only by the writers a `tx_select` frame calls; a
@@ -1102,6 +1129,20 @@ pub struct BlockCoeffs {
1102 pub tx_depth: u8,1129 pub tx_depth: u8,
1103 }1130 }
1104 1131
1132+/// A block's luma palette: its base colours (ascending, only the first
1133+/// `size` entries are real) and the per-pixel colour-index map, `side*side`
1134+/// row-major -- exactly what [`crate::decode`]'s own `PaletteY` carries back
1135+/// out of the stream.
1136+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1137+pub struct PaletteY {
1138+ /// How many base colours, 2..=8 (spec `PaletteSizeY`).
1139+ pub size: u8,
1140+ /// The base colours, ascending.
1141+ pub colors: [u16; 8],
1142+ /// Which colour each pixel takes, row-major over the block's own side.
1143+ pub map: Vec<u8>,
1144+}
1145+
1105 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole1146 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole
1106 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by1147 /// single-reference set of spec 5.11.24 `read_inter_mode`, each written by
1107 /// [`write_inter_mode`] with the decoder's own contexts.1148 /// [`write_inter_mode`] with the decoder's own contexts.
@@ -1336,6 +1377,27 @@ struct Neighbours {
1336 above_txfm: Vec<u8>,1377 above_txfm: Vec<u8>,
1337 /// The same, down the left edge (transform HEIGHT).1378 /// The same, down the left edge (transform HEIGHT).
1338 left_txfm: Vec<u8>,1379 left_txfm: Vec<u8>,
1380+ /// The palette size each 4x4 mode-info column last left behind, and its
1381+ /// base colours -- `av1_get_palette_mode_ctx`'s neighbour lookup and
1382+ /// `av1_get_palette_cache`'s colour source, mirrored from the decoder's
1383+ /// own `above_palette_size`/`above_palette_colors` bands (decode.rs
1384+ /// `palette_ctx_and_cache_mi`). Every intra block of a screen-content
1385+ /// frame writes them, `0` when it took no palette, so a stale size never
1386+ /// survives into the next block's context.
1387+ above_palette_size: Vec<u8>,
1388+ /// The same, down the left edge.
1389+ left_palette_size: Vec<u8>,
1390+ /// What the block being written right now will leave in the two palette
1391+ /// bands, published by [`Self::record_mi_planes`] -- the one point EVERY
1392+ /// block of either frame type passes through, so an inter block (or an
1393+ /// intra block that took no palette) clears the bands rather than letting
1394+ /// an earlier palette block's size stand (the neighbour-band hazard
1395+ /// lane-t900 r23 hit on the decoder side).
1396+ pending_palette: Option<(u8, [u16; 8])>,
1397+ /// The colours beside [`Self::above_palette_size`].
1398+ above_palette_colors: Vec<[u16; 8]>,
1399+ /// The same, down the left edge.
1400+ left_palette_colors: Vec<[u16; 8]>,
1339 /// Whether the neighbour was coded inter, for the `is_inter` context.1401 /// Whether the neighbour was coded inter, for the `is_inter` context.
1340 /// Unused by the key frame writers.1402 /// Unused by the key frame writers.
1341 above_inter: Vec<bool>,1403 above_inter: Vec<bool>,
@@ -1421,6 +1483,11 @@ impl Neighbours {
1421 left_tx: vec![0; rows * (SUB / MI)],1483 left_tx: vec![0; rows * (SUB / MI)],
1422 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],1484 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
1423 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],1485 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
1486+ above_palette_size: vec![0; cols * (SUB / MI)],
1487+ left_palette_size: vec![0; rows * (SUB / MI)],
1488+ pending_palette: None,
1489+ above_palette_colors: vec![[0; 8]; cols * (SUB / MI)],
1490+ left_palette_colors: vec![[0; 8]; rows * (SUB / MI)],
1424 mi_cols,1491 mi_cols,
1425 mi_rows,1492 mi_rows,
1426 }1493 }
@@ -1457,6 +1524,82 @@ impl Neighbours {
1457 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);1524 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1458 self.left_tx.iter_mut().for_each(|t| *t = 0);1525 self.left_tx.iter_mut().for_each(|t| *t = 0);
1459 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);1526 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
1527+ self.left_palette_size.iter_mut().for_each(|s| *s = 0);
1528+ }
1529+
1530+ /// `av1_get_palette_mode_ctx` + `av1_get_palette_cache`, mirrored from
1531+ /// the decoder's [`crate::decode`] `palette_ctx_and_cache_mi`: the
1532+ /// `palette_y_mode` context (how many of the two neighbours took a
1533+ /// palette) and the ascending, deduplicated colour cache the neighbours
1534+ /// offer. `mi` is the block's own position in 4x4 units; this writer
1535+ /// codes one tile starting at (0, 0), which is what the `r > 0`/`c > 0`
1536+ /// availability terms read against.
1537+ fn palette_ctx_and_cache(&self, (r, c): (usize, usize)) -> (usize, Vec<u16>) {
1538+ // `av1_get_palette_cache` drops the above neighbour on a 64-px
1539+ // superblock boundary (pred_common.c:76) -- but the mode CONTEXT does
1540+ // not, which is why the two terms below are asked separately.
1541+ let above_ok = r % 16 != 0;
1542+ let above_is_palette = r > 0 && self.above_palette_size[c] > 0;
1543+ let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1544+ (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
1545+ } else {
1546+ (0, [0u16; 8])
1547+ };
1548+ let (left_n, left_colors) = if c > 0 && self.left_palette_size[r] > 0 {
1549+ (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
1550+ } else {
1551+ (0, [0u16; 8])
1552+ };
1553+ let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
1554+ let mut cache = Vec::with_capacity(16);
1555+ let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1556+ if cache.last() != Some(&v) {
1557+ cache.push(v);
1558+ }
1559+ };
1560+ let (mut ai, mut li) = (0usize, 0usize);
1561+ while ai < above_n && li < left_n {
1562+ let (va, vl) = (above_colors[ai], left_colors[li]);
1563+ if vl < va {
1564+ push_dedup(&mut cache, vl);
1565+ li += 1;
1566+ } else {
1567+ push_dedup(&mut cache, va);
1568+ ai += 1;
1569+ if vl == va {
1570+ li += 1;
1571+ }
1572+ }
1573+ }
1574+ while ai < above_n {
1575+ push_dedup(&mut cache, above_colors[ai]);
1576+ ai += 1;
1577+ }
1578+ while li < left_n {
1579+ push_dedup(&mut cache, left_colors[li]);
1580+ li += 1;
1581+ }
1582+ (ctx, cache)
1583+ }
1584+
1585+ /// What a just-written block leaves in the palette bands (decode.rs
1586+ /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
1587+ /// spans, `0` for a block that took no palette.
1588+ fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
1589+ for cell in 0..(side / MI).max(1) {
1590+ if let Some(e) = self.above_palette_size.get_mut(c + cell) {
1591+ *e = size;
1592+ if size > 0 {
1593+ self.above_palette_colors[c + cell] = colors;
1594+ }
1595+ }
1596+ if let Some(e) = self.left_palette_size.get_mut(r + cell) {
1597+ *e = size;
1598+ if size > 0 {
1599+ self.left_palette_colors[r + cell] = colors;
1600+ }
1601+ }
1602+ }
1460 }1603 }
1461 1604
1462 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block1605 /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
@@ -1604,6 +1747,10 @@ impl Neighbours {
1604 luma: bool,1747 luma: bool,
1605 ) {1748 ) {
1606 let (mi_r, mi_c) = at_mi;1749 let (mi_r, mi_c) = at_mi;
1750+ if screen_armed() {
1751+ let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
1752+ self.record_palette_y(at_mi, side, size, colors);
1753+ }
1607 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));1754 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
1608 let side_mi = side / MI;1755 let side_mi = side / MI;
1609 for cell in 0..side_mi {1756 for cell in 0..side_mi {
@@ -2300,6 +2447,130 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
2300 Ok(enc.finish())2447 Ok(enc.finish())
2301 }2448 }
2302 2449
2450+/// `av1_write_uniform` -- the inverse of [`crate::decode`]'s `read_uniform`,
2451+/// which the palette colour-index map's first (context-free) symbol is coded
2452+/// with.
2453+fn write_uniform(enc: &mut SymbolEncoder, value: usize, n: usize) {
2454+ let l = crate::decode::ceil_log2(n as u32);
2455+ let m = (1usize << l) - n;
2456+ if value < m {
2457+ enc.literal(value as u32, l - 1);
2458+ } else {
2459+ enc.literal(((value + m) >> 1) as u32, l - 1);
2460+ enc.literal(((value + m) & 1) as u32, 1);
2461+ }
2462+}
2463+
2464+/// `write_palette_colors_y` (bitstream.c:1178), the write side of
2465+/// [`crate::decode`]'s `read_palette_colors_y` at 8 bits: one flag per cache
2466+/// entry (taken when this palette holds that colour, in cache order, stopping
2467+/// once `n` are cached), then the colours the cache did not supply -- the
2468+/// first raw, the rest as deltas off a bit width that shrinks with the range
2469+/// left. `colors` is ascending and distinct, so the decoder's `merge_colors`
2470+/// of the two ascending lists puts it back exactly.
2471+fn write_palette_colors_y(enc: &mut SymbolEncoder, colors: &[u16], cache: &[u16]) {
2472+ let n = colors.len();
2473+ let mut cached: Vec<u16> = Vec::with_capacity(n);
2474+ for &c in cache {
2475+ if cached.len() >= n {
2476+ break;
2477+ }
2478+ let take = colors.contains(&c);
2479+ enc.literal(u32::from(take), 1);
2480+ if take {
2481+ cached.push(c);
2482+ }
2483+ }
2484+ let transmitted: Vec<u16> = colors
2485+ .iter()
2486+ .copied()
2487+ .filter(|c| !cached.contains(c))
2488+ .collect();
2489+ if transmitted.is_empty() {
2490+ return;
2491+ }
2492+ enc.literal(u32::from(transmitted[0]), 8);
2493+ if transmitted.len() == 1 {
2494+ return;
2495+ }
2496+ // The 2-bit `extra` the decoder adds to `bit_depth - 3`: the smallest one
2497+ // under which every delta still fits its (shrinking) width. `extra == 3`
2498+ // always works -- a delta can never exceed the range left -- so the
2499+ // search below always finds one.
2500+ let fits = |extra: u32| -> bool {
2501+ let mut bits = 5 + extra;
2502+ let mut range = 255i32 - i32::from(transmitted[0]);
2503+ for w in transmitted.windows(2) {
2504+ let delta = i32::from(w[1]) - i32::from(w[0]);
2505+ if delta - 1 >= (1i32 << bits) {
2506+ return false;
2507+ }
2508+ range -= delta;
2509+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2510+ }
2511+ true
2512+ };
2513+ let extra = (0..=3).find(|&e| fits(e)).unwrap_or(3);
2514+ enc.literal(extra, 2);
2515+ let mut bits = 5 + extra;
2516+ let mut range = 255i32 - i32::from(transmitted[0]);
2517+ for w in transmitted.windows(2) {
2518+ let delta = i32::from(w[1]) - i32::from(w[0]);
2519+ enc.literal((delta - 1) as u32, bits);
2520+ range -= delta;
2521+ bits = bits.min(crate::decode::ceil_log2(range.max(0) as u32));
2522+ }
2523+}
2524+
2525+/// `write_palette_color_map` (bitstream.c), the write side of
2526+/// [`crate::decode`]'s `decode_color_index_map`: the same wavefront diagonal,
2527+/// each symbol written as the position its colour takes in the neighbour
2528+/// ordering `av1_get_palette_color_index_context` hands back.
2529+fn write_color_index_map(
2530+ enc: &mut SymbolEncoder,
2531+ idx_cdfs: &mut [[u16; 9]; 5],
2532+ map: &[u8],
2533+ side: usize,
2534+ n: usize,
2535+) {
2536+ write_uniform(enc, usize::from(map[0]), n);
2537+ for i in 1..(2 * side - 1) {
2538+ for j in (i.saturating_sub(side - 1)..=i.min(side - 1)).rev() {
2539+ let (row, col) = (i - j, j);
2540+ let (ctx, color_order) =
2541+ crate::decode::palette_color_index_context(map, side, row, col, n);
2542+ let want = map[row * side + col];
2543+ let symbol = color_order[..n]
2544+ .iter()
2545+ .position(|&c| c == want)
2546+ .expect("every colour index is in the block\'s own palette");
2547+ enc.symbol(symbol, &mut idx_cdfs[ctx][..=n]);
2548+ }
2549+ }
2550+}
2551+
2552+/// What one block's palette syntax costs, in bits: the `palette_y_mode` flag,
2553+/// the size symbol, the colours and the whole colour-index map, priced
2554+/// through the very writers above on a [`SymbolEncoder::pricer`] -- so the
2555+/// search reads the rate the tile will really spend, not an estimate of it.
2556+/// The neighbour cache is taken as empty (the search runs before the tile
2557+/// knows what its neighbours will be), which only ever over-prices.
2558+pub(crate) fn palette_bits(pal: &PaletteY, side: usize) -> f64 {
2559+ let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) else {
2560+ return f64::INFINITY;
2561+ };
2562+ let n = usize::from(pal.size);
2563+ let mut enc = SymbolEncoder::pricer();
2564+ let mut mode_cdf = cdf::PALETTE_Y_MODE[bsize_ctx][0];
2565+ enc.symbol(1, &mut mode_cdf);
2566+ let mut size_cdf = cdf::PALETTE_Y_SIZE[bsize_ctx];
2567+ enc.symbol(n - 2, &mut size_cdf);
2568+ write_palette_colors_y(&mut enc, &pal.colors[..n], &[]);
2569+ let mut idx_cdfs = cdf::PALETTE_Y_COLOR_INDEX[n - 2];
2570+ write_color_index_map(&mut enc, &mut idx_cdfs, &pal.map, side, n);
2571+ enc.bits()
2572+}
2573+
2303 /// Writes everything a key frame's block carries before its coefficients: the2574 /// Writes everything a key frame's block carries before its coefficients: the
2304 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,2575 /// skip flag, its luma intra mode against the CDF its neighbours' modes pick,
2305 /// the angle a directional mode is steered by, and its chroma mode. Hands back2576 /// the angle a directional mode is steered by, and its chroma mode. Hands back
@@ -2307,6 +2578,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
2307 fn write_intra_mode(2578 fn write_intra_mode(
2308 enc: &mut SymbolEncoder,2579 enc: &mut SymbolEncoder,
2309 cdfs: &mut Cdfs,2580 cdfs: &mut Cdfs,
2581+ neighbours: &mut Neighbours,
2310 block: &BlockCoeffs,2582 block: &BlockCoeffs,
2311 above_mode: usize,2583 above_mode: usize,
2312 left_mode: usize,2584 left_mode: usize,
@@ -2314,6 +2586,9 @@ fn write_intra_mode(
2314 // This block's own position in 4x4 mode-info units, for the `cdef_idx`2586 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
2315 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).2587 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
2316 mi: (usize, usize),2588 mi: (usize, usize),
2589+ // The block's side in samples, which gates the palette syntax below
2590+ // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
2591+ side: usize,
2317 ) -> usize {2592 ) -> usize {
2318 let mode = usize::from(block.mode);2593 let mode = usize::from(block.mode);
2319 enc.symbol(0, &mut cdfs.skip[0]);2594 enc.symbol(0, &mut cdfs.skip[0]);
@@ -2339,9 +2614,89 @@ fn write_intra_mode(
2339 if (V_PRED..=D67_PRED).contains(&uv_mode) {2614 if (V_PRED..=D67_PRED).contains(&uv_mode) {
2340 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);2615 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
2341 }2616 }
2617+ // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
2618+ // the decoder's own read in `read_intra_mode`: on a frame whose header set
2619+ // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
2620+ // chroma pair each carry a use-palette flag. Both contexts are 0 here --
2621+ // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
2622+ // codes none -- exactly the ctx-0 read the decoder does under the same
2623+ // condition.
2624+ write_palette_syntax(enc, cdfs, neighbours, block.palette.as_ref(), mode, uv_mode, mi, side);
2342 mode2625 mode
2343 }2626 }
2344 2627
2628+/// `read_palette_mode_info` (spec 5.11.46) written out, mirrored symbol for
2629+/// symbol from the decoder's own read in `read_intra_mode`: on a frame whose
2630+/// header set `allow_screen_content_tools`, a `DC_PRED` luma block and a
2631+/// `UV_DC_PRED` chroma pair each carry a use-palette flag, and a luma palette
2632+/// then codes its size, its colours (against the neighbour colour cache) and
2633+/// -- after the chroma flag, exactly where libaom's `av1_visit_palette` runs
2634+/// -- its colour-index map. Shared by the key frame's [`write_intra_mode`] and
2635+/// by the three intra arms of the inter-frame writers, which read the same
2636+/// syntax back through `decode_inter_block`/`decode_intra_rect_in_inter`.
2637+///
2638+/// The band publication is deferred to [`Neighbours::record_mi_planes`] (the
2639+/// one point every block passes through), so a block that takes no palette
2640+/// still clears what the column held.
2641+#[allow(clippy::too_many_arguments)]
2642+fn write_palette_syntax(
2643+ enc: &mut SymbolEncoder,
2644+ cdfs: &mut Cdfs,
2645+ neighbours: &mut Neighbours,
2646+ palette: Option<&PaletteY>,
2647+ mode: usize,
2648+ uv_mode: usize,
2649+ mi: (usize, usize),
2650+ side: usize,
2651+) {
2652+ if !screen_armed() {
2653+ return;
2654+ }
2655+ let palette = palette.filter(|_| mode == DC_PRED);
2656+ if let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side) {
2657+ let (mode_ctx, cache) = neighbours.palette_ctx_and_cache(mi);
2658+ if mode == DC_PRED {
2659+ enc.symbol(
2660+ usize::from(palette.is_some()),
2661+ &mut cdfs.palette_y_mode[bsize_ctx][mode_ctx],
2662+ );
2663+ }
2664+ if let Some(pal) = palette {
2665+ let n = usize::from(pal.size);
2666+ enc.symbol(n - 2, &mut cdfs.palette_y_size[bsize_ctx]);
2667+ write_palette_colors_y(enc, &pal.colors[..n], &cache);
2668+ }
2669+ if uv_mode == DC_PRED {
2670+ enc.symbol(0, &mut cdfs.palette_uv_mode[usize::from(palette.is_some())]);
2671+ }
2672+ if let Some(pal) = palette {
2673+ let n = usize::from(pal.size);
2674+ write_color_index_map(enc, &mut cdfs.palette_y_color_index[n - 2], &pal.map, side, n);
2675+ note_palette(n);
2676+ }
2677+ }
2678+ neighbours.pending_palette = palette.map(|p| (p.size, p.colors));
2679+}
2680+
2681+/// How many blocks took a palette, and of what size -- the fire count a gate
2682+/// prints so that "palette is on" is a measurement rather than a claim
2683+/// (class `gate-blind-to-feature`). Index 0 is the block count, 2..=8 the
2684+/// per-size histogram.
2685+static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
2686+ [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
2687+
2688+fn note_palette(n: usize) {
2689+ PALETTE_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2690+ PALETTE_HITS[n].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2691+}
2692+
2693+/// Reads [`PALETTE_HITS`] and zeroes it, so a gate can attribute the counts to
2694+/// its own encode.
2695+#[cfg(test)]
2696+pub(crate) fn take_palette_hits() -> [usize; 9] {
2697+ std::array::from_fn(|i| PALETTE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2698+}
2699+
2345 /// Writes one coded block: its mode, its three transform blocks, and what it2700 /// Writes one coded block: its mode, its three transform blocks, and what it
2346 /// leaves behind for the blocks beside it. Its partition symbol is already2701 /// leaves behind for the blocks beside it. Its partition symbol is already
2347 /// written, because only the caller knows what tree led here.2702 /// written, because only the caller knows what tree led here.
@@ -2366,14 +2721,17 @@ fn write_block(
2366 ) -> Result<()> {2721 ) -> Result<()> {
2367 let (r, c) = at;2722 let (r, c) = at;
2368 let at_mi = (r * (SUB / MI), c * (SUB / MI));2723 let at_mi = (r * (SUB / MI), c * (SUB / MI));
2724+ let (above_mode, left_mode) = (neighbours.above_mode[c], neighbours.left_mode[r]);
2369 let mode = write_intra_mode(2725 let mode = write_intra_mode(
2370 enc,2726 enc,
2371 cdfs,2727 cdfs,
2728+ neighbours,
2372 block,2729 block,
2373- neighbours.above_mode[c],2730+ above_mode,
2374- neighbours.left_mode[r],2731+ left_mode,
2375 cfl,2732 cfl,
2376 at_mi,2733 at_mi,
2734+ side,
2377 );2735 );
2378 let split = if tx_select {2736 let split = if tx_select {
2379 let tx = write_luma_select(2737 let tx = write_luma_select(
@@ -2448,7 +2806,7 @@ fn write_leaf8(
2448 // true first divergence (a differently-sized alphabet under the same2806 // true first divergence (a differently-sized alphabet under the same
2449 // DC_PRED decision desyncs the coder even though the decoded mode is2807 // DC_PRED decision desyncs the coder even though the decoded mode is
2450 // unchanged).2808 // unchanged).
2451- let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi);2809+ let mode = write_intra_mode(enc, cdfs, neighbours, block, above_mode, left_mode, true, leaf_mi, 8);
2452 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];2810 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
2453 let split = if tx_select {2811 let split = if tx_select {
2454 let tx = write_luma_select(2812 let tx = write_luma_select(
@@ -4250,6 +4608,16 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
4250 // Intra: no vote, but still a coded cell -- mvstack's4608 // Intra: no vote, but still a coded cell -- mvstack's
4251 // extended-scan coverage must see it (module doc).4609 // extended-scan coverage must see it (module doc).
4252 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);4610 let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8);
4611+ write_palette_syntax(
4612+ &mut enc,
4613+ &mut cdfs,
4614+ &mut neighbours,
4615+ block.palette.as_ref(),
4616+ mode,
4617+ uv_mode,
4618+ (mi_row, mi_col),
4619+ BLOCK,
4620+ );
4253 for dr in 0..8 {4621 for dr in 0..8 {
4254 for dc in 0..8 {4622 for dc in 0..8 {
4255 grid.set(4623 grid.set(
@@ -4463,6 +4831,16 @@ fn write_inter_frame_leaf(
4463 // Intra: no vote, but still a coded cell -- mvstack's extended-scan4831 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
4464 // coverage must see it (module doc).4832 // coverage must see it (module doc).
4465 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);4833 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4834+ write_palette_syntax(
4835+ enc,
4836+ cdfs,
4837+ neighbours,
4838+ block.palette.as_ref(),
4839+ mode,
4840+ uv_mode,
4841+ (mi_row, mi_col),
4842+ SUB,
4843+ );
4466 for dr in 0..SUB_MI as usize {4844 for dr in 0..SUB_MI as usize {
4467 for dc in 0..SUB_MI as usize {4845 for dc in 0..SUB_MI as usize {
4468 grid.set(4846 grid.set(
@@ -4682,6 +5060,16 @@ fn write_inter_frame_leaf8(
4682 // Intra: no vote, but still a coded cell -- mvstack's extended-scan5060 // Intra: no vote, but still a coded cell -- mvstack's extended-scan
4683 // coverage must see it (module doc).5061 // coverage must see it (module doc).
4684 let (mi_row, mi_col) = leaf_mi;5062 let (mi_row, mi_col) = leaf_mi;
5063+ write_palette_syntax(
5064+ enc,
5065+ cdfs,
5066+ neighbours,
5067+ block.palette.as_ref(),
5068+ mode,
5069+ uv_mode,
5070+ leaf_mi,
5071+ 8,
5072+ );
4685 for dr in 0..2 {5073 for dr in 0..2 {
4686 for dc in 0..2 {5074 for dc in 0..2 {
4687 grid.set(5075 grid.set(