forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1price2' (50b7ad42): the frame-tables coefficient price is the default on non-screen frames

Browse files at this commit

fbeac1907cf3c14828d0c02f07907a2de05ceaf7Ahmet Kaan GümüşParent: 1dee32dd4a3234
Native crops: film 1080p +18.7/+1.4 -> +18.0/+0.7, film 2160p +48.1/+19.8
-> +47.3/+19.2, screen byte-identical (the detector fires on every screen
frame). At 640x384 the 2160p clip regresses +0.5/+0.7; the native table
is the standing recipe for this decision.
crates/ec-av1/src/encode.rsmodified+106 -14
@@ -4545,7 +4545,7 @@ pub(crate) fn encode_key_frame_inner(
4545 // A key frame's writer really does start from the defaults, and a search4545 // A key frame's writer really does start from the defaults, and a search
4546 // worker may be carrying an inter frame's armed tables (lane-av1txbits):4546 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
4547 // disarm, or a key frame's bits would depend on which thread searched it.4547 // disarm, or a key frame's bits would depend on which thread searched it.
4548- crate::tile::arm_pricing_cdfs(None);4548+ crate::tile::arm_pricing_cdfs(None, false);
4549 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit4549 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
4550 // forces deblocking, CDEF and loop restoration OFF for this frame4550 // forces deblocking, CDEF and loop restoration OFF for this frame
4551 // (frame.rs:194/210/252/272), so it is only set when the source repeats4551 // (frame.rs:194/210/252/272), so it is only set when the source repeats
@@ -4685,7 +4685,7 @@ pub(crate) fn encode_key_frame_inner(
4685 let search_tile = |index: usize,4685 let search_tile = |index: usize,
4686 fctx: &crate::decode::FrameCtx|4686 fctx: &crate::decode::FrameCtx|
4687 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {4687 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
4688- crate::tile::arm_pricing_cdfs(None);4688+ crate::tile::arm_pricing_cdfs(None, false);
4689 let rect = layout.rect(index);4689 let rect = layout.rect(index);
4690 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);4690 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
4691 let mut chroma = [4691 let mut chroma = [
@@ -4963,7 +4963,7 @@ pub(crate) fn encode_key_frame_inner(
4963 let mut cdfs = start_cdfs.0.clone();4963 let mut cdfs = start_cdfs.0.clone();
4964 crate::tile::arm_screen(screen);4964 crate::tile::arm_screen(screen);
4965 crate::tile::arm_intrabc(allow_intrabc);4965 crate::tile::arm_intrabc(allow_intrabc);
4966- crate::tile::arm_pricing_cdfs(None);4966+ crate::tile::arm_pricing_cdfs(None, false);
4967 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(4967 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
4968 mi_cols,4968 mi_cols,
4969 mi_rows,4969 mi_rows,
@@ -6403,9 +6403,6 @@ pub(crate) fn encode_inter_frame(
6403 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob6403 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
6404 // never reached the tool).6404 // never reached the tool).
6405 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);6405 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6406- // The search prices coefficients against the tables this frame's writer
6407- // starts from, not against the defaults (lane-av1txbits).
6408- crate::tile::arm_pricing_cdfs(start_cdfs);
6409 if let Some(p) = pyramid {6406 if let Some(p) = pyramid {
6410 header.show_frame = p.show_frame;6407 header.show_frame = p.show_frame;
6411 header.showable_frame = !p.show_frame;6408 header.showable_frame = !p.show_frame;
@@ -6434,6 +6431,11 @@ pub(crate) fn encode_inter_frame(
6434 let screen = seq_screen()6431 let screen = seq_screen()
6435 && screen_content(&picture_y8, picture.width, true_width, true_height);6432 && screen_content(&picture_y8, picture.width, true_width, true_height);
6436 header.allow_screen_content_tools = screen;6433 header.allow_screen_content_tools = screen;
6434+ // The search prices coefficients against the tables this frame's writer
6435+ // starts from, not against the defaults (lane-av1txbits) -- but only on a
6436+ // frame the screen detector said no to (lane-av1price2): armed HERE, after
6437+ // `screen` exists, and again on every search/tile worker below.
6438+ crate::tile::arm_pricing_cdfs(start_cdfs, screen);
6437 let mut luma = Plane {6439 let mut luma = Plane {
6438 source: &picture_y8,6440 source: &picture_y8,
6439 reconstruction: vec![128; picture_y8.len()],6441 reconstruction: vec![128; picture_y8.len()],
@@ -6526,7 +6528,7 @@ pub(crate) fn encode_inter_frame(
6526 // search step) is read by the SEARCH, so every worker arms it or the6528 // search step) is read by the SEARCH, so every worker arms it or the
6527 // tile's bits depend on the thread count.6529 // tile's bits depend on the thread count.
6528 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);6530 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6529- crate::tile::arm_pricing_cdfs(start_cdfs);6531+ crate::tile::arm_pricing_cdfs(start_cdfs, screen);
6530 let rect = layout.rect(index);6532 let rect = layout.rect(index);
6531 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);6533 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
6532 let mut chroma = [6534 let mut chroma = [
@@ -6997,7 +6999,7 @@ pub(crate) fn encode_inter_frame(
6997 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);6999 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
6998 crate::tile::arm_screen(screen);7000 crate::tile::arm_screen(screen);
6999 let mut cdfs = start_cdfs.0.clone();7001 let mut cdfs = start_cdfs.0.clone();
7000- crate::tile::arm_pricing_cdfs(Some(&cdfs));7002+ crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
7001 // Each tile's own MV grid: a candidate scan never reaches past7003 // Each tile's own MV grid: a candidate scan never reaches past
7002 // the tile's bounds, so a grid holding only this tile's own7004 // the tile's bounds, so a grid holding only this tile's own
7003 // blocks reads exactly as the decoder's frame-wide one does7005 // blocks reads exactly as the decoder's frame-wide one does
@@ -9486,12 +9488,13 @@ mod tests {
9486 // (compound share 8.8% -> 11.5%): a compound block carries a second9488 // (compound share 8.8% -> 11.5%): a compound block carries a second
9487 // reference tree, a compound mode symbol and -- for the half-new modes9489 // reference tree, a compound mode symbol and -- for the half-new modes
9488 // -- an MV residual, none of which the coefficient sum counts.9490 // -- an MV residual, none of which the coefficient sum counts.
9489- // lane-av1txbits: under `EC_AV1_PRICE_FRAME_CDFS=1` this reads +32.6%9491+ // lane-av1txbits: pricing against the tables the frame's writer really
9490- // instead -- pricing against the tables the frame's writer really
9491 // starts from collapses the over-price above to nothing, so the whole9492 // starts from collapses the over-price above to nothing, so the whole
9492- // remaining gap is the syntax the coefficient sum leaves out.9493+ // remaining gap is the syntax the coefficient sum leaves out. That is
9494+ // the default on a non-screen frame since lane-av1price2 (this
9495+ // fixture is one), and it reads +32.6% here.
9493 assert!(9496 assert!(
9494- worst_under <= 0.32,9497+ worst_under <= 0.34,
9495 "the writer spent {:.2}% more than the search priced -- more than \9498 "the writer spent {:.2}% more than the search priced -- more than \
9496 the mode/mv syntax outside the coefficient sum explains",9499 the mode/mv syntax outside the coefficient sum explains",
9497 worst_under * 100.09500 worst_under * 100.0
@@ -9541,6 +9544,80 @@ mod tests {
9541 assert!(written_all > 0.0);9544 assert!(written_all > 0.0);
9542 }9545 }
9543 9546
9547+ /// Step (2) of the pricer lane: the same census, but on the REAL clips
9548+ /// the BD gate scores -- one film clip and the screen capture -- so the
9549+ /// question the film/screen split raises can be answered from data. Real
9550+ /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
9551+ /// the screen capture larger, and the census says why: on a screen
9552+ /// capture the frame's own starting tables are the tables of a frame that
9553+ /// coded PALETTE and long runs of zero blocks, so they are far from the
9554+ /// tables the writer ends the frame with; the pricer error does not fall
9555+ /// the way it does on film.
9556+ ///
9557+ /// Not a gate -- it prints. Run it once per mode:
9558+ /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
9559+ /// --ignored pricer_error_census_on_clips --nocapture
9560+ #[test]
9561+ #[ignore = "reads the real library, needs ffmpeg"]
9562+ fn pricer_error_census_on_clips() {
9563+ if !have_ffmpeg() {
9564+ eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
9565+ return;
9566+ }
9567+ let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
9568+ let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
9569+ let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
9570+ if film.exists() {
9571+ clips.push(("film 1080p".to_string(), film));
9572+ }
9573+ if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
9574+ && let Some(p) = manifest
9575+ .lines()
9576+ .skip(1)
9577+ .filter_map(|l| l.split('\t').next())
9578+ .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
9579+ {
9580+ clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
9581+ }
9582+ assert!(!clips.is_empty(), "no source clip available");
9583+ let (width, height, frames) = (640usize, 384usize, 6usize);
9584+ for (name, path) in &clips {
9585+ let fctx = &crate::decode::FrameCtx::new();
9586+ let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
9587+ SCREEN_FRAMES.iter().for_each(|c| {
9588+ c.store(0, std::sync::atomic::Ordering::Relaxed);
9589+ });
9590+ let _ = crate::tile::take_pricing_hits();
9591+ crate::tile::pricer_census_on();
9592+ let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
9593+ let rows = crate::tile::take_pricer_census();
9594+ let (price_default, price_real) = crate::tile::take_pricing_hits();
9595+ let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
9596+ println!(
9597+ "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
9598+ {screen_on}, pricer armings default={price_default} real={price_real}"
9599+ );
9600+ println!("| set | nz | blocks | priced bits | written bits | error |");
9601+ println!("|---|---|---|---|---|---|");
9602+ let (mut priced_all, mut written_all) = (0.0, 0.0);
9603+ for ((set, bucket), (blocks, priced, written)) in &rows {
9604+ priced_all += priced;
9605+ written_all += written;
9606+ println!(
9607+ "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
9608+ crate::tile::census_bucket_label(*bucket),
9609+ if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
9610+ );
9611+ }
9612+ println!(
9613+ "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
9614+ rows.values().map(|r| r.0).sum::<u64>(),
9615+ (priced_all - written_all) / written_all * 100.0
9616+ );
9617+ assert!(written_all > 0.0, "{name}: the census saw no transform block");
9618+ }
9619+ }
9620+
9544 /// Low motion has to actually buy something: at least one inter frame of9621 /// Low motion has to actually buy something: at least one inter frame of
9545 /// a panning sequence has to cost fewer bytes than the key frame that9622 /// a panning sequence has to cost fewer bytes than the key frame that
9546 /// starts it, and the inter-block share it prints has to be non-zero --9623 /// starts it, and the inter-block share it prints has to be non-zero --
@@ -10446,7 +10523,10 @@ mod tests {
10446 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits10523 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
10447 /// in the tile) and again on lane-av1mv's merge of it: an extra10524 /// in the tile) and again on lane-av1mv's merge of it: an extra
10448 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate10525 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
10449- /// above, not by this pin.10526+ /// above, not by this pin. Re-pinned on lane-av1price2: the search now
10527+ /// prices coefficients against the tables the frame's writer really
10528+ /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
10529+ /// decision change the BD gate judges.
10450 #[test]10530 #[test]
10451 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {10531 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
10452 if !have_ffmpeg() {10532 if !have_ffmpeg() {
@@ -10468,7 +10548,7 @@ mod tests {
10468 })10548 })
10469 };10549 };
10470 let pins: [(u8, usize, u64); 2] =10550 let pins: [(u8, usize, u64); 2] =
10471- [(150, 7084, 0x00bc_da74_e540_28d7), (60, 25905, 0x1623_f794_727e_0716)];10551+ [(150, 7106, 0x1da4_9acd_a892_68e3), (60, 25963, 0x94df_8f46_174e_1a5e)];
10472 for (q, bytes, hash) in pins {10552 for (q, bytes, hash) in pins {
10473 let encoded = encode_sequence(&source, q, 0.5).unwrap();10553 let encoded = encode_sequence(&source, q, 0.5).unwrap();
10474 assert_eq!(10554 assert_eq!(
@@ -10862,6 +10942,12 @@ mod tests {
10862 // and of what size. A film clip must print `screen frames on=0`.10942 // and of what size. A film clip must print `screen frames on=0`.
10863 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);10943 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
10864 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);10944 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
10945+ // Which tables the SEARCH priced against, per frame arming
10946+ // (`tile::arm_pricing_cdfs`): the default tables or the frame's
10947+ // real starting ones. A film clip must show every inter arming on
10948+ // the real side, a screen clip none of them.
10949+ let (price_default, price_real) = crate::tile::take_pricing_hits();
10950+ eprintln!("{name}: pricer armings default={price_default} real={price_real}");
10865 let palette = crate::tile::take_palette_hits();10951 let palette = crate::tile::take_palette_hits();
10866 eprintln!(10952 eprintln!(
10867 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",10953 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
@@ -11132,6 +11218,12 @@ mod tests {
11132 // native resolution, over this clip's four encodes.11218 // native resolution, over this clip's four encodes.
11133 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);11219 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
11134 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);11220 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
11221+ // Which tables the SEARCH priced against, per frame arming
11222+ // (`tile::arm_pricing_cdfs`): the default tables or the frame's
11223+ // real starting ones. A film clip must show every inter arming on
11224+ // the real side, a screen clip none of them.
11225+ let (price_default, price_real) = crate::tile::take_pricing_hits();
11226+ eprintln!("{name}: pricer armings default={price_default} real={price_real}");
11135 let palette = crate::tile::take_palette_hits();11227 let palette = crate::tile::take_palette_hits();
11136 let palette_uv = crate::tile::take_palette_uv_hits();11228 let palette_uv = crate::tile::take_palette_uv_hits();
11137 let ibc = crate::tile::take_intrabc_hits();11229 let ibc = crate::tile::take_intrabc_hits();
crates/ec-av1/src/tile.rsmodified+91 -14
@@ -13,6 +13,7 @@ use std::cell::RefCell;
13 #[cfg(test)]13 #[cfg(test)]
14 use std::collections::BTreeMap;14 use std::collections::BTreeMap;
15 use std::sync::LazyLock;15 use std::sync::LazyLock;
16+use std::sync::atomic::{AtomicUsize, Ordering};
16 17
17 use ec_core::{Error, Result};18 use ec_core::{Error, Result};
18 19
@@ -3965,6 +3966,21 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
3965 /// the four points of the BD ladder were priced against another quantizer's3966 /// the four points of the BD ladder were priced against another quantizer's
3966 /// tables), and against the contexts a block whose neighbours coded nothing3967 /// tables), and against the contexts a block whose neighbours coded nothing
3967 /// reads.3968 /// reads.
3969+///
3970+/// That last assumption -- `skip_ctx` 0, `sign_ctx` 0 -- is the largest
3971+/// remaining row of the census and lane-av1price2 did NOT close it: every
3972+/// all-zero block is priced at the `txb_skip` cost of a block whose
3973+/// neighbours coded nothing, which is the most expensive context there is, so
3974+/// an all-zero chroma block is UNDER-priced by 41-81% on film and 51-73% on
3975+/// the screen capture (`pricer_error_census_on_clips`), and an all-zero
3976+/// Luma4 is over-priced by 400%+. Arming the frame's real tables does not
3977+/// touch those rows (Chroma8 nz=0 reads -73.0% in both modes). Pricing them
3978+/// right needs the real neighbour context, which needs something the search
3979+/// does not have: a per-plane non-zero context map committed in coding order.
3980+/// The search ranks partition TREES, so it prices candidates whose neighbours
3981+/// are not yet decided; the map would have to be built per trial, not per
3982+/// block. Deferred with the numbers above rather than approximated by a
3983+/// fitted constant.
3968 pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {3984 pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
3969 /// Built once per size: the search prices thirteen modes for every block,3985 /// Built once per size: the search prices thirteen modes for every block,
3970 /// and the scan is the same table every time.3986 /// and the scan is the same table every time.
@@ -4044,29 +4060,90 @@ thread_local! {
4044 4060
4045 /// Arms the tables [`coeff_bits`] prices against on this thread: the state4061 /// Arms the tables [`coeff_bits`] prices against on this thread: the state
4046 /// this frame's tile writer starts from. `None` goes back to the per-q-context4062 /// this frame's tile writer starts from. `None` goes back to the per-q-context
4047-/// defaults (a key frame, whose writer really does start there).4063+/// defaults (a key frame, whose writer really does start there), and so does
4064+/// any frame the screen detector said yes to (`screen`).
4065+///
4066+/// ON by default for non-screen frames since lane-av1price2;
4067+/// `EC_AV1_PRICE_FRAME_CDFS` selects 0 = never (the pre-lane behaviour),
4068+/// 1 = always, unset/2 = the screen-gated default.
4048 ///4069 ///
4049-/// OFF by default (`EC_AV1_PRICE_FRAME_CDFS=1`). It is the more accurate4070+/// Pricing against the frame's REAL starting tables is the more accurate
4050 /// estimate by measurement -- the pricer census4071 /// estimate by measurement -- the pricer census
4051 /// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every4072 /// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every
4052 /// transform block, and the one- and two-coefficient inter blocks the search4073 /// transform block, and the one- and two-coefficient inter blocks the search
4053-/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy does not4074+/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy only
4054-/// convert into ladder bytes on every clip: on the 640x384 gate it scores4075+/// converts into ladder bytes on camera content. Measured on ONE build
4055-/// +78.8/+95.1/+54.5 vs libaom and +36.1/+56.4/+1.4 vs rav1e against the4076+/// (lane-av1price2, mode 0 vs mode 2), BD-rate vs libaom / vs rav1e:
4056-/// +79.9/+94.6/+54.5 and +37.3/+55.7/+1.1 the defaults score (film 1080p4077+///
4057-/// down 1.1, film 2160p up 0.5, screen flat), and on the native crops4078+/// | clip | 640x384 base | 640x384 gated | native base | native gated |
4058-/// +18.0/+47.3/+60.7 and +0.7/+19.2/-7.3 against +18.9/+48.2/+59.3 and4079+/// |---|---|---|---|---|
4059-/// +1.5/+19.8/-10.0 (both film clips down against both references, screen up4080+/// | film 1080p | +79.9 / +37.3 | +78.8 / +36.1 | +18.7 / +1.4 | +18.0 / +0.7 |
4060-/// 1.4/2.7). Two clips better, one worse: it does not meet this lane's keep4081+/// | film 2160p | +94.6 / +55.7 | +95.1 / +56.4 | +48.1 / +19.8 | +47.3 / +19.2 |
4061-/// rule, so it ships as a knob rather than as the default.4082+/// | screen | +54.5 / +1.1 | +54.5 / +1.1 | +59.4 / -10.0 | +59.4 / -10.0 |
4062-pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>) {4083+///
4063- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();4084+/// The screen rows are not merely close, they are byte-identical (the ladders
4064- let on = *ON.get_or_init(|| std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() == Ok("1"));4085+/// print 8832/13507/18772/24754 and 39312/52829/70719/92134 in both modes):
4086+/// the gate is per frame and the detector fires on 48 of 48 screen frames, so
4087+/// no screen frame is ever armed with anything but the defaults. At native
4088+/// resolution -- the resolution his library is in -- both films come down
4089+/// against both references and the screen capture is flat, which is this
4090+/// lane's keep rule. At the downscaled 640x384 gate the 2160p film goes the
4091+/// other way (+0.5/+0.7) while the 1080p one comes down further (-1.1/-1.2);
4092+/// the downscale is the same recipe that exaggerated the frame pyramid's loss
4093+/// sixfold, so the native table decides and the 640x384 2160p regression is
4094+/// recorded here rather than argued away.
4095+///
4096+/// Why the screen capture needs the gate at all is in the census
4097+/// (`pricer_error_census_on_clips`, 6 frames of each clip at 640x384, q=100).
4098+/// Real tables take the film clip's total pricer error from +7.8% to +5.3%
4099+/// and flatten its inter classes outright (Luma8Inter/Luma16Inter/Luma32Inter
4100+/// 1-coefficient rows from +11.7%/+17.4%/+24.9% to -0.3%/-5.5%/+8.8%). On the
4101+/// screen capture the total only moves +12.8% -> +10.3%, because the classes
4102+/// that dominate a screen frame are not the ones the tables fix: its chroma
4103+/// stays over-priced (Chroma8 nz=1 +32.2% -> +31.8%, nz=2 +26.2% -> +26.2%,
4104+/// unmoved) and its all-zero blocks stay hugely UNDER-priced (Chroma8 nz=0
4105+/// -73.0% -> -73.0%, Luma4 nz=0 +464% -> +467% -- both a pricer that assumes
4106+/// `skip_ctx` 0, not a table set). So on screen the change makes the inter
4107+/// luma price accurate while leaving the bigger chroma and all-zero errors
4108+/// exactly where they were, which SKEWS the search's tradeoffs between them
4109+/// instead of correcting them -- and the bytes get worse. The fix for that
4110+/// row is the neighbour skip context, not another table set (see
4111+/// [`coeff_bits`]).
4112+pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
4113+ static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
4114+ let mode = *MODE.get_or_init(|| match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() {
4115+ Ok("0") => 0,
4116+ Ok("1") => 1,
4117+ _ => 2,
4118+ });
4119+ let on = match mode {
4120+ 0 => false,
4121+ 1 => true,
4122+ _ => !screen,
4123+ };
4124+ PRICING_HITS[usize::from(on && base.is_some())].fetch_add(1, Ordering::Relaxed);
4065 PRICING_BASE.with_borrow_mut(|slot| {4125 PRICING_BASE.with_borrow_mut(|slot| {
4066 *slot = base.filter(|_| on).map(|c| Box::new((c.clone(), c.clone())));4126 *slot = base.filter(|_| on).map(|c| Box::new((c.clone(), c.clone())));
4067 });4127 });
4068 }4128 }
4069 4129
4130+/// How many times a frame's search was armed with the DEFAULT tables and how
4131+/// many with the frame's REAL starting tables ([`arm_pricing_cdfs`]), so a
4132+/// gate can print which side of the screen gate every frame landed on. Counts
4133+/// arming calls, not frames: a multi-tile frame arms one worker per tile.
4134+pub(crate) static PRICING_HITS: [AtomicUsize; 2] =
4135+ [AtomicUsize::new(0), AtomicUsize::new(0)];
4136+
4137+/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table
4138+/// armings).
4139+#[cfg(test)]
4140+pub(crate) fn take_pricing_hits() -> (usize, usize) {
4141+ (
4142+ PRICING_HITS[0].swap(0, Ordering::Relaxed),
4143+ PRICING_HITS[1].swap(0, Ordering::Relaxed),
4144+ )
4145+}
4146+
4070 /// The pricer census (`pricer_census_on`): for every transform block the tile4147 /// The pricer census (`pricer_census_on`): for every transform block the tile
4071 /// writer really codes, the bits it spent against the bits [`coeff_bits`]4148 /// writer really codes, the bits it spent against the bits [`coeff_bits`]
4072 /// prices those very levels at -- the search's rate term measured against the4149 /// prices those very levels at -- the search's rate term measured against the