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> {
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
crates/ec-av1/src/encode.rsmodified+125 -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,96 @@ 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+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+
708 /// The sequence and frame headers a picture of this size is coded under: one804 /// 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 yet805 /// tile, one transform size per block, no in-loop filter parameters yet
710 /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and806 /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
@@ -788,7 +884,17 @@ pub(crate) fn key_frame_headers_colour(
788 // CDEF simply carries zero strengths.884 // CDEF simply carries zero strengths.
789 enable_cdef: true,885 enable_cdef: true,
790 enable_restoration: true,886 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+ },
792 seq_force_integer_mv: 0,898 seq_force_integer_mv: 0,
793 color_config,899 color_config,
794 still_picture: false,900 still_picture: false,
@@ -3080,7 +3186,19 @@ pub(crate) fn encode_key_frame_inner(
3080 // `render_and_frame_size_different` is false and no render_size bits are3186 // `render_and_frame_size_different` is false and no render_size bits are
3081 // written, mirroring libaom/rav1e: the padded `picture` below is only the3187 // written, mirroring libaom/rav1e: the padded `picture` below is only the
3082 // internal coding surface, never what the header names.3188 // 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);
3083 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;3200 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
3201+ header.allow_screen_content_tools = screen;
3084 header.render_width = render.0 as u32;3202 header.render_width = render.0 as u32;
3085 header.render_height = render.1 as u32;3203 header.render_height = render.1 as u32;
3086 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split3204 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
@@ -3359,6 +3477,7 @@ pub(crate) fn encode_key_frame_inner(
3359 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);3477 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
3360 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));3478 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
3361 let start_cdfs = CdfSnapshot(cdfs.clone());3479 let start_cdfs = CdfSnapshot(cdfs.clone());
3480+ crate::tile::arm_screen(screen);
3362 let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(3481 let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs(
3363 mi_cols,3482 mi_cols,
3364 mi_rows,3483 mi_rows,
@@ -3395,6 +3514,7 @@ pub(crate) fn encode_key_frame_inner(
3395 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());3514 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
3396 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());3515 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
3397 let mut cdfs = start_cdfs.0.clone();3516 let mut cdfs = start_cdfs.0.clone();
3517+ crate::tile::arm_screen(screen);
3398 crate::tile::sb_coeff_key_frame_tile_cdfs(3518 crate::tile::sb_coeff_key_frame_tile_cdfs(
3399 mi_cols,3519 mi_cols,
3400 mi_rows,3520 mi_rows,
@@ -3445,6 +3565,7 @@ pub(crate) fn encode_key_frame_inner(
3445 mi_rows: header.mi_rows,3565 mi_rows: header.mi_rows,
3446 base_q_idx,3566 base_q_idx,
3447 tx_select,3567 tx_select,
3568+ screen,
3448 next_cdfs: start_cdfs.clone(),3569 next_cdfs: start_cdfs.clone(),
3449 start_cdfs,3570 start_cdfs,
3450 loop_filter: header.loop_filter,3571 loop_filter: header.loop_filter,
@@ -5072,6 +5193,9 @@ pub(crate) fn encode_inter_frame(
5072 mi_rows: header.mi_rows,5193 mi_rows: header.mi_rows,
5073 base_q_idx,5194 base_q_idx,
5074 tx_select,5195 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,
5075 start_cdfs,5199 start_cdfs,
5076 next_cdfs,5200 next_cdfs,
5077 loop_filter: header.loop_filter,5201 loop_filter: header.loop_filter,
crates/ec-av1/src/stream.rsmodified+6 -1
@@ -2999,7 +2999,12 @@ 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+42 -1
@@ -160,6 +160,25 @@ pub(crate) fn arm_sign_bias(sign_bias: crate::mvstack::SignBiasTable) {
160 SIGN_BIAS.with(|c| c.set(sign_bias));160 SIGN_BIAS.with(|c| c.set(sign_bias));
161 }161 }
162 162
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+
163 /// Clears the armed plan when the tile writer that consumed it returns.182 /// Clears the armed plan when the tile writer that consumed it returns.
164 struct CdefIdxGuard;183 struct CdefIdxGuard;
165 184
@@ -168,6 +187,7 @@ impl Drop for CdefIdxGuard {
168 CDEF_IDX.with(|c| *c.borrow_mut() = None);187 CDEF_IDX.with(|c| *c.borrow_mut() = None);
169 LR_PLAN.with(|c| *c.borrow_mut() = None);188 LR_PLAN.with(|c| *c.borrow_mut() = None);
170 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));189 SIGN_BIAS.with(|c| c.set(crate::mvstack::NO_SIGN_BIAS));
190+ SCREEN.with(|c| c.set(false));
171 }191 }
172 }192 }
173 193
@@ -1715,6 +1735,9 @@ fn write_intra_mode(
1715 // This block's own position in 4x4 mode-info units, for the `cdef_idx`1735 // This block's own position in 4x4 mode-info units, for the `cdef_idx`
1716 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).1736 // literal that follows the `skip` symbol (see [`write_cdef_idx`]).
1717 mi: (usize, usize),1737 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,
1718 ) -> usize {1741 ) -> usize {
1719 let mode = usize::from(block.mode);1742 let mode = usize::from(block.mode);
1720 enc.symbol(0, &mut cdfs.skip[0]);1743 enc.symbol(0, &mut cdfs.skip[0]);
@@ -1740,6 +1763,23 @@ fn write_intra_mode(
1740 if (V_PRED..=D67_PRED).contains(&uv_mode) {1763 if (V_PRED..=D67_PRED).contains(&uv_mode) {
1741 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);1764 enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[uv_mode - V_PRED]);
1742 }1765 }
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+ }
1743 mode1783 mode
1744 }1784 }
1745 1785
@@ -1775,6 +1815,7 @@ fn write_block(
1775 neighbours.left_mode[r],1815 neighbours.left_mode[r],
1776 cfl,1816 cfl,
1777 at_mi,1817 at_mi,
1818+ side,
1778 );1819 );
1779 let split = if tx_select {1820 let split = if tx_select {
1780 let tx = write_luma_select(1821 let tx = write_luma_select(
@@ -1849,7 +1890,7 @@ fn write_leaf8(
1849 // true first divergence (a differently-sized alphabet under the same1890 // true first divergence (a differently-sized alphabet under the same
1850 // DC_PRED decision desyncs the coder even though the decoded mode is1891 // DC_PRED decision desyncs the coder even though the decoded mode is
1851 // unchanged).1892 // 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);
1853 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];1894 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
1854 let split = if tx_select {1895 let split = if tx_select {
1855 let tx = write_luma_select(1896 let tx = write_luma_select(