forge
Explore
Log in

Don't you dare go Hollow

Screen-content detection sets allow_screen_content_tools on a key frame

Browse files at this commit

3136cbe9e0bc825e9ca58b468ebfcb4284f0486fAhmet Kaan GümüşParent: 39035c8
  • feat
    • screen-content detection sets allow_screen_content_tools on a key frame
Show full message
feat(av1): screen-content detection sets allow_screen_content_tools on a key frame

libaom's `av1_set_screen_content_options` shape (distinct colours per 16x16
luma block, blocks with 2..=4 of them covering more than a tenth of the
frame), run on the source luma before any header is built. When it fires the
sequence header carries the SELECT form of
`seq_force_screen_content_tools` and the key frame sets its own
`allow_screen_content_tools`; every intra block of that tile then codes the
two `read_palette_mode_info` flags (spec 5.11.46), both at ctx 0 and both
"no palette" -- the syntax a palette block will fire inside next.

A sequence with no screen content leaves the sequence bit at 0 and writes
exactly the stream it wrote before: the byte pins do not move.

Verified with the detector forced on (EC_AV1_SCREEN=1):
ffmpeg_decodes_exactly_what_the_encoder_reconstructed and
every_frame_of_a_sequence_decodes_through_our_own_decoder both pass, so the
new symbols are the ones libaom reads.
crates/ec-av1/src/decode.rsmodified+1 -1
@@ -8334,7 +8334,7 @@ fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
83348334 /// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
83358335 /// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
83368336 /// 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> {
83388338 palette_bsize_ctx_wh(side, side)
83398339 }
83408340
crates/ec-av1/src/encode.rsmodified+125 -1
@@ -625,6 +625,7 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En
625625 mi_rows: encoded.mi_rows,
626626 base_q_idx: encoded.base_q_idx,
627627 tx_select: encoded.tx_select,
628+ screen: encoded.screen,
628629 start_cdfs: encoded.start_cdfs.clone(),
629630 next_cdfs: encoded.next_cdfs.clone(),
630631 loop_filter: encoded.loop_filter,
@@ -698,6 +699,11 @@ pub struct Encoded {
698699 /// This frame header's chosen CDEF parameters, threaded for the same
699700 /// reason as `loop_filter`.
700701 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,
701707 /// This frame header's chosen loop restoration parameters, threaded for
702708 /// the same reason as `loop_filter` -- and doubly so: the per-unit
703709 /// filters themselves are coded in `tile`, so a decode of it under a
@@ -705,6 +711,96 @@ pub struct Encoded {
705711 pub(crate) loop_restoration: LoopRestorationParams,
706712 }
707713
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+pub(crate) fn arm_seq_screen(on: bool) {
729+ SEQ_SCREEN.with(|c| c.set(on));
730+}
731+
732+fn seq_screen() -> bool {
733+ SEQ_SCREEN.with(std::cell::Cell::get)
734+}
735+
736+/// How many distinct colours a 16x16 luma block may hold and still count as
737+/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
738+/// `av1_set_screen_content_options` bound is 4.
739+fn screen_colors() -> usize {
740+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
741+ *N.get_or_init(|| {
742+ std::env::var("EC_AV1_SCREEN_COLORS")
743+ .ok()
744+ .and_then(|v| v.parse().ok())
745+ .unwrap_or(4)
746+ })
747+}
748+
749+/// The reciprocal of the frame area those blocks must cover, in tenths --
750+/// libaom's `counts * blk_h * blk_w * 10 > width * height` is 10 (one tenth).
751+/// `EC_AV1_SCREEN_PCT`.
752+fn screen_pct() -> usize {
753+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
754+ *N.get_or_init(|| {
755+ std::env::var("EC_AV1_SCREEN_PCT")
756+ .ok()
757+ .and_then(|v| v.parse().ok())
758+ .unwrap_or(10)
759+ })
760+}
761+
762+/// How many frames [`screen_content`] said yes/no to, so a gate can print
763+/// whether the detector fired at all (class `gate-blind-to-feature`).
764+pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
765+ [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
766+
767+/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
768+/// the distinct colours of every 16x16 block and turn the screen-content
769+/// tools on when the blocks holding between 2 and [`screen_colors`] of them
770+/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's
771+/// stride, `true_*` the frame's real (decodable) extent.
772+fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
773+ if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
774+ let on = v != "0";
775+ SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
776+ return on;
777+ }
778+ let (blk, limit) = (16usize, screen_colors());
779+ let mut counted = 0usize;
780+ for by in (0..true_height).step_by(blk) {
781+ for bx in (0..true_width).step_by(blk) {
782+ let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
783+ let mut seen = [false; 256];
784+ let mut colors = 0usize;
785+ for row in 0..h {
786+ for col in 0..w {
787+ let v = usize::from(y[(by + row) * width + bx + col]);
788+ if !seen[v] {
789+ seen[v] = true;
790+ colors += 1;
791+ }
792+ }
793+ }
794+ if colors > 1 && colors <= limit {
795+ counted += 1;
796+ }
797+ }
798+ }
799+ let on = counted * blk * blk * screen_pct() > true_width * true_height;
800+ SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
801+ on
802+}
803+
708804 /// The sequence and frame headers a picture of this size is coded under: one
709805 /// tile, one transform size per block, no in-loop filter parameters yet
710806 /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
@@ -788,7 +884,17 @@ pub(crate) fn key_frame_headers_colour(
788884 // CDEF simply carries zero strengths.
789885 enable_cdef: true,
790886 enable_restoration: true,
791- seq_force_screen_content_tools: 0,
887+ // SELECT (2) when this sequence's key frame detected screen content
888+ // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
889+ // is then coded in every frame header, and only the frames that want
890+ // the palette syntax set it. 0 -- the forced-off form, no bit at all
891+ // -- otherwise, which is what every non-screen stream this encoder
892+ // writes still carries.
893+ seq_force_screen_content_tools: if seq_screen() {
894+ ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
895+ } else {
896+ 0
897+ },
792898 seq_force_integer_mv: 0,
793899 color_config,
794900 still_picture: false,
@@ -3080,7 +3186,19 @@ pub(crate) fn encode_key_frame_inner(
30803186 // `render_and_frame_size_different` is false and no render_size bits are
30813187 // written, mirroring libaom/rav1e: the padded `picture` below is only the
30823188 // internal coding surface, never what the header names.
3189+ // Screen-content detection runs on the SOURCE luma, before any header is
3190+ // built: it decides this sequence's `seq_force_screen_content_tools` (and
3191+ // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
3192+ // this frame's own `allow_screen_content_tools`.
3193+ let screen = screen_content(
3194+ &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
3195+ picture.width,
3196+ (picture.width).min(render.0),
3197+ (picture.height).min(render.1),
3198+ );
3199+ arm_seq_screen(screen);
30833200 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
3201+ header.allow_screen_content_tools = screen;
30843202 header.render_width = render.0 as u32;
30853203 header.render_height = render.1 as u32;
30863204 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
@@ -3359,6 +3477,7 @@ pub(crate) fn encode_key_frame_inner(
33593477 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
33603478 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
33613479 let start_cdfs = CdfSnapshot(cdfs.clone());
3480+ crate::tile::arm_screen(screen);
33623481 let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
33633482 mi_cols,
33643483 mi_rows,
@@ -3395,6 +3514,7 @@ pub(crate) fn encode_key_frame_inner(
33953514 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
33963515 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
33973516 let mut cdfs = start_cdfs.0.clone();
3517+ crate::tile::arm_screen(screen);
33983518 crate::tile::sb_coeff_key_frame_tile_cdfs(
33993519 mi_cols,
34003520 mi_rows,
@@ -3445,6 +3565,7 @@ pub(crate) fn encode_key_frame_inner(
34453565 mi_rows: header.mi_rows,
34463566 base_q_idx,
34473567 tx_select,
3568+ screen,
34483569 next_cdfs: start_cdfs.clone(),
34493570 start_cdfs,
34503571 loop_filter: header.loop_filter,
@@ -5072,6 +5193,9 @@ pub(crate) fn encode_inter_frame(
50725193 mi_rows: header.mi_rows,
50735194 base_q_idx,
50745195 tx_select,
5196+ // An inter frame of this encoder never sets the bit (its intra blocks
5197+ // code no palette syntax yet -- see the lane report's deferred item).
5198+ screen: false,
50755199 start_cdfs,
50765200 next_cdfs,
50775201 loop_filter: header.loop_filter,
crates/ec-av1/src/stream.rsmodified+6 -1
@@ -2999,7 +2999,12 @@ mod tests {
29992999 encoded.tx_select,
30003000 // Our own encoder always writes `reduced_tx_set: true`.
30013001 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,
30033008 false,
30043009 &encoded.loop_restoration, fctx,
30053010 )
crates/ec-av1/src/tile.rsmodified+42 -1
@@ -160,6 +160,25 @@ pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
160160 SIGN_BIAS.with(|c| c.set(sign_bias));
161161 }
162162
163+thread_local! {
164+ static SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
165+}
166+
167+/// Arms the next tile write with this frame's `allow_screen_content_tools`
168+/// (spec 5.9.2), which is what makes every intra block carry the
169+/// `palette_y_mode`/`palette_uv_mode` symbols spec 5.11.46
170+/// `read_palette_mode_info` reads. Armed the same way [`arm_cdef_idx`]/
171+/// [`arm_sign_bias`] are -- and disarmed by the same guard -- so a frame that
172+/// never detected screen content writes exactly the stream it wrote before
173+/// this lane.
174+pub(crate) fn arm_screen(on: bool) {
175+ SCREEN.with(|c| c.set(on));
176+}
177+
178+fn screen_armed() -> bool {
179+ SCREEN.with(std::cell::Cell::get)
180+}
181+
163182 /// Clears the armed plan when the tile writer that consumed it returns.
164183 struct CdefIdxGuard;
165184
@@ -168,6 +187,7 @@ impl Drop for CdefIdxGuard {
168187 CDEF_IDX.with(|c| *c.borrow_mut() = None);
169188 LR_PLAN.with(|c| *c.borrow_mut() = None);
170189 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
190+ SCREEN.with(|c| c.set(false));
171191 }
172192 }
173193
@@ -1715,6 +1735,9 @@ fn write_intra_mode(
17151735 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
17161736 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
17171737 mi: (usize, usize),
1738+ // The block's side in samples, which gates the palette syntax below
1739+ // (`av1_allow_palette`, [`crate::decode::palette_bsize_ctx`]).
1740+ side: usize,
17181741 ) -> usize {
17191742 let mode = usize::from(block.mode);
17201743 enc.symbol(0, &mut cdfs.skip[0]);
@@ -1740,6 +1763,23 @@ fn write_intra_mode(
17401763 if (V_PRED..=D67_PRED).contains(&uv_mode) {
17411764 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
17421765 }
1766+ // `read_palette_mode_info` (spec 5.11.46), mirrored symbol for symbol from
1767+ // the decoder's own read in `read_intra_mode`: on a frame whose header set
1768+ // `allow_screen_content_tools`, a `DC_PRED` luma block and a `UV_DC_PRED`
1769+ // chroma pair each carry a use-palette flag. Both contexts are 0 here --
1770+ // `av1_get_palette_mode_ctx` counts palette NEIGHBOURS, and this writer
1771+ // codes none -- exactly the ctx-0 read the decoder does under the same
1772+ // condition.
1773+ if screen_armed()
1774+ && let Some(bsize_ctx) = crate::decode::palette_bsize_ctx(side)
1775+ {
1776+ if mode == DC_PRED {
1777+ enc.symbol(0, &mut cdfs.palette_y_mode[bsize_ctx][0]);
1778+ }
1779+ if uv_mode == DC_PRED {
1780+ enc.symbol(0, &mut cdfs.palette_uv_mode[0]);
1781+ }
1782+ }
17431783 mode
17441784 }
17451785
@@ -1775,6 +1815,7 @@ fn write_block(
17751815 neighbours.left_mode[r],
17761816 cfl,
17771817 at_mi,
1818+ side,
17781819 );
17791820 let split = if tx_select {
17801821 let tx = write_luma_select(
@@ -1849,7 +1890,7 @@ fn write_leaf8(
18491890 // true first divergence (a differently-sized alphabet under the same
18501891 // DC_PRED decision desyncs the coder even though the decoded mode is
18511892 // unchanged).
1852- let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi);
1893+ let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi, 8);
18531894 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
18541895 let split = if tx_select {
18551896 let tx = write_luma_select(