forge
Explore
Log in

Don't you dare go Hollow

The screen-content detector needs libaom's variance term

Browse files at this commit

47036af6f94f9a63782857cbc22ed1187c6cd0b6Ahmet Kaan GümüşParent: 1aa39c7
  • fix
    • the screen-content detector needs libaom's variance term
Show full message
fix(av1): the screen-content detector needs libaom's variance term

Without it a smooth dark film frame is all few-colour 16x16 blocks, so
both real films of the native gate classified as screen content on 48/48
frames: palette search ran over film and every coefficient was priced
against the default CDFs instead of the frame's real tables.

probe_screen_detect now sweeps the colour bound against a per-block
variance floor on all five native gate rows (native_gate_clips, shared
with the gate) at both the native crop and the 640x384 gate's scale.
16 colours / var > 16 / an eighth of the frame separates them: every
non-screen row at most 9.6% of blocks, the OBS capture 17.9-23.6%.
crates/ec-av1/src/encode.rsmodified+170 -110
@@ -954,33 +954,56 @@ fn seq_screen() -> bool {
954 954
955 /// How many distinct colours a 16x16 luma block may hold and still count as955 /// How many distinct colours a 16x16 luma block may hold and still count as
956 /// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own956 /// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
957-/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a957+/// `av1_set_screen_content_options` bound is 4, which separates nothing on
958-/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect`958+/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
959-/// measures the share of 16x16 blocks under each bound on the gate's own959+/// the variance floor below on the five gate clips at BOTH the native crop
960-/// three clips, and only at 32 do the populations part -- film 20.3..21.9%,960+/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
961-/// his OBS capture 51.1..51.5%.961+/// the frame is the widest-margin split of those ten rows -- every
962+/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
963+/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
964+/// native and 17.9% scaled.
962 fn screen_colors() -> usize {965 fn screen_colors() -> usize {
963 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();966 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
964 *N.get_or_init(|| {967 *N.get_or_init(|| {
965 std::env::var("EC_AV1_SCREEN_COLORS")968 std::env::var("EC_AV1_SCREEN_COLORS")
966 .ok()969 .ok()
967 .and_then(|v| v.parse().ok())970 .and_then(|v| v.parse().ok())
968- .unwrap_or(32)971+ .unwrap_or(16)
969 })972 })
970 }973 }
971 974
972 /// The reciprocal of the frame area those blocks must cover, in tenths --975 /// The reciprocal of the frame area those blocks must cover, in tenths --
973-/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one976+/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
974-/// tenth). 3 (a third) is the midpoint of the two populations977+/// 8 (an eighth) is the midpoint of the two populations
975-/// `probe_screen_detect` measured at the colour bound above.978+/// `probe_screen_detect` measures at the colour bound and variance floor
976-/// `EC_AV1_SCREEN_PCT`.979+/// around it. `EC_AV1_SCREEN_PCT`.
977 fn screen_pct() -> usize {980 fn screen_pct() -> usize {
978 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();981 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
979 *N.get_or_init(|| {982 *N.get_or_init(|| {
980 std::env::var("EC_AV1_SCREEN_PCT")983 std::env::var("EC_AV1_SCREEN_PCT")
981 .ok()984 .ok()
982 .and_then(|v| v.parse().ok())985 .and_then(|v| v.parse().ok())
983- .unwrap_or(3)986+ .unwrap_or(10)
987+ })
988+}
989+
990+/// The per-pixel variance a few-colour block must clear before it counts as
991+/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
992+/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
993+/// a smooth dark film frame is all few-colour blocks and reads as a desktop
994+/// capture -- which is exactly what this detector did until 2026-09-07, when
995+/// it called BOTH real films screen content on 48/48 frames, priced every
996+/// coefficient against the default CDFs and ran the palette search over
997+/// film. `probe_screen_detect`: at 16 colours the floor takes both films
998+/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
999+/// 23.6%.
1000+fn screen_var() -> u64 {
1001+ static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1002+ *N.get_or_init(|| {
1003+ std::env::var("EC_AV1_SCREEN_VAR")
1004+ .ok()
1005+ .and_then(|v| v.parse().ok())
1006+ .unwrap_or(16)
984 })1007 })
985 }1008 }
986 1009
@@ -992,7 +1015,8 @@ pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
992 /// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count1015 /// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
993 /// the distinct colours of every 16x16 block and turn the screen-content1016 /// the distinct colours of every 16x16 block and turn the screen-content
994 /// tools on when the blocks holding between 2 and [`screen_colors`] of them1017 /// tools on when the blocks holding between 2 and [`screen_colors`] of them
995-/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's1018+/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
1019+/// frame. `width` is the plane's
996 /// stride, `true_*` the frame's real (decodable) extent.1020 /// stride, `true_*` the frame's real (decodable) extent.
997 fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {1021 fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
998 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {1022 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
@@ -1004,23 +1028,28 @@ fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize)
1004 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);1028 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1005 return on;1029 return on;
1006 }1030 }
1007- let (blk, limit) = (16usize, screen_colors());1031+ let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
1008 let mut counted = 0usize;1032 let mut counted = 0usize;
1009 for by in (0..true_height).step_by(blk) {1033 for by in (0..true_height).step_by(blk) {
1010 for bx in (0..true_width).step_by(blk) {1034 for bx in (0..true_width).step_by(blk) {
1011 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));1035 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
1012 let mut seen = [false; 256];1036 let mut seen = [false; 256];
1013- let mut colors = 0usize;1037+ let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1014 for row in 0..h {1038 for row in 0..h {
1015 for col in 0..w {1039 for col in 0..w {
1016- let v = usize::from(y[(by + row) * width + bx + col]);1040+ let v = y[(by + row) * width + bx + col];
1017- if !seen[v] {1041+ sum += u64::from(v);
1018- seen[v] = true;1042+ sq += u64::from(v) * u64::from(v);
1043+ if !seen[usize::from(v)] {
1044+ seen[usize::from(v)] = true;
1019 colors += 1;1045 colors += 1;
1020 }1046 }
1021 }1047 }
1022 }1048 }
1023- if colors > 1 && colors <= limit {1049+ // Per-pixel variance over the block's real (edge-clipped) extent.
1050+ let n = (h * w) as u64;
1051+ let var = (sq - sum * sum / n) / n;
1052+ if colors > 1 && colors <= limit && var > floor {
1024 counted += 1;1053 counted += 1;
1025 }1054 }
1026 }1055 }
@@ -12408,68 +12437,90 @@ mod tests {
12408 }12437 }
12409 }12438 }
12410 12439
12411- /// The sweep behind [`screen_content`]'s two constants12440+ /// The sweep behind [`screen_content`]'s constants
12412- /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at12441+ /// (`unswept-decision-constants`), on the SAME five clips
12413- /// most N distinct colours, per gate clip, at the size the gate codes.12442+ /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
12443+ /// same native crop: for each colour bound N the share of 16x16 luma
12444+ /// blocks with 2..=N distinct colours, and the share of those whose
12445+ /// per-pixel variance also clears a floor V -- libaom's
12446+ /// `av1_set_screen_content_options` counts the variance-cleared blocks
12447+ /// too (its `counts_2`, which gates intrabc), and without that term a
12448+ /// smooth dark film frame reads as screen content.
12414 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`12449 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
12415 #[test]12450 #[test]
12416 #[ignore = "reads the real library"]12451 #[ignore = "reads the real library"]
12417 fn probe_screen_detect() {12452 fn probe_screen_detect() {
12418- let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");12453+ if !have_ffmpeg() {
12419- let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();12454+ eprintln!("SKIP probe_screen_detect: no ffmpeg");
12420- for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {12455+ return;
12421- let path = fixtures.join("video").join(name);
12422- if path.exists() {
12423- clips.push((name.to_string(), path));
12424- }
12425- }
12426- if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
12427- && let Some(p) = manifest
12428- .lines()
12429- .skip(1)
12430- .filter_map(|l| l.split('\t').next())
12431- .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
12432- {
12433- clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
12434 }12456 }
12435- let (width, height) = (640usize, 384usize);12457+ let limits = [4usize, 8, 16, 32, 64, 128];
12436- for (name, path) in &clips {12458+ let floors = [0u64, 4, 16, 64, 256];
12437- let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4);12459+ // The census of one clip at one size: mean share, over the frames, of
12438- for (f, picture) in frames.iter().enumerate() {12460+ // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
12461+ let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
12462+ let mut acc = [[0f64; 5]; 6];
12463+ for picture in frames {
12439 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();12464 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
12440- let mut hist = [0usize; 257];12465+ let mut hit = [[0usize; 5]; 6];
12441 let mut blocks = 0usize;12466 let mut blocks = 0usize;
12442- for by in (0..height).step_by(16) {12467+ for by in (0..ch).step_by(16) {
12443- for bx in (0..width).step_by(16) {12468+ for bx in (0..cw).step_by(16) {
12444 let mut seen = [false; 256];12469 let mut seen = [false; 256];
12445- let mut colors = 0usize;12470+ let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
12446 for row in 0..16 {12471 for row in 0..16 {
12447 for col in 0..16 {12472 for col in 0..16 {
12448- let v = usize::from(y[(by + row) * width + bx + col]);12473+ let v = y[(by + row) * cw + bx + col];
12449- if !seen[v] {12474+ sum += u64::from(v);
12450- seen[v] = true;12475+ sq += u64::from(v) * u64::from(v);
12476+ if !seen[usize::from(v)] {
12477+ seen[usize::from(v)] = true;
12451 colors += 1;12478 colors += 1;
12452 }12479 }
12453 }12480 }
12454 }12481 }
12455- hist[colors] += 1;12482+ let var = (sq - sum * sum / 256) / 256;
12456 blocks += 1;12483 blocks += 1;
12484+ for (li, &limit) in limits.iter().enumerate() {
12485+ if colors > 1 && colors <= limit {
12486+ for (fi, &floor) in floors.iter().enumerate() {
12487+ hit[li][fi] += usize::from(var > floor);
12488+ }
12489+ }
12490+ }
12457 }12491 }
12458 }12492 }
12459- let share = |limit: usize| {12493+ for li in 0..6 {
12460- 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f6412494+ for fi in 0..5 {
12461- / blocks.max(1) as f6412495+ acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
12462- };12496+ }
12497+ }
12498+ }
12499+ let n = frames.len().max(1) as f64;
12500+ eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
12501+ eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
12502+ for (li, &limit) in limits.iter().enumerate() {
12463 eprintln!(12503 eprintln!(
12464- "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%",12504+ " {limit:>5} |{}",
12465- share(4),12505+ (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
12466- share(8),
12467- share(16),
12468- share(32),
12469- share(64),
12470- share(128),
12471 );12506 );
12472 }12507 }
12508+ };
12509+ for (name, path, seek) in native_gate_clips() {
12510+ let Some((nw, nh)) = probe_dims(&path) else {
12511+ eprintln!("SKIP {name}: ffprobe gave no size");
12512+ continue;
12513+ };
12514+ let cw = nw.min(1920) / 128 * 128;
12515+ let ch = nh.min(1024) / 128 * 128;
12516+ let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
12517+ let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
12518+ census(&name, &frames, cw, ch);
12519+ // The 640x384 gate scales instead of cropping, and the scaling
12520+ // changes the census (bars smooth out): the constants have to
12521+ // separate at BOTH sizes.
12522+ let small = clip_frames(&path, &seek, 640, 384, 12);
12523+ census(&name, &small, 640, 384);
12473 }12524 }
12474 }12525 }
12475 12526
@@ -12932,56 +12983,11 @@ mod tests {
12932 Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?))12983 Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?))
12933 }12984 }
12934 12985
12935- /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate12986+ /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
12936- /// downscales the OBS capture to 640x384, which destroys exactly the12987+ /// with `probe_screen_detect` so the detector sweep measures exactly the
12937- /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist12988+ /// clips the keep table is read off. Selector env vars as documented on
12938- /// for (class `gate-recipe-confound`), so every screen-tool decision taken12989+ /// the gate; a missing clip prints a SKIP and drops its row.
12939- /// on that recipe is taken on content the tool cannot serve. This arm12990+ fn native_gate_clips() -> Vec<(String, String, String)> {
12940- /// crops -- never scales -- a superblock-aligned window out of the middle
12941- /// of the capture at its own resolution (at most 1920x1024, so the wall
12942- /// stays in the minutes) and runs the same 12-frame, four-quantizer
12943- /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
12944- /// thread, with the same three-way (encoder / ffmpeg / our decoder)
12945- /// sample-exactness assertion `our_ladder` makes.
12946- ///
12947- /// It is its own `--ignored` test so the default gate's wall does not
12948- /// grow. Every variant is an environment knob, and each of those is a
12949- /// `OnceLock` read once per process, so a variant is a separate run:
12950- ///
12951- /// cargo test -p ec-av1 --release --lib -- --ignored \
12952- /// bd_rate_screen_native --nocapture # baseline
12953- /// EC_AV1_INTRABC=1 ... same command # intra block copy
12954- /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
12955- /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
12956- /// EC_AV1_PYRAMID=4:-16:8 ... same command # coding pyramid
12957- ///
12958- /// Under `EC_AV1_PYRAMID` this arm codes its ladder through the streaming
12959- /// facade ([`our_ladder_pyramid`]), which exposes no per-packet
12960- /// reconstruction: that path asserts ffmpeg's decode against our own
12961- /// decoder on all three planes in display order, and prints the per-level
12962- /// frame and byte census.
12963- ///
12964- /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
12965- /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
12966- /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
12967- /// cost -- so every "film" column in the historical tables of this file
12968- /// is that generator, not film. The real content is `film A`, `film B`
12969- /// (native crops out of the two AV1 films the real-library manifest
12970- /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
12971- /// decision only the bars rows support is not supported.
12972- ///
12973- /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
12974- /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
12975- /// setting any one of them keeps only the selected rows (the two 1080p
12976- /// rows, the two 2160p rows, the capture row respectively). A missing
12977- /// real film SKIPs its row; it never fails the gate.
12978- #[test]
12979- #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
12980- fn bd_rate_screen_native() {
12981- if !have_ffmpeg() {
12982- eprintln!("SKIP bd_rate_screen_native: no ffmpeg");
12983- return;
12984- }
12985 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");12991 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
12986 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");12992 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
12987 let (film, film4k, screen) = (12993 let (film, film4k, screen) = (
@@ -13062,6 +13068,60 @@ mod tests {
13062 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),13068 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
13063 }13069 }
13064 }13070 }
13071+ clips
13072+ }
13073+
13074+ /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
13075+ /// downscales the OBS capture to 640x384, which destroys exactly the
13076+ /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
13077+ /// for (class `gate-recipe-confound`), so every screen-tool decision taken
13078+ /// on that recipe is taken on content the tool cannot serve. This arm
13079+ /// crops -- never scales -- a superblock-aligned window out of the middle
13080+ /// of the capture at its own resolution (at most 1920x1024, so the wall
13081+ /// stays in the minutes) and runs the same 12-frame, four-quantizer
13082+ /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
13083+ /// thread, with the same three-way (encoder / ffmpeg / our decoder)
13084+ /// sample-exactness assertion `our_ladder` makes.
13085+ ///
13086+ /// It is its own `--ignored` test so the default gate's wall does not
13087+ /// grow. Every variant is an environment knob, and each of those is a
13088+ /// `OnceLock` read once per process, so a variant is a separate run:
13089+ ///
13090+ /// cargo test -p ec-av1 --release --lib -- --ignored \
13091+ /// bd_rate_screen_native --nocapture # baseline
13092+ /// EC_AV1_INTRABC=1 ... same command # intra block copy
13093+ /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
13094+ /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
13095+ /// EC_AV1_PYRAMID=4:-16:8 ... same command # coding pyramid
13096+ ///
13097+ /// Under `EC_AV1_PYRAMID` this arm codes its ladder through the streaming
13098+ /// facade ([`our_ladder_pyramid`]), which exposes no per-packet
13099+ /// reconstruction: that path asserts ffmpeg's decode against our own
13100+ /// decoder on all three planes in display order, and prints the per-level
13101+ /// frame and byte census.
13102+ ///
13103+ /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
13104+ /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
13105+ /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
13106+ /// cost -- so every "film" column in the historical tables of this file
13107+ /// is that generator, not film. The real content is `film A`, `film B`
13108+ /// (native crops out of the two AV1 films the real-library manifest
13109+ /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
13110+ /// decision only the bars rows support is not supported.
13111+ ///
13112+ /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
13113+ /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
13114+ /// setting any one of them keeps only the selected rows (the two 1080p
13115+ /// rows, the two 2160p rows, the capture row respectively). A missing
13116+ /// real film SKIPs its row; it never fails the gate.
13117+ #[test]
13118+ #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
13119+ fn bd_rate_screen_native() {
13120+ if !have_ffmpeg() {
13121+ eprintln!("SKIP bd_rate_screen_native: no ffmpeg");
13122+ return;
13123+ }
13124+ let clips = native_gate_clips();
13065 if clips.is_empty() {13125 if clips.is_empty() {
13066 eprintln!("SKIP bd_rate_screen_native: no clip");13126 eprintln!("SKIP bd_rate_screen_native: no clip");
13067 return;13127 return;