diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 58997555..ced2d7d6 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -4545,7 +4545,7 @@ pub(crate) fn encode_key_frame_inner( // A key frame's writer really does start from the defaults, and a search // worker may be carrying an inter frame's armed tables (lane-av1txbits): // disarm, or a key frame's bits would depend on which thread searched it. - crate::tile::arm_pricing_cdfs(None); + crate::tile::arm_pricing_cdfs(None, false); // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit // forces deblocking, CDEF and loop restoration OFF for this frame // (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( let search_tile = |index: usize, fctx: &crate::decode::FrameCtx| -> Result)>> { - crate::tile::arm_pricing_cdfs(None); + crate::tile::arm_pricing_cdfs(None, false); let rect = layout.rect(index); let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); let mut chroma = [ @@ -4963,7 +4963,7 @@ pub(crate) fn encode_key_frame_inner( let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); crate::tile::arm_intrabc(allow_intrabc); - crate::tile::arm_pricing_cdfs(None); + crate::tile::arm_pricing_cdfs(None, false); let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, @@ -6403,9 +6403,6 @@ pub(crate) fn encode_inter_frame( // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob // never reached the tool). crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); - // The search prices coefficients against the tables this frame's writer - // starts from, not against the defaults (lane-av1txbits). - crate::tile::arm_pricing_cdfs(start_cdfs); if let Some(p) = pyramid { header.show_frame = p.show_frame; header.showable_frame = !p.show_frame; @@ -6434,6 +6431,11 @@ pub(crate) fn encode_inter_frame( let screen = seq_screen() && screen_content(&picture_y8, picture.width, true_width, true_height); header.allow_screen_content_tools = screen; + // The search prices coefficients against the tables this frame's writer + // starts from, not against the defaults (lane-av1txbits) -- but only on a + // frame the screen detector said no to (lane-av1price2): armed HERE, after + // `screen` exists, and again on every search/tile worker below. + crate::tile::arm_pricing_cdfs(start_cdfs, screen); let mut luma = Plane { source: &picture_y8, reconstruction: vec![128; picture_y8.len()], @@ -6526,7 +6528,7 @@ pub(crate) fn encode_inter_frame( // search step) is read by the SEARCH, so every worker arms it or the // tile's bits depend on the thread count. crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); - crate::tile::arm_pricing_cdfs(start_cdfs); + crate::tile::arm_pricing_cdfs(start_cdfs, screen); let rect = layout.rect(index); let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); let mut chroma = [ @@ -6997,7 +6999,7 @@ pub(crate) fn encode_inter_frame( crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); crate::tile::arm_screen(screen); let mut cdfs = start_cdfs.0.clone(); - crate::tile::arm_pricing_cdfs(Some(&cdfs)); + crate::tile::arm_pricing_cdfs(Some(&cdfs), screen); // Each tile's own MV grid: a candidate scan never reaches past // the tile's bounds, so a grid holding only this tile's own // blocks reads exactly as the decoder's frame-wide one does @@ -9486,12 +9488,13 @@ mod tests { // (compound share 8.8% -> 11.5%): a compound block carries a second // reference tree, a compound mode symbol and -- for the half-new modes // -- an MV residual, none of which the coefficient sum counts. - // lane-av1txbits: under `EC_AV1_PRICE_FRAME_CDFS=1` this reads +32.6% - // instead -- pricing against the tables the frame's writer really + // lane-av1txbits: pricing against the tables the frame's writer really // starts from collapses the over-price above to nothing, so the whole - // remaining gap is the syntax the coefficient sum leaves out. + // remaining gap is the syntax the coefficient sum leaves out. That is + // the default on a non-screen frame since lane-av1price2 (this + // fixture is one), and it reads +32.6% here. assert!( - worst_under <= 0.32, + worst_under <= 0.34, "the writer spent {:.2}% more than the search priced -- more than \ the mode/mv syntax outside the coefficient sum explains", worst_under * 100.0 @@ -9541,6 +9544,80 @@ mod tests { assert!(written_all > 0.0); } + /// Step (2) of the pricer lane: the same census, but on the REAL clips + /// the BD gate scores -- one film clip and the screen capture -- so the + /// question the film/screen split raises can be answered from data. Real + /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and + /// the screen capture larger, and the census says why: on a screen + /// capture the frame's own starting tables are the tables of a frame that + /// coded PALETTE and long runs of zero blocks, so they are far from the + /// tables the writer ends the frame with; the pricer error does not fall + /// the way it does on film. + /// + /// Not a gate -- it prints. Run it once per mode: + /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \ + /// --ignored pricer_error_census_on_clips --nocapture + #[test] + #[ignore = "reads the real library, needs ffmpeg"] + fn pricer_error_census_on_clips() { + if !have_ffmpeg() { + eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg"); + return; + } + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); + let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); + let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4"); + if film.exists() { + clips.push(("film 1080p".to_string(), film)); + } + if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) + && let Some(p) = manifest + .lines() + .skip(1) + .filter_map(|l| l.split('\t').next()) + .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) + { + clips.push(("screen".to_string(), std::path::PathBuf::from(p))); + } + assert!(!clips.is_empty(), "no source clip available"); + let (width, height, frames) = (640usize, 384usize, 6usize); + for (name, path) in &clips { + let fctx = &crate::decode::FrameCtx::new(); + let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); + SCREEN_FRAMES.iter().for_each(|c| { + c.store(0, std::sync::atomic::Ordering::Relaxed); + }); + let _ = crate::tile::take_pricing_hits(); + crate::tile::pricer_census_on(); + let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); + let rows = crate::tile::take_pricer_census(); + let (price_default, price_real) = crate::tile::take_pricing_hits(); + let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); + println!( + "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \ + {screen_on}, pricer armings default={price_default} real={price_real}" + ); + println!("| set | nz | blocks | priced bits | written bits | error |"); + println!("|---|---|---|---|---|---|"); + let (mut priced_all, mut written_all) = (0.0, 0.0); + for ((set, bucket), (blocks, priced, written)) in &rows { + priced_all += priced; + written_all += written; + println!( + "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", + crate::tile::census_bucket_label(*bucket), + if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 } + ); + } + println!( + "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", + rows.values().map(|r| r.0).sum::(), + (priced_all - written_all) / written_all * 100.0 + ); + assert!(written_all > 0.0, "{name}: the census saw no transform block"); + } + } + /// Low motion has to actually buy something: at least one inter frame of /// a panning sequence has to cost fewer bytes than the key frame that /// starts it, and the inter-block share it prints has to be non-zero -- @@ -10446,7 +10523,10 @@ mod tests { /// `cdef_idx` literals and per-unit loop restoration syntax are new bits /// in the tile) and again on lane-av1mv's merge of it: an extra /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate - /// above, not by this pin. + /// above, not by this pin. Re-pinned on lane-av1price2: the search now + /// prices coefficients against the tables the frame's writer really + /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a + /// decision change the BD gate judges. #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { if !have_ffmpeg() { @@ -10468,7 +10548,7 @@ mod tests { }) }; let pins: [(u8, usize, u64); 2] = - [(150, 7084, 0x00bc_da74_e540_28d7), (60, 25905, 0x1623_f794_727e_0716)]; + [(150, 7106, 0x1da4_9acd_a892_68e3), (60, 25963, 0x94df_8f46_174e_1a5e)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( @@ -10862,6 +10942,12 @@ mod tests { // and of what size. A film clip must print `screen frames on=0`. let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); + // Which tables the SEARCH priced against, per frame arming + // (`tile::arm_pricing_cdfs`): the default tables or the frame's + // real starting ones. A film clip must show every inter arming on + // the real side, a screen clip none of them. + let (price_default, price_real) = crate::tile::take_pricing_hits(); + eprintln!("{name}: pricer armings default={price_default} real={price_real}"); let palette = crate::tile::take_palette_hits(); eprintln!( "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", @@ -11132,6 +11218,12 @@ mod tests { // native resolution, over this clip's four encodes. let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); + // Which tables the SEARCH priced against, per frame arming + // (`tile::arm_pricing_cdfs`): the default tables or the frame's + // real starting ones. A film clip must show every inter arming on + // the real side, a screen clip none of them. + let (price_default, price_real) = crate::tile::take_pricing_hits(); + eprintln!("{name}: pricer armings default={price_default} real={price_real}"); let palette = crate::tile::take_palette_hits(); let palette_uv = crate::tile::take_palette_uv_hits(); let ibc = crate::tile::take_intrabc_hits(); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 14cd3f78..4716428e 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -13,6 +13,7 @@ use std::cell::RefCell; #[cfg(test)] use std::collections::BTreeMap; use std::sync::LazyLock; +use std::sync::atomic::{AtomicUsize, Ordering}; use ec_core::{Error, Result}; @@ -3965,6 +3966,21 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { /// the four points of the BD ladder were priced against another quantizer's /// tables), and against the contexts a block whose neighbours coded nothing /// reads. +/// +/// That last assumption -- `skip_ctx` 0, `sign_ctx` 0 -- is the largest +/// remaining row of the census and lane-av1price2 did NOT close it: every +/// all-zero block is priced at the `txb_skip` cost of a block whose +/// neighbours coded nothing, which is the most expensive context there is, so +/// an all-zero chroma block is UNDER-priced by 41-81% on film and 51-73% on +/// the screen capture (`pricer_error_census_on_clips`), and an all-zero +/// Luma4 is over-priced by 400%+. Arming the frame's real tables does not +/// touch those rows (Chroma8 nz=0 reads -73.0% in both modes). Pricing them +/// right needs the real neighbour context, which needs something the search +/// does not have: a per-plane non-zero context map committed in coding order. +/// The search ranks partition TREES, so it prices candidates whose neighbours +/// are not yet decided; the map would have to be built per trial, not per +/// block. Deferred with the numbers above rather than approximated by a +/// fitted constant. pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { /// Built once per size: the search prices thirteen modes for every block, /// and the scan is the same table every time. @@ -4044,29 +4060,90 @@ thread_local! { /// Arms the tables [`coeff_bits`] prices against on this thread: the state /// this frame's tile writer starts from. `None` goes back to the per-q-context -/// defaults (a key frame, whose writer really does start there). +/// defaults (a key frame, whose writer really does start there), and so does +/// any frame the screen detector said yes to (`screen`). +/// +/// ON by default for non-screen frames since lane-av1price2; +/// `EC_AV1_PRICE_FRAME_CDFS` selects 0 = never (the pre-lane behaviour), +/// 1 = always, unset/2 = the screen-gated default. /// -/// OFF by default (`EC_AV1_PRICE_FRAME_CDFS=1`). It is the more accurate +/// Pricing against the frame's REAL starting tables is the more accurate /// estimate by measurement -- the pricer census /// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every /// transform block, and the one- and two-coefficient inter blocks the search -/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy does not -/// convert into ladder bytes on every clip: on the 640x384 gate it scores -/// +78.8/+95.1/+54.5 vs libaom and +36.1/+56.4/+1.4 vs rav1e against the -/// +79.9/+94.6/+54.5 and +37.3/+55.7/+1.1 the defaults score (film 1080p -/// down 1.1, film 2160p up 0.5, screen flat), and on the native crops -/// +18.0/+47.3/+60.7 and +0.7/+19.2/-7.3 against +18.9/+48.2/+59.3 and -/// +1.5/+19.8/-10.0 (both film clips down against both references, screen up -/// 1.4/2.7). Two clips better, one worse: it does not meet this lane's keep -/// rule, so it ships as a knob rather than as the default. -pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>) { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - let on = *ON.get_or_init(|| std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() == Ok("1")); +/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy only +/// converts into ladder bytes on camera content. Measured on ONE build +/// (lane-av1price2, mode 0 vs mode 2), BD-rate vs libaom / vs rav1e: +/// +/// | clip | 640x384 base | 640x384 gated | native base | native gated | +/// |---|---|---|---|---| +/// | film 1080p | +79.9 / +37.3 | +78.8 / +36.1 | +18.7 / +1.4 | +18.0 / +0.7 | +/// | film 2160p | +94.6 / +55.7 | +95.1 / +56.4 | +48.1 / +19.8 | +47.3 / +19.2 | +/// | screen | +54.5 / +1.1 | +54.5 / +1.1 | +59.4 / -10.0 | +59.4 / -10.0 | +/// +/// The screen rows are not merely close, they are byte-identical (the ladders +/// print 8832/13507/18772/24754 and 39312/52829/70719/92134 in both modes): +/// the gate is per frame and the detector fires on 48 of 48 screen frames, so +/// no screen frame is ever armed with anything but the defaults. At native +/// resolution -- the resolution his library is in -- both films come down +/// against both references and the screen capture is flat, which is this +/// lane's keep rule. At the downscaled 640x384 gate the 2160p film goes the +/// other way (+0.5/+0.7) while the 1080p one comes down further (-1.1/-1.2); +/// the downscale is the same recipe that exaggerated the frame pyramid's loss +/// sixfold, so the native table decides and the 640x384 2160p regression is +/// recorded here rather than argued away. +/// +/// Why the screen capture needs the gate at all is in the census +/// (`pricer_error_census_on_clips`, 6 frames of each clip at 640x384, q=100). +/// Real tables take the film clip's total pricer error from +7.8% to +5.3% +/// and flatten its inter classes outright (Luma8Inter/Luma16Inter/Luma32Inter +/// 1-coefficient rows from +11.7%/+17.4%/+24.9% to -0.3%/-5.5%/+8.8%). On the +/// screen capture the total only moves +12.8% -> +10.3%, because the classes +/// that dominate a screen frame are not the ones the tables fix: its chroma +/// stays over-priced (Chroma8 nz=1 +32.2% -> +31.8%, nz=2 +26.2% -> +26.2%, +/// unmoved) and its all-zero blocks stay hugely UNDER-priced (Chroma8 nz=0 +/// -73.0% -> -73.0%, Luma4 nz=0 +464% -> +467% -- both a pricer that assumes +/// `skip_ctx` 0, not a table set). So on screen the change makes the inter +/// luma price accurate while leaving the bigger chroma and all-zero errors +/// exactly where they were, which SKEWS the search's tradeoffs between them +/// instead of correcting them -- and the bytes get worse. The fix for that +/// row is the neighbour skip context, not another table set (see +/// [`coeff_bits`]). +pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() { + Ok("0") => 0, + Ok("1") => 1, + _ => 2, + }); + let on = match mode { + 0 => false, + 1 => true, + _ => !screen, + }; + PRICING_HITS[usize::from(on && base.is_some())].fetch_add(1, Ordering::Relaxed); PRICING_BASE.with_borrow_mut(|slot| { *slot = base.filter(|_| on).map(|c| Box::new((c.clone(), c.clone()))); }); } +/// How many times a frame's search was armed with the DEFAULT tables and how +/// many with the frame's REAL starting tables ([`arm_pricing_cdfs`]), so a +/// gate can print which side of the screen gate every frame landed on. Counts +/// arming calls, not frames: a multi-tile frame arms one worker per tile. +pub(crate) static PRICING_HITS: [AtomicUsize; 2] = + [AtomicUsize::new(0), AtomicUsize::new(0)]; + +/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table +/// armings). +#[cfg(test)] +pub(crate) fn take_pricing_hits() -> (usize, usize) { + ( + PRICING_HITS[0].swap(0, Ordering::Relaxed), + PRICING_HITS[1].swap(0, Ordering::Relaxed), + ) +} + /// The pricer census (`pricer_census_on`): for every transform block the tile /// writer really codes, the bits it spent against the bits [`coeff_bits`] /// prices those very levels at -- the search's rate term measured against the