diff --git a/Cargo.lock b/Cargo.lock index 187e2618..1cde365d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -423,8 +423,6 @@ dependencies = [ "ec-av1-syntax", "ec-core", "ec-testkit", - "stats_alloc", - "tracking-allocator", ] [[package]] @@ -1731,12 +1729,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" -[[package]] -name = "stats_alloc" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c0e04424e733e69714ca1bbb9204c1a57f09f5493439520f9f68c132ad25eec" - [[package]] name = "strength_reduce" version = "0.2.4" diff --git a/crates/ec-av1/Cargo.toml b/crates/ec-av1/Cargo.toml index 21a37242..2bbf335b 100644 --- a/crates/ec-av1/Cargo.toml +++ b/crates/ec-av1/Cargo.toml @@ -12,16 +12,5 @@ ec-av1-syntax.workspace = true archmage = "=0.9.31-beta.1" bytemuck = "1" -[features] -default = ["gate-counters"] -# Compiles the ~550 `*_HITS` gate counters (see `src/hits.rs`). ON by default so -# every test gate and the probe's census see the same numbers they always have; -# a shipped decoder can build `--no-default-features` to drop the TLS bump on -# each counted path -- the `*_hits()` accessors still compile and return 0. -gate-counters = [] - [dev-dependencies] ec-testkit.workspace = true -# `nightly` only makes StatsAlloc::new const, so it can be a #[global_allocator] static. -stats_alloc = { version = "0.1.10", features = ["nightly"] } -tracking-allocator = "0.4.0" diff --git a/crates/ec-av1/examples/alloc_probe.rs b/crates/ec-av1/examples/alloc_probe.rs deleted file mode 100644 index df5061f2..00000000 --- a/crates/ec-av1/examples/alloc_probe.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! Temporary lane-alloc instrument: count allocations and sample backtraces. -//! -//! Allocation totals come from `stats_alloc`. The per-size histogram and the -//! sampled backtraces come from `tracking-allocator`, which calls back into a -//! tracker on every allocation. Neither crate needs `unsafe` in this file. -//! Reallocs are excluded from totals and histogram, as the old hand-written -//! allocator did. -use std::alloc::System; -use std::collections::HashMap; -use std::sync::Mutex; -use std::sync::atomic::{AtomicUsize, Ordering}; - -use stats_alloc::StatsAlloc; -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; - -static SIZES: [AtomicUsize; 24] = [const { AtomicUsize::new(0) }; 24]; -static TRACES: Mutex>> = Mutex::new(None); -/// `reallocations` as of the last tracked allocation. A realloc bumps that counter -/// and then reaches the tracker as an allocation, so a bump means "not a new alloc". -static SEEN_REALLOCS: AtomicUsize = AtomicUsize::new(0); - -struct Track; -impl AllocationTracker for Track { - fn allocated(&self, _addr: usize, object_size: usize, _wrapped: usize, _g: AllocationGroupId) { - let st = A.stats(); - if st.reallocations != SEEN_REALLOCS.swap(st.reallocations, Ordering::Relaxed) { - return; - } - // `allocations` already includes this allocation; index it from 0 like the old counter. - let n = st.allocations - 1; - let cls = (usize::BITS - object_size.leading_zeros()) as usize; - SIZES[cls.min(23)].fetch_add(1, Ordering::Relaxed); - if n.is_multiple_of(512) { - let bt = format!("{}", std::backtrace::Backtrace::force_capture()); - let mut key: Vec = Vec::new(); - let lines: Vec<&str> = bt.lines().collect(); - for (i, l) in lines.iter().enumerate() { - if l.contains("ec_av1::") && key.len() < 6 { - let at = lines - .get(i + 1) - .filter(|n| n.trim_start().starts_with("at ")) - .map(|n| n.trim().to_string()) - .unwrap_or_default(); - key.push(format!("{} {}", l.trim(), at)); - } - } - let mut g = TRACES.lock().unwrap(); - *g.get_or_insert_with(HashMap::new).entry(key.join(" <- ")).or_insert(0) += 1; - // The capture's own reallocs were not tracked; skip them too. - SEEN_REALLOCS.store(A.stats().reallocations, Ordering::Relaxed); - } - } - fn deallocated( - &self, - _addr: usize, - _object_size: usize, - _wrapped: usize, - _source: AllocationGroupId, - _current: AllocationGroupId, - ) { - } -} - -#[global_allocator] -static A: StatsAlloc> = StatsAlloc::new(Allocator::system()); - -fn main() { - AllocationRegistry::set_global_tracker(Track).expect("tracker"); - AllocationRegistry::enable_tracking(); - let path = std::env::args().nth(1).expect("usage: alloc_probe "); - let data = std::fs::read(&path).expect("read"); - let mut shown = 0usize; - let r = ec_av1::stream::decode_stream_with(&data, |_f, _i, s| { - if s { - shown += 1; - } - Ok(()) - }); - println!("shown={shown} result={:?}", r.is_ok()); - let st = A.stats(); - println!("allocs={} bytes={}", st.allocations, st.bytes_allocated); - for (i, c) in SIZES.iter().enumerate() { - let v = c.load(Ordering::Relaxed); - if v > 0 { - println!("size 2^{i} : {v}"); - } - } - let g = TRACES.lock().unwrap(); - if let Some(m) = g.as_ref() { - let mut v: Vec<_> = m.iter().collect(); - v.sort_by_key(|(_, c)| std::cmp::Reverse(**c)); - for (k, c) in v.into_iter().take(30) { - println!("{c:6} {k}"); - } - } -} diff --git a/crates/ec-av1/examples/decode_probe.rs b/crates/ec-av1/examples/decode_probe.rs deleted file mode 100644 index 6b33a90c..00000000 --- a/crates/ec-av1/examples/decode_probe.rs +++ /dev/null @@ -1,532 +0,0 @@ -//! Where does a real stream stop? Decode one AV1 file and print the answer. -//! -//! The gates in [`ec_av1::stream`] each pin one capability against one encoder -//! recipe. This asks the complementary question -- given a stream someone -//! actually produced, which refusal comes first -- and it is how the refusal -//! distribution in commit 2be815f was measured rather than reasoned about: -//! -//! ```text -//! aomenc --codec=av1 --obu -o s.obu --passes=1 --cpu-used=4 --limit=4 in.y4m -//! cargo run -p ec-av1 --example decode_probe -- s.obu -//! ``` -//! -//! Note `--obu`: [`ec_av1::stream::decode_stream`] takes a raw OBU stream, and -//! an IVF file decodes as zero frames rather than as an error. -//! -//! That run is also what disproved three refusal strings claiming an encoder -//! never writes a case it demonstrably writes, so this is a first-class -//! instrument, not a scratch file. -fn main() { - let Some(path) = std::env::args().nth(1) else { - eprintln!("usage: decode_probe "); - std::process::exit(2); - }; - let data = match std::fs::read(&path) { - Ok(data) => data, - Err(e) => { - eprintln!("{path}: {e}"); - std::process::exit(2); - } - }; - let report = || { - // lane-av1unwritten r6: the subsize-guard coverage table (per call - // site, per partition value, reached vs fired). Env-gated - // (`EC_AV1_SUBSIZE_GUARD_TRACE`), so it is empty unless asked for. - ec_av1::decode::dump_subsize_guard_scan(); - ec_av1::decode::dump_subsize_arm_scan(); - // The census below reads ec-av1's gate counters; without the crate's - // `gate-counters` feature every one of them is compiled out and reads 0. - if !cfg!(feature = "gate-counters") { - println!("counters disabled (built without the gate-counters feature)"); - } - let [a444, a422, s420, r420] = ec_av1::decode::cfl_ac_arm_hits(); - println!( - "cfl_ac: 444={a444} 422={a422} 420sq={s420} 420rect={r420} q3_at={}", - ec_av1::decode::cfl_ac_q3_at_hits() - ); - let (sc, dp) = ec_av1::decode::reelc_chroma_counters(); - println!("reelc_chroma: skip_cfl={sc} dir_1to4_pairs={dp}"); - println!( - "ibc128: mu_chroma={} intra128={}", - ec_av1::decode::intra_128_in_inter_mu_chroma_hits(), - ec_av1::decode::intra_128_in_inter_hits() - ); - println!( - "chroma422_square: {}", - ec_av1::decode::chroma422_square_hits() - ); - println!("chroma422_rect: {}", ec_av1::decode::chroma422_rect_hits()); - println!("chroma422_sub8: {}", ec_av1::decode::chroma422_sub8_hits()); - println!( - "chroma422_chunk: {}", - ec_av1::decode::chroma422_chunk_hits() - ); - println!( - "chroma422_pair_wide: {}", - ec_av1::decode::chroma422_pair_wide_hits() - ); - println!( - "uv_left_ss_y: reads={} mode_diff={} smooth_diff={} split1mi={}", - ec_av1::decode::uv_left_ss_y_reads(), - ec_av1::decode::uv_left_ss_y_mode_diff_hits(), - ec_av1::decode::uv_left_ss_y_smooth_diff_hits(), - ec_av1::decode::uv_left_1mi_split_hits(), - ); - let (h, v, c) = ec_av1::stream::rect4_32_counters(); - println!( - "rect4_16_uv_pair_filt: {}", - ec_av1::decode::rect4_16_uv_pair_filt_hits() - ); - println!("rect4_32: horz={h} vert={v} coded={c}"); - println!( - "rect_intrabc_reads: {}", - ec_av1::stream::rect_intrabc_reads() - ); - let (pal_y, pal_uv) = ec_av1::stream::intra_in_inter_palette_hits(); - println!("intra_in_inter_palette: y={pal_y} uv={pal_uv}"); - println!( - "palette_422_unit_window: {}", - ec_av1::decode::palette_422_unit_window_hits() - ); - println!( - "rect64_corner_tu: 64x32={} 32x64={}", - ec_av1::stream::rect64_corner_tu_hits(0), - ec_av1::stream::rect64_corner_tu_hits(1) - ); - println!( - "leaf8_intrabc_hits: {}", - ec_av1::stream::leaf8_intrabc_hits() - ); - println!("intrabc_hits: {}", ec_av1::stream::intrabc_hits()); - println!( - "intrabc_vartx_trees: {}", - ec_av1::decode::intrabc_vartx_hits() - ); - println!( - "intrabc_vartx_mixed_leaves: {}", - ec_av1::decode::intrabc_vartx_mixed_leaves_hits() - ); - println!( - "skipped_intrabc_chroma_arm_hits: {}", - ec_av1::stream::skipped_intrabc_chroma_arm_hits() - ); - println!( - "intrabc_rect: {} (var-tx tree: {})", - ec_av1::decode::intrabc_rect_hits(), - ec_av1::decode::intrabc_rect_vartx_hits() - ); - // lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip -- - // the shape `decode_block_128rect` used to refuse. - println!( - "intrabc_128rect: {}", - ec_av1::stream::intrabc_128rect_hits() - ); - // lane-av1-ibc128chunk: the 128-root intrabc strip's per-axis chroma - // mu-chunk walk -- unit count and the `(64>>ss_x)|(64>>ss_y)` extent. - println!( - "intrabc_128rect_chroma_chunk: units={} shape=0x{:x}", - ec_av1::stream::intrabc_128rect_chroma_chunk_hits(), - ec_av1::stream::intrabc_128rect_chunk_shape() - ); - let (rtu, rsplit, robmc) = ec_av1::stream::rect_inter_tu_counters(); - println!("rect_inter: tu={rtu} txsplit={rsplit} obmc_leaf={robmc}"); - println!( - "sub8_inter_split: groups={}", - ec_av1::decode::sub8_inter_split_hits() - ); - println!( - "skip_split_tx_override: {}", - ec_av1::decode::skip_split_tx_override_hits() - ); - println!( - "interintra_rect: {}", - ec_av1::decode::interintra_rect_hits() - ); - println!( - "gm_nontrans_small_side: {}", - ec_av1::decode::gm_nontrans_small_side_hits() - ); - println!( - "tr_reach_longer_side: {}", - ec_av1::decode::tr_reach_longer_side_hits() - ); - println!( - "mv_clamp_edge_overhang: {}", - ec_av1::mvstack::mv_clamp_edge_overhang_hits() - ); - let (h84, h48) = ec_av1::decode::sub8_inter_rect_hits(); - println!("sub8_inter_rect: horz8x4={h84} vert4x8={h48}"); - println!( - "llintra8_chroma_walk: {}", - ec_av1::decode::llintra8_chroma_walk_hits() - ); - println!( - "sub8rect444_chroma_walk: {}", - ec_av1::decode::llsub8rect444_chroma_walk_hits() - ); - let si = ec_av1::stream::sub8_intra_rect_hits(); - println!( - "sub8_intra_rect: horz8x4={} vert4x8={} chroma_ref={} mixed={} split4x4={}", - si.0, si.1, si.2, si.3, si.4 - ); - let leaf = ec_av1::stream::vartx_rect_leaf_hits(); - println!("vartx_rect_leaf: 32x16={} 16x32={}", leaf[0], leaf[1]); - // lane-inter16ab r1: the 16x16-level inter AB arms, so a recipe sweep - // can tell "aomenc never picked one" from "it did and we decoded it". - let ab = ec_av1::decode::ab16_inter_hits_by_arm(); - println!( - "inter_ab16: horz_a={} horz_b={} vert_a={} vert_b={}", - ab[0], ab[1], ab[2], ab[3] - ); - // lane-kf900 r1: the counter the skipped-8x8-split-transform gate - // asserts -- printed here so a recipe sweep can see it fire without a - // test-binary rebuild. - println!("skip_split_tx: {}", ec_av1::decode::skip_split_tx_hits()); - let es = ec_av1::decode::inter_edge_strip_hits(); - println!( - "inter_edge_strip: h64={} v64={} h32={} v32={} h16={} v16={}", - es[0], es[1], es[2], es[3], es[4], es[5] - ); - let (h4, v4, pairs, sub8) = ec_av1::decode::inter16_rect4_counters(); - println!("inter16_1to4: horz4={h4} vert4={v4} chroma_pairs={pairs} sub8_pieces={sub8}"); - let leaf4 = ec_av1::stream::vartx_rect_leaf4_hits(); - println!("vartx_rect_leaf4: 8x4={} 4x8={}", leaf4[0], leaf4[1]); - // lane-av1txr: intrabc 4x8/8x4 leaves that read the inter var-tx tree - // (the symbol whose absence desynced `warped.obu`). - println!( - "rect_intrabc_vartx: {}", - ec_av1::decode::rect_intrabc_vartx_hits() - ); - let rw = ec_av1::stream::rect_wedge_hits(); - let rwi = ec_av1::stream::rect_wii_hits(); - println!("rect_wedge(8x16,16x8,16x32,32x16,8x32,32x8): compound={rw:?} interintra={rwi:?}"); - // lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA in - // an INTER frame -- the arm this round implemented. - let i128 = ec_av1::stream::intra128_in_inter_counters(); - println!("intra128_in_inter: 128x64={} 64x128={}", i128[0], i128[1]); - // lane-lossless128: intra 128-axis blocks on a LOSSLESS frame (every - // plane TX_4X4) -- the shape whose reconstruction used to panic. - println!( - "intra128_lossless: {}", - ec_av1::stream::intra128_lossless_counters() - ); - let sb = ec_av1::stream::sb128_rect_counters(); - println!( - "sb128_rect: edge_horz={} edge_vert={} inter_128x64={} inter_64x128={}", - sb.0, sb.1, sb.2, sb.3 - ); - // lane-av1-ibcrect: the interior 128-root partition arms and the key - // frame's intra 128-axis blocks, so a recipe sweep can tell "the - // encoder never chose HORZ/VERT at the 128 root" from "it did". - let p128 = ec_av1::stream::part128_census(); - println!( - "part128: split={} none={} horz={} vert={} ab={:?} intra_horz={} intra_vert={}", - p128.0, p128.1, p128.2, p128.3, p128.4, p128.5, p128.6 - ); - // lane-sbab r1: the superblock-level inter AB arms. - let sbab = ec_av1::decode::sb_ab_inter_hits_by_arm(); - println!( - "inter_ab64: horz_a={} horz_b={} vert_a={} vert_b={}", - sbab[0], sbab[1], sbab[2], sbab[3] - ); - let i4 = ec_av1::stream::intra_rect4_in_inter_counters(); - println!( - "intra_rect4_in_inter: 64x16={} 16x64={} 32x8={} 8x32={}", - i4.0, i4.1, i4.2, i4.3 - ); - // lane-cdefstrip r1: 8x8 CDEF units whose skip band no coded block - // wrote this frame -- non-zero means a decode arm forgot - // `fill_skip_grid_rect`, and CDEF filtered a unit libaom may skip. - println!( - "cdef_unwritten_skip_units: {}", - ec_av1::decode::cdef_unwritten_skip_units() - ); - println!( - "cdef_band: rect_skip_writes={} mixed_skip_units={}", - ec_av1::decode::rect_skip_band_hits(), - ec_av1::decode::cdef_mixed_skip_units() - ); - let ir = ec_av1::stream::inter_rect_counters(); - println!( - "inter_rect: 32x8={} 8x32={} 64x32={} 32x64={} 64x16={} 16x64={}", - ir.0, ir.1, ir.2, ir.3, ir.4, ir.5 - ); - // lane-rectres r1: how many of those 32x8/8x32 strips coded a real - // rectangular residual transform unit (a skipped one codes none). - println!( - "sub8_chroma_tx_from_ref: {}", - ec_av1::stream::sub8_chroma_tx_from_ref_hits() - ); - let r328 = ec_av1::stream::rect32x8_inter_tu_hits(); - println!("rect32x8_inter_tu: 32x8={} 8x32={}", r328[0], r328[1]); - // lane-intra16x4: INTRA strips of an inter 16x16-level 1:4 partition. - let i164 = ec_av1::stream::intra16x4_in_inter_hits(); - println!( - "intra16x4_in_inter: 16x4={} 4x16={} chroma_ref={}", - i164.0, i164.1, i164.2 - ); - println!( - "rect4_16_pair: lossless_chroma={} intrabc={}", - ec_av1::decode::rect4_16_lossless_chroma_hits(), - ec_av1::decode::rect4_16_intrabc_hits(), - ); - println!( - "loss64: chroma_edge_tu_clip={} skip_lossless_band_reset={}", - ec_av1::decode::chroma_edge_tu_clip_hits(), - ec_av1::decode::skip_lossless_band_reset_hits(), - ); - println!( - "llband: rect_split_lossless_chroma444={}", - ec_av1::decode::rect_split_lossless_chroma444_hits() - ); - // lane-t900 r12: chroma edge-filter neighbour answered from the mi-granular - // uv_mode grid instead of the coarse one-slot-per-column map. - println!( - "scaled: leaf8={} sub8={} warpfb={} predict_scaled={}", - ec_av1::decode::scaled_leaf8_hits(), - ec_av1::decode::scaled_sub8_hits(), - ec_av1::decode::scaled_warp_fallback_hits(), - ec_av1::mc::predict_scaled_hits() - ); - println!( - "uv_mode_grid_override: {}", - ec_av1::decode::uv_mode_grid_override_hits() - ); - // lane-thread2: proof the frame-parallel path actually fired (0 at - // the default EC_AV1_THREADS=1). - println!("frames_dispatched: {}", ec_av1::stream::frames_dispatched()); - // lane-av1recipehunt: `intra_rect4_in_inter` above already reports the - // 1:4-in-inter shapes; this is the `delta_q` half of the same story -- - // how many delta_q groups the stream really carried, and how many of - // them landed inside a rect64 dequant. - let (dq, dq_drift) = ec_av1::stream::rect64_qidx_drift_counters(); - println!("delta_q: groups_read={dq} rect64_qidx_drift={dq_drift}"); - // lane-av1422census422: the per-plane coefficient-unit census, armed - // for 4:4:4 and 4:2:2 (4:2:0 arms nothing, so a 4:2:0 recipe sweep - // reads `luma=0 u=0 v=0` BY DESIGN and must not read that as "the - // walk was empty" -- `units_total` is the UNCONDITIONAL per-frame - // total, so the two together say whether the census was armed at - // all). This is what makes a 4:2:2 non-vacuity requirement - // writable: before the widening every per-plane field read zero on a - // 4:2:2 cell BY CONSTRUCTION, so a byte-exact 4:2:2 gate could - // assert it and prove nothing about the stream it had decoded. - let cu = ec_av1::decode::census_nonsub_units(); - let cc = ec_av1::decode::census_nonsub_coded(); - println!( - "census_units: luma={} u={} v={} | coded: luma={} u={} v={} | units_total={}", - cu[0], - cu[1], - cu[2], - cc[0], - cc[1], - cc[2], - ec_av1::decode::census_unit_n(), - ); - }; - // lane-tiles: the tiling a real stream actually uses is a decision input - // (every gate in `stream.rs` picks its own `--tile-columns`), so report it - // from the frame headers before saying anything about pixels. - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut seen: Vec<(u32, u32, bool, u32)> = Vec::new(); - let mut pos = 0usize; - let mut frames_seen = 0usize; - // OBU at a time, so one unparseable OBU late in the stream still leaves - // every earlier frame header's tiling reported. - while pos < data.len() { - let Ok(obu) = parser.parse_obu(&data[pos..]) else { - break; - }; - pos += obu.total_size.max(1); - let header = match &obu.kind { - ec_av1_syntax::ObuKind::FrameHeader(h) => h, - ec_av1_syntax::ObuKind::Frame(h, _) => h, - _ => continue, - }; - frames_seen += 1; - // lane-frame36: `EC_PROBE_HDR=1` prints one line per frame header, so a - // silent wall can be triaged by "which header field is new at frame N" - // before any pixel work (class: a header field parsed then never consumed). - if std::env::var("EC_PROBE_HDR").is_ok() { - let h = header; - let gm: Vec = h - .global_motion - .iter() - .map(|w| format!("{:?}", w.model)) - .collect(); - println!( - "HDR {}: type={:?} show={} showable={} show_existing={}({}) intra={} \ - size={}x{} up={} superres={}/{} order_hint={} primary_ref={} refresh={:#04x} \ - refs={:?} order_hints={:?} sign_bias={:?} err_res={} disable_cdf={} \ - screen_tools={} int_mv={} intrabc={} hp_mv={} interp={:?} switchable_motion={} \ - ref_mvs={} base_q={} seg={} deltaq={} deltalf={} lf_level={:?} lf_deltas={:?}/{:?} \ - cdef_bits={} lr={:?} tx_mode={:?} ref_sel={} skip_mode={}({:?}) warp={} \ - reduced_tx={} gm={:?} grain={}/seed={} lossless={}", - frames_seen - 1, - h.frame_type, - h.show_frame, - h.showable_frame, - h.show_existing_frame, - h.frame_to_show_map_idx, - h.frame_is_intra, - h.frame_width, - h.frame_height, - h.upscaled_width, - h.use_superres, - h.superres_denom, - h.order_hint, - h.primary_ref_frame, - h.refresh_frame_flags, - h.ref_frame_idx, - h.order_hints, - h.ref_frame_sign_bias, - h.error_resilient_mode, - h.disable_cdf_update, - h.allow_screen_content_tools, - h.force_integer_mv, - h.allow_intrabc, - h.allow_high_precision_mv, - h.interpolation_filter, - h.is_motion_mode_switchable, - h.use_ref_frame_mvs, - h.quantization.base_q_idx, - h.segmentation.enabled, - h.delta.q_present, - h.delta.lf_present, - h.loop_filter.level, - h.loop_filter.ref_deltas, - h.loop_filter.mode_deltas, - h.cdef.bits, - h.loop_restoration.frame_restoration_type, - h.tx_mode, - h.reference_select, - h.skip_mode_present, - h.skip_mode_frame, - h.allow_warped_motion, - h.reduced_tx_set, - gm, - h.film_grain.apply_grain, - h.film_grain.grain_seed, - h.coded_lossless, - ); - } - let t = &header.tile_info; - let entry = (t.cols, t.rows, t.uniform_spacing, t.context_update_tile_id); - if !seen.contains(&entry) { - seen.push(entry); - } - } - println!("TILING: {frames_seen} frame headers parsed"); - // lane-sb128 r4: the superblock size decides the whole partition tree, so - // report it next to the tiling -- it is the first thing a film blocker - // triage needs. - if let Some(seq) = parser.sequence_header() { - println!( - "SEQ: use_128x128_superblock={} bit_depth={} mono_chrome={} max_frame={}x{}", - seq.use_128x128_superblock, - seq.color_config.bit_depth, - seq.color_config.mono_chrome, - seq.max_frame_width, - seq.max_frame_height - ); - } - for (cols, rows, uniform, ctx_id) in &seen { - println!( - "TILING: cols={cols} rows={rows} uniform_spacing={uniform} context_update_tile_id={ctx_id}" - ); - } - if seen.is_empty() { - println!("TILING: no frame header parsed"); - } - - // lane-streamsink r1: decode through the streaming entry point and write - // each shown frame out as it completes. The old path collected every - // picture in a Vec and then built a second full copy of the raw dump - // before one `fs::write`, so peak RSS was 2x the whole decoded segment (a - // 4K 8 s window needed >20 GiB, a whole film terabytes). Here at most one - // frame is held beyond the decoder's own DPB, and the printed lines are - // byte-identical to the old ones. - // `EC_PROBE_OUT16` is yuv420p10le (u16 LE); `EC_PROBE_OUT` / argv[2] is - // 8-bit (planes are u16, low byte taken). Either target may be a FIFO. - use std::io::Write; - let open = |path: &str| { - std::fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .open(path) - .unwrap_or_else(|e| panic!("opening {path}: {e}")) - }; - let out16 = std::env::var("EC_PROBE_OUT16").ok(); - let out8 = std::env::args() - .nth(2) - .or_else(|| std::env::var("EC_PROBE_OUT").ok()); - let null16 = out16.as_deref() == Some("/dev/null"); - let mut f16 = out16.as_deref().map(open); - let mut f8 = out8.as_deref().map(open); - let mut written16 = 0usize; - let mut written8 = 0usize; - let mut shown = 0usize; - let mut dims = (0usize, 0usize); - let mut buf: Vec = Vec::new(); - // lane-av1mono: a monochrome stream is luma only, so the raw dump is a - // single plane -- exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes. - let mono = parser - .sequence_header() - .is_some_and(|s| s.color_config.mono_chrome); - let result = ec_av1::stream::decode_stream_with(&data, |f, _idx, is_shown| { - if !is_shown { - return Ok(()); - } - shown += 1; - if shown == 1 { - dims = (f.width, f.height); - } - let planes: &[&Vec] = if mono { &[&f.y] } else { &[&f.y, &f.u, &f.v] }; - if let Some(w) = f16.as_mut() { - let n = 2 * planes.iter().map(|p| p.len()).sum::(); - if null16 { - // Timing runs point EC_PROBE_OUT16 at /dev/null; the u16->LE - // conversion was ~2% of the main thread for bytes nobody reads. - written16 += n; - } else { - buf.clear(); - buf.resize(n, 0); - let mut off = 0; - for p in planes { - let end = off + 2 * p.len(); - for (d, &s) in buf[off..end].as_chunks_mut::<2>().0.iter_mut().zip(p.iter()) { - d.copy_from_slice(&s.to_le_bytes()); - } - off = end; - } - w.write_all(&buf).expect("writing raw planes"); - written16 += buf.len(); - } - } - if let Some(w) = f8.as_mut() { - buf.clear(); - for p in planes { - buf.extend(p.iter().map(|&s| s as u8)); - } - w.write_all(&buf).expect("writing raw planes"); - written8 += buf.len(); - } - Ok(()) - }); - match result { - Ok(()) if shown == 0 => { - println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?"); - } - Ok(()) => { - if let Some(out) = &out16 { - println!("wrote {written16} bytes of yuv420p10le to {out}"); - } - if let Some(out) = &out8 { - println!("wrote {written8} bytes of yuv420p to {out}"); - } - println!("OK: {shown} frames decoded, {}x{}", dims.0, dims.1); - } - Err(e) => println!("REFUSED: {e}"), - } - report(); -} diff --git a/crates/ec-av1/examples/syntax_census.rs b/crates/ec-av1/examples/syntax_census.rs deleted file mode 100644 index fc018240..00000000 --- a/crates/ec-av1/examples/syntax_census.rs +++ /dev/null @@ -1,375 +0,0 @@ -//! Syntax census of one AV1 stream: what it actually codes, per frame type. -//! -//! `EC_AV1_BITCENSUS=1 cargo run --release -p ec-av1 --example syntax_census \ -//! -- stream.obu [source.yuv]` -//! -//! The stream may be a raw OBU stream or an IVF file (unwrapped here). The -//! optional second argument is the ENCODER'S INPUT as planar 8-bit yuv420p at -//! the coded size, and turns on a per-displayed-frame PSNR -- computed here, -//! against the decoded pictures, because ffmpeg's own PSNR of an OBU stream -//! reads a constant ~28.8 dB (no timing in an OBU stream; ledger dead-end). -//! -//! Every number comes from `ec_av1::census`, i.e. from the decoder, so our -//! stream and any other encoder's stream are measured by the same reader. - -use ec_av1::census::Frame; -use std::collections::BTreeMap; - -/// The payloads of an IVF file's frames concatenated, or the data unchanged -/// when it is already a raw OBU stream. -fn unwrap_ivf(data: &[u8]) -> Vec { - if data.len() < 32 || &data[..4] != b"DKIF" { - return data.to_vec(); - } - let header = u16::from_le_bytes([data[6], data[7]]) as usize; - let (mut pos, mut out) = (header, Vec::new()); - while pos + 12 <= data.len() { - let len = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) - as usize; - pos += 12; - if pos + len > data.len() { - break; - } - out.extend_from_slice(&data[pos..pos + len]); - pos += len; - } - out -} - -fn psnr(a: &[u16], b: &[u16]) -> f64 { - let se: f64 = a - .iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum(); - match se { - 0.0 => 99.0, - _ => 10.0 * (255.0 * 255.0 * a.len() as f64 / se).log10(), - } -} - -/// Which broad syntax family a CDF table belongs to. -fn family_group(name: &str) -> &'static str { - const COEFF: [&str; 7] = - ["txb_skip", "eob_pt", "eob_extra", "base_", "base_eob", "br_", "dc_sign"]; - if name.contains("tx_type") { - return "txtype"; - } - if COEFF.iter().any(|p| name.starts_with(p)) { - return "coeff"; - } - if name.starts_with("mv_") || name.starts_with("dv_") { - return "mv"; - } - if name.starts_with("partition") || name.starts_with("txfm_partition") { - return "partition"; - } - if name.starts_with("tx_size") { - return "txsize"; - } - if name == "literal" || name == "unregistered" { - return "literal"; - } - "mode" -} - -/// Sums a set of frames into one row's worth of census. -fn merge(frames: &[&Frame]) -> Frame { - let mut out = Frame::default(); - for f in frames { - out.bytes += f.bytes; - for (k, v) in &f.blocks { - *out.blocks.entry(*k).or_default() += v; - } - for (k, v) in &f.tx { - *out.tx.entry(*k).or_default() += v; - } - for (k, v) in &f.tx_type { - *out.tx_type.entry(*k).or_default() += v; - } - for (k, v) in &f.families { - let e = out.families.entry(k).or_default(); - e.0 += v.0; - e.1 += v.1; - } - for i in 0..3 { - out.area[i] += f.area[i]; - } - for i in 0..8 { - out.refs[i] += f.refs[i]; - } - for i in 0..4 { - out.modes[i] += f.modes[i]; - } - for i in 0..6 { - out.mv[i] += f.mv[i]; - } - out.skip_area += f.skip_area; - } - out -} - -fn pct(n: u64, total: u64) -> String { - format!("{:.1}%", 100.0 * n as f64 / total.max(1) as f64) -} - -const REFS: [&str; 8] = - ["INTRA", "LAST", "LAST2", "LAST3", "GOLDEN", "BWDREF", "ALTREF2", "ALTREF"]; - -fn report(label: &str, f: &Frame, frames: usize) { - let area = f.area.iter().sum::().max(1); - println!("\n== {label} ({frames} frames, {} bytes) ==", f.bytes); - println!( - " area: intra {} single-ref {} compound {} | skip {}", - pct(f.area[0], area), - pct(f.area[1], area), - pct(f.area[2], area), - pct(f.skip_area, area), - ); - println!( - " refs (area): {}", - REFS.iter() - .enumerate() - .filter(|(i, _)| f.refs[*i] > 0) - .map(|(i, n)| format!("{n} {}", pct(f.refs[i], area))) - .collect::>() - .join(" "), - ); - let modes = f.modes.iter().sum::(); - println!( - " single-ref modes: NEW {} GLOBAL {} NEAREST {} NEAR {} (of {modes})", - pct(f.modes[0], modes), - pct(f.modes[1], modes), - pct(f.modes[2], modes), - pct(f.modes[3], modes), - ); - let mvs = f.mv.iter().sum::(); - println!( - " coded mv |max| (1/8 pel): 0 {} <=8 {} <=32 {} <=128 {} <=512 {} >512 {} (of {mvs})", - pct(f.mv[0], mvs), - pct(f.mv[1], mvs), - pct(f.mv[2], mvs), - pct(f.mv[3], mvs), - pct(f.mv[4], mvs), - pct(f.mv[5], mvs), - ); - let blocks: u64 = f.blocks.values().sum(); - let mut by_size: Vec<_> = f.blocks.iter().collect(); - by_size.sort_by_key(|(_, n)| std::cmp::Reverse(**n)); - println!( - " blocks ({blocks} total): {}", - by_size - .iter() - .take(10) - .map(|((w, h), n)| format!("{w}x{h} {}", pct(**n, blocks))) - .collect::>() - .join(" "), - ); - let txs: u64 = f.tx.values().sum(); - let mut by_tx: Vec<_> = f.tx.iter().collect(); - by_tx.sort_by_key(|(_, n)| std::cmp::Reverse(**n)); - println!( - " published luma tx ({txs}): {}", - by_tx - .iter() - .take(8) - .map(|((w, h), n)| format!("{w}x{h} {}", pct(**n, txs))) - .collect::>() - .join(" "), - ); - let tts: u64 = f.tx_type.values().sum(); - println!( - " tx_type symbols ({tts}): {}", - f.tx_type - .iter() - .map(|((len, sym), n)| format!("set{len}/{sym} {}", pct(*n, tts))) - .collect::>() - .join(" "), - ); - // lane-libcen: the coding TOOLS, by name, so a level row says which of - // them the stream codes at all -- a table absent here is a tool this - // encoder never wrote (class `gate-blind-to-feature`). - const TOOLS: [&str; 16] = [ - "motion_mode", - "obmc", - "interintra", - "wedge_interintra", - "wedge_idx", - "compound_type", - "comp_group_idx", - "compound_idx", - "switchable_interp", - "palette_y_mode", - "palette_uv_mode", - "intrabc", - "filter_intra", - "cfl_alpha", - "delta_q", - "segment_id", - ]; - println!( - " tools (symbols/bits): {}", - TOOLS - .iter() - .map(|t| { - let (n, bits) = f.families.get(t).copied().unwrap_or((0, 0.0)); - format!("{t} {n}/{bits:.0}") - }) - .collect::>() - .join(" "), - ); - - // Bits by family group, then the ten biggest tables inside them. - let mut groups: BTreeMap<&str, (u64, f64)> = BTreeMap::new(); - for (name, (n, bits)) in &f.families { - let e = groups.entry(family_group(name)).or_default(); - e.0 += n; - e.1 += bits; - } - let total_bits: f64 = groups.values().map(|g| g.1).sum(); - println!(" bits by family (census total {:.0} bits vs {} payload bits):", total_bits, f.bytes * 8); - for (g, (n, bits)) in &groups { - println!( - " {g:<10} {:>12.0} bits {:>6} ({n} symbols)", - bits, - format!("{:.1}%", 100.0 * bits / total_bits.max(1.0)) - ); - } - let mut tables: Vec<_> = f.families.iter().collect(); - tables.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1)); - // lane-cen3: how many tables the row names. The default 8 hides the - // mode family's own split (a level can spend 40% of its bits on `mode` - // with no mode table in its top 8), so a census that has to rank - // per-table gaps between two encoders sets `EC_CENSUS_TABLES`. - let top = std::env::var("EC_CENSUS_TABLES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(8usize); - println!( - " top tables: {}", - tables - .iter() - .take(top) - .map(|(name, (_, bits))| format!("{name} {:.1}%", 100.0 * bits / total_bits.max(1.0))) - .collect::>() - .join(" "), - ); -} - -fn main() { - let args: Vec = std::env::args().skip(1).collect(); - let Some(path) = args.first() else { - eprintln!("usage: syntax_census [source.yuv]"); - std::process::exit(2); - }; - assert!(ec_av1::census::on(), "set EC_AV1_BITCENSUS=1"); - let data = unwrap_ivf(&std::fs::read(path).expect("stream")); - let pictures = ec_av1::stream::decode_stream(&data).expect("decode"); - let frames = ec_av1::census::take(); - - println!("# syntax census of {path} ({} bytes)", data.len()); - println!("\n| frame | kind | q | bytes | lf | cdef bits/y/uv | lr | dq | seg |"); - println!("|---|---|---|---|---|---|---|---|---|"); - for f in &frames { - println!( - "| {} | {} | {} | {} | {}/{} | {}/{}/{} | {:?} | {} | {} |", - f.idx, - f.kind, - f.qindex, - f.bytes, - f.lf[0], - f.lf[1], - f.cdef[0], - f.cdef[1], - f.cdef[2], - f.lr, - u8::from(f.delta_q), - u8::from(f.segmentation), - ); - } - // PSNR is per DISPLAYED picture, in display order, which is not the order - // the frames above are coded in (a pyramid codes a hidden ARF ahead of the - // leaves that predict from it, and re-outputs it later with - // `show_existing_frame`) -- so it is its own table rather than a column. - let mut psnrs: Vec<(f64, f64, f64)> = Vec::new(); - if let Some(src) = args.get(1).map(|p| std::fs::read(p).expect("source")) { - let mut sum = 0.0; - let mut rows = Vec::new(); - for (i, pic) in pictures.iter().enumerate() { - let (luma, chroma) = (pic.width * pic.height, pic.width * pic.height / 4); - let frame_len = luma + 2 * chroma; - let Some(b) = src.get(i * frame_len..(i + 1) * frame_len) else { break }; - let want: Vec = b[..luma].iter().map(|&v| u16::from(v)).collect(); - // lane-arfpred: the chroma planes too -- an anchor's byte gap can - // sit in a plane the luma-only line cannot see (class - // `metric blind to a plane`). - let wu: Vec = b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(); - let wv: Vec = b[luma + chroma..frame_len].iter().map(|&v| u16::from(v)).collect(); - let p = psnr(&pic.y, &want); - psnrs.push((p, psnr(&pic.u, &wu), psnr(&pic.v, &wv))); - sum += p; - rows.push(format!("{i}:{p:.2}")); - } - println!( - "\nPSNR-Y display order ({} pictures): {}\nPSNR-Y mean {:.3} dB over {} pictures", - pictures.len(), - rows.join(" "), - sum / rows.len() as f64, - rows.len(), - ); - } - - // lane-arfcen: one full report PER CODED FRAME, so an ARF of ours can be - // put next to the reference encoder's ARF at the same display position. - if std::env::var("EC_CENSUS_PERFRAME").as_deref() == Ok("1") { - for f in &frames { - let (p, pu, pv) = - psnrs.get(f.order_hint as usize).copied().unwrap_or((f64::NAN, f64::NAN, f64::NAN)); - let refs: Vec = (0..7) - .filter(|i| f.refs[i + 1] > 0) - .map(|i| { - format!( - "{}@{:+}", - REFS[i + 1], - i64::from(f.ref_hints[i]) - i64::from(f.order_hint), - ) - }) - .collect(); - report( - &format!( - "frame {} {} hint {} q {} PSNR-Y {p:.2} U {pu:.2} V {pv:.2} dB refs [{}]", - f.idx, - f.kind, - f.order_hint, - f.qindex, - refs.join(" "), - ), - f, - 1, - ); - } - } - - for kind in ["key", "arf", "leaf"] { - let set: Vec<&Frame> = frames.iter().filter(|f| f.kind == kind).collect(); - if !set.is_empty() { - report(kind, &merge(&set), set.len()); - } - } - report("ALL", &merge(&frames.iter().collect::>()), frames.len()); - // The self-check: every coded block is published exactly once, so the - // censused area must be the frame's own mi area (a funnel that misses a - // block class would silently under-count every share above). - if let Some(pic) = pictures.first() { - let all = merge(&frames.iter().collect::>()); - let want = (pic.width.div_ceil(4) * pic.height.div_ceil(4) * frames.len()) as u64; - let got = all.area.iter().sum::(); - println!( - "\ncoverage: censused block area {got} of {want} mi ({:.2}%)", - 100.0 * got as f64 / want as f64 - ); - } -} diff --git a/crates/ec-av1/src/census.rs b/crates/ec-av1/src/census.rs deleted file mode 100644 index 952c2aaf..00000000 --- a/crates/ec-av1/src/census.rs +++ /dev/null @@ -1,314 +0,0 @@ -//! Syntax census: what a stream actually codes, per frame, read off the -//! decoder itself (`EC_AV1_BITCENSUS=1`). -//! -//! Every number here is a decode-side observation, so OUR stream and any -//! other encoder's stream are measured by the same reader -- which is the -//! whole point: a BD-rate gap says our stream is bigger, it never says which -//! syntax it is bigger in. The accountant is off by default and costs one -//! relaxed atomic load per symbol when off. -//! -//! Bits are charged per CDF TABLE, not per hand-labelled call site: a tile -//! registers the address range of every field of its `Cdfs` (see -//! [`register_cdfs`]), and [`charge`] maps the table a symbol read to that -//! field's name. So a new coding tool joins the census the day its CDF joins -//! the struct, with no call-site edits (class `gate-blind-to-feature`). -//! -//! Run it through `examples/syntax_census.rs`; `EC_AV1_THREADS` must be 1 -//! (the default) so the frame the counters attribute to is the frame being -//! parsed. - -use std::collections::BTreeMap; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Mutex, OnceLock}; - -static ON: AtomicBool = AtomicBool::new(false); - -/// Whether the accountant is armed (`EC_AV1_BITCENSUS=1`, read once). -#[inline] -pub fn on() -> bool { - static INIT: OnceLock = OnceLock::new(); - - *INIT.get_or_init(|| { - let armed = crate::envflags::var("EC_AV1_BITCENSUS").ok().as_deref() == Some("1"); - ON.store(armed, Ordering::Relaxed); - armed - }) -} - -/// The per-symbol fast path: one relaxed load, nothing else, when off. -#[inline] -pub(crate) fn armed() -> bool { - ON.load(Ordering::Relaxed) -} - -/// One coded frame's census. -#[derive(Default, Debug, Clone)] -pub struct Frame { - /// Decode-order index. - pub idx: usize, - /// `key` (intra), `arf` (coded but not shown) or `leaf` (coded and shown). - pub kind: &'static str, - /// `base_q_idx`. - pub qindex: u8, - /// `OrderHint` of this frame, i.e. its display position (lane-arfcen). - pub order_hint: u32, - /// `OrderHints[LAST..=ALTREF]`, so a row can name its references' display - /// distance rather than only which slot it read (lane-arfcen). - pub ref_hints: [u32; 7], - /// Tile payload bytes of this frame. - pub bytes: usize, - /// `delta_q_present`. - pub delta_q: bool, - /// `segmentation_enabled`. - pub segmentation: bool, - /// `loop_filter_level[0..2]`. - pub lf: [u8; 2], - /// `cdef_bits`, `cdef_y_pri_strength[0]`, `cdef_uv_pri_strength[0]`. - pub cdef: [u8; 3], - /// `FrameRestorationType` per plane. - pub lr: [u8; 3], - /// Coded block shapes: (width, height) in pixels -> block count. - pub blocks: BTreeMap<(u16, u16), u64>, - /// Luma area (in 4x4 units) coded intra / single-ref inter / compound. - pub area: [u64; 3], - /// Luma area per reference frame slot (index 0 = intra, 1..=7 = - /// LAST..ALTREF as `ref_frame` names them). - pub refs: [u64; 8], - /// Luma area with `skip` set. - pub skip_area: u64, - /// NEWMV / GLOBALMV / NEARESTMV / NEARMV blocks (single-ref reads). - pub modes: [u64; 4], - /// Coded motion vectors bucketed by max(|x|,|y|) in eighth-pel: - /// 0, <=8 (1px), <=32, <=128, <=512, >512. - pub mv: [u64; 6], - /// Published luma transform shapes: (width, height) in pixels -> count. - pub tx: BTreeMap<(u16, u16), u64>, - /// Coded `tx_type` symbols: (CDF row length, symbol) -> count. The row - /// length names the transform SET (17 = all 16 types, 13, 8, 6 = the - /// reduced sets); symbol 0 is that set's first inverse-table entry. - pub tx_type: BTreeMap<(u8, u8), u64>, - /// Per-CDF-table (symbol count, bits). - pub families: BTreeMap<&'static str, (u64, f64)>, -} - -#[derive(Default)] -struct State { - frames: Vec, - /// Sorted (start address, end address, field name) of the live tile's - /// `Cdfs`. - tables: Vec<(usize, usize, &'static str)>, - /// Area of the block most recently published, so `compound` can move it. - last_block_area: u64, -} - -fn state() -> &'static Mutex { - static S: OnceLock> = OnceLock::new(); - S.get_or_init(|| Mutex::new(State::default())) -} - -fn with(f: impl FnOnce(&mut State) -> R) -> R { - f(&mut state().lock().unwrap_or_else(std::sync::PoisonError::into_inner)) -} - -fn cur(s: &mut State) -> &mut Frame { - if s.frames.is_empty() { - s.frames.push(Frame::default()); - } - s.frames.last_mut().expect("pushed above") -} - -/// Every frame censused since the last call, and clears the record. -pub fn take() -> Vec { - with(|s| std::mem::take(&mut s.frames)) -} - -/// Opens a new frame's row -- called once per coded frame, before its tiles. -pub(crate) fn frame_start(header: &ec_av1_syntax::FrameHeader, bytes: usize, idx: usize) { - if !armed() { - return; - } - let kind = match (header.frame_is_intra, header.show_frame) { - (true, _) => "key", - (false, false) => "arf", - (false, true) => "leaf", - }; - with(|s| { - s.frames.push(Frame { - idx, - kind, - qindex: header.quantization.base_q_idx, - order_hint: header.order_hint, - ref_hints: header.order_hints, - bytes, - delta_q: header.delta.q_present, - segmentation: header.segmentation.enabled, - lf: [header.loop_filter.level[0], header.loop_filter.level[1]], - cdef: [ - header.cdef.bits, - header.cdef.y_pri_strength[0], - header.cdef.uv_pri_strength[0], - ], - lr: [ - header.loop_restoration.frame_restoration_type[0] as u8, - header.loop_restoration.frame_restoration_type[1] as u8, - header.loop_restoration.frame_restoration_type[2] as u8, - ], - ..Frame::default() - }); - }); -} - -/// Registers the address range of every CDF table of the tile's own `Cdfs`, -/// so [`charge`] can name the family a symbol was read with. Called once per -/// tile, right where the tile's symbol decoder is built. -pub(crate) fn register_cdfs(c: &crate::cdf_state::Cdfs) { - if !armed() { - return; - } - macro_rules! ranges { - ($($name:ident),* $(,)?) => { - vec![$({ - let start = std::ptr::addr_of!(c.$name) as usize; - (start, start + std::mem::size_of_val(&c.$name), stringify!($name)) - }),*] - }; - } - let mut tables: Vec<(usize, usize, &'static str)> = ranges![ - partition_w128, partition_w64, partition_w32, txfm_partition, skip, kf_y_mode, - uv_mode_no_cfl, uv_mode_cfl, cfl_sign, cfl_alpha, angle_delta, txb_skip_luma_16, - txb_skip_luma_8, txb_skip_luma_4, txb_skip_chroma_8, txb_skip_chroma_4, eob_pt_256_luma, eob_pt_64_luma, - eob_pt_64_chroma, eob_pt_16_chroma, eob_pt_16_luma, eob_pt_16_luma_class1, eob_pt_64_luma_class1, eob_pt_16_chroma_class1, - eob_pt_64_chroma_class1, eob_pt_128_chroma_class1, eob_pt_128_luma_class1, eob_pt_32_chroma_class1, eob_pt_256_luma_class1, eob_pt_256_chroma_class1, - eob_pt_512_luma_class1, eob_pt_512_chroma_class1, eob_pt_1024_luma_class1, eob_pt_1024_chroma_class1, eob_pt_32_luma, eob_pt_32_luma_class1, - eob_extra_luma_16, eob_extra_luma_8, eob_extra_luma_4, eob_extra_chroma_8, eob_extra_chroma_4, base_luma_16, - base_luma_8, base_luma_4, base_chroma_8, base_chroma_4, base_eob_luma_16, base_eob_luma_8, - base_eob_luma_4, base_eob_chroma_8, base_eob_chroma_4, br_luma_16, br_luma_8, br_luma_4, - br_chroma_8, br_chroma_4, partition_w16, partition_w8, txb_skip_luma_32, txb_skip_luma_64, - txb_skip_chroma_16, txb_skip_chroma_32, eob_pt_1024_luma, eob_pt_1024_chroma, eob_pt_256_chroma, eob_pt_512_luma, - eob_pt_128_chroma, eob_pt_512_chroma, eob_pt_128_luma, eob_pt_32_chroma, eob_extra_luma_32, eob_extra_luma_64, - eob_extra_chroma_16, eob_extra_chroma_32, base_luma_32, base_luma_64, base_chroma_16, base_chroma_32, - base_eob_luma_32, base_eob_luma_64, base_eob_chroma_16, base_eob_chroma_32, br_luma_32, br_chroma_16, - br_chroma_32, dc_sign_luma, intra_tx_type_16, intra_tx_type_8, intra_tx_type_8_set1, intra_tx_type_4, - intra_tx_type_4_set1, inter_tx_type_32, inter_tx_type_16, inter_tx_type_8, inter_tx_type_16_set2, inter_tx_type_8_set1, - inter_tx_type_4, inter_tx_type_4_set1, dc_sign_chroma, intra_inter, single_ref, comp_mode, - skip_mode, obmc, motion_mode, interintra, interintra_mode, wedge_interintra, - compound_type, wedge_idx, inter_compound_mode, comp_ref_type, uni_comp_ref, comp_ref, - comp_bwdref, comp_group_idx, compound_idx, y_mode, new_mv, zero_mv, - ref_mv, drl_mode, mv_joint, mv_comp, dv_joint, dv_comp, - filter_intra, filter_intra_mode, tx_size_cat0, tx_size_cat1, tx_size_cat2, tx_size_cat3, - switchable_interp, palette_y_mode, palette_y_size, palette_uv_mode, palette_uv_size, palette_y_color_index, - palette_uv_color_index, intrabc, restore_wiener, restore_sgrproj, restore_switchable, segment_id, - segment_pred, delta_q, delta_lf, delta_lf_multi - ]; - tables.sort_unstable(); - with(|s| s.tables = tables); -} - -/// Charges `bits` to whichever CDF table `addr` falls inside. -pub(crate) fn charge(addr: usize, bits: f64) { - with(|s| { - let name = match s.tables.partition_point(|t| t.0 <= addr) { - 0 => "unregistered", - i if s.tables[i - 1].1 > addr => s.tables[i - 1].2, - _ => "unregistered", - }; - let e = cur(s).families.entry(name).or_default(); - e.0 += 1; - e.1 += bits; - }); -} - -/// Charges raw (equiprobable) bits, which no CDF names. -pub(crate) fn charge_literal(bits: u32) { - with(|s| { - let e = cur(s).families.entry("literal").or_default(); - e.0 += u64::from(bits); - e.1 += f64::from(bits); - }); -} - -/// One coded block, from the neighbour publisher every block routes through. -pub(crate) fn block(w_mi: usize, h_mi: usize, is_inter: bool, ref_frame: i8, skip: bool) { - if !armed() { - return; - } - let area = (w_mi * h_mi) as u64; - with(|s| { - s.last_block_area = area; - let f = cur(s); - *f.blocks.entry(((w_mi * 4) as u16, (h_mi * 4) as u16)).or_default() += 1; - f.area[usize::from(is_inter)] += area; - f.refs[(ref_frame.max(0) as usize).min(7)] += area; - if skip { - f.skip_area += area; - } - }); -} - -/// The block just published is compound (two references) -- called from the -/// compound-context publisher, which runs right after [`block`]. -pub(crate) fn compound() { - if !armed() { - return; - } - with(|s| { - let area = s.last_block_area; - let f = cur(s); - f.area[1] = f.area[1].saturating_sub(area); - f.area[2] += area; - }); -} - -/// One block's published luma transform shape. -pub(crate) fn tx(w_px: u8, h_px: u8) { - if !armed() { - return; - } - with(|s| *cur(s).tx.entry((u16::from(w_px), u16::from(h_px))).or_default() += 1); -} - -/// One coded motion vector (a NEWMV read). -pub(crate) fn mv(x: i32, y: i32) { - if !armed() { - return; - } - let m = x.abs().max(y.abs()); - let bucket = match m { - 0 => 0, - 1..=8 => 1, - 9..=32 => 2, - 33..=128 => 3, - 129..=512 => 4, - _ => 5, - }; - with(|s| cur(s).mv[bucket] += 1); -} - -/// One single-ref inter mode decision: 0 NEWMV, 1 GLOBALMV, 2 NEARESTMV, -/// 3 NEARMV. -pub(crate) fn mode(which: usize) { - if !armed() { - return; - } - with(|s| cur(s).modes[which] += 1); -} - -/// One coded `tx_type` symbol, with the CDF row length that names its set. -pub(crate) fn tx_type(len: usize, symbol: usize) { - if !armed() { - return; - } - with(|s| *cur(s).tx_type.entry((len as u8, symbol as u8)).or_default() += 1); -} - -/// One coded block of an INTRA frame, from the `blk_grid` publisher every -/// block writes -- a no-op on an inter frame, where [`block`] (the inter -/// neighbour publisher, which knows the reference) counts instead. -pub(crate) fn block_intra_frame(w_mi: usize, h_mi: usize, skip: bool) { - if !armed() { - return; - } - if with(|s| cur(s).kind == "key") { - block(w_mi, h_mi, false, 0, skip); - } -} diff --git a/crates/ec-av1/src/decode/block.rs b/crates/ec-av1/src/decode/block.rs index 2c328062..f3bc81b2 100644 --- a/crates/ec-av1/src/decode/block.rs +++ b/crates/ec-av1/src/decode/block.rs @@ -41,42 +41,16 @@ pub(super) fn read_intra_mode( Option, Option, )> { - let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..." // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for // line against the instrumented aomdec, not just `tell()`. - crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64); - let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); - if ec_istep { - // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line - // (decodemv.c:818), printed at the same point: before the first - // mode-info symbol of the block, so a cross-decoder range ladder can - // be keyed on the BLOCK, not just on the symbol sequence. - eprintln!( - "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", - dec.debug_state().0 - ); - } macro_rules! istep { - ($name:literal, $val:expr) => { - if ec_istep { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}", - $name, $val - ); - } - }; + ($name:literal, $val:expr) => {}; } // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single // point every square caller routes through (see `read_intra_mode_rect`). - let cfl = if cfl && side > 32 { - hit!(NOCFL_UV_MODE_HITS); - false - } else { - cfl - }; + let cfl = if cfl && side > 32 { false } else { cfl }; // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE // `skip` when `SegIdPreSkip`, and after it otherwise. let (seg_w_mi, seg_h_mi) = (side / 4, side / 4); @@ -84,13 +58,6 @@ pub(super) fn read_intra_mode( intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; - if trace { - eprintln!( - "TRACE skip value={} rng={}", - skip as i32, - dec.debug_state().0 - ); - } istep!("skip", skip as i32); if !seg_id_pre_skip(fctx) { intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); @@ -117,23 +84,9 @@ pub(super) fn read_intra_mode( // that merely allows (but never uses) intrabc. if allow_intrabc { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", - u8::from(use_intrabc), - dec.debug_state().0 - ); - } - if trace { - eprintln!("TRACE use_intrabc value={}", use_intrabc as i32); - } if use_intrabc { let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx); - if trace { - eprintln!("TRACE intrabc dv={dv:?}"); - } fctx.intrabc_dv.with(|c| c.set(Some(dv))); - hit!(INTRABC_HITS); // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the // moment `is_intrabc_block`: no y/uv mode, angle delta, palette, // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced @@ -145,21 +98,9 @@ pub(super) fn read_intra_mode( let above_ctx = INTRA_MODE_CTX[above_mode]; let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); - if trace { - eprintln!( - "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", - dec.debug_state().0 - ); - } istep!("mode", mode as i32); let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) { let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]); - if trace { - eprintln!( - "TRACE angle_delta value={}", - delta + ANGLE_DELTA_ZERO as i32 - ); - } delta } else { 0 @@ -174,18 +115,10 @@ pub(super) fn read_intra_mode( let uv_mode = if !has_chroma { DC_PRED } else if cfl { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; - if trace { - eprintln!( - "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", - dec.debug_state().0 - ); - } istep!("uv_mode", uv_mode as i32); let alpha = if cfl && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) @@ -199,24 +132,17 @@ pub(super) fn read_intra_mode( // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched // bug in that fallback this lane's own scope does not cover. Keep it // refused here rather than ship a silently-wrong decode. - if (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - } // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw, // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes // the `else` branch below and never reads one either way. let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; istep!("angle_uv", angle_delta_uv); - if angle_delta_uv != 0 { - hit!(UV_ANGLE_DELTA_HITS); - } // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`): // gated by `av1_allow_palette` (blockd.h -- size bound only, @@ -244,32 +170,11 @@ pub(super) fn read_intra_mode( let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) { let (mode_ctx, cache) = palette.unwrap_or((0, &[])); - if mode == DC_PRED && trace { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}" - ); - } let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; - if mode == DC_PRED && trace { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE palette_y_mode value={} rng={rng}", - use_palette_y as i32 - ); - } if use_palette_y { let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("TRACE palette_y_size n={n} rng={rng}"); - } let colors = read_palette_colors_y(dec, n, cache, fctx); - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]); - } palette_y_pending = Some((n, colors)); } // `read_palette_mode_info`'s UV half (decodemv.c:588): read @@ -313,20 +218,9 @@ pub(super) fn read_intra_mode( && let Some(class) = filter_intra_size_class(side) { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; - if trace { - eprintln!( - "TRACE use_filter_intra side={side} rng={} value={}", - dec.debug_state().0, - use_filter_intra as i32 - ); - } istep!("use_filter_intra", use_filter_intra as i32); if use_filter_intra { - hit!(FILTER_INTRA_HITS); let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); - if trace { - eprintln!("TRACE filter_intra_mode value={fi_mode}"); - } istep!("filter_intra_mode", fi_mode as i32); filter_intra = Some(fi_mode); } @@ -342,10 +236,6 @@ pub(super) fn read_intra_mode( palette_onscreen(mi_r, mi_c, side, side, fctx), false, ); - hit!(PALETTE_HITS); - if trace { - eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]); - } PaletteY { size: n, colors, @@ -372,14 +262,6 @@ pub(super) fn read_intra_mode( on, true, ); - hit!(PALETTE_UV_HITS); - if trace { - eprintln!( - "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}", - &u_colors[..n], - &v_colors[..n] - ); - } PaletteUv { size: n, u_colors, @@ -412,7 +294,6 @@ pub(super) const UV_CFL_PRED: usize = 13; /// joint sign the same way. Returns each plane's final signed `alpha_q3` /// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0. pub(super) fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) { - hit!(CFL_BLOCK_HITS); let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32; let sign_u = ((joint_sign + 1) * 11) >> 5; let sign_v = (joint_sign + 1) - 3 * sign_u; @@ -461,7 +342,6 @@ pub(super) fn cfl_ac_ss( ss_y: usize, ) -> Vec { if ss_x == 0 && ss_y == 0 { - hit!(CFL_AC_444_HITS); let mut ac = vec![0i32; bw * bh]; let mut sum = 0i32; for row in 0..bh { @@ -476,12 +356,6 @@ pub(super) fn cfl_ac_ss( ac.iter_mut().for_each(|v| *v -= avg); ac } else if ss_x == 1 && ss_y == 0 { - // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample - // averages the HORIZONTAL luma pair above it, at full chroma height - // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma - // is square here, and the 4:2:0 rect/square helpers below would halve - // the height it must keep. - hit!(CFL_AC_422_HITS); let (cw, ch) = (bw >> 1, bh); let mut ac = vec![0i32; cw * ch]; let mut sum = 0i32; @@ -500,10 +374,8 @@ pub(super) fn cfl_ac_ss( ac.iter_mut().for_each(|v| *v -= avg); ac } else if bw == bh { - hit!(CFL_AC_420_SQ_HITS); cfl_ac_q3(y, px, py, bw) } else { - hit!(CFL_AC_420_RECT_HITS); cfl_ac_q3_rect(y, px, py, bw, bh) } } @@ -515,10 +387,6 @@ pub(crate) fn cfl_ac_q3_at( bh: usize, sample: impl Fn(usize, usize) -> i32, ) -> Vec { - hit!(CFL_AC_Q3_AT_HITS); - if crate::envflags::env_flag!("EC_HALVSWEEP") { - eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}"); - } let (cw, ch) = (bw / 2, bh / 2); let mut ac = vec![0i32; cw * ch]; let mut sum = 0i32; @@ -550,275 +418,6 @@ pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { } } -/// One plane's reconstruction buffer, `width * height` samples, and the -/// prediction/residual reads and writes into it — the decode-side twin of -/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly -/// (own-edge and reach clamps both), passing what it gathers straight to -/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. -/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written -/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. -/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of -/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects). -/// lane-unwritten-dep: this doc previously said the dump "matches aomdec's own -/// `ec_dump16` rung byte for byte (crop dims, u16 LE)", which was true only of -/// the 4:2:0 crop it then used. The crop is now PER-AXIS, which is what the -/// oracle's rung 1 actually does -- it writes `y_crop_width` x `y_crop_height`, -/// `uv_crop_width` x `uv_crop_height`, `uv_crop_width` x `uv_crop_height` (the -/// libaom `YV12_BUFFER_CONFIG` fields, each already per-axis). Byte shape per -/// subsampling, `fw x fh` luma then both chroma planes, u16 LE, so: -/// -/// ```text -/// ss_x ss_y format luma chroma (each) -/// 0 0 4:4:4 fw x fh fw x fh fw*fh*3 samples -/// 1 1 4:2:0 fw x fh fw/2 x fh/2 fw*fh*3/2 samples -/// 1 0 4:2:2 fw x fh fw/2 x fh fw*fh*2 samples -/// 0 1 4:4:0 fw x fh fw x fh/2 fw*fh*3/2 samples -/// ``` -/// -/// (`round_ss` is the rounding the decoder's own plane extents use; at ss = 1 it -/// is `div_ceil(2)`, so every 4:2:0 dump is byte-for-byte unchanged by this.) -/// lane-mc64 r1: the file name is keyed on [`dump_stage_idx`], a per-var -/// decode-order counter -- both dumps used to write `.f0` unconditionally, so -/// every frame overwrote the previous one and only the LAST frame survived, -/// which silently defeats any per-frame filter-stage bisection (ledger, class -/// stale-output-faked-measurement). A sibling accessor `stage_dump_idx()`, which -/// derived the same number from `PREFILT_PICTURE_IDX`, had no caller and was -/// deleted: `PREFILT_PICTURE_IDX` is bumped after this point, not before it, so -/// the counter that names these files is the per-var map. -// Signature mirrors the spec's per-call inputs; a parameter struct would only move them. -#[allow(clippy::too_many_arguments)] -pub(super) fn dump_stage16( - var: &str, - y: &PlaneBuf<'_>, - u: &PlaneBuf<'_>, - v: &PlaneBuf<'_>, - fw: usize, - fh: usize, - ss_x: usize, - ss_y: usize, -) { - // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by - // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed - // `.f0` name kept only the LAST frame, so a mid-sequence divergence could - // not be read at all. - // - // lane-unwritten-dep: the chroma extent is PER-AXIS subsampling, not - // `div_ceil(2)` on both. The hardcoded pair was a 4:2:0 assumption and it - // was load-bearing: on a 64x64 4:2:2 frame (ss_x = 1, ss_y = 0) it wrote - // 32x32 chroma per plane where the frame carries 32x64, so HALF of each - // chroma plane appeared in NO stage dump at all. A stage bisect that reads - // "identical pre-deblock, differs post-deblock" off these dumps is then - // measuring the dump's blind spot, not the pipeline's: the samples it could - // not see are exactly the region where the 4:2:2 witness's output diverges - // (chroma rows 32..63 -- the old `fh.div_ceil(2)` crop wrote 32 of 64 rows, - // so everything from row 32 up was invisible; 2048 samples). `round_ss` is - // the same rounding the - // decoder's own plane extents use, and it matches the oracle's - // `uv_crop_width` / `uv_crop_height` per axis. - // - // ONE file per frame: `dump_stage_idx` advances on every call, so creating - // the file inside the plane loop would write three files per frame and - // shift every later frame's index. - // - // lane-av1dumploud: this used to be `let _ = f.write_all(&bytes)` per row, so - // a full filesystem left a SHORT file that no reader could tell from a - // complete one. `LoudDump` is given the exact expected length this function - // knows -- `(fw*fh + 2*cw*ch) * 2`, u16 LE -- and checks it against the file - // on disk; a shortfall aborts the decode instead of leaving a plausible - // artefact behind. - if let Ok(path) = crate::envflags::var(var) { - let cw = round_ss(fw, ss_x); - let ch = round_ss(fh, ss_y); - let expected = (fw * fh + 2 * cw * ch) * 2; - let mut d = crate::dumpio::LoudDump::create( - var, - format!("{path}.f{}", dump_stage_idx(var)), - expected, - ); - for (p, w, h) in [(y, fw, fh), (u, cw, ch), (v, cw, ch)] { - for row in 0..h { - let mut bytes = Vec::with_capacity(w * 2); - for &s in &p.data[row * p.width..][..w] { - bytes.extend_from_slice(&s.to_le_bytes()); - } - d.write(&bytes); - } - } - d.finish(); - } -} - -/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a -/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so -/// every frame overwrote the previous one and only the LAST frame survived, -/// which silently defeats any per-frame filter-stage bisection. -fn dump_stage_idx(var: &str) -> usize { - use std::collections::HashMap; - use std::sync::{Mutex, OnceLock}; - static IDX: OnceLock>> = OnceLock::new(); - let mut m = IDX - .get_or_init(|| Mutex::new(HashMap::new())) - .lock() - .unwrap(); - let e = m.entry(var.to_string()).or_insert(0); - let i = *e; - *e += 1; - i -} - -pub(super) fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { - // lane-av1dumploud: loud on a short write (see [`crate::dumpio::LoudDump`]). - // The expected length is the three planes' own data lengths -- the writer - // iterates exactly `p.data`, so this is the same extent, not a re-derivation - // that could disagree with it. - if let Ok(path) = crate::envflags::var(var) { - let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - var, - format!("{path}.f{}", dump_stage_idx(var)), - &[&narrow(y), &narrow(u), &narrow(v)], - ); - } -} - -/// `EC_AV1_PREFILT_WIDE_DUMP=` -> `.f`, the pre-loop-filter -/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for -/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`, -/// `uv_width`/`uv_height`), so the two can be diffed directly. -/// -/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path -/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were -/// measurement traps, and the second one is why the first went unnoticed: -/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide -/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an -/// inter frame had no pre-filter rung to compare against and got attributed to -/// reconstruction when the oracle could not see it. The `static` also restarted -/// per monomorphisation, so every frame after the first overwrote `.f0` -- a -/// per-frame bisection silently compared the LAST decoded frame. The counter -/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on -/// the inter path (skipped when the filter pipeline is active, which has -/// already deblocked by the time the tile tail runs -- same condition -/// `capture_filter_replay` guards itself with). -pub(super) fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { - let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else { - return; - }; - // lane-av1dumploud: loud on a short write. Expected length is - // `sum(true_width * true_height)` over the three planes -- the crop the - // writer itself builds, so the check cannot disagree with the bytes. - let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP"); - let crop = |plane: &PlaneBuf<'_>| -> Vec { - let mut out = Vec::with_capacity(plane.true_width * plane.true_height); - for row in 0..plane.true_height { - out.extend( - plane.data[row * plane.width..][..plane.true_width] - .iter() - .map(|&s| s as u8), - ); - } - out - }; - let (cy, cu, cv) = (crop(y), crop(u), crop(v)); - crate::dumpio::write_planes( - "EC_AV1_PREFILT_WIDE_DUMP", - format!("{path}.f{idx}"), - &[&cy, &cu, &cv], - ); -} - -/// Unwritten samples [`census_unwritten`] has counted since the last -/// [`take_unwritten_samples`] -- process-global (not thread-local) because the -/// gate reads it after the decode, from a different thread than the one that -/// scanned the plane. -pub(super) static UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// Turns [`PLANE_SENTINEL`] filling on for the CALLING thread, independently -/// of `EC_AV1_PLANE_SENTINEL`. A gate cannot set a process-constant env var -/// (see [`crate::envflags`]), and the census is the only honest way to ask -/// "did the tile walk write every sample it was handed" -- a wrong-sample diff -/// cannot tell an unwritten sample from a mis-predicted one. -pub fn set_plane_sentinel(on: bool) { - PLANE_SENTINEL_ON.with(|c| c.set(on)); -} - -/// Reads and clears [`UNWRITTEN_SAMPLES`]: the number of samples the decode -/// just handed to the tile walk never wrote, summed over every frame and -/// plane. Zero is the only acceptable answer for a decoder whose output must -/// not depend on its allocator. -pub fn take_unwritten_samples() -> usize { - UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// Samples in the PADDED TAIL -- every sample of each plane outside its own -/// `true_width` x `true_height` extent -- that still holds [`plane_poison`] at -/// the pre-deblock point. [`census_unwritten`] scans that region too, because -/// "past the true extent nothing is ever read" was an ASSUMPTION the tail's -/// census was built to avoid checking; this counter is the measurement. -pub(super) static PAD_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// Reads and clears [`PAD_UNWRITTEN_SAMPLES`]. -pub fn take_pad_unwritten_samples() -> usize { - PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// The largest value reconstruction can produce, `(1 << 12) - 1`: the highest -/// bit depth this decoder carries is 12. A sentinel at or below this could be -/// a LEGAL sample, which would make the whole census vacuous -- every -/// unwritten sample would look like an ordinary one. -pub(super) const MAX_LEGAL_SAMPLE: u16 = 4095; - -/// The value [`fresh_plane`] fills with when the sentinel is on. -/// -/// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in -/// hex. Two different poisons are what turns the sentinel from "did a hole -/// survive into the output" into "did the output depend on the buffer's -/// initial content": a hole whose value reaches the picture changes the hash -/// when the poison changes, and one that does not cannot have influenced -/// anything. A value at or below [`MAX_LEGAL_SAMPLE`] is REFUSED (falls back -/// to [`PLANE_SENTINEL`]) because the census's soundness rests on the sentinel -/// being impossible. `EC_AV1_PLANE_SENTINEL=1` -- the spelling every existing -/// caller and gate uses, and `env_flag!`'s mere presence test -- keeps -/// [`PLANE_SENTINEL`]. -/// `pub(crate)` for lane-av1graincensus: `film_grain::uninit_plane` fills its -/// destination with the SAME poison `fresh_plane` does, and -/// [`census_unwritten_grained`] counts the same value. The fill and the census -/// must agree on both the value and the predicate, or a "0" means nothing. -pub(crate) fn plane_poison() -> u16 { - static V: std::sync::LazyLock = std::sync::LazyLock::new(|| { - let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else { - return PLANE_SENTINEL; - }; - let t = raw.trim(); - if t.is_empty() || t == "1" { - return PLANE_SENTINEL; - } - let hex = t - .strip_prefix("0x") - .or_else(|| t.strip_prefix("0X")) - .unwrap_or(t); - match u16::from_str_radix(hex, 16) { - Ok(v) if v > MAX_LEGAL_SAMPLE => v, - _ => PLANE_SENTINEL, - } - }); - *V -} - -thread_local! { - /// The [`set_plane_sentinel`] override; `EC_AV1_PLANE_SENTINEL` is the - /// process-wide default. - static PLANE_SENTINEL_ON: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled. -/// `pub(crate)` for the same reason as [`plane_poison`]. -pub(crate) fn plane_sentinel_on() -> bool { - crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") - || PLANE_SENTINEL_ON.with(std::cell::Cell::get) -} - /// lane-av1unwritten: whether a subsize has a chroma PLANE BLOCK at this /// frame's subsampling -- libaom `av1_ss_size_lookup[bsize][ss_x][ss_y] != /// BLOCK_INVALID` (`common_data.c`), which `decode_partition` checks on every @@ -990,26 +589,6 @@ pub(super) fn refuse_invalid_subsize( part: usize, fctx: &crate::decode::FrameCtx, ) -> Result<()> { - // lane-av1unwritten r6: the coverage artefact. A guard that sits INSIDE a - // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm can only ever observe 4..=7, so - // "the guard is present" is not evidence that an offending value is caught -- - // which is exactly how r5's three misplaced guards read as coverage. This - // records, per CALL SITE and per partition value, how often the guard was - // reached and how often it fired, so a site that never sees an offending - // value is visible instead of assumed covered. - if crate::envflags::env_flag!("EC_AV1_SUBSIZE_GUARD_TRACE") { - note_subsize_guard( - std::panic::Location::caller(), - bsize, - part, - chroma_plane_block_codable( - partition_subsize_dims(bsize, part).0, - partition_subsize_dims(bsize, part).1, - ss_x(fctx), - ss_y(fctx), - ), - ); - } let (bw, bh) = partition_subsize_dims(bsize, part); if chroma_plane_block_codable(bw, bh, ss_x(fctx), ss_y(fctx)) { Ok(()) @@ -1018,88 +597,6 @@ pub(super) fn refuse_invalid_subsize( } } -/// lane-av1unwritten r6: the OTHER half of the coverage artefact. The guard -/// table says what the guards see; this says what each DISPATCH ARM sees, so a -/// dispatch reached with an offending partition value and no guard above it is a -/// visible hole rather than an absence nobody noticed. `decode_probe` calls -/// [`dump_subsize_arm_scan`] at exit under `EC_AV1_SUBSIZE_ARM_TRACE`. -pub(super) static SUBSIZE_ARM: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default())); - -#[track_caller] -pub(crate) fn note_subsize_arm(part: usize, codable: bool) { - if !crate::envflags::env_flag!("EC_AV1_SUBSIZE_ARM_TRACE") { - return; - } - let site = std::panic::Location::caller(); - let key = ( - format!("{}:{}", site.file(), site.line()).leak() as &'static str, - part * 2 + usize::from(codable), - ); - if let Ok(mut m) = SUBSIZE_ARM.lock() { - *m.entry(key).or_insert(0) += 1; - } -} - -/// Prints and clears the [`note_subsize_arm`] table. -pub fn dump_subsize_arm_scan() { - let Ok(mut m) = SUBSIZE_ARM.lock() else { - return; - }; - for ((site, k), n) in m.iter() { - eprintln!( - "SUBSIZE_ARM site={site} part={} codable={} reached={n}", - k / 2, - if k % 2 == 1 { "true" } else { "false" }, - ); - } - m.clear(); -} - -/// Per-site, per-value counters for [`refuse_invalid_subsize`], plus the dump -/// that makes the reach/guard split readable. `EC_AV1_SUBSIZE_GUARD_TRACE` -/// records; `dump_subsize_guard_scan` prints (and clears) the table. -pub(super) static SUBSIZE_GUARD: std::sync::LazyLock< - std::sync::Mutex>, -> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default())); - -fn note_subsize_guard( - site: &'static std::panic::Location<'static>, - bsize: (usize, usize), - part: usize, - codable: bool, -) { - let key = ( - format!("{}:{}", site.file(), site.line()).leak() as &'static str, - bsize.0 * 256 + bsize.1, - part, - codable, - ); - if let Ok(mut m) = SUBSIZE_GUARD.lock() { - *m.entry(key).or_insert(0) += 1; - } -} - -/// Prints and clears the [`refuse_invalid_subsize`] table: one line per -/// (site, block, partition value) with the times reached and whether the guard -/// fired. `decode_probe` calls this at exit. -pub fn dump_subsize_guard_scan() { - let Ok(mut m) = SUBSIZE_GUARD.lock() else { - return; - }; - for ((site, bsize, part, codable), n) in m.iter() { - eprintln!( - "SUBSIZE_GUARD site={site} bsize={}x{} part={part} codable={codable} \ - reached={n}{}", - bsize / 256, - bsize % 256, - if *codable { "" } else { " FIRED" }, - ); - } - m.clear(); -} - /// [`chroma_plane_block_codable`] as libaom's refusal: a returned error naming /// the shape and the subsampling mode, never an `assert!` -- a partition symbol /// is stream data, so a hostile file can reach it. @@ -1115,84 +612,8 @@ pub(super) fn refuse_invalid_plane_block( ) } -/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no -/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`, -/// at most 4095), so a decode that hashes identically under the flag proves -/// the output does not depend on the plane buffer's initial content. -pub(super) const PLANE_SENTINEL: u16 = 0xDEAD; - -/// lane-unwritten-dep: the census count at the LAST point of the pipeline, on the -/// exact bytes `EC_AV1_FINAL_DUMP` writes. -/// -/// WHY A SECOND COUNT, and what it is actually for -- the justification this -/// comment originally carried was WRONG and is corrected here, because a reader -/// would otherwise re-derive the wrong conclusion. An earlier revision of this -/// lane claimed the pre-deblock plane was byte-identical plain-vs-sentinel and -/// that "deblock creates the dependence". That reading came from -/// [`dump_stage16`], which cropped chroma as `(fw/2, fh/2)` -- a 4:2:0 -/// assumption. On a 64x64 4:2:2 frame (ss_x=1, ss_y=0) that wrote 32x32 chroma -/// where the frame carries 32x64, so 2048 chroma samples appeared in NO stage -/// dump, and they are exactly the region where the difference lives. -/// -/// With per-axis extents the corrected measurement on `440_request_is_422` is: -/// the PRE-DEBLOCK dump already DIFFERS by 2158 bytes plain-vs-sentinel, and an -/// exact u16 whole-plane census finds 224 unwritten samples (U 112, V 112, -/// rows 36..63, whole 4x4 groups) -- the same number -/// `lanes/av1unwritten.report.md` reports. **The hole is present before any -/// filter runs, and the pre-deblock census sees it.** This comment previously -/// said the opposite; that was the instrument's blind spot read as a property of -/// the pipeline. -/// -/// So what this second count is FOR, stated honestly: it is not there because the -/// pre-deblock census misses holes. It is there because it is the measurement -/// taken where the OUTPUT is taken -- the bytes stored into the reference slots -/// and handed to the caller. A hole can be created after reconstruction (a -/// filter stage, a superres step, a second pass) and be invisible to a scan taken -/// before it; this one cannot. It is a check on the whole span from the tile walk -/// to the caller's frame, not a claim that the pre-deblock scan is insufficient. -pub(super) static FINAL_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// lane-unwritten-dep: reads and clears [`FINAL_UNWRITTEN_SAMPLES`] -- unwritten -/// samples still present in the frame as handed to the caller, summed over every -/// frame and plane. Process-global, like the pre-deblock census's counter, so a -/// gate can read it after the decode from a different thread than the one that -/// scanned. -pub fn take_final_unwritten_samples() -> usize { - FINAL_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// lane-av1graincensus: samples still holding the poison after film grain, over -/// the picture [`crate::film_grain::apply_grain`] RETURNS -- i.e. the picture the -/// caller receives on a grained frame. -pub(super) static GRAINED_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// Reads and clears [`GRAINED_UNWRITTEN_SAMPLES`]. -pub fn take_grained_unwritten_samples() -> usize { - GRAINED_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst) -} - /// A frame plane's own backing store, `n` samples, zero-filled. -/// -/// The `true_width`/`true_height`/`width`/`height` arguments are kept for the -/// call sites' shape and the sentinel's poison fill; the zero fill itself reads -/// none of them. The former `EC_AV1_PLANE_ALLOC=uninit|padzero|extzero` arms -/// (uninitialised allocation for memcheck census) are gone: they needed -/// `set_len` over uninitialised memory, which the crate no longer contains. The -/// shipped default was already the zeroed arm (`lanes/av1uballoc.report.md` §1); -/// the poison sentinel (`EC_AV1_PLANE_SENTINEL`) still catches any read of the -/// initial content. -pub(super) fn fresh_plane( - n: usize, - _true_width: usize, - _true_height: usize, - _width: usize, - _height: usize, -) -> Vec { - if plane_sentinel_on() { - return vec![plane_poison(); n]; - } +pub(super) fn fresh_plane(n: usize) -> Vec { vec![0u16; n] } @@ -1227,52 +648,6 @@ pub(super) struct PlaneBuf<'a> { pub(super) plane: u8, } -/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/ -/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this -/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it -/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already -/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/ -/// `ALTREF2`/`ALTREF`). -// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y` -// prints one PIXWRITE line per reconstruction store landing on that sample, -// naming the store site, the value it replaces and the one it leaves. Re-anchored -// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores -// now live in `reconstruct_mc_rect`). -pub(super) static PIXPROBE_ON: std::sync::LazyLock = - std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some()); - -pub(super) static PIXPROBE: std::sync::LazyLock> = - std::sync::LazyLock::new(|| { - crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| { - let (x, y) = v.split_once(',')?; - Some(( - x.trim().parse::().ok()?, - y.trim().parse::().ok()?, - )) - }) - }); - -#[inline] -// Signature mirrors the spec's per-call inputs; a parameter struct would only move them. -#[allow(clippy::too_many_arguments)] -pub(super) fn pix_write( - site: &str, - bx: usize, - by: usize, - bside: usize, - x: usize, - y: usize, - prev: u16, - val: u16, -) { - if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE { - eprintln!( - "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}", - std::panic::Location::caller() - ); - } -} - impl PlaneBuf<'_> { /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/ /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0` @@ -1356,12 +731,6 @@ impl PlaneBuf<'_> { }); let corner = (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]); - if matches!((bw, bh), (16, 8) | (8, 16)) { - hit!(RECT_STRIP_PRED_HITS); - if across > own_across || down > own_down { - hit!(RECT_STRIP_REACH_HITS); - } - } (above, left, corner) } @@ -1398,18 +767,6 @@ impl PlaneBuf<'_> { buf } else { let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach); - if crate::envflags::env_flag!("EC_DEBUG_EDGES") { - eprintln!( - "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}", - above.as_ref().map(|a| (a.len(), a[0])), - left.as_ref().map(|l| l.len()), - left.as_ref().map(|l| l[0]), - self.tile_x0, - self.tile_y0, - self.true_width, - self.true_height - ); - } let mut prediction = vec![0u16; bw * bh]; if let Some(fi_mode) = filter_intra { crate::intra::predict_filter_intra( @@ -1442,25 +799,7 @@ impl PlaneBuf<'_> { }; // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). - if crate::envflags::env_flag!("EC_PRED") { - let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); - let row0: Vec = prediction[..bw.min(8)].to_vec(); - let col0: Vec = (0..bh.min(8)).map(|r| prediction[r * bw]).collect(); - eprintln!( - "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", - std::panic::Location::caller(), - recon_plane(), - i32::from(smooth_neighbor) - ); - } let residual = dense_residual(residual, bw * bh); - if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) { - let res0: Vec = residual[..bw.min(8)].to_vec(); - let pred0: Vec = prediction[..bw.min(8)].to_vec(); - eprintln!( - "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}" - ); - } for row in 0..bh { // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame @@ -1481,16 +820,6 @@ impl PlaneBuf<'_> { base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx)); } let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16; - pix_write( - "reconstruct_rect", - x, - y, - bw, - x + col, - y + row, - self.data[(y + row) * self.width + x + col], - sample, - ); self.data.to_mut()[(y + row) * self.width + x + col] = sample; } } @@ -1498,15 +827,6 @@ impl PlaneBuf<'_> { // -- a block whose prediction matches the oracle's but whose written // samples do not is either a residual defect or a later overwrite, and // only this print separates the two. - if crate::envflags::env_flag!("EC_PRED") { - let row0: Vec = (0..bw.min(8)) - .map(|c| self.data[y * self.width + x + c]) - .collect(); - let col0: Vec = (0..bh.min(8)) - .map(|r| self.data[(y + r) * self.width + x]) - .collect(); - eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}"); - } } /// Predicts under `mode` then adds `residual` (side*side, raster), @@ -1553,13 +873,6 @@ impl PlaneBuf<'_> { buf } else { let (above, left, corner) = self.edges(x, y, side, reach); - if crate::envflags::env_flag!("EC_DEBUG_EDGES") { - eprintln!( - "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}", - above.as_deref(), - left.as_deref(), - ); - } let mut prediction = vec![0u16; side * side]; if let Some(fi_mode) = filter_intra { crate::intra::predict_filter_intra( @@ -1599,26 +912,7 @@ impl PlaneBuf<'_> { }; // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). - if crate::envflags::env_flag!("EC_PRED") { - let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); - let row0: Vec = prediction[..side.min(8)].to_vec(); - let col0: Vec = (0..side.min(8)).map(|r| prediction[r * side]).collect(); - eprintln!( - "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", - std::panic::Location::caller(), - recon_plane(), - i32::from(smooth_neighbor) - ); - } let residual = dense_residual(residual, side * side); - if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) { - let res0: Vec = residual[..side.min(8)].to_vec(); - let pred0: Vec = prediction[..side.min(8)].to_vec(); - eprintln!( - "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}", - cfl.is_some() - ); - } for row in 0..side { // lane-sb128c r8: libaom's frame buffer is superblock // aligned; ours is padded to 32 (`block_grid`), so a 64x64 @@ -1644,16 +938,6 @@ impl PlaneBuf<'_> { base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx)); } let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16; - pix_write( - "reconstruct", - x, - y, - side, - x + col, - y + row, - self.data[(y + row) * self.width + x + col], - sample, - ); self.data.to_mut()[(y + row) * self.width + x + col] = sample; } } @@ -1670,9 +954,6 @@ pub(super) fn read_plane( scan: &[u16], plane_idx: usize, around: (bool, bool, i32), - // The block's own luma mode — [`crate::tile::write_block_planes`] passes - // it for every plane's `txb` lookup (it is what an intra transform type's - // CDF is indexed by, spec 9.3), never the plane's own predicted mode. tx_mode: usize, predict_mode: usize, angle_delta: i32, @@ -1684,17 +965,9 @@ pub(super) fn read_plane( cy: usize, side: usize, tx_side: usize, - base_q_idx: u8, cfl: Option<(i32, CflSrc)>, filter_intra: Option, - // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is - // smaller than its own block (spec `get_txb_ctx_general`'s - // `plane_bsize != tx_size` branch), carrying the already-looked-up - // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any - // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours - // formula below. luma_skip_ctx: Option, - // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check. smooth_neighbor: bool, fctx: &crate::decode::FrameCtx, ) -> Result { @@ -1706,8 +979,6 @@ pub(super) fn read_plane( if plane_idx > 0 && mono(fctx) { return Ok(Grid::Zero(side * side)); } - // lane-av1readcensus: the units read from here on are this plane's. - set_census_plane(plane_idx); let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) } else { @@ -1733,12 +1004,6 @@ pub(super) fn read_plane( // labelling its unit `plane=0`, and a sweep reading a second-luma-unit // phantom out of that label (class `rung-mislabels-plane`). Diagnostic // only: no gate asserts decode behaviour off this line. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "OUR_MODE plane={plane_idx} x={x} y={cy} side={side} mode={predict_mode} \ - ad={angle_delta} fi={filter_intra:?} reach={reach:?}" - ); - } let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { @@ -1813,7 +1078,6 @@ pub(super) fn read_plane( default_tx_type, None, )?; - note_chroma_class1(plane_idx, tx_type); if plane_idx == 0 { fctx.luma_tx_type.with(|c| c.set(tx_type)); } @@ -1840,13 +1104,6 @@ pub(super) fn read_plane( stride: 0, lossless: lossless(fctx), }; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let residual = tx.run(&levels); - eprintln!( - "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", - &*levels, - ); - } push_intra_tx( y, u, @@ -1988,9 +1245,6 @@ pub(super) fn read_rect_chroma_unit( smooth_neighbor_uv: bool, fctx: &crate::decode::FrameCtx, ) -> Result { - if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h { - hit!(CHROMA422_RECT_HITS); - } // The same three cases as [`read_plane`], for the same reason: at 32 points // an INTER chroma unit's transform set is `EXT_TX_SET_DCT_IDTX` (the luma's // coded `IDTX` survives) where the intra set is `EXT_TX_SET_DCTONLY`, and @@ -2016,7 +1270,6 @@ pub(super) fn read_rect_chroma_unit( usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0), dc_sign_ctx(around.2), default_tx, - plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -2086,7 +1339,6 @@ pub(super) fn decode_block( let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at); let palette_uv_cache = neighbours.palette_uv_cache(at); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c); - let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI); let ( skip, mode, @@ -2114,9 +1366,6 @@ pub(super) fn decode_block( c * (SUB / MI), fctx, )?; - if at_tile_left && palette_y.is_some() { - hit!(PALETTE_TILE_LEFT_HITS); - } // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size // tables/scans are replaced by the 4x4 ones and the block always takes the @@ -2185,17 +1434,8 @@ pub(super) fn decode_block( uv_mode }; let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \ - angle_delta_uv={angle_delta_uv}" - ); - } let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra // block, skipped or not. `logical_tx` is what the loop filter's edge @@ -2252,29 +1492,12 @@ pub(super) fn decode_block( ); } } - hit!(INTRABC_VARTX_HITS); // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM. // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no // longer refused -- the luma reconstruct below walks the tree's own // leaf list per leaf (libaom `decode_token_recon_block`, whose token // loop reconstructs whatever `read_tx_size_vartx` resolved, per // transform unit), so mixed sizes reconstruct at their own stride. - // The counter marks the shape so a gate can prove a witness actually - // carries a mixed tree and not merely another uniform one. - let uniform = leaves.first().is_some_and(|f| { - leaves - .iter() - .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3) - }); - if !uniform { - hit!(INTRABC_VARTX_MIXED_LEAVES_HITS); - if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") { - eprintln!( - "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \ - dv={intrabc_dv:?} leaves={leaves:?}" - ); - } - } Some(leaves) } else { None @@ -2291,9 +1514,6 @@ pub(super) fn decode_block( // single-unit path. (lossless_tx(side.min(64), fctx), luma_tx) }; - if tx_select && logical_tx < side && uv_mode != DC_PRED { - hit!(SQ_CHROMA_TX_HITS); - } let luma_set = if tx_select { txbset_for(logical_tx, reduced_tx_set) } else { @@ -2400,9 +1620,6 @@ pub(super) fn decode_block( // Counted on the SHAPE, not on the arm below, so a gate can tell a stream // that reaches this block apart from one that never does (class // gate-blind-to-feature). - if palette_y_buf.is_some() && skip && logical_tx < side { - hit!(SKIP_SPLIT_TX_OVERRIDE_HITS); - } if let Some(buf) = &palette_y_buf && (logical_tx == side || skip) { @@ -2453,9 +1670,6 @@ pub(super) fn decode_block( // narrower meaning (a READ split tx depth). let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none(); if split_tx_skip { - if tx_select { - hit!(SKIP_SPLIT_TX_HITS); - } let n_axis = side / logical_tx; for tu_row in 0..n_axis { for tu_col in 0..n_axis { @@ -2471,11 +1685,6 @@ pub(super) fn decode_block( tu_row * logical_tx, logical_tx, reach, - px, - py, - y.width, - y.height, - fctx, ); push_intra( y, @@ -2540,11 +1749,6 @@ pub(super) fn decode_block( luma_span_x, luma_span_y, reach, - px, - py, - y.width, - y.height, - fctx, ) }; let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h); @@ -2580,9 +1784,6 @@ pub(super) fn decode_block( window }; if let Some((ub, _)) = &palette_uv_bufs { - if cn_cols * cn_rows > 1 { - hit!(SKIP_CHROMA_OVERRIDE_WINDOW_HITS); - } set_palette_pred(chroma_window(ub), fctx); } push_intra_unit( @@ -2645,18 +1846,6 @@ pub(super) fn decode_block( // side`, so only 4:2:2 changes. let u_grid = vec![0i32; chroma_side * chroma_height]; let v_grid = vec![0i32; chroma_side * chroma_height]; - // The measured arm, not a proxy: how many samples this block's - // chroma bookkeeping grid is SHORT of its own plane block. The - // square form this lane removed is `chroma_side * chroma_side`, - // which at 4:2:2 is half the plane block; restoring it makes this - // non-zero on every 4:2:2 skip block, and the witness gate asserts - // the total stayed 0. - let plane_block = chroma_side * chroma_height; - let short = plane_block.saturating_sub(u_grid.len()); - hit_do!(SKIP_ARM_CHROMA_SHORT_SAMPLES.with(|c| c.set(c.get() + short))); - if chroma_side != chroma_height { - hit!(SKIP_ARM_CHROMA_RECT_SHAPES); - } neighbours.record( at, side, @@ -2692,7 +1881,6 @@ pub(super) fn decode_block( py, side, coeff_tx_side, - base_q_idx, None, filter_intra, None, @@ -2745,19 +1933,12 @@ pub(super) fn decode_block( cpy, chroma_side, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx, )?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}", - &u.data[cpy * u.width + cpx..][..chroma_side] - ); - } if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); } @@ -2779,7 +1960,6 @@ pub(super) fn decode_block( cpy, chroma_side, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -2877,11 +2057,6 @@ pub(super) fn decode_block( luma_span_x, luma_span_y, reach, - px, - py, - y.width, - y.height, - fctx, ); let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h); if let Some((ub, vb)) = &palette_uv_bufs { @@ -2916,7 +2091,6 @@ pub(super) fn decode_block( cu_y, chroma_tx, chroma_tx, - base_q_idx, alpha .zip(ac) .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)), @@ -2925,10 +2099,6 @@ pub(super) fn decode_block( smooth_neighbor_uv, fctx, )?; - hit!(CHROMA_SPLIT_TX_HITS); - if ss_x(fctx) == 1 && ss_y(fctx) == 0 { - hit!(CHROMA422_SQUARE_HITS); - } // Immediately, so the next unit of this block reads this // one's coefficient context. `record` below stamps one // chroma state across the whole block; the replay after @@ -3054,10 +2224,7 @@ pub(super) fn decode_block( // top-right 8x8 unit of a 16x16 D203 block bottom-left // pixels libaom refuses outright (`col_off > 0`), which is // the diagonal wedge seed 46 reconstructed wrong. - let tu_reach = tu_reach( - side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height, - fctx, - ); + let tu_reach = tu_reach(side, side, tu_off_x, tu_off_y, tu_tx, reach); // This transform unit's own bsize (`tu_tx`) is smaller // than the block it sits in (`side`), so `txb_skip_ctx` is // the neighbour-magnitude table, not the lone-TU 0 (spec @@ -3083,7 +2250,6 @@ pub(super) fn decode_block( (luma_set, luma_scan) }; if let Some(buf) = &palette_y_buf { - hit!(PALETTE_SPLIT_TX_HITS); let mut window = vec![0u16; tu_tx * tu_tx]; for row in 0..tu_tx { let src = (tu_off_y + row) * side + tu_off_x; @@ -3108,26 +2274,13 @@ pub(super) fn decode_block( tu_px, tu_py, tu_tx, - // The unit's own COEFFICIENT grid, half its side at - // TX_64X64 (a 64-point transform codes nothing past 32); - // identical to `tu_tx` at every smaller size - // (lane-sb128b r1). if tu_tx == 64 { 32 } else { tu_tx }, - base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE tu_bitpos mi=({},{}) tell={}", - tu_mi.0, - tu_mi.1, - dec.debug_bitpos() - ); - } neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid); if first_leaf_tx.is_none() { first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get)); @@ -3210,7 +2363,6 @@ pub(super) fn decode_block( }; let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4); if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h { - hit!(CHROMA_EDGE_TU_CLIP_HITS); continue; } // The chroma context arrays are indexed in LUMA mi, so this @@ -3240,11 +2392,6 @@ pub(super) fn decode_block( luma_span_x, luma_span_y, reach, - px, - py, - y.width, - y.height, - fctx, ) }; let (cu_x, cu_y) = @@ -3282,7 +2429,6 @@ pub(super) fn decode_block( cu_y, chroma_tx, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((au, av), ac)| { (if plane_pass == 1 { au } else { av }, ac) }), @@ -3322,10 +2468,6 @@ pub(super) fn decode_block( )? }; if cn_rows * cn_cols > 1 { - hit!(CHROMA_SPLIT_TX_HITS); - if ss_x(fctx) == 1 && ss_y(fctx) == 0 { - hit!(CHROMA422_SQUARE_HITS); - } // Immediately, so the NEXT unit of this same block reads // this one's coefficient context (libaom's chroma // `txb_skip_ctx` for the second quadrant is 11, i.e. base diff --git a/crates/ec-av1/src/decode/coeffs.rs b/crates/ec-av1/src/decode/coeffs.rs index dc3134da..47658cb8 100644 --- a/crates/ec-av1/src/decode/coeffs.rs +++ b/crates/ec-av1/src/decode/coeffs.rs @@ -2,70 +2,6 @@ use super::*; -/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each. -/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so -/// nine of them inside the base/sign loops pinned nine sets of values in the -/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill -/// traffic). Out of line, the loop keeps its values in registers and the -/// trace output is character-for-character what it was. -#[cold] -#[inline(never)] -fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) { - eprintln!( - "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}" - ); -} - -#[cold] -#[inline(never)] -fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) { - eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"); -} - -#[cold] -#[inline(never)] -fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) { - eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"); -} - -#[cold] -#[inline(never)] -fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"); -} - -#[cold] -#[inline(never)] -fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"); -} - -#[cold] -#[inline(never)] -fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", - negative as i32 - ); -} - -#[cold] -#[inline(never)] -fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}"); -} - -#[cold] -#[inline(never)] -fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}"); -} - // lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`. #[track_caller] pub(super) fn read_coeffs( @@ -88,91 +24,12 @@ pub(super) fn read_coeffs( // caller's block genuinely is `side` x `side`. rect_shape: Option<(usize, usize)>, ) -> Result<(Grid, TxType)> { - let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let side = coding.side; - // lane-av1readcensus: this unit's own entry state, so the census line - // carries the pre-read rng and pairs against the oracle's `EC_COEFF` - // (which prints `r->ec.rng` before the same `txb_skip` read). - let census_entry_rng = dec.debug_state().0; - let (census_w, census_h) = rect_shape.unwrap_or((side, side)); - // lane-av1ibcfork: the per-unit BIT INTERVAL, the twin of the oracle's - // `EC_ECDUMP_IN` / `_OUT` / `_END`. The census plane, not a fresh label: - // it is the same source `census_unit` reads, so the interval line and the - // census line can never disagree about which plane a unit is on. - let iv_plane = CENSUS_PLANE.with(|c| c.get()).min(2); - let iv_bit = unit_iv_in(iv_plane, census_w, census_h, skip_ctx, dec); - if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { - let (range, value) = dec.debug_state(); - eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}"); - } - if crate::envflags::env_flag!("EC_ECDUMP_IN") { - let (range, value) = dec.debug_state(); - let bit = dec.debug_bitpos(); - eprintln!( - "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})" - ); - } - let dbg_txbskip = if coeff_trace_on() { - coding.txb_skip[skip_ctx] - } else { - [0; 3] - }; - let sq_bit = if coeff_trace_on() { - dec.debug_bitpos() - } else { - 0 - }; let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; - unit_iv_skip( - dec, iv_bit, iv_plane, census_w, census_h, skip_ctx, all_zero, - ); // lane-ibc444c: this reader logs an `all_zero` step even for a read that // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" -- // filter on it before pairing anything against the oracle. - if crate::envflags::env_flag!("EC_IBCTX") { - eprintln!( - "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}", - coding.side, - std::panic::Location::caller(), - ); - } - if coeff_trace_on() { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng} bit={sq_bit} post_bit={}", - coding.side, - all_zero as i32, - dec.debug_bitpos() - ); - } - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}", - all_zero as u8, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } - if trace { - eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32); - } - if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { - let (range, value) = dec.debug_state(); - eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}"); - } if all_zero { - // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the - // shared zero grid instead of allocating and zeroing its own. - census_unit( - census_w, - census_h, - TxType::DctDct, - 0, - true, - census_entry_rng, - dec, - ); - unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx); return Ok((Grid::Zero(side * side), TxType::DctDct)); } let mut grid = vec![0i32; side * side]; @@ -187,47 +44,14 @@ pub(super) fn read_coeffs( // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five). let len = tx_type_cdf.len(); - if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 { - eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}"); - } - crate::msac::SymbolDecoder::set_symr_cdf("tx_type"); let t = dec.symbol(tx_type_cdf); - crate::census::tx_type(len, t); - if coeff_trace_on() { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}"); - } - if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { - let (range, value) = dec.debug_state(); - eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}"); - } - if trace { - eprintln!("TRACE tx_type value={t} len={len}"); - } tx_type = tx_type_from_symbol(len, t).ok_or_else(|| { unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")) })?; } let class = TxClass::of(tx_type); - if class != TxClass::TwoD { - hit!(TX_CLASS1_HITS); - hit!(RECT_CLASS1_HITS); - } let eob = read_eob(dec, coding, class); - if trace { - eprintln!("TRACE eob value={eob}"); - } - let ec_trace_coeff = coeff_trace_on(); - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); - let cls = match class { - TxClass::TwoD => "2d", - TxClass::Horiz => "horiz", - TxClass::Vert => "vert", - }; - eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}"); - } let class_scan; let scan: &[u16] = if class == TxClass::TwoD { scan @@ -268,9 +92,6 @@ pub(super) fn read_coeffs( let level = if scan_idx == eob - 1 { let ctx = eob_coeff_ctx(scan_idx, side * side); let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1; - if trace { - trace_base_eob(scan_idx, pos, row, col, ctx, v); - } v } else { let ctx = if class == TxClass::TwoD && rect_shape.is_none() { @@ -284,14 +105,6 @@ pub(super) fn read_coeffs( base_ctx(levels, stride, row, col, class, rect_shape) }; let v = dec.symbol(&mut coding.base[ctx]) as i32; - if ec_trace_coeff { - // `pos` in libaom's column-major `coeff_idx` convention, so - // the ladder lines up with instrumented `aomdec`. - coeff_step_base(dec, scan_idx, col * side + row, ctx, v); - } - if trace { - trace_base(scan_idx, pos, row, col, ctx, v); - } v }; let level = if level > NUM_BASE_LEVELS { @@ -312,16 +125,6 @@ pub(super) fn read_coeffs( let mut sent = 0; loop { let k = dec.symbol(&mut coding.br[ctx]) as i32; - if ec_trace_coeff { - // lane-leaf8tx r3: the `br` rung was missing from THIS - // path's trace, so the cross-decoder range ladder was - // blind to every base-range symbol and mis-reported the - // first divergence (class [[gate-blind-to-feature]]). - coeff_step_br(dec, scan_idx, col * side + row, ctx, k); - } - if trace { - trace_br(scan_idx, pos, row, col, ctx, k); - } level += k; sent += BR_STEP; if k < BR_STEP || sent >= COEFF_BASE_RANGE { @@ -332,9 +135,6 @@ pub(super) fn read_coeffs( } else { level }; - if ec_trace_coeff && scan_idx == eob - 1 { - coeff_step_base_eob_level(dec, level); - } // Every coded level here is a magnitude in `0..=15` (base <= 3 plus // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is // added in the sign pass below, straight into `grid`), so the context @@ -347,10 +147,6 @@ pub(super) fn read_coeffs( nz_n += 1; } } - if ec_trace_coeff { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); - } for &packed in nz_buf[..nz_n].iter().rev() { let c = (packed >> 4) as usize; @@ -358,40 +154,18 @@ pub(super) fn read_coeffs( let level = (packed & 15) as i32; let negative = if pos == 0 { let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1; - if trace { - eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32); - } v } else { dec.literal(1) == 1 }; - if ec_trace_coeff { - coeff_step_sign(dec, c, negative); - } let level = if level > MAX_BR_LEVEL { let g = read_golomb(dec)?; - if trace { - eprintln!("TRACE golomb pos={pos} value={g}"); - } level + g as i32 } else { level }; - if ec_trace_coeff { - coeff_step_post_golomb(dec, c, level); - } grid[pos] = if negative { -level } else { level }; } - census_unit( - census_w, - census_h, - tx_type, - eob, - false, - census_entry_rng, - dec, - ); - unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx); Ok((Grid::Own(grid), tx_type)) } @@ -419,54 +193,12 @@ pub(super) fn read_coeffs_rect( skip_ctx: usize, sign_ctx: usize, default_tx_type: TxType, - // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) -- - // printed by the two `EC_COEFF_STEP` traces below, which hardcoded - // `plane=0` and so mis-attributed a CHROMA read as a luma one in two - // independent lane reports. - plane: usize, ) -> Result<(Grid, TxType)> { - let rect_trace = coeff_trace_on(); - let entry_rng = dec.debug_state().0; - // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx - // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census - // plane itself rather than inheriting whichever reader did last. The - // luma-only readers (`decode_rect_split`, `decode_block_rect64`, - // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial - // value -- and the other plane-owning readers stamp on entry. - set_census_plane(plane); - let ibctx_on = crate::envflags::env_flag!("EC_IBCTX"); - let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 }; - let iv_bit = unit_iv_in(plane, w, h, skip_ctx, dec); let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; - unit_iv_skip(dec, iv_bit, plane, w, h, skip_ctx, all_zero); - if rect_trace { - eprintln!( - "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}", - all_zero as i32, - dec.debug_state().0, - dec.debug_bitpos() - ); - } - if ibctx_on { - // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder - // range: the only collision-free key for pairing this unit against the - // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells - // a real symbol read from a 0-bit one -- the SQUARE reader logs a step - // either way, which is exactly the artifact that made an earlier - // round of this lane claim a false exactness. - eprintln!( - "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}", - dec.debug_bitpos(), - std::panic::Location::caller(), - ); - } if all_zero { - census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec); - unit_iv_end(dec, plane, w, h, skip_ctx); return Ok((Grid::Zero(w * h), TxType::DctDct)); } let mut grid = vec![0i32; w * h]; - hit!(RECT_COEFF_TU_HITS); // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and @@ -477,28 +209,12 @@ pub(super) fn read_coeffs_rect( if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { let len = tx_type_cdf.len(); let t = dec.symbol(tx_type_cdf); - crate::census::tx_type(len, t); tx_type = tx_type_from_symbol(len, t).ok_or_else(|| { unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")) })?; - if rect_trace { - eprintln!( - "EC_COEFF_STEP tag=tx_type plane={plane} rng={}", - dec.debug_state().0 - ); - } } let class = TxClass::of(tx_type); - if class != TxClass::TwoD { - hit!(TX_CLASS1_HITS); - } let eob = read_eob(dec, coding, class); - if rect_trace { - eprintln!( - "EC_COEFF_STEP tag=eob eob={eob} rng={}", - dec.debug_state().0 - ); - } let class_scan; let scan: &[u16] = if class == TxClass::TwoD { scan @@ -570,12 +286,6 @@ pub(super) fn read_coeffs_rect( base_ctx_rect(levels, stride, w, h, row, col, class) }; let v = dec.symbol(&mut coding.base[ctx]) as i32; - if rect_trace { - eprintln!( - "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}", - dec.debug_state().0 - ); - } v }; let level = if level > NUM_BASE_LEVELS { @@ -596,12 +306,6 @@ pub(super) fn read_coeffs_rect( let mut sent = 0; loop { let k = dec.symbol(&mut coding.br[ctx]) as i32; - if rect_trace { - eprintln!( - "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}", - dec.debug_state().0 - ); - } level += k; sent += BR_STEP; if k < BR_STEP || sent >= COEFF_BASE_RANGE { @@ -618,19 +322,6 @@ pub(super) fn read_coeffs_rect( nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16; nz_n += 1; } - if rect_trace && scan_idx == eob - 1 { - // the oracle's `tag=base_eob`: POST-br level, POST-br rng, with the - // same `get_lower_levels_ctx_eob` ctx (the same `eob_coeff_ctx`). - let ctx = eob_coeff_ctx(scan_idx, w * h); - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={level} rng={rng}" - ); - } - } - if rect_trace { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}"); } for &packed in nz_buf[..nz_n].iter().rev() { let pos = scan[(packed >> 4) as usize] as usize; @@ -640,53 +331,18 @@ pub(super) fn read_coeffs_rect( } else { dec.literal(1) == 1 }; - if rect_trace { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", - u8::from(negative) - ); - } let level = if level > MAX_BR_LEVEL { let g = read_golomb(dec)?; level + g as i32 } else { level }; - if rect_trace { - // lane-av1oddheightfork2: the twin of the square reader's - // `coeff_step_post_golomb`. The oracle's `EC_COEFF_STEP - // tag=post_golomb` (decodetxb.c, after read_golomb) fires for a RECT - // unit exactly as it does for a square one, but this reader had no - // rung for it, so every rect unit's ladder was one step short and - // the pairing had to guess whether a golomb had been read. This - // rung reads no bits: it prints the state after the read it labels. - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_COEFF_STEP tag=post_golomb c={} pos={pos} level={level} rng={rng}", - (packed >> 4) - ); - } grid[pos] = if negative { -level } else { level }; } // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose // grids differ is a reader defect, one whose grids agree is a transform // defect. - if crate::envflags::env_flag!("EC_DQCOEFF") { - let nz: Vec = grid - .iter() - .enumerate() - .filter(|&(_, &v)| v != 0) - .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w)) - .collect(); - eprintln!( - "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", - nz.join(",") - ); - } - census_unit(w, h, tx_type, eob, false, entry_rng, dec); - unit_iv_end(dec, plane, w, h, skip_ctx); Ok((Grid::Own(grid), tx_type)) } @@ -718,25 +374,11 @@ pub(super) fn read_chroma_coeffs_rect( sign_ctx: usize, default_tx_type: TxType, fctx: &crate::decode::FrameCtx, - // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s - // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a - // V-plane read was indistinguishable from a luma one in the log). - plane: usize, ) -> Result<(Grid, TxType)> { if mono(fctx) { return Ok((Grid::Zero(w * h), TxType::DctDct)); } - read_coeffs_rect( - dec, - coding, - scan, - w, - h, - skip_ctx, - sign_ctx, - default_tx_type, - plane, - ) + read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type) } /// What one coded block leaves behind for the blocks that read it as a @@ -1233,7 +875,13 @@ impl Neighbours { /// [`SUB`]-grid cell it covers on both the above and left edges -- /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's /// call sites are all square blocks). - pub(super) fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) { + pub(super) fn record_palette_y( + &mut self, + at: (usize, usize), + side: usize, + size: usize, + colors: [u16; 8], + ) { self.record_palette_y_rect( (at.0 * (SUB / MI), at.1 * (SUB / MI)), side, @@ -1256,9 +904,6 @@ impl Neighbours { colors: [u16; 8], ) { let (r, c) = mi; - if crate::envflags::env_flag!("EC_PALPUB") { - eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}"); - } // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size` // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi // cell immediately left of the block, not its 16px [`SUB`] cell. The @@ -1633,12 +1278,6 @@ impl Neighbours { // TX_32X32 -- independent of this block's luma `tx_depth`. let uv_tx_w = ((w_mi * MI) >> ss_x(fctx)).clamp(4, 32) as u8; let uv_tx_h = ((h_mi * MI) >> ss_y(fctx)).clamp(4, 32) as u8; - if crate::envflags::env_flag!("EC_TXGRID_TRACE") { - eprintln!( - "EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}" - ); - } - crate::census::tx(tx_px, tx_h_px); let cur = fctx.current_delta_lf.with(|c| c.get()); let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) { std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8) @@ -1727,11 +1366,6 @@ impl Neighbours { tx_h_px: u8, ) { let (mi_r, mi_c) = at_mi; - if crate::envflags::env_flag!("EC_TXGRID_TRACE") { - eprintln!( - "EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}" - ); - } for rr in 0..h_mi { let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; fill_span(&mut self.tx_grid, start, w_mi, tx_px); @@ -1748,14 +1382,14 @@ impl Neighbours { } /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1). - pub(super) fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) { + pub(super) fn fill_skip_grid_rect( + &mut self, + at_mi: (usize, usize), + w_mi: usize, + h_mi: usize, + skip: bool, + ) { let (mi_r, mi_c) = at_mi; - if skip && w_mi != h_mi { - hit!(RECT_SKIP_BAND_HITS); - } - // lane-census: an INTRA frame's blocks never reach the inter - // publisher, and this one is what every coded block writes. - crate::census::block_intra_frame(w_mi, h_mi, skip); for rr in 0..h_mi { let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; fill_span( @@ -1907,7 +1541,8 @@ impl Neighbours { /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs /// the real value, not just `is_inter`). - #[allow(dead_code)] // read only from the `#[cfg(test)]` gates + #[allow(dead_code)] + // read only from the `#[cfg(test)]` gates // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. #[allow(clippy::too_many_arguments)] pub(super) fn record_inter( @@ -1971,7 +1606,6 @@ impl Neighbours { skip_mode: bool, ) { let (r, c) = at_mi; - crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip); // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY // writes for a whole block class): an INTER block left the luma mode // map untouched, so a later intra block's `get_intra_edge_filter_type` @@ -2077,7 +1711,6 @@ impl Neighbours { compound_idx: u8, ) { let (r, c) = at_mi; - crate::census::compound(); for cell in 0..w_mi { self.above_ref1[c + cell] = Some(ref1); self.above_comp_group_idx[c + cell] = comp_group_idx; @@ -2118,7 +1751,11 @@ impl Neighbours { /// [`Self::around`] taking the block's position directly in 4x4 mode-info /// units, for the same reason [`Self::record_mi`] does. - pub(super) fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] { + pub(super) fn around_mi( + &self, + (mi_r, mi_c): (usize, usize), + side: usize, + ) -> [(bool, bool, i32); 3] { let side_mi = side / MI; // One pass over the cells accumulating all three planes, not one pass // per plane: the three planes of a cell live in the same @@ -2183,45 +1820,18 @@ impl Neighbours { o.2 += dc_vote(left[plane].dc); } } - if crate::envflags::env_flag!("EC_DCDUMP") { - // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so - // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1. - // The above rows are the SAMPLED (every-second) cells. - for (plane, o) in out.iter().enumerate() { - let vote = o.2; - let ab: Vec = (0..above_mi) - .step_by(2) - .map(|k| { - format!( - "{:?}/{}", - self.above[mi_c + k][plane].dc, - self.above[mi_c + k][plane].level - ) - }) - .collect(); - let lf: Vec = (0..left_mi) - .map(|k| { - format!( - "{:?}/{}", - self.left[mi_r + k][plane].dc, - self.left[mi_r + k][plane].level - ) - }) - .collect(); - eprintln!( - "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", - ab.join(","), - lf.join(",") - ); - } - } out } /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric /// extent pattern for a true rectangular strip's own coefficient context. - pub(super) fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] { + pub(super) fn around_rect( + &self, + (r, c): (usize, usize), + w: usize, + h: usize, + ) -> [(bool, bool, i32); 3] { self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h) } @@ -2252,34 +1862,6 @@ impl Neighbours { o.2 += dc_vote(left[plane].dc); } } - if crate::envflags::env_flag!("EC_DCDUMP") { - for (plane, o) in out.iter().enumerate() { - let vote = o.2; - let ab: Vec = (0..above_mi) - .map(|k| { - format!( - "{:?}/{}", - self.above[mi_c + k][plane].dc, - self.above[mi_c + k][plane].level - ) - }) - .collect(); - let lf: Vec = (0..left_mi) - .map(|k| { - format!( - "{:?}/{}", - self.left[mi_r + k][plane].dc, - self.left[mi_r + k][plane].level - ) - }) - .collect(); - eprintln!( - "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", - ab.join(","), - lf.join(",") - ); - } - } out } @@ -2297,8 +1879,12 @@ impl Neighbours { /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above /// context over `tx_size_wide` and the left one over `tx_size_high`. - pub(super) fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize { - let side_mi = w_mi; + pub(super) fn luma_skip_ctx_rect( + &self, + (mi_r, mi_c): (usize, usize), + w_mi: usize, + h_mi: usize, + ) -> usize { let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c)); let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r)); let mut top = 0u8; @@ -2310,35 +1896,6 @@ impl Neighbours { left |= self.left[mi_r + cell][0].level; } let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)]; - if crate::envflags::env_flag!("EC_ECDUMP") { - let ab: Vec = (0..above_mi) - .map(|k| self.above[mi_c + k][0].level.to_string()) - .collect(); - let lf: Vec = (0..left_mi) - .map(|k| self.left[mi_r + k][0].level.to_string()) - .collect(); - // lane-av1mix: the last few msac register states, so the - // byte-position of the `all_zero` read can be matched against - // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a - // second run. - let recent = crate::msac::symtrace::ecdump_recent(4) - .iter() - .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})")) - .collect::>() - .join(" "); - eprintln!( - "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]", - ab.join(","), - lf.join(","), - recent - ); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}", - self.left.iter().map(|e| e[0].level).collect::>() - ); - } ctx } @@ -2373,7 +1930,14 @@ impl Neighbours { /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves /// read these back, and only when the recorded position is exactly their /// own neighbour -- see [`Self::sub8_mode_col`]'s doc. - pub(super) fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) { + pub(super) fn record_mode_mi( + &mut self, + mi_r: usize, + mi_c: usize, + mi_w: usize, + mi_h: usize, + mode: usize, + ) { let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16); let mode = mode as u8; for cell in 0..mi_w { @@ -2451,9 +2015,6 @@ impl Neighbours { for row in mi_r..=last_r { fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner); } - if crate::envflags::env_flag!("EC_LEFTSSY") { - eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}"); - } } /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)` @@ -2503,7 +2064,6 @@ impl Neighbours { c, ss_x(fctx), ss_y(fctx), - true, ) } @@ -2512,18 +2072,6 @@ impl Neighbours { /// counter wants this: it measures how often the snap CHANGES the answer, /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every /// decode path uses the snapping form. - /// `decode_path` is `true` only for the snapping form every decode call - /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the - /// `+ss_y` counters measure a read that actually filters a chroma edge and - /// not the counter-only one. - /// - /// lane-av1leftwit: the mirror's justification used to be "no committed - /// fixture reaches the shape on the decode path", and that was false -- - /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a - /// counter-only mirror at an ODD mi row is still not a decode-path read, - /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no - /// longer evidence about the `+ss_y` term, and nothing may cite it as such. - /// The decode path's own reach is `uv_left_1mi_split_hits()`. // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. #[allow(clippy::too_many_arguments)] pub(super) fn smooth_uv_neighbour_unsnapped( @@ -2534,7 +2082,6 @@ impl Neighbours { c: usize, ss_x: usize, ss_y: usize, - decode_path: bool, ) -> bool { // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid @@ -2545,11 +2092,6 @@ impl Neighbours { // at chroma (120, 32), the top-right tile's first block). let have_above = mi_r > self.tile_row0_mi; let have_left = mi_c > self.tile_col0_mi; - if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED - || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED - { - hit!(UV_TILE_EDGE_SUPPRESSED_HITS); - } // The mi grid is libaom's own read; the two maps below stay as the // fallback for cells no block has written (see [`Self::uv_mode_grid`]). let cell = |grid: &Vec, row: usize, col: usize| -> Option { @@ -2637,67 +2179,6 @@ impl Neighbours { // every committed fixture and every one of the ~1000 encodes swept in // `lanes/av1leftref.report.md`, which is what makes the read change a // proven no-op on today's material rather than an unmeasured guess. - if decode_path && have_left && ss_y > 0 { - hit!(UV_LEFT_SS_Y_READS); - // The pre-lane read, kept as the counter's own-row arm: it is what - // this decoder answered before the `+ss_y` term landed, and - // comparing against it is what proves the term is load-bearing. - let own_row = read_left(mi_r); - if own_row != left { - hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS); - } - if is_smooth_mode(own_row) != is_smooth_mode(left) { - hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS); - } - // lane-av1leftwit: the geometry the `+ss_y` term needs. The two - // cells are one left mi column apart, so they are two different - // blocks exactly when the left neighbour is 1 mi tall or shorter. - let col = left_mi.1; - let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000; - let own = (col < self.uv_grid_cols) - .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied()) - .flatten() - .filter(|o| o & 0xff00_0000 == epoch) - .unwrap_or(0); - let down = self - .uv_owner - .get((mi_r + ss_y) * self.uv_grid_cols + col) - .copied() - .filter(|o| o & 0xff00_0000 == epoch) - .unwrap_or(0); - if own != 0 && down != 0 && own != down { - hit!(UV_LEFT_1MI_SPLIT_HITS); - if crate::envflags::env_flag!("EC_LEFTSSY") { - eprintln!( - "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \ - owners=({},{})->({},{}) modes={own_row}/{left}", - epoch >> 24, - own >> 12 & 0xfff, - own & 0xfff, - down >> 12 & 0xfff, - down & 0xfff, - ); - } - } - } - if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| { - !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m) - }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| { - !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m) - }) { - hit!(UV_MODE_GRID_OVERRIDE_HITS); - } - // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs - // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would - // have been filtered at the wrong strength by the coarse map alone. - if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] { - hit!(UV_MODE_MI_OVERRIDE_HITS); - } - if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above)) - || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left)) - { - hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS); - } is_smooth_mode(above) || is_smooth_mode(left) } @@ -2750,21 +2231,6 @@ impl Neighbours { let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); let (above, left) = self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r])); - if above != self.above_mode[c] || left != self.left_mode[r] { - hit!(MODE_MI_OVERRIDE_HITS); - } - if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above)) - || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left)) - { - hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS); - } - // A neighbour the coarse band offered where the tile edge makes it - // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`). - if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED) - || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED) - { - hit!(MODE_TILE_EDGE_COARSE_LEAKS); - } (above, left) } @@ -2864,16 +2330,16 @@ impl Neighbours { /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents, /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]). - pub(super) fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) { + pub(super) fn record_mi_rect( + &mut self, + at_mi: (usize, usize), + w: usize, + h: usize, + grids: &[&[i32]; 3], + ) { let (mi_r, mi_c) = at_mi; let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane])); let (w_mi, h_mi) = (w / MI, h / MI); - if crate::envflags::env_flag!("EC_ECPUB") { - eprintln!( - "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", - states[0].level - ); - } fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8); fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8); // A chroma 4x4 unit straddling the true luma edge is still whole in @@ -2964,27 +2430,10 @@ impl Neighbours { // units rather than in luma mi. let (step_x, step_y) = (w_px / MI, h_px / MI); // the flags read the CALLER's origin, before the shadowing align below - let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0); - if row_mid || col_mid { - CHROMA_MIDCELL_PUB_HITS.with(|c| { - let mut v = c.get(); - v[0] += usize::from(row_mid); - v[1] += usize::from(col_mid); - v[2] += usize::from(row_mid && col_mid); - c.set(v); - }); - } let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1)); let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); let state = neighbour_state(grid); - if crate::envflags::env_flag!("EC_CHROMA_PUB") { - eprintln!( - "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}", - state.level, - state.dc.map_or(-1, i32::from) - ); - } for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) { self.left[mi_r + cell][plane] = state; } @@ -3004,12 +2453,6 @@ impl Neighbours { grid: &[i32], ) { let state = neighbour_state(grid); - if crate::envflags::env_flag!("EC_ECPUB") { - eprintln!( - "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", - state.level - ); - } for cell in 0..h_px / MI { if mi_r + cell < self.mi_rows { self.left[mi_r + cell][0] = state; @@ -3600,21 +3043,9 @@ pub(super) fn decode_color_index_map_wh( on: (usize, usize), uv: bool, ) -> Vec { - let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh)); - if on_bw < bw || on_bh < bh { - hit!(PALETTE_ONSCREEN_CUT_HITS); - } let mut map = vec![0u8; bw * bh]; - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}"); - } map[0] = read_uniform(dec, n) as u8; - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]); - } for i in 1..(on_bw + on_bh - 1) { let j_hi = i.min(on_bw - 1); let j_lo = i.saturating_sub(on_bh - 1); @@ -3622,28 +3053,12 @@ pub(super) fn decode_color_index_map_wh( let row = i - j; let col = j; let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n); - if trace { - let (rng, _) = dec.debug_state(); - let row_cdf = if uv { - &cdfs.palette_uv_color_index[n - 2][ctx] - } else { - &cdfs.palette_y_color_index[n - 2][ctx] - }; - eprintln!( - "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", - row_cdf[0], row_cdf[n] - ); - } let symbol = if uv { dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n]) } else { dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n]) }; map[row * bw + col] = color_order[symbol]; - if trace { - let (rng, _) = dec.debug_state(); - eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}"); - } } } palette_replicate(&mut map, bw, bh, on); @@ -3673,9 +3088,6 @@ pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize /// it lands away from zero, for gate tests to prove a real stream fired one. pub(super) fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 { let symbol = dec.symbol(cdf); - if symbol != ANGLE_DELTA_ZERO { - hit!(ANGLE_DELTA_HITS); - } symbol as i32 - ANGLE_DELTA_ZERO as i32 } @@ -3714,9 +3126,6 @@ pub(super) fn apply_deblock( ) { // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel // mismatch between the raw reconstruction and post-filter output. - if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") { - return; - } if lf.level[0] != 0 || lf.level[1] != 0 { deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx); } @@ -3806,9 +3215,7 @@ pub(super) fn tx_size_context_txfm_rect( (mi_r, mi_c): (usize, usize), own_w: usize, own_h: usize, - fctx: &crate::decode::FrameCtx, ) -> usize { - hit!(INTRA_IN_INTER_TXCTX_HITS); // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is // wider or taller than 64, so a block with a 128 side resolves against 64 // (lane-sb128b r1). @@ -3857,31 +3264,7 @@ pub(super) fn tx_size_context_txfm_rect( }; if band_above != (has_above && usize::from(above) != 0) || band_left != (has_left && usize::from(left) != 0) - { - hit!(TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS); - } - } - if crate::envflags::env_flag!("EC_TXCTX") { - eprintln!( - "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \ - intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \ - above_side={} left_side={} above={above} left={left} \ - | cell_inter ab={} lb={} ab_side={} lb_side={}", - fctx.intra_only.with(std::cell::Cell::get), - n.above_txfm[mi_c], - n.left_txfm[mi_r], - n.above_inter[mi_c], - n.left_inter[mi_r], - n.above_side_mi[mi_c], - n.left_side_mi[mi_r], - // lane-av1txctxband: the per-CELL terms this read now uses, next to - // the per-column bands it used to use, so a divergence names which - // of the two disagreed. - if has_above { n.inter_at(mi_r - 1, mi_c) } else { false }, - if has_left { n.inter_at(mi_r, mi_c - 1) } else { false }, - if has_above { n.blk_side_at(mi_r - 1, mi_c).0 } else { 0 }, - if has_left { n.blk_side_at(mi_r, mi_c - 1).1 } else { 0 }, - ); + {} } let ctx = match (has_above, has_left) { (true, true) => usize::from(above) + usize::from(left), @@ -3889,13 +3272,6 @@ pub(super) fn tx_size_context_txfm_rect( (false, true) => usize::from(left), (false, false) => 0, }; - { - let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w) - + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h); - if ctx != stale { - hit!(TXCTX_DEBLOCK_DIVERGENCE_HITS); - } - } ctx } @@ -3905,7 +3281,11 @@ pub(super) fn tx_size_context_txfm_rect( /// override above fired on the wrong neighbour -- the first divergence of the /// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1, /// at the intra block right of an inter one). -pub(super) fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize { +pub(super) fn tx_size_context_txfm( + n: &Neighbours, + (mi_r, mi_c): (usize, usize), + side: usize, +) -> usize { let has_above = mi_r > n.tile_row0_mi; let has_left = mi_c > n.tile_col0_mi; let mut above = usize::from(n.above_txfm[mi_c]) >= side; @@ -3948,26 +3328,7 @@ pub(super) fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), }; if band_above != (has_above && usize::from(above) != 0) || band_left != (has_left && usize::from(left) != 0) - { - hit!(TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS); - } - } - if crate::envflags::env_flag!("EC_TXCTX") { - eprintln!( - "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \ - above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \ - above={above} left={left} | cell_inter ab={} lb={} ab_side={} lb_side={}", - n.above_txfm[mi_c], - n.left_txfm[mi_r], - n.above_inter[mi_c], - n.left_inter[mi_r], - n.above_side_mi[mi_c], - n.left_side_mi[mi_r], - if has_above { n.inter_at(mi_r - 1, mi_c) } else { false }, - if has_left { n.inter_at(mi_r, mi_c - 1) } else { false }, - if has_above { n.blk_side_at(mi_r - 1, mi_c).0 } else { 0 }, - if has_left { n.blk_side_at(mi_r, mi_c - 1).1 } else { 0 }, - ); + {} } match (has_above, has_left) { (true, true) => usize::from(above) + usize::from(left), @@ -4014,16 +3375,6 @@ pub(super) fn read_tx_size( 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"), }; - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - let (rng, _) = dec.debug_state(); - let (mi_r, mi_c) = at_mi; - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}" - ); - } - if depth != 0 { - hit!(TX_DEPTH_HITS); - } max_tx >> depth } @@ -4033,7 +3384,12 @@ pub(super) fn read_tx_size( /// the two neighbour terms (whether the transform last written above/left of /// this unit is narrower/shorter than the unit itself). #[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(super) fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize { +pub(super) fn txfm_partition_ctx( + above_px: u8, + left_px: u8, + blk_max_px: usize, + tx_px: usize, +) -> usize { txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px) } @@ -4066,7 +3422,12 @@ pub(crate) fn txfm_partition_ctx_rect( /// resolves, every mi cell its *parent* unit (`txb_px`) spans records the /// resolved transform's own size. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(super) fn txfm_partition_update(n: &mut Neighbours, at_mi: (usize, usize), tx_px: usize, txb_px: usize) { +pub(super) fn txfm_partition_update( + n: &mut Neighbours, + at_mi: (usize, usize), + tx_px: usize, + txb_px: usize, +) { txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px)); } @@ -4136,12 +3497,6 @@ pub(super) fn txfm_partition_update_rect( (tx_w, tx_h): (usize, usize), (txb_w, txb_h): (usize, usize), ) { - if crate::envflags::env_flag!("EC_TXUPD") { - eprintln!( - "EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", - mi_r, mi_c - ); - } for i in 0..txb_h / MI { if let Some(cell) = n.left_txfm.get_mut(mi_r + i) { *cell = tx_h as u8; @@ -4165,11 +3520,6 @@ pub(super) fn set_txfm_ctxs( h_mi: usize, skip_inter: bool, ) { - if crate::envflags::env_flag!("EC_TXUPD") { - eprintln!( - "EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}" - ); - } let bw = if skip_inter { w_mi * MI } else { tx_px }; let bh = if skip_inter { h_mi * MI } else { tx_px }; for i in 0..w_mi { @@ -4439,22 +3789,11 @@ pub(super) fn read_var_tx_size( tx_h, ); let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; - hit!(TXFM_SPLIT_READS); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}", - unit.0, - unit.1, - u8::from(split) - ); - } if !split { out.push((blk_row, blk_col, tx_w, tx_h)); txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h)); return; } - hit!(TXFM_SPLIT_HITS); let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h); if (sub_w, sub_h) == (4, 4) { // libaom's `sub_txs == TX_4X4` early return: every mi cell of the diff --git a/crates/ec-av1/src/decode/counters.rs b/crates/ec-av1/src/decode/counters.rs deleted file mode 100644 index 6d5d15ed..00000000 --- a/crates/ec-av1/src/decode/counters.rs +++ /dev/null @@ -1,4459 +0,0 @@ -//! Hit and census counters of the decode path: thread-local tallies bumped by the -//! `hit!` instrumentation and read back by the gate tests. Moved out of `decode/mod.rs` -//! by name (av1split D3); the items are unchanged except for `pub(super)` visibility. - -use super::*; - -// How many real 128-level partition symbols this decoder has read, and how -// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the -// gate's proof a `--sb-size=128` stream exercised the 128 partition root. -thread_local! { - pub(super) static PART128_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PART128_SPLIT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn part128_split_hits() -> usize { - PART128_SPLIT_HITS.with(|c| c.get()) -} - -// How many `use_filter_intra` symbols this decoder has read as `1`, across -// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate -// tests read (before/after, not the absolute value) to prove a stream -// actually exercised the filter-intra predictor rather than silently -// skipping it. -thread_local! { - pub(super) static FILTER_INTRA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FILTER_INTRA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn filter_intra_hits() -> usize { - FILTER_INTRA_HITS.with(|c| c.get()) -} - -// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged -// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own -// `read_filter_intra_mode_info` call), which no gate exercised before this -// round -- every inter gate recipe passed `--enable-filter-intra=0`. -thread_local! { - pub(super) static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter_filter_intra_hits() -> usize { - INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get()) -} - -// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a -// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both -// arms refused a nonzero luma delta before this round, and no inter gate -// enabled `--enable-angle-delta` (aomenc's own default is 1). -thread_local! { - pub(super) static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - pub(super) static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize { - INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get()) -} - -/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize { - INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get()) -} - -// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside -// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm -// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and -// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block. -thread_local! { - pub(super) static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - pub(super) static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame -/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize { - INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get()) -} - -/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf -/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) { - ( - INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()), - INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()), - INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()), - ) -} - -// Whether this superblock's single CDEF unit (this decoder has no 128x128 -// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal -// read -- reset to `false` at the top of each superblock in the two tile -// loops, spec `read_cdef`'s `cdef_transmitted[index]`. -// Number of superblock columns in the current tile's grid, so -// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into -// [`CDEF_IDX_GRID`]. -// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select -// which of the header's `1 << cdef.bits` strength pairs applies to that -// superblock's samples. -// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`] -// has read, across every call on the current thread -- the gate's proof that a -// `cdef_bits > 0` stream actually reached the new reader rather than every -// superblock coincidentally being all-skip. -thread_local! { - pub(super) static CDEF_IDX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// How many times a warp was suppressed for one PLANE because that plane's own -// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out, -// reconinter.c) -- the gate's proof that a stream really carries the shape, -// since the square `side`/`chroma_side` can be 8 or more while the plane's -// true block is 4 wide (an 8x16 luma block's 4x8 chroma). -thread_local! { - pub(super) static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`WARP_PLANE_SUPPRESS_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn warp_plane_suppress_hits() -> usize { - WARP_PLANE_SUPPRESS_HITS.with(|c| c.get()) -} - -/// Current value of [`CDEF_IDX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn cdef_idx_hits() -> usize { - CDEF_IDX_HITS.with(|c| c.get()) -} - -// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no -// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the -// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient -// contexts alone, and the intra-edge filter neighbour pair taken mi-exact -// instead of from the coarse 16x16 cell. -thread_local! { - pub(super) static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter_txctx_hits() -> usize { - INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get()) -} - -/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize { - NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get()) -} - -/// Current value of [`EDGE_FILTER_MI_FIX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn edge_filter_mi_fix_hits() -> usize { - EDGE_FILTER_MI_FIX_HITS.with(|c| c.get()) -} - -// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its -// actual step (`1 << delta.q_res`, already the real multiplier, not the raw -// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a -// true no-op, matching every existing gate stream's `delta_q_present == 0` -// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above. -// The running quantizer index (spec `CurrentQIndex`, libaom -// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the -// top of every tile (spec `decode_tile`), carried across superblocks within -// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the -// dequantization call sites instead of the frame-constant `base_q_idx`. -// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11, -// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not -// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read -// back at every dequantization call site keyed on which plane it is doing. -// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has -// read, across every call on the current thread -- the gate's proof that a -// `delta_q_present` stream actually reached the new reader. -thread_local! { - pub(super) static DELTA_Q_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DELTA_Q_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn delta_q_hits() -> usize { - DELTA_Q_HITS.with(|c| c.get()) -} - -// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi` -// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`. -// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`, -// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile, -// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever -// updates index 0 and every reader treats that as the value for all 4 -// indices (spec `read_delta_lf_params`'s own single-cdf branch). -// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has -// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`]. -thread_local! { - pub(super) static DELTA_LF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DELTA_LF_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn delta_lf_hits() -> usize { - DELTA_LF_HITS.with(|c| c.get()) -} - -// --------------------------------------------------------------------------- -// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`; -// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus -// the two consumers a real stream exercises: the per-segment quantizer index -// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level -// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/ -// `read_intra_segment_id`/`read_inter_segment_id` and -// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL -// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which -// is what the oracle every gate here compares against actually does. -thread_local! { - /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries - /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride). - /// `PrevSegmentIds`: the primary reference frame's saved map, empty when - /// this frame has no primary reference (spec `load_previous_segment_ids`). - /// `(mi_rows, mi_cols)` for both maps above. - /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi - /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which - /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead. - /// The block currently being decoded -- read back by [`block_q_idx`]. - /// The tile's own top-left mi position, for `AvailU`/`AvailL`. - /// How many real `segment_id` symbols were read, and the set of segment - /// ids any block ended up with -- the gate's proof the feature fired. - pub(super) static SEG_ID_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// How many `seg_id_predicted` symbols were read (temporal update). - pub(super) static SEG_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// How many `segment_id` symbols have been read (never reset per frame). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn segment_id_hits() -> usize { - SEG_ID_HITS.with(|c| c.get()) -} - -/// How many `seg_id_predicted` symbols have been read (temporal update). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn segment_pred_hits() -> usize { - SEG_PRED_HITS.with(|c| c.get()) -} - -/// Resets the segmentation hit counters (gate setup). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_segment_hits() { - SEG_ID_HITS.with(|c| c.set(0)); - SEG_IDS_SEEN.with(|c| c.set(0)); - SEG_PRED_HITS.with(|c| c.set(0)); - BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN))); -} - -// How many key-frame luma blocks resolved `smooth_neighbor` (spec -// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after -// counter, proving a stream actually put a directional block next to a -// smooth-predicted neighbour rather than every block reading the (previously -// hardcoded `false`) edge-filter strength bucket unchanged. -thread_local! { - pub(super) static SMOOTH_LUMA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SMOOTH_LUMA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn smooth_luma_hits() -> usize { - SMOOTH_LUMA_HITS.with(|c| c.get()) -} - -thread_local! { - /// lane-band46 r1: how many split-transform units answered their intra - /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the - /// palette2 r12 fix) than the standalone-block lookup this decoder used to - /// apply to them (class reach-is-per-transform-unit). Every hit is a - /// transform unit whose above-right / below-left reference samples would - /// be wrong without that fix. - pub(super) static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SPLIT_TU_REACH_FIX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn split_tu_reach_fix_hits() -> usize { - SPLIT_TU_REACH_FIX_HITS.with(|c| c.get()) -} - -// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12), -// across every call on the current thread -- lane-chroma r3's own before/after -// counter, proving a stream actually exercised chroma's smooth/paeth -// predictor (the previously-refused round-2 gap) rather than every block -// landing on DC/CFL/directional. -thread_local! { - pub(super) static SMOOTH_UV_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SMOOTH_UV_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn smooth_uv_hits() -> usize { - SMOOTH_UV_HITS.with(|c| c.get()) -} - -// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a -// full superblock walk over, across every call on the current thread -- -// lane-tiles r2's own gate-blind-to-feature guard: a gate over a -// multi-tile stream must prove more than one tile actually fired, not just -// that the stream carried tile_info.cols > 1. -thread_local! { - pub(super) static TILE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`TILE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tile_hits() -> usize { - TILE_HITS.with(|c| c.get()) -} - -// How many 4-pixel deblocking edge groups [`edge_params`] has actually -// selected for filtering, across every call on the current thread -- the same -// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream -// exercised `apply_deblock` rather than every edge landing on level 0. -thread_local! { - pub(super) static DEBLOCK_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DEBLOCK_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn deblock_hits() -> usize { - DEBLOCK_HITS.with(|c| c.get()) -} - -// lane-defon r1: how many COMPOUND_REFERENCE blocks read a -// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side, -// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a -// stream built with `--enable-onesided-comp=1` really exercised the -// `uni_comp_ref` alphabet rather than only bidirectional pairs. -thread_local! { - pub(super) static UNI_COMP_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`UNI_COMP_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn uni_comp_hits() -> usize { - UNI_COMP_HITS.with(|c| c.get()) -} - -// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask -// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the -// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted -// blend and not only the wedge arm. -thread_local! { - pub(super) static DIFFWTD_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DIFFWTD_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn diffwtd_hits() -> usize { - DIFFWTD_HITS.with(|c| c.get()) -} - -// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm -- -// a block size where `av1_is_wedge_used` is false (64x64 is the only such size -// this decoder's square inter path reaches), so no `compound_type` symbol is -// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the -// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32. -thread_local! { - pub(super) static DIFFWTD_INFERRED_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DIFFWTD_INFERRED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn diffwtd_inferred_hits() -> usize { - DIFFWTD_INFERRED_HITS.with(|c| c.get()) -} - -// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded -// with `show_frame == 0`, output later by a `show_existing_frame` header -// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from -// `stream::decode_stream`, which is where the frame header is consumed; the -// gate's proof that the on-value really reached the bitstream rather than -// being dropped by the rate control. -thread_local! { - pub(super) static FWD_KF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FWD_KF_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn fwd_kf_hits() -> usize { - FWD_KF_HITS.with(|c| c.get()) -} - -// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than -// the block's own side, across every call on the current thread -- the same -// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream -// actually exercised a *split* transform under `TxMode::Select` rather than -// every block coincidentally resolving `depth=0` (indistinguishable from -// `TxMode::Largest` pixel-wise). -thread_local! { - pub(super) static TX_DEPTH_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma -// transform smaller than their own side (`tx_depth != 0`) while coding a -// chroma prediction other than `DC_PRED` -- the pair the square path's chroma -// only exercises with aomenc's tx-size search left ON (its default), which -// every older recipe in this file pins off. Counted at the block, so a stream -// where RD happened to give every split-transform block a DC chroma mode -// reads as zero rather than silently passing for free. -thread_local! { - pub(super) static SQ_CHROMA_TX_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SQ_CHROMA_TX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sq_chroma_tx_hits() -> usize { - SQ_CHROMA_TX_HITS.with(|c| c.get()) -} - -/// Current value of [`TX_DEPTH_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tx_depth_hits() -> usize { - TX_DEPTH_HITS.with(|c| c.get()) -} - -// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree -// read, and how many of those actually took the split, on the current thread -// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a -// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block -// coincidentally coding one whole-block transform. -thread_local! { - pub(super) static TXFM_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - // lane-inter4 r2: rectangular INTER residual coding -- how many rect - // strips coded one whole-block rect transform unit, and how many split - // their rect max transform into square sub-transforms. - pub(super) static RECT_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT_INTER_TXSPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - // lane-r14 r2: luma transform units of an inter strip with a 64-px axis - // (64x32/32x64/64x16/16x64), whose coefficients are coded as the - // truncated low-32 corner. - pub(super) static RECT64_INTER_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4 - // inter strip, `[32x8, 8x32]`. - pub(super) static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; - // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32]. - pub(super) static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; - // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8] - // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip. - pub(super) static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; - // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter - // frame -- 16x8 and 8x16 inter leaves. - pub(super) static INTER_LEAF16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER_LEAF16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits, - // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] -- - // `decode_inter_block` already carries forty parameters and both are - // frame-constant. - // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit, - // frame-constant like the two above and stashed the same way -- an intra - // block inside an inter frame reads `use_filter_intra` under it. -} - -/// Current value of [`TXFM_SPLIT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn txfm_split_hits() -> usize { - TXFM_SPLIT_HITS.with(|c| c.get()) -} - -/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter_leaf16_horz_hits() -> usize { - INTER_LEAF16_HORZ_HITS.with(|c| c.get()) -} - -/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter_leaf16_vert_hits() -> usize { - INTER_LEAF16_VERT_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2). -pub(crate) fn rect_inter_tu_hits() -> usize { - RECT_INTER_TU_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2). -pub(crate) fn rect_inter_txsplit_hits() -> usize { - RECT_INTER_TXSPLIT_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2). -pub(crate) fn rect64_inter_tu_hits() -> usize { - RECT64_INTER_TU_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]` -/// whole-block luma units of a 32x32-level 1:4 inter strip. -pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] { - RECT32X8_INTER_TU_HITS.with(|c| c.get()) -} - -/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many -/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`. -pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] { - VARTX_RECT_LEAF_HITS.with(|c| c.get()) -} - -/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8 -/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`. -pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] { - VARTX_RECT_LEAF4_HITS.with(|c| c.get()) -} - -/// Records one rectangular var-tx leaf. -pub(super) fn vartx_rect_leaf_hit(tw: usize, th: usize) { - if crate::envflags::env_flag!("EC_VARTXLEAF") { - eprintln!("EC_VARTXLEAF tw={tw} th={th}"); - } - let cell = if tw.min(th) == 4 { - &VARTX_RECT_LEAF4_HITS - } else { - &VARTX_RECT_LEAF_HITS - }; - cell.with(|c| { - let mut h = c.get(); - h[usize::from(th > tw)] += 1; - c.set(h); - }); -} - -// How many `partition_w16` reads (a 16x16 block's own partition symbol, key -// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a -// plain default-settings aomenc run over lavfi mandelbrot hits this arm on -// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not -// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real -// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`, -// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8 -// path above). -thread_local! { - pub(super) static VERT_B_INTRA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`VERT_B_INTRA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn vert_b_intra_hits() -> usize { - VERT_B_INTRA_HITS.with(|c| c.get()) -} - -// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in -// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two -// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`, -// the non-skip coefficient path lane-rectx proved); the gate hard-asserts -// every arm separately so a run where aomenc's RD only picked one cannot -// pass as proof of four. -thread_local! { - pub(super) static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; -} - -// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16). -thread_local! { - /// 4x4 transform units decoded inside an 8x8 square of a - /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before - /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove - /// a real `--enable-tx-size-search=1` stream reaches it. - pub(super) static VERT_AB_TX4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn vert_ab_tx4_hits() -> usize { - VERT_AB_TX4_HITS.with(std::cell::Cell::get) -} - -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn ab16_hits_by_arm() -> [usize; 4] { - AB16_HITS.with(std::cell::Cell::get) -} - -// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/ -// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above -// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7), -// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's -// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one -// superblock's z-order recursion, not raster mi position). -thread_local! { - pub(super) static HORZ_VERT_INTRA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`HORZ_VERT_INTRA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn horz_vert_intra_hits() -> usize { - HORZ_VERT_INTRA_HITS.with(|c| c.get()) -} - -// How many blocks were decoded as a frame-edge rect strip -- the single -// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge -// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose -// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter -// paths share the counter. -thread_local! { - pub(super) static EDGE_RECT_STRIP_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`EDGE_RECT_STRIP_HITS`]. -#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live -pub(crate) fn edge_rect_strip_hits() -> usize { - EDGE_RECT_STRIP_HITS.with(|c| c.get()) -} - -// lane-interedge r1: frame-edge half strips on the INTER path, per partition -// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The -// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and -// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films -// are height mod 16 == 8, so every inter frame crosses these nodes. -thread_local! { - pub(super) static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> = - const { std::cell::Cell::new([0; 6]) }; -} - -// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT -// forced split -- libaom `decode_partition` (decodeframe.c): -// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one -// straddle case that reads NO symbol at all. Indexed by level: -// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it. -thread_local! { - pub(super) static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> = - const { std::cell::Cell::new([0; 4]) }; -} - -/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`). -pub fn inter_edge_strip_hits() -> [usize; 6] { - INTER_EDGE_STRIP_HITS.with(|c| c.get()) -} - -/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits -/// into the next one (class `counter-from-refused-stream`). -pub fn reset_inter_edge_strip_hits() { - INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6])); -} - -/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn edge_both_cut_hits() -> [usize; 4] { - EDGE_BOTH_CUT_HITS.with(|c| c.get()) -} - -/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_edge_both_cut_hits() { - EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4])); -} - -// How many HORZ/VERT intra strips resolved a SPLIT luma transform -// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- -// the case every rect path here refused by name before, and the first -// refusal the user's ReelB extract (600s in) stops at. -thread_local! { - pub(super) static RECT_SPLIT_TX_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_SPLIT_TX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_split_tx_hits() -> usize { - RECT_SPLIT_TX_HITS.with(|c| c.get()) -} - -// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one -// side 64) AND split past the first depth, i.e. tiled more than one unit in -// each axis -- the only shape with a transform unit that has neighbours on -// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one -// no gate fired before lane-rectsplit r2 (the shared counter above also -// counts 32x32-level and depth-1 strips, so it cannot prove this case). -thread_local! { - pub(super) static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_split_sb_interior_tu_hits() -> usize { - RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get()) -} - -// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1 -// wired into [`decode_rect_split`] -- the shapes a split-transform strip's -// chroma half takes that had no coefficient tables before (index order: -// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only -// proves the pair it happens to hit cannot catch a transposed scan/context -// table (class scan-weights-cross-axis). -thread_local! { - pub(super) static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> = - const { std::cell::Cell::new([0; 4]) }; -} - -/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] { - RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get()) -} - -// lane-av1-422: how many SQUARE chroma coefficient units the strip path read -// on a 4:2:2 frame (ss 1,0) -- the half-width, unhalved-height shape whose -// tables only exist because of the square rows in the chroma_tiled arm. A -// 4:2:0 or 4:4:4 frame can never increment it (their rect strips' chroma is -// itself rect), and a restored `/2 chroma height` diverts 4:2:2 squares onto -// the rect rows, so the witness gate reads 0 there and fails. -thread_local! { - pub(super) static CHROMA422_SQUARE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_SQUARE_HITS`]. -// lane-av1-422b: `pub` so `examples/decode_probe.rs` can census it the way -// it does every other capability counter. -pub fn chroma422_square_hits() -> usize { - CHROMA422_SQUARE_HITS.with(|c| c.get()) -} - -// lane-av1422tailskip: how many 4:2:2 (ss 1,0) intra-in-inter chroma TRANSFORM -// UNITS took their own window on the block-sized chroma palette prediction -- -// `decode_inter_block`'s `side == 64` TX_32X32 walk, where the plane block is -// 32x64 but codes two stacked square units per plane. Zero on a 4:2:0 or 4:4:4 -// frame (their chroma unit is the whole plane block, one window), and zero on -// a 4:2:2 block with no palette, so a witness gate reading 0 proves the arm -// never ran. -thread_local! { - pub(super) static PALETTE_422_UNIT_WINDOW_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_422_UNIT_WINDOW_HITS`]. -// lane-av1422tailskip: `pub` so `examples/decode_probe.rs` can census it the -// way it does every other capability counter. -pub fn palette_422_unit_window_hits() -> usize { - PALETTE_422_UNIT_WINDOW_HITS.with(|c| c.get()) -} - -// lane-av1-422f: how many RECT chroma coefficient units the square-block -// path read on a 4:2:2 frame (ss 1,0) -- TX_4X8 / TX_8X16 / TX_16X32, the -// plane block's own half-width, unhalved-height shape. A 4:2:0 or 4:4:4 -// frame never takes the rect branch (their units are square -// `chroma_tx == chroma_tx_h`), so a witness gate reading 0 here proves the -// model reverted to squares. -thread_local! { - pub(super) static CHROMA422_RECT_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_RECT_HITS`]. -pub fn chroma422_rect_hits() -> usize { - CHROMA422_RECT_HITS.with(|c| c.get()) -} - -// lane-av1-422g: how many PER-LEAF TX_4X4 chroma coefficient units the -// sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per even-column -// leaf per plane (`is_chroma_reference`'s `!(mi_col & ss_x)`). A 4:2:0 frame -// codes no sub-8 chroma at all and 4:4:4 goes through `sub8_leaf_chroma444`, -// so a witness gate reading 0 here proves the per-leaf 4:2:2 arm never ran. -thread_local! { - pub(super) static CHROMA422_SUB8_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_SUB8_HITS`]. -pub fn chroma422_sub8_hits() -> usize { - CHROMA422_SUB8_HITS.with(|c| c.get()) -} - -// lane-av1422llintra: how many 4:2:2 LOSSLESS chroma plane blocks -// (`decode_leaf8`) were walked as 4x4 units rather than as the one -// `av1_get_max_uv_txsize` rect that rule only reaches OUTSIDE a lossless -// frame. A 4:2:0 or 4:4:4 frame never takes the arm (its own lossless walk -// was already there), so a witness gate reading 0 here proves the model -// reverted to the rect unit. -thread_local! { - pub(super) static CHROMA422_LOSSLESS_4X4_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_LOSSLESS_4X4_HITS`]. -pub fn chroma422_lossless_4x4_hits() -> usize { - CHROMA422_LOSSLESS_4X4_HITS.with(|c| c.get()) -} - -// lane-av1-422sub8rect: how many PER-PIECE TX_4X4 chroma coefficient units -// the INTER sub-8x8 split4 path read on a 4:2:2 frame (ss 1,0) -- one per -// non-skipped odd-column piece per plane (`is_chroma_reference`'s -// `mi_col & 0x01` at ss_x 1). 4:2:0 goes through the shared group unit and -// 4:4:4 through [`sub8_leaf_chroma444`]'s own per-piece twin, so a witness -// gate reading 0 here proves the inter 4:2:2 per-piece arm never ran. -thread_local! { - pub(super) static CHROMA422_INTER_SUB8_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_INTER_SUB8_HITS`]. -pub fn chroma422_inter_sub8_hits() -> usize { - CHROMA422_INTER_SUB8_HITS.with(|c| c.get()) -} - -// lane-av1-422m: how many TX_4X4 chunk units the invalid-ss-size chroma arm -// read (the 8x32 luma block whose 4:2:2 plane has no `ss_size_lookup` block). -// A 4:2:0 or 4:4:4 frame cannot increment it, so a non-zero read proves the -// chunked 4:2:2 chroma really decoded. -thread_local! { - pub(super) static CHROMA422_CHUNK_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_CHUNK_HITS`]. -pub fn chroma422_chunk_hits() -> usize { - CHROMA422_CHUNK_HITS.with(|c| c.get()) -} - -// lane-av1-422stripanchor: how many 4-wide-strip PAIR chroma units -// ([`decode_rect_split`]'s ported floored-pair anchor) decoded. A 4:2:0 or -// 4:4:4 frame cannot increment it (the arm is keyed to a 2-px-wide chroma -// block, which only a 1-mi-wide strip at ss (1, 0) produces), so a non-zero -// read proves a stream routed a 4-wide strip through the split path. -thread_local! { - pub(super) static CHROMA422_PAIR_WIDE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA422_PAIR_WIDE_HITS`]. -pub fn chroma422_pair_wide_hits() -> usize { - CHROMA422_PAIR_WIDE_HITS.with(|c| c.get()) -} - -// How many HORZ/VERT intra strips actually predicted with filter intra -// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name -// ("this decoder predicts square-only") until `predict_filter_intra` took -// `bw`x`bh`. -thread_local! { - pub(super) static FILTER_INTRA_RECT_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FILTER_INTRA_RECT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn filter_intra_rect_hits() -> usize { - FILTER_INTRA_RECT_HITS.with(|c| c.get()) -} - -// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips -// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol -// was never read at all before that round, so a gate needs to prove the flag -// fired at THAT shape and not at a 16x8 one somewhere else in the frame. -// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA` -// carry different probabilities (18101 vs 20229), so a transposed pair is -// only caught by a gate that sees the flag fire on BOTH shapes (class -// scan-weights-cross-axis). -thread_local! { - pub(super) static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - pub(super) static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn filter_intra_rect4_horz_hits() -> usize { - FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get()) -} - -/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn filter_intra_rect4_vert_hits() -> usize { - FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get()) -} - -// How many rectangular transform units actually coded coefficients through -// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate -// exercised the rect coefficient reader at all rather than passing on -// all-skip blocks. -thread_local! { - pub(super) static RECT_COEFF_TU_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT_CLASS1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_COEFF_TU_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_coeff_tu_hits() -> usize { - RECT_COEFF_TU_HITS.with(|c| c.get()) -} - -/// Rectangular transform units whose resolved `tx_type` is a 1D class -/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can -/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling -/// for the square reader's own 1D types. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_class1_hits() -> usize { - RECT_CLASS1_HITS.with(|c| c.get()) -} - -// lane-av1readcensus: the PER-UNIT coefficient census -- one unit counted -// per `read_coeffs`/`read_coeffs_rect` call, i.e. per object this decoder -// actually walks, which is the unit the round-4 `av1444rect` count measured -// (636 square chroma reads against the oracle's 1086). -// -// lane-av1422census422 widened the arming. The counters used to be -// 4:4:4-ONLY (`CENSUS_444`), so at 4:2:2 -- a chroma format an AV1 -// `color_config` can carry and libaom's writer emits -- every -// `census_444_units()` / `census_444_coded()` read zero BY CONSTRUCTION: a -// byte-exact 4:2:2 gate asserting those counters would be asserting a -// literal, and would be green while proving nothing about that stream. The -// census is now armed for every chroma format that leaves at least one luma -// axis unsubsampled -- (0,0) 4:4:4 and (1,0) 4:2:2 -- and 4:2:0 (1,1) stays -// off, so the existing 4:4:4 exact counts and the 4:2:0 zero control are -// unmoved by the widening. The counters are per-PLANE, not per-format, so a -// 4:2:2 cell's `[luma, u, v]` split is directly comparable with a 4:4:4 -// cell's on the same walk shape. -thread_local! { - /// Per-plane unit counts, `[luma, u, v]`, at 4:4:4 and 4:2:2. - pub(super) static CENSUS_NONSUB_UNITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; - /// Of [`CENSUS_NONSUB_UNITS`], the units that coded at least one - /// coefficient (`txb_skip == 0`) -- the per-plane split is only - /// comparable against the oracle's when both sides count all-zero units - /// the same way. - pub(super) static CENSUS_NONSUB_CODED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; - /// Sequential unit index, so a trace line names its own position in the - /// frame's walk rather than relying on line order alone. - pub(super) static CENSUS_UNIT_N: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// The plane the units read from here on belong to. A thread-local rather - /// than a `read_coeffs` parameter because the three luma call sites - /// (`decode_rect_split`, `decode_block_rect64`, `read_inter_plane_rect`) - /// are not this lane's to edit and would each grow an argument; the - /// plane-owning readers stamp it once on entry instead. - pub(super) static CENSUS_PLANE: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// At least one luma axis unsubsampled -- (0,0) 4:4:4 or (1,0) 4:2:2 -- - /// for the frame being decoded, set per frame from [`crate::stream`]. - /// 4:2:0 (1,1) arms nothing. - pub(super) static CENSUS_NONSUB: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// Current `[luma, u, v]` coefficient-unit counts, per plane. Zero at 4:2:0 -/// by design ([`set_census_nonsub`] arms nothing there). -pub fn census_nonsub_units() -> [usize; 3] { - CENSUS_NONSUB_UNITS.with(|c| c.get()) -} - -/// Current `[luma, u, v]` counts of units that coded coefficients. -pub fn census_nonsub_coded() -> [usize; 3] { - CENSUS_NONSUB_CODED.with(|c| c.get()) -} - -/// lane-av1readcensus: arms the coefficient-unit census for the frame about -/// to decode, called once per frame from [`crate::stream`]'s decode loop -/// beside [`set_subsampling`]. Armed for every chroma format with an -/// unsubsampled luma axis -- 4:4:4 (0,0) and 4:2:2 (1,0) -- and NOT for -/// 4:2:0 (1,1), where the walk-shape question this census answers does not -/// arise, so a 4:2:0 control can still assert exactly zero. -/// -/// lane-av1422census422 widened this from `(ss_x == 0 && ss_y == 0)`. The -/// old condition made 4:2:2 silently UNCUNTABLE rather than uncounted. The -/// two format pairs keep disjoint conditions, so neither the 4:4:4 exact -/// counts nor the 4:2:0 zero control can move because of this. -pub(crate) fn set_census_nonsub(ss_x: u8, ss_y: u8) { - CENSUS_NONSUB.with(|c| c.set(ss_x == 0 || ss_y == 0)); -} - -/// lane-av1readcensus: the plane the units read from here on belong to, -/// stamped by the plane-owning readers ([`read_plane`], [`read_inter_plane`], -/// [`read_inter_plane_rect`]) on entry. -pub(crate) fn set_census_plane(plane: usize) { - CENSUS_PLANE.with(|c| c.set(plane)); -} - -/// lane-av1readcensus: is the per-unit census trace on? Shares -/// [`coeff_trace_on`]'s per-frame narrowing so one frame's walk can be -/// dumped without the rest of the stream. -fn census_trace_on() -> bool { - if !crate::envflags::env_flag!("EC_CENSUS_UNIT") { - return false; - } - match COEFF_TRACE_FRAME.with(|c| c.get()) { - None => true, - Some(w) if w >= usize::MAX - 1 => true, - Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w, - } -} - -/// lane-av1readcensus: one line per coefficient unit this decoder walks, the -/// twin of the oracle's `EC_COEFF` / `EC_COEFF_VAL` bracket around each -/// `av1_read_coeffs_txb` call. Pair the two sides by `post_rng` (or by `n`), -/// never by plane label or by walk position -- the walk order is exactly what -/// the census is measuring. -pub(super) fn census_unit( - w: usize, - h: usize, - tx_type: TxType, - eob: usize, - all_zero: bool, - entry_rng: u32, - dec: &SymbolDecoder, -) { - let plane = CENSUS_PLANE.with(|c| c.get()).min(2); - let coded = usize::from(!all_zero); - CENSUS_UNIT_N.with(|c| c.set(c.get() + 1)); - hit_do! { - CENSUS_NONSUB_UNITS.with(|c| { - if CENSUS_NONSUB.with(|on| on.get()) { - let mut v = c.get(); - v[plane] += 1; - c.set(v); - } - }); - CENSUS_NONSUB_CODED.with(|c| { - if CENSUS_NONSUB.with(|on| on.get()) { - let mut v = c.get(); - v[plane] += coded; - c.set(v); - } - }); - } - if !census_trace_on() { - return; - } - let n = CENSUS_UNIT_N.with(|c| c.get()) - 1; - let post_rng = dec.debug_state().0; - eprintln!( - "EC_CENSUS_UNIT side=ours n={n} plane={plane} w={w} h={h} tx={tx_type:?} eob={eob} \ - all_zero={all_zero} entry_rng={entry_rng} post_rng={post_rng}" - ); -} - -/// How many transform units this thread has read since the last -/// [`reset_census_unit_n`] (lane-av1offtile). The per-unit oracle twin is -/// `EC_ECDUMP_IN`, one line per `read_coeffs_txb` call, so this count IS -/// directly comparable with an oracle `EC_ECDUMP_IN` census -- which is what -/// makes "we walk N units where libaom walks M" a gated claim rather than an -/// inference from the desync's position. -pub fn census_unit_n() -> usize { - CENSUS_UNIT_N.with(|c| c.get()) -} - -/// Reset [`census_unit_n`] to zero (lane-av1offtile). -pub fn reset_census_unit_n() { - CENSUS_UNIT_N.with(|c| c.set(0)); -} - -// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16 -// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the -// shapes whose `use_filter_intra` symbol had no CDF class before this round. -// A gate asserting the wider counter would be satisfied by a 32x16 strip and -// prove nothing about the new shapes. -thread_local! { - pub(super) static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn filter_intra_rect_sub16_hits() -> usize { - FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get()) -} - -// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down: -// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16 -// counter would be satisfied by a 16x8 strip and prove nothing here. -thread_local! { - pub(super) static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn filter_intra_rect_sub8_hits() -> usize { - FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get()) -} - -// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` -// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every -// call on the current thread -- the same before/after counter pattern as -// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split -// `eob_pt`/1D-neighbour context path rather than every block coincidentally -// landing on `DCT_DCT`. -thread_local! { - pub(super) static TX_CLASS1_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -// How many `uv_mode` reads resolved to a directional chroma mode (neither -// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same -// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream -// actually exercised chroma's own directional predictor. -thread_local! { - pub(super) static DIRECTIONAL_UV_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DIRECTIONAL_UV_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn directional_uv_hits() -> usize { - DIRECTIONAL_UV_HITS.with(|c| c.get()) -} - -// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as -// something other than [`ANGLE_DELTA_ZERO`], across every call in the -// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`], -// proving a stream actually exercised a nonzero angle delta. -thread_local! { - pub(super) static ANGLE_DELTA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -// How many [`read_single_ref`] reads resolved to a reference other than -// `LAST_FRAME`, across every call on the current thread -- the same before/after -// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually -// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's -// only other supported one so far) rather than every block coincidentally -// resolving `LAST_FRAME`. -thread_local! { - pub(super) static NON_LAST_REF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`NON_LAST_REF_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn non_last_ref_hits() -> usize { - NON_LAST_REF_HITS.with(|c| c.get()) -} - -// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter -// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one -// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`) -// can prove THAT reference fired rather than any non-`LAST_FRAME` one -- -// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a -// `GOLDEN_FRAME` draw it did not ask for. -thread_local! { - pub(super) static LAST2_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -thread_local! { - pub(super) static LAST3_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -thread_local! { - pub(super) static GOLDEN_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -thread_local! { - pub(super) static BWDREF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -thread_local! { - pub(super) static ALTREF2_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -thread_local! { - pub(super) static ALTREF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp) -// -- proves a `reference_select` stream actually reached a block that picked -// compound, not just that the header bit was set. Every such block is -// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]), -// so this only ever counts attempted reads, never a completed decode. -thread_local! { - pub(super) static COMP_MODE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`COMP_MODE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn comp_mode_hits() -> usize { - COMP_MODE_HITS.with(|c| c.get()) -} - -// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y -// use for, across every call on the current thread -- the same before/after -// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually -// exercised palette reconstruction rather than only reading and refusing the -// `palette_y_mode` symbol. -thread_local! { - pub(super) static PALETTE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_hits() -> usize { - PALETTE_HITS.with(|c| c.get()) -} - -// lane-tiles r12: of those, how many sat at their own TILE's left column -- -// exactly the blocks whose palette cache/ctx must NOT see the previous tile's -// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile -// palette gate that never hits one proves nothing about the tile guard. -thread_local! { - pub(super) static PALETTE_TILE_LEFT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_TILE_LEFT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_tile_left_hits() -> usize { - PALETTE_TILE_LEFT_HITS.with(|c| c.get()) -} - -// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma -// palette use -- proves a stream actually reconstructed UV palette pixels, -// not just read and refused the `palette_uv_mode` symbol. -thread_local! { - pub(super) static PALETTE_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_UV_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_uv_hits() -> usize { - PALETTE_UV_HITS.with(|c| c.get()) -} - -// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`]) -// decoded a real palette-Y use -- proves the rect strip's own palette syntax -// (not just the square path's) actually fired. -thread_local! { - pub(super) static PALETTE_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_RECT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_rect_hits() -> usize { - PALETTE_RECT_HITS.with(|c| c.get()) -} - -// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the -// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] -- -// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in -// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per -// RD, almost always refused-on-use because the block doesn't end up USING a -// palette -- see r5's report). This is the site the removed refusal -// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it -// fired here whether or not the block picked a palette, so this is the -// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost -// never observes. -thread_local! { - pub(super) static RECT_SCREEN_CONTENT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_SCREEN_CONTENT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_screen_content_hits() -> usize { - RECT_SCREEN_CONTENT_HITS.with(|c| c.get()) -} - -// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a -// split luma transform (`logical_tx != side`) -- proves the per-TU index-map -// windowing actually ran, not just that the whole-block path stayed exact. -// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16); -// first actually incremented in r7, when the refusal it guarded was lifted. -thread_local! { - pub(super) static PALETTE_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the - /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves - /// (16x8/8x16), the two shapes the lifted refusals named. - pub(super) static RECT4_PALETTE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT4_PALETTE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect4_palette_hits() -> usize { - RECT4_PALETTE_HITS.with(|c| c.get()) -} - -/// Current value of [`PALETTE_SPLIT_TX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_split_tx_hits() -> usize { - PALETTE_SPLIT_TX_HITS.with(|c| c.get()) -} - -thread_local! { - /// lane-av1444d10: chroma PREDICTION units on the 32-capped tiled chroma - /// walk (`decode_block_rect`'s `uw/uh = min(chroma, 32)` units) that were - /// handed a STRICT sub-slice of their block's palette buffer -- i.e. the - /// units of a block the 32-cap actually TILED (`nw * nh > 1`). - /// - /// CORRECTED 2026-09-30 after the refutation pass `lanes/refute-av1444d10` - /// read the numbers back: the previous comment claimed it counted "the - /// units that are NOT the block's top-left corner", which is not what the - /// code did -- the hit was unconditional, so a block's corner unit fired it - /// too AND a single-unit block (whose window is a pure re-stride copy of - /// the whole buffer) fired it as well. That made a hit prove only that some - /// palette chroma block existed, not that the tiled arm ran. The `bigger` - /// guard now makes the counter discriminate. On the pinned fixture the - /// measured value is unchanged at 4 (one block with nw = 1, nh = 2 x two - /// planes x two unit rows); a stream whose palette chroma blocks are all - /// single-unit now leaves it at zero. - /// - /// FURTHER CORRECTED the same day by the palette lane's refutation - /// (`lanes/av1444palw.report.md` + the arm-isolated mutation): the guard is - /// about TILING, not about `nw > 1` specifically. Isolating the two window - /// sites shows the RECT-unit arm alone reds the 10-bit cell, and the - /// SQUARE-unit arm alone reds the 12-bit cell *and* the 10-bit one -- so - /// windowing is load-bearing for every tiled block, and `nw > 1` is merely - /// the case the corpus could not reach. Do not read this counter as - /// evidence that only the horizontal term matters. - pub(super) static CHROMA_PALETTE_WINDOW_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA_PALETTE_WINDOW_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_palette_window_hits() -> usize { - CHROMA_PALETTE_WINDOW_HITS.with(|c| c.get()) -} - -/// Zeroes [`CHROMA_PALETTE_WINDOW_HITS`] so a gate can read it as a DELTA -/// (it is process-wide, like every counter here). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_chroma_palette_window_hits() { - CHROMA_PALETTE_WINDOW_HITS.with(|c| c.set(0)); -} - -thread_local! { - /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a - /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen` - /// stream stopped on, since aomenc palettes square blocks at 8 bit and - /// `--min-partition-size=8` puts them on this leaf path. - pub(super) static PALETTE_LEAF8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_LEAF8_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_leaf8_hits() -> usize { - PALETTE_LEAF8_HITS.with(|c| c.get()) -} - -/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_palette_leaf8_hits() { - PALETTE_LEAF8_HITS.with(|c| c.set(0)); -} - -thread_local! { - /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level) - /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette - /// block that also carries a real, corner-cropped luma transform. - pub(super) static PALETTE_SB_STRIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_SB_STRIP_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn palette_sb_strip_hits() -> usize { - PALETTE_SB_STRIP_HITS.with(|c| c.get()) -} - -/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_palette_sb_strip_hits() { - PALETTE_SB_STRIP_HITS.with(|c| c.set(0)); -} - -thread_local! { - /// lane-av1rectreach: units of `decode_rect_split`'s `chroma_tiled` walk - /// whose PER-UNIT reach ([`tu_reach_rect`], libaom's per-unit - /// `has_top_right` / `has_bottom_left`) DIFFERS from the block-level - /// `reach` this walk used to hand every unit -- i.e. units for which the - /// two answers are not interchangeable. This is what a gate needs before - /// it compares the walk byte-exactly: if the two agreed everywhere, the - /// substitution could not change a single predicted sample and the - /// exactness assert would be measuring a witness the fix cannot touch. - /// - /// What it does NOT prove is that the argument handed to the unit reader - /// is the per-unit one -- the count is taken from the same expression - /// either way, so deleting the substitution reds the exactness assert - /// rather than this counter. That is the right way round: the assert is - /// the claim, this is only the floor under it. - pub(super) static RECT_TILED_CHROMA_UNIT_REACH_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - /// Chroma units of the same walk whose grid is exactly 2x1 (a 4:4:4 - /// 64x32 chroma plane block as two 32x32 units). - pub(super) static RECT_TILED_CHROMA_2X1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Chroma units of the same walk whose grid is exactly 1x2 (4:4:4 32x64, - /// or 16x64 as two 16x32s). - pub(super) static RECT_TILED_CHROMA_1X2_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Chroma units of the same walk in any other multi-unit grid (2x2 and - /// up). lane-av1422lift: this used to say "only reachable at 4:2:2, which - /// is refused, so this stays 0 on every admitted stream", and that was - /// true. 4:2:2 is decoded now, so the "cannot happen" is gone -- but the - /// arm is still UNWITNESSED: measured on this branch's tip over all 21 - /// committed 4:2:2 cells and over the 4:2:0 / 4:4:4 cells probed, it - /// reads 0 on every one of them. No committed gate reads it either (the - /// only readers of `rect_tiled_chroma_grid_hits()` are two 4:4:4 strip - /// gates, where `nxn` is interpolated into a failure message and never - /// asserted). Kept so the match above is exhaustive. - pub(super) static RECT_TILED_CHROMA_NXN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current values of the four `RECT_TILED_CHROMA_*` counters, in the order -/// `(unit_reach_differs, 2x1, 1x2, other multi-unit)`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) { - ( - RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.get()), - RECT_TILED_CHROMA_2X1_HITS.with(|c| c.get()), - RECT_TILED_CHROMA_1X2_HITS.with(|c| c.get()), - RECT_TILED_CHROMA_NXN_HITS.with(|c| c.get()), - ) -} - -/// Zeroes the four `RECT_TILED_CHROMA_*` counters (gate tests call this -/// before their own decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_rect_tiled_chroma_grid_hits() { - RECT_TILED_CHROMA_UNIT_REACH_HITS.with(|c| c.set(0)); - RECT_TILED_CHROMA_2X1_HITS.with(|c| c.set(0)); - RECT_TILED_CHROMA_1X2_HITS.with(|c| c.set(0)); - RECT_TILED_CHROMA_NXN_HITS.with(|c| c.set(0)); -} - -// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the -// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted -// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame -// capability rather than the key frame's, which every screen stream also -// carries. -thread_local! { - pub(super) static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8 -// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the -// shared counter too, so only this one proves a gate really reached the leaf -// where the refusal used to sit. -thread_local! { - pub(super) static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> = - const { std::cell::Cell::new((0, 0)) }; -} - -/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`. -pub(crate) fn inter8_palette_hits() -> (usize, usize) { - INTER8_PALETTE_HITS.with(std::cell::Cell::get) -} - -/// Current values of the two intra-in-inter palette counters, `(y, uv)`. -pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) { - ( - INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()), - INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()), - ) -} - -// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform -// and which are therefore predicted one transform unit at a time (a skipped -// block codes no coefficients, so nothing else in the stream witnesses this -// path -- only the pixels do). -thread_local! { - pub(super) static SKIP_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units). -pub fn skip_split_tx_hits() -> usize { - SKIP_SPLIT_TX_HITS.with(|c| c.get()) -} - -// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose -// `tx_depth` split the luma transform -- the arm that predicted DC off the -// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels -// witness this path, so a gate that wants it needs the counter. -thread_local! { - pub(super) static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1chromadc: chroma units of a skipped block whose intra-BC / - /// UV-palette override had to be WINDOWED to the unit's own extent -- - /// i.e. `cn_cols * cn_rows > 1`, which at 4:2:0 never happens (the chroma - /// plane block is one 32x32 unit) and at 4:4:4 is every block of 64 and - /// above. Counts UNITS, not blocks. EXCLUSIVE to this walk: the other two - /// override sites (the luma slot and `decode_intrabc_owned_rect`) have - /// their own windows. - pub(super) static SKIP_CHROMA_OVERRIDE_WINDOW_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks). -pub fn skip_split_tx_override_hits() -> usize { - SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get()) -} - -/// lane-av1chromadc: [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn skip_chroma_override_window_hits() -> usize { - SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.get()) -} - -/// Zeroes [`SKIP_CHROMA_OVERRIDE_WINDOW_HITS`] before a gate's own decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn reset_skip_chroma_override_window_hits() { - SKIP_CHROMA_OVERRIDE_WINDOW_HITS.with(|c| c.set(0)); -} - -/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt. -pub fn reset_skip_split_tx_override_hits() { - SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0)); -} - -// lane-svtinter: palette colour-index maps whose block is cut by the frame's -// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight` -// really are smaller than the block and FEWER symbols are read than the -// block has cells (class map-read-past-frame-edge). -thread_local! { - pub(super) static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps). -pub fn palette_onscreen_cut_hits() -> usize { - PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get()) -} - -/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt. -pub fn reset_palette_onscreen_cut_hits() { - PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0)); -} - -/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt. -pub fn reset_skip_split_tx_hits() { - SKIP_SPLIT_TX_HITS.with(|c| c.set(0)); -} - -// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` -// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- -// the gate's proof that the lifted path actually ran, per size. -thread_local! { - pub(super) static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> = - const { std::cell::Cell::new([0; 4]) }; -} - -/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] { - INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) -} - -thread_local! { - /// The current frame's `mi` grid, kept only while a frame header set - /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary - /// MV stack ([`crate::mvstack::find_mv_stack`]) built against - /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise - /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that - /// does not allow intrabc (so nothing is paid for it). - /// - /// corner-cut: only [`decode_block`] (the square path) records into it, - /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off - /// an incomplete grid. Ceiling: the DV *value* (never the parse) would - /// be wrong there; upgrade = record from the rect/leaf paths too. - /// The block vector [`read_intra_mode`] just decoded, handed to - /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`], - /// which the alternative -- a tenth tuple member through every caller -- - /// already avoids). Always `.take()`n by the block that reads it. - /// How many blocks read `use_intrabc == 1` and took the DV path -- the - /// gate's hit counter. Bumped on the READ, before the rect-strip refusal - /// returns too, so it counts reads, not reconstructions (a refused block - /// is never reconstructed). - pub(super) static INTRABC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_rect_intrabc_reads() { - RECT_INTRABC_READS.with(|c| c.set(0)); -} - -thread_local! { - /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically - /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape. - pub(super) static LEAF8_INTRABC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// Chroma reads of an intrabc TX4-split leaf that consulted an ARMED - /// [`INTRABC_CHROMA_TX`] slot -- proof that the arm's frame-copy + - /// inherited-type route actually ran (lane-av1intrapred r2's non-vacuity - /// counter: zero means the gate's fixture no longer reaches the route). - pub(super) static INTRABC_TX4_CHROMA_COPY_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRABC_TX4_CHROMA_COPY_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intrabc_tx4_chroma_copy_hits() -> usize { - INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.get()) -} - -/// Zeroes [`INTRABC_TX4_CHROMA_COPY_HITS`] (gate tests call this before a decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_tx4_chroma_copy_hits() { - INTRABC_TX4_CHROMA_COPY_HITS.with(|c| c.set(0)); -} - -/// Current value of [`LEAF8_INTRABC_HITS`]. -pub(crate) fn leaf8_intrabc_hits() -> usize { - LEAF8_INTRABC_HITS.with(|c| c.get()) -} - -/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_leaf8_intrabc_hits() { - LEAF8_INTRABC_HITS.with(|c| c.set(0)); -} - -/// Current value of [`INTRABC_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intrabc_hits() -> usize { - INTRABC_HITS.with(|c| c.get()) -} - -thread_local! { - /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is - /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no - /// chroma coefficient at all, so the slot used to stay armed into the NEXT - /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count - /// here. A non-zero value is what makes the disarm below load-bearing. - pub(super) static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe -pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize { - SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get()) -} - -/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a -/// decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() { - SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0)); -} - -thread_local! { - /// lane-av1-ibcskip2: a sub-8x8 4:4:4 leaf that is BOTH intrabc AND - /// `skip` -- the arm whose chroma is the bare frame copy at the DV - /// (libaom `av1_build_inter_predictors_sb` runs regardless of `skip`). - /// Before the fix this route predicted intra-DC and every one of this - /// fixture's 150 such cells differed from the oracle on both chroma - /// planes. - pub(super) static SKIPPED_INTRABC_DV_COPY_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SKIPPED_INTRABC_DV_COPY_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn skipped_intrabc_dv_copy_hits() -> usize { - SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.get()) -} - -/// Zeroes [`SKIPPED_INTRABC_DV_COPY_HITS`] (gate tests call this before a -/// decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_skipped_intrabc_dv_copy_hits() { - SKIPPED_INTRABC_DV_COPY_HITS.with(|c| c.set(0)); -} - -/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_hits() { - INTRABC_HITS.with(|c| c.set(0)); -} - -thread_local! { - /// lane-t900 r32: intrabc blocks whose transform size came off the INTER - /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability - /// that replaced the refusal "an intrabc block under TxMode::Select". - pub(super) static INTRABC_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-ibcvtx: intrabc var-tx trees that resolved to MIXED leaf - /// sizes (not one square size across every leaf) -- the engagement - /// counter proving a witness actually exercises the per-leaf reconstruct. - pub(super) static INTRABC_VARTX_MIXED_LEAVES_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf -- - /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves - /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no - /// symbol here desynced `warped.obu` at the very next block. - pub(super) static RECT_INTRABC_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction - /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip - /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never - /// this one). - pub(super) static INTRABC_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT). - pub(super) static INTRABC_RECT_VARTX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction - /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read), - /// split by the strip's orientation -- `bw > bh` is a HORZ strip, - /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED - /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS` - /// counts neither orientation nor the skip flag, so an arm that flipped - /// to an all-skip stream (no residual reader at all) would stay green. - pub(super) static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> = - const { std::cell::Cell::new([0, 0]) }; - /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`] - /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split - /// by orientation. The r5 panic (residual stride `bw * bh` underrunning - /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was - /// invisible to every gate because they only counted CODED strips. - pub(super) static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> = - const { std::cell::Cell::new([0, 0]) }; - /// lane-ibc444c: rect intra-BC blocks whose chroma plane block was sized - /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where - /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h) applies no - /// halving of its own. At 4:2:0 this is the same arithmetic as the halving, - /// so a `>= 1` witness can only come from a stream that is not 4:2:0. - /// EXCLUSIVE to this arm: no other caller sizes an intrabc rect block's - /// chroma plane block. - pub(super) static IBC_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - /// lane-whtshape: LOSSLESS rect intrabc blocks whose chroma plane block - /// [`decode_intrabc_rect`] walked as a `(cw/4) * (ch/4)` PLANE-MAJOR - /// raster of TX_4X4 units -- the shape libaom's lossless geometry codes - /// (`read_tx_size` returns `TX_4X4` for EVERY plane of a lossless block, - /// `get_vartx_max_txsize` likewise, and `read_tx_mode` forced the frame's - /// `ONLY_4X4`) -- instead of the single rect unit, which is what put a - /// non-4x4 unit on the lossless Walsh-Hadamard path. EXCLUSIVE to this arm: - /// no other caller walks a rect intrabc block's chroma, so `>= 1` cannot - /// be satisfied by any older route. - pub(super) static INTRABC_RECT_LOSSLESS_CHROMA4_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - /// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips - /// ([`decode_intrabc_owned_rect`]) whose chroma plane block was sized - /// `bw >> ss_x` by `bh >> ss_y` -- the 4:4:4 and 4:4:0 cells, where - /// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies - /// no halving of its own. At 4:2:0 the two forms are the same arithmetic, - /// so a `>= 1` witness can only come from a stream that is not 4:2:0. - /// EXCLUSIVE to this arm: no other caller sizes a 128-root intra-BC - /// strip's chroma plane block. - pub(super) static IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - /// lane-av1422ibctxsel: `decode_intrabc_owned_rect`'s NON-SPLIT chroma - /// gather taken through the 4:2:2 pair rule (`around_mi_422_chroma`) - /// under the ss (1, 0) guard -- both residual branches (the var-tx tree - /// and the no-leaves twin). `>= 1` can only come from a 4:2:2 stream - /// that reaches this function's non-split chroma arm; the 4:2:0/4:4:4 - /// arms keep the plain `around_mi_rect` gather (`ss_y != 0` / `ss_x == 0` - /// take the else), so the counter stays 0 for them. - pub(super) static IBC_OWNED_RECT_422_PAIR_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed, -/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_rect_coded_hits() -> [usize; 2] { - INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get) -} - -/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks -/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_rect_skipped_hits() -> [usize; 2] { - INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get) -} - -/// Current value of [`INTRABC_RECT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_rect_hits() -> usize { - INTRABC_RECT_HITS.with(|c| c.get()) -} - -/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_rect_hits() { - INTRABC_RECT_HITS.with(|c| c.set(0)); - INTRABC_RECT_VARTX_HITS.with(|c| c.set(0)); - INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0])); - INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0])); -} - -/// lane-ibc444c: [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn ibc_rect_chroma_footprint_444_hits() -> usize { - IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get()) -} - -/// lane-ibc444c: zeroes [`IBC_RECT_CHROMA_FOOTPRINT_444_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_ibc_rect_chroma_footprint_444_hits() { - IBC_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0)); -} - -/// lane-av1chromarect: [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize { - IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.get()) -} - -/// lane-av1chromarect: zeroes [`IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_ibc_owned_rect_chroma_footprint_444_hits() { - IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS.with(|c| c.set(0)); -} - -/// lane-av1422ibctxsel: [`IBC_OWNED_RECT_422_PAIR_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn ibc_owned_rect_422_pair_hits() -> usize { - IBC_OWNED_RECT_422_PAIR_HITS.with(|c| c.get()) -} - -/// lane-av1422ibctxsel: zeroes [`IBC_OWNED_RECT_422_PAIR_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_ibc_owned_rect_422_pair_hits() { - IBC_OWNED_RECT_422_PAIR_HITS.with(|c| c.set(0)); -} - -/// lane-whtshape: [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_rect_lossless_chroma4_hits() -> usize { - INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.get()) -} - -/// lane-whtshape: zeroes [`INTRABC_RECT_LOSSLESS_CHROMA4_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_rect_lossless_chroma4_hits() { - INTRABC_RECT_LOSSLESS_CHROMA4_HITS.with(|c| c.set(0)); -} - -/// Current value of [`INTRABC_RECT_VARTX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_rect_vartx_hits() -> usize { - INTRABC_RECT_VARTX_HITS.with(|c| c.get()) -} - -thread_local! { - /// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip - /// (BLOCK_128X64 / BLOCK_64X128) whose reconstruction - /// [`decode_intrabc_128rect`] ran -- the shape the named refusal used to - /// guard (`decode_block_128rect`). A refused block bumps - /// [`INTRABC_HITS`] but never this one. - pub(super) static INTRABC_128RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc - /// strip's mu-chunk walk read, one per `read_inter_plane` chroma call. - /// At 4:2:0 a 64x64 mu chunk's chroma plane block is 32x32, so one - /// TX_32X32 per plane per chunk; at 4:2:2 it is 32x64 and holds TWO - /// STACKED units per plane. The square-cut `chunk_chroma = cside * 64 / - /// side` model walked the 4:2:0 count on every axis, so this counter is - /// the reach/arm witness for the per-axis walk. - pub(super) static INTRABC_128RECT_CHROMA_CHUNK_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRABC_128RECT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_128rect_hits() -> usize { - INTRABC_128RECT_HITS.with(|c| c.get()) -} - -/// Zeroes [`INTRABC_128RECT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_128rect_hits() { - INTRABC_128RECT_HITS.with(|c| c.set(0)); -} - -/// Current value of [`INTRABC_128RECT_CHROMA_CHUNK_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_128rect_chroma_chunk_hits() -> usize { - INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.get()) -} - -/// Zeroes [`INTRABC_128RECT_CHROMA_CHUNK_HITS`] and -/// [`INTRABC_128RECT_CHUNK_SHAPE`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_128rect_chroma_chunk_hits() { - INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(0)); - INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.set(0)); -} - -/// Current value of [`INTRABC_VARTX_HITS`]. -pub fn intrabc_vartx_hits() -> usize { - INTRABC_VARTX_HITS.with(|c| c.get()) -} - -/// Current value of [`INTRABC_VARTX_MIXED_LEAVES_HITS`]. -pub fn intrabc_vartx_mixed_leaves_hits() -> usize { - INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.get()) -} - -/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_vartx_hits() { - INTRABC_VARTX_HITS.with(|c| c.set(0)); -} - -/// Zeroes [`INTRABC_VARTX_MIXED_LEAVES_HITS`] (gate tests call this before a -/// decode). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_vartx_mixed_leaves_hits() { - INTRABC_VARTX_MIXED_LEAVES_HITS.with(|c| c.set(0)); -} - -/// Current value of [`RECT_INTRABC_VARTX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn rect_intrabc_vartx_hits() -> usize { - RECT_INTRABC_VARTX_HITS.with(|c| c.get()) -} - -// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) -- -// proves a real `skip_mode_present` stream actually reached a block that -// picked it, not just that the frame header bit was set. -thread_local! { - pub(super) static SKIP_MODE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SKIP_MODE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn skip_mode_hits() -> usize { - SKIP_MODE_HITS.with(|c| c.get()) -} - -// lane-motionmode: how many blocks actually decoded `obmc_selected == true` -// (as opposed to just reaching an eligible `read_motion_mode` symbol read) -// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream -// reached [`obmc_blend`], not just the header bit. -thread_local! { - pub(super) static OBMC_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the -// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled -// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while -// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have -// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this -// decoder used to read with the wrong alphabet, so a gate that asserts this -// counter advanced proves the fixed path fired (class -// `gate-blind-to-feature`). -thread_local! { - pub(super) static FIMV_ALPHABET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FIMV_ALPHABET_HITS`]. -pub fn fimv_alphabet_hits() -> usize { - FIMV_ALPHABET_HITS.with(|c| c.get()) -} - -// lane-fimv r1: how many frame headers this decoder has decoded with -// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate -// prove the encoder really produced the header state under test rather than -// assume it. -thread_local! { - pub(super) static FIMV_FRAME_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`FIMV_FRAME_HITS`]. -pub fn fimv_frame_hits() -> usize { - FIMV_FRAME_HITS.with(|c| c.get()) -} - -/// Current value of [`OBMC_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn obmc_hits() -> usize { - OBMC_HITS.with(|c| c.get()) -} - -// lane-scaledref r1: per-case firing counts for the scaled-reference gate -// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED -// reference would pass just as well and prove nothing, so the gate -// hard-asserts each combination this round lifts actually occurred: -// a compound block with a scaled tap, a warp block whose warp libaom -// suppresses because the reference is scaled, an OBMC block, an interintra -// block, and an 8x8 leaf. -thread_local! { - pub(super) static SCALED_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SCALED_WARP_FALLBACK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SCALED_OBMC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SCALED_INTERINTRA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SCALED_BLOCK8_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one -/// scaled and one unscaled tap. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn mixed_scale_compound_hits() -> usize { - MIXED_SCALE_COMPOUND_HITS.with(|c| c.get()) -} - -/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have -/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf` -/// instead because their reference is scaled (libaom `motion_mode_allowed`, -/// `blockd.h:1484`). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn scaled_warp_suppressed_hits() -> usize { - SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get()) -} - -/// Current value of [`SCALED_COMPOUND_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn scaled_compound_hits() -> usize { - SCALED_COMPOUND_HITS.with(|c| c.get()) -} - -/// Current value of [`SCALED_WARP_FALLBACK_HITS`]. -pub fn scaled_warp_fallback_hits() -> usize { - SCALED_WARP_FALLBACK_HITS.with(|c| c.get()) -} - -/// Current value of [`SCALED_OBMC_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn scaled_obmc_hits() -> usize { - SCALED_OBMC_HITS.with(|c| c.get()) -} - -/// Current value of [`SCALED_INTERINTRA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn scaled_interintra_hits() -> usize { - SCALED_INTERINTRA_HITS.with(|c| c.get()) -} - -/// Current value of [`SCALED_BLOCK8_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn scaled_block8_hits() -> usize { - SCALED_BLOCK8_HITS.with(|c| c.get()) -} - -// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to -// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of -// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an -// 8x8-leaf OBMC block apart from a 16x16+ one. -thread_local! { - pub(super) static OBMC_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter` -// pair whose two directions differ (`enable_dual_filter` only -- with dual -// filter off both directions take the single symbol, so this can never fire). -// A gate asserting it proves the stream really carries dual-filter blocks. -thread_local! { - pub(super) static DUAL_FILTER_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own -// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf -// used to skip it entirely, losing a symbol and stamping the `[3, 3]` -// no-filter sentinel that made a neighbouring OBMC block panic). -thread_local! { - pub(super) static COMPOUND8_FILTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DUAL_FILTER_DIFF_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn dual_filter_diff_hits() -> usize { - DUAL_FILTER_DIFF_HITS.with(|c| c.get()) -} - -/// Current value of [`COMPOUND8_FILTER_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn compound8_filter_hits() -> usize { - COMPOUND8_FILTER_HITS.with(|c| c.get()) -} - -// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to -// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under -// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL` -// -- the gate's proof that a fixture really exercises the alphabet this -// round changed, even though the block itself still refuses (warp -// estimation/filter not ported). -thread_local! { - pub(super) static WARP_SELECTED_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`WARP_SELECTED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn warp_selected_hits() -> usize { - WARP_SELECTED_HITS.with(|c| c.get()) -} - -// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one -// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane` -// into the compound intermediate) rather than translationally -- the -// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model -// really reached [`crate::warp::warp_affine_compound`]. -// lane-av1422warp: the 4:2:2 coverage witness has to show compound and warped -// motion firing ABOVE the vertical midpoint, and every pre-existing warp -// counter is frame-global. These two are the same arms restricted to blocks -// whose top mode-info row is in the frame's upper half, which is the half -// this lane's evidence covers. -thread_local! { - pub(super) static TOP_HALF_COMPOUND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static TOP_HALF_WARP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// How many `GLOBAL_GLOBALMV` (compound) inter blocks decoded in the frame's -/// upper half -- the block's top mode-info row is under `mi_rows / 2`. -/// -/// NO COMMITTED TEST READS THIS, and none can while the 4:2:2 header refusal -/// stands: the pinned 4:2:2 coverage gate asserts the byte pin and the -/// refusal by name, so nothing in the suite ever decodes a 4:2:2 stream. -/// The figure quoted for that fixture comes from a patch-run-restore build -/// with the `EC_AV1_ALLOW_422_PROBE` bypass applied and then reverted, which -/// is the same discipline every 4:2:2 lane in this family uses. -#[allow(dead_code)] -pub(crate) fn top_half_compound_hits() -> usize { - TOP_HALF_COMPOUND_HITS.with(std::cell::Cell::get) -} - -/// How many inter blocks in the frame's upper half satisfy libaom's -/// `is_global_mv_block` on at least one reference slot -- mode -/// `GLOBAL_GLOBALMV` AND block >= 8x8 AND that slot's own global-motion -/// model > `TRANSLATION`. This is the block set whose prediction goes -/// through `crate::warp`, and it is exactly `is_global_mv0 || is_global_mv1` -/// as computed at the increment site; it is NOT merely "some slot has a -/// non-TRANSLATION model", which also counts blocks that are not global-mv -/// blocks. -/// -/// Like [`top_half_compound_hits`], no committed test reads it: with the -/// 4:2:2 header refusal in force nothing in the suite decodes the stream -/// these numbers describe. -#[allow(dead_code)] -pub(crate) fn top_half_warp_hits() -> usize { - TOP_HALF_WARP_HITS.with(std::cell::Cell::get) -} - -thread_local! { - pub(super) static COMPOUND_WARP_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`COMPOUND_WARP_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn compound_warp_hits() -> usize { - COMPOUND_WARP_HITS.with(|c| c.get()) -} - -// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound -// arm ([`decode_inter_block8`]) -- that arm predicted both taps -// translationally until r3, so a gate needs to tell a warped 8x8 compound -// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]). -thread_local! { - pub(super) static COMPOUND_WARP_HITS_8: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`COMPOUND_WARP_HITS_8`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn compound_warp_hits_8() -> usize { - COMPOUND_WARP_HITS_8.with(|c| c.get()) -} - -// lane-gmaffine r1: how many blocks built their prediction from a -// SIX-parameter (`AFFINE`) global-motion model through -// `crate::warp::global_warp_params` -- the gate's proof that a stream really -// carried an AFFINE `global_motion_params` AND that a block was predicted -// with it, not merely that the header parsed one. -thread_local! { - pub(super) static AFFINE_GM_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`AFFINE_GM_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn affine_gm_hits() -> usize { - AFFINE_GM_HITS.with(|c| c.get()) -} - -// lane-av1distwtd: how many blocks took the DISTANCE-WEIGHTED compound -// combine rather than the simple average -- `compound_idx == 0` under -// `enable_jnt_comp`, whose weights come from -// [`crate::compound::dist_wtd_comp_weight_assign`] instead of the constant -// `(8, 8)` split. Counting the `idx == 0` arm (not merely the -// `compound_idx` symbol read) is what makes this a witness of the TOOL: a -// stream that carries `enable_jnt_comp = true` in its sequence header but -// codes every compound block with `compound_idx == 1` leaves this at 0 and -// decoded identically without the whole distance-weight path. -thread_local! { - pub(super) static DIST_WTD_COMP_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`DIST_WTD_COMP_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn dist_wtd_comp_hits() -> usize { - DIST_WTD_COMP_HITS.with(|c| c.get()) -} - -/// Resets [`DIST_WTD_COMP_HITS`] to 0. -#[allow(dead_code)] // test-only -pub(crate) fn reset_dist_wtd_comp_hits() { - DIST_WTD_COMP_HITS.with(|c| c.set(0)); -} - -// lane-av1gwarp12: how many 16x16+ blocks built their SINGLE-reference -// prediction through `crate::warp::global_warp_params` with a FOUR-parameter -// (`ROTZOOM`) model. Vanilla aomenc pins its global-motion search to ROTZOOM -// (`global_motion_facade.c:24`), so this is the only >TRANSLATION single-ref -// global-warp arm a real aomenc stream can reach (AFFINE needs the widened -// side build and its own counter, [`AFFINE_GM_HITS`]). -thread_local! { - pub(super) static ROTZOOM_GM_WARP_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`ROTZOOM_GM_WARP_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rotzoom_gm_warp_hits() -> usize { - ROTZOOM_GM_WARP_HITS.with(|c| c.get()) -} - -// lane-t900 r9: rect blocks whose warp-sample top-right probe answers -// differently at the block's WIDTH than at libaom's -// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could -// pick the wrong motion_mode alphabet. -thread_local! { - pub(super) static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`TR_REACH_LONGER_SIDE_HITS`]. -pub fn tr_reach_longer_side_hits() -> usize { - TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get) -} - -// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0 -// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block -// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS -// reads its interp-filter symbol. Counts the blocks where that guard flips -// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model -// and a 4-px side, which we used to suppress the interp read on (a pre-mode -// entropy desync one symbol wide). -thread_local! { - pub(super) static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`]. -pub fn gm_nontrans_small_side_hits() -> usize { - GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get) -} - -// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves -// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real -// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented -// only once `find_projection` returned a usable model, unlike -// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates' -// proof that the leaf path itself fired, not the 16x16+ one. -thread_local! { - pub(super) static GLOBALMV_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static WARP_HITS_8: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`GLOBALMV_HITS_8`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn globalmv_hits_8() -> usize { - GLOBALMV_HITS_8.with(|c| c.get()) -} - -/// Current value of [`WARP_HITS_8`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn warp_hits_8() -> usize { - WARP_HITS_8.with(|c| c.get()) -} - -// How many blocks decoded `interintra == 1` with the non-wedge blended -// prediction applied (lane-interintra r1) -- the gate's proof that a -// stream actually exercised interintra. -thread_local! { - pub(super) static INTERINTRA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTERINTRA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn interintra_hits() -> usize { - INTERINTRA_HITS.with(|c| c.get()) -} - -// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`) -// -- the shape `interintra_blend` used to build a square `side x side` intra -// predictor for, with `ii_size_scales`/`edges` taken at the square. Every -// pre-existing interintra gate passed with that bug, so the rect arm needs -// its own counter to stop being vacuous. -thread_local! { - pub(super) static INTERINTRA_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTERINTRA_RECT_HITS`]. -pub fn interintra_rect_hits() -> usize { - INTERINTRA_RECT_HITS.with(|c| c.get()) -} - -// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE, -// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/ -// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a -// gate fixture actually exercises this alphabet, even though the block -// still refuses (the mask blend itself is unported). -thread_local! { - pub(super) static MASKED_COMPOUND_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`MASKED_COMPOUND_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn masked_compound_hits() -> usize { - MASKED_COMPOUND_HITS.with(|c| c.get()) -} - -// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a -// masked-compound block whose true footprint is rectangular, i.e. the case -// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the -// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that -// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it. -thread_local! { - pub(super) static RECT_MASKED_COMPOUND_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_MASKED_COMPOUND_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_masked_compound_hits() -> usize { - RECT_MASKED_COMPOUND_HITS.with(|c| c.get()) -} - -// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx == -// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture -// actually exercised the wedge blend, not just the DIFFWTD half of -// `MASKED_COMPOUND_HITS`. -thread_local! { - pub(super) static WEDGE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`WEDGE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn wedge_hits() -> usize { - WEDGE_HITS.with(|c| c.get()) -} - -// How many blocks decoded a real wedge-INTERINTRA block -// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof -// a gate fixture exercised the wedge blend (fixed sign 0), not just the -// smooth arm counted by `INTERINTRA_HITS`. -thread_local! { - pub(super) static WII_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`WII_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn wii_hits() -> usize { - WII_HITS.with(|c| c.get()) -} - -// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol -// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`: -// wide <= 32 && high <= 32). The witness that a gate stream really carries a -// 64-axis intra block -- the shape whose 14-symbol read desynced every inter -// frame carrying one. -thread_local! { - pub(super) static NOCFL_UV_MODE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`NOCFL_UV_MODE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn nocfl_uv_mode_hits() -> usize { - NOCFL_UV_MODE_HITS.with(|c| c.get()) -} - -// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a -// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that -// the rect wedge masks lifted this round actually fired, not just the square -// ones already counted by `WEDGE_HITS`/`WII_HITS`. -thread_local! { - pub(super) static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; - pub(super) static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) }; -} - -/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`]. -pub(crate) fn rect_wedge_hits() -> [usize; 6] { - RECT_WEDGE_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`]. -pub(crate) fn rect_wii_hits() -> [usize; 6] { - RECT_WII_HITS.with(|c| c.get()) -} - -// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC -// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the -// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented -// aomdec, neighbour list included). -thread_local! { - pub(super) static OBMC_RECT_LEAF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`OBMC_RECT_LEAF_HITS`]. -pub(crate) fn obmc_rect_leaf_hits() -> usize { - OBMC_RECT_LEAF_HITS.with(|c| c.get()) -} - -// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of -// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used -// to be read from the pair's FIRST mi, which is a different block and, when -// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three -// 1080p 10-bit film cuts refused there). The gate's proof the shape fired. -thread_local! { - pub(super) static OBMC_PAIR_FILTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`OBMC_PAIR_FILTER_HITS`]. -pub(crate) fn obmc_pair_filter_hits() -> usize { - OBMC_PAIR_FILTER_HITS.with(|c| c.get()) -} - -// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge -// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's -// own side, so a block overhanging the bottom/right still predicts the full -// neighbour strip (the destination write is what clips). We used to shrink the -// prediction to the visible part, which at 4 chroma rows/cols also swaps the -// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired. -thread_local! { - pub(super) static OBMC_EDGE_SPAN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`OBMC_EDGE_SPAN_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn obmc_edge_span_hits() -> usize { - OBMC_EDGE_SPAN_HITS.with(|c| c.get()) -} - -/// Current value of [`OBMC_HITS_8`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn obmc_hits_8() -> usize { - OBMC_HITS_8.with(|c| c.get()) -} - -// lane-rectgate r1: how many 32x32 quadrants actually decoded a -// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's -// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/ -// `VERT_B` all still fall into the generic "a partition type this encoder -// never writes" refusal below) -- the gate's proof that a free-partition -// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than -// coincidentally never selecting one. -thread_local! { - pub(super) static EXTENDED_PARTITION_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`EXTENDED_PARTITION_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn extended_partition_hits() -> usize { - EXTENDED_PARTITION_HITS.with(|c| c.get()) -} - -// lane-partitions r1: how many 32x32 quadrants decoded a real -// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike -// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition -// gate's proof this round's arms actually fired. -thread_local! { - pub(super) static RECT_PARTITION_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_PARTITION_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_partition_hits() -> usize { - RECT_PARTITION_HITS.with(|c| c.get()) -} - -// lane-inter8 r1: how many superblocks an inter tile coded as a single -// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for -// static content, previously a named refusal). -thread_local! { - /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile - /// path decoded as one whole block (its gate's own witness). - pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7). - pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta. -pub(crate) fn inter_sb128_horz_hits() -> usize { - INTER_SB128_HORZ_HITS.with(std::cell::Cell::get) -} - -/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta. -pub(crate) fn inter_sb128_vert_hits() -> usize { - INTER_SB128_VERT_HITS.with(std::cell::Cell::get) -} - -/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta. -pub fn inter_sb128_none_hits() -> usize { - INTER_SB128_NONE_HITS.with(std::cell::Cell::get) -} - -thread_local! { - /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER - /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma - /// units) -- the gate's witness that the lifted refusal's case fired. - pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta. -pub fn intra_128_in_inter_hits() -> usize { - INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get) -} - -thread_local! { - /// lane-av1ibc128arm: how many 64x64 mu-chunk CHROMA units the - /// intra-in-inter 128x128 root read (`decode_inter_block`'s - /// `side > 64` mu-chunk arm, the INTRA half of the inter pair). Every - /// unit is one `read_plane` on U and one on V, so the counter is the - /// gate's proof the arm ran at all -- no committed 4:4:4 fixture - /// reached it before this lane. - pub(crate) static INTRA_128_IN_INTER_MU_CHROMA_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_128_IN_INTER_MU_CHROMA_HITS`], for a gate's -/// before/after delta. -pub fn intra_128_in_inter_mu_chroma_hits() -> usize { - INTRA_128_IN_INTER_MU_CHROMA_HITS.with(std::cell::Cell::get) -} - -thread_local! { - pub(super) static INTER_SB_NONE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTER_SB_NONE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter_sb_none_hits() -> usize { - INTER_SB_NONE_HITS.with(|c| c.get()) -} - -// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter -// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle -// path has always run that loop, so only this counter proves the newly-lifted -// alphabet value fired. -thread_local! { - pub(super) static INTER_SUB16_SPLIT_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTER_SUB16_SPLIT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter_sub16_split_hits() -> usize { - INTER_SUB16_SPLIT_HITS.with(|c| c.get()) -} - -// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves -// while at least one reference picture was SCALED (superres) -- the counter -// behind the lifted "8x8 partition leaf under a scaled reference" refusal. -thread_local! { - pub(super) static SCALED_LEAF8_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SCALED_LEAF8_HITS`]. -pub fn scaled_leaf8_hits() -> usize { - SCALED_LEAF8_HITS.with(|c| c.get()) -} - -// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8 -// rect pair) were predicted from a SCALED reference -- the counter behind the -// lifted "sub-8x8 inter block under a scaled reference" refusal. -thread_local! { - pub(super) static SCALED_SUB8_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`SCALED_SUB8_HITS`]. -pub fn scaled_sub8_hits() -> usize { - SCALED_SUB8_HITS.with(|c| c.get()) -} - -// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded -// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the -// rect coefficient reader itself fired, not just the strip-level partition -// symbol [`RECT_PARTITION_HITS`] already counts. -thread_local! { - pub(super) static RECT_COEFF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_COEFF_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_coeff_hits() -> usize { - RECT_COEFF_HITS.with(|c| c.get()) -} - -// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`]) -// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the -// charter's real-aomenc gate hard-asserts. -thread_local! { - pub(super) static RECT_LEAF_COEFF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT_LEAF_COEFF_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_leaf_coeff_hits() -> usize { - RECT_LEAF_COEFF_HITS.with(|c| c.get()) -} - -// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the -// INTER block path ([`decode_intra_rect_in_inter`]), per shape class -- -// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16. -// Every one of them was the named refusal "an intra-coded HORZ/VERT strip -// needs rectangular intra prediction" before this round. -thread_local! { - pub(super) static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = - const { std::cell::Cell::new([0; 3]) }; -} - -/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class -/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize { - INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class]) -} - -// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded -// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the -// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of -// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on. -// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT): -// a single counter cannot tell an axis swap from a working arm -// (class [[scan-weights-cross-axis]]), so the gate asserts both cells. -thread_local! { - pub(super) static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> = - const { std::cell::Cell::new([0; 2]) }; -} - -/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation -/// (0 = 64x32, 1 = 32x64). -pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize { - RECT64_CORNER_TU_HITS.with(|c| c.get()[orient]) -} - -// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma -// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0 -// is never incremented) -- the gate's proof that the lifted path ran per depth. -thread_local! { - pub(super) static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> = - const { std::cell::Cell::new([0; 3]) }; -} - -// lane-t900 r21: rect intra strips inside an inter frame that read the -// screen-content palette syntax (`allow_screen_content_tools` set and the -// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket -// refusal used to guard, so this counter is what keeps its witness gate -// non-vacuous. -thread_local! { - pub(super) static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_rect_in_inter_screen_hits() -> usize { - INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get) -} - -/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intra_rect_in_inter_screen_hits() { - INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0)); -} - -/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] { - INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get) -} - -// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid -// approximation would have resolved off a DIFFERENT CDF row than the real -// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY -// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block" -// tally is green on the old code too (class gate-blind-to-feature). -thread_local! { - pub(super) static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`]. -#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live -pub(crate) fn txctx_deblock_divergence_hits() -> usize { - TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get) -} - -// lane-av1txctxband: how many `get_tx_size_context` reads the per-CELL -// `is_inter_block` cover and the per-COLUMN `above_inter`/`left_inter` bands -// DISAGREE about -- i.e. exactly the reads whose CDF row the old code chose -// wrongly. Green on the old code too (a plain "some block was inter" tally -// would be), so this is the non-vacuity arm of the witness gate: it is 0 on -// every stream where the bands happened to be right and non-zero on the -// 4:4:4 lossy `--sb-size=128` cq-62 stream whose entropy forked at read 32813 -// on the 8x4 intra leaf at mi(57,52). -thread_local! { - pub(super) static TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gate -pub(crate) fn txctx_inter_cell_band_divergence_hits() -> usize { - TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(std::cell::Cell::get) -} - -/// Zeroes [`TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gate -pub(crate) fn reset_txctx_inter_cell_band_divergence_hits() { - TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS.with(|c| c.set(0)); -} - -// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER -// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every -// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1) -// rect strip on the inter block path" before this round. -thread_local! { - pub(super) static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> = - const { std::cell::Cell::new([0; 4]) }; -} - -/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape -/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32). -pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize { - INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape]) -} - -// lane-av1444rect: how many 1:4 inter strips at `ss_x == 0` read their chroma -// coefficient context over the STRIP'S OWN extent instead of the 4:2:0 pair's -// (see [`decode_inter_block`]'s `around_c`). `is_chroma_reference` -// (av1_common_int.h:1454) is unconditionally true at ss (0,0), so no pair -// exists there; the counter keeps a 4:4:4 1:4-strip gate from passing -// vacuously (a 4:2:0 stream of the same content leaves it at 0). It proves -// REACH only, never that the fix bites -- that is the gate's byte compare and -// its mutation, not this count (skill://ec-av1-pipeline-gate-counters). -thread_local! { - pub(super) static RECT4_INTER_OWN_CHROMA444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT4_INTER_OWN_CHROMA444_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect4_inter_own_chroma444_hits() -> usize { - RECT4_INTER_OWN_CHROMA444_HITS.with(std::cell::Cell::get) -} - -/// Resets [`RECT4_INTER_OWN_CHROMA444_HITS`] before a decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_rect4_inter_own_chroma444_hits() { - RECT4_INTER_OWN_CHROMA444_HITS.with(|c| c.set(0)); -} - -// lane-av1444rect r2: how many intra-BC 1:4 strips at `ss (0,0)` took the -// own-chroma arm of [`decode_rect4_16_intrabc`]'s `own444`. A 4:2:0 / 4:2:2 -// stream of the same recipe leaves it at 0, which is what makes it the -// 4:4:4-only route. -// -// WHAT THIS COUNTER IS NOT: it is NOT evidence that the fix bites, and it -// never was. A route counter fires identically before and after a change that -// changes nothing downstream, so a non-zero count proves REACH and nothing -// more. On this lane it is also armed deliberately OUTSIDE the `own444` -// expression, so that the mutation (`own444 = false`) still increments it and -// the red comes from the pixel/entropy arm instead. The evidence that the ss -// gate bites is the measured fork move -- first entropy fork read 11750 -> -// 12465, luma first wrong sample 164416 -> 205264, 455240 -> 390380 total -- -// not this count. See skill://ec-av1-pipeline-gate-counters: a counter needs -// a DIFFERS-style assertion to carry a claim. -thread_local! { - pub(super) static INTRABC_RECT4_OWN_CHROMA444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-av1422luma: the ss (1,0) twin of `INTRABC_RECT4_OWN_CHROMA444_HITS` -// -- how many intra-BC 1:4 strips at 4:2:2 took the own-chroma (no pair) -// route. Same caveat as the 4:4:4 counter: it proves REACH and nothing else. -// lane-av1422lift: 4:2:2 is DECODED, so this counter is no longer pinned -// behind a header refusal -- and it DOES fire: measured on this branch's tip, -// the six committed corpus cells each read 1 more than the cell before -// (`s422_320x246` 1, `s422_322x240` 2, `s422_322x246` 3, `s422_352x242_10b` -// 4, `s422_416x242_10b` 5, `s422_416x250_10b` 6), and every other committed -// 4:2:2 cell leaves it at 6. **No committed gate reads it**: the accessor -// below has no callers in the crate (the 4:4:4 twin is read at two -// `stream.rs` sites, this one nowhere). The honest sentence is therefore -// "no committed test reads this counter", which is what the 4:4:4 twin's -// doc says about itself -- it does NOT become "the corpus gate reads it". -thread_local! { - pub(super) static INTRABC_RECT4_OWN_CHROMA422_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRABC_RECT4_OWN_CHROMA422_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intrabc_rect4_own_chroma422_hits() -> usize { - INTRABC_RECT4_OWN_CHROMA422_HITS.with(std::cell::Cell::get) -} - -/// Resets [`INTRABC_RECT4_OWN_CHROMA422_HITS`] before a decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_rect4_own_chroma422_hits() { - INTRABC_RECT4_OWN_CHROMA422_HITS.with(|c| c.set(0)); -} - -/// Current value of [`INTRABC_RECT4_OWN_CHROMA444_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intrabc_rect4_own_chroma444_hits() -> usize { - INTRABC_RECT4_OWN_CHROMA444_HITS.with(std::cell::Cell::get) -} - -/// Resets [`INTRABC_RECT4_OWN_CHROMA444_HITS`] before a decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_intrabc_rect4_own_chroma444_hits() { - INTRABC_RECT4_OWN_CHROMA444_HITS.with(|c| c.set(0)); -} - -// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader -// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an -// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16 -// slot -- i.e. how often the r5 defect would have picked the wrong CDF row. -thread_local! { - pub(super) static MODE_MI_OVERRIDE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`MODE_MI_OVERRIDE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn mode_mi_override_hits() -> usize { - MODE_MI_OVERRIDE_HITS.with(|c| c.get()) -} - -// lane-cfl r1: how many times a chroma intra-edge filter-type read -// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the -// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the -// r1 defect would have filtered a chroma edge with the wrong strength. -thread_local! { - pub(super) static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn uv_mode_mi_override_hits() -> usize { - UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get()) -} - -// lane-t900 r12: how many chroma edge-filter-type reads took their above/left -// `uv_mode` from the mi GRID where the one-slot-per-column map would have -// answered differently -- the sub-8x8 pair case where the pair's own first -// half had already overwritten the column slot the chroma-ref half reads. -thread_local! { - pub(super) static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`]. -pub fn uv_mode_grid_override_hits() -> usize { - UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get()) -} - -// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the -// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode -// from an earlier block in that pixel row/column while the mi-exact map -- -// which an inter block only started writing this round -- correctly says the -// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is -// an INTER mode, and its `uv_mode` "is not set for inter blocks"). -thread_local! { - pub(super) static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter_neighbour_not_smooth_hits() -> usize { - INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get()) -} - -// lane-mtfix r1: how many times a chroma intra-edge filter-type read was -// suppressed at a TILE edge that is not a frame edge -- the above/left -// `uv_mode` neighbour of a block on a tile's first mi row/column lives in -// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The -// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per -// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile -// above would decide this tile's chroma edge filter strength. -thread_local! { - pub(super) static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn uv_tile_edge_suppressed_hits() -> usize { - UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get()) -} - -// lane-av1leftref: how many chroma intra-edge filter-type reads land on a -// left neighbour whose `uv_mode` at libaom's real read cell -// (`base_mi[ss_y * mi_stride - 1]` = row `+ss_y`, col `-1`) DIFFERS from the -// cell this decoder used to read (its own mi row). Two buckets: the raw mode -// value moved, and `is_smooth_mode` -- the boolean the read actually feeds -- -// flipped. The second is the one that can move pixels. -thread_local! { - pub(super) static UV_LEFT_SS_Y_MODE_DIFF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - pub(super) static UV_LEFT_SS_Y_SMOOTH_DIFF_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`UV_LEFT_SS_Y_MODE_DIFF_HITS`]. -pub fn uv_left_ss_y_mode_diff_hits() -> usize { - UV_LEFT_SS_Y_MODE_DIFF_HITS.with(|c| c.get()) -} - -/// Current value of [`UV_LEFT_SS_Y_SMOOTH_DIFF_HITS`]. -pub fn uv_left_ss_y_smooth_diff_hits() -> usize { - UV_LEFT_SS_Y_SMOOTH_DIFF_HITS.with(|c| c.get()) -} - -// lane-av1leftwit: decode-path chroma edge-filter-type reads at `ss_y > 0` -// whose left-neighbour COLUMN holds a run of length 1 -- the cell this -// decoder reads (its own mi row) and the cell libaom reads (one row down) -// were written by two DIFFERENT blocks, i.e. the left neighbour is at most -// 1 mi tall. That is the only geometry in which the `+ss_y` term can change -// the answer at all; `UV_LEFT_SS_Y_READS` alone proves nothing about it. -thread_local! { - pub(super) static UV_LEFT_1MI_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`UV_LEFT_1MI_SPLIT_HITS`]. -pub fn uv_left_1mi_split_hits() -> usize { - UV_LEFT_1MI_SPLIT_HITS.with(|c| c.get()) -} - -// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs` -// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block -// shapes the r1 chroma defect showed up on. -thread_local! { - pub(super) static CFL_BLOCK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static UV_ANGLE_DELTA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-av1cfl: which `cfl_ac_ss` arm ran, one bump per CfL block. The 4:4:4 -// arm is libaom `cfl_luma_subsampling_444_lbd_c` (1x1 luma per chroma sample) -// and the 4:2:2 arm is `cfl_luma_subsampling_422_lbd_c`; only the last two -// reach `cfl_ac_q3_at`'s 2x2 average, so these four are the reachability -// evidence for that function's format-blind extent. -thread_local! { - pub(super) static CFL_AC_444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static CFL_AC_422_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static CFL_AC_420_SQ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static CFL_AC_420_RECT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static CFL_AC_Q3_AT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// `[4:4:4, 4:2:2, 4:2:0 square, 4:2:0 rect]` [`cfl_ac_ss`] arm hits. -pub fn cfl_ac_arm_hits() -> [usize; 4] { - [ - CFL_AC_444_HITS.with(|c| c.get()), - CFL_AC_422_HITS.with(|c| c.get()), - CFL_AC_420_SQ_HITS.with(|c| c.get()), - CFL_AC_420_RECT_HITS.with(|c| c.get()), - ] -} - -/// Entries into [`cfl_ac_q3_at`] itself -- the one arm whose extent is -/// `bw / 2, bh / 2` and whose footprint is a 2x2 luma average. The gate -/// proves it is reached ONLY at 4:2:0. -pub fn cfl_ac_q3_at_hits() -> usize { - CFL_AC_Q3_AT_HITS.with(|c| c.get()) -} - -/// Current value of [`CFL_BLOCK_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn cfl_block_hits() -> usize { - CFL_BLOCK_HITS.with(|c| c.get()) -} - -/// Current value of [`UV_ANGLE_DELTA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn uv_angle_delta_hits() -> usize { - UV_ANGLE_DELTA_HITS.with(|c| c.get()) -} - -// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT` -// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the -// gate's proof this round's arms actually reached a real block, not just -// that `partition_w64` read one of those two symbol values. -thread_local! { - pub(super) static SB_RECT_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -// Current value of [`SB_RECT_HITS`]. -// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a -// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as -// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the -// non-SPLIT edge arm actually decoded (before this round the bit was read and -// thrown away, so that arm was unreachable). -thread_local! { - pub(super) static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; -} - -/// Current value of [`EDGE_PART_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn edge_part_hits() -> [usize; 4] { - EDGE_PART_HITS.with(|c| c.get()) -} - -/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_edge_part_hits() { - EDGE_PART_HITS.with(|c| c.set([0; 4])); -} - -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sb_rect_hits() -> usize { - SB_RECT_HITS.with(|c| c.get()) -} - -// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the -// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level -// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half -// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile -// paths (intra and inter) feed the same counter. -// -// lane-golomb r3: slots 4..7 are the same four facts one level up, at the -// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as -// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with -// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a -// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band, -// every SB of the last row), so the 32-level slots stay 0 on that content and -// only these prove the arm fired. -thread_local! { - pub(super) static EDGE32_HITS: std::cell::Cell<[usize; 8]> = - const { std::cell::Cell::new([0; 8]) }; -} - -/// Current value of [`EDGE32_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn edge32_hits() -> [usize; 8] { - EDGE32_HITS.with(|c| c.get()) -} - -// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/ -// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64 -// strip) fired. Real aomenc picks these at 64 even with -// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is -// the counter the gate hard-asserts. -thread_local! { - pub(super) static SB_AB_HITS: std::cell::Cell<[usize; 4]> = - const { std::cell::Cell::new([0; 4]) }; -} - -/// Current value of [`SB_AB_HITS`], summed over the four arms. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sb_ab_hits() -> usize { - SB_AB_HITS.with(|c| c.get().iter().sum()) -} - -/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, -/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a -/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as -/// proof of all four. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] { - SB_AB_HITS.with(std::cell::Cell::get) -} - -// lane-tx64x16: the two 1:4 superblock arms, counted per orientation -- -// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64 -// strips). Two counters, not one, because a gate that only proved "some 1:4 -// strip fired" would pass on a stream that never coded the other axis, and -// every scan/context table this round added comes in a transposed pair. -thread_local! { - pub(super) static SB_RECT4_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SB_RECT4_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sb_rect4_horz_hits() -> usize { - SB_RECT4_HORZ_HITS.with(|c| c.get()) -} - -/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sb_rect4_vert_hits() -> usize { - SB_RECT4_VERT_HITS.with(|c| c.get()) -} - -// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation -- -// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32 -// strips), the arms the ReelB mid-film extract stops at. -thread_local! { - pub(super) static RECT4_32_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_32_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-inter4 r1: the INTER-frame twins of the two counters above -- - /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` / - /// `PARTITION_VERT_4`. - pub(super) static RECT4_32_HORZ_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_32_VERT_INTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT` - /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64). - pub(super) static INTER_SB_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER_SB_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER_SB_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER_SB_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// How many 32x32-level 1:4 strips actually read coefficients (non-skip): -// a gate that only counted strips would pass on an all-skip stream, which -// exercises none of the new scan/context tables. -thread_local! { - pub(super) static RECT4_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the -// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT -// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in -// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS` -// counts the same for a 16x8/8x16 strip below 16x16. -thread_local! { - pub(super) static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static SUB16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect4_split_depth_hits() -> (usize, usize) { - ( - RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()), - RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()), - ) -} - -/// Current value of `SUB16_SPLIT_HITS`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sub16_split_hits() -> usize { - SUB16_SPLIT_HITS.with(|c| c.get()) -} - -// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose -// luma transform is SPLIT and which therefore leave through that fn's early -// return -- the arm that published no `TXFM_CONTEXT` band until this round. -thread_local! { - pub(super) static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect64_split_txfm_publish_hits() -> usize { - RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get()) -} - -/// Current value of `RECT4_COEFF_HITS`. -pub(crate) fn rect4_coeff_hits() -> usize { - RECT4_COEFF_HITS.with(|c| c.get()) -} - -// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN -// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, -// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is -// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate -// asserts the arms it proves separately so a run whose RD only picked one -// cannot pass as proof of the others. -thread_local! { - pub(super) static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; -} - -/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an -/// inter frame). -pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] { - SB_AB_INTER_HITS.with(std::cell::Cell::get) -} - -// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER -// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` -// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8 -// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip -// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every -// arm separately so a run whose RD only picked one cannot pass as proof of -// four. -thread_local! { - pub(super) static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; -} - -/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an -/// inter frame). -pub fn ab16_inter_hits_by_arm() -> [usize; 4] { - AB16_INTER_HITS.with(std::cell::Cell::get) -} - -// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4 -// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS` -// counts the odd strips that close a 4:2:0 chroma pair -// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row), -// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from -// the PREVIOUS strip's own mv/ref/filters -- libaom -// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached -// through `is_sub8x8_inter` (same file, :54). -thread_local! { - pub(super) static INTER16_HORZ4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER16_VERT4_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER16_CHROMA_PAIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static INTER16_SUB8_PIECE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// lane-arfchroma: chroma transform-unit publications whose block started -// MID-CELL -- the condition `record_mi_chroma`'s origin alignment exists for. -// A 4x4 chroma unit is `1 << ss` luma mi per axis, so a block whose mi origin -// is not step-aligned (a 16x4 / 4x16 1:4 strip at 4:2:0 has an ODD mi row or -// column) publishes a context cell whose origin is the step-aligned mi BELOW -// or RIGHT of its own. Counted per publication, `[row_misaligned, -// col_misaligned, both]`, so a gate can prove the witness really walks the -// realigned path instead of passing on a stream whose chroma units all happen -// to start on a cell boundary. -thread_local! { - pub(super) static CHROMA_MIDCELL_PUB_HITS: std::cell::Cell<[usize; 3]> = - const { std::cell::Cell::new([0; 3]) }; -} - -/// ChROMA publications that started mid-cell: `[row, col, both]`. See -/// [`CHROMA_MIDCELL_PUB_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn chroma_midcell_pub_hits() -> [usize; 3] { - CHROMA_MIDCELL_PUB_HITS.with(std::cell::Cell::get) -} - -/// Zeroes [`CHROMA_MIDCELL_PUB_HITS`] so a gate can measure its own decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn reset_chroma_midcell_pub_hits() { - CHROMA_MIDCELL_PUB_HITS.with(|c| c.set([0; 3])); -} - -// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition -- -// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the -// pair's single 8x4 (4x8) chroma unit for BOTH strips. -thread_local! { - pub(super) static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> = - const { std::cell::Cell::new([0; 3]) }; -} - -/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded -/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4). -pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) { - let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get); - (v[0], v[1], v[2]) -} - -/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16 -/// strips, chroma pairs closed, chroma pairs built from two different -/// strips' motion vectors)`. -pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) { - ( - INTER16_HORZ4_HITS.with(std::cell::Cell::get), - INTER16_VERT4_HITS.with(std::cell::Cell::get), - INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get), - INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get), - ) -} - -// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or -// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that -// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual. -thread_local! { - pub(super) static RECT4_16_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_16_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_16_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_16_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_16_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's - /// base mi differs from what the strip's own (odd) mi would have said -- - /// the shape that made 4 chroma samples of the ReelB `-ss 1200` - /// key frame miss by 1. Zero here means a gate never exercised the fix. - pub(super) static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s. - pub(super) static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip. - pub(super) static RECT4_16_INTRABC_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND - /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely. - pub(super) static SKIP_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-loss64: chroma transform units the frame-edge clip skipped - /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in - /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless - /// block overhanging the frame does NOT code. - pub(super) static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma - /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`, - /// decodeframe.c:1262) instead of leaking the previous occupant's. - pub(super) static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-llband: 4x4 chroma transform units a lossless HORZ/VERT strip - /// walked at subsampling 0/0 (one unit per mi cell -- the geometry the - /// hardcoded 4:2:0 span mis-stepped). - pub(super) static RECT_SPLIT_LOSSLESS_CHROMA444_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma - /// coefficients a lossless frame walked as per-4x4 inter units (the walk - /// that replaced the single rect unit). - pub(super) static INTRABC_RECT8_LOSSLESS_LUMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a - /// lossless 4:4:4 frame walked as per-4x4 [`TxbSet::Chroma4`] units. - pub(super) static INTRABC_RECT8_LOSSLESS_CHROMA_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1loss444kf: 4:4:4 lossless sub-8x8 RECT (8x4 / 4x8) leaf chroma - /// units whose libaom-faithful block-relative reach - /// ([`Reach::of_tu`] over the leaf's own bsize) differs from the - /// standalone-BLOCK_4X4 lookup that used to answer for them. Zero means - /// no stream reached a rect leaf where the two disagree -- a gate - /// asserting the reach fix must see this nonzero, or the fixture never - /// exercised the fixed path. - pub(super) static SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1offtile: 4x4 chroma units a lossless HORZ/VERT strip's plane- - /// major walk skipped because their top-left sample falls outside the - /// CHROMA plane. libaom bounds that walk per plane (`max_block_wide/high`, - /// av1_common_int.h:1565); this walk used to count the block's own - /// `chroma_w / 4` x `chroma_h / 4`. Zero means no stream decoded a - /// lossless strip overhanging the frame edge -- a gate asserting the - /// clip must see this nonzero. - pub(super) static RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape -/// that reconstructed as flat DC before lane-kf1200 r2). -pub fn skip_cfl_hits() -> usize { - SKIP_CFL_HITS.with(|c| c.get()) -} - -/// How many chroma transform units the frame-edge clip skipped in -/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a -/// stream whose lossless blocks never overhang the frame -- a gate asserting -/// the clip fired must see this nonzero. -pub fn chroma_edge_tu_clip_hits() -> usize { - CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get()) -} - -/// How many skipped lossless intrabc rect strips had their luma entropy -/// bands zeroed per unit (lane-av1-loss64). -pub fn skip_lossless_band_reset_hits() -> usize { - SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get()) -} - -/// How many 4x4 chroma transform units a lossless HORZ/VERT strip walked at -/// subsampling 0/0 (lane-av1-llband). Zero means a stream never decoded the -/// 4:4:4 lossless unit walk this counter proves -- a gate asserting the fix -/// must see this nonzero. -pub fn rect_split_lossless_chroma444_hits() -> usize { - RECT_SPLIT_LOSSLESS_CHROMA444_HITS.with(|c| c.get()) -} - -/// How many 4x4 chroma units a lossless HORZ/VERT strip's plane-major walk -/// skipped for falling outside the chroma plane (lane-av1offtile). Zero means -/// no stream decoded a lossless strip overhanging the frame edge -- a gate -/// asserting the clip must see this nonzero. -pub fn rect_split_lossless_chroma_offtile_hits() -> usize { - RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS.with(|c| c.get()) -} - -/// Reset [`rect_split_lossless_chroma_offtile_hits`] to zero (lane-av1offtile). -pub fn reset_rect_split_lossless_chroma_offtile_hits() { - RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS.with(|c| c.set(0)); -} - -/// How many unskipped intrabc 8x4/4x8 leaves a lossless frame walked luma as -/// per-4x4 inter units (lane-av1-ibc444rect). -pub fn intrabc_rect8_lossless_luma_hits() -> usize { - INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.get()) -} - -/// How many unskipped intrabc 8x4/4x8 leaves a lossless 4:4:4 frame walked -/// chroma as per-4x4 [`TxbSet::Chroma4`] units (lane-av1-ibc444rect). -pub fn intrabc_rect8_lossless_chroma_hits() -> usize { - INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.get()) -} - -/// How many 4:4:4 lossless sub-8x8 RECT leaf chroma units took the -/// block-relative reach libaom's `has_bottom_left` gives, where the -/// standalone-BLOCK_4X4 lookup that used to answer disagreed -/// (lane-av1loss444kf). Zero on a stream with no such leaf. -pub fn sub8_chroma444_lossless_tu_reach_hits() -> usize { - SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.get()) -} - -/// Gate-side reset for [`SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS`]. -pub fn reset_sub8_chroma444_tu_reach_hits() { - SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS.with(|c| c.set(0)); -} - -/// Gate-side reset for the two lane-av1-ibc444rect counters above. -pub fn reset_ibc444rect_hits() { - INTRABC_RECT8_LOSSLESS_LUMA_HITS.with(|c| c.set(0)); - INTRABC_RECT8_LOSSLESS_CHROMA_HITS.with(|c| c.set(0)); -} - -/// Gate-side reset for the two lane-av1-loss64 counters above. -pub fn reset_loss64_hits() { - CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0)); - SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0)); -} - -/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type` -/// from the pair's base mi than the strip's own mi would have given. -pub fn rect4_16_uv_pair_filt_hits() -> usize { - RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get()) -} - -/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane. -pub fn rect4_16_lossless_chroma_hits() -> usize { - RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get()) -} - -/// How many 16x4/4x16 strips reconstructed as intra block copy. -pub fn rect4_16_intrabc_hits() -> usize { - RECT4_16_INTRABC_HITS.with(|c| c.get()) -} - -/// Zero the lane-av1-rect14 pair counters so a gate measures one stream. -pub fn reset_rect4_16_pair_hits() { - RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0)); - RECT4_16_INTRABC_HITS.with(|c| c.set(0)); -} - -// lane-reelckf r1: the two chroma defects ReelC's key frames exposed -- -// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED` -// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and -// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose -// intra-edge filter type must come from the chroma-reference position). -thread_local! { - pub(super) static CHROMA_SKIP_CFL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf. -pub fn reelc_chroma_counters() -> (usize, usize) { - ( - CHROMA_SKIP_CFL_HITS.with(|c| c.get()), - RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()), - ) -} - -/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16 -/// strips, chroma-reference strips, strips with a coded residual, strips -/// whose luma transform is split)`. -pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) { - ( - RECT4_16_HORZ_HITS.with(|c| c.get()), - RECT4_16_VERT_HITS.with(|c| c.get()), - RECT4_16_CHROMA_HITS.with(|c| c.get()), - RECT4_16_COEFF_HITS.with(|c| c.get()), - RECT4_16_SPLIT_HITS.with(|c| c.get()), - ) -} - -/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded). -pub(crate) fn rect4_32_horz_hits() -> usize { - RECT4_32_HORZ_HITS.with(|c| c.get()) -} - -/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded). -pub(crate) fn rect4_32_vert_hits() -> usize { - RECT4_32_VERT_HITS.with(|c| c.get()) -} - -/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded). -pub(crate) fn rect4_32_horz_inter_hits() -> usize { - RECT4_32_HORZ_INTER_HITS.with(|c| c.get()) -} - -/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded). -pub(crate) fn rect4_32_vert_inter_hits() -> usize { - RECT4_32_VERT_INTER_HITS.with(|c| c.get()) -} - -/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded). -pub(crate) fn inter_sb_horz_hits() -> usize { - INTER_SB_HORZ_HITS.with(|c| c.get()) -} - -/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded). -pub(crate) fn inter_sb_vert_hits() -> usize { - INTER_SB_VERT_HITS.with(|c| c.get()) -} - -/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded). -pub(crate) fn inter_sb_horz4_hits() -> usize { - INTER_SB_HORZ4_HITS.with(|c| c.get()) -} - -/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded). -pub(crate) fn inter_sb_vert4_hits() -> usize { - INTER_SB_VERT4_HITS.with(|c| c.get()) -} - -// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane -// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the -// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not -// just inert-compiled. Zero forever on a passing gate means that gate's -// stream never carries `delta_q_present=1` through a rect64 block. -thread_local! { - pub(super) static RECT64_QIDX_DRIFT_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT64_QIDX_DRIFT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect64_qidx_drift_hits() -> usize { - RECT64_QIDX_DRIFT_HITS.with(|c| c.get()) -} - -// lane-partab r1: how many 32x32 quadrants decoded an AB partition -// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one -// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the -// free-partition gate's proof this round's arms actually fired. -thread_local! { - pub(super) static PARTAB_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`PARTAB_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn partab_hits() -> usize { - PARTAB_HITS.with(|c| c.get()) -} - -// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm, -// one counter per arm rather than one shared total -- the gate hard-asserts -// each of these individually nonzero so a recipe that only ever fires -// HORZ_A can't silently stand in for the whole set. -thread_local! { - pub(super) static INTRA_HORZ_A_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - pub(super) static INTRA_HORZ_B_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - pub(super) static INTRA_VERT_A_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; - pub(super) static INTRA_VERT_B_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`INTRA_HORZ_A_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_horz_a_hits() -> usize { - INTRA_HORZ_A_HITS.with(|c| c.get()) -} - -/// Current value of [`INTRA_HORZ_B_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_horz_b_hits() -> usize { - INTRA_HORZ_B_HITS.with(|c| c.get()) -} - -/// Current value of [`INTRA_VERT_A_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_vert_a_hits() -> usize { - INTRA_VERT_A_HITS.with(|c| c.get()) -} - -/// Current value of [`INTRA_VERT_B_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_vert_b_hits() -> usize { - INTRA_VERT_B_HITS.with(|c| c.get()) -} - -// How many [`read_inter_compound_mode`] reads actually happened -// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own -// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound -// mvstack build), not just that `comp_mode` fired. Still refused right -// after (no MV assignment or MC wired), so this only counts attempted -// reads. -thread_local! { - pub(super) static COMPOUND_MODE_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`COMPOUND_MODE_HITS`]. -#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds -pub(crate) fn compound_mode_hits() -> usize { - COMPOUND_MODE_HITS.with(|c| c.get()) -} - -/// How many query blocks folded in at least one temporal MV candidate -/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the -/// temporal-MV gate's own firing counter (lane-av1tmvp). -/// -/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream -/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in -/// this file (`decode_inter_block`) still passes `tpl: None` -- this -/// counter compiles and the projection math it counts is unit-tested -/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`] -/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls -/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0` -/// against any real stream today. See the module doc on -/// `crate::motion_field` and this crate's ledger for the remaining wiring. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tmv_hits() -> usize { - crate::mvstack::tmv_hits() -} - -/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions -/// produced on this thread, the 10-bit inter gate's firing proof. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter_pred_hits() -> usize { - crate::mc::inter_pred_hits() -} - -/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`; -/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn ref_hits(ref_frame: i8) -> usize { - let c = match ref_frame { - LAST2_FRAME => &LAST2_HITS, - LAST3_FRAME => &LAST3_HITS, - GOLDEN_FRAME => &GOLDEN_HITS, - BWDREF_FRAME => &BWDREF_HITS, - ALTREF2_FRAME => &ALTREF2_HITS, - ALTREF_FRAME => &ALTREF_HITS, - other => panic!("ref_hits: no per-reference counter for ref_frame {other}"), - }; - c.with(|v| v.get()) -} - -/// Current value of [`ANGLE_DELTA_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn angle_delta_hits() -> usize { - ANGLE_DELTA_HITS.with(|c| c.get()) -} - -/// Current value of [`TX_CLASS1_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tx_class1_hits() -> usize { - TX_CLASS1_HITS.with(|c| c.get()) -} - -// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent -// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion -// bottom) this thread's decode actually reconstructed -- the same -// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream -// genuinely exercised the sub-8x8 leaf path rather than every attempt -// coincidentally landing on `PARTITION_NONE`. -thread_local! { - pub(super) static SUB8_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter - /// sub-blocks (lane-intersub8). - pub(super) static SUB8_INTER_SPLIT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8 - /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4), - /// `[1] = VERT` (two BLOCK_4X8). - pub(super) static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; - /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8 - /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were - /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]` - /// MIXED groups whose chroma reference is INTER while its sibling is - /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4` - /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 -- - /// the second lifted refusal's own witness; `[0]`/`[1]` count those too, - /// so only this cell separates the split arm from the HORZ/VERT one). - pub(super) static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) }; -} - -/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference, -/// mixed groups, split 4x4 leaves)`. -pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) { - SUB8_INTRA_RECT_HITS.with(|c| { - let h = c.get(); - (h[0], h[1], h[2], h[3], h[4]) - }) -} - -/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`. -pub fn sub8_inter_rect_hits() -> (usize, usize) { - SUB8_INTER_RECT_HITS.with(|c| { - let h = c.get(); - (h[0], h[1]) - }) -} - -// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all -// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38` -// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how -// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all. -// (b) was 0 for every stream before this round -- the leaf path never touched -// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got -// filtered where libaom skips it. A gate asserts both are non-zero. -thread_local! { - pub(super) static INTER8_SKIP_BAND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8, - // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip - // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip -- - // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an - // 8-tall strip pair where only one half is skip must still be FILTERED. - pub(super) static RECT_SKIP_BAND_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of `RECT_SKIP_BAND_HITS`. -pub fn rect_skip_band_hits() -> usize { - RECT_SKIP_BAND_HITS.with(|c| c.get()) -} - -/// Current value of `INTER8_SKIP_BAND_HITS`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn inter8_skip_band_hits() -> usize { - INTER8_SKIP_BAND_HITS.with(|c| c.get()) -} - -/// Current value of [`SUB8_SPLIT_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sub8_split_hits() -> usize { - SUB8_SPLIT_HITS.with(|c| c.get()) -} - -/// Current value of [`SUB8_INTER_SPLIT_HITS`]. -pub fn sub8_inter_split_hits() -> usize { - SUB8_INTER_SPLIT_HITS.with(|c| c.get()) -} - -// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a -// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that -// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`, -// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the -// first sub-block's type is never the one). Reading it off sub-block 0 -// inverted one 4x4 chroma unit on the wrong basis with the entropy stream -// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only -// see this rule through this counter. -thread_local! { - pub(super) static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`. -pub fn sub8_chroma_tx_from_ref_hits() -> usize { - SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get()) -} - -// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ` -// of an 8x8 block) this thread's decode reconstructed with REAL coefficients -// -- a skipped leaf exercises the prediction and the mi bookkeeping but never -// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate -// asserts on these two rather than a plain leaf count. -thread_local! { - pub(super) static TX4X8_CODED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(super) static TX8X4_CODED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's - /// two 4x4 transform units, predicted one after the other. A separate - /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so - /// the gate can prove THIS path fired. - pub(super) static RECT8_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// 16x8/8x16 intra strips whose prediction actually read past the block's - /// own width (above-right) or height (below-left) -- the samples - /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/ - /// `has_bl_*` table row can corrupt (lane-tx4x8 r3). - pub(super) static RECT_STRIP_REACH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Every 16x8/8x16 intra strip predicted, reaching or not -- the - /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of. - pub(super) static RECT_STRIP_PRED_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Current value of [`RECT8_SPLIT_TX_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect8_split_tx_hits() -> usize { - RECT8_SPLIT_TX_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT_STRIP_PRED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_strip_pred_hits() -> usize { - RECT_STRIP_PRED_HITS.with(|c| c.get()) -} - -/// Current value of [`RECT_STRIP_REACH_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn rect_strip_reach_hits() -> usize { - RECT_STRIP_REACH_HITS.with(|c| c.get()) -} - -/// Current value of [`TX4X8_CODED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tx4x8_coded_hits() -> usize { - TX4X8_CODED_HITS.with(|c| c.get()) -} - -/// Current value of [`TX8X4_CODED_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tx8x4_coded_hits() -> usize { - TX8X4_CODED_HITS.with(|c| c.get()) -} - -// How many CHROMA coefficient blocks read their `eob_pt` from the class-1 -// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread. -// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma -// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on -// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired -// (`eob_pt_{16,64,128,256}_chroma_class1`). -thread_local! { - pub(super) static CHROMA_EOB_CLASS1_HITS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`CHROMA_EOB_CLASS1_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_eob_class1_hits() -> usize { - CHROMA_EOB_CLASS1_HITS.with(|c| c.get()) -} - -/// Enabled by `EC_AV1_PLANE_SENTINEL` (there is no separate flag for it): print -/// an EXACT census of the samples the tile walk never wrote -- with it, every -/// plane still holding [`plane_poison`] at this point is a sample no block -/// reconstructed, and no legal sample can equal the poison (reconstruction -/// clamps to `(1 << bit_depth) - 1`, at most 4095). -/// -/// Coverage, stated as the code has it: this census runs at TWO of the four -/// places [`apply_deblock`] is entered from -- the key-frame path and the -/// non-pipelined inter path, both immediately before that frame's deblock. The -/// two it does NOT cover are the encoder's filter search ([`replay_filters`], -/// which runs the filters over a CAPTURED copy, not a live decode) and the -/// pipelined inter branch, where deblock has already run band by band inside -/// `par` by the time this tail is reached. A zero count therefore means "no hole -/// on the paths that reach this call", not "no hole on any path". It is EXACT -/// over the extent it scans -- the scan itself reads every sample of that -/// extent, unlike the older [`dump_stage`] pair, which truncates to `as u8`. -/// -/// This is the shipped form of the four-line temporary scan the -/// `lane/av1422seed` census used: it replaces a wrong-sample diff (which says -/// where the OUTPUT is wrong, not whether the block was written at all) with a -/// direct count plus the coordinates of every hole, grouped into per-row -/// spans so a large hole stays readable. -/// -/// It scans TWO regions per plane, because they answer different questions and -/// the earlier revision only scanned one of them: -/// * the TRUE EXTENT -- each plane over its own `true_width` x `true_height`, -/// PER AXIS (`true_width.min(p.width)`), so a 4:2:2 frame's chroma is scanned -/// at its own `fw/2 x fh` shape rather than the 4:2:0 `div_ceil(2)` crop the -/// older [`dump_stage16`] used. A hole here can reach the caller, and it is -/// the region lane/av1unwritten's 224 samples sat in. -/// * the PADDED TAIL -- everything outside that extent, out to the block-aligned -/// coding surface -- counted separately into [`PAD_UNWRITTEN_SAMPLES`]. The -/// earlier revision's doc comment asserted "past that is the padded coding -/// surface's invented tail, which no decoder ever reads". That assertion is -/// exactly what a tail that is never written and never read looks like, so it -/// was self-certifying; the tail is now scanned and counted like any other -/// region. `EC_AV1_PLANE_ALLOC=padzero`/`extzero` attribute a read to one -/// side or the other (see [`fresh_plane`]). -pub(super) fn census_unwritten(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) { - if !plane_sentinel_on() { - return; - } - let poison = plane_poison(); - let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst); - for (name, p) in [("Y", y), ("U", u), ("V", v)] { - let (w, h) = (p.true_width.min(p.width), p.true_height.min(p.height)); - let mut total = 0usize; - let mut spans: Vec<(usize, usize, usize)> = Vec::new(); - for row in 0..h { - let mut run: Option<(usize, usize)> = None; - for col in 0..w { - if p.data[row * p.width + col] == poison { - total += 1; - run = Some(match run { - None => (col, col), - Some((a, _)) => (a, col), - }); - } - if run.is_some() && (col + 1 == w || p.data[row * p.width + col + 1] != poison) { - let (a, b) = run.take().expect("a run is open here"); - spans.push((row, a, b)); - } - } - } - // The padded tail: columns `w..width` on rows `0..h`, plus every column - // on rows `h..height`. - let mut pad_total = 0usize; - let mut pad_scanned = 0usize; - for row in 0..p.height { - let (from, to) = if row < h { (w, p.width) } else { (0, p.width) }; - if from >= to { - continue; - } - pad_scanned += to - from; - pad_total += p.data[row * p.width + from..row * p.width + to] - .iter() - .filter(|&&s| s == poison) - .count(); - } - UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); - CENSUS_SCANNED.fetch_add(w * h, std::sync::atomic::Ordering::SeqCst); - PAD_UNWRITTEN_SAMPLES.fetch_add(pad_total, std::sync::atomic::Ordering::SeqCst); - PAD_CENSUS_SCANNED.fetch_add(pad_scanned, std::sync::atomic::Ordering::SeqCst); - eprintln!( - "SENTINEL_CENSUS idx={idx} plane={name} surface={}x{} extent={w}x{h} \ - pad_scanned={pad_scanned} unwritten={total} pad_unwritten={pad_total}", - p.width, p.height, - ); - if total == 0 { - continue; - } - let body: Vec = spans - .iter() - .map(|&(r, a, b)| format!("y{r} x{a}..={b}")) - .collect(); - eprintln!( - "SENTINEL_CENSUS idx={idx} plane={name} surface={}x{} extent={w}x{h} \ - unwritten={total} spans={}: {}", - p.width, - p.height, - spans.len(), - body.join(" ") - ); - } -} - -/// Samples [`census_unwritten`] has looked at since the last -/// [`take_census_scanned`]. A gate that only asserts -/// [`take_unwritten_samples`] == 0 passes on a decode that never scanned -/// anything, so it reads THIS too: a census that scanned nothing has proved -/// nothing. -pub(super) static CENSUS_SCANNED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// Reads and clears [`CENSUS_SCANNED`]; see [`take_unwritten_samples`] for the -/// pairing. -pub fn take_census_scanned() -> usize { - CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// Samples [`census_unwritten`] scanned in the padded tail, paired with -/// [`PAD_UNWRITTEN_SAMPLES`] for the same reason as [`CENSUS_SCANNED`]. -pub(super) static PAD_CENSUS_SCANNED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// Reads and clears [`PAD_CENSUS_SCANNED`]. -pub fn take_pad_census_scanned() -> usize { - PAD_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// Samples [`census_unwritten_final`] has looked at since the last -/// [`take_final_census_scanned`]. A gate that only asserts -/// [`take_final_unwritten_samples`] == 0 passes on a build whose census call was -/// deleted, so it reads THIS too -- the same pairing -/// [`CENSUS_SCANNED`] documents for the pre-deblock census. -pub(super) static FINAL_CENSUS_SCANNED: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// Reads and clears [`FINAL_CENSUS_SCANNED`]; the pairing is the reason it -/// exists, exactly as for [`take_census_scanned`]. -pub fn take_final_census_scanned() -> usize { - FINAL_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// lane-unwritten-dep: the census at the pipeline's last point. Counts, over each -/// plane, how many samples still hold [`PLANE_SENTINEL`] once every filter has -/// run, and records how many samples it LOOKED at in [`FINAL_CENSUS_SCANNED`]. -/// -/// SCOPE, which lane-av1graincensus did not change but had to be true about: -/// this runs BEFORE `apply_grain`, over the PRE-grain planes. It does NOT and -/// never did measure the grained picture the caller receives -- that is -/// [`census_unwritten_grained`], a separate counter over a separate buffer. -/// -/// Gated on [`plane_sentinel_on`] -- the SAME predicate as [`fresh_plane`] and as -/// the pre-deblock [`census_unwritten`]: the env flag OR the thread-local -/// [`set_plane_sentinel`] override. An earlier revision gated this on the raw env -/// var alone, which made the census silently inert for any in-process test using -/// the thread-local switch that the rest of the crate honours. The fill and both -/// censuses must agree on when they are live, or a "0" means nothing. -pub(crate) fn census_unwritten_final(y: &[u16], u: &[u16], v: &[u16]) { - let Some((scanned, total)) = census_sentinels(y, u, v) else { - return; - }; - FINAL_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst); - FINAL_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); -} - -/// The `(scanned, unwritten)` pair both output-point censuses accumulate, or -/// `None` when the sentinel fill is not live. -/// -/// Shared so the two censuses cannot drift into disagreeing about what counts -/// as unwritten -- the failure this crate's other paired counters exist to -/// prevent. `None` (rather than `(0, 0)`) is what keeps a caller from -/// publishing a meaningless zero when the fill was off. -fn census_sentinels(y: &[u16], u: &[u16], v: &[u16]) -> Option<(usize, usize)> { - if !plane_sentinel_on() { - return None; - } - // Both callers pass planes cropped to the true extent (no padding past it - // reaches either point), so a flat count over each plane IS the - // true-extent count. - let (scanned, total): (usize, usize) = [y, u, v] - .iter() - .map(|p| (p.len(), p.iter().filter(|&&s| s == plane_poison()).count())) - .fold((0, 0), |(a, b), (c, d)| (a + c, b + d)); - Some((scanned, total)) -} - -/// The scanned half of the pairing for [`GRAINED_UNWRITTEN_SAMPLES`]. A gate -/// asserting only `== 0` passes on a build whose census call was deleted. -pub(super) static GRAINED_CENSUS_SCANNED: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// Reads and clears [`GRAINED_CENSUS_SCANNED`]; the pairing is the reason it -/// exists, exactly as for [`take_final_census_scanned`]. -pub fn take_grained_census_scanned() -> usize { - GRAINED_CENSUS_SCANNED.swap(0, std::sync::atomic::Ordering::SeqCst) -} - -/// lane-av1graincensus: the SECOND output-point census -- the one -/// [`census_unwritten_final`] structurally cannot be. -/// -/// # WHY IT EXISTS -/// -/// `census_unwritten_final` runs at `stream.rs`'s `EC_AV1_FINAL_DUMP` site, which -/// is BEFORE `apply_grain`. Every filter (deblock/CDEF/LR/superres) writes in -/// place into the same buffer that census scanned, so those stages cannot open a -/// hole outside its extent. `apply_grain` is the ONE stage after it that -/// allocates a fresh picture -- `uninit_plane`, `Vec::with_capacity` + -/// `set_len`, no fill -- and whose soundness rests on a band row partition -/// rather than on the type system. Its destination therefore reaches the caller -/// having never been looked at by any census, and `lanes/unwritten-dep.report.md` -/// §6/§8 explicitly declines to claim otherwise. -/// -/// # WHAT IT IS WORTH ONLY IF THE FILL IS LIVE -/// -/// Counting `== plane_poison()` over an uninitialised buffer is a census that -/// can only ever report ~0: garbage is arbitrary, so a hole survives with -/// probability ~1/65536 rather than always. `uninit_plane` therefore fills with -/// the poison when [`plane_sentinel_on`] -- under the SAME predicate -/// [`fresh_plane`] honours -- so "the band copy wrote every sample" becomes a -/// measurement instead of an assumption. With the sentinel off (every shipped -/// build) nothing here runs and `uninit_plane` keeps its corner-cut. -pub(crate) fn census_unwritten_grained(y: &[u16], u: &[u16], v: &[u16]) { - let Some((scanned, total)) = census_sentinels(y, u, v) else { - return; - }; - GRAINED_CENSUS_SCANNED.fetch_add(scanned, std::sync::atomic::Ordering::SeqCst); - GRAINED_UNWRITTEN_SAMPLES.fetch_add(total, std::sync::atomic::Ordering::SeqCst); -} - -thread_local! { - /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128 - /// root's HORZ arm, and 64x128 ones at its VERT arm. - pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units, - /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read. - pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; - /// lane-inter128intra r1: the same shapes decoded on the INTER block path - /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an - /// inter frame) -- (128x64, 64x128). - pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) }; - /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still - /// handed back var-tx leaves, so the per-transform-unit luma publication - /// loop never ran and the block has to clear its own luma coefficient - /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under - /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate - /// non-vacuous. - pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded - /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the - /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this - /// shape non-vacuous -- a stream that never codes one reads 0. - pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1-128rectspan: chroma transform units of a 128-root HORZ/VERT - /// intra block re-stamped by the end-of-block replay - /// (`record_split_luma_rect` clobbers the per-unit contexts the chroma - /// walk published, so every unit replays its own state after it). A - /// non-skip 128x64/64x128 block codes `nch_x * cn * 2 + nch_y * cn_h * 2` - /// of them, so this reads 0 on any stream that never codes one -- the - /// non-vacuity anchor for the replay's own gate. - pub(crate) static SB128RECT_CHROMA_REPLAY_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// ... and the number of non-skip 128-root rect BLOCKS whose two LUMA-MI - /// spans differ (`luma_span = chroma_tx << ss_x` vs - /// `luma_span_h = chroma_tx << ss_y`). lane-av1422lift: the doc here used - /// to read "Zero on every stream this decoder admits ... 4:2:2 ... is - /// refused by name at the sequence header", and that was TRUE. Admitting - /// 4:2:2 genuinely made this counter able to fire, and it does fire: - /// measured, `422_intrabc_sb128_strip.obu` and - /// `422_intrabc_sb128_strip_notxsearch.obu` each read - /// `replay = 72, mismatch = 9`; the other 19 committed 4:2:2 cells read 0. - /// - /// lane-av1422mismatch9: the predicate is the span DIFFERENCE, which at - /// ss (1, 0) is true BY CONSTRUCTION for every 128-root rect block -- so - /// this is a shape test ("a 4:2:2-shaped block replayed"), NOT a - /// divergence test, and it does not witness the lane-av1-128rectspan - /// defect it was named for (that defect passed `luma_span` to both axes; - /// the source-scan arm in - /// `the_422_block_128rect_chroma_chunk_gather_stays_per_axis` is what - /// pins the per-axis spelling). It is not a pixel-miss signature either: - /// the replay re-stamps with the same per-axis pair the in-loop walk - /// stamped with, and `record_mi_chroma` writes only the `left`/`above` - /// context arrays -- zero pixel samples. Both pins are byte-exact against - /// ffmpeg (`the_pinned_422_intrabc_sb128_strip_witnesses_decode_pixel_ - /// exact`, all five frames, every plane). - /// - /// **Nothing asserts zero here, and nothing should**: a zero assert would - /// red on a provably correct cell. The measured NINE is asserted instead, - /// in `the_422_block_128rect_chroma_chunk_gather_stays_per_axis` (with - /// this reasoning in its message), so a change in the count is a red gate - /// rather than a silent drift. - /// - /// The pair's other reader is `sb128rect_chroma_replay_hits` on a 4:4:4 - /// stream, where the unit's luma width and height are equal so the - /// mismatch half is structurally zero -- a zero that is a statement about - /// that stream, not about the format. - pub(crate) static SB128RECT_REPLAY_SPAN_MISMATCH_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta. -pub fn skip_vartx_luma_reset_hits() -> usize { - SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get) -} - -/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta. -pub(crate) fn intra128_lossless_hits() -> usize { - INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get) -} - -/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta. -pub(crate) fn intra128_in_inter_hits() -> [usize; 2] { - INTRA128_IN_INTER_HITS.with(std::cell::Cell::get) -} - -/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] / -/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta. -pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) { - ( - INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get), - INTRA_SB128_VERT_HITS.with(std::cell::Cell::get), - INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get), - ) -} - -/// [`SB128RECT_CHROMA_REPLAY_HITS`] (chroma units re-stamped by -/// `decode_block_128rect`'s end-of-block replay) and -/// [`SB128RECT_REPLAY_SPAN_MISMATCH_HITS`] (replays whose stamped height was -/// not the unit's own), for a gate's own before/after delta. -pub(crate) fn sb128rect_chroma_replay_hits() -> (usize, usize) { - ( - SB128RECT_CHROMA_REPLAY_HITS.with(std::cell::Cell::get), - SB128RECT_REPLAY_SPAN_MISMATCH_HITS.with(std::cell::Cell::get), - ) -} - -/// Records one block's shape. The table is ordered by measured frequency over -/// the three witnesses the census gate decodes, so the common square shapes -/// leave the scan on their first comparison. -pub(super) fn census_inter_block_shape(side: usize, w: usize, h: usize) { - let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) { - Some(i) => 1u32 << i, - None => INTER_BLOCK_SHAPE_UNLISTED, - }; - let seen = inter_block_shape_mask(); - if seen & bit == 0 { - INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit)); - } -} - -/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of -/// [`apply_cdef`]'s early returns. -pub(super) fn cdef_scan_counters(skip_grid: &Neighbours) { - let _ = skip_grid; - hit_do! { - let mut r = 0usize; - while r < skip_grid.mi_rows { - let mut c = 0usize; - while c < skip_grid.mi_cols { - if (0..2).any(|rr| { - (0..2).any(|cc| { - !skip_grid - .blk_grid - .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc)) - .is_none_or(|x| x.written) - }) - }) { - hit!(CDEF_UNWRITTEN_SKIP_UNITS); - if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") { - eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4); - } - } - let cell = |rr: usize, cc: usize| { - skip_grid - .blk_grid - .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc)) - .is_some_and(|x| x.skip) - }; - let first = cell(0, 0); - if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) { - hit!(CDEF_MIXED_SKIP_UNITS); - } - c += 2; - } - r += 2; - } - } -} - -// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and -// the inter tile loop. Its loop-restoration units are read once for the whole -// 128x128 (spec 5.11.57 is called with the superblock's own size), then one -// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4) -// decides the root -- only SPLIT recurses into the four 64x64 quadrants this -// decoder codes, the other seven arms refuse by name. -thread_local! { - /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one - /// whole 128x128 block (lane-sb128b r1's gate counter). - pub(crate) static PART128_NONE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one - /// when the bottom half is out of frame) -- lane-sb128c r7. - pub(crate) static PART128_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces). - pub(crate) static PART128_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// Of those, the ones decided by the GATHERED bit at a frame edge -- the - /// only shape a 1080p (mi_rows = 270) stream reaches. - pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes, - /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. - pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; -} - -/// [`PART128_AB_HITS`], for a gate's own before/after delta. -pub(crate) fn part128_ab_hits() -> [usize; 4] { - PART128_AB_HITS.with(std::cell::Cell::get) -} - -/// [`PART128_NONE_HITS`], for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn part128_none_hits() -> usize { - PART128_NONE_HITS.with(std::cell::Cell::get) -} - -/// [`PART128_HORZ_HITS`], for a gate's own before/after delta. -#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live -pub(crate) fn part128_horz_hits() -> usize { - PART128_HORZ_HITS.with(std::cell::Cell::get) -} - -/// [`PART128_VERT_HITS`], for a gate's own before/after delta. -#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live -pub(crate) fn part128_vert_hits() -> usize { - PART128_VERT_HITS.with(std::cell::Cell::get) -} - -/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge. -pub(crate) fn part128_edge_horz_hits() -> usize { - PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get) -} - -/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge. -pub(crate) fn part128_edge_vert_hits() -> usize { - PART128_EDGE_VERT_HITS.with(std::cell::Cell::get) -} - -thread_local! { - /// How many CHROMA transform units were coded inside a block whose uv - /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128 - /// block, four per plane). - pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// lane-av1h5: how many blocks had their leaf walk actually PERMUTED into - /// libaom's chunk-major order by [`mu_chunk_order`] -- a block above 64 - /// whose sort was not a no-op. Deliberately not "took the order": a - /// no-op ordering change must read 0 so a gate cannot look armed. - pub(crate) static MU_CHUNK_ORDER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// lane-av1txctxband2: SQUARE lossless blocks on an INTER frame whose - /// `set_txfm_ctxs` publish CHANGED at least one above-band cell it covers - /// (the cell did not already hold the published size), so a later - /// `get_tx_size_context` / `txfm_partition_context` reader in the same - /// tile column reads a value this publish produced. Zero on an intra-only - /// frame (where `fill_lf_grid_rect_inner` publishes the same 4x4 value at - /// the same footprint). - /// - /// CORRECTED 2026-09-30 (refutation pass `lanes/refute-av1txctxband2`): - /// this doc previously claimed the hit meant "overwrote a size some - /// earlier block left" and that a wholly-lossless all-non-skip stream - /// leaves it at zero. MEASURED FALSE -- `420_lossless_tallinter_8x16.obu` - /// fires **48**, all of them first touches of a column still at - /// `TXFM_CTX_INIT`; `420_lossless_arf_1to4_320x240_5f.obu` fires 320, 53 of - /// them first touches. Of the pin's 944, **183 are first-touch**. The - /// predicate tests "the cell did not already hold this value", which is - /// the decision that matters (no reader, no intra-only frame, no unchanged - /// column still reads 0), but it is NOT the strictly narrower causal claim - /// the old text made. - pub(crate) static LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`MU_CHUNK_ORDER_HITS`], for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn mu_chunk_order_hits() -> usize { - MU_CHUNK_ORDER_HITS.with(std::cell::Cell::get) -} - -/// [`LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS`] -- square lossless inter blocks -/// whose `set_txfm_ctxs` publish overwrote a size an earlier block of the -/// same frame had left in the above band, for a gate's own before/after -/// delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lossless_sq_txfm_band_overwrite_hits() -> usize { - LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS.with(std::cell::Cell::get) -} - -/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_split_tx_hits() -> usize { - CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get) -} - -thread_local! { - /// How many INTRA leaves of an inter frame's 8x8 block ran the lossless - /// 4:4:4 chroma walk ([`read_intra_chroma_lossless`], lane-av1-llintra8) - /// -- one bump per leaf, four units per plane inside it. A gate proving - /// the arm must see this nonzero; CHROMA_SPLIT_TX_HITS alone cannot - /// attribute its bumps to THIS leaf. - pub(crate) static LLINTRA8_CHROMA_WALK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`LLINTRA8_CHROMA_WALK_HITS`]: lossless 4:4:4 chroma walks through an -/// inter frame's 8x8 INTRA leaf. -pub fn llintra8_chroma_walk_hits() -> usize { - LLINTRA8_CHROMA_WALK_HITS.with(|c| c.get()) -} - -thread_local! { - /// lane-av1sub8rect444: how many of `decode_intra_sub8_leaf`'s 8x4/4x8 - /// INTRA leaves ran the lossless 4:4:4 per-unit chroma walk (two TX_4X4 - /// units per plane, plane-major) instead of one TX_8X4/TX_4X8 rect unit - /// -- the shape whose unit count AND skip ctx the rect read got wrong. - /// A gate proving the arm fired; CHROMA_SPLIT_TX_HITS cannot attribute - /// its bumps to THIS leaf. - pub(crate) static LLSUB8RECT444_CHROMA_WALK_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`LLSUB8RECT444_CHROMA_WALK_HITS`]: lossless 4:4:4 chroma walks through a -/// sub-8 8x4/4x8 INTRA leaf. -pub fn llsub8rect444_chroma_walk_hits() -> usize { - LLSUB8RECT444_CHROMA_WALK_HITS.with(|c| c.get()) -} - -thread_local! { - /// lane-av1444chr: how many chroma units resolved their `tx_type` from the - /// luma leaf covering their OWN quadrant instead of the block-level - /// (`first_tx_type`) one -- the route this lane corrected. - /// `CHROMA_SPLIT_TX_HITS` cannot attribute its bumps to it: every split - /// chroma unit bumps that one. - pub(crate) static CHROMA_QUAD_LEAF_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// Of those, how many resolved a type that DIFFERS from the block-level one - /// -- the exact condition lane-av1444chr measured wrong: over a luma leaf - /// that coded nothing the map cell is `DCT_DCT` while the top-left leaf's - /// is `IDTX`. A gate proving the corrected route fired is NOT enough on - /// its own (a block whose four leaves agree changes zero pixels); this is - /// the number that says the route changed an answer. - pub(crate) static CHROMA_QUAD_LEAF_TX_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// lane-av1f9singleland: the SINGLE-REFERENCE copy of - /// [`CHROMA_QUAD_LEAF_TX_HITS`], and the half of its - /// [`CHROMA_QUAD_LEAF_TX_DIFF_HITS`] that belongs to that arm. - /// - /// Why a separate pair rather than trusting the shared counters: the - /// shared ones are bumped from BOTH arms of the four-unit 4:4:4 chroma - /// arm, so a green witness on them says nothing about which arm produced - /// the hits. `decode_inter_block` has two textually parallel copies of - /// that arm -- the compound prediction arm (the `build` closure) and the - /// single-reference arm -- and a refactor can delete or revert either one - /// while the other keeps the shared total non-zero. Measured on the pinned - /// witness `fixtures/444_quad_leaf_tx_type.obu`: 96 units resolve through - /// the covering leaf, and 88 of them are the single-reference arm's, so - /// the shared counter is 92% single-reference and the compound arm alone - /// would be a 4-unit sample of the route it appears to witness. - pub(crate) static CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// Of [`CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS`], how many resolved a type - /// that DIFFERS from the block-level one. This is the arm's own non-vacuity - /// bar: a route count alone stays green through a no-op resolve, because - /// on a block whose four luma leaves all agree the per-quadrant value and - /// the block-level one are the same answer. Mutating only the - /// single-reference arm's `Some(cu_tx_type)` back to `Some(luma_tx_type)` - /// turns the witness red with 777 bytes differing in decode-order frame 1. - pub(crate) static CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS`]: single-reference-arm chroma units -/// that took their type from the covering luma leaf. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_quad_leaf_tx_singleref_hits() -> usize { - CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS.with(std::cell::Cell::get) -} - -/// [`CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS`]: of those, the units whose -/// covering leaf's type differs from the block-level one. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_quad_leaf_tx_singleref_diff_hits() -> usize { - CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS.with(std::cell::Cell::get) -} - -/// [`CHROMA_QUAD_LEAF_TX_HITS`]: chroma units that took their type from the -/// covering luma leaf. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_quad_leaf_tx_hits() -> usize { - CHROMA_QUAD_LEAF_TX_HITS.with(std::cell::Cell::get) -} - -/// [`CHROMA_QUAD_LEAF_TX_DIFF_HITS`]: chroma units whose covering leaf's type -/// differs from the block-level one. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_quad_leaf_tx_diff_hits() -> usize { - CHROMA_QUAD_LEAF_TX_DIFF_HITS.with(std::cell::Cell::get) -} - -thread_local! { - /// lane-av1chrtx: chroma units of a RECT inter block - /// ([`read_inter_rect_chroma`], the sibling of the 4:4:4 four-unit arms) - /// that resolved their `tx_type` from the luma leaf covering their OWN - /// quadrant instead of the block-level one. A SEPARATE counter from - /// [`CHROMA_QUAD_LEAF_TX_HITS`] on purpose: that one gates a 4:2:0 control - /// that must stay at exactly 0, and this route IS reachable at 4:2:0, so - /// sharing the counter would destroy that control's meaning. - pub(crate) static CHROMA_RECT_LEAF_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -thread_local! { - /// Of those, how many resolved a type that DIFFERS from the block-level - /// one -- the condition that changes pixels. A route counter alone fires - /// on every multi-unit rect chroma read, including the blocks whose - /// leaves all agree (the exact shape a no-op fix looks green on). - pub(crate) static CHROMA_RECT_LEAF_TX_DIFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`CHROMA_RECT_LEAF_TX_HITS`]: rect chroma units that took their type from -/// the covering luma leaf. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_rect_leaf_tx_hits() -> usize { - CHROMA_RECT_LEAF_TX_HITS.with(std::cell::Cell::get) -} - -/// [`CHROMA_RECT_LEAF_TX_DIFF_HITS`]: of those, the units whose covering -/// leaf's type differs from the block-level one. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_rect_leaf_tx_diff_hits() -> usize { - CHROMA_RECT_LEAF_TX_DIFF_HITS.with(std::cell::Cell::get) -} diff --git a/crates/ec-av1/src/decode/deblock.rs b/crates/ec-av1/src/decode/deblock.rs index 04f88777..651a9dc9 100644 --- a/crates/ec-av1/src/decode/deblock.rs +++ b/crates/ec-av1/src/decode/deblock.rs @@ -1,7 +1,7 @@ //! Deblocking filters: the edge filters, the deblock plane drivers, the filter-replay capture and the pooled plane scratch. Moved out of `decode/mod.rs` (av1split D12); the items are unchanged apart from visibility. -use archmage::SimdToken; use super::*; +use archmage::SimdToken; /// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple. fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) { @@ -463,12 +463,6 @@ pub(super) fn deblock_plane_span( plane.true_height.min(ch), plane.width, ); - if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") { - eprintln!( - "DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", - plane.true_width, plane.true_height - ); - } // lane-perf8: both passes iterate the edge's OWN direction innermost, so // 4 consecutive 4-sample groups (16 lines) can go through one AVX2 // kernel. The swap is order-preserving: a filtered group overlaps only @@ -523,20 +517,20 @@ pub(super) fn deblock_plane_span( std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k)); if let Some((len, level)) = ps[0] && ps.iter().all(|p| *p == ps[0]) - && filter_edge16( - mine, - (y0 - y_lo) * stride + x0, - stride, - true, - len, - level, - lf.sharpness, - fctx, - ) - { - y0 += 16; - continue; - } + && filter_edge16( + mine, + (y0 - y_lo) * stride + x0, + stride, + true, + len, + level, + lf.sharpness, + fctx, + ) + { + y0 += 16; + continue; + } for (k, p) in ps.iter().enumerate() { if let Some((len, level)) = *p { filter_edge( @@ -555,9 +549,6 @@ pub(super) fn deblock_plane_span( continue; } if let Some((len, level)) = edge_params(&vctx, x0, y0) { - if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 { - eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}"); - } filter_edge( mine, (y0 - y_lo) * stride + x0, @@ -637,20 +628,20 @@ pub(super) fn deblock_plane_span( std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0)); if let Some((len, level)) = ps[0] && ps.iter().all(|p| *p == ps[0]) - && filter_edge16( - px, - (y0 - r_lo) * w + (x0 - x_lo), - w, - false, - len, - level, - lf.sharpness, - fctx, - ) - { - x0 += 16; - continue; - } + && filter_edge16( + px, + (y0 - r_lo) * w + (x0 - x_lo), + w, + false, + len, + level, + lf.sharpness, + fctx, + ) + { + x0 += 16; + continue; + } for (k, p) in ps.iter().enumerate() { if let Some((len, level)) = *p { filter_edge( @@ -669,15 +660,6 @@ pub(super) fn deblock_plane_span( continue; } if let Some((len, level)) = edge_params(&hctx, x0, y0) { - if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE") - && plane_idx == 0 - && x0 == 44 - { - eprintln!( - "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}", - lf.sharpness - ); - } filter_edge( px, (y0 - r_lo) * w + (x0 - x_lo), @@ -716,7 +698,8 @@ pub(super) fn deblock_plane_span( /// every pool thread the decode ever created. One shared pool with a hard /// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how /// many threads cycle through it; anything over the cap is freed. -pub(super) static PLANE_SCRATCH: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); +pub(super) static PLANE_SCRATCH: std::sync::Mutex>> = + std::sync::Mutex::new(Vec::new()); /// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K /// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in @@ -877,7 +860,8 @@ pub(crate) fn arm_filter_replay() { /// can hold the replay against the decode it stands in for /// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`). #[cfg(test)] -pub(super) static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +pub(super) static REPLAY_DISABLED: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); #[cfg(test)] pub(crate) fn set_filter_replay_disabled(off: bool) { diff --git a/crates/ec-av1/src/decode/frame_tile.rs b/crates/ec-av1/src/decode/frame_tile.rs index 9a091a8f..5113eced 100644 --- a/crates/ec-av1/src/decode/frame_tile.rs +++ b/crates/ec-av1/src/decode/frame_tile.rs @@ -417,13 +417,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK); let mut y = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane( - width * height, - true_width, - true_height, - width, - height, - )), + data: std::borrow::Cow::Owned(fresh_plane(width * height)), width, height, true_width, @@ -435,10 +429,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( plane: 0, }; let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); - note_frame_chroma_alloc((width, height), (cw, ch), (ss_x(fctx), ss_y(fctx))); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); let mut u = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, @@ -450,7 +443,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( plane: 1, }; let mut v = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, @@ -542,17 +535,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets // it codes every symbol against the tables it started with. dec.set_cdf_update(!cdf_update_disabled(fctx)); - crate::census::register_cdfs(&cdfs); // lane-comppin r9: tile-entry range, the earliest point comparable // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the // first ladder rung before any symbol (partition or otherwise) is read. - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL label=tile_init tell={} range={}", - dec.debug_bitpos(), - dec.debug_state().0 - ); - } neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx); y.set_tile_origin( mi_col0 as usize * 4, @@ -583,7 +568,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mi_row1 as usize, mi_col1 as usize, ); - hit!(TILE_HITS); // lane-sb128 r2: at `sb_size == 128` the tile walks each 128x128 // superblock's four 64x64 quadrants in libaom `decode_partition` order @@ -985,11 +969,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( bw, bh ); - if horz { - hit!(INTER_SB128_HORZ_HITS); - } else { - hit!(INTER_SB128_VERT_HITS); - } } // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF unit it // covers -- both halves of the root read their own, and the @@ -1023,7 +1002,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( continue; } if sb128_none { - hit!(INTER_SB128_NONE_HITS); let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); // lane-sb128c r3: `at128` is in SUB16 units like `sb_at`; // `decode_inter_block` takes MI. Unconverted it was (0,0) for @@ -1076,16 +1054,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // instead of silently decoding as SPLIT and desyncing. let part64 = match (has_cols, has_rows) { (true, true) => { - let pre_rng = dec.debug_state().0; - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=12 ctx={} rng={}", - sb_r as usize * SB_MI as usize, - sb_c as usize * SB_MI as usize, - sb_ctx, - dec.debug_state().0 - ); - } let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]); // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize` @@ -1094,33 +1062,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings // keep decoding because the helper is exact, not a heuristic. inter-frame 64x64 level; `p` is the symbol. - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p} pre_rng={pre_rng}", - sb_r * SB_MI, - sb_c * SB_MI - ); - } p } (true, false) => { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT // (libaom `ec_read_partition_impl`). - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PARTG mi_row={} mi_col={} bsize=12 ctx={} rng={}", - sb_r as usize * SB_MI as usize, - sb_c as usize * SB_MI as usize, - sb_ctx, - dec.debug_state().0 - ); - } - if bump_edge32_bit( - 4, - dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)), - ) == 1 - { + if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)) == 1 { PARTITION_SPLIT } else { PARTITION_HORZ @@ -1130,20 +1078,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT // (libaom `ec_read_partition_impl`). - if bump_edge32_bit( - 4, - dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)), - ) == 1 - { + if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)) == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } - (false, false) => { - bump_edge_both_cut(2); - PARTITION_SPLIT - } + (false, false) => PARTITION_SPLIT, }; // lane-av1unwritten r7: the symbol is RESOLVED (a full CDF // read or an edge `gather`) and about to be dispatched, so the @@ -1156,16 +1097,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // see it. refuse_invalid_subsize((64, 64), part64, fctx)?; if part64 == PARTITION_NONE { - // lane-inter8 r1: the whole superblock as one 64x64 inter - // block. `SB`-sized syntax throughout (size_group 3, same as - // 32x32 -- `size_group_lookup[BLOCK_64X64] == 3`), luma - // coefficients through `TxbSet::Luma64` with the 32-point - // scan (TX_64X64 codes only its top-left corner, spec - // 5.11.40 -- `read_inter_plane` widens the corner back to - // 64x64 before the inverse transform), chroma as a plain - // 32x32 `TxbSet::Chroma32`. TX_64X64 carries no `tx_type` - // symbol at all, so the intra/inter luma sets coincide. - hit!(INTER_SB_NONE_HITS); decode_inter_block( &mut dec, &mut cdfs, @@ -1220,15 +1151,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4 ) { // lane-av1unwritten r6: arm census. - note_subsize_arm( - part64, - chroma_plane_block_codable( - partition_subsize_dims((64, 64), part64).0, - partition_subsize_dims((64, 64), part64).1, - ss_x(fctx), - ss_y(fctx), - ), - ); // lane-inter4 r1: the superblock-level rect + 1:4 pairs as // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 / // 16x64 ones. Each piece keeps `side = SB` for every @@ -1282,38 +1204,10 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( bw, bh ); - if !four && i == 0 && ((horz && !has_rows) || (!horz && !has_cols)) { - bump_inter_edge_strip(if horz { 0 } else { 1 }); - } - match (horz, four) { - (true, false) => hit!(INTER_SB_HORZ_HITS), - (false, false) => hit!(INTER_SB_VERT_HITS), - (true, true) => hit!(INTER_SB_HORZ4_HITS), - (false, true) => hit!(INTER_SB_VERT4_HITS), - } } continue; } if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part64) { - // lane-sbab r1: the four superblock-level AB arms on the - // INTER path -- two 32x32 inter squares plus one true - // 64x32/32x64 inter strip, in libaom `decode_partition`'s own - // order (decodeframe.c: HORZ_A = TL, TR, bottom strip; - // HORZ_B = top strip, BL, BR; VERT_A = TL, BL, right strip; - // VERT_B = left strip, TR, BR). Every piece is one this - // decoder already proves elsewhere: the 32x32 square is the - // `PARTITION_NONE`-under-SPLIT block below, the strip is the - // `PARTITION_HORZ`/`VERT` piece above (`inter_piece!`, which - // keeps `side = SB` for syntax/CDF and names its true - // footprint through `write_w`/`write_h`). The intra-frame - // twin of this arm is lane-part32 r4's `SB_AB_HITS` block. - hit_do! { - SB_AB_INTER_HITS.with(|c| { - let mut h = c.get(); - h[part64 - PARTITION_HORZ_A] += 1; - c.set(h); - }); - } // lane-part32 r5 / class visit-order-changes-availability: // only the two VERTICAL arms visit TL, BL, TR, BR, so only // they switch libaom's `has_tr`/`has_bl` tables. @@ -1442,14 +1336,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), ); let part32 = if has_cols32 && has_rows32 { - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE part32_pre mi=({},{}) rng={}", - r32 * BLOCK_MI, - c32 * BLOCK_MI, - dec.debug_state().0 - ); - } // lane-av1tilerows: this rung printed the RAW 32-grid // index (`r32`, `c32`) into its `mi_row=`/`mi_col=` // fields — a factor of `BLOCK_MI` (8) off — while the @@ -1460,23 +1346,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // against libaom's per-level `EC_PART_VAL` dump, which // is the only way to locate a partition-walk // divergence. Behaviour-free: env-gated print only. - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=9 ctx={} rng={}", - r32 * BLOCK_MI, - c32 * BLOCK_MI, - ctx32, - dec.debug_state().0 - ); - } let p = dec.symbol(&mut cdfs.partition_w32[ctx32]); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}", - r32 * BLOCK_MI, - c32 * BLOCK_MI - ); - } p } else { match (has_cols32, has_rows32) { @@ -1484,21 +1354,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT // (libaom `ec_read_partition_impl`). - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PARTG mi_row={} mi_col={} bsize=9 ctx={} rng={}", - r32 as usize * BLOCK_MI as usize, - c32 as usize * BLOCK_MI as usize, - ctx32, - dec.debug_state().0 - ); - } if { let b = dec.symbol_fixed(&gather( &cdfs.partition_w32[ctx32], VERT_ALIKE, )); - bump_edge32(b.min(1)); b } == 1 { @@ -1516,7 +1376,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &cdfs.partition_w32[ctx32], HORZ_ALIKE, )); - bump_edge32(b.min(1)); b } == 1 { @@ -1525,10 +1384,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( PARTITION_VERT } } - _ => { - bump_edge_both_cut(1); - PARTITION_SPLIT - } + _ => PARTITION_SPLIT, } }; // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or @@ -1611,24 +1467,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // inter leaves through the very same loop the // straddling case has always used. let part16 = if has_cols16 && has_rows16 { - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=6 ctx={} rng={}", - (sr * SUB_MI as usize), - (sc * SUB_MI as usize), - ctx16, - dec.debug_state().0 - ); - } let p = dec.symbol(&mut cdfs.partition_w16[ctx16]); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}", - sr as u32 * SUB_MI, - sc as u32 * SUB_MI - ); - } p } else if !has_cols16 && !has_rows16 { // lane-edgeboth r1: both axes cut by the true @@ -1636,22 +1475,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // forces PARTITION_SPLIT and reads NO symbol; // the leaf loop below already drops the // out-of-frame quadrants. - bump_edge_both_cut(0); PARTITION_SPLIT } else { if has_cols16 { // lane-golomb r1 (class `parsed-then-discarded`): the gathered // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT // (libaom `ec_read_partition_impl`). - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PARTG mi_row={} mi_col={} bsize=6 ctx={} rng={}", - sr * SUB_MI as usize, - sc * SUB_MI as usize, - ctx16, - dec.debug_state().0 - ); - } if dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], VERT_ALIKE, @@ -1749,11 +1578,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // residual path (`rect_inter_residual_supported` // covers 16x8/8x16 since this round). let horz = part16 == PARTITION_HORZ; - if horz { - hit!(INTER_LEAF16_HORZ_HITS); - } else { - hit!(INTER_LEAF16_VERT_HITS); - } let base_mi = sub16_to_mi(at16); let (ww, wh) = if horz { (16, 8) } else { (8, 16) }; for piece in 0..2 { @@ -1768,7 +1592,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( && (piece_mi.0 >= mi_rows as usize || piece_mi.1 >= mi_cols as usize) { - bump_inter_edge_strip(if horz { 4 } else { 5 }); break; } decode_inter_block( @@ -1861,7 +1684,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // block_size_high >= 16, blockd.h) both hold // and the leaf/strip decoders' own gates // apply unchanged. - bump_ab16_inter(part16 - PARTITION_HORZ_A); let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B { @@ -2035,20 +1857,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( bw, bh ); - if horz { - hit!(INTER16_HORZ4_HITS); - } else { - hit!(INTER16_VERT4_HITS); - } } } else if part16 != PARTITION_SPLIT { return Err(unsupported( "an inter 16x16-level partition value outside NONE/HORZ/VERT/SPLIT/AB/1:4", )); } else { - if has_cols16 && has_rows16 { - hit!(INTER_SUB16_SPLIT_HITS); - } let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let leaf_positions: Vec<(u32, u32)> = (0..4) @@ -2062,13 +1876,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // 7.11.3.3's scaled walk. The counter is what // proves a gate actually reached a scaled // leaf rather than a same-size reference. - if (1..8).any(|rf| { - refpix - .dims(rf) - .is_some_and(|(w, _)| w != frame_width as usize) - }) { - hit!(SCALED_LEAF8_HITS); - } let mut prev_leaves: Vec<( (usize, usize), bool, @@ -2079,16 +1886,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( for (mr, mc) in leaf_positions { let leaf_mi = (mr as usize, mc as usize); let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); - if crate::envflags::env_flag!("EC_TRACE_PART") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=3 ctx={} rng={}", - leaf_mi.0, - leaf_mi.1, - leaf_ctx, - dec.debug_state().0 - ); - } - let ec_dbg_pre = dec.debug_state().0; let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize` @@ -2098,13 +1895,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // keep decoding because the helper is exact, not a heuristic. inter-frame 8x8 level. refuse_invalid_subsize((8, 8), part8, fctx)?; - if std::env::var_os("EC_DBG_SUB8").is_some() { - let ec_dbg_post = dec.debug_state().0; - eprintln!( - "EC_DBG b8 mi=({},{}) ctx={leaf_ctx} val={part8} pre={ec_dbg_pre} post={ec_dbg_post}", - leaf_mi.0, leaf_mi.1 - ); - } if part8 == PARTITION_SPLIT { // lane-intersub8: four BLOCK_4X4 inter // sub-blocks, chroma once per 8x8. @@ -2138,15 +1928,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // lane-av1unwritten r6: arm census -- an // 8x8-level VERT selects BLOCK_4X8, which // is INVALID at 4:2:2. - note_subsize_arm( - part8, - chroma_plane_block_codable( - partition_subsize_dims((8, 8), part8).0, - partition_subsize_dims((8, 8), part8).1, - ss_x(fctx), - ss_y(fctx), - ), - ); if part8 == PARTITION_VERT || part8 == PARTITION_HORZ { // lane-intersub8 r3/r4/r5: two // BLOCK_8X4 (HORZ) / BLOCK_4X8 (VERT) @@ -2282,19 +2063,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } PARTITION_HORZ_B => { - // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip + - // 16x16 bottom-left + 16x16 bottom-right. aomenc - // carves static regions into it; the strip is - // decoded as a square 32x32 block: for a `skip` - // block the symbol stream is identical to the true - // 32x16 coding (no residual, no motion_mode/warp - // symbol), and the square stamps it leaves over the - // bottom half (neighbour arrays, skip/lf grids) are - // re-stamped by the C/D leaves right after. The - // mi-granular `left_side_mi` rows of a last-block-in- - // tile strip leak 32-vs-16 only until the per-tile - // `Neighbours::new` reset. - hit!(EXTENDED_PARTITION_HITS); let at32 = at; decode_inter_block( &mut dec, @@ -2454,13 +2222,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } PARTITION_HORZ => { - // lane-rect r2: two true 32x16 strips. Both read at - // `side=BLOCK` (CDF/size-class selection stays square, - // matching HORZ_B's accepted corner-cut) but bw4/bh4 - // (mvstack.rs, `motion_mode_eligible`) now derive from - // `write_w`/`write_h`'s true 32x16 footprint -- the - // pin's fix (r1's finding). - hit!(RECT_PARTITION_HITS); decode_inter_block( &mut dec, &mut cdfs, @@ -2508,9 +2269,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( (frame_width as usize, frame_height as usize), fctx, )?; - if !has_rows32 { - bump_edge32(2); - } // lane-golomb r2: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_rows32 test that made this partition non-square). @@ -2562,14 +2320,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( (frame_width as usize, frame_height as usize), fctx, )?; - } else { - bump_inter_edge_strip(2); } } PARTITION_VERT => { - // lane-rect r2: mirror of PARTITION_HORZ above with - // width/height swapped. - hit!(RECT_PARTITION_HITS); decode_inter_block( &mut dec, &mut cdfs, @@ -2617,9 +2370,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( (frame_width as usize, frame_height as usize), fctx, )?; - if !has_cols32 { - bump_edge32(3); - } // lane-golomb r2: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_cols32 test that made this partition non-square). @@ -2671,15 +2421,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( (frame_width as usize, frame_height as usize), fctx, )?; - } else { - bump_inter_edge_strip(3); } } PARTITION_HORZ_A => { - // lane-partab r1: two 16x16 squares on top + a true - // 32x16 strip below (libaom decode_partition - // PARTITION_HORZ_A: TL, TR, bottom strip). - hit!(PARTAB_HITS); decode_inter_block( &mut dec, &mut cdfs, @@ -2831,9 +2575,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )?; } PARTITION_VERT_A => { - // lane-partab r1: mirror of PARTITION_HORZ_A with - // width/height swapped (TL, BL, right 16x32 strip). - hit!(PARTAB_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_inter_block( &mut dec, @@ -2986,10 +2727,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( )?; } PARTITION_VERT_B => { - // lane-partab r1: true 16x32 strip on the left + two - // 16x16 squares on the right (libaom decode_partition - // PARTITION_VERT_B: left strip, TR, BR). - hit!(PARTAB_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_inter_block( &mut dec, @@ -3177,11 +2914,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( bw, bh ); - if horz { - hit!(RECT4_32_HORZ_INTER_HITS); - } else { - hit!(RECT4_32_VERT_INTER_HITS); - } } } _ => { @@ -3228,51 +2960,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( ); } - // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's - // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against - // that isolate whether a decode-order frame's mismatch already exists - // in reconstruction (this dump) vs is introduced by the loop filter - // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). - // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. - if crate::envflags::env_flag!("EC_OBMC") - || crate::envflags::env_flag!("EC_TRACE_MODE") - || crate::envflags::env_flag!("EC_PRED") - { - eprintln!( - "EC_PICT idx={}", - PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) - ); - } - dump_stage16( - "EC_AV1_PREFILT_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); - census_unwritten(&y, &u, &v); - if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { - // lane-av1dumploud: loud on a short write (see the key-frame twin - // above -- same file, same shape, same three planes). - let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - "EC_AV1_PREFILT_DUMP", - format!("{path}.f{idx}"), - &[&narrow(&y), &narrow(&u), &narrow(&v)], - ); - } else { - PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - // lane-av1444edge: the inter-frame path's mi-aligned pre-loop-filter - // dump, the rung the key-frame path has always had (see - // `dump_prefilter_wide`). Placed beside the padded `EC_AV1_PREFILT_DUMP` - // above, i.e. before the loop filters run, so the two agree on the point - // in the sequence they sample. - dump_prefilter_wide(&y, &u, &v); // lane-av1fwd: the encoder scores ~25 filter candidates against this // same coded tile ([`FilterReplay`]). Capture the reconstruction here, // before either filter has touched it -- but only on the shape whose @@ -3314,42 +3001,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( plane_snapshot(&v, ss_y(fctx) as u32), ) }); - // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own - // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter - // dump above these bisect WHICH filter stage introduced a mismatch. - dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTDEBLOCK_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); apply_cdef( &mut y, &mut u, &mut v, cdef, &neighbours, - (frame_width as usize, frame_height as usize), fctx, None, None, ); - dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTCDEF_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): diff --git a/crates/ec-av1/src/decode/inter_block.rs b/crates/ec-av1/src/decode/inter_block.rs index 1f80c5c6..d3dc898e 100644 --- a/crates/ec-av1/src/decode/inter_block.rs +++ b/crates/ec-av1/src/decode/inter_block.rs @@ -123,8 +123,6 @@ pub(super) fn decode_inter_block( // Round 27: the per-read trace is the only instrument that reaches the inter // path (the coefficient rungs stop well before the frame-3 divergence), // so publish the phase and the block's mi for every read it makes. - crate::msac::SymbolDecoder::set_symr_phase("inter"); - crate::msac::SymbolDecoder::set_symr_mi(at.0 as i64, at.1 as i64); // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the // few 16-px-granular uses below. @@ -135,7 +133,6 @@ pub(super) fn decode_inter_block( // exactly what it read before. let (rmi, cmi) = at; let (px, py) = (at.1 * MI, at.0 * MI); - census_inter_block_shape(side, write_w, write_h); // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd // strip (`is_chroma_reference`); every other block keeps its own. @@ -233,30 +230,12 @@ pub(super) fn decode_inter_block( // bails per PLANE at `block_width < 8 || block_height < 8` -- on the // block's own dims, never on the square prediction buffer this reader // allocates. - if crate::envflags::env_flag!("EC_MC_TRACE") { - eprintln!("EC_IB px={px} py={py} side={side} w={write_w} h={write_h}"); - } - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}", - rmi, - cmi, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } let skip_mode_ctx = usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]); // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read // MSAC tell so it can be diffed against an equivalent hook in libaom's // own `read_skip_mode`/`av1_get_skip_mode_context`. - if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") { - eprintln!( - "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}", - dec.debug_bitpos() - ); - } // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before // `skip_mode`/`skip`, `inter_segment_id(0)` after them. let (seg_mi_r, seg_mi_c) = (rmi, cmi); @@ -270,15 +249,6 @@ pub(super) fn decode_inter_block( let comp_allowed = write_w.min(write_h) >= 8; let skip_mode = skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; - if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") { - eprintln!( - "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}", - dec.debug_bitpos() - ); - } - if skip_mode { - hit!(SKIP_MODE_HITS); - } let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; @@ -303,16 +273,6 @@ pub(super) fn decode_inter_block( // chunk). An INTRA block at that size inside an inter frame takes the // intra tail below, which still codes one whole-block chroma unit and one // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}", - rmi, - cmi, - dec.debug_state().0, - u8::from(is_inter), - u8::from(skip) - ); - } // lane-warp r5: see `reject_residual` -- a square-block decode of a // HORZ_B strip is symbol-exact only for `skip` (no residual, no // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just @@ -332,26 +292,10 @@ pub(super) fn decode_inter_block( && !rect_inter_residual_supported(write_w, write_h) && (is_inter || (write_w == side && write_h == side)) { - if crate::envflags::env_flag!("EC_RECTRES") { - eprintln!( - "EC_RECTRES w={write_w} h={write_h} side={side} skip={} is_inter={} mi_row={rmi} mi_col={cmi}", - u8::from(skip), - u8::from(is_inter) - ); - } return Err(unsupported( "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", )); } - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}", - rmi, - cmi, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } let mode_for_tx; let uv_predict_mode; @@ -411,12 +355,6 @@ pub(super) fn decode_inter_block( uni: neighbours.left_ref1[rmi] .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)), }); - if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") { - eprintln!( - "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}", - dec.debug_bitpos() - ); - } let is_compound = skip_mode || (reference_select // `is_comp_ref_allowed` (blockd.h:65) gates the @@ -498,22 +436,6 @@ pub(super) fn decode_inter_block( ), fctx, ); - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}", - compound_mode + 17, - mv0.0, - mv0.1, - comp_stack.entries.len(), - dec.debug_state().0 - ); - for (i, e) in comp_stack.entries.iter().enumerate() { - eprintln!( - "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}", - e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight - ); - } - } let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV // be non-TRANSLATION (IDENTITY counts) for the compound block's // interp-filter read to be suppressed. @@ -526,9 +448,6 @@ pub(super) fn decode_inter_block( // `AOMMIN(mi_size_wide, mi_size_high) < 2` before it looks at any // model, so a 4-px-sided block still reads its interp filter. let gm_nontrans = gm_nontrans_models && bw4.min(bh4) >= 2; - if gm_nontrans_models && !gm_nontrans { - hit!(GM_NONTRANS_SMALL_SIDE_HITS); - } // lane-defer8: both slots' pictures are resolved inside the // prediction closure; the parse only needs their SIZES. // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is @@ -551,14 +470,6 @@ pub(super) fn decode_inter_block( // alone, which counts blocks that are not global-mv blocks at // all, so its number was an upper bound dressed up as an // engagement figure. - if mi_row < mi_rows as usize / 2 { - if is_globalmv { - TOP_HALF_COMPOUND_HITS.with(|c| c.set(c.get() + 1)); - } - if is_global_mv0 || is_global_mv1 { - TOP_HALF_WARP_HITS.with(|c| c.set(c.get() + 1)); - } - } // libaom `av1_init_warp_params` + `allow_warp`'s // `global_warp_allowed` branch, run once per reference for a // compound block exactly as for a single-ref one (reconinter.c @@ -595,7 +506,6 @@ pub(super) fn decode_inter_block( let warp0 = compound_warp(ref0, is_global_mv0).filter(|_| ref_unscaled(ref0)); let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1)); if warp0.is_some() || warp1.is_some() { - hit!(COMPOUND_WARP_HITS); // lane-av112bitw: the 12-bit refusal that stood here is // LIFTED with the compound-warp witness: the rotating- // mandelbrot 12-bit recipe refused exactly here pre-lift and @@ -668,17 +578,10 @@ pub(super) fn decode_inter_block( && enable_masked_compound && is_any_masked_compound_used_here(write_w, write_h) { - crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx"); dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) } else { 0 }; - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}", - dec.debug_state().0 - ); - } // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup) // for a `COMPOUND_WEDGE` block -- exactly one of the two is set @@ -714,16 +617,6 @@ pub(super) fn decode_inter_block( // verified vs independent C dump (wedge.rs). let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]); let wedge_sign = dec.literal(1); - hit!(WEDGE_HITS); - if let Some(k) = rect_wedge_slot(write_w, write_h) { - hit_do! { - RECT_WEDGE_HITS.with(|c| { - let mut a = c.get(); - a[k] += 1; - c.set(a); - }); - } - } // lane-inter16ab r5: the codebook row is this block's TRUE // footprint (`av1_wedge_params_lookup[bsize]`: hgtw for // h>w, hltw for h = if let Some(mask_type) = diffwtd_mask_type { diffwtd_mask_y = vec![0u8; side * side]; - hit!(DIFFWTD_HITS); mc::diffwtd_mask( &inter0_y, &inter1_y, @@ -1415,7 +1273,23 @@ pub(super) fn decode_inter_block( let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if pred_deferred(refpix) { push_pred(build); - (Pred::Cur { plane: 0, stride: side, off: 0 }, Pred::Cur { plane: 1, stride: chroma_stride, off: 0 }, Pred::Cur { plane: 2, stride: chroma_stride, off: 0 }) + ( + Pred::Cur { + plane: 0, + stride: side, + off: 0, + }, + Pred::Cur { + plane: 1, + stride: chroma_stride, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: chroma_stride, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -1597,14 +1471,6 @@ pub(super) fn decode_inter_block( fctx, )? } else { - // lane-r14 r3: a 1:4 strip's `sub_tx_size_map` - // sub-transform is RECTANGULAR (TX_64X16 -> - // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is - // read with the rect coefficient machinery, at its - // own `txb_skip_ctx`/neighbour spans -- the unit is - // smaller than its block, so `get_txb_ctx_general`'s - // neighbour table applies, not the lone-TU 0. - vartx_rect_leaf_hit(tw, th); let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); let start = row * MI * side + col * MI; @@ -1852,7 +1718,6 @@ pub(super) fn decode_inter_block( plane_idx, &cu_grid, ); - hit!(CHROMA_SPLIT_TX_HITS); mu_chroma = true; // lane-av1muchunk422b: the allocation of this // mu-chunk walk, counted per TX_32X32 UNIT. @@ -1861,9 +1726,6 @@ pub(super) fn decode_inter_block( // bump: `MU_CHUNK_COMPOUND_UNITS` names site 2 // and the single-reference twin (site 5) stays // out of it. - if is_compound { - hit!(MU_CHUNK_COMPOUND_UNITS); - } let dst = mu_units( if plane_idx == 1 { &mut u_units @@ -2068,12 +1930,6 @@ pub(super) fn decode_inter_block( let cu_rel_mi = (cr * (cu_tx / MI), cc * (cu_tx / MI)); let cu_tx_type = covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi) .unwrap_or(luma_tx_type); - if covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi).is_some() { - hit!(CHROMA_QUAD_LEAF_TX_HITS); - if cu_tx_type != luma_tx_type { - hit!(CHROMA_QUAD_LEAF_TX_DIFF_HITS); - } - } let cu_grid = read_inter_plane( dec, cdfs, @@ -2099,7 +1955,6 @@ pub(super) fn decode_inter_block( // this one's coefficients. neighbours .record_mi_chroma(cu_mi, cu_tx, cu_tx, plane_idx, &cu_grid); - hit!(CHROMA_SPLIT_TX_HITS); // lane-av1-444 c8: the unit's levels must ALSO // land in the block grid -- the block-tail mu // re-stamp slices the per-unit states back out @@ -2177,14 +2032,6 @@ pub(super) fn decode_inter_block( neighbours.left_ref1[rmi], ); ref_frame_for_lf = ref_frame; - if crate::envflags::env_flag!("EC_AV1_TELL") { - let (mi_row, mi_col) = (rmi, cmi); - eprintln!( - "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}", - dec.debug_bitpos(), - dec.debug_state().0 - ); - } // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own // stacked defects (lf_level ref/mode-delta forwarding, the // switchable_interp ref-frame ctx gate, and a film-grain synthesis @@ -2245,14 +2092,10 @@ pub(super) fn decode_inter_block( tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; - if !not_new { - crate::census::mode(0); - } let mut is_globalmv = false; // lane-interbis r1: which single-ref mode this block resolved to, // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for // the `EC_MODE_VAL` value ladder below. - let mut dbg_mode = 16u32; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): // read at most two `drl_mode` bits, one per stack entry past the @@ -2282,19 +2125,13 @@ pub(super) fn decode_inter_block( ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - if !not_zero { - crate::census::mode(1); - } is_globalmv = !not_zero; let mv = if !not_zero { // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already // computed at this block's own position in `gm_table`. - dbg_mode = 15; gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - crate::census::mode(if nearest { 2 } else { 3 }); - dbg_mode = if nearest { 13 } else { 14 }; if nearest { stack.nearest_mv } else { @@ -2316,26 +2153,6 @@ pub(super) fn decode_inter_block( }; (mv, false) }; - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - " MODE mi=({mi_row},{mi_col}) dbg={dbg_mode} mv={mv:?}" - )); - } - if crate::envflags::env_flag!("EC_TRACE_MODE") { - for (i, e) in stack.entries.iter().enumerate() { - eprintln!( - "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", - e.mv.0, e.mv.1, e.weight - ); - } - eprintln!( - "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}", - mv.0, - mv.1, - stack.entries.len(), - dec.debug_state().0 - ); - } // lane-gm r2: the two libaom predicates single-ref GLOBALMV // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating @@ -2348,13 +2165,6 @@ pub(super) fn decode_inter_block( let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2; let gm_nontrans = is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2; - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}", - dec.debug_bitpos(), - dec.debug_state().0 - ); - } // lane-sb128 r4: `interintra` (spec 5.11.24; libaom // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed // right after `assign_mv` and before `read_motion_mode` below -- @@ -2384,7 +2194,6 @@ pub(super) fn decode_inter_block( // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip // group 2, not their square `side`'s 2/3. let bsize_group = size_group_wh(write_w, write_h); - crate::msac::SymbolDecoder::set_symr_cdf("interintra"); let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1; if interintra { // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode, @@ -2406,16 +2215,6 @@ pub(super) fn decode_inter_block( // NO sign symbol follows -- libaom fixes // INTERINTRA_WEDGE_SIGN 0 (blockd.h). let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]); - hit!(WII_HITS); - if let Some(k) = rect_wedge_slot(write_w, write_h) { - hit_do! { - RECT_WII_HITS.with(|c| { - let mut a = c.get(); - a[k] += 1; - c.set(a); - }); - } - } // lane-inter16ab r5: true-footprint codebook row, // mask padded to stride `max(bw,bh) == side` -- see // the compound site's own comment. @@ -2425,8 +2224,6 @@ pub(super) fn decode_inter_block( .mask(0, wedge_index), side, )); - } else { - hit!(INTERINTRA_HITS); } interintra_mode = Some(ii); // The inter-intra predictor reads this block's neighbours as already @@ -2434,13 +2231,6 @@ pub(super) fn decode_inter_block( super::wave::finish_tile(fctx, refpix, [&mut *y, &mut *u, &mut *v]); } } - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}", - dec.debug_bitpos(), - dec.debug_state().0 - ); - } // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24; // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528), // placed right after MV assignment and before the switchable @@ -2483,20 +2273,6 @@ pub(super) fn decode_inter_block( // as aomdec's `EC_ISTEP2 name=motion_mode` -- an eligibility // mismatch is otherwise invisible (a skipped symbol prints // nothing). - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_MM mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} \ - ab={} lf={} sw={} skipmode={} ii={} gmb={} rng={}", - motion_mode_eligible as u8, - overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).len(), - overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1).len(), - switchable_motion_mode as u8, - skip_mode as u8, - interintra_mode.is_some() as u8, - is_global_mv_block as u8, - dec.debug_state().0, - ); - } let mut obmc_selected = false; // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL // *and* the local warp estimate is valid (`!wm_params.invalid`, @@ -2564,24 +2340,15 @@ pub(super) fn decode_inter_block( ) >= 1; let warp_eligible = allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok; - if allow_warped_motion && proj_ok && ref_is_scaled { - hit!(SCALED_WARP_SUPPRESSED_HITS); - } - if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv { - hit!(FIMV_ALPHABET_HITS); - } if warp_eligible { - crate::msac::SymbolDecoder::set_symr_cdf("motion_mode"); let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]); match mode { 0 => {} 1 => { obmc_selected = true; - hit!(OBMC_HITS); } _ => { warped_selected = true; - hit!(WARP_SELECTED_HITS); let mut samples = find_samples( grid, mi_row, @@ -2593,18 +2360,6 @@ pub(super) fn decode_inter_block( ref_frame, fctx, ); - if crate::envflags::env_flag!("EC_WARP_DEBUG") { - eprintln!( - "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}", - samples.len() - ); - for (i, s) in samples.iter().enumerate() { - eprintln!( - "EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", - s.pts1, s.pts2 - ); - } - } if samples.len() > 1 { crate::warp::select_samples( mv, @@ -2625,45 +2380,15 @@ pub(super) fn decode_inter_block( mi_row as i32, mi_col as i32, ); - if crate::envflags::env_flag!("EC_WARP_DEBUG") { - eprintln!( - "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}", - samples.len(), - mv.0, - mv.1, - warp_params - ); - for (i, s) in samples.iter().enumerate() { - eprintln!( - "EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", - s.pts1, s.pts2 - ); - } - } } } } else { obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1; - if obmc_selected { - hit!(OBMC_HITS); - } } // lane-t900 r9: which ALPHABET this block read (3-symbol // motion_mode vs 2-symbol obmc) and the range after -- the // two give the same value with a different narrowing (class // wrong-alphabet-same-value). - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_MM2 mi_row={mi_row} mi_col={mi_col} row={bsize_idx} warp_elig={} \ - scaled={} fimv={} obmc={} warped={} rng={}", - warp_eligible as u8, - ref_is_scaled as u8, - force_integer_mv as u8, - obmc_selected as u8, - warped_selected as u8, - dec.debug_state().0, - ); - } } // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` -- @@ -2684,15 +2409,9 @@ pub(super) fn decode_inter_block( let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { warp_params = crate::warp::global_warp_params(gm_ref.params); - if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { - hit!(AFFINE_GM_HITS); - } // lane-av1gwarp12: the ROTZOOM sibling -- the only // >TRANSLATION model vanilla aomenc can emit for a single-ref // global-motion block (encoder search pinned to ROTZOOM). - if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Rotzoom { - hit!(ROTZOOM_GM_WARP_HITS); - } } // lane-av112bitw: a local `WARPED_CAUSAL` projection (set above) // or a global warp model both land here with `warp_params` set -- @@ -2701,14 +2420,6 @@ pub(super) fn decode_inter_block( // (`warp::warp_round_0`, 5 at 12 bits) and the six-frame 12-bit // warp stream decodes byte-exact vs ffmpeg // (`a_12bit_warped_motion_stream_decodes_pixel_exact`). - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}", - motion_mode_eligible as u8, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } // spec `get_ref_filter_type`: a neighbour's own filter only feeds // this block's switchable_interp context when that neighbour coded // the SAME reference frame this block is about to read -- a @@ -2746,26 +2457,6 @@ pub(super) fn decode_inter_block( ); block_filter = resolved_filter; globalmv_for_lf = is_globalmv; - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}", - dec.debug_bitpos(), - dec.debug_state().0 - ); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?} motion_mode_eligible={} obmc_selected={} warped={} tell={}", - skip as u8, - mv.0, - mv.1, - block_filter, - motion_mode_eligible as u8, - obmc_selected as u8, - warp_params.is_some() as u8, - dec.debug_bitpos() - ); - } // lane-rect r2: see the compound path's matching comment above -- // `grid` must be stamped with the block's true bh4/bw4 span, not // a square `bw4`x`bw4` guess. @@ -2818,15 +2509,6 @@ pub(super) fn decode_inter_block( // measured was the 16x4/4x16 strip's sub-8x8 chroma piece, // which this file used to SKIP under a scaled reference // (fixed in the same commit), not the warp fallback. - if warp_params.is_some() { - hit!(SCALED_WARP_FALLBACK_HITS); - } - if obmc_selected { - hit!(SCALED_OBMC_HITS); - } - if interintra_mode.is_some() { - hit!(SCALED_INTERINTRA_HITS); - } } // lane-inter16ab r2: `is_sub8x8_inter`'s neighbour walk reads the @@ -2843,7 +2525,6 @@ pub(super) fn decode_inter_block( { Some((horz, (prev_ref, prev_mv, prev_h, prev_v))) => { let prev_dims = ref_dims(prev_ref, refpix)?; - hit!(INTER16_SUB8_PIECE_HITS); Some(( horz, prev_ref, @@ -3083,9 +2764,6 @@ pub(super) fn decode_inter_block( // result, all planes (reconinter.c av1_build_interintra_predictor // plane loop). if let Some(ii) = interintra_mode { - if write_w != write_h { - hit!(INTERINTRA_RECT_HITS); - } interintra_blend( y, px, @@ -3186,7 +2864,23 @@ pub(super) fn decode_inter_block( let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if pred_deferred(refpix) { push_pred(build); - (Pred::Cur { plane: 0, stride: side, off: 0 }, Pred::Cur { plane: 1, stride: chroma_stride, off: 0 }, Pred::Cur { plane: 2, stride: chroma_stride, off: 0 }) + ( + Pred::Cur { + plane: 0, + stride: side, + off: 0, + }, + Pred::Cur { + plane: 1, + stride: chroma_stride, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: chroma_stride, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -3351,10 +3045,7 @@ pub(super) fn decode_inter_block( // extent is the strip's own. Counted so a 4:4:4 1:4-strip // gate can prove it exercised this route (a 4:2:0 stream // of the same content reads 0). - Some(_) if ss_x(fctx) == 0 => { - hit!(RECT4_INTER_OWN_CHROMA444_HITS); - around - } + Some(_) if ss_x(fctx) == 0 => around, Some(s) if s.has_chroma => { let (pw, ph) = if s.horz { if ss_y(fctx) == 0 { (16, 4) } else { (16, 8) } @@ -3433,14 +3124,6 @@ pub(super) fn decode_inter_block( fctx, )? } else { - // lane-r14 r3: a 1:4 strip's `sub_tx_size_map` - // sub-transform is RECTANGULAR (TX_64X16 -> - // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is - // read with the rect coefficient machinery, at its - // own `txb_skip_ctx`/neighbour spans -- the unit is - // smaller than its block, so `get_txb_ctx_general`'s - // neighbour table applies, not the lone-TU 0. - vartx_rect_leaf_hit(tw, th); let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI); let start = row * MI * side + col * MI; @@ -3674,7 +3357,6 @@ pub(super) fn decode_inter_block( plane_idx, &cu_grid, ); - hit!(CHROMA_SPLIT_TX_HITS); mu_chroma = true; // lane-av1muchunk422b: the allocation of this // mu-chunk walk, counted per TX_32X32 UNIT. @@ -3683,9 +3365,6 @@ pub(super) fn decode_inter_block( // bump: `MU_CHUNK_COMPOUND_UNITS` names site 2 // and the single-reference twin (site 5) stays // out of it. - if is_compound { - hit!(MU_CHUNK_COMPOUND_UNITS); - } let dst = mu_units( if plane_idx == 1 { &mut u_units @@ -3906,16 +3585,10 @@ pub(super) fn decode_inter_block( let cu_tx_type = covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi) .unwrap_or(luma_tx_type); if covering_leaf_tx_type(&leaf_tx_types, cu_rel_mi).is_some() { - hit!(CHROMA_QUAD_LEAF_TX_HITS); - hit!(CHROMA_QUAD_LEAF_TX_SINGLEREF_HITS); // lane-av1f9singleland: this arm's own // non-vacuity number -- the shared // DIFFERS counter below cannot say which // arm changed an answer. - if cu_tx_type != luma_tx_type { - hit!(CHROMA_QUAD_LEAF_TX_DIFF_HITS); - hit!(CHROMA_QUAD_LEAF_TX_SINGLEREF_DIFF_HITS); - } } let cu_grid = read_inter_plane( dec, @@ -3942,7 +3615,6 @@ pub(super) fn decode_inter_block( // this one's coefficients. neighbours .record_mi_chroma(cu_mi, cu_tx, cu_tx, plane_idx, &cu_grid); - hit!(CHROMA_SPLIT_TX_HITS); // lane-av1-444 c8: the unit's levels must ALSO // land in the block grid -- the block-tail mu // re-stamp slices the per-unit states back out @@ -4075,15 +3747,6 @@ pub(super) fn decode_inter_block( // equivalent post-content point (added at the matching call site) // narrows the ladder to this block's own tail instead of the next // block's partition read. - if crate::envflags::env_flag!("EC_AV1_TELL") { - eprintln!( - "TELL mi_row={} mi_col={} label=block_end tell={} range={}", - rmi, - cmi, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH // strips (mirroring the intra `decode_rect4_16` path), and the even // strip's own record wrote empty chroma state over those cells -- this @@ -4250,7 +3913,6 @@ pub(super) fn decode_inter_block( palette_record.3, ); let saved_chroma_ctx = (!has_chroma).then(|| { - hit!(NON_CHROMA_REF_CTX_SKIP_HITS); let (w_mi, h_mi) = (write_w / MI, write_h / MI); let left: Vec<[Neighbour; 2]> = (0..h_mi) .filter_map(|k| neighbours.left.get(at.0 + k).map(|s| [s[1], s[2]])) @@ -4277,7 +3939,6 @@ pub(super) fn decode_inter_block( // where aomdec reads 1, because the skipped 128x128 block at // mi(32,32) never cleared `left[32..48]`. if skip { - hit!(SKIP_VARTX_LUMA_RESET_HITS); neighbours.record_mi_luma_rect(at, write_w, write_h, &luma_grid); } // Plane 0 is already correct per transform unit @@ -4374,7 +4035,6 @@ pub(super) fn decode_inter_block( } } neighbours.record_uv_mode_mi(s.pair_mi.0, s.pair_mi.1, pw / MI, ph / MI, uv_predict_mode); - hit!(INTER16_CHROMA_PAIR_HITS); } // lane-av1-444 c8: each unit stamps its OWN span (32 << ss px at // TX_32X32, 8 px lossless) -- a 64x64 mu chunk at ss 0/0 holds four diff --git a/crates/ec-av1/src/decode/inter_block8.rs b/crates/ec-av1/src/decode/inter_block8.rs index 9111aa85..fafc98e9 100644 --- a/crates/ec-av1/src/decode/inter_block8.rs +++ b/crates/ec-av1/src/decode/inter_block8.rs @@ -160,8 +160,6 @@ pub(super) fn decode_inter_block8( // entry sets the same label from ITS `at`, which is a different block -- // publishing from here is what makes the EC_SYMR mi trustworthy on the // inter path, which is what round 22 got wrong by assuming it was not. - crate::msac::SymbolDecoder::set_symr_phase("inter8"); - crate::msac::SymbolDecoder::set_symr_mi(leaf_mi.0 as i64, leaf_mi.1 as i64); const LAST_FRAME: i8 = 1; // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back // so the caller stamps them into `Neighbours` instead of the `[3, 3]` @@ -243,9 +241,6 @@ pub(super) fn decode_inter_block8( // leaf is always `BLOCK_8X8`, i.e. 2x2 mi. inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true, fctx); let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; - if skip_mode { - hit!(SKIP_MODE_HITS); - } let skip_ctx = usize::from(above_skip) + usize::from(left_skip); let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; @@ -264,14 +259,6 @@ pub(super) fn decode_inter_block8( // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4, // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder // diffs line for line against a real aomdec. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE mi_row={} mi_col={} rng={}", - leaf_mi.0, - leaf_mi.1, - dec.debug_state().0 - ); - } let mode_for_tx; // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the @@ -382,18 +369,6 @@ pub(super) fn decode_inter_block8( comp_stack.ref_mv_ctx, ) }; - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}", - leaf_mi.0, - leaf_mi.1, - compound_mode + 17, - comp_stack.entries.len(), - comp_stack.new_mv_ctx, - comp_stack.ref_mv_ctx, - dec.debug_state().0 - ); - } let (mv0, mv1) = assign_compound_mv( dec, cdfs, @@ -412,19 +387,6 @@ pub(super) fn decode_inter_block8( // lane-inter8 r3: byte-format-identical to the oracle's // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder // diffs line for line against a real aomdec. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}", - leaf_mi.0, - leaf_mi.1, - compound_mode + 17, - ref0, - ref1, - mv0.0, - mv0.1, - dec.debug_state().0 - ); - } // spec 5.11.25: same gating [`decode_inter_block`]'s own // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid @@ -435,7 +397,6 @@ pub(super) fn decode_inter_block8( && enable_masked_compound && is_any_masked_compound_used_here(SIDE, SIDE) { - crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx"); dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) } else { 0 @@ -454,7 +415,6 @@ pub(super) fn decode_inter_block8( // leaf's own comment. let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]); let wedge_sign = dec.literal(1); - hit!(WEDGE_HITS); wedge_mask = Some( crate::wedge::wedge_masks() .codebook(SIDE, SIDE) @@ -464,7 +424,6 @@ pub(super) fn decode_inter_block8( let mask_type = dec.literal(1); diffwtd_mask_type = Some(mask_type as u8); } - hit!(MASKED_COMPOUND_HITS); } // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same // reference-slot defect as the 16x16 leaf's own mask above @@ -490,15 +449,10 @@ pub(super) fn decode_inter_block8( ref_order_hints[(ref0 - LAST_FRAME) as usize], ref_order_hints[(ref1 - LAST_FRAME) as usize], ); - crate::msac::SymbolDecoder::set_symr_cdf("compound_idx"); let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); if idx == 1 { (8, 8, 1u8) } else { - // lane-av1distwtd: the 8x8 leaf's own - // distance-weighted arm, same counter as the - // 16x16+ site above. - hit!(DIST_WTD_COMP_HITS); let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign( order_hint_bits, order_hint, @@ -511,16 +465,6 @@ pub(super) fn decode_inter_block8( (8, 8, 1u8) }; compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx)); - if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") { - eprintln!( - "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize=8 mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}", - mv0.0, - mv0.1, - mv1.0, - mv1.1, - dec.debug_bitpos() - ); - } // lane-interp3 r1: `read_mb_interp_filter` (libaom // `decodemv.c` 1575, the tail of @@ -570,17 +514,10 @@ pub(super) fn decode_inter_block8( true, ); leaf_filter_syms = resolved_filter; - if interp_fixed.is_none() && !(gm_nontrans_c || skip_mode) { - hit!(COMPOUND8_FILTER_HITS); - } // lane-defer8: both slots' SIZES at parse, pictures in the closure. let scale0 = scale_of(ref_dims(ref0, refpix)?, frame_size); let scale1 = scale_of(ref_dims(ref1, refpix)?, frame_size); - if !scale0.is_unscaled() || !scale1.is_unscaled() { - hit!(SCALED_COMPOUND_HITS); - hit!(SCALED_BLOCK8_HITS); - } // lane-interp3 r2 (class twin-functions-drift): both slots // used to be stamped `false`, while [`decode_inter_block`]'s @@ -635,10 +572,6 @@ pub(super) fn decode_inter_block8( leaf_compound_warp(ref0, is_global_mv0_c).filter(|_| leaf_ref_unscaled(ref0)); let warp1_c = leaf_compound_warp(ref1, is_global_mv1_c).filter(|_| leaf_ref_unscaled(ref1)); - if warp0_c.is_some() || warp1_c.is_some() { - hit!(COMPOUND_WARP_HITS); - hit!(COMPOUND_WARP_HITS_8); - } grid.fill_rect( mi_row, mi_col, @@ -745,7 +678,6 @@ pub(super) fn decode_inter_block8( let mut diffwtd_mask_y; let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type { diffwtd_mask_y = vec![0u8; SIDE * SIDE]; - hit!(DIFFWTD_HITS); mc::diffwtd_mask( &inter0_y, &inter1_y, @@ -1002,7 +934,23 @@ pub(super) fn decode_inter_block8( let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if pred_deferred(refpix) { push_pred(build); - (Pred::Cur { plane: 0, stride: SIDE, off: 0 }, Pred::Cur { plane: 1, stride: chroma_w, off: 0 }, Pred::Cur { plane: 2, stride: chroma_w, off: 0 }) + ( + Pred::Cur { + plane: 0, + stride: SIDE, + off: 0, + }, + Pred::Cur { + plane: 1, + stride: chroma_w, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: chroma_w, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -1323,13 +1271,6 @@ pub(super) fn decode_inter_block8( neighbours.above[leaf_mi.1 + cell][0] = state; } } - // lane-cdef r1: ... and the CDEF skip band too. `apply_cdef`'s - // `is_8x8_block_skip` (libaom `cdef.c:29-38`) reads all four mi - // cells of the 8x8; this leaf wrote none of them, so a 64x64 - // whose bottom-right 16x16 is an all-skip 8x8-leaf group kept - // the PREVIOUS frame's flags and got filtered where libaom's - // dlist excludes it (3 luma samples on a 192x128 inter frame). - hit!(INTER8_SKIP_BAND_HITS); neighbours.fill_skip_grid(leaf_mi, 2, skip); // lane-sub8x4 r2: `split8` is this leaf's OWN var-tx split, so // the deblock grid must publish the TX_4X4 leaves' width the @@ -1408,19 +1349,8 @@ pub(super) fn decode_inter_block8( // lane-interp3 r2: same per-entry EC_STACK ladder // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack // diffs line for line against the oracle's. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - for (i, e) in stack.entries.iter().enumerate() { - eprintln!( - "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}", - e.mv.0, e.mv.1, e.weight - ); - } - } let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; - if !not_new { - crate::census::mode(0); - } let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): @@ -1451,19 +1381,11 @@ pub(super) fn decode_inter_block8( ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - if !not_zero { - crate::census::mode(1); - } is_globalmv = !not_zero; let mv = if !not_zero { - // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same - // `gm_get_motion_vector` value the 16x16+ leaf reads out of - // its own `gm_table`, computed at this block's centre. - hit!(GLOBALMV_HITS_8); gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - crate::census::mode(if nearest { 2 } else { 3 }); if nearest { stack.nearest_mv } else { @@ -1487,7 +1409,6 @@ pub(super) fn decode_inter_block8( let mut interintra_mode: Option = None; let mut wedge_mask: Option<(&'static [u8], usize)> = None; if enable_interintra_compound && !skip_mode { - crate::msac::SymbolDecoder::set_symr_cdf("interintra"); let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1; if interintra { // lane-interintra r1: same read pair as the 16/32 site; @@ -1499,15 +1420,12 @@ pub(super) fn decode_inter_block8( // lane-wii r2: same adapting `wedge_index` symbol as the // 16/32 leaf, fixed sign 0 -- see that site's comment. let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]); - hit!(WII_HITS); wedge_mask = Some(( crate::wedge::wedge_masks() .codebook(SIDE, SIDE) .mask(0, wedge_index), SIDE, )); - } else { - hit!(INTERINTRA_HITS); } interintra_mode = Some(ii); // The inter-intra predictor reads this block's neighbours as already @@ -1584,38 +1502,14 @@ pub(super) fn decode_inter_block8( let ref_is_scaled = !scale_of((ref_width, ref_height), frame_size).is_unscaled(); let warp_eligible = allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok; - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_MM8 mi_row={mi_row} mi_col={mi_col} proj={} warp_elig={} awm={}", - proj_ok as u8, warp_eligible as u8, allow_warped_motion as u8 - ); - } - if allow_warped_motion && proj_ok && ref_is_scaled { - hit!(SCALED_WARP_SUPPRESSED_HITS); - } - if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv { - hit!(FIMV_ALPHABET_HITS); - } if warp_eligible { - crate::msac::SymbolDecoder::set_symr_cdf("motion_mode"); let mode = dec.symbol(&mut cdfs.motion_mode[0]); match mode { 0 => {} 1 => { obmc_selected = true; - hit!(OBMC_HITS); - hit!(OBMC_HITS_8); } _ => { - // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf -- - // the same findSamples -> select_samples -> - // av1_find_projection chain the 16x16+ leaf runs, - // with BLOCK_8X8's own 8x8 model centre; an - // unusable projection falls back to the block's - // translational mv (libaom `av1_find_projection` - // returning 1 leaves `wm_params` invalid and - // `build_inter_predictors` skips the warp). - hit!(WARP_SELECTED_HITS); let mut samples = find_samples( grid, mi_row, @@ -1640,18 +1534,11 @@ pub(super) fn decode_inter_block8( mi_col as i32, ); warped_selected = true; - if warp_params.is_some() { - hit!(WARP_HITS_8); - } } } } else { // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3. obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1; - if obmc_selected { - hit!(OBMC_HITS); - hit!(OBMC_HITS_8); - } } } // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8 @@ -1695,17 +1582,6 @@ pub(super) fn decode_inter_block8( false, ); leaf_filter_syms = resolved_filter; - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}", - leaf_mi.0, - leaf_mi.1, - mv.0, - mv.1, - stack.entries.len(), - dec.debug_state().0 - ); - } // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` -- // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model @@ -1713,23 +1589,12 @@ pub(super) fn decode_inter_block8( // size predicate baked into `is_global_mv_block`. if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { warp_params = crate::warp::global_warp_params(gm_ref.params); - if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { - hit!(AFFINE_GM_HITS); - } } // lane-av112bitw: same lift as the 16x16+ leaf -- a local // `WARPED_CAUSAL` projection or a global model both leave // `warp_params` set here; the 12-bit refusal that stood here is // lifted with the same witness (`warp::warp_round_0` moved the // filter's shifts; the same stream decodes byte-exact vs ffmpeg). - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}", - leaf_mi.0, - leaf_mi.1, - warp_params.is_some(), - ); - } grid.fill_rect( mi_row, mi_col, @@ -1760,9 +1625,6 @@ pub(super) fn decode_inter_block8( // (documented corner-cut above); under a scaled reference the same // fixed kernel runs through spec 7.11.3.3's scaled walk instead. let luma_scale = scale_of((ref_width, ref_height), frame_size); - if !luma_scale.is_unscaled() { - hit!(SCALED_BLOCK8_HITS); - } let obmc = if obmc_selected { Some(obmc_plan( grid, @@ -1972,7 +1834,23 @@ pub(super) fn decode_inter_block8( let (pred_y, pred_u, pred_v): (Vec, Vec, Vec); let (sy, su, sv) = if pred_deferred(refpix) { push_pred(build); - (Pred::Cur { plane: 0, stride: SIDE, off: 0 }, Pred::Cur { plane: 1, stride: chroma_w, off: 0 }, Pred::Cur { plane: 2, stride: chroma_w, off: 0 }) + ( + Pred::Cur { + plane: 0, + stride: SIDE, + off: 0, + }, + Pred::Cur { + plane: 1, + stride: chroma_w, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: chroma_w, + off: 0, + }, + ) } else { // The interintra predictor reads this block's own above/left // edges, which are already written at this point. @@ -2194,7 +2072,6 @@ pub(super) fn decode_inter_block8( } } } else { - crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]); if mode >= 13 { return Err(unsupported( @@ -2214,19 +2091,6 @@ pub(super) fn decode_inter_block8( } else { 0 }; - if angle_delta_y != 0 { - hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); - // lane-leaf8tx r1: `av1_use_angle_delta(BLOCK_8X8)` is true - // (`bsize >= BLOCK_8X8`), so this leaf codes `angle_delta_y` off - // `angle_delta_cdf[mode - V_PRED]` exactly as a key-frame block - // does (libaom `read_intra_angle_info` inside - // `read_intra_block_mode_info`, decodemv.c), and the delta feeds - // the directional predictor + the edge filter/upsample decision - // through the same `reconstruct` argument below. Counted - // separately from the >=16x16 arm so the gate cannot be satisfied - // by a bigger block. - hit!(INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS); - } // lane-uv8 r1: the delta'd angle decides the intra edge filter, and a // directional luma mode is already legal on this leaf -- the arm // passed a hardcoded `false` where [`decode_leaf8`] reads the @@ -2256,42 +2120,20 @@ pub(super) fn decode_inter_block8( let uv_mode = if !has_chroma { DC_PRED } else if cfl_allowed_px(SIDE, SIDE, fctx) { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}", - leaf_mi.0, - leaf_mi.1, - fctx.enable_filter_intra_inter.with(std::cell::Cell::get), - dec.debug_state().0 - ); - } - if (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - hit!(INTRA_IN_INTER8_UV_SMOOTH_HITS); - } let alpha = if has_chroma && uv_mode == UV_CFL_PRED { - hit!(INTRA_IN_INTER8_UV_CFL_HITS); Some(read_cfl_alphas(dec, cdfs)) } else { None }; let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); - hit!(INTRA_IN_INTER8_UV_DIR_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; - if angle_delta_uv != 0 { - hit!(UV_ANGLE_DELTA_HITS); - hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); - } // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED`. uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED @@ -2333,16 +2175,6 @@ pub(super) fn decode_inter_block8( let use_palette_uv = has_chroma && uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; - if crate::envflags::env_flag!("EC_PALSYN") { - eprintln!( - "EC_PALSYN leaf8 mi={},{} bw=8 bh=8 mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", - leaf_mi.0, - leaf_mi.1, - palette_y_pending.map_or(0, |(n, _)| n), - u8::from(use_palette_uv), - dec.debug_state().0 - ); - } if use_palette_uv { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); @@ -2362,7 +2194,6 @@ pub(super) fn decode_inter_block8( // prints `use_filter_intra` for an intra block inside an INTER frame // and nothing else, so this leaf needs the same two lines for a // range-ladder diff against it. - let ec_istep8 = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); if mode == DC_PRED && fctx.enable_filter_intra_inter.with(std::cell::Cell::get) // `av1_filter_intra_allowed` (reconintra.h:77) excludes a @@ -2371,27 +2202,8 @@ pub(super) fn decode_inter_block8( && let Some(class) = filter_intra_size_class(SIDE) { let use_fi = dec.symbol(&mut cdfs.filter_intra[class]) != 0; - if ec_istep8 { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={} rng={}", - leaf_mi.0, - leaf_mi.1, - u8::from(use_fi), - dec.debug_state().0 - ); - } if use_fi { - hit!(FILTER_INTRA_HITS); - hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); let fi = dec.symbol(&mut cdfs.filter_intra_mode); - if ec_istep8 { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}", - leaf_mi.0, - leaf_mi.1, - dec.debug_state().0 - ); - } filter_intra = Some(fi); } } @@ -2407,15 +2219,6 @@ pub(super) fn decode_inter_block8( palette_onscreen(rmi, cmi, SIDE, SIDE, fctx), false, ); - hit!(PALETTE_HITS); - hit!(INTRA_IN_INTER_PALETTE_Y_HITS); - hit_do! { - INTER8_PALETTE_HITS.with(|c| { - let mut v = c.get(); - v.0 += 1; - c.set(v); - }); - } PaletteY { size: n, colors, @@ -2433,15 +2236,6 @@ pub(super) fn decode_inter_block8( (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, chroma_w, chroma_h, on, true); - hit!(PALETTE_UV_HITS); - hit!(INTRA_IN_INTER_PALETTE_UV_HITS); - hit_do! { - INTER8_PALETTE_HITS.with(|c| { - let mut v = c.get(); - v.1 += 1; - c.set(v); - }); - } PaletteUv { size: n, u_colors, @@ -2528,7 +2322,6 @@ pub(super) fn decode_inter_block8( // (the whole-block buffer would be indexed at the wrong // stride by the first unit). if let Some(buf) = &palette_y_buf { - hit!(PALETTE_SPLIT_TX_HITS); let window: Vec = (0..tx_px) .flat_map(|i| { let base = (row * MI + i) * SIDE + col * MI; @@ -2564,10 +2357,6 @@ pub(super) fn decode_inter_block8( read_plane( dec, cdfs, - // Intra 4x4 luma: seven-type - // `EXT_TX_SET_DTT4_IDTX_1DDCT` unless reduced, whose - // CDF row is the intra dir (`fi_tx_row` inside - // `read_plane` maps a filter-intra block's). txbset_for(tx_px, reduced_tx_set), default_scan(tx_px), 0, @@ -2583,7 +2372,6 @@ pub(super) fn decode_inter_block8( tu_py, tx_px, tx_px, - base_q_idx, None, filter_intra, Some(tu_skip_ctx), @@ -2682,14 +2470,6 @@ pub(super) fn decode_inter_block8( read_plane( dec, cdfs, - // lane-uv8 r3: an intra leaf inside an inter frame is - // `is_inter == 0` in `av1_get_ext_tx_set_type`, so its 8x8 - // luma reads the INTRA set -- seven-type - // `EXT_TX_SET_DTT4_IDTX_1DDCT` when `reduced_tx_set == 0`, - // five-type `EXT_TX_SET_DTT4_IDTX` when it is 1. Hardcoding - // the reduced set read the wrong ALPHABET (class - // [[wrong-alphabet-same-value]]) and desynced at the leaf's - // first `tx_type`. txbset_for(8, reduced_tx_set), scan8, 0, @@ -2705,7 +2485,6 @@ pub(super) fn decode_inter_block8( py, SIDE, TX8, - base_q_idx, None, filter_intra, None, @@ -2752,7 +2531,6 @@ pub(super) fn decode_inter_block8( cdfs, neighbours, leaf_mi, - (px, py), (cpx, cpy), SIDE, (chroma_w, chroma_h), @@ -2760,13 +2538,11 @@ pub(super) fn decode_inter_block8( (chroma_w, chroma_h), chroma_w, reach, - (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, - base_q_idx, &mut uo, &mut vo, fctx, @@ -2782,7 +2558,6 @@ pub(super) fn decode_inter_block8( Grid::Own(vo) }; chroma_stamped_per_unit = true; - hit!(LLINTRA8_CHROMA_WALK_HITS); } else { if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); @@ -2830,7 +2605,6 @@ pub(super) fn decode_inter_block8( cpy, chroma_w, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -2884,7 +2658,6 @@ pub(super) fn decode_inter_block8( cpy, chroma_w, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -2989,18 +2762,6 @@ pub(super) fn decode_inter_block8( neighbours.above[leaf_mi.1 + cell][0] = state; } } - // lane-gmaffine r2: the deblock grid's ref id is the leaf's OWN reference - // (r1 taught this leaf non-LAST refs; the hardcoded LAST_FRAME made every - // GOLDEN/ALTREF leaf read as LAST at the loop-filter's ref/mv edge test). - // lane-cdef r1: the fall-through twin of the compound arm's skip-band - // write above -- `skip` is one flag for the whole 8x8 leaf (read at - // `decode.rs`'s `skip_ctx` site), `split8` only splits its transform. - // lane-intersub8 r5: ... and it counts too. r1 incremented the counter in - // the COMPOUND early-return arm only, so the gate's assert really read - // "a COMPOUND 8x8 leaf wrote the band"; once main's inter16ab/r14 routing - // landed, the 10-bit cq12 arm's leaves come through here instead and the - // gate failed on an instrumentation gap, with the band written either way. - hit!(INTER8_SKIP_BAND_HITS); neighbours.fill_skip_grid(leaf_mi, 2, skip); neighbours.fill_lf_grid( leaf_mi, diff --git a/crates/ec-av1/src/decode/inter_ctx.rs b/crates/ec-av1/src/decode/inter_ctx.rs index 1ee02746..6201e05c 100644 --- a/crates/ec-av1/src/decode/inter_ctx.rs +++ b/crates/ec-av1/src/decode/inter_ctx.rs @@ -64,34 +64,13 @@ pub(super) fn resolve_interp_filter( // `h_kind`/`v_kind` argument order, which is why this function returns // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`). let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound); - if crate::envflags::env_flag!("EC_AV1_IFDBG") { - eprintln!( - "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}", - &cdfs.switchable_interp[ctx0][..3] - ); - } let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8; let sym1 = if enable_dual_filter { let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound); - if crate::envflags::env_flag!("EC_AV1_IFDBG") { - eprintln!( - "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}", - &cdfs.switchable_interp[ctx1][..3] - ); - } dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8 } else { sym0 }; - if enable_dual_filter && sym0 != sym1 { - hit!(DUAL_FILTER_DIFF_HITS); - } - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}", - dec.debug_state().0 - ); - } ( mc::InterpFilterKind::from_switchable_symbol(sym1 as usize), mc::InterpFilterKind::from_switchable_symbol(sym0 as usize), @@ -227,7 +206,6 @@ pub(super) fn read_mv( mv.1.clamp(-MV_LIMIT + 1, MV_LIMIT - 1), ); } - crate::census::mv(mv.0, mv.1); mv } @@ -297,13 +275,6 @@ pub(super) fn read_intrabc_dv( true, fctx, ); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_DV mi_row={mi_r} mi_col={mi_c} dv_col={} dv_row={} rng={rng}", - dv.1, dv.0 - ); - } dv } @@ -335,7 +306,6 @@ impl PlaneBuf<'_> { &mut self, x: usize, y: usize, - plane: usize, side: usize, w: usize, h: usize, @@ -363,13 +333,6 @@ impl PlaneBuf<'_> { // prediction is byte-identical to the oracle's and whose committed // samples are not can only be a DIFFERENT WRITE -- and this is the // only write path with no rung of its own. - if crate::envflags::env_flag!("EC_MCWR") { - eprintln!( - "EC_MCWR x={x} y={y} side={side} w={w} h={h} empty_res={} at {}", - residual.is_empty(), - std::panic::Location::caller() - ); - } // lane-av1444altref r2: EC_CPRED, the picture-independent twin of the // oracle's rung of the same name (aomdec's // `dec_build_inter_predictor`). This is the ONE site every inter @@ -380,33 +343,6 @@ impl PlaneBuf<'_> { // pictures, so a rung line alone is ambiguous, but a geometry whose // samples differ by at most 1 is a unique match (any wrong pairing // differs by tens). - // Env: EC_CPRED="x:y" (plane-absolute origin; -1 for either = any). - if let Ok(spec) = crate::envflags::var("EC_CPRED") { - let (fx, fy): (i64, i64) = spec - .split_once(':') - .and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?))) - .unwrap_or((-1, -1)); - let hit = (fx < 0 || fx == x as i64) && (fy < 0 || fy == y as i64); - if hit { - // `PREFILT_PICTURE_IDX` is bumped once per frame just AFTER - // that frame's last block, so it still reads this frame's own - // decode-order index here -- the same numbering the oracle's - // `aom_ec_pict_idx` and the `.fN` prefilter dumps use. - let pict = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst); - eprintln!( - "OUR_CPRED pict={pict} plane={plane} x={x} y={y} w={w} h={h} side={side}" - ); - for row in 0..h { - let src = &prediction[row * side..row * side + w]; - let mut line = String::with_capacity(w * 4); - for v in src { - line.push(' '); - line.push_str(&v.to_string()); - } - eprintln!("OUR_CPROW{row}:{line}"); - } - } - } // lane-recoparse: an all-zero residual (60% of the units) is a plain // prediction copy -- the same arithmetic with `r == 0`, without // reading `side * h` zeros out of [`ZERO_RESIDUAL`]. @@ -416,9 +352,8 @@ impl PlaneBuf<'_> { let dst = (y + row) * self.width + x; let pred = &prediction[src..src + w]; let out = &mut self.data.to_mut()[dst..dst + w]; - for (col, (o, &p)) in out.iter_mut().zip(pred).enumerate() { + for (o, &p) in out.iter_mut().zip(pred) { let v = i32::from(p).clamp(0, max) as u16; - pix_write("mc_copy", x, y, w, x + col, y + row, *o, v); *o = v; } } @@ -431,9 +366,8 @@ impl PlaneBuf<'_> { let pred = &prediction[src..src + w]; let res = &residual[src..src + w]; let out = &mut self.data.to_mut()[dst..dst + w]; - for (col, ((o, &p), &r)) in out.iter_mut().zip(pred).zip(res).enumerate() { + for ((o, &p), &r) in out.iter_mut().zip(pred).zip(res) { let v = (i32::from(p) + r).clamp(0, max) as u16; - pix_write("mc_add", x, y, w, x + col, y + row, *o, v); *o = v; } } @@ -485,8 +419,6 @@ pub(super) fn read_inter_plane( if plane_idx > 0 && mono(fctx) { return Ok((Grid::Zero(side * side), TxType::DctDct)); } - // lane-av1readcensus: the units read from here on are this plane's. - set_census_plane(plane_idx); let skip_ctx = if plane_idx == 0 { luma_skip_ctx.unwrap_or(0) } else { @@ -527,12 +459,6 @@ pub(super) fn read_inter_plane( default_tx_type, None, )?; - note_chroma_class1(plane_idx, tx_type); - if crate::envflags::env_flag!("EC_TRACE_TXTYPE") { - eprintln!( - "OUR_TXTYPE plane={plane_idx} x={x} y={cy} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}" - ); - } // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the // caller hands the 32-point `scan` there, and the coded corner goes into @@ -578,7 +504,6 @@ pub(super) fn read_intra_chroma_lossless( cdfs: &mut Cdfs, neighbours: &mut Neighbours, at_mi: (usize, usize), - (px, py): (usize, usize), (cpx, cpy): (usize, usize), side: usize, (blk_w, blk_h): (usize, usize), @@ -586,13 +511,11 @@ pub(super) fn read_intra_chroma_lossless( (reg_w, reg_h): (usize, usize), stride: usize, reach: Reach, - (frame_w, frame_h): (usize, usize), mode: usize, uv_predict_mode: usize, angle_delta_uv: i32, palette_uv_bufs: Option<(&[u16], &[u16])>, smooth_neighbor_uv: bool, - base_q_idx: u8, u_out: &mut Vec, v_out: &mut Vec, fctx: &crate::decode::FrameCtx, @@ -635,11 +558,6 @@ pub(super) fn read_intra_chroma_lossless( 4 << ss_x(fctx), 4 << ss_y(fctx), reach, - px, - py, - frame_w, - frame_h, - fctx, ); if let Some((ub, vb)) = palette_uv_bufs { let buf = if plane_idx == 1 { ub } else { vb }; @@ -663,7 +581,6 @@ pub(super) fn read_intra_chroma_lossless( cpy + oy, 4, 4, - base_q_idx, None, None, offset, @@ -679,7 +596,6 @@ pub(super) fn read_intra_chroma_lossless( plane_idx, &cu_grid, ); - hit!(CHROMA_SPLIT_TX_HITS); let dst = mu_units( if plane_idx == 1 { &mut *u_out @@ -738,9 +654,6 @@ pub(super) fn mu_chunk_order( let mut order = identity.clone(); order.sort_by_key(|&i| ((leaves[i].0 / 16) * nchunk + (leaves[i].1 / 16), i)); let changed = order != identity; - if changed { - hit!(MU_CHUNK_ORDER_HITS); - } (order, changed) } @@ -788,10 +701,6 @@ pub(super) fn read_inter_chroma_lossless( // lane-av1h5: a plane block above 64 is the 128-root class, whose chroma // libaom walks one 64x64 mu chunk at a time. Counted so a gate can pin // the walk/unit totals exactly rather than as a floor on wrong output. - let counted_128 = blk_w > 64 || blk_h > 64; - if counted_128 { - hit!(MU_CHUNK_WALKS); - } for plane_idx in 1..3 { for rr in 0..reg_h / 4 { for cc in 0..reg_w / 4 { @@ -851,10 +760,6 @@ pub(super) fn read_inter_chroma_lossless( plane_idx, &cu_grid, ); - hit!(CHROMA_SPLIT_TX_HITS); - if counted_128 { - hit!(MU_CHUNK_WALK_UNITS); - } let dst = mu_units( if plane_idx == 1 { &mut *u_out @@ -1018,19 +923,6 @@ pub(super) fn read_single_ref( if p4 == 1 { LAST2_FRAME } else { LAST_FRAME } } }; - if ref_frame != LAST_FRAME { - hit!(NON_LAST_REF_HITS); - let c = match ref_frame { - LAST2_FRAME => &LAST2_HITS, - LAST3_FRAME => &LAST3_HITS, - GOLDEN_FRAME => &GOLDEN_HITS, - BWDREF_FRAME => &BWDREF_HITS, - ALTREF2_FRAME => &ALTREF2_HITS, - ALTREF_FRAME => &ALTREF_HITS, - _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"), - }; - hit_do! { c.with(|v| v.set(v.get() + 1)); } - } ref_frame } @@ -1070,9 +962,8 @@ pub(crate) struct RefPix<'p> { #[derive(Clone)] pub(crate) struct SharedRefs { pub(crate) dims: [Option<(usize, usize)>; 8], - pub(crate) wait: std::sync::Arc< - dyn Fn() -> Result<[Option>; 8]> + Send + Sync, - >, + pub(crate) wait: + std::sync::Arc Result<[Option>; 8]> + Send + Sync>, } /// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait @@ -1207,12 +1098,6 @@ impl<'p> RefPix<'p> { /// (lane-defer8). pub(super) fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> { refpix.dims(ref_frame).ok_or_else(|| { - if crate::envflags::env_flag!("EC_AV1_REFPROBE") { - eprintln!( - "EC_REFPROBE missing ref {ref_frame}\n{}", - std::backtrace::Backtrace::force_capture() - ); - } // lane-hdrlossless: libaom errors on the same stream // (`decodeframe.c:5027`: `if (cm->ref_frame_map[ref] == NULL) // aom_internal_error(... AOM_CODEC_CORRUPT_FRAME, "Inter frame @@ -1406,9 +1291,6 @@ pub(super) fn overlappable_above( if let Some(info) = nb && info.is_inter { - if src != col { - hit!(OBMC_PAIR_FILTER_HITS); - } // lane-t900 r14: libaom passes `AOMMIN(xd->width, mi_step)` // as `op_mi_size` -- the block's OWN width, never the // frame-edge clamp `end_col` carries. Clamping here shrank the @@ -1473,9 +1355,6 @@ pub(super) fn overlappable_left( if let Some(info) = nb && info.is_inter { - if src != row { - hit!(OBMC_PAIR_FILTER_HITS); - } // lane-t900 r14: `AOMMIN(xd->height, mi_step)` -- see // `overlappable_above`. out.push(( @@ -1509,23 +1388,6 @@ pub(crate) fn has_overlappable_neighbour( || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty() } -/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples` -/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2: -/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128` -/// libaom's mask loop runs one level further and strips the top-right sample -/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame -/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates -/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is -/// the block's own side in 4x4 (`mi`) units (square inter leaves only here). -pub(super) fn has_top_right( - mi_row: usize, - mi_col: usize, - bs: usize, - fctx: &crate::decode::FrameCtx, -) -> bool { - crate::mvstack::has_top_right(mi_row, mi_col, bs, bs, fctx) -} - /// `av1_findSamples` (`mvref_common.c`), full port: the up to /// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour /// samples (`record_samples`) that share this block's own single reference @@ -1557,16 +1419,8 @@ pub(crate) fn find_samples( // motion_mode alphabet over the 2-symbol obmc one. // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on // every warp block; the flag itself is a process constant. - let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI") - && crate::envflags::var("EC_PROJ_MI").is_ok_and(|v| v == format!("{mi_row},{mi_col}")); let single_ref_match = |info: &MiInfo| { let m = info.ref_frame == ref_frame && info.ref_frame1 == NO_REF1; - if proj_dbg { - eprintln!( - "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}", - info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter - ); - } m }; let mut do_tl = true; @@ -1682,9 +1536,6 @@ pub(crate) fn find_samples( // libaom reads the 2-symbol `obmc_cdf` (class // wrong-alphabet-same-value). let tr_reach = crate::mvstack::has_top_right(mi_row, mi_col, bw4, bh4, fctx); - if do_tr && bw4 != bh4 && tr_reach != has_top_right(mi_row, mi_col, bw4, fctx) { - hit!(TR_REACH_LONGER_SIDE_HITS); - } if do_tr && tr_reach { let tr_col = mi_col + bw4; if mi_row > 0 @@ -1785,53 +1636,12 @@ pub(super) fn neighbour_filter( "an OBMC neighbour whose switchable interp filter was never recorded", )); } - hit!(OBMC_FILTER_BAND_READS); Ok(( mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize), mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize), )) } -/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose -/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel -/// -- names the neighbour's own position/shape/reference so the decode path that -/// failed to record its filter can be identified. Read-only, off by default. -#[allow(clippy::too_many_arguments)] -fn obmcrec_probe( - dir: &str, - mi_row: usize, - mi_col: usize, - write_w: usize, - write_h: usize, - off4: usize, - span4: usize, - nb: &MiInfo, - syms: [u8; 2], - cell: Option, - fixed: bool, -) { - if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") { - return; - } - eprintln!( - "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \ -span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \ -nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}", - nb.size * 4, - nb.size_h * 4, - nb.ref_frame, - nb.ref_frame1, - nb.mv.0, - nb.mv.1, - nb.is_new_mv, - cell.map(|c| (c.size * 4, c.size_h * 4)), - cell.map(|c| c.is_inter), - cell.map(|c| c.ref_frame), - mi_row % 32, - mi_col % 32, - ); -} - /// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh /// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor` /// under `av1_setup_build_prediction_by_{above,left}_pred`). @@ -2060,71 +1870,6 @@ fn obmc_blend_h( } } -/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block -- -/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to -/// the instrumented aomdec's `backup_mbmi.bsize`. -fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 { - match (w4, h4) { - (1, 1) => 0, - (1, 2) => 1, - (2, 1) => 2, - (2, 2) => 3, - (2, 4) => 4, - (4, 2) => 5, - (4, 4) => 6, - (4, 8) => 7, - (8, 4) => 8, - (8, 8) => 9, - (8, 16) => 10, - (16, 8) => 11, - (16, 16) => 12, - (1, 4) => 16, - (4, 1) => 17, - (2, 8) => 18, - (8, 2) => 19, - (4, 16) => 20, - (16, 4) => 21, - _ => -1, - } -} - -/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented -/// aomdec's own byte format (`decodeframe.c` -/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC -/// neighbour lists diff line for line. `filt` is libaom's packed -/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`. -#[allow(clippy::too_many_arguments)] -fn ec_obmc_trace( - dir: &str, - mi_row: usize, - mi_col: usize, - write_w: usize, - write_h: usize, - rel: usize, - op: usize, - nb: &MiInfo, - h_kind: mc::InterpFilterKind, - v_kind: mc::InterpFilterKind, -) { - if !crate::envflags::env_flag!("EC_OBMC") { - return; - } - let sym = |k: mc::InterpFilterKind| match k { - mc::InterpFilterKind::Smooth => 1u32, - mc::InterpFilterKind::Sharp => 2, - _ => 0, - }; - eprintln!( - "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \ -nbmv=({},{}) nbref={} nbbsize={} filt={}", - nb.mv.0, - nb.mv.1, - nb.ref_frame, - ec_obmc_bsize(nb.size as usize, nb.size_h as usize), - sym(v_kind) | (sym(h_kind) << 16), - ); -} - /// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts /// the overlap strip against each bordering above/left inter neighbour's own /// mv/ref/filter and blends it into this block's just-built single-reference @@ -2201,9 +1946,6 @@ pub(crate) fn obmc_plan( // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf; re-measured // byte-exact against an instrumented aomdec, the refusal is gone and the // counter below is what the gate's `--enable-obmc=1` arm reads. - if matches!((write_w, write_h), (16, 8) | (8, 16)) { - hit!(OBMC_RECT_LEAF_HITS); - } // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own // half (`reconinter.c` 860/899), inert below 128. let overlap_above = write_h.min(64) / 2; @@ -2233,27 +1975,8 @@ pub(crate) fn obmc_plan( // `av1_setup_build_prediction_by_above_pred` reads // `above_mbmi->interp_filters`). let above_syms = above_filter.get(mi_col + src4).copied().unwrap_or([3; 2]); - obmcrec_probe( - "above", - mi_row, - mi_col, - write_w, - write_h, - off4, - span4, - &nb, - above_syms, - grid.get(mi_row - 1, mi_col + src4), - interp_fixed.is_some(), - ); let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?; - ec_obmc_trace( - "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind, - ); let nb_dims = ref_dims(nb.ref_frame, refpix)?; - if mi_col + off4 + span4 > mi_cols { - hit!(OBMC_EDGE_SPAN_HITS); - } above.push(ObmcNb { off4, span4, @@ -2269,27 +1992,8 @@ pub(crate) fn obmc_plan( overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) { let left_syms = left_filter.get(mi_row + src4).copied().unwrap_or([3; 2]); - obmcrec_probe( - "left", - mi_row, - mi_col, - write_w, - write_h, - off4, - span4, - &nb, - left_syms, - grid.get(mi_row + src4, mi_col - 1), - interp_fixed.is_some(), - ); let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?; - ec_obmc_trace( - "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind, - ); let nb_dims = ref_dims(nb.ref_frame, refpix)?; - if mi_row + off4 + span4 > mi_rows { - hit!(OBMC_EDGE_SPAN_HITS); - } left.push(ObmcNb { off4, span4, @@ -2405,41 +2109,6 @@ pub(crate) fn obmc_run( // block, reused by every neighbour of the above and left passes. let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new()); - // lane-t900 r13 rung: EC_MCB="::[:]" (chroma plane - // 1 only; : are chroma-plane pixels, the oracle's own dump - // window) prints this block's chroma prediction rows before and after the - // OBMC blend, matching the instrumented aomdec's EC_MCB dump. - let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB") - .then(|| crate::envflags::var("EC_MCB").ok()) - .flatten() - .and_then(|v| { - let f: Vec<&str> = v.split(':').collect(); - if f.len() < 3 || f[0] != "1" { - return None; - } - let (x, y) = (f[1].parse::().ok()?, f[2].parse::().ok()?); - let fr = f.get(3).and_then(|s| s.parse::().ok()).unwrap_or(-1); - let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64; - // lane-av1ecmcb: the window is the CHROMA plane's own write region -- - // the oracle's EC_MCB spans are plane pixels, and at 4:4:4 (ss 0/0) - // the chroma block is full-size, so nothing halves. The old - // `write_w / 2` was a 4:2:0-era assumption that quartered the window - // (and the dumps below) at ss 0/0. - let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx)); - if x >= cpx && x < cpx + cw && y >= cpy && y < cpy + ch && (fr < 0 || fr == idx) { - Some((x, y, idx)) - } else { - None - } - }); - if let Some((_, _, idx)) = ec_mcb { - let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx)); - eprintln!("OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={cw} ch={ch}"); - for r in 0..ch { - let row: Vec = (0..cw).map(|c| pred_u[r * chroma_stride + c]).collect(); - eprintln!("OUR_MCB prerow{r}: {row:?}"); - } - } for nb in &plan.above { let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else { return; @@ -2547,16 +2216,6 @@ pub(crate) fn obmc_run( &mut tmp_u, fctx, ); - if let Some((_, _, idx)) = ec_mcb { - eprintln!( - "OUR_MCB left f={idx} off4={} span4={} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}", - nb.off4, nb.span4, nb.mv.0, nb.mv.1, nb.ref_frame - ); - for r in 0..cbh { - let row: Vec = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect(); - eprintln!("OUR_MCB lrow{r}: {row:?}"); - } - } let ch = cbh.min((write_h >> ss_y(fctx)) - coy); obmc_blend_h(pred_u, chroma_stride, 0, coy, cbw, ch, &tmp_u); obmc_neighbour_pred( @@ -2575,13 +2234,6 @@ pub(crate) fn obmc_run( ); obmc_blend_h(pred_v, chroma_stride, 0, coy, cbw, ch, &tmp_v); } - if let Some((_, _, idx)) = ec_mcb { - let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx)); - for r in 0..ch { - let row: Vec = (0..cw).map(|c| pred_u[r * chroma_stride + c]).collect(); - eprintln!("OUR_MCB post f={idx} row{r}: {row:?}"); - } - } } /// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to @@ -2714,18 +2366,6 @@ pub(super) fn read_comp_mode( ) -> bool { let ctx = reference_mode_ctx(above, left); let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1; - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_RCM ctx={ctx} val={} a={:?} l={:?} rng={}", - usize::from(compound), - above.map(|n| (n.is_inter, n.ref0, n.ref1)), - left.map(|n| (n.is_inter, n.ref0, n.ref1)), - dec.debug_state().0 - ); - } - if compound { - hit!(COMP_MODE_HITS); - } compound } @@ -2767,7 +2407,6 @@ pub(super) fn read_compound_ref_frames( let type_ctx = comp_reference_type_ctx(above, left); let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0; if unidir { - hit!(UNI_COMP_HITS); // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_- // uni_comp_ref_p is single_ref_p1's own forward/backward vote. let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]); @@ -2829,7 +2468,6 @@ pub(super) fn read_inter_compound_mode( ref_mv_ctx: usize, ) -> u8 { let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)]; - hit!(COMPOUND_MODE_HITS); dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8 } @@ -3031,17 +2669,3 @@ thread_local! { /// chroma plane -- the non-vacuity bar for the assertion at that site. pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI: std::cell::Cell = const { std::cell::Cell::new(0) }; } - -/// [`CHROMA_RECT_BLOCK_TX_FALLBACK`]: rect chroma units handed the block-level -/// type because no luma leaf covered their own MI cell. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_rect_block_tx_fallback() -> usize { - CHROMA_RECT_BLOCK_TX_FALLBACK.with(std::cell::Cell::get) -} - -/// [`CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI`]: of those, the ones whose chroma -/// plane had more than one unit. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn chroma_rect_block_tx_fallback_multi() -> usize { - CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI.with(std::cell::Cell::get) -} diff --git a/crates/ec-av1/src/decode/inter_intra_arm.rs b/crates/ec-av1/src/decode/inter_intra_arm.rs index b876dc98..cc59b00a 100644 --- a/crates/ec-av1/src/decode/inter_intra_arm.rs +++ b/crates/ec-av1/src/decode/inter_intra_arm.rs @@ -132,25 +132,6 @@ pub(super) fn decode_inter_block_intra_arm( .filter(|_| write_w.min(write_h) == 4 && write_w.max(write_h) == 16) .map(|s| (s.horz, s.has_chroma)); if write_w.min(write_h) < 8 && strip16.is_none() { - if crate::envflags::env_flag!("EC_INTRA16X4") { - let (idx, hc, prev_inter) = match strip_chroma { - Some(s) => ( - if s.horz { - rmi - s.pair_mi.0 - } else { - cmi - s.pair_mi.1 - }, - s.has_chroma, - s.prev.is_some(), - ), - None => (9, true, false), - }; - eprintln!( - "EC_INTRA16X4 w={write_w} h={write_h} pair_parity={idx} has_chroma={hc} prev_single_inter={prev_inter} skip={skip} mi={rmi},{cmi} tx_select={} scr={}", - fctx.tx_select_inter.with(std::cell::Cell::get), - allow_screen_content_tools, - ); - } return Err(unsupported( "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)", )); @@ -215,14 +196,7 @@ pub(super) fn decode_inter_block_intra_arm( ); return Ok(None); } - crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]); - if crate::envflags::env_flag!("EC_IIS") { - eprintln!( - "TRACE iis px={px} py={py} side={side} w={write_w} h={write_h} sg={} mode={mode} skip={skip}", - size_group_wh(write_w, write_h) - ); - } if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", @@ -241,9 +215,6 @@ pub(super) fn decode_inter_block_intra_arm( } else { 0 }; - if angle_delta_y != 0 { - hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); - } // The delta'd angle decides whether the intra edge filter runs at // all, so this block needs the same luma edge-filter-type neighbour // check a key-frame block does (`get_intra_edge_filter_type`, spec @@ -263,21 +234,13 @@ pub(super) fn decode_inter_block_intra_arm( // (libaom `decodemv.c:933`). let has_chroma = !mono(fctx); let cfl_allowed = has_chroma && cfl_allowed_px(write_w, write_h, fctx); - if !cfl_allowed { - hit!(NOCFL_UV_MODE_HITS); - } let uv_mode = if !has_chroma { DC_PRED } else if cfl_allowed { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; - if (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - } let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { @@ -288,15 +251,10 @@ pub(super) fn decode_inter_block_intra_arm( // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the // `else` branch below is exact for it either way. let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; - if angle_delta_uv != 0 { - hit!(UV_ANGLE_DELTA_HITS); - hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); - } uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { @@ -336,24 +294,9 @@ pub(super) fn decode_inter_block_intra_arm( let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]); palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx))); } - if crate::envflags::env_flag!("EC_PALSYN") { - eprintln!( - "EC_PALSYN_PRE sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} rng={}", - palette_y_pending.map_or(0, |(n, _)| n), - dec.debug_state().0 - ); - } let use_palette_uv = has_chroma && uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; - if crate::envflags::env_flag!("EC_PALSYN") { - eprintln!( - "EC_PALSYN sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", - use_palette_y as i32, - use_palette_uv as i32, - dec.debug_state().0 - ); - } if use_palette_uv { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); @@ -379,8 +322,6 @@ pub(super) fn decode_inter_block_intra_arm( && let Some(class) = filter_intra_size_class_rect(write_w, write_h) && dec.symbol(&mut cdfs.filter_intra[class]) != 0 { - hit!(FILTER_INTRA_HITS); - hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); } // `av1_visit_palette`: the two colour-index maps, Y then the shared @@ -395,8 +336,6 @@ pub(super) fn decode_inter_block_intra_arm( palette_onscreen(rmi, cmi, write_w, write_h, fctx), false, ); - hit!(PALETTE_HITS); - hit!(INTRA_IN_INTER_PALETTE_Y_HITS); PaletteY { size: n, colors, @@ -419,8 +358,6 @@ pub(super) fn decode_inter_block_intra_arm( (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true); - hit!(PALETTE_UV_HITS); - hit!(INTRA_IN_INTER_PALETTE_UV_HITS); PaletteUv { size: n, u_colors, @@ -516,7 +453,6 @@ pub(super) fn decode_inter_block_intra_arm( // (the whole-block buffer would be indexed at the wrong // stride by the first unit). if let Some(buf) = &palette_y_buf { - hit!(PALETTE_SPLIT_TX_HITS); let window: Vec = (0..tx_px) .flat_map(|i| { let base = (row * MI + i) * side + col * MI; @@ -553,10 +489,6 @@ pub(super) fn decode_inter_block_intra_arm( dec, cdfs, txbset_for(tx_px, reduced), - // lane-sb128c r5: a TX_64X64 unit codes only its - // top-left 32x32 of frequencies (spec 5.11.40), so - // the scan and `tx_side` are the CODED corner while - // `side` stays the transform's true 64. default_scan(tx_px.min(32)), 0, neighbours.around_mi(tu_mi, tx_px)[0], @@ -571,7 +503,6 @@ pub(super) fn decode_inter_block_intra_arm( tu_py, tx_px, tx_px.min(32), - base_q_idx, None, filter_intra, Some(tu_skip_ctx), @@ -588,7 +519,6 @@ pub(super) fn decode_inter_block_intra_arm( continue; } let (cr, cc) = chunk; - hit!(INTRA_128_IN_INTER_MU_CHROMA_HITS); // The unit's CHROMA size, its LUMA footprint, the // CHUNK's chroma extent and the unit's ORIGIN inside the // chunk are four different quantities; this arm had the @@ -641,32 +571,18 @@ pub(super) fn decode_inter_block_intra_arm( cdfs, neighbours, at_mi, - (px, py), (cpx, cpy), side, - // lane-av1422lpf site 6 (the intra-in-inter twin of - // site 5 at 41572): the plane block's own per-axis - // shape and stride, never the enclosing square. - // `palette_uv_bufs` is the decoded colour-index map - // at `(write_w >> ss_x, write_h >> ss_y)` (44144), - // i.e. per-axis already, and the lossless walk - // windows it at this `stride` -- at 4:2:2 a - // 16-wide square stride over an 8-wide map put the - // third unit row at index 180 of 128 samples - // (`palette_window`, decode.rs:2946; measured on - // `Y_intrabc_10b.obu`). (chroma_stride, chroma_buf_h), (cc * chunk_chroma_w, cr * chunk_chroma_h), (chunk_chroma_w, chunk_chroma_h), chroma_stride, reach, - (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, - base_q_idx, &mut u_units, &mut v_units, fctx, @@ -718,11 +634,6 @@ pub(super) fn decode_inter_block_intra_arm( cr * chunk_luma + ur * unit_luma_h, unit_luma_w, reach, - px, - py, - y.width, - y.height, - fctx, ); let cu_grid = if skip { push_intra( @@ -762,15 +673,8 @@ pub(super) fn decode_inter_block_intra_arm( cu_y, cu_tx, cu_tx, - base_q_idx, - // CfL is refused above 32x32 - // (`is_cfl_allowed`), so never here. None, None, - // The uv plane block is larger than - // the unit: `get_txb_ctx`'s offset-10 - // rows, +3 on the `txb_skip_chroma_32` - // table (lane-sb128b r3). Some(3), smooth_neighbor_uv, fctx, @@ -785,7 +689,6 @@ pub(super) fn decode_inter_block_intra_arm( plane_idx, &cu_grid, ); - hit!(CHROMA_SPLIT_TX_HITS); // lane-dpm1: the two INTER mu-chunk sites set // this and this INTRA-in-inter one did not, so // the whole-block chroma record below re-stamped @@ -794,9 +697,6 @@ pub(super) fn decode_inter_block_intra_arm( // libaom never selects (class // `override-slot-on-one-arm`). mu_chroma = true; - // lane-av1muchunk422b: the allocation of the intra-in-inter - // mu-chunk walk (site 8), per TX_32X32 unit. - hit!(MU_CHUNK_INTRA_IN_INTER_UNITS); let dst = mu_units( if plane_idx == 1 { &mut u_units @@ -846,7 +746,6 @@ pub(super) fn decode_inter_block_intra_arm( } else { Grid::Own(std::mem::take(&mut v_units)) }; - hit!(INTRA_128_IN_INTER_HITS); } else if skip { if !split_luma { if let Some(buf) = &palette_y_buf { @@ -945,7 +844,6 @@ pub(super) fn decode_inter_block_intra_arm( py, side, luma_tx, - base_q_idx, None, filter_intra, None, @@ -966,26 +864,18 @@ pub(super) fn decode_inter_block_intra_arm( cdfs, neighbours, at_mi, - (px, py), (cpx, cpy), side, - // lane-av1422lpf site 6 (the whole-block twin of the mu - // chunk fix at 44374): the plane block's own per-axis shape - // and its own stride, never the enclosing square - // `chroma_side`. At 4:2:0 and 4:4:4 all three are the same - // number. (chroma_stride, chroma_buf_h), (0, 0), (chroma_stride, chroma_buf_h), chroma_stride, reach, - (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, - base_q_idx, &mut uo, &mut vo, fctx, @@ -1035,11 +925,6 @@ pub(super) fn decode_inter_block_intra_arm( cu_row * chroma_tx, chroma_tx, reach, - px, - py, - y.width, - y.height, - fctx, ); let cu_grid = read_plane( dec, @@ -1059,9 +944,6 @@ pub(super) fn decode_inter_block_intra_arm( cpy + cu_row * chroma_tx, chroma_tx, chroma_tx, - base_q_idx, - // CfL is capped at 32x32 (`is_cfl_allowed`), - // so a block this size never carries alpha. None, None, Some(3), @@ -1072,7 +954,6 @@ pub(super) fn decode_inter_block_intra_arm( // coefficient context. neighbours .record_mi_chroma(cu_mi, chroma_tx, chroma_tx, plane_idx, &cu_grid); - hit!(CHROMA_SPLIT_TX_HITS); let acc = if plane_idx == 1 { &mut u_acc } else { @@ -1123,7 +1004,6 @@ pub(super) fn decode_inter_block_intra_arm( cpy, chroma_side, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -1161,11 +1041,6 @@ pub(super) fn decode_inter_block_intra_arm( luma_span_x, luma_span_y, reach, - px, - py, - y.width, - y.height, - fctx, ); // The 4:2:2 plane block is `(chroma_w, chroma_h)` -- // 32x64 -- but codes TWO stacked TX_32X32 units, so @@ -1181,7 +1056,6 @@ pub(super) fn decode_inter_block_intra_arm( fctx, ); } - hit!(PALETTE_422_UNIT_WINDOW_HITS); let cu_grid = read_plane( dec, cdfs, @@ -1200,18 +1074,12 @@ pub(super) fn decode_inter_block_intra_arm( cpy + cu_row * cu_h, cu_w, cu_w, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, - // The uv plane block (32x64) is larger than the unit - // (32x32): `get_txb_ctx`'s offset-10 rows, +3 on the - // `txb_skip_chroma_32` table (lane-sb128b r3). Some(3), smooth_neighbor_uv, fctx, )?; - hit!(CHROMA_SPLIT_TX_HITS); - hit!(CHROMA422_SQUARE_HITS); // Immediately, so the next unit of this plane reads this // one's coefficient context; the whole-block record below // re-stamps the block over these and the tail's @@ -1280,7 +1148,6 @@ pub(super) fn decode_inter_block_intra_arm( cpy, chroma_side, chroma_tx, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -1309,11 +1176,6 @@ pub(super) fn decode_inter_block_intra_arm( luma_span_x, luma_span_y, reach, - px, - py, - y.width, - y.height, - fctx, ); // The V twin of the U arm's per-unit window above. if let Some((_, vb)) = &palette_uv_bufs { @@ -1322,7 +1184,6 @@ pub(super) fn decode_inter_block_intra_arm( fctx, ); } - hit!(PALETTE_422_UNIT_WINDOW_HITS); let cu_grid = read_plane( dec, cdfs, @@ -1341,15 +1202,12 @@ pub(super) fn decode_inter_block_intra_arm( cpy + cu_row * cu_h, cu_w, cu_w, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, Some(3), smooth_neighbor_uv, fctx, )?; - hit!(CHROMA_SPLIT_TX_HITS); - hit!(CHROMA422_SQUARE_HITS); neighbours.record_mi_chroma(cu_mi, luma_span_x, luma_span_y, 2, &cu_grid); for rr in 0..cu_h { let start = (cu_row * cu_h + rr) * chroma_side; diff --git a/crates/ec-av1/src/decode/inter_shapes.rs b/crates/ec-av1/src/decode/inter_shapes.rs index e8ad0582..25806e0a 100644 --- a/crates/ec-av1/src/decode/inter_shapes.rs +++ b/crates/ec-av1/src/decode/inter_shapes.rs @@ -81,11 +81,6 @@ pub(super) fn read_block_tx_size( // // The RECT twin [`read_block_tx_size_rect`] has published on this arm // since lane-av1lm444loss; only the square arm had the hole. - let pub_above: u8 = if skip && is_inter { - (side_mi * MI) as u8 - } else { - 4 - }; // The gate's non-vacuity arm, on the DECISION, sampled BEFORE the // write: this publish CHANGES at least one of the above-band cells it // covers -- the cell did not already hold `pub_above`, so a later @@ -104,12 +99,7 @@ pub(super) fn read_block_tx_size( // first-touch case. The count is still a decision (no reader, no // intra-only frame, no unchanged column), so the gate keeps its teeth; // only the doc's stronger reading was wrong. - let overwrote = !fctx.intra_only.with(std::cell::Cell::get) - && (0..side_mi).any(|i| n.above_txfm.get(at_mi.1 + i) != Some(&pub_above)); set_txfm_ctxs(n, at_mi, 4, side_mi, side_mi, skip && is_inter); - if overwrote { - hit!(LOSSLESS_SQ_TXFM_BAND_OVERWRITE_HITS); - } return Ok((4, Some(leaves))); } if !fctx.tx_select_inter.with(std::cell::Cell::get) { @@ -194,13 +184,6 @@ pub(super) fn read_block_tx_size( leaves.push((row, col, tx, tx)); } } - hit_do! { - INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| { - let mut h = c.get(); - h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1; - c.set(h); - }); - } return Ok((tx, Some(leaves))); } Ok((tx, None)) @@ -261,6 +244,7 @@ pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool { // these triples are what decides whether those refusals can fire at all. Bit // 31 is "a triple this table does not list", which is what makes the gate a // census rather than a restatement of its own table. +#[cfg(test)] pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [ (16, 16, 16), (32, 32, 32), @@ -393,9 +377,6 @@ pub(super) fn rect_inter_chroma_set(w: usize, h: usize) -> Result { // (`av1_ss_size_lookup[BLOCK_8X32][1][0]`, common_data.c:38) and // for which no TX_4X32 exists -- that chroma is coded as a // TX_8X32-chunked merge, not a 4-px unit. - if crate::envflags::env_flag!("EC_AV1_TRACE_422") { - eprintln!("EC_422 rect_inter_chroma_set missing (w,h)=({w},{h})"); - } return Err(unsupported( "a rectangular inter chroma transform unit whose shape has no coefficient table set here", )); @@ -508,16 +489,6 @@ fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan( // the shape domain and, on its own, named NONE of the strings that domain // was about -- under a real function boundary rather than a window that // ran into the next test, all three rows read as unanchored. - for refusal in [ - "a rectangular inter luma transform unit whose shape has no coefficient table set here", - "a rectangular inter chroma transform unit whose shape has no coefficient table set here", - "a rectangular transform unit whose shape has no coefficient scan table here", - ] { - assert!( - crate::test_source::module_source("decode").contains(refusal), - "this gate proves {refusal:?}, but that string is no longer in decode.rs" - ); - } let fctx = &crate::decode::FrameCtx::new(); let corner_scan = |w: usize, h: usize| { let (cw, ch) = (w.min(32), h.min(32)); @@ -684,7 +655,6 @@ pub(super) fn read_block_tx_size_rect( // transform, and `set_txfm_ctxs` records exactly what // `txfm_partition_update` would for that same unit. txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); - hit!(RECT_INTER_TU_HITS); return Ok(None); } // lane-av1oddheightfork2: `above_px` / `left_px` are the two @@ -696,24 +666,10 @@ pub(super) fn read_block_tx_size_rect( let (above_px, left_px) = (n.above_txfm[at_mi.1], n.left_txfm[at_mi.0]); let ctx = txfm_partition_ctx_rect(above_px, left_px, bw.max(bh), tx_w, tx_h); let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; - hit!(TXFM_SPLIT_READS); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} above={above_px} left={left_px} maxblk={} tx={tx_w}x{tx_h} rng={rng}", - at_mi.0, - at_mi.1, - u8::from(split), - bw.max(bh), - ); - } if !split { txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh)); - hit!(RECT_INTER_TU_HITS); return Ok(None); } - hit!(TXFM_SPLIT_HITS); - hit!(RECT_INTER_TXSPLIT_HITS); // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`, // `[TX_16X64] == TX_16X32` -- so the recursion below is the general @@ -825,7 +781,6 @@ pub(super) fn read_inter_rect_chroma( // replay (the c8 re-stamp, at the strip's own tiling). let mut units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new(); if multi { - hit!(CHROMA_SPLIT_TX_HITS); assembled = [ vec![0i32; chroma_side * assembled_h], vec![0i32; chroma_side * assembled_h], @@ -862,35 +817,8 @@ pub(super) fn read_inter_rect_chroma( let cu_pred = src.offset(cu_row * uh * chroma_side + cu_col * uw); let inherit_tx_type = if let Some(t) = covering_leaf_tx_type(leaf_tx_types, unit_rel_mi) { - hit!(CHROMA_RECT_LEAF_TX_HITS); - if Some(t) != Some(luma_tx_type) { - hit!(CHROMA_RECT_LEAF_TX_DIFF_HITS); - } Some(t) } else { - // lane-av1ichromatx: the ONE remaining site in - // `decode_inter_block` that can hand a chroma unit a - // BLOCK-level type on a split plane. `covering_leaf_tx_ - // type` found nothing, i.e. no luma leaf covers this - // unit's own MI cell -- which is exactly the shape a - // block that coded a SINGLE luma transform has (its - // leaf list is empty, so every lookup misses). For - // that block `luma_tx_type` IS the type of the one - // luma unit whose stamp covers the whole plane, so the - // fallback is correct there. - // - // What is NOT correct is a fallback on a plane with - // `leaves` NON-empty: then some luma leaf does exist, - // it simply does not cover this unit's cell, and the - // block-level value is a DIFFERENT leaf's type. The - // assertion below is what closes that shape, so the - // fallback can never again be a silent mistype: the - // class is "block-level where the unit's own cell - // says otherwise", and this is its last site. - hit!(CHROMA_RECT_BLOCK_TX_FALLBACK); - if multi { - hit!(CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI); - } debug_assert!( leaf_tx_types.is_empty(), "lane-av1ichromatx: a multi-unit rect chroma plane fell back to the \ @@ -921,9 +849,6 @@ pub(super) fn read_inter_rect_chroma( fctx, )? .0; - if invalid_ss_plane { - hit!(CHROMA422_CHUNK_HITS); - } if multi { // Immediately, so the next unit of this block reads this // one's coefficient context (libaom updates the chroma @@ -985,8 +910,6 @@ pub(super) fn read_inter_plane_rect( if plane_idx > 0 && mono(fctx) { return Ok((Grid::Zero(w * h), TxType::DctDct)); } - // lane-av1readcensus: the units read from here on are this plane's. - set_census_plane(plane_idx); let skip_ctx = if plane_idx == 0 { // `get_txb_ctx_general`: 0 only when this unit IS the whole plane // block; a var-tx leaf passes its own neighbour-table context. @@ -1030,18 +953,6 @@ pub(super) fn read_inter_plane_rect( // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted // rectangular shape (lane-sbpart r8). let (cw, ch) = (w.min(32), h.min(32)); - if plane_idx == 0 && w.max(h) == 64 { - hit!(RECT64_INTER_TU_HITS); - } - if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) { - hit_do! { - RECT32X8_INTER_TU_HITS.with(|c| { - let mut v = c.get(); - v[usize::from(w == 8)] += 1; - c.set(v); - }); - } - } let (corner, tx_type) = if (cw, ch) == (32, 32) { let scan32 = default_scan(TX32); read_coeffs( @@ -1063,16 +974,10 @@ pub(super) fn read_inter_plane_rect( skip_ctx, dc_sign_ctx(around.2), default_tx_type, - plane_idx, )? }; let grid = extend_corner(corner, cw, ch, w, h); let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx); - if crate::envflags::env_flag!("EC_TRACE_TXTYPE") { - eprintln!( - "OUR_TXTYPE plane={plane_idx} x={x} y={cy} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}" - ); - } // `reconstruct_mc_rect` reads both buffers at the square prediction // stride, so the dense `w x h` residual is re-laid at that stride // (`TxParams::stride`) after the inverse transform. @@ -1716,6 +1621,5 @@ pub(super) fn edge_params_body( [4, 8, 14, 14, 14][dim] }; let level = if cur_level != 0 { cur_level } else { pv_level }; - hit!(DEBLOCK_HITS); Some((len, level)) } diff --git a/crates/ec-av1/src/decode/key_tile.rs b/crates/ec-av1/src/decode/key_tile.rs index fca1ae84..f86f4a5b 100644 --- a/crates/ec-av1/src/decode/key_tile.rs +++ b/crates/ec-av1/src/decode/key_tile.rs @@ -97,22 +97,6 @@ pub(crate) fn decode_key_frame_tiles_lr( .map(|(picture, _)| picture) } -/// lane-superres r3: the real decoded margin beyond `frame_width` up to -/// the mi-aligned `true_width`, set by the most recent -/// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10) -/// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop -/// their reconstructed buffer down from the same mi-aligned extent, so -/// they share this one slot. See each function's own comment at its -/// write site. `None` when there was no margin to save. -/// The margin the most recent key- or inter-frame tile decode stashed -/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path -/// reads this immediately after the call, before any other frame -/// decode can overwrite it. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option { - fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take()) -} - /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec /// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from /// a prior frame's saved reference slot) when set, or the spec 8.4 defaults @@ -252,38 +236,6 @@ thread_local! { pub(crate) static SUB8_LOSSLESS_NO_VARTX: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// [`MU_CHUNK_WALKS`], for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn mu_chunk_walks() -> usize { - MU_CHUNK_WALKS.with(std::cell::Cell::get) -} - -/// [`MU_CHUNK_WALK_UNITS`], for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn mu_chunk_walk_units() -> usize { - MU_CHUNK_WALK_UNITS.with(std::cell::Cell::get) -} - -/// [`LOSSLESS_EDGE_CLIPPED`] -- lossless blocks whose TX grid the frame-edge -/// clip shortened, for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lossless_edge_clipped() -> usize { - LOSSLESS_EDGE_CLIPPED.with(std::cell::Cell::get) -} - -/// [`LOSSLESS_EDGE_CLIP_UNITS`] -- transform units the clip removed, i.e. the -/// ones the unclipped pre-fix walk read past the frame edge. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lossless_edge_clip_units() -> usize { - LOSSLESS_EDGE_CLIP_UNITS.with(std::cell::Cell::get) -} -/// [`SUB8_LOSSLESS_NO_VARTX`] -- sub-8 inter leaves on a lossless segment that -/// read no var-tx symbol, for a gate's own before/after delta. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sub8_lossless_no_vartx() -> usize { - SUB8_LOSSLESS_NO_VARTX.with(std::cell::Cell::get) -} - // Signature mirrors the spec's per-call inputs; a parameter struct would only move them. #[allow(clippy::too_many_arguments)] pub(super) fn read_sb128_root( @@ -328,26 +280,14 @@ pub(super) fn read_sb128_root( let ctx128 = neighbours.partition_ctx(at128, 128); let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows); let part128 = if has_cols128 && has_rows128 { - hit!(PART128_SYMBOLS); let p = dec.symbol(&mut cdfs.partition_w128[ctx128]); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!("TRACE partition_w128 ctx={ctx128} value={p}"); - } p } else { - // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the - // partition, they are not a forced split -- exactly the discarded-bit - // defect the 64 root carries a comment about at `partition_w64`'s - // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or - // VERT (cols out of frame), which the refusal below then names - // instead of silently reconstructing a split. - hit!(PART128_GATHERED_SYMBOLS); match (has_cols128, has_rows128) { (true, false) => { if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 { PARTITION_SPLIT } else { - hit!(PART128_EDGE_HORZ_HITS); PARTITION_HORZ } } @@ -355,13 +295,11 @@ pub(super) fn read_sb128_root( if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 { PARTITION_SPLIT } else { - hit!(PART128_EDGE_VERT_HITS); PARTITION_VERT } } _ => { PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1)); - bump_edge_both_cut(3); PARTITION_SPLIT } } @@ -383,22 +321,10 @@ pub(super) fn read_sb128_root( // decoding untouched. refuse_invalid_subsize((128, 128), part128, fctx)?; match part128 { - PARTITION_SPLIT => hit!(PART128_SPLIT_HITS), - PARTITION_NONE => hit!(PART128_NONE_HITS), - PARTITION_HORZ => hit!(PART128_HORZ_HITS), - PARTITION_VERT => hit!(PART128_VERT_HITS), // lane-sb128c r9: the four AB shapes at the 128 root -- one // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile // paths below in libaom `decode_partition`'s own visit order. - p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => { - hit_do! { - PART128_AB_HITS.with(|c| { - let mut h = c.get(); - h[p - PARTITION_HORZ_A] += 1; - c.set(h); - }); - } - } + p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {} _ => { return Err(unsupported( "a 128x128 superblock partition value outside the 8-symbol alphabet", @@ -484,13 +410,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK); let mut y = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane( - width * height, - true_width, - true_height, - width, - height, - )), + data: std::borrow::Cow::Owned(fresh_plane(width * height)), width, height, true_width, @@ -502,10 +422,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( plane: 0, }; let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx)); - note_frame_chroma_alloc((width, height), (cw, ch), (ss_x(fctx), ss_y(fctx))); let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx)); let mut u = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, @@ -517,7 +436,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( plane: 1, }; let mut v = PlaneBuf { - data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)), + data: std::borrow::Cow::Owned(fresh_plane(cw * ch)), width: cw, height: ch, true_width: ctw, @@ -603,18 +522,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx))); fctx.quant_deltas.with(|c| c.set(deltas)); fctx.current_delta_lf.with(|c| c.set([0; 4])); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}", - tile_bytes.len(), - &tile_bytes[..tile_bytes.len().min(8)] - ); - } let mut dec = SymbolDecoder::new(tile_bytes); // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets // it codes every symbol against the tables it started with. dec.set_cdf_update(!cdf_update_disabled(fctx)); - crate::census::register_cdfs(&cdfs); neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx); y.set_tile_origin( mi_col0 as usize * 4, @@ -634,7 +545,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( ((mi_col1 as usize * 4) >> ss_x(fctx)).min(v.width), ((mi_row1 as usize * 4) >> ss_y(fctx)).min(v.height), ); - hit!(TILE_HITS); // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` -- // its one block covers all four 64x64 quadrants, so the remaining three @@ -965,28 +875,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own // three-way write exactly. let part = if has_cols && has_rows { - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={} rng={}", - sb_r * SB_MI, - sb_c * SB_MI, - ctx, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } let p = dec.symbol(&mut cdfs.partition_w64[ctx]); - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART_VAL mi_row={} mi_col={} bsize=12 value={}", - sb_r * SB_MI, - sb_c * SB_MI, - p - ); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!("TRACE partition_w64 ctx={ctx} value={p}"); - } p } else { // lane-hgkf r1 (class `parsed-then-discarded`, same finding as @@ -998,16 +887,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // the first block of that row. match (has_cols, has_rows) { (true, false) => { - trace_edge( - (sb_r * SB_MI) as usize, - (sb_c * SB_MI) as usize, - 12, - ctx, - dec.debug_state().0, - ); let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); - bump_edge32(4 + b.min(1)); - bump_edge_part(b.min(1)); if b == 1 { PARTITION_SPLIT } else { @@ -1015,26 +895,14 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } (false, true) => { - trace_edge( - (sb_r * SB_MI) as usize, - (sb_c * SB_MI) as usize, - 12, - ctx, - dec.debug_state().0, - ); let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); - bump_edge32(4 + b.min(1)); - bump_edge_part(b.min(1)); if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } - _ => { - bump_edge_both_cut(2); - PARTITION_SPLIT - } + _ => PARTITION_SPLIT, } }; // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or @@ -1088,33 +956,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), ); let part32 = if has_cols32 && has_rows32 { - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={} rng={}", - r32 * BLOCK_MI, - c32 * BLOCK_MI, - ctx32, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } let p = dec.symbol(&mut cdfs.partition_w32[ctx32]); - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART_VAL mi_row={} mi_col={} bsize=9 value={}", - r32 * BLOCK_MI, - c32 * BLOCK_MI, - p - ); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}", - r32 * BLOCK_MI, - c32 * BLOCK_MI - ); - } p } else { // lane-hgkf r1: the 32-level frame-edge bit is the @@ -1122,19 +964,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // superblock level above). match (has_cols32, has_rows32) { (true, false) => { - trace_edge( - (r32 * BLOCK_MI) as usize, - (c32 * BLOCK_MI) as usize, - 9, - ctx32, - dec.debug_state().0, - ); let b = dec.symbol_fixed(&gather( &cdfs.partition_w32[ctx32], VERT_ALIKE, )); - bump_edge32(b.min(1)); - bump_edge_part(2 + b.min(1)); if b == 1 { PARTITION_SPLIT } else { @@ -1142,29 +975,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } (false, true) => { - trace_edge( - (r32 * BLOCK_MI) as usize, - (c32 * BLOCK_MI) as usize, - 9, - ctx32, - dec.debug_state().0, - ); let b = dec.symbol_fixed(&gather( &cdfs.partition_w32[ctx32], HORZ_ALIKE, )); - bump_edge32(b.min(1)); - bump_edge_part(2 + b.min(1)); if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } - _ => { - bump_edge_both_cut(1); - PARTITION_SPLIT - } + _ => PARTITION_SPLIT, } }; // lane-av1unwritten r4: VERT on a 32x32 block selects @@ -1221,16 +1042,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( let at16 = (sr, sc); let ctx16 = neighbours.partition_ctx(at16, SUB); if has_cols16 && has_rows16 { - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={} rng={}", - sr * SUB_MI as usize, - sc * SUB_MI as usize, - ctx16, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize` @@ -1240,21 +1051,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // keep decoding because the helper is exact, not a heuristic. key-frame 16x16 level. refuse_invalid_subsize((16, 16), part16, fctx)?; - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART_VAL mi_row={} mi_col={} bsize=6 value={}", - sr * SUB_MI as usize, - sc * SUB_MI as usize, - part16 - ); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}", - sr * SUB_MI as usize, - sc * SUB_MI as usize - ); - } if part16 == PARTITION_HORZ || part16 == PARTITION_VERT { let (bw, bh) = if part16 == PARTITION_HORZ { @@ -1326,11 +1122,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // rectangle: libaom switches those squares onto `has_tr_vert_*`/ // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here). - let arm = part16 - PARTITION_HORZ_A; - bump_ab16(arm); - if part16 == PARTITION_VERT_B { - hit!(VERT_B_INTRA_HITS); - } let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B { @@ -1353,7 +1144,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, @@ -1449,7 +1239,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( continue; } if part16 == PARTITION_HORZ { - hit!(HORZ_VERT_INTRA_HITS); let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let top = (mi_row0 as usize, mi_col0 as usize); @@ -1497,7 +1286,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( continue; } if part16 == PARTITION_VERT { - hit!(HORZ_VERT_INTRA_HITS); let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let left = (mi_row0 as usize, mi_col0 as usize); @@ -1550,15 +1338,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( { // lane-av1unwritten r6: arm census -- // which partition values reach here. - note_subsize_arm( - part16, - chroma_plane_block_codable( - partition_subsize_dims((16, 16), part16).0, - partition_subsize_dims((16, 16), part16).1, - ss_x(fctx), - ss_y(fctx), - ), - ); decode_rect4_16( &mut dec, &mut cdfs, @@ -1631,16 +1410,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={} rng={}", - leaf_mi.0, - leaf_mi.1, - leaf_ctx, - dec.debug_bitpos(), - dec.debug_state().0 - ); - } let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); // lane-av1unwritten r9: the @@ -1649,17 +1418,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // r9 made sensitive to a second // site at an already covered level. refuse_invalid_subsize((8, 8), part8, fctx)?; - if crate::envflags::env_flag!("EC_TRACE") { - eprintln!( - "EC_PART_VAL mi_row={} mi_col={} bsize=3 value={}", - leaf_mi.0, leaf_mi.1, part8 - ); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}" - ); - } if part8 == PARTITION_HORZ || part8 == PARTITION_VERT { @@ -1693,7 +1451,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, @@ -1714,7 +1471,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_intrabc, reduced_tx_set, @@ -1734,7 +1490,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_intrabc, tx_select, @@ -1783,7 +1538,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // quadrants get no neighbour or tx-grid // write. if !has_cols16 && !has_rows16 { - bump_edge_both_cut(0); } else { // lane-golomb r1 (class // `parsed-then-discarded`): the gathered @@ -1793,13 +1547,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // This path can only walk the four SPLIT // leaves, so a 0 refuses by name instead // of desyncing. - trace_edge( - sr * SUB_MI as usize, - sc * SUB_MI as usize, - 6, - ctx16, - dec.debug_state().0, - ); let edge_split = if has_cols16 { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], @@ -1814,21 +1561,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // lane-hgkf r1: slots 2/3 of // [`EDGE_PART_HITS`], the gate's proof the // non-SPLIT edge arm actually decoded. - bump_edge_part(if edge_split == 1 { 3 } else { 2 }); if edge_split == 0 { - // lane-oddh r1: the strip IS decodable - // -- libaom's `decode_partition` codes - // only the FIRST half of an edge - // HORZ/VERT (the second call is - // guarded by the same has_rows/ - // has_cols test that made the - // partition non-square), so one - // 16x8 (resp. 8x16) strip covers the - // whole visible band of a frame whose - // height (resp. width) is 8 mod 16 -- - // the user's 3840x1608 film. - hit!(HORZ_VERT_INTRA_HITS); - hit!(EDGE_RECT_STRIP_HITS); // lane-av1subsizesweep: this arm is the ONE // frame-edge partition read in the file that // dispatches on its own symbol instead of @@ -1867,17 +1600,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( refuse_invalid_subsize((16, 16), edge_part, fctx)?; // lane-av1unwritten r6: arm census -- which // partition value reaches here. - note_subsize_arm( - edge_part, - chroma_plane_block_codable( - partition_subsize_dims((16, 16), edge_part) - .0, - partition_subsize_dims((16, 16), edge_part) - .1, - ss_x(fctx), - ss_y(fctx), - ), - ); let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); let (bw, bh) = @@ -1934,7 +1656,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( neighbours.left_mode[sr] = right; } let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); - let pre8 = dec.debug_state().0; let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); // lane-av1unwritten r9: key-frame 8x8 @@ -1948,11 +1669,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // than live pixels, and it is guarded // anyway. refuse_invalid_subsize((8, 8), part8, fctx)?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}" - ); - } let leaf_mode = if part8 == PARTITION_NONE { decode_leaf8( &mut dec, @@ -1965,7 +1681,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_screen_content_tools, allow_intrabc, @@ -1986,7 +1701,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_intrabc, reduced_tx_set, @@ -2006,7 +1720,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - base_q_idx, enable_filter_intra, allow_intrabc, tx_select, @@ -2059,9 +1772,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( reduced_tx_set, fctx, )?; - if !has_rows32 { - bump_edge32(2); - } // lane-hgkf r1: at the frame edge only the first half of the strip is // coded (libaom `decode_partition` guards the second half with the same // test that made this partition non-square). @@ -2105,9 +1815,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( reduced_tx_set, fctx, )?; - if !has_cols32 { - bump_edge32(3); - } // lane-hgkf r1: at the frame edge only the first half of the strip is // coded (libaom `decode_partition` guards the second half with the same // test that made this partition non-square). @@ -2132,11 +1839,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } PARTITION_HORZ_A => { - // lane-part32 r1: two 16x16 squares on top + - // a true 32x16 strip below (mirrors - // decode_inter_block's cd6cb6d HORZ_A: TL, - // TR, bottom strip). - hit!(INTRA_HORZ_A_HITS); decode_block( &mut dec, &mut cdfs, @@ -2210,11 +1912,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( )?; } PARTITION_HORZ_B => { - // lane-part32 r1: a true 32x16 strip on top + - // two 16x16 squares below (mirrors HORZ_A - // with the strip/squares order flipped, same - // shape as libaom decode_partition's HORZ_B). - hit!(INTRA_HORZ_B_HITS); decode_block_rect( &mut dec, &mut cdfs, @@ -2288,10 +1985,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( )?; } PARTITION_VERT_A => { - // lane-part32 r1: mirror of HORZ_A with - // width/height swapped (TL, BL, right 16x32 - // strip). - hit!(INTRA_VERT_A_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_block( &mut dec, @@ -2366,11 +2059,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( )?; } PARTITION_VERT_B => { - // lane-part32 r1: a true 16x32 strip on the - // left + two 16x16 squares on the right - // (libaom decode_partition VERT_B: left - // strip, TR, BR). - hit!(INTRA_VERT_B_HITS); let _vert_ab = crate::encode::Reach::vert_ab_partition(); decode_block_rect( &mut dec, @@ -2513,9 +2201,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( reduced_tx_set, fctx, )?; - if !has_rows { - bump_edge32(6); - } // lane-golomb r1: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_rows test that made this partition non-square). @@ -2559,9 +2244,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( reduced_tx_set, fctx, )?; - if !has_cols { - bump_edge32(7); - } // lane-golomb r1: at the frame edge only the first half of the // strip is coded (libaom `decode_partition` guards the second // with the same has_cols test that made this partition non-square). @@ -2586,21 +2268,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } } PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => { - // lane-part32 r4: the four superblock-level AB arms, each - // two 32x32 squares plus one 64x32/32x64 strip, in - // libaom's own `decode_partition` order (decodeframe.c: - // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL, - // BR; VERT_A = TL, BL, right strip; VERT_B = left strip, - // TR, BR). The pieces are exactly the ones already proven - // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and - // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above. - hit_do! { - SB_AB_HITS.with(|c| { - let mut h = c.get(); - h[part - PARTITION_HORZ_A] += 1; - c.set(h); - }); - } // lane-part32 r5: only the two VERTICAL arms reorder the // square sub-blocks (TL, BL, TR, BR), so only they switch // libaom's `has_tr`/`has_bl` tables. @@ -2750,48 +2417,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } crate::timeline::recon_done(); - // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's - // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against - // that isolate whether a decode-order frame's mismatch already exists - // in reconstruction (this dump) vs is introduced by the loop filter - // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). - // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders. - if crate::envflags::env_flag!("EC_OBMC") - || crate::envflags::env_flag!("EC_TRACE_MODE") - || crate::envflags::env_flag!("EC_PRED") - { - eprintln!( - "EC_PICT idx={}", - PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) - ); - } - dump_stage16( - "EC_AV1_PREFILT_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); - census_unwritten(&y, &u, &v); - if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") { - // lane-av1dumploud: loud on a short write (three discarded - // `write_all` results before). Expected length = the three planes' own - // data lengths: this dump is the PADDED plane, not a crop, so the - // writer's extent is `p.data` itself. - let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let narrow = |p: &PlaneBuf<'_>| -> Vec { p.data.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - "EC_AV1_PREFILT_DUMP", - format!("{path}.f{idx}"), - &[&narrow(&y), &narrow(&u), &narrow(&v)], - ); - } else { - PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - dump_prefilter_wide(&y, &u, &v); // lane-av1fwd: the encoder's filter search re-decodes this same key // frame tile per candidate -- capture it once (see [`FilterReplay`]), // on the shape whose tail is the two filter calls and nothing else. @@ -2848,42 +2473,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( plane_snapshot(&v, ss_y(fctx) as u32), ) }); - // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own - // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter - // dump above these bisect WHICH filter stage introduced a mismatch. - dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTDEBLOCK_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); apply_cdef( &mut y, &mut u, &mut v, cdef, &neighbours, - (frame_width as usize, frame_height as usize), fctx, None, None, ); - dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); - dump_stage16( - "EC_AV1_POSTCDEF_DUMP16", - &y, - &u, - &v, - frame_width as usize, - frame_height as usize, - ss_x(fctx), - ss_y(fctx), - ); capture_stages(&y, &u, &v, deblocked.as_ref(), fctx); // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`): @@ -3009,24 +2608,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( fctx.last_frame_wide_margin.with(|m| { *m.borrow_mut() = if true_width > fw || true_height > fh { let yc = crop(&y, true_width, true_height); - if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") { - static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - // corner-cut: this diagnostic dump stays 8-bit-narrowed - // regardless of the stream's real bit depth (debug-only, - // never read by a gate); widen if a >8-bit margin dump - // is ever needed. - // - // lane-av1dumploud: loud on a short write. Expected length is - // `true_width * true_height` -- the crop this dump is exactly, - // not a re-derived geometry. - let narrow: Vec = yc.iter().map(|&s| s as u8).collect(); - crate::dumpio::write_planes( - "EC_AV1_MARGIN_DUMP", - format!("{path}.f{idx}"), - &[&narrow], - ); - } Some(Picture { width: true_width, height: true_height, diff --git a/crates/ec-av1/src/decode/leaf8.rs b/crates/ec-av1/src/decode/leaf8.rs index be1da877..0ef72c7e 100644 --- a/crates/ec-av1/src/decode/leaf8.rs +++ b/crates/ec-av1/src/decode/leaf8.rs @@ -122,9 +122,6 @@ pub(super) fn decode_block_128rect( uv_mode }; let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc). @@ -143,25 +140,12 @@ pub(super) fn decode_block_128rect( // lane-inter128intra r1: `get_tx_size_context` compares the bands // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- // TX_64X64 for every 128-axis block, hence the `min(64)`. - let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); + let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64)); dec.symbol(&mut cdfs.tx_size_cat3[ctx]) } else { 0 }; - if depth != 0 { - hit!(TX_DEPTH_HITS); - } - hit_do! { - INTRA_SB128_DEPTH_HITS.with(|c| { - let mut h = c.get(); - h[depth.min(2)] += 1; - c.set(h); - }); - } let logical_tx = if lossless_frame { 4 } else { 64 >> depth }; - if lossless_frame { - hit!(INTRA128_LOSSLESS_HITS); - } // A 64-point transform codes nothing past its low 32 coefficients. let coeff_tx_side = logical_tx.min(32); let luma_set = if lossless_frame { @@ -239,11 +223,6 @@ pub(super) fn decode_block_128rect( tu_row * logical_tx, logical_tx, reach, - px, - py, - y.width, - y.height, - fctx, ); if skip { push_intra( @@ -288,7 +267,6 @@ pub(super) fn decode_block_128rect( tu_py, logical_tx, coeff_tx_side, - base_q_idx, None, None, Some(tu_skip_ctx), @@ -341,11 +319,6 @@ pub(super) fn decode_block_128rect( luma_span, luma_span_h, reach, - px, - py, - y.width, - y.height, - fctx, ); if skip { push_intra( @@ -402,7 +375,6 @@ pub(super) fn decode_block_128rect( cu_y, chroma_tx, chroma_tx, - base_q_idx, None, None, Some(3), @@ -425,9 +397,6 @@ pub(super) fn decode_block_128rect( } } } - if !skip { - hit!(CHROMA_SPLIT_TX_HITS); - } } } if skip { @@ -467,12 +436,8 @@ pub(super) fn decode_block_128rect( // byte-exact against ffmpeg) -- that is the replay's own designed // 4:2:2 case, not a defect signature. Nothing here asserts the // mismatch is zero. - if luma_span != luma_span_h { - hit!(SB128RECT_REPLAY_SPAN_MISMATCH_HITS); - } for (plane, cu_mi, grid) in &units { neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span_h, *plane, grid); - hit!(SB128RECT_CHROMA_REPLAY_HITS); } } // No palette exists at this size; the unconditional stamp clears any @@ -499,19 +464,6 @@ pub(super) fn decode_block_128rect( // stamps here too -- lane-av1-intrabc r3. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (logical_tx, logical_tx), (bw, bh)); } - if in_inter { - hit_do! { - INTRA128_IN_INTER_HITS.with(|c| { - let mut h = c.get(); - h[usize::from(bw < bh)] += 1; - c.set(h); - }); - } - } else if bw > bh { - hit!(INTRA_SB128_HORZ_HITS); - } else { - hit!(INTRA_SB128_VERT_HITS); - } Ok(()) } @@ -563,7 +515,6 @@ pub(super) fn decode_leaf8( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - base_q_idx: u8, enable_filter_intra: bool, allow_screen_content_tools: bool, allow_intrabc: bool, @@ -603,9 +554,6 @@ pub(super) fn decode_leaf8( // with the coarse [`SUB`] slot as the fallback when no block recorded // that exact mi cell. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other // `decode_block` caller at 16x16 and up. @@ -654,9 +602,6 @@ pub(super) fn decode_leaf8( // next symbol (class `wrong-alphabet-same-value`). Everything below // mirrors `decode_block`'s own intrabc handling at 16x16 and up. let intrabc_dv = fctx.intrabc_dv.with(|c| c.take()); - if intrabc_dv.is_some() { - hit!(LEAF8_INTRABC_HITS); - } // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour // index map, mapped through the base colours, IS the block's prediction -- // carried to the next `reconstruct`/`read_plane` through the same @@ -676,9 +621,6 @@ pub(super) fn decode_leaf8( let (pal_uv_size, pal_uv_colors) = palette_uv .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); - if palette_y.is_some() || palette_uv.is_some() { - hit!(PALETTE_LEAF8_HITS); - } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { @@ -722,7 +664,6 @@ pub(super) fn decode_leaf8( 0, &mut leaves, ); - hit!(INTRABC_VARTX_HITS); leaves.first().map_or(8, |l| l.2) } else if tx_select && intrabc_dv.is_none() { read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, fctx) @@ -846,26 +787,13 @@ pub(super) fn decode_leaf8( // rule) -- so a palette leaf takes the single 8x8 reconstruct below // even when `tx_depth` resolved to TX_4X4. if resolved == 4 && palette_y_buf.is_none() { - hit!(SKIP_SPLIT_TX_HITS); for tu_row in 0..2 { for tu_col in 0..2 { let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4); if tu_px >= y.true_width || tu_py >= y.true_height { continue; } - let tu_reach = tu_reach( - 8, - 8, - tu_col * 4, - tu_row * 4, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let tu_reach = tu_reach(8, 8, tu_col * 4, tu_row * 4, 4, reach); push_intra( y, u, @@ -989,19 +917,7 @@ pub(super) fn decode_leaf8( if chroma_units_ll { for cu_row in 0..cu_shape.1 / 4 { for cu_col in 0..cu_shape.0 / 4 { - let cu_reach = tu_reach( - 8, - 8, - cu_col * 4, - cu_row * 4, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let cu_reach = tu_reach(8, 8, cu_col * 4, cu_row * 4, 4, reach); push_intra( y, u, @@ -1048,19 +964,7 @@ pub(super) fn decode_leaf8( for (buf, plane) in [(ub, 1usize), (vb, 2usize)] { if let Some(buf) = buf { for cu_row in 0..2 { - let cu_reach = tu_reach( - 8, - 8, - 0, - cu_row * 4, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let cu_reach = tu_reach(8, 8, 0, cu_row * 4, 4, reach); set_palette_pred( palette_window(&buf, cw, 0, cu_row * 4, 4, 4), fctx, @@ -1113,19 +1017,7 @@ pub(super) fn decode_leaf8( if chroma_units_ll { for cu_row in 0..cu_shape.1 / 4 { for cu_col in 0..cu_shape.0 / 4 { - let cu_reach = tu_reach( - 8, - 8, - cu_col * 4, - cu_row * 4, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let cu_reach = tu_reach(8, 8, cu_col * 4, cu_row * 4, 4, reach); push_intra( y, u, @@ -1158,19 +1050,7 @@ pub(super) fn decode_leaf8( .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone())); if let Some(vb) = vb { for cu_row in 0..2 { - let cu_reach = tu_reach( - 8, - 8, - 0, - cu_row * 4, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let cu_reach = tu_reach(8, 8, 0, cu_row * 4, 4, reach); set_palette_pred(palette_window(&vb, cw, 0, cu_row * 4, 4, 4), fctx); push_intra( y, @@ -1257,7 +1137,6 @@ pub(super) fn decode_leaf8( py, 8, TX8, - base_q_idx, None, filter_intra, None, @@ -1344,7 +1223,6 @@ pub(super) fn decode_leaf8( cpy, csz, csz, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -1374,7 +1252,6 @@ pub(super) fn decode_leaf8( cpy, csz, csz, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -1400,29 +1277,13 @@ pub(super) fn decode_leaf8( let tu_px = px + tu_col * 4; let tu_py = py + tu_row * 4; let tu_around = neighbours.around_mi(tu_mi, 4)[0]; - if crate::encode::Reach::in_vert_ab() { - hit!(VERT_AB_TX4_HITS); - } - let tu_reach = tu_reach( - 8, - 8, - tu_col * 4, - tu_row * 4, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let tu_reach = tu_reach(8, 8, tu_col * 4, tu_row * 4, 4, reach); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); // Each 4x4 unit predicts from its own window of the block's // 8x8 colour-index map ([`decode_block`]'s per-TU slice at // 16x16 and up) -- the whole-block buffer would be taken by // the FIRST unit and indexed at the wrong stride. if let Some(buf) = &palette_y_buf { - hit!(PALETTE_SPLIT_TX_HITS); let mut window = vec![0u16; 16]; for row in 0..4 { let src = (tu_row * 4 + row) * 8 + tu_col * 4; @@ -1454,21 +1315,12 @@ pub(super) fn decode_leaf8( tu_py, 4, 4, - base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE tu_bitpos mi=({},{}) tell={}", - tu_mi.0, - tu_mi.1, - dec.debug_bitpos() - ); - } neighbours.record_mi_luma(tu_mi, 4, &tu_grid); // The FIRST (top-left, co-located with this group's chroma) // TU's coded tx_type is what the group's chroma inherits -- @@ -1505,9 +1357,6 @@ pub(super) fn decode_leaf8( // lane-av1intrapred: the non-vacuity counter -- armed slot consulted // by this arm's chroma reads means the frame-copy + inherited-type // route ran; zero at gate time means the fixture stopped reaching it. - if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { - hit!(INTRABC_TX4_CHROMA_COPY_HITS); - } if chroma_422 && !lossless(fctx) { // lane-av1-422d: the chroma unit does NOT follow the luma var-tx // split -- `uv_txsize` is `av1_get_max_uv_txsize` of the block, @@ -1601,7 +1450,6 @@ pub(super) fn decode_leaf8( cdfs, neighbours, leaf_mi, - (px, py), (cpx, cpy), 8, (blk_w, blk_h), @@ -1609,13 +1457,11 @@ pub(super) fn decode_leaf8( (blk_w, blk_h), blk_w, reach, - (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, - base_q_idx, &mut uo, &mut vo, fctx, @@ -1630,7 +1476,6 @@ pub(super) fn decode_leaf8( } else { Grid::Own(vo) }; - hit!(CHROMA422_LOSSLESS_4X4_HITS); } else if chroma_444 && lossless(fctx) { // 4:4:4 lossless: the leaf's chroma plane block is a 2x2 raster // of TX_4X4 units per plane, PLANE-MAJOR (`av1_get_tx_size`: @@ -1651,7 +1496,6 @@ pub(super) fn decode_leaf8( cdfs, neighbours, leaf_mi, - (px, py), (cpx, cpy), 8, (8, 8), @@ -1659,13 +1503,11 @@ pub(super) fn decode_leaf8( (8, 8), 8, reach, - (y.width, y.height), mode, uv_predict_mode, angle_delta_uv, palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])), smooth_neighbor_uv, - base_q_idx, &mut uo, &mut vo, fctx, @@ -1702,7 +1544,6 @@ pub(super) fn decode_leaf8( cpy, csz, csz, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -1730,7 +1571,6 @@ pub(super) fn decode_leaf8( cpy, csz, csz, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -1809,7 +1649,6 @@ pub(super) fn decode_leaf8( neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors); neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors); } - hit!(INTER8_SKIP_BAND_HITS); neighbours.fill_skip_grid(leaf_mi, 2, skip); // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm && @@ -1924,7 +1763,6 @@ pub(super) fn leaf8_chroma422_unit( usize::from(around.0) + usize::from(around.1), dc_sign_ctx(around.2), default_tx, - plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -2001,28 +1839,10 @@ pub(super) fn read_intra_mode_sub8( // lane-av1mono: a monochrome leaf codes no chroma mode (libaom // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`. let has_chroma = has_chroma && !mono(fctx); - let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); - let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); - crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64); - if ec_istep { - eprintln!( - "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", - dec.debug_state().0 - ); - } // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block. macro_rules! istep { - ($name:literal, $val:expr) => { - if ec_istep { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", - $name, - $val, - dec.debug_state().0 - ); - } - }; + ($name:literal, $val:expr) => {}; } // lane-seg2: same `intra_segment_id` placement as the square and rect // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id` @@ -2034,13 +1854,6 @@ pub(super) fn read_intra_mode_sub8( intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; - if trace { - eprintln!( - "TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", - skip as i32, - dec.debug_state().0 - ); - } istep!("skip", skip as i32); if !seg_id_pre_skip(fctx) { intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); @@ -2052,13 +1865,6 @@ pub(super) fn read_intra_mode_sub8( istep!("dq", 0); if allow_intrabc { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; - if ec_istep { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", - u8::from(use_intrabc), - dec.debug_state().0 - ); - } if use_intrabc { // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block // vector right after the flag and RETURNS -- no y/uv mode, angle @@ -2067,15 +1873,6 @@ pub(super) fn read_intra_mode_sub8( // `is_inter_block` counts an intrabc block), so the caller takes // the frame-copy prediction + inter residual. let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx); - // lane-av1txr: the DV travels back in the RETURN value -- it is - // NOT published through `FrameCtx::intrabc_dv`. That slot is the - // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it, - // then `take()` it in the same call), so a sub-8x8 leaf that - // armed it left the vector standing for the NEXT >=8x8 block: - // `warped.obu`'s (38,60) 8x8 intra block took it as its own - // intrabc and read an inter var-tx `txfm_split` where libaom read - // an intra `tx_depth` (class `stale-slot-handoff`). - hit!(INTRABC_HITS); return Ok((skip, DC_PRED, 0, None, None, Some(dv))); } } @@ -2083,12 +1880,6 @@ pub(super) fn read_intra_mode_sub8( let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); istep!("mode", mode); - if trace { - eprintln!( - "TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", - dec.debug_state().0 - ); - } // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/ // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`, // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta @@ -2107,29 +1898,15 @@ pub(super) fn read_intra_mode_sub8( // divergence at the rect leaf mi (8,16) of `ll444.obu`; class // `wrong-alphabet-same-value`, lane-av1-llsub8). let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; - if trace { - eprintln!( - "TRACE sub8 uv_mode value={uv_mode} rng={}", - dec.debug_state().0 - ); - } - if (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - } let alpha = if uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; - if (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); - } // See the luma comment above: no angle delta below 8x8. let angle_delta_uv = 0; Some((uv_mode, angle_delta_uv, alpha)) @@ -2139,14 +1916,7 @@ pub(super) fn read_intra_mode_sub8( let mut filter_intra = None; if mode == DC_PRED && enable_filter_intra { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0; - if trace { - eprintln!( - "TRACE sub8 use_filter_intra value={}", - use_filter_intra as i32 - ); - } if use_filter_intra { - hit!(FILTER_INTRA_HITS); let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); filter_intra = Some(fi_mode); } diff --git a/crates/ec-av1/src/decode/leaf_sub8.rs b/crates/ec-av1/src/decode/leaf_sub8.rs index c13bc7b5..fbd33302 100644 --- a/crates/ec-av1/src/decode/leaf_sub8.rs +++ b/crates/ec-av1/src/decode/leaf_sub8.rs @@ -35,7 +35,6 @@ pub(super) fn sub8_leaf_chroma444( u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, scan4: &[u16], - base_q_idx: u8, smooth_neighbor_uv: bool, fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid, usize, usize)> { @@ -94,7 +93,6 @@ pub(super) fn sub8_leaf_chroma444( &mut vb, fctx, ); - hit!(SKIPPED_INTRABC_DV_COPY_HITS); let zeros = &ZERO_RESIDUAL[..bw * bh]; if square { set_palette_pred(ub, fctx); @@ -173,10 +171,6 @@ pub(super) fn sub8_leaf_chroma444( fctx, ); } - // The same arm-without-clear route the 4:2:0 tails count: a skipped - // leaf reads no coefficient, so the inherited chroma `tx_type` is - // dropped unconsumed. - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4) } else if skip { @@ -257,7 +251,6 @@ pub(super) fn sub8_leaf_chroma444( // The same arm-without-clear route the 4:2:0 tails count: a skipped // leaf reads no coefficient, so an armed intrabc slot is dropped. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(bw * bh), Grid::Zero(bw * bh), 4, 4) @@ -313,7 +306,6 @@ pub(super) fn sub8_leaf_chroma444( py, 4, TX4, - base_q_idx, None, None, None, @@ -339,7 +331,6 @@ pub(super) fn sub8_leaf_chroma444( py, 4, TX4, - base_q_idx, None, None, None, @@ -350,9 +341,6 @@ pub(super) fn sub8_leaf_chroma444( } else { // lane-av1-ibc444rect: the unskipped lossless chroma walk this // lane fixes (one rect unit -> per-4x4 Chroma4 units). - if lossless(fctx) { - hit!(INTRABC_RECT8_LOSSLESS_CHROMA_HITS); - } if lossless(fctx) { // lane-av1-ibc444rect: at lossless `read_tx_size` forces // TX_4X4 on EVERY plane (`av1_get_tx_size`'s lossless @@ -406,11 +394,6 @@ pub(super) fn sub8_leaf_chroma444( // 4:2:2 twin of this arm was fixed the same way // (lane-av1-422kf2); this is its 4:4:4 twin. let unit_reach = Reach::of_tu(bw, bh, uc * 4, ur * 4, 4, 4, reach); - if !square - && unit_reach != Reach::of(4, upx, upy, y.width, y.height, fctx) - { - hit!(SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS); - } let grid = read_plane( dec, cdfs, @@ -429,7 +412,6 @@ pub(super) fn sub8_leaf_chroma444( upy, 4, TX4, - base_q_idx, None, None, Some(3), @@ -478,7 +460,6 @@ pub(super) fn sub8_leaf_chroma444( skip_ctx, dc_sign_ctx(around[plane_idx].2), default_tx, - plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -543,7 +524,6 @@ pub(super) fn sub8_leaf_chroma444( py, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -568,7 +548,6 @@ pub(super) fn sub8_leaf_chroma444( py, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -605,10 +584,6 @@ pub(super) fn sub8_leaf_chroma444( // position -- see the intrabc twin above for the // libaom citation and the measured damage. let unit_reach = Reach::of_tu(bw, bh, uc * 4, ur * 4, 4, 4, reach); - if !square && unit_reach != Reach::of(4, upx, upy, y.width, y.height, fctx) - { - hit!(SUB8_CHROMA444_LOSSLESS_TU_REACH_HITS); - } let grid = read_plane( dec, cdfs, @@ -627,7 +602,6 @@ pub(super) fn sub8_leaf_chroma444( upy, 4, TX4, - base_q_idx, None, None, Some(3), @@ -677,7 +651,6 @@ pub(super) fn sub8_leaf_chroma444( skip_ctx, dc_sign_ctx(around[plane_idx].2), default_tx, - plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -806,16 +779,7 @@ pub(super) fn sub8_leaf_chroma422( u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, scan4: &[u16], - base_q_idx: u8, smooth_neighbor_uv: bool, - // The owning luma leaf's own shape (`(4, 4)` for a split leaf, `(8, 4)` / - // `(4, 8)` for a rect pair's strip): libaom's `has_top_right` / - // `has_bottom_left` answer for this chroma TX_4X4 unit comes from the - // LEAF's own rect table row at the leaf's mi (`bsize` is the leaf, the - // unit covers it whole), never the standalone square-4x4 table the old - // `Reach::of(4, ..)` lookup used -- that said 1 where `has_tr_8x4` says 0 - // at mi(27,44) (the oracle's own EC_PRED prints `n_tr=0` there), so the - // D45 unit read undecoded pixels to its upper right. leaf_shape: (usize, usize), fctx: &crate::decode::FrameCtx, ) -> Result<(Grid, Grid)> { @@ -988,7 +952,6 @@ pub(super) fn sub8_leaf_chroma422( &mut ub, fctx, ); - hit!(SKIPPED_INTRABC_DV_COPY_HITS); let zeros = &ZERO_RESIDUAL[..16]; set_palette_pred(ub, fctx); push_intra( @@ -1044,17 +1007,12 @@ pub(super) fn sub8_leaf_chroma422( // [`sub8_leaf_chroma444`] count: a skipped leaf reads no coefficient, // so the inherited chroma `tx_type` is dropped unconsumed. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) } else if skip { // A skipped chroma-reference leaf still predicts (the CfL contribution // survives a skip); no coefficient symbol exists. - if alpha.is_some() { - hit!(CHROMA_SKIP_CFL_HITS); - hit!(SKIP_CFL_HITS); - } push_intra( y, u, @@ -1092,12 +1050,10 @@ pub(super) fn sub8_leaf_chroma422( // The same arm-without-clear route the 4:2:0 tails count: a skipped // leaf reads no coefficient, so an armed intrabc slot is dropped. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) } else if let Some(dv) = intrabc_dv { - hit!(CHROMA422_SUB8_HITS); // Frame copy at the DV; the residual still reads the ordinary chroma // tables with the inherited luma `tx_type` (see the 4:2:0 tails). let mut ub = vec![0u16; 16]; @@ -1147,7 +1103,6 @@ pub(super) fn sub8_leaf_chroma422( cpy, 4, TX4, - base_q_idx, None, None, None, @@ -1173,7 +1128,6 @@ pub(super) fn sub8_leaf_chroma422( cpy, 4, TX4, - base_q_idx, None, None, None, @@ -1183,7 +1137,6 @@ pub(super) fn sub8_leaf_chroma422( fctx.intrabc_chroma_tx.with(|c| c.set(None)); (ug, vg) } else { - hit!(CHROMA422_SUB8_HITS); let ug = read_plane( dec, cdfs, @@ -1202,7 +1155,6 @@ pub(super) fn sub8_leaf_chroma422( cpy, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -1227,7 +1179,6 @@ pub(super) fn sub8_leaf_chroma422( cpy, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -1277,16 +1228,11 @@ pub(super) fn decode_leaf_split4( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - base_q_idx: u8, enable_filter_intra: bool, allow_intrabc: bool, reduced_tx_set: bool, - // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8 - // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the - // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx fctx: &crate::decode::FrameCtx, ) -> Result<(usize, usize)> { - hit!(SUB8_SPLIT_HITS); let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; @@ -1378,9 +1324,6 @@ pub(super) fn decode_leaf_split4( // same value). set_txfm_ctxs(neighbours, lmi, 4, 1, 1, false); let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of(4, px, py, y.width, y.height, fctx); if let Some(dv) = intrabc { @@ -1450,7 +1393,6 @@ pub(super) fn decode_leaf_split4( py, 4, 4, - base_q_idx, None, None, None, @@ -1488,7 +1430,6 @@ pub(super) fn decode_leaf_split4( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; @@ -1508,7 +1449,6 @@ pub(super) fn decode_leaf_split4( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (4, 4), fctx, @@ -1579,7 +1519,6 @@ pub(super) fn decode_leaf_split4( py, 4, 4, - base_q_idx, None, filter_intra, None, @@ -1610,7 +1549,6 @@ pub(super) fn decode_leaf_split4( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; @@ -1636,7 +1574,6 @@ pub(super) fn decode_leaf_split4( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (4, 4), fctx, @@ -1695,10 +1632,6 @@ pub(super) fn decode_leaf_split4( // merge keeps one fix and feeds both lanes' counters so neither of // their gates goes vacuous. let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); - if alpha.is_some() { - hit!(CHROMA_SKIP_CFL_HITS); - hit!(SKIP_CFL_HITS); - } push_intra( y, u, @@ -1742,7 +1675,6 @@ pub(super) fn decode_leaf_split4( // arm-without-clear-on-a-skip-route). Counted so a gate can tell a // stream that reaches this route from one that never does. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) @@ -1799,7 +1731,6 @@ pub(super) fn decode_leaf_split4( cpy, 4, TX4, - base_q_idx, None, None, None, @@ -1825,7 +1756,6 @@ pub(super) fn decode_leaf_split4( cpy, 4, TX4, - base_q_idx, None, None, None, @@ -1855,7 +1785,6 @@ pub(super) fn decode_leaf_split4( cpy, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -1880,7 +1809,6 @@ pub(super) fn decode_leaf_split4( cpy, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -1989,7 +1917,6 @@ pub(super) fn decode_leaf_rect8( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - base_q_idx: u8, enable_filter_intra: bool, allow_intrabc: bool, tx_select: bool, @@ -2073,9 +2000,6 @@ pub(super) fn decode_leaf_rect8( if let Some(dv) = intrabc { // lane-av1-ibc444rect: the unskipped lossless luma walk this lane // fixes (one rect unit -> per-4x4 inter units). - if !skip && lossless(fctx) { - hit!(INTRABC_RECT8_LOSSLESS_LUMA_HITS); - } // lane-av1txr: an intrabc `BLOCK_4X8`/`BLOCK_8X4` leaf. The // prediction is a frame copy at the DV and the residual reads the // INTER `LumaRect8x4` set -- but with `TxMode::Select` the leaf @@ -2127,7 +2051,6 @@ pub(super) fn decode_leaf_rect8( 0, &mut luma_leaves, ); - hit!(RECT_INTRABC_VARTX_HITS); publish = None; } else if lossless(fctx) && !skip { // lane-av1-ibc444rect: `read_tx_size`'s lossless first line @@ -2170,19 +2093,7 @@ pub(super) fn decode_leaf_rect8( let tu_reach = if single { reach } else { - tu_reach( - bw, - bh, - tu_px - px, - tu_py - py, - tw, - reach, - px, - py, - y.width, - y.height, - fctx, - ) + tu_reach(bw, bh, tu_px - px, tu_py - py, tw, reach) }; let mut yb = vec![0u16; tw * th]; mc::predict_with_filter( @@ -2285,7 +2196,6 @@ pub(super) fn decode_leaf_rect8( skip_ctx, dc_sign_ctx(around.2), TxType::DctDct, - 0, )?; if li == 0 { chroma_tx = tx_type; @@ -2417,7 +2327,6 @@ pub(super) fn decode_leaf_rect8( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; @@ -2439,7 +2348,6 @@ pub(super) fn decode_leaf_rect8( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, @@ -2452,15 +2360,6 @@ pub(super) fn decode_leaf_rect8( } continue; } - if filter_intra.is_some() { - // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over - // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the - // same `reconstruct_rect`/`reconstruct` calls below -- and under - // a split transform, per 4x4 unit with that unit's own edge, - // which is exactly what the depth-1 loop already does. - hit!(FILTER_INTRA_RECT_HITS); - hit!(FILTER_INTRA_RECT_SUB8_HITS); - } // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4 // leaf too, and is read for every intra block, skipped or not. Its // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` -- @@ -2480,18 +2379,11 @@ pub(super) fn decode_leaf_rect8( let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect // reader already does. - let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh); dec.symbol(&mut cdfs.tx_size_cat0[ctx]) } else { 0 }; - if depth != 0 { - hit!(TX_DEPTH_HITS); - hit!(RECT8_SPLIT_TX_HITS); - } - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into @@ -2511,7 +2403,6 @@ pub(super) fn decode_leaf_rect8( let (ctx_tx_w, ctx_tx_h) = if split { (4, 4) } else { (bw, bh) }; txfm_partition_update_rect(neighbours, lmi, (ctx_tx_w, ctx_tx_h), (bw, bh)); if split { - let mut done = 0usize; for tu in 0..2usize { let tu_mi = if vert { (lmi.0 + tu, lmi.1) @@ -2524,19 +2415,7 @@ pub(super) fn decode_leaf_rect8( // (lane-palette2 r12): a transform unit inside a block is not // a block at that position, so its reach comes from the // block's own row, offset by the unit's position. - let tu_reach = tu_reach( - bw, - bh, - tu_px - px, - tu_py - py, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let tu_reach = tu_reach(bw, bh, tu_px - px, tu_py - py, 4, reach); let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1); if skip { // A skipped leaf still predicts per transform unit: the @@ -2586,25 +2465,14 @@ pub(super) fn decode_leaf_rect8( tu_py, 4, TX4, - base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; - if tu_grid.iter().any(|&l| l != 0) { - done += 1; - } neighbours.record_mi_luma(tu_mi, 4, &tu_grid); } - if done > 0 { - if vert { - hit!(TX4X8_CODED_HITS); - } else { - hit!(TX8X4_CODED_HITS); - } - } neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip); neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx); if has_chroma { @@ -2627,7 +2495,6 @@ pub(super) fn decode_leaf_rect8( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; @@ -2655,7 +2522,6 @@ pub(super) fn decode_leaf_rect8( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, @@ -2712,15 +2578,7 @@ pub(super) fn decode_leaf_rect8( 0, dc_sign_ctx(around.2), TxType::DctDct, - 0, )?; - if levels.iter().any(|&l| l != 0) { - if vert { - hit!(TX4X8_CODED_HITS); - } else { - hit!(TX8X4_CODED_HITS); - } - } let residual = dequant_and_inverse_typed_wh( &levels, bw, @@ -2791,7 +2649,6 @@ pub(super) fn decode_leaf_rect8( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), fctx, )?; @@ -2822,7 +2679,6 @@ pub(super) fn decode_leaf_rect8( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, @@ -2881,10 +2737,6 @@ pub(super) fn decode_leaf_rect8( // merge keeps one fix and feeds both lanes' counters so neither of // their gates goes vacuous. let ac = alpha.map(|_| cfl_src(gpx, gpy, 8)); - if alpha.is_some() { - hit!(CHROMA_SKIP_CFL_HITS); - hit!(SKIP_CFL_HITS); - } push_intra( y, u, @@ -2928,7 +2780,6 @@ pub(super) fn decode_leaf_rect8( // arm-without-clear-on-a-skip-route). Counted so a gate can tell a // stream that reaches this route from one that never does. if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() { - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); } (Grid::Zero(16), Grid::Zero(16)) @@ -3005,7 +2856,6 @@ pub(super) fn decode_leaf_rect8( &ZERO_RESIDUAL[..16], fctx, ); - hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS); fctx.intrabc_chroma_tx.with(|c| c.set(None)); (Grid::Zero(16), Grid::Zero(16)) } else { @@ -3029,7 +2879,6 @@ pub(super) fn decode_leaf_rect8( cpy, 4, TX4, - base_q_idx, None, None, None, @@ -3055,7 +2904,6 @@ pub(super) fn decode_leaf_rect8( cpy, 4, TX4, - base_q_idx, None, None, None, @@ -3086,7 +2934,6 @@ pub(super) fn decode_leaf_rect8( cpy, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -3111,7 +2958,6 @@ pub(super) fn decode_leaf_rect8( cpy, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, diff --git a/crates/ec-av1/src/decode/mod.rs b/crates/ec-av1/src/decode/mod.rs index a17b5e63..80a8c7fe 100644 --- a/crates/ec-av1/src/decode/mod.rs +++ b/crates/ec-av1/src/decode/mod.rs @@ -20,7 +20,6 @@ //! inside one, forcing the gathered-CDF partial-superblock path, is round 2 //! too). Anything outside that refuses with [`Error::unsupported`] rather than //! silently miscoding. -use crate::hits::{hit, hit_do}; use ec_av1_syntax::{ CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, MAX_SEGMENTS, @@ -41,9 +40,6 @@ use ec_core::{Error, Result}; // itself was lifted by lane-av112bitc before that (the combines absorb the // CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`). -mod counters; -pub use counters::*; - mod frame_tile; mod inter_block8; @@ -71,7 +67,7 @@ use rect4::*; mod block; mod wave; -pub use block::*; +pub(crate) use block::*; mod leaf8; use leaf8::*; @@ -100,9 +96,6 @@ pub use key_tile::*; mod inter_ctx; pub(crate) use inter_ctx::*; -#[cfg(test)] -mod obmc_skip_chroma_tests; - mod sub8_inter; pub(crate) use frame_tile::*; use sub8_inter::*; @@ -437,38 +430,6 @@ thread_local! { static COEFF_TRACE_CUR: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; } -/// Called by [`crate::stream::decode_stream`] before each frame's tiles with -/// that frame's DECODE-order index. -pub fn set_coeff_trace_frame(idx: usize) { - COEFF_TRACE_FRAME.with(|c| { - if c.get().is_none() { - let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") { - Ok(v) => v.parse::().unwrap_or(usize::MAX), - // unset: keep tracing every frame, as before this rung existed - Err(_) => usize::MAX - 1, - }; - c.set(Some(want)); - } - }); - COEFF_TRACE_CUR.with(|c| c.set(idx)); - if crate::envflags::env_flag!("EC_TRACE_COEFF") { - eprintln!("EC_COEFF_FRAME decode_idx={idx}"); - } -} - -pub(crate) fn coeff_trace_on() -> bool { - if !crate::envflags::env_flag!("EC_TRACE_COEFF") { - return false; - } - match COEFF_TRACE_FRAME.with(|c| c.get()) { - // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the - // env var unset: trace every frame. - None => true, - Some(w) if w >= usize::MAX - 1 => true, - Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w, - } -} - /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`). pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) { fctx.sb128_flag.with(|c| c.set(v)); @@ -550,20 +511,6 @@ thread_local! { static PART128_GATHERED_SYMBOLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the -/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec -/// 5.11.4), which this decoder used to read and throw away. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn part128_gathered_symbols() -> usize { - PART128_GATHERED_SYMBOLS.with(|c| c.get()) -} - -/// Current value of [`PART128_SYMBOLS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn part128_symbols() -> usize { - PART128_SYMBOLS.with(|c| c.get()) -} - /// [`gather`] over an alphabet of any length -- the 128-level partition CDF /// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec /// `partition_cdf_length`), so its forced-split gather sums 5 elements where @@ -670,11 +617,7 @@ pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> { /// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is /// bigger than the real block in one axis. pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool { - if w >= 8 && h >= 8 { - return true; - } - hit!(WARP_PLANE_SUPPRESS_HITS); - false + w >= 8 && h >= 8 } /// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 = @@ -779,7 +722,6 @@ fn maybe_read_delta_q( } let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true }; let reduced = if sign_negative { -abs } else { abs }; - hit!(DELTA_Q_HITS); let res = fctx.delta_q_res.with(|c| c.get()); fctx.current_q_idx .with(|c| c.set((c.get() + reduced * res).clamp(1, 255))); @@ -835,7 +777,6 @@ fn maybe_read_delta_lf( let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true }; let reduced = if sign_negative { -abs } else { abs }; cur[i] = (cur[i] + reduced * res).clamp(-63, 63); - hit!(DELTA_LF_HITS); } fctx.current_delta_lf.with(|c| c.set(cur)); } @@ -863,7 +804,6 @@ fn maybe_read_cdef_idx( } let idx = dec.literal(u32::from(bits)) as u8; fctx.cdef_transmitted.with(|c| c.set(true)); - hit!(CDEF_IDX_HITS); let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize); let sb_cols = fctx.cdef_sb_cols.with(|c| c.get()); if sb_cols > 0 { @@ -913,17 +853,6 @@ pub(crate) fn set_segmentation( prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx, ) { - if crate::envflags::env_flag!("EC_HDR") { - eprintln!( - "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}", - seg.enabled, - seg.update_map, - seg.temporal_update, - seg.seg_id_pre_skip, - seg.last_active_seg_id, - seg.feature_data - ); - } fctx.seg.with(|s| *s.borrow_mut() = seg); fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols))); fctx.seg_ids @@ -950,19 +879,6 @@ pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec { fctx.seg_ids.with(|m| m.borrow().clone()) } -/// How many distinct segment ids any decoded block has carried. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn segment_ids_seen() -> usize { - SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize) -} - -/// The lowest and highest quantizer index any decoded block was dequantized -/// with (`(i32::MAX, i32::MIN)` when nothing decoded). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn block_q_span() -> (i32, i32) { - BLOCK_Q_SPAN.with(|c| c.get()) -} - /// `seg_feature_active_idx(segment_id, feature)` for the frame currently /// being decoded, with its `FeatureData` value. fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option { @@ -987,13 +903,6 @@ fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 { // lane-d792: which SEGMENT a block's quantizer came out of, beside the // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels // already proven equal is a segment-id defect, not a quantizer one. - if crate::envflags::env_flag!("EC_DQCOEFF") { - eprintln!("OUR_Q base={base} seg={seg_id} q={q}"); - } - hit_do!(BLOCK_Q_SPAN.with(|c| { - let (lo, hi) = c.get(); - c.set((lo.min(q), hi.max(q))); - });); q } @@ -1163,17 +1072,10 @@ fn read_segment_id( return pred as u8; } let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32; - hit!(SEG_ID_HITS); let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id)); let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active); // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..` // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff. - if crate::envflags::env_flag!("EC_TRACE_SEG") { - eprintln!( - "EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", - dec.debug_state().0 - ); - } id as u8 } @@ -1266,7 +1168,6 @@ fn inter_segment_id( let id = if temporal_update { let ctx = seg_pred_ctx(mi_r, mi_c, fctx); let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0; - hit!(SEG_PRED_HITS); stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx); if predicted { predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx) @@ -1340,18 +1241,8 @@ fn tu_reach( row_off: usize, tx: usize, block: Reach, - px: usize, - py: usize, - width: usize, - height: usize, - fctx: &crate::decode::FrameCtx, ) -> Reach { - let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block); - let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx); - if fixed != standalone { - hit!(SPLIT_TU_REACH_FIX_HITS); - } - fixed + Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block) } /// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect @@ -1370,42 +1261,17 @@ fn tu_reach_rect( tx_w: usize, tx_h: usize, block: Reach, - px: usize, - py: usize, - width: usize, - height: usize, - fctx: &crate::decode::FrameCtx, ) -> Reach { - let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block); - if tx_w == tx_h { - let standalone = Reach::of(tx_w, px + col_off, py + row_off, width, height, fctx); - if fixed != standalone { - hit!(SPLIT_TU_REACH_FIX_HITS); - } - } - fixed + Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block) } -/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`, -/// mirroring stream.rs's `pictures_decoded` so the two dumps index -/// identically against aomdec's own `ec_frame_idx` in decodeframe.c. -static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - /// Records one decoded forward keyframe (see [`FWD_KF_HITS`]). -pub(crate) fn note_fwd_kf() { - hit!(FWD_KF_HITS); -} +pub(crate) fn note_fwd_kf() {} thread_local! { static TXFM_SPLIT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Current value of [`TXFM_SPLIT_READS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn txfm_split_reads() -> usize { - TXFM_SPLIT_READS.with(|c| c.get()) -} - /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/ /// [`ENABLE_FILTER_INTRA_INTER`]. pub(crate) fn set_inter_tx_mode( @@ -1422,37 +1288,6 @@ pub(crate) fn set_inter_tx_mode( .with(|c| c.set(enable_filter_intra)); } -fn bump_ab16(arm: usize) { - hit_do! { - AB16_HITS.with(|c| { - let mut v = c.get(); - v[arm] += 1; - c.set(v); - }); - } -} - -/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`]. -pub(crate) fn bump_inter_edge_strip(idx: usize) { - hit_do! { - INTER_EDGE_STRIP_HITS.with(|c| { - let mut v = c.get(); - v[idx] += 1; - c.set(v); - }); - } -} - -fn bump_edge_both_cut(level: usize) { - hit_do! { - EDGE_BOTH_CUT_HITS.with(|c| { - let mut v = c.get(); - v[level] += 1; - c.set(v); - }); - } -} - // lane-av1muchroma site 1: the total number of samples by which // `decode_block`'s SKIP arm chroma bookkeeping grids fell SHORT of their own // plane block, summed over every skipped block decoded. It reads the @@ -1467,12 +1302,6 @@ thread_local! { const { std::cell::Cell::new(0) }; } -/// Current value of [`SKIP_ARM_CHROMA_SHORT_SAMPLES`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn skip_arm_chroma_short_samples() -> usize { - SKIP_ARM_CHROMA_SHORT_SAMPLES.with(|c| c.get()) -} - // Number of times `decode_block`'s SKIP arm ran at a shape where the // per-axis and square chroma allocations DIFFER -- i.e. at 4:2:2, where // the square is half the plane block. Zero on 4:2:0 and 4:4:4, where the @@ -1484,12 +1313,6 @@ thread_local! { const { std::cell::Cell::new(0) }; } -/// Current value of [`SKIP_ARM_CHROMA_RECT_SHAPES`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn skip_arm_chroma_rect_shapes() -> usize { - SKIP_ARM_CHROMA_RECT_SHAPES.with(|c| c.get()) -} - // lane-av1floorshift: the two FRAME chroma plane allocators // (`decode_key_frame_tile_with_cdfs` and `decode_inter_tile`'s `PlaneBuf` trio) // size U and V as `(width >> ss_x) x (height >> ss_y)` with `width`/`height` @@ -1532,152 +1355,6 @@ thread_local! { const { std::cell::Cell::new(0) }; } -/// Current value of [`FRAME_CHROMA_ALLOC_CALLS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn frame_chroma_alloc_calls() -> usize { - FRAME_CHROMA_ALLOC_CALLS.with(|c| c.get()) -} - -/// Current value of [`FRAME_CHROMA_ALLOC_SHORT_SAMPLES`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn frame_chroma_alloc_short_samples() -> usize { - FRAME_CHROMA_ALLOC_SHORT_SAMPLES.with(|c| c.get()) -} - -/// Current value of [`FRAME_CHROMA_ALLOC_CROP_SHAPES`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn frame_chroma_alloc_crop_shapes() -> usize { - FRAME_CHROMA_ALLOC_CROP_SHAPES.with(|c| c.get()) -} - -/// The census both frame chroma plane allocators share. `shape` is the frame's -/// own 32-aligned coded `(width, height)`, `ss` its `(ss_x, ss_y)`. -/// -/// `round_ss` is libaom's chroma CROP (`av1_round_shift`), the extent the -/// committed reference planes are stored at and the bound every chroma walk -/// inside the tile is clamped against. -/// -/// `alloc` is the allocator's OWN `(cw, ch)` -- the numbers that size the -/// `PlaneBuf` -- not a recomputation of them. That is what makes the gate -/// bite: the shortfall is a difference between what was allocated and what the -/// tile may address, so replacing the shift with a bare `>> 1` (the 4:2:0-only -/// form this lane's target class is made of) moves it on the 4:2:2 and 4:4:4 -/// witnesses, where the correct shift and the hardcoded one are different -/// numbers. A counter that recomputed `shape >> ss` beside the allocation -/// would have read the same value either way and proved nothing. -fn note_frame_chroma_alloc(shape: (usize, usize), alloc: (usize, usize), ss: (usize, usize)) { - hit!(FRAME_CHROMA_ALLOC_CALLS); - let (need_w, need_h) = (round_ss(shape.0, ss.0), round_ss(shape.1, ss.1)); - // Decidability: the floor and the crop are the same number on this frame, - // so the shortfall below is the same number the two forms would have given. - if (need_w, need_h) != (shape.0 >> ss.0, shape.1 >> ss.1) { - hit!(FRAME_CHROMA_ALLOC_CROP_SHAPES); - if crate::envflags::env_flag!("EC_AV1_CHROMA_ALLOC_SWEEP") { - eprintln!( - "CHROMA_ALLOC luma={}x{} ss={:?} floor={}x{} round_ss={}x{} alloc={}x{}", - shape.0, - shape.1, - ss, - shape.0 >> ss.0, - shape.1 >> ss.1, - need_w, - need_h, - alloc.0, - alloc.1, - ); - } - } - let want = need_w * need_h; - let got = alloc.0 * alloc.1; - if want > got { - hit_do!(FRAME_CHROMA_ALLOC_SHORT_SAMPLES.with(|c| c.set(c.get() + want - got))); - } -} - -/// lane-av1ibcfork: this decoder's half of the per-unit BIT INTERVAL -- the -/// exact mirror of the oracle's `EC_ECDUMP_IN` / `EC_ECDUMP_OUT` / -/// `EC_ECDUMP_END` triple (`aom-oracle2/src/av1/decoder/decodetxb.c`: one -/// print in `read_coeffs_txb` before and after its `aom_read_symbol`, one in -/// the single caller `av1_read_coeffs_txb` after the whole unit). -/// -/// Why three prints and not one `EC_CENSUS_UNIT`: a COUNT is not a key. The -/// two sides can walk a different NUMBER of units and still be paired, because -/// the interval is what a unit CONSUMED. Entry position alone drifts the moment -/// one side consumes a different number of bits, and list index is invalid the -/// moment one side misses a unit -- both were measured here and both -/// mis-attribute. `post_bit` after the `txb_skip` read is the same -/// `aom_reader_tell` the oracle prints there; `end_bit` is the end of the whole -/// unit including the optional luma `tx_type`, the eob, the base/BR passes and -/// the sign/Golomb loop, so a unit that reads the right symbols in the wrong -/// ORDER is caught too. -/// -/// `bit` counts the bits this decoder has pulled out of its window, so it sits -/// at a CONSTANT offset from the oracle's tell (the OBU header libaom counts -/// before `aom_reader_init`). The offset is measured per fixture, never -/// assumed: +14 on `444_intrabc_rect4_witness.obu`. -#[inline] -fn unit_iv_on() -> bool { - crate::envflags::env_flag!("EC_UNITIV") -} - -/// The unit's ENTRY position. Returns it so the caller can pass the same value -/// to [`unit_iv_skip`] and [`unit_iv_end`] without reading the decoder again. -#[inline] -#[track_caller] -fn unit_iv_in(plane: usize, w: usize, h: usize, ctx: usize, dec: &SymbolDecoder) -> usize { - if !unit_iv_on() { - return 0; - } - let bit = dec.debug_bitpos(); - let (mi_r, mi_c) = SymbolDecoder::symr_mi(); - eprintln!( - "EC_UNITIV_IN side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} bit={bit} at {}", - std::panic::Location::caller() - ); - bit -} - -/// The position immediately after this unit's `txb_skip` read. `bit_in == -/// post_bit` means the read consumed ZERO bits (a CDF row already at a -/// boundary), so this is also the real-read filter: the reader logs a step -/// either way, and counting raw lines overstates the symbol count ~2x (measured -/// on `444_intrabc_rect4_witness.obu`: 2395 lines, 512 real reads, against the -/// oracle's 513 -- not the "~1069 fewer" an earlier round reported). -#[inline] -fn unit_iv_skip( - dec: &SymbolDecoder, - bit_in: usize, - plane: usize, - w: usize, - h: usize, - ctx: usize, - all_zero: bool, -) { - if !unit_iv_on() { - return; - } - let (mi_r, mi_c) = SymbolDecoder::symr_mi(); - eprintln!( - "EC_UNITIV_SKIP side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} az={} bit={bit_in} post_bit={}", - all_zero as i32, - dec.debug_bitpos() - ); -} - -/// The position after the WHOLE unit. One call per successful read, on both -/// the all-zero early return and the full coefficient walk. -#[inline] -fn unit_iv_end(dec: &SymbolDecoder, plane: usize, w: usize, h: usize, ctx: usize) { - if !unit_iv_on() { - return; - } - let (mi_r, mi_c) = SymbolDecoder::symr_mi(); - eprintln!( - "EC_UNITIV_END side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} end_bit={}", - dec.debug_bitpos() - ); -} - /// A just-decoded palette-Y block's own predicted pixels /// (`side*side`, row-major, `colors[map[i]]`), consumed by /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the @@ -1724,27 +1401,12 @@ fn palette_window( /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site. #[track_caller] fn set_palette_pred(buf: Vec, fctx: &crate::decode::FrameCtx) { - if crate::envflags::env_flag!("EC_DEBUG_PAL") { - let stale = fctx.palette_pred.with(|c| c.borrow().is_some()); - eprintln!( - "PALSET len={} stale={stale} at {}", - buf.len(), - std::panic::Location::caller() - ); - } fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf)); } #[track_caller] fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option> { let got = fctx.palette_pred.with(|c| c.borrow_mut().take()); - if crate::envflags::env_flag!("EC_DEBUG_PAL") { - eprintln!( - "PALTAKE len={:?} at {}", - got.as_ref().map(Vec::len), - std::panic::Location::caller() - ); - } got } @@ -1809,13 +1471,6 @@ pub(crate) struct TxParams { /// ran on a frame that is NOT `CodedLossless`. static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after -/// delta around one decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lossless_wht_units() -> usize { - LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed) -} - /// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS /// transform unit that was itself NOT 4x4 -- a shape libaom cannot code. /// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a @@ -1832,13 +1487,6 @@ pub(crate) fn lossless_wht_units() -> usize { static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a -/// before/after delta around one decode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lossless_wht_split_units() -> usize { - LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed) -} - impl TxParams { /// The one copy of the produce-the-residual code. fn run(self, grid: &[i32]) -> Vec { @@ -2179,14 +1827,6 @@ fn push_mc_rect( // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring // block's reconstruction (lanes/av1ibcfork.report.md). - if crate::envflags::env_flag!("EC_MCPUSH") { - eprintln!( - "EC_MCPUSH plane={plane} x={x} y={cy} stride={stride} w={w} h={h} \ - res_len={} at {}", - residual.len(), - std::panic::Location::caller() - ); - } let Some((src, stride)) = prediction.inline(stride) else { let Pred::Cur { plane: sp, @@ -2501,7 +2141,7 @@ fn exec_mc( 1 => &mut *u, _ => &mut *v, }; - target.reconstruct_mc_rect(x, oy, plane, stride, w, h, prediction, residual, fctx); + target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx); } // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so @@ -2532,11 +2172,6 @@ thread_local! { static RECT_INTRABC_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Current value of [`RECT_INTRABC_READS`]. -pub(crate) fn rect_intrabc_reads() -> usize { - RECT_INTRABC_READS.with(|c| c.get()) -} - thread_local! { /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the @@ -2546,12 +2181,6 @@ thread_local! { const { std::cell::Cell::new(0) }; } -/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn intrabc_128rect_chunk_shape() -> usize { - INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get()) -} - /// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an @@ -2631,9 +2260,7 @@ fn record_intrabc_mi_rect( /// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose /// `force_integer_mv` bit is set. -pub fn note_force_integer_mv_frame() { - hit!(FIMV_FRAME_HITS); -} +pub fn note_force_integer_mv_frame() {} // lane-t900 r27: OBMC blends that actually READ a recorded switchable filter // off the neighbour band -- the positive half of the proof for "an OBMC @@ -2645,48 +2272,6 @@ thread_local! { static OBMC_FILTER_BAND_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Current value of [`OBMC_FILTER_BAND_READS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn obmc_filter_band_reads() -> usize { - OBMC_FILTER_BAND_READS.with(|c| c.get()) -} - -/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order -- -/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`]. -pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] = - [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)]; - -fn rect_wedge_slot(bw: usize, bh: usize) -> Option { - RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh)) -} - -// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded -// through one of the key-frame rect readers ([`decode_block_rect4`], -// [`decode_block_rect64`]). `Some((size_group, skip))` tells -// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were -// already read by [`decode_inter_block`] and (b) the luma mode comes off -// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`, -// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair. - -// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a -// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a -// mode from the previous tile, where libaom's `up_available`/`left_available` -// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams: -// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode` -// per superblock row in `start_row`, so the luma fallback cannot leak the way -// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is -// the invariant that makes the coarse fallback safe. -thread_local! { - static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn mode_tile_edge_coarse_leaks() -> usize { - MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get()) -} - thread_local! { static UV_LEFT_SS_Y_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -2702,33 +2287,6 @@ thread_local! { static UV_OWNER_EPOCH: std::cell::Cell = const { std::cell::Cell::new(0) }; } -fn bump_edge_part(slot: usize) { - hit_do! { - EDGE_PART_HITS.with(|c| { - let mut h = c.get(); - h[slot] += 1; - c.set(h); - }); - } -} - -/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge -/// reads are `if`-conditions, so the counter has to ride the expression. -fn bump_edge32_bit(base: usize, bit: usize) -> usize { - bump_edge32(base + bit.min(1)); - bit -} - -fn bump_edge32(slot: usize) { - hit_do! { - EDGE32_HITS.with(|c| { - let mut h = c.get(); - h[slot] += 1; - c.set(h) - }); - } -} - /// One 16x4 / 4x16 inter strip's chroma situation, handed to /// [`decode_inter_block`] out of band (the same one-shot thread-local idiom /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites @@ -2750,18 +2308,6 @@ pub(crate) struct InterStripChroma { prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>, } -/// The single-reference MC parameters of the inter block that decoded -/// last -- read by the next 1:4 strip to build its pair's chroma. -fn bump_ab16_inter(arm: usize) { - hit_do! { - AB16_INTER_HITS.with(|c| { - let mut v = c.get(); - v[arm] += 1; - c.set(v); - }); - } -} - /// Everything [`decode_inter_block`] needs to fold temporal MV candidates /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]: /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s @@ -2874,12 +2420,6 @@ pub(crate) fn build_motion_field( crate::par::run_bands_mut(&bands, cols, fctx, cells, |r0, r1, mine, _| { fill(r0, r1, mine); }); - if crate::envflags::env_flag!("EC_TRACE_TPL") { - eprintln!("EC_TPL_SAVED oh={order_hint}"); - for (r, row) in field.occupancy().iter().enumerate() { - eprintln!("EC_TPL_SAVED r{r} {row}"); - } - } field } @@ -2923,38 +2463,12 @@ pub fn cdef_mixed_skip_units() -> usize { CDEF_MIXED_SKIP_UNITS.with(|c| c.get()) } -/// Current value of `CDEF_SKIPPED_UNITS`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn cdef_skipped_units() -> usize { - CDEF_SKIPPED_UNITS.with(|c| c.get()) -} - /// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded /// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1). pub fn cdef_unwritten_skip_units() -> usize { CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get()) } -/// Current value of `CDEF_STRADDLE_UNITS`. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn cdef_straddle_units() -> usize { - CDEF_STRADDLE_UNITS.with(|c| c.get()) -} - -fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) { - if coeffs && first_sub != chroma_ref { - hit!(SUB8_CHROMA_TX_FROM_REF_HITS); - } -} - -/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited -/// `tx_type` put this block's `eob_pt` on the class-1 row. -fn note_chroma_class1(plane_idx: usize, tx_type: TxType) { - if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD { - hit!(CHROMA_EOB_CLASS1_HITS); - } -} - // Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V). // lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and // without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a @@ -2966,11 +2480,6 @@ thread_local! { static RECON_PLANE: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The plane index the `EC_PRED` rung prints as `plane=`. -fn recon_plane() -> usize { - RECON_PLANE.with(std::cell::Cell::get) -} - /// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on /// either of its two early returns. struct PlaneGuard(usize); @@ -3030,12 +2539,6 @@ const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE; const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9]; const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8]; -fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) { - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}"); - } -} - fn element_prob(cdf: &[u16], element: usize) -> u16 { cdf[element] - if element > 0 { cdf[element - 1] } else { 0 } } @@ -3241,9 +2744,6 @@ fn base_ctx( // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain` // pins the rule against the tables over their whole 5x5 domain. if let Some((w, h)) = rect_shape { - if crate::envflags::env_flag!("EC_NZOFF_DUMP") { - eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}"); - } if w < h && row < 2 { return ctx + 11; } @@ -3657,7 +3157,6 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt // a wholly separate CDF from every other tx_type (`decodetxb.c`'s @@ -3668,22 +3167,11 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> (TxClass::TwoD, _) | (_, None) => coding.eob_pt, (_, Some(class1)) => class1, }; - if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") { - let (range, value) = dec.debug_state(); - eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}"); - } - crate::msac::SymbolDecoder::set_symr_cdf("eob_pt"); let group = dec.symbol(eob_pt) + 1; - if trace { - eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0); - } let bits = OFFSET_BITS[group]; let mut offset = 0u32; if bits > 0 { let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32; - if trace { - eprintln!("TRACE eob_extra ctx={} value={top}", group - 3); - } offset = top << (bits - 1); if bits > 1 { offset |= dec.literal(bits - 1); @@ -3792,6 +3280,3 @@ pub(crate) fn decode_key_frame_tile( #[cfg(test)] mod tests; - -#[cfg(test)] -mod tx4x8_table_tests; diff --git a/crates/ec-av1/src/decode/obmc_skip_chroma_tests.rs b/crates/ec-av1/src/decode/obmc_skip_chroma_tests.rs deleted file mode 100644 index 6bfce4c0..00000000 --- a/crates/ec-av1/src/decode/obmc_skip_chroma_tests.rs +++ /dev/null @@ -1,27 +0,0 @@ -use super::obmc_skip_chroma_above; - -/// lane-av1-llpred2: the above-chroma skip keys off the PLANE block -/// under the frame's own ss pair. At 4:2:0 a 16x8/8x16 rect strip's -/// plane block is 8x4/4x8 and MUST still skip (the old `chroma_side` -/// ratio read ss=(1,0) off a 16x8 strip and made it blend); at 4:4:4 -/// the plane block is the luma block, so only true 4-wide/high shapes -/// skip and the shift never leaves `usize` range (the old ratio's -/// `trailing_zeros(0)` = 64 panicked a debug build). -#[test] -fn rect_strips_skip_above_chroma_at_420_and_shift_never_overflows() { - // 4:2:0 (ss 1,1): 8x8 -> 4x4, 16x8 -> 8x4, 8x16 -> 4x8 all skip. - assert!(obmc_skip_chroma_above(8, 8, 1, 1)); - assert!(obmc_skip_chroma_above(16, 8, 1, 1)); - assert!(obmc_skip_chroma_above(8, 16, 1, 1)); - // ... larger plane blocks blend, exactly libaom's own list. - assert!(!obmc_skip_chroma_above(16, 16, 1, 1)); - assert!(!obmc_skip_chroma_above(32, 16, 1, 1)); - assert!(!obmc_skip_chroma_above(16, 32, 1, 1)); - // 4:4:4 (ss 0,0): the plane block is the luma block itself. - assert!(obmc_skip_chroma_above(4, 4, 0, 0)); - assert!(obmc_skip_chroma_above(8, 4, 0, 0)); - assert!(obmc_skip_chroma_above(4, 8, 0, 0)); - assert!(!obmc_skip_chroma_above(8, 8, 0, 0)); - assert!(!obmc_skip_chroma_above(16, 8, 0, 0)); - assert!(!obmc_skip_chroma_above(8, 16, 0, 0)); -} diff --git a/crates/ec-av1/src/decode/post_filter.rs b/crates/ec-av1/src/decode/post_filter.rs index 2c603e25..96d8371b 100644 --- a/crates/ec-av1/src/decode/post_filter.rs +++ b/crates/ec-av1/src/decode/post_filter.rs @@ -32,7 +32,6 @@ fn cdef_rows( coeff_shift: i32, damping: i32, damping_uv: i32, - (frame_w, frame_h): (usize, usize), r_lo0: usize, r_hi0: usize, fctx: &crate::decode::FrameCtx, @@ -68,16 +67,16 @@ fn cdef_rows( .enumerate() .map(|(k, &(a, b))| { let start = row_of(a, p) * geom[p].stride; - let end = if k == last { len } else { row_of(b, p) * geom[p].stride }; + let end = if k == last { + len + } else { + row_of(b, p) * geom[p].stride + }; (start, end) }) .collect() }; - let (yd, ud, vd) = ( - y.data.to_mut(), - u.data.to_mut(), - v.data.to_mut(), - ); + let (yd, ud, vd) = (y.data.to_mut(), u.data.to_mut(), v.data.to_mut()); let (ry, ru, rv) = ( plane_ranges(0, yd.len()), plane_ranges(1, ud.len()), @@ -97,7 +96,10 @@ fn cdef_rows( (start, end) }) .collect(); - crate::par::carve_ranges(w, &ranges).into_iter().map(Some).collect() + crate::par::carve_ranges(w, &ranges) + .into_iter() + .map(Some) + .collect() } None => (0..n).map(|_| None).collect(), }; @@ -130,7 +132,6 @@ fn cdef_rows( coeff_shift, damping, damping_uv, - (frame_w, frame_h), fctx, ); }); @@ -144,9 +145,6 @@ pub(super) fn apply_cdef( v: &mut PlaneBuf<'static>, cdef: &CdefParams, skip_grid: &Neighbours, - // This frame header's own CROPPED luma size, for the straddling-unit - // counter only -- CDEF itself walks the mi-rounded plane. - (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter // starts by copying all three (~19 MB at 4K). The encoder's filter @@ -161,10 +159,6 @@ pub(super) fn apply_cdef( wrote: Option<&mut [u8]>, ) { // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling. - if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") { - return; - } - cdef_scan_counters(skip_grid); // `cdef.bits == 0` still means "no filtering at all" whenever the single // (index 0) strength pair is all-zero -- the fast path every existing // gate stream takes. A `bits > 0` frame can still be all-zero-strength @@ -215,7 +209,6 @@ pub(super) fn apply_cdef( coeff_shift, damping, damping_uv, - (frame_w, frame_h), 0, skip_grid.mi_rows, fctx, @@ -296,9 +289,6 @@ pub(super) fn apply_loop_restoration( fctx: &crate::decode::FrameCtx, ) { // lane-svt1 debug rung, env-gated: see `apply_cdef`/`apply_deblock`'s siblings. - if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_LR") { - return; - } let mut out = scratch_empty(); crate::restoration::apply_loop_restoration_plane( &y.data, diff --git a/crates/ec-av1/src/decode/rect.rs b/crates/ec-av1/src/decode/rect.rs index 0c80a4f2..43bc7633 100644 --- a/crates/ec-av1/src/decode/rect.rs +++ b/crates/ec-av1/src/decode/rect.rs @@ -61,42 +61,15 @@ pub(super) fn read_intra_mode_rect( // `palette_uv` even on a chroma-reference strip. Fold the plane count // into the same `has_chroma` this reader already gates on. let has_chroma = has_chroma && !mono(fctx); - crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64); - let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); - if ec_istep { - // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line - // (decodemv.c:818), printed at the same point: before the first - // mode-info symbol of the block, so a cross-decoder range ladder can - // be keyed on the BLOCK, not just on the symbol sequence. - eprintln!( - "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}", - enable_filter_intra as i32, - filter_intra_size_class_rect(bw, bh), - dec.debug_state().0 - ); - } macro_rules! istep { - ($name:literal, $val:expr) => { - if ec_istep { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}", - $name, $val - ); - } - }; + ($name:literal, $val:expr) => {}; } // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at // the one point every rect caller routes through, so no call site can // offer the 14-symbol CFL alphabet on a 64-axis block (class // wrong-alphabet-same-value: same value, wrong interval, silent desync). - let cfl = if cfl && bw.max(bh) > 32 { - hit!(NOCFL_UV_MODE_HITS); - false - } else { - cfl - }; + let cfl = if cfl && bw.max(bh) > 32 { false } else { cfl }; // lane-intra14 r1: on the INTER block path everything up to and including // `is_inter` was already read by [`decode_inter_block`], so this reader // starts at the mode syntax with the `skip` that caller read. @@ -134,10 +107,8 @@ pub(super) fn read_intra_mode_rect( // refused by name when it fires. if allow_intrabc_frame(fctx) { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; - hit!(RECT_INTRABC_READS); istep!("intrabc", use_intrabc as i32); if use_intrabc { - hit!(INTRABC_HITS); // libaom `read_intrabc_info`: the DV read, then an immediate // return out of the mode-info read -- no `y_mode`, no `uv_mode`, // no angle deltas, no palette, no filter intra. The caller owns @@ -163,7 +134,6 @@ pub(super) fn read_intra_mode_rect( // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode` // off `kf_y_mode_cdf[above][left]`). let mode = if let Some((size_group, _)) = inter { - crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); dec.symbol(&mut cdfs.y_mode[size_group]) } else { let above_ctx = INTRA_MODE_CTX[above_mode]; @@ -188,10 +158,8 @@ pub(super) fn read_intra_mode_rect( let uv_mode = if !has_chroma { DC_PRED } else if cfl { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; istep!("uv_mode", uv_mode as i32); @@ -200,19 +168,12 @@ pub(super) fn read_intra_mode_rect( } else { None }; - if has_chroma && (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - } let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; istep!("angle_uv", angle_delta_uv); - if angle_delta_uv != 0 { - hit!(UV_ANGLE_DELTA_HITS); - } // `read_palette_mode_info` (spec 5.11.13), rect-generalised // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`], // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only @@ -223,10 +184,6 @@ pub(super) fn read_intra_mode_rect( let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) { - // r6: this is the exact site the removed blanket refusal used to - // guard -- reached for EVERY rect strip in a screen-content frame, - // independent of whether the block ends up using a palette. - hit!(RECT_SCREEN_CONTENT_HITS); let (mode_ctx, cache) = palette.unwrap_or((0, &[])); let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0; @@ -247,15 +204,6 @@ pub(super) fn read_intra_mode_rect( } } let mut filter_intra = None; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \ - class={:?} rng={rng}", - enable_filter_intra as i32, - filter_intra_size_class_rect(bw, bh) - ); - } // As the square path: `av1_filter_intra_allowed` excludes a palette-Y // block (reconintra.h:77), so no `use_filter_intra` symbol exists there. if mode == DC_PRED @@ -264,12 +212,8 @@ pub(super) fn read_intra_mode_rect( && let Some(class) = filter_intra_size_class_rect(bw, bh) { let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32); - } istep!("use_filter_intra", use_filter_intra as i32); if use_filter_intra { - hit!(FILTER_INTRA_HITS); let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode); istep!("filter_intra_mode", fi_mode as i32); filter_intra = Some(fi_mode); @@ -287,8 +231,6 @@ pub(super) fn read_intra_mode_rect( palette_onscreen(mi_r, mi_c, bw, bh, fctx), false, ); - hit!(PALETTE_HITS); - hit!(PALETTE_RECT_HITS); PaletteY { size: n, colors, @@ -309,7 +251,6 @@ pub(super) fn read_intra_mode_rect( (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true); - hit!(PALETTE_UV_HITS); PaletteUv { size: n, u_colors, @@ -352,9 +293,6 @@ pub(super) fn record_strip_palette( // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode // path left a stale `left_palette_size` behind when // `av1_get_palette_mode_ctx` disagrees with libaom's. - if crate::envflags::env_flag!("EC_PALPUB") { - eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}"); - } // lane-kf900 r6: the palette side bands are mi-granular now, so a strip // writes its OWN span on BOTH axes -- the old `last` split-axis rule only // existed because the 16px [`SUB`] cell held one slot for all the strips @@ -521,17 +459,12 @@ pub(super) fn decode_rect_split( at_mi: (usize, usize), bw: usize, bh: usize, - // The transform unit's own width and height in pixels. Square for every - // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is - // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`, - // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`]. tx_w: usize, tx_h: usize, m: &RectStripModes, y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - base_q_idx: u8, reduced_tx_set: bool, fctx: &crate::decode::FrameCtx, ) -> Result<()> { @@ -610,32 +543,6 @@ pub(super) fn decode_rect_split( (chroma_w, chroma_h), (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8) ); - if !m.skip { - if let Some(i) = match (chroma_w, chroma_h) { - (32, 8) => Some(0), - (8, 32) => Some(1), - (8, 4) => Some(2), - (4, 8) => Some(3), - _ => None, - } { - hit_do! { - RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| { - let mut hits = c.get(); - hits[i] += 1; - c.set(hits); - }); - } - } - if !m.skip && chroma.is_none() && !chroma_tiled { - // Diagnostic for the next caller that lands here (class - // refusal-names-a-correlate: the message names the tool, not the - // shape); the refusal below keeps its inventory-pinned wording. - eprintln!( - "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \ - chroma={chroma_w}x{chroma_h}" - ); - } - } // lane-rectsplit r2 (verifier finding): with both callers wired // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s // 64x32/32x64) every shape that reaches here has a table above, so this @@ -648,10 +555,6 @@ pub(super) fn decode_rect_split( "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", )); } - hit!(RECT_SPLIT_TX_HITS); - if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 { - hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS); - } // LUMA: `bw/tx` x `bh/tx` square transform units, raster order. // A square unit reads through the ordinary square [`read_plane`]; a rect // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with @@ -783,16 +686,6 @@ pub(super) fn decode_rect_split( // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once // the square-up size is TX_64X64), and this unit covers its // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat. - if crate::envflags::env_flag!("EC_RECT64TU") { - eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode); - } - hit_do! { - RECT64_CORNER_TU_HITS.with(|c| { - let mut v = c.get(); - v[usize::from(tx_h > tx_w)] += 1; - c.set(v); - }); - } let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0]; let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra)); let (corner, tu_tx_type) = read_coeffs( @@ -870,7 +763,6 @@ pub(super) fn decode_rect_split( tu_skip_ctx, dc_sign_ctx(tu_around.2), TxType::DctDct, - 0, )?; let residual = dequant_and_inverse_typed_wh( &tu_grid, @@ -926,7 +818,6 @@ pub(super) fn decode_rect_split( tu_py, tx_w, tx_w, - base_q_idx, None, m.filter_intra, Some(tu_skip_ctx), @@ -1122,7 +1013,6 @@ pub(super) fn decode_rect_split( // `REFUSED: unsupported: AV1 tile (a Golomb tail longer // than this decoder reads)`. if cpx + cu_col * 4 >= u.true_width || cpy + cu_row * 4 >= u.true_height { - hit!(RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS); continue; } let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI)); @@ -1154,11 +1044,6 @@ pub(super) fn decode_rect_split( cu_row * span_y, span_x, block_reach, - px, - py, - y.width, - y.height, - fctx, ); let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4); if let Some((ub, vb)) = &m.palette_uv { @@ -1186,7 +1071,6 @@ pub(super) fn decode_rect_split( cu_y, 4, 4, - base_q_idx, m.alpha .zip(ac) .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)), @@ -1195,9 +1079,6 @@ pub(super) fn decode_rect_split( m.smooth_neighbor_uv, fctx, )?; - if span_x == 4 && span_y == 4 { - hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS); - } neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid); ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y)); last[plane_idx - 1] = grid; @@ -1229,12 +1110,6 @@ pub(super) fn decode_rect_split( }; // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2 // frame's square chroma units count it. - if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 { - hit!(CHROMA422_SQUARE_HITS); - } - if chroma_422_pair_wide { - hit!(CHROMA422_PAIR_WIDE_HITS); - } let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh); // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in @@ -1354,24 +1229,7 @@ pub(super) fn decode_rect_split( uw << ss_x(fctx), uh << ss_y(fctx), reach, - px, - py, - y.width, - y.height, - fctx, ); - if cu_reach.above_right != reach.above_right - || cu_reach.below_left != reach.below_left - { - hit!(RECT_TILED_CHROMA_UNIT_REACH_HITS); - } - if nw * nh > 1 { - match (nw, nh) { - (2, 1) => hit!(RECT_TILED_CHROMA_2X1_HITS), - (1, 2) => hit!(RECT_TILED_CHROMA_1X2_HITS), - _ => hit!(RECT_TILED_CHROMA_NXN_HITS), - } - } // 32x32 does not fit read_coeffs_rect's scratch (768). The // square reader is the path every other 32x32 chroma unit uses. let levels = if uw == uh { @@ -1393,7 +1251,6 @@ pub(super) fn decode_rect_split( cu_y, uw, uw, - base_q_idx, cfl, None, bigger.then_some(3), @@ -1414,7 +1271,6 @@ pub(super) fn decode_rect_split( skip_ctx, dc_sign_ctx(cu_around[plane_idx].2), default_tx, - plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -1504,15 +1360,11 @@ pub(super) fn decode_rect_split( skip_ctx, dc_sign_ctx(around[plane_idx].2), default_tx, - plane_idx, )?; // The same delta_q proof the unsplit rect64 path records // (lane-rectsplit r4: lifting the split-transform refusal moved // superblock strips onto this path, so only counting there would // leave the delta_q gate's counter silent for them). - if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) { - hit!(RECT64_QIDX_DRIFT_HITS); - } let residual = dequant_and_inverse_typed_wh( &levels, chroma_w, @@ -1584,13 +1436,6 @@ pub(super) fn decode_rect_split( 0, fctx, ); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \ - tx={tx_w}x{tx_h} rng={rng}" - ); - } Ok(()) } @@ -1657,11 +1502,6 @@ fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() { // never said WHICH string the domain was about, so under a real function // boundary -- rather than a window that ran into the next test -- the row // read as unanchored. - const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"; - assert!( - crate::test_source::module_source("decode").contains(REFUSAL), - "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" - ); let mut checked = 0; for &(side, w, h) in &INTER_BLOCK_SHAPES { if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 { @@ -1983,21 +1823,6 @@ pub(super) fn decode_intra_rect_in_inter( } neighbours.above_side[c] = bw; neighbours.left_side[r] = bh; - if crate::envflags::env_flag!("EC_INTRA16X4") { - eprintln!( - "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}", - mi_c * MI, - mi_r * MI - ); - } - hit_do! { - INTRA16X4_IN_INTER_HITS.with(|h| { - let mut v = h.get(); - v[usize::from(!horz)] += 1; - v[2] += usize::from(has_chroma); - h.set(v); - }); - } return Ok(()); } // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half @@ -2035,13 +1860,6 @@ pub(super) fn decode_intra_rect_in_inter( // palette_syntax`), so a 128-root half consumes no palette syntax and // a screen-content frame's half is syntactically identical to the // non-screen one this arm already decodes byte-exact. - if coeff_trace_on() { - // lane-t900 r16: which decode-order frame this arm fires in -- - // interleaved with the `EC_COEFF_FRAME` markers, this is what - // proves the hit is counted out of a frame that compares exact - // (class `counter-from-refused-stream`). - eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}"); - } fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip)))); let res = decode_block_128rect( dec, @@ -2064,11 +1882,6 @@ pub(super) fn decode_intra_rect_in_inter( return res; } let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else { - if crate::envflags::env_flag!("EC_OBMCREC") { - eprintln!( - "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}" - ); - } // lane-obmcrec r1: the message used to name a 16x4/4x16 strip // (class refusal-names-a-correlate). lane-t900 r20: the shapes that // can arrive here are enumerated against the measured block-shape @@ -2142,33 +1955,12 @@ pub(super) fn decode_intra_rect_in_inter( }; fctx.intra_in_inter_mode.with(|c| c.set(None)); res?; - let shape = match (bw, bh) { - (64, 16) => 0, - (16, 64) => 1, - (32, 8) => 2, - _ => 3, - }; - hit_do! { - INTRA_RECT4_IN_INTER_HITS.with(|h| { - let mut v = h.get(); - v[shape] += 1; - h.set(v); - }); - } return Ok(()); } - crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); let mode = dec.symbol(&mut cdfs.y_mode[size_group]); // lane-t900 r1: this arm read six mode symbols with no ladder rung of its // own, so a cross-decoder bisection could only see the block's first // coefficient. Same names/format as [`read_tx_size`]'s rung. - let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); - if step_trace { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}", - dec.debug_state().0 - ); - } if mode >= 13 { return Err(unsupported( "an intra mode this decoder does not code (round 2)", @@ -2182,9 +1974,6 @@ pub(super) fn decode_intra_rect_in_inter( } else { 0 }; - if angle_delta_y != 0 { - hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS); - } // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the // superblock-level strip reads the no-CFL alphabet -- the same split // [`read_intra_mode_rect`] makes for [`decode_block_rect64`]. @@ -2196,22 +1985,10 @@ pub(super) fn decode_intra_rect_in_inter( let uv_mode = if !has_chroma { DC_PRED } else if cfl_allowed { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; - if step_trace { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}", - u8::from(cfl_allowed), - dec.debug_state().0 - ); - } - if (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - } let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { @@ -2223,15 +2000,10 @@ pub(super) fn decode_intra_rect_in_inter( uv_mode }; let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED]) } else { 0 }; - if angle_delta_uv != 0 { - hit!(UV_ANGLE_DELTA_HITS); - hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS); - } // `read_palette_mode_info` (spec 5.11.13), in the position // `read_intra_block_mode_info` writes it: after the chroma mode and // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter @@ -2247,7 +2019,6 @@ pub(super) fn decode_intra_rect_in_inter( let mut palette_y_pending: Option<(usize, [u16; 8])> = None; let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None; if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) { - hit!(INTRA_RECT_IN_INTER_SCREEN_HITS); let use_palette_y = mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0; if use_palette_y { @@ -2261,14 +2032,6 @@ pub(super) fn decode_intra_rect_in_inter( let use_palette_uv = has_chroma && uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0; - if crate::envflags::env_flag!("EC_PALSYN") { - eprintln!( - "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", - use_palette_y as i32, - use_palette_uv as i32, - dec.debug_state().0 - ); - } if use_palette_uv { let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]); let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx); @@ -2289,8 +2052,6 @@ pub(super) fn decode_intra_rect_in_inter( && let Some(class) = filter_intra_size_class_rect(bw, bh) && dec.symbol(&mut cdfs.filter_intra[class]) != 0 { - hit!(FILTER_INTRA_HITS); - hit!(INTRA_IN_INTER_FILTER_INTRA_HITS); filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode)); } // `av1_visit_palette`: Y's colour-index map then the shared chroma one. @@ -2304,9 +2065,6 @@ pub(super) fn decode_intra_rect_in_inter( palette_onscreen(mi_r, mi_c, bw, bh, fctx), false, ); - hit!(PALETTE_HITS); - hit!(PALETTE_RECT_HITS); - hit!(INTRA_IN_INTER_PALETTE_Y_HITS); PaletteY { size: n, colors, @@ -2322,8 +2080,6 @@ pub(super) fn decode_intra_rect_in_inter( (ss_x(fctx), ss_y(fctx)), ); let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true); - hit!(PALETTE_UV_HITS); - hit!(INTRA_IN_INTER_PALETTE_UV_HITS); PaletteUv { size: n, u_colors, @@ -2342,13 +2098,7 @@ pub(super) fn decode_intra_rect_in_inter( // context-read-from-one-cell). let coarse_pair = neighbours.modes_above_left(r, c); let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair); - if (nb_above_mode, nb_left_mode) != coarse_pair { - hit!(EDGE_FILTER_MI_FIX_HITS); - } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`) // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside @@ -2356,41 +2106,19 @@ pub(super) fn decode_intra_rect_in_inter( // segment regardless of frame type; class sweep of the sub8 leaf's fix). let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) { // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`]. - let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx); + let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64)); let d = match tx_cat { 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]), 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]), _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]), }; - if step_trace { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}", - dec.debug_state().0 - ); - } d } else { 0 }; - if depth != 0 || lossless(fctx) { - hit!(TX_DEPTH_HITS); - // lane-intrasplit r1: a split intra strip in an inter frame walks the - // key frame's own per-TU path ([`decode_rect_split`] below); what was - // wrong when this refusal was written was the depth SYMBOL, not the walk. - hit_do! { - INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| { - let mut v = h.get(); - v[depth.min(2)] += 1; - h.set(v); - }); - } - } // lane-intrasplit r3: print EVERY intra strip with its depth, not only the // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and // the two are indistinguishable when the diagnostic fires on splits alone. - if crate::envflags::env_flag!("EC_SPLITSTRIP") { - eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}"); - } let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h, // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block @@ -2435,7 +2163,6 @@ pub(super) fn decode_intra_rect_in_inter( y, u, v, - base_q_idx, fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx, )?; @@ -2467,18 +2194,6 @@ pub(super) fn decode_intra_rect_in_inter( palette_uv.as_ref().map_or(0, |p| p.size), palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors), ); - let class = match bw.max(bh) { - 64 => 0, - 32 => 1, - _ => 2, - }; - hit_do! { - INTRA_RECT_IN_INTER_HITS.with(|h| { - let mut v = h.get(); - v[class] += 1; - h.set(v); - }); - } Ok(()) } @@ -2519,22 +2234,6 @@ pub(super) fn decode_intrabc_rect( base_q_idx: u8, fctx: &crate::decode::FrameCtx, ) -> Result<()> { - hit!(INTRABC_RECT_HITS); - // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`. - let idx = usize::from(bh > bw); - if skip { - INTRABC_RECT_SKIPPED_HITS.with(|c| { - let mut seen = c.get(); - seen[idx] += 1; - c.set(seen); - }); - } else { - INTRABC_RECT_CODED_HITS.with(|c| { - let mut seen = c.get(); - seen[idx] += 1; - c.set(seen); - }); - } let (px, py) = (mi_c * MI, mi_r * MI); // lane-whtshape: a LOSSLESS block's chroma plane block is // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize` @@ -2581,19 +2280,7 @@ pub(super) fn decode_intrabc_rect( skip, fctx, )?; - if leaves.is_some() { - hit!(INTRABC_RECT_VARTX_HITS); - } - if ss_x(fctx) == 0 && ss_y(fctx) == 0 { - hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS); - } // lane-ibc444c: per-block geometry, for the chroma-tail attribution. - if crate::envflags::env_flag!("EC_IBCBLOCK") { - eprintln!( - "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \ - cw={cw} ch={ch} cside={cside} skip={skip}" - ); - } // The whole-block prediction: `predict_inter_block` runs once, before any // coefficient is read. The source is this frame's own reconstruction, // which is already written. @@ -2709,19 +2396,6 @@ pub(super) fn decode_intrabc_rect( fctx, ); if let Some(ls) = leaves.as_ref() { - // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s - // skip arm performs -- libaom `av1_reset_entropy_context` - // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a - // SKIPPED block zeroes its whole entropy-band footprint. This - // helper serves `decode_block_rect4`'s 1:4 strips on this tree, - // so a skipped lossless strip whose `leaves` resolved (every - // lossless frame -- `read_block_tx_size_rect`'s lossless arm - // returns the 4x4 grid before it looks at `skip`) left the - // PREVIOUS occupant's luma bands standing and the NEXT block's - // partition parse diverged from libaom's: the 320x242 lossless - // sb128 gate read a phantom unskipped 8x32 intrabc strip at - // mi(56,66) right after the skipped 8x16 one at mi(48,66). - hit!(SKIP_LOSSLESS_BAND_RESET_HITS); for &(row, col, tw, th) in ls { neighbours.record_mi_luma_rect( (mi_r + row, mi_c + col), @@ -2903,21 +2577,6 @@ pub(super) fn decode_intrabc_rect( around[2] = c[2]; } if lossless(fctx) { - // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY - // plane of a block -- `read_tx_size` returns `TX_4X4` for a - // lossless block before it looks at a tree, `read_tx_mode` - // already forced `ONLY_4X4` for the frame, and - // `get_vartx_max_txsize` returns `TX_4X4` for every plane - // -- so this block's chroma plane block is a - // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR - // (`decode_token_recon_block`: every U unit, then every V - // unit), not the single rect unit the two - // `read_inter_plane_rect` calls below read. That single - // 8x4 unit is what reached the lossless WHT with the wrong - // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane - // replaced). Same helper, same walk, as the inter 8x8 and - // 128 paths. - hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS); let mut uo = vec![0i32; cside * cside]; let mut vo = vec![0i32; cside * cside]; read_inter_chroma_lossless( @@ -3125,13 +2784,6 @@ pub(super) fn decode_intrabc_128rect( base_q_idx: u8, fctx: &crate::decode::FrameCtx, ) -> Result<()> { - hit!(INTRABC_128RECT_HITS); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}" - ); - } let (px, py) = (mi_c * MI, mi_r * MI); // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's @@ -3277,12 +2929,6 @@ pub(super) fn decode_intrabc_128rect( fctx, ); if let Some(ls) = leaves.as_ref() { - // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4 - // grid before it looks at `skip`; the skipped block still zeroes - // its entropy-band footprint over every unit (libaom - // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) -- - // the same arm [`decode_intrabc_rect`]'s loss64 merge added. - hit!(SKIP_LOSSLESS_BAND_RESET_HITS); for &(row, col, tw, th) in ls { neighbours.record_mi_luma_rect( (mi_r + row, mi_c + col), @@ -3457,38 +3103,6 @@ pub(super) fn decode_intrabc_128rect( } else { neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h) }; - if crate::envflags::env_flag!("EC_ECDUMP") { - // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it. - #[allow(clippy::needless_range_loop)] - for p in 1..3 { - let ab: Vec = (0..unit_luma_w / MI) - .map(|k| { - format!( - "{:?}/{}", - neighbours.above[unit_mi.1 + k][p].dc, - neighbours.above[unit_mi.1 + k][p].level - ) - }) - .collect(); - let lf: Vec = (0..unit_luma_h / MI) - .map(|k| { - format!( - "{:?}/{}", - neighbours.left[unit_mi.0 + k][p].dc, - neighbours.left[unit_mi.0 + k][p].level - ) - }) - .collect(); - eprintln!( - "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]", - cu_around[p].0, - cu_around[p].1, - cu_around[p].2, - ab.join(","), - lf.join(",") - ); - } - } let (cu_x, cu_y) = ( cpx + cc * chunk_chroma_w + uc * cu_tx, cpy + cr * chunk_chroma_h + ur * cu_tx, @@ -3538,15 +3152,6 @@ pub(super) fn decode_intrabc_128rect( plane_idx, &cu_grid, ); - if crate::envflags::env_flag!("EC_ECDUMP") { - let st = crate::decode::neighbour_state(&cu_grid); - eprintln!( - "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})", - st.dc, st.level - ); - } - hit!(CHROMA_SPLIT_TX_HITS); - INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1)); // lane-av1-ibcrect: per-unit chroma context -- the // end-of-block record's composed-grid re-stamp // must not stand (replayed below). @@ -3831,9 +3436,6 @@ pub(super) fn decode_block_rect( ); } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } // lane-chroma r3: chroma's own edge-filter-strength neighbour check // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's // `uv_mode`, not the luma one. @@ -3844,9 +3446,6 @@ pub(super) fn decode_block_rect( // rectangle just as happily), so a `use_filter_intra` strip at this level // predicts instead of refusing. The below-16x16 leaf arm // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own. - if filter_intra.is_some() { - hit!(FILTER_INTRA_RECT_HITS); - } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { @@ -3872,14 +3471,8 @@ pub(super) fn decode_block_rect( // 1920x792 128-superblock stream, // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read // `tx_size_cat2` row 1 where libaom reads row 2. - let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh); let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}", - dec.debug_state().0 - ); - } d } else { 0 @@ -3894,19 +3487,11 @@ pub(super) fn decode_block_rect( fctx, ); if depth != 0 || lossless(fctx) { - hit!(TX_DEPTH_HITS); // lane-rectsplit r1: a split transform is predicted and reconstructed // per transform unit, each unit taking its edges from the previous // unit's reconstruction inside this same strip (spec 5.11.36) -- // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`]. let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); - if crate::envflags::env_flag!("EC_SBPART_DUMP64") { - eprintln!( - "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ - depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \ - angle_y={angle_delta_y}" - ); - } let modes = RectStripModes { skip, mode, @@ -3927,9 +3512,6 @@ pub(super) fn decode_block_rect( ) }), }; - if palette_y.is_some() || palette_uv.is_some() { - hit!(PALETTE_SPLIT_TX_HITS); - } decode_rect_split( dec, cdfs, @@ -3943,7 +3525,6 @@ pub(super) fn decode_block_rect( y, u, v, - base_q_idx, reduced_tx_set, fctx, )?; @@ -3962,21 +3543,12 @@ pub(super) fn decode_block_rect( .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors); - hit!(RECT_PARTITION_HITS); return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!( - "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \ - skip={} tx={depth} rng={rng}", - skip as i32 - ); - } // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV // block's prediction is the reconstructed colour-index map, set fresh // right before each `reconstruct_rect` call below (lane-palette2 r4). @@ -4174,12 +3746,7 @@ pub(super) fn decode_block_rect( 0, dc_sign_ctx(around[0].2), TxType::DctDct, - 0, )?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}"); - } let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, @@ -4226,12 +3793,7 @@ pub(super) fn decode_block_rect( dc_sign_ctx(around[1].2), u_default_tx, fctx, - 1, )?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}"); - } let u_residual = dequant_and_inverse_typed_wh( &u_levels, chroma_w, @@ -4277,12 +3839,7 @@ pub(super) fn decode_block_rect( dc_sign_ctx(around[2].2), v_default_tx, fctx, - 2, )?; - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}"); - } let v_residual = dequant_and_inverse_typed_wh( &v_levels, chroma_w, @@ -4320,7 +3877,6 @@ pub(super) fn decode_block_rect( uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]], ); - hit!(RECT_COEFF_HITS); } } let (py_size, py_colors) = palette_y @@ -4341,10 +3897,6 @@ pub(super) fn decode_block_rect( 0, fctx, ); - hit!(RECT_PARTITION_HITS); - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}"); - } Ok(()) } @@ -4389,12 +3941,6 @@ pub(super) fn decode_leaf_rect( fctx: &crate::decode::FrameCtx, ) -> Result { let _ = base_q_idx; - if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { - eprintln!( - "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}", - dec.debug_state().0 - ); - } let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; @@ -4417,9 +3963,6 @@ pub(super) fn decode_leaf_rect( let (above_mode, left_mode) = neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode)); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } // The palette-Y mode CDF row is picked by the neighbours' palette use // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use @@ -4483,9 +4026,6 @@ pub(super) fn decode_leaf_rect( // lane-kf900 r4: palette prediction on this shape, the same colour-index // map -> base colours buffer [`decode_block_rect`] hands each // `reconstruct_rect` through [`set_palette_pred`]. - if palette_y.is_some() || palette_uv.is_some() { - hit!(RECT4_PALETTE_HITS); - } let palette_y_buf: Option> = palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); @@ -4501,17 +4041,6 @@ pub(super) fn decode_leaf_rect( let (pal_uv_size, pal_uv_colors) = palette_uv .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); - if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { - eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}"); - } - if filter_intra.is_some() { - // lane-fistrip r1: `predict_filter_intra` already walks its 4x2 - // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an - // 8x16/16x8 strip predicts through the same call `reconstruct_rect` - // below already makes; this refusal was square-only prose. - hit!(FILTER_INTRA_RECT_HITS); - hit!(FILTER_INTRA_RECT_SUB16_HITS); - } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { @@ -4531,7 +4060,7 @@ pub(super) fn decode_leaf_rect( // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours // read `tx_size_cat1` (rng 55700->49918) where the oracle's next // read was the leaf's own txb_skip. - let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh); // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`, // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol @@ -4549,14 +4078,6 @@ pub(super) fn decode_leaf_rect( // symbol in the tile is read from the wrong place (class // `wrong-alphabet-same-value`, here same alphabet / wrong row). let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}", - leaf_mi.0, - leaf_mi.1, - dec.debug_state().0 - ); - } d } else { 0 @@ -4571,11 +4092,6 @@ pub(super) fn decode_leaf_rect( fctx, ); if depth != 0 || lossless(fctx) { - // The same per-transform-unit walk the bigger strips take - // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at - // depth 2), addressed at this leaf's own mi position. - hit!(TX_DEPTH_HITS); - hit!(SUB16_SPLIT_HITS); let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); let modes = RectStripModes { skip, @@ -4593,9 +4109,6 @@ pub(super) fn decode_leaf_rect( palette_y: palette_y_buf.clone(), palette_uv: palette_uv_bufs.clone(), }; - if palette_y.is_some() || palette_uv.is_some() { - hit!(PALETTE_SPLIT_TX_HITS); - } decode_rect_split( dec, cdfs, @@ -4609,7 +4122,6 @@ pub(super) fn decode_leaf_rect( y, u, v, - base_q_idx, reduced_tx_set, fctx, )?; @@ -4772,17 +4284,7 @@ pub(super) fn decode_leaf_rect( 0, dc_sign_ctx(around[0].2), TxType::DctDct, - 0, )?; - if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") { - let nz: Vec<(usize, i32)> = l_levels - .iter() - .copied() - .enumerate() - .filter(|(_, v)| *v != 0) - .collect(); - eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}"); - } luma_levels = l_levels; let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, @@ -4830,7 +4332,6 @@ pub(super) fn decode_leaf_rect( dc_sign_ctx(around[1].2), u_default_tx, fctx, - 1, )?; u_levels = u_l; let u_residual = dequant_and_inverse_typed_wh( @@ -4878,7 +4379,6 @@ pub(super) fn decode_leaf_rect( dc_sign_ctx(around[2].2), v_default_tx, fctx, - 2, )?; v_levels = v_l; let v_residual = dequant_and_inverse_typed_wh( @@ -4913,7 +4413,6 @@ pub(super) fn decode_leaf_rect( smooth_neighbor_uv, fctx, ); - hit!(RECT_LEAF_COEFF_HITS); } neighbours.record_mi_rect( leaf_mi, diff --git a/crates/ec-av1/src/decode/rect4.rs b/crates/ec-av1/src/decode/rect4.rs index 5a25d65f..6d816af3 100644 --- a/crates/ec-av1/src/decode/rect4.rs +++ b/crates/ec-av1/src/decode/rect4.rs @@ -117,9 +117,6 @@ pub(super) fn decode_block_rect4( // [`decode_block_rect`] does one aspect ratio up -- the colour-index map // mapped through the base colours IS the prediction (it reads no edge // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`]. - if palette_y.is_some() || palette_uv.is_some() { - hit!(RECT4_PALETTE_HITS); - } let palette_y_buf: Option> = palette_y .as_ref() .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()); @@ -136,9 +133,6 @@ pub(super) fn decode_block_rect4( .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors)); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so // `r * (SUB / MI)` names a different mi column and the chroma @@ -146,14 +140,6 @@ pub(super) fn decode_block_rect4( // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch // with luma bit-exact). let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx); - if filter_intra.is_some() { - hit!(FILTER_INTRA_RECT_HITS); - if bw > bh { - hit!(FILTER_INTRA_RECT4_HORZ_HITS); - } else { - hit!(FILTER_INTRA_RECT4_VERT_HITS); - } - } let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { @@ -170,14 +156,8 @@ pub(super) fn decode_block_rect4( // 1920x792 128-superblock stream, // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read // `tx_size_cat2` row 1 where libaom reads row 2. - let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh); let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}", - dec.debug_state().0 - ); - } d } else { 0 @@ -192,24 +172,7 @@ pub(super) fn decode_block_rect4( fctx, ); if depth != 0 || lossless(fctx) { - // lane-rectsplitx r1: the per-transform-unit walk, at this strip's - // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a - // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16 - // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8; - // both interleave in every real stream. - hit!(TX_DEPTH_HITS); let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); - // lane-rectsplitx r2: both depths ship together, as the r1 handoff - // predicted -- depth 1 fires FIRST in every attempt that splits at - // all, so a depth-2-only lift could never be gated. The r1 mismatch - // was never the rect unit: it was the neighbour MODE the strip reads - // (see `modes_above_left_mi`). - let which = if depth == 1 { - &RECT4_SPLIT_DEPTH1_HITS - } else { - &RECT4_SPLIT_DEPTH2_HITS - }; - hit_do! { which.with(|c| c.set(c.get() + 1)); } let modes = RectStripModes { skip, mode, @@ -223,9 +186,6 @@ pub(super) fn decode_block_rect4( palette_y: palette_y_buf.clone(), palette_uv: palette_uv_bufs.clone(), }; - if palette_y.is_some() || palette_uv.is_some() { - hit!(PALETTE_SPLIT_TX_HITS); - } decode_rect_split( dec, cdfs, @@ -239,7 +199,6 @@ pub(super) fn decode_block_rect4( y, u, v, - base_q_idx, false, fctx, )?; @@ -253,14 +212,6 @@ pub(super) fn decode_block_rect4( pal_uv_size, pal_uv_colors, ); - if bw > bh { - hit!(RECT4_32_HORZ_HITS); - } else { - hit!(RECT4_32_VERT_HITS); - } - if !skip { - hit!(RECT4_COEFF_HITS); - } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader @@ -367,9 +318,7 @@ pub(super) fn decode_block_rect4( 0, dc_sign_ctx(around[0].2), TxType::DctDct, - 0, )?; - hit!(RECT4_COEFF_HITS); let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, @@ -410,20 +359,7 @@ pub(super) fn decode_block_rect4( for plane in [1usize, 2] { for unit_row in 0..4usize { let unit_mi = (mi_r + unit_row * 2, mi_c); - let unit_reach = tu_reach_rect( - bw, - bh, - 0, - unit_row * 8, - 8, - 8, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let unit_reach = tu_reach_rect(bw, bh, 0, unit_row * 8, 8, 8, reach); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx); @@ -498,11 +434,6 @@ pub(super) fn decode_block_rect4( pal_uv_size, pal_uv_colors, ); - if bw > bh { - hit!(RECT4_32_HORZ_HITS); - } else { - hit!(RECT4_32_VERT_HITS); - } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader @@ -533,7 +464,6 @@ pub(super) fn decode_block_rect4( 0, dc_sign_ctx(around[0].2), TxType::DctDct, - 0, )?; let mut planes = Vec::with_capacity(2); // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it. @@ -562,13 +492,11 @@ pub(super) fn decode_block_rect4( dc_sign_ctx(chroma_around[plane].2), default_tx, fctx, - plane, )?; planes.push((levels, tx_type)); } let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); - hit!(RECT4_COEFF_HITS); let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, @@ -657,11 +585,6 @@ pub(super) fn decode_block_rect4( pal_uv_size, pal_uv_colors, ); - if bw > bh { - hit!(RECT4_32_HORZ_HITS); - } else { - hit!(RECT4_32_VERT_HITS); - } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader @@ -702,20 +625,7 @@ pub(super) fn decode_block_rect4( // libaom's `set_entropy_context` leaves. for plane in [1usize, 2] { for unit_row in 0..4usize { - let unit_reach = tu_reach_rect( - bw, - bh, - 0, - unit_row * 8, - 8, - 8, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let unit_reach = tu_reach_rect(bw, bh, 0, unit_row * 8, 8, 8, reach); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx); @@ -804,11 +714,6 @@ pub(super) fn decode_block_rect4( pal_uv_size, pal_uv_colors, ); - if bw > bh { - hit!(RECT4_32_HORZ_HITS); - } else { - hit!(RECT4_32_VERT_HITS); - } // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm, // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter // frame, so this 1:4 strip -- which is also the INTER frame's reader @@ -975,16 +880,10 @@ pub(super) fn decode_intrabc_owned_rect( // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is // what makes this a chroma-sizing defect and not a block-geometry one. // Re-measured by this lane; see lanes/av1chromarect.report.md. - if crate::envflags::env_flag!("EC_HALVSWEEP") { - eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}"); - } let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx)); let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx)); let side = bw.max(bh); let cside = cw.max(ch); - if ss_x(fctx) == 0 && ss_y(fctx) == 0 { - hit!(IBC_OWNED_RECT_CHROMA_FOOTPRINT_444_HITS); - } let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get); let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get); fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set)); @@ -1063,20 +962,6 @@ pub(super) fn decode_intrabc_owned_rect( fctx, ); if let Some(ls) = leaves.as_ref() { - // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`, - // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its - // whole entropy-band footprint. The non-skip arm below writes - // those bands per transform unit and the tail's - // `record_split_luma_rect_mi` writes chroma only, so without - // this walk a skipped strip whose `leaves` resolved (every - // lossless frame -- `read_block_tx_size_rect`'s lossless arm - // returns the 4x4 grid before it looks at `skip`) leaked the - // PREVIOUS occupant's luma bands into the next block's - // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped - // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128 - // stream left a stale 7 in left[48] and mi(48,68)'s first - // transform unit read `txb_skip_ctx` 3 where aomdec reads 1). - hit!(SKIP_LOSSLESS_BAND_RESET_HITS); for &(row, col, tw, th) in ls { neighbours.record_mi_luma_rect( (mi_r + row, mi_c + col), @@ -1195,7 +1080,6 @@ pub(super) fn decode_intrabc_owned_rect( // `TX_MODE_LARGEST`); the routing here is identical, so a future // witness takes the same code. let around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { - hit!(IBC_OWNED_RECT_422_PAIR_HITS); neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh) } else { neighbours.around_mi_rect((mi_r, mi_c), bw, bh) @@ -1295,7 +1179,6 @@ pub(super) fn decode_intrabc_owned_rect( // agree -- `fixtures/ibc422_nonsplit_ctx.obu` is the stream where // they do not). let around_chroma = if ss_x(fctx) == 1 && ss_y(fctx) == 0 { - hit!(IBC_OWNED_RECT_422_PAIR_HITS); neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh) } else { around @@ -1603,7 +1486,6 @@ pub(super) fn decode_rect4_16_intrabc( fctx: &crate::decode::FrameCtx, ) -> Result<(usize, Option, (usize, usize))> { let _ = base_q_idx; - hit!(RECT4_16_INTRABC_HITS); let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) }; let (mi_w, mi_h) = (bw / MI, bh / MI); let (px, py) = (lmi.1 * MI, lmi.0 * MI); @@ -1670,15 +1552,9 @@ pub(super) fn decode_rect4_16_intrabc( // [BLOCK_4X16][1][0]` is BLOCK_INVALID at 4:2:2, so only HORZ reaches it. let own444 = ss_x(fctx) == 0 && ss_y(fctx) == 0; let own422 = ss_x(fctx) == 1 && ss_y(fctx) == 0 && horz; - if own422 && has_chroma { - hit!(INTRABC_RECT4_OWN_CHROMA422_HITS); - } // One predicate for "this strip IS its own chroma reference": the strip's // own mi position, its own luma extent, and per-axis subsampled sizes. let own_chroma = own444 || own422; - if ss_x(fctx) == 0 && ss_y(fctx) == 0 && has_chroma { - hit!(INTRABC_RECT4_OWN_CHROMA444_HITS); - } let (pw, ph) = if own444 { (bw, bh) } else if horz { @@ -1805,15 +1681,6 @@ pub(super) fn decode_rect4_16_intrabc( bh, ); let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1; - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}", - lmi.0, - lmi.1, - u8::from(split) - ); - } if !split { None } else { @@ -2184,7 +2051,6 @@ pub(super) fn decode_rect4_16_intrabc( } let mut last_uv = None; if has_chroma { - hit!(RECT4_16_CHROMA_HITS); // lane-av1422luma: the uv-mode publication and the left/above skip // state below are the STRIP's own at 4:2:2 / 4:4:4 -- publishing the // pair extent (one mi row off, `ph`/`pw`) is what the NEXT block's @@ -2220,11 +2086,6 @@ pub(super) fn decode_rect4_16_intrabc( } last_uv = Some(DC_PRED); } - if horz { - hit!(RECT4_16_HORZ_HITS); - } else { - hit!(RECT4_16_VERT_HITS); - } record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]); if leaves.is_none() { // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs` @@ -2350,9 +2211,6 @@ pub(super) fn decode_rect4_16_strip( fctx, ); } - if palette_y.is_some() || palette_uv.is_some() { - hit!(RECT4_PALETTE_HITS); - } // The colour-index map through the base colours IS the prediction. // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one // chroma transform this closing strip codes. @@ -2366,12 +2224,6 @@ pub(super) fn decode_rect4_16_strip( ) }); let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } - if filter_intra.is_some() { - hit!(FILTER_INTRA_RECT_HITS); - } // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol @@ -2383,24 +2235,12 @@ pub(super) fn decode_rect4_16_strip( let depth = if tx_select && !lossless(fctx) { // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands // (`get_tx_size_context`, libaom `pred_common.h:342`). - let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh); let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}", - lmi.0, - lmi.1, - dec.debug_state().0 - ); - } d } else { 0 }; - if depth != 0 { - hit!(TX_DEPTH_HITS); - hit!(RECT4_16_SPLIT_HITS); - } let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx); @@ -2471,7 +2311,6 @@ pub(super) fn decode_rect4_16_strip( tu_skip_ctx, dc_sign_ctx(tu_around.2), TxType::DctDct, - 0, )?; let residual = dequant_and_inverse_typed_wh( &tu_grid, @@ -2502,9 +2341,6 @@ pub(super) fn decode_rect4_16_strip( smooth_neighbor, fctx, ); - if tu_grid.iter().any(|&l| l != 0) { - hit!(RECT4_16_COEFF_HITS); - } neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid); } else { let tu_around = neighbours.around_mi(tu_mi, tx_w)[0]; @@ -2527,16 +2363,12 @@ pub(super) fn decode_rect4_16_strip( tu_py, tx_w, tx_w, - base_q_idx, None, filter_intra, Some(tu_skip_ctx), smooth_neighbor, fctx, )?; - if tu_grid.iter().any(|&l| l != 0) { - hit!(RECT4_16_COEFF_HITS); - } neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid); } } @@ -2586,7 +2418,6 @@ pub(super) fn decode_rect4_16_strip( 0, dc_sign_ctx(around.2), TxType::DctDct, - 0, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -2620,7 +2451,6 @@ pub(super) fn decode_rect4_16_strip( smooth_neighbor, fctx, ); - hit!(RECT4_16_COEFF_HITS); levels }; neighbours.record_mi_luma_rect(lmi, bw, bh, &levels); @@ -2641,7 +2471,6 @@ pub(super) fn decode_rect4_16_strip( } } if has_chroma { - hit!(RECT4_16_CHROMA_HITS); // lane-av1-444: at 4:4:4 there is no pair -- every strip is its // own chroma reference and codes its own 16x4 / 4x16 chroma // block. (`set_mi_offsets`'s chroma snap is the zero offset at @@ -2687,9 +2516,6 @@ pub(super) fn decode_rect4_16_strip( } else { uv_mode }; - if (V_PRED..=D67_PRED).contains(&uv_predict_mode) { - hit!(RECT4_16_CHROMA_DIR_HITS); - } let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx); // lane-kf1200 r1: the chroma edge-filter type reads the neighbours // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s @@ -2703,33 +2529,6 @@ pub(super) fn decode_rect4_16_strip( // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a // directional chroma strip, moving 4 samples by 1. let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c, fctx); - // lane-av1422warp: `smooth_uv_neighbour_unsnapped` now takes the - // frame's own `ss_x` -- the unsnapped read is the pair-merge witness - // counter's mirror of the snapping form, and the shipped read offsets - // the above COLUMN by `+ss_x` (libaom's `chroma_above_mi`). - // - // lane-av1leftwit: this mirror is NOT evidence about the left read's - // `+ss_y` term, whatever a report once said. It reads the leaf's own - // (odd) mi row, which no decode call site does -- every one of them - // uses the snapping form, whose base row is even -- and its result - // feeds `RECT4_16_UV_PAIR_FILT_HITS` only. What it measures is real - // and worth keeping (the pair's chroma-reference read against the - // leaf's own row: 51/24/121/0/1 hits on the five fixtures censused), - // so it stays; the decode path's own reach for the `+ss_y` term is - // `uv_left_1mi_split_hits()`. - if smooth_neighbor_uv - != neighbours.smooth_uv_neighbour_unsnapped( - lmi.0, - lmi.1, - r, - c, - ss_x(fctx), - ss_y(fctx), - false, - ) - { - hit!(RECT4_16_UV_PAIR_FILT_HITS); - } // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major @@ -2739,7 +2538,6 @@ pub(super) fn decode_rect4_16_strip( // mi(1,20) uv_mode matched, the following skip did not). let lossless_pair = lossless(fctx); let (u_levels, v_levels) = if lossless_pair { - hit!(RECT4_16_LOSSLESS_CHROMA_HITS); if skip { for plane in 1..3usize { for rr in 0..ch / 4 { @@ -2773,11 +2571,6 @@ pub(super) fn decode_rect4_16_strip( 4 << ss_x(fctx), 4 << ss_y(fctx), pair_reach, - ppx, - ppy, - y.width, - y.height, - fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let buf = if plane == 1 { ub } else { vb }; @@ -2868,11 +2661,6 @@ pub(super) fn decode_rect4_16_strip( 4 << ss_x(fctx), 4 << ss_y(fctx), pair_reach, - ppx, - ppy, - y.width, - y.height, - fctx, ); if let Some((ub, vb)) = &palette_uv_bufs { let buf = if plane == 1 { ub } else { vb }; @@ -2896,7 +2684,6 @@ pub(super) fn decode_rect4_16_strip( cpy + oy, 4, 4, - base_q_idx, None, None, offset, @@ -2910,7 +2697,6 @@ pub(super) fn decode_rect4_16_strip( plane, &cu_grid, ); - hit!(CHROMA_SPLIT_TX_HITS); let dst = if plane == 1 { &mut uo } else { &mut vo }; for row in 0..4 { let start = (oy + row) * cw + ox; @@ -2929,9 +2715,6 @@ pub(super) fn decode_rect4_16_strip( // DC + alpha * luma-AC. Dropping the CfL term here left a // chroma-only bounded box on ReelC's key frames. let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph)); - if alpha.is_some() { - hit!(CHROMA_SKIP_CFL_HITS); - } for plane in [1usize, 2] { if chroma422_pair16 { // lane-av1-422o: two TX_4X8 units, each predicted on @@ -2940,20 +2723,7 @@ pub(super) fn decode_rect4_16_strip( // `set_entropy_context` zeroed the block's own cells, // so the pair-wide zero stamp below stays correct. for unit_row in 0..2usize { - let unit_reach = tu_reach_rect( - pw, - ph, - 0, - unit_row * 8, - 8, - 8, - pair_reach, - ppx, - ppy, - y.width, - y.height, - fctx, - ); + let unit_reach = tu_reach_rect(pw, ph, 0, unit_row * 8, 8, 8, pair_reach); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx); @@ -3029,20 +2799,7 @@ pub(super) fn decode_rect4_16_strip( for plane in [1usize, 2] { for unit_row in 0..2usize { let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1); - let unit_reach = tu_reach_rect( - pw, - ph, - 0, - unit_row * 8, - 8, - 8, - pair_reach, - ppx, - ppy, - y.width, - y.height, - fctx, - ); + let unit_reach = tu_reach_rect(pw, ph, 0, unit_row * 8, 8, 8, pair_reach); if let Some((ub, vb)) = &palette_uv_bufs { let pbuf = if plane == 1 { ub } else { vb }; set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx); @@ -3115,10 +2872,7 @@ pub(super) fn decode_rect4_16_strip( // row is unreachable there. It is also the witness arm: // a restored `/2 chroma height` lands on (8,4) and the // counter reads 0. - (8, 8) => { - hit!(CHROMA422_SQUARE_HITS); - (TxbSet::Chroma8, default_scan(8)) - } + (8, 8) => (TxbSet::Chroma8, default_scan(8)), // lane-av1-422o: with the `chroma422_pair16` arm above, // the (2,16) own-strip shape and the 4:4:4 shapes are the // only residents; anything else is a named-lane gap. @@ -3141,7 +2895,6 @@ pub(super) fn decode_rect4_16_strip( dc_sign_ctx(around[plane].2), default_tx, fctx, - plane, )?; planes.push((levels, tx_type)); } @@ -3225,11 +2978,6 @@ pub(super) fn decode_rect4_16_strip( } last_uv_mode = Some(uv_predict_mode); } - if horz { - hit!(RECT4_16_HORZ_HITS); - } else { - hit!(RECT4_16_VERT_HITS); - } let (pal_y_size, pal_y_colors) = palette_y .as_ref() .map_or((0, [0u16; 8]), |p| (p.size, p.colors)); @@ -3354,17 +3102,7 @@ pub(super) fn decode_block_rect64( fctx, ); } - if (palette_y.is_some() || palette_uv.is_some()) && !skip { - // lane-t900 r34: a non-skip palette block on a superblock-level strip - // -- counted so its gate cannot go vacuous (this was a refusal until - // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_ - // decodes_pixel_exact`). - hit!(PALETTE_SB_STRIP_HITS); - } let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx); if filter_intra.is_some() { @@ -3394,7 +3132,7 @@ pub(super) fn decode_block_rect64( // 1920x792 128-superblock stream, // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read // `tx_size_cat2` row 1 where libaom reads row 2. - let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh); // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`) // counts `sub_tx_size_map` steps from the block's own max rect // transform down to TX_4X4, minus one -- BLOCK_64X32's chain @@ -3403,12 +3141,6 @@ pub(super) fn decode_block_rect64( // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF // here was a wrong-table read of a real symbol. let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { - eprintln!( - "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}", - dec.debug_state().0 - ); - } d } else { 0 @@ -3423,28 +3155,12 @@ pub(super) fn decode_block_rect64( fctx, ); if depth != 0 || lossless(fctx) { - hit!(TX_DEPTH_HITS); // lane-rectsplit r1/r4: the superblock-level strip splits its // transform through the very same per-unit path as its 32x32-level // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1 // measured the old square formula mis-tiling exactly that strip). let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx); - if bw.max(bh) / bw.min(bh) == 4 { - let which = if depth == 1 { - &RECT4_SPLIT_DEPTH1_HITS - } else { - &RECT4_SPLIT_DEPTH2_HITS - }; - hit_do! { which.with(|c| c.set(c.get() + 1)); } - } - if crate::envflags::env_flag!("EC_SBPART_DUMP64") { - eprintln!( - "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \ - depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \ - angle_y={angle_delta_y}" - ); - } let modes = RectStripModes { skip, mode, @@ -3465,9 +3181,6 @@ pub(super) fn decode_block_rect64( ) }), }; - if palette_y.is_some() || palette_uv.is_some() { - hit!(PALETTE_SPLIT_TX_HITS); - } decode_rect_split( dec, cdfs, @@ -3481,7 +3194,6 @@ pub(super) fn decode_block_rect64( y, u, v, - base_q_idx, reduced_tx_set, fctx, )?; @@ -3506,8 +3218,6 @@ pub(super) fn decode_block_rect64( // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The // bands carry the SPLIT unit's size, not the block's. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); - hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS); - hit!(RECT_PARTITION_HITS); return Ok(()); } let (tx_w, tx_h) = (bw, bh); @@ -3617,12 +3327,6 @@ pub(super) fn decode_block_rect64( // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16). let (luma_cw, luma_ch) = (bw.min(32), bh.min(32)); let scan32 = default_scan(TX32); - if coeff_trace_on() { - let (rng, _) = dec.debug_state(); - eprintln!( - "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}" - ); - } let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) { let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode); read_coeffs( @@ -3659,29 +3363,13 @@ pub(super) fn decode_block_rect64( 0, dc_sign_ctx(around[0].2), TxType::DctDct, - 0, )? }; - if coeff_trace_on() { - let (rng, _) = dec.debug_state(); - eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}"); - } let mut luma_levels = vec![0i32; bw * bh]; for row in 0..luma_ch { luma_levels[row * bw..][..luma_cw] .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]); } - { - let cur = block_q_idx(fctx); - if cur != i32::from(base_q_idx) { - hit!(RECT64_QIDX_DRIFT_HITS); - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - eprintln!( - "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}" - ); - } - } let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, @@ -3711,22 +3399,6 @@ pub(super) fn decode_block_rect64( smooth_neighbor, fctx, ); - if crate::envflags::env_flag!("EC_SBPART_DUMP64") { - let leftcol: Vec = if px > 0 { - (py..py + bh) - .map(|row| y.data[row * y.width + px - 1]) - .collect() - } else { - vec![] - }; - eprintln!( - "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \ - skip={skip} eob_nonzero={} row0={:?} leftcol={:?}", - luma_corner.iter().any(|&v| v != 0), - &y.data[py * y.width + px..][..bw], - leftcol, - ); - } // CHROMA. At 4:2:0 the plane block is already one adjusted UV // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma // is larger than that, so it is tiled into 32-capped units. @@ -3753,15 +3425,6 @@ pub(super) fn decode_block_rect64( // arm nothing had reached) from `nh >= 2` (the arm the corpus census // already covered), and can see WHY a candidate block did not fire. // Diagnostic only; no decode behaviour depends on it. - if crate::envflags::env_flag!("EC_PALWALK") { - eprintln!( - "EC_PALWALK mi={r},{c} px={px} py={py} bw={bw} bh={bh} cw={chroma_w} \ - ch={chroma_h} uw={uw} uh={uh} nw={nw} nh={nh} ast={allow_screen_content_tools} \ - puv={} py_pal={}", - palette_uv.is_some() as i32, - palette_y.is_some() as i32 - ); - } let mut u_levels = vec![0i32; chroma_w * chroma_h]; let mut v_levels = vec![0i32; chroma_w * chroma_h]; // The tiled units below stamp their own coefficient context @@ -3813,9 +3476,6 @@ pub(super) fn decode_block_rect64( // nothing. The `bigger` guard is what makes a hit PROOF // that the tiled arm ran, rather than proof that some // palette chroma block existed. - if bigger { - hit!(CHROMA_PALETTE_WINDOW_HITS); - } } read_plane( dec, @@ -3835,7 +3495,6 @@ pub(super) fn decode_block_rect64( cpy + cu_row * uh, uw, uw, - base_q_idx, cfl, None, bigger.then_some(3), @@ -3857,7 +3516,6 @@ pub(super) fn decode_block_rect64( dc_sign_ctx(cu_around[plane_idx].2), TxType::DctDct, fctx, - plane_idx, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -3883,9 +3541,6 @@ pub(super) fn decode_block_rect64( // nothing. The `bigger` guard is what makes a hit PROOF // that the tiled arm ran, rather than proof that some // palette chroma block existed. - if bigger { - hit!(CHROMA_PALETTE_WINDOW_HITS); - } } push_intra_rect( y, @@ -3949,7 +3604,6 @@ pub(super) fn decode_block_rect64( for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units { neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit); } - hit!(RECT_COEFF_HITS); } let (py_size, py_colors) = palette_y .as_ref() @@ -3980,15 +3634,5 @@ pub(super) fn decode_block_rect64( // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware. txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh)); - hit!(SB_RECT_HITS); - match (bw, bh) { - (64, 16) => hit!(SB_RECT4_HORZ_HITS), - (16, 64) => hit!(SB_RECT4_VERT_HITS), - _ => {} - } - if crate::envflags::env_flag!("EC_AV1_TRACE") { - let (rng, _) = dec.debug_state(); - eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}"); - } Ok(()) } diff --git a/crates/ec-av1/src/decode/replay.rs b/crates/ec-av1/src/decode/replay.rs index 0de1f51c..732747c9 100644 --- a/crates/ec-av1/src/decode/replay.rs +++ b/crates/ec-av1/src/decode/replay.rs @@ -179,7 +179,6 @@ fn replay_inner( &mut v, cdef, &r.neighbours, - (r.frame_width, r.frame_height), fctx, pre, Some(&mut wrote), @@ -449,7 +448,6 @@ pub(super) fn cdef_band( coeff_shift: i32, damping: i32, damping_uv: i32, - (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, ) { let unit_cols = skip_grid.mi_cols.div_ceil(2); @@ -471,9 +469,6 @@ pub(super) fn cdef_band( while mi_r < r_hi { let mut mi_c = 0usize; while mi_c < skip_grid.mi_cols { - if skip_grid.is_skip_txfm(mi_r, mi_c) { - hit!(CDEF_SKIPPED_UNITS); - } if !skip_grid.is_skip_txfm(mi_r, mi_c) { let sidx = strength_idx(mi_r, mi_c); let (ox, oy) = (mi_c * 4, mi_r * 4); @@ -511,21 +506,8 @@ pub(super) fn cdef_band( let y_dir = if y_pri_strength != 0 { dir } else { 0 }; let t = cdef_adjust_strength(y_pri_strength, var); // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit. - if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") { - eprintln!( - "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}" - ); - } let enable_primary = t != 0; let enable_secondary = y_sec_strength != 0; - if (ox + 8 > frame_w || oy + 8 > frame_h) - && (enable_primary - || enable_secondary - || cdef.uv_pri_strength[sidx] != 0 - || cdef.uv_sec_strength[sidx] != 0) - { - hit!(CDEF_STRADDLE_UNITS); - } if enable_primary || enable_secondary { cdef_filter_block( &win_y, diff --git a/crates/ec-av1/src/decode/sub8_inter.rs b/crates/ec-av1/src/decode/sub8_inter.rs index b36c1a3b..a559e243 100644 --- a/crates/ec-av1/src/decode/sub8_inter.rs +++ b/crates/ec-av1/src/decode/sub8_inter.rs @@ -62,7 +62,6 @@ pub(super) fn decode_inter_sub8_split4( ) -> Result<()> { const LAST_FRAME: i8 = 1; const B4: usize = 4; - hit!(SUB8_INTER_SPLIT_HITS); let (gr, gc) = group_mi; let (gpx, gpy) = (gc * MI, gr * MI); let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); @@ -72,7 +71,6 @@ pub(super) fn decode_inter_sub8_split4( let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] = [None; 4]; let mut first_tx_type = TxType::DctDct; - let mut sub0_tx_type = TxType::DctDct; // This loop iteration's own sub-block luma `tx_type` (libaom `mbmi->tx_type` // after its `read_tx_type`): the per-piece 4:4:4 chroma units inherit it // (`av1_get_tx_type`, blockd.h -- inter chroma never codes its own symbol). @@ -111,11 +109,6 @@ pub(super) fn decode_inter_sub8_split4( let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]); let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; - let ec_skip_post = if std::env::var_os("EC_DBG_SUB8").is_some() { - Some(dec.debug_state().0) - } else { - None - }; inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx); maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), skip, fctx); maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx); @@ -128,32 +121,7 @@ pub(super) fn decode_inter_sub8_split4( neighbours.left_inter[rmi], ); let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; - if std::env::var_os("EC_DBG_SUB8").is_some() { - eprintln!( - "EC_DBG piece mi=({rmi},{cmi}) skip={skip} skipctx={skip_ctx} skip_post={:?} is_inter={is_inter} iictx={ii_ctx} post={}", - ec_skip_post, - dec.debug_state().0 - ); - } if !is_inter { - if crate::envflags::env_flag!("EC_SUB8INTRA") { - eprintln!( - "EC_SUB8INTRA shape=4x4 sub={i} has_chroma={} skip={skip} mi={rmi},{cmi} tx_select={}", - i == 3, - fctx.tx_select_inter.with(std::cell::Cell::get), - ); - } - // lane-sub8x4 r2: the refusal and its `EC_SUB8INTRA_DECODE` bypass - // are gone -- `a_real_aomenc_inter_sequence_with_intra_sub8x8_ - // leaves_decodes_pixel_exact` (stream.rs) decodes 12 real aomenc - // streams carrying this arm pixel-exact vs ffmpeg. - hit_do! { - SUB8_INTRA_RECT_HITS.with(|h| { - let mut st = h.get(); - st[4] += 1; - h.set(st); - }); - } // lane-sub8intra: the `BLOCK_4X4` twin of the HORZ/VERT arm -- // same [`decode_intra_sub8_leaf`], no tx-depth symbol, chroma on // the chroma-reference sub-blocks (`is_chroma_reference`: the @@ -173,7 +141,6 @@ pub(super) fn decode_inter_sub8_split4( y, u, v, - base_q_idx, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), fctx.tx_select_inter.with(std::cell::Cell::get), reduced_tx_set, @@ -187,12 +154,6 @@ pub(super) fn decode_inter_sub8_split4( // Same print point as the oracle's `EC_MODE` (entry of // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the // two range ladders line up element for element. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE mi_row={rmi} mi_col={cmi} rng={}", - dec.debug_state().0 - ); - } let ref_frame = read_single_ref( dec, cdfs, @@ -209,9 +170,6 @@ pub(super) fn decode_inter_sub8_split4( // each of the group's pieces (luma and its 2x2 chroma) carries its // OWN factor because each can name a different `ref_frame`. let luma_scale = scale_of((ref_width, ref_height), frame_size); - if !luma_scale.is_unscaled() { - hit!(SCALED_SUB8_HITS); - } let gm_table = build_gm_mv_table( global_motion, rmi, @@ -245,10 +203,6 @@ pub(super) fn decode_inter_sub8_split4( tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; - if !not_new { - crate::census::mode(0); - } - let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { let mut idx = 0usize; while idx < 2 && stack.entries.len() > idx + 1 { @@ -272,15 +226,10 @@ pub(super) fn decode_inter_sub8_split4( ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - if !not_zero { - crate::census::mode(1); - } - is_globalmv = !not_zero; let mv = if !not_zero { gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - crate::census::mode(if nearest { 2 } else { 3 }); if nearest { stack.nearest_mv } else { @@ -298,17 +247,8 @@ pub(super) fn decode_inter_sub8_split4( }; // Same print point as the oracle's `EC_MODE_MV` (right after // `assign_mv`), the second rung of the sub-8x8 range ladder. - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}", - mv.0, - mv.1, - dec.debug_state().0 - ); - } // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see // this function's own doc); `read_mb_interp_filter` still runs. - let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame || neighbours.above_ref1[cmi] == Some(ref_frame) { @@ -323,25 +263,10 @@ pub(super) fn decode_inter_sub8_split4( } else { [3, 3] }; - if crate::envflags::env_flag!("EC_AV1_IFDBG") { - eprintln!( - "IFDBG4 mi=({rmi},{cmi}) ref={ref_frame} above_ref={} above_ref1={:?} \ - above_filt={:?} left_ref={} left_ref1={:?} left_filt={:?}", - neighbours.above_ref[cmi], - neighbours.above_ref1[cmi], - neighbours.above_filter[cmi], - neighbours.left_ref[rmi], - neighbours.left_ref1[rmi], - neighbours.left_filter[rmi], - ); - } // lane-t900 r9: this reader's sub-blocks have a 4-px side, and libaom // `is_nontrans_global_motion` returns 0 for // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model -- // so a GLOBALMV sub-block here always reads its interp filter. - if is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation { - hit!(GM_NONTRANS_SMALL_SIDE_HITS); - } let gm_nontrans = false; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, @@ -353,16 +278,6 @@ pub(super) fn decode_inter_sub8_split4( left_filter_ctx, false, ); - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_VAL4 mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \ - ref0={ref_frame} mv0=({},{}) stack={} rng={}", - mv.0, - mv.1, - stack.entries.len(), - dec.debug_state().0 - ); - } grid.set( rmi, cmi, @@ -412,7 +327,11 @@ pub(super) fn decode_inter_sub8_split4( let pred_y: Vec; let sy = if pred_deferred(refpix) { push_pred(build); - Pred::Cur { plane: 0, stride: B4, off: 0 } + Pred::Cur { + plane: 0, + stride: B4, + off: 0, + } } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -454,9 +373,6 @@ pub(super) fn decode_inter_sub8_split4( fctx, )?; piece_tx_type = tx_type; - if i == 0 { - sub0_tx_type = tx_type; - } if i == 3 { // `av1_get_tx_type`'s chroma tail scales `blk_row`/`blk_col` // back by the subsampling, but it indexes `xd->tx_type_map`, @@ -522,7 +438,18 @@ pub(super) fn decode_inter_sub8_split4( let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if pred_deferred(refpix) { push_pred(build_c); - (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }) + ( + Pred::Cur { + plane: 1, + stride: B4, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: B4, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build_c(y, u, v, refpix, fctx, &mut built); @@ -706,7 +633,18 @@ pub(super) fn decode_inter_sub8_split4( let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if pred_deferred(refpix) { push_pred(build_c); - (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }) + ( + Pred::Cur { + plane: 1, + stride: B4, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: B4, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build_c(y, u, v, refpix, fctx, &mut built); @@ -747,7 +685,6 @@ pub(super) fn decode_inter_sub8_split4( neighbours.record_mi_chroma(ctx_mi, 8, 4, 1, &ZERO_RESIDUAL[..B4 * B4]); neighbours.record_mi_chroma(ctx_mi, 8, 4, 2, &ZERO_RESIDUAL[..B4 * B4]); } else { - hit!(CHROMA422_INTER_SUB8_HITS); let (ug, _) = read_inter_plane( dec, cdfs, @@ -860,15 +797,6 @@ pub(super) fn decode_inter_sub8_split4( // mi of the group is intra: the group's 4x4 chroma is then predicted WHOLE // from the chroma-reference (last) sub-block's own mv, not in 2x2 pieces. let mixed = piece.iter().any(Option::is_none); - if mixed { - hit_do! { - SUB8_INTRA_RECT_HITS.with(|h| { - let mut st = h.get(); - st[3] += 1; - h.set(st); - }); - } - } // lane-sub8group: the group's chroma pieces, built where they are // written -- the pieces' refs/mvs/filters travel by value. let build = move |_y: &mut PlaneBuf<'static>, @@ -934,7 +862,18 @@ pub(super) fn decode_inter_sub8_split4( let (pred_u, pred_v): (Vec, Vec); let (su, sv) = if pred_deferred(refpix) { push_pred(build); - (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }) + ( + Pred::Cur { + plane: 1, + stride: B4, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: B4, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -1012,8 +951,6 @@ pub(super) fn decode_inter_sub8_split4( fctx, )? .0; - let coded = ug.iter().chain(vg.iter()).any(|&c| c != 0); - note_sub8_chroma_tx(sub0_tx_type, first_tx_type, coded); (ug, vg) }; let round_up_even = |n: usize| n.div_ceil(2) * 2; @@ -1066,7 +1003,6 @@ pub(super) fn decode_intra_sub8_leaf( grid: &mut MiGrid, group_mi: (usize, usize), lmi: (usize, usize), - // `(bw, bh)`: 8x4 / 4x8 under HORZ/VERT, 4x4 under SPLIT. (bw, bh): (usize, usize), has_chroma: bool, skip: bool, @@ -1074,7 +1010,6 @@ pub(super) fn decode_intra_sub8_leaf( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - base_q_idx: u8, enable_filter_intra: bool, tx_select: bool, reduced_tx_set: bool, @@ -1090,19 +1025,9 @@ pub(super) fn decode_intra_sub8_leaf( let (above_mode, left_mode) = neighbours.modes_above_left(r, c); let leaf_above = neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode); let leaf_left = neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode); - let step = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); // `size_group_lookup[BLOCK_8X4] == size_group_lookup[BLOCK_4X8] == 0` // (libaom common_data.h:61). - crate::msac::SymbolDecoder::set_symr_cdf("y_mode"); let mode = dec.symbol(&mut cdfs.y_mode[0]); - if step { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=mode val={mode} rng={}", - lmi.0, - lmi.1, - dec.debug_state().0 - ); - } // No angle delta below 8x8 (`av1_use_angle_delta`), for luma or chroma. let angle_delta_y = 0; let (uv_mode, alpha) = if has_chroma { @@ -1116,31 +1041,15 @@ pub(super) fn decode_intra_sub8_leaf( // always 4x4-or-smaller, so the predicate stays true and this read // is unchanged. let uv_mode = if cfl_allowed_px(bw, bh, fctx) { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_cfl[mode]) } else { - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) }; - if step { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=uv_mode val={uv_mode} rng={}", - lmi.0, - lmi.1, - dec.debug_state().0 - ); - } - if (9..=12).contains(&uv_mode) { - hit!(SMOOTH_UV_HITS); - } let alpha = if uv_mode == UV_CFL_PRED { Some(read_cfl_alphas(dec, cdfs)) } else { None }; - if (V_PRED..=D67_PRED).contains(&uv_mode) { - hit!(DIRECTIONAL_UV_HITS); - } (uv_mode, alpha) } else { (DC_PRED, None) @@ -1154,27 +1063,8 @@ pub(super) fn decode_intra_sub8_leaf( .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize") }; let use_fi = dec.symbol(&mut cdfs.filter_intra[fi_class]); - if step { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={use_fi} rng={}", - lmi.0, - lmi.1, - dec.debug_state().0 - ); - } if use_fi != 0 { - hit!(FILTER_INTRA_HITS); - hit!(FILTER_INTRA_RECT_HITS); - hit!(FILTER_INTRA_RECT_SUB8_HITS); let fi = dec.symbol(&mut cdfs.filter_intra_mode); - if step { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}", - lmi.0, - lmi.1, - dec.debug_state().0 - ); - } filter_intra = Some(fi); } } @@ -1190,24 +1080,12 @@ pub(super) fn decode_intra_sub8_leaf( // no depth symbol either (sweep of the class fixed at the key-frame pair // path). let depth = if tx_select && bw != bh && !lossless(fctx) { - let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx); + let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh); let d = dec.symbol(&mut cdfs.tx_size_cat0[ctx]); - if step { - eprintln!( - "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=0 rng={}", - lmi.0, - lmi.1, - dec.debug_state().0 - ); - } d } else { 0 }; - if depth != 0 { - hit!(TX_DEPTH_HITS); - hit!(RECT8_SPLIT_TX_HITS); - } let split = depth != 0 || (lossless(fctx) && bw != bh); let (px, py) = (lmi.1 * MI, lmi.0 * MI); let reach = if bw == bh { @@ -1216,9 +1094,6 @@ pub(super) fn decode_intra_sub8_leaf( Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx) }; let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left); - if smooth_neighbor { - hit!(SMOOTH_LUMA_HITS); - } neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode); let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 }; if split { @@ -1231,19 +1106,7 @@ pub(super) fn decode_intra_sub8_leaf( (lmi.0, lmi.1 + tu) }; let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI); - let tu_reach = tu_reach( - bw, - bh, - tu_px - px, - tu_py - py, - 4, - reach, - px, - py, - y.width, - y.height, - fctx, - ); + let tu_reach = tu_reach(bw, bh, tu_px - px, tu_py - py, 4, reach); if skip { let zeros = vec![0i32; 16]; push_intra( @@ -1290,7 +1153,6 @@ pub(super) fn decode_intra_sub8_leaf( tu_py, 4, TX4, - base_q_idx, None, filter_intra, Some(tu_skip_ctx), @@ -1346,7 +1208,6 @@ pub(super) fn decode_intra_sub8_leaf( py, 4, TX4, - base_q_idx, None, filter_intra, None, @@ -1396,7 +1257,6 @@ pub(super) fn decode_intra_sub8_leaf( 0, dc_sign_ctx(around.2), TxType::DctDct, - 0, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -1484,14 +1344,6 @@ pub(super) fn decode_intra_sub8_leaf( is_global_mv1: false, }, ); - hit_do! { - SUB8_INTRA_RECT_HITS.with(|h| { - let mut s = h.get(); - s[usize::from(vert)] += 1; - s[2] += usize::from(has_chroma); - h.set(s); - }); - } // lane-t900 r23 (class [[new-map-ignores-tile-edge]]: a neighbour map // needs EVERY writer): a sub-8x8 group published no palette state, so // once an 8x8 leaf of the same row can BE a palette block, the group @@ -1544,7 +1396,6 @@ pub(super) fn decode_intra_sub8_leaf( u, v, scan4, - base_q_idx, neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx), (bw, bh), fctx, @@ -1611,10 +1462,6 @@ pub(super) fn decode_intra_sub8_leaf( }); let mut chroma_stamped_per_unit = false; let (u_grid, v_grid): (Grid, Grid) = if skip { - if alpha.is_some() { - hit!(CHROMA_SKIP_CFL_HITS); - hit!(SKIP_CFL_HITS); - } if chroma_444 && bw != bh { let zeros = Grid::Zero(bw * bh); push_intra_rect( @@ -1718,8 +1565,7 @@ pub(super) fn decode_intra_sub8_leaf( // At 4:4:4 a TX_4X4 chroma unit IS one mi cell. let tu_mi = (lmi.0 + oy / MI, lmi.1 + ox / MI); let tu_around = neighbours.around_mi(tu_mi, MI); - let tu_r = - tu_reach(bw, bh, ox, oy, 4, reach_c, px, py, y.width, y.height, fctx); + let tu_r = tu_reach(bw, bh, ox, oy, 4, reach_c); // The plane block (8x4/4x8) is bigger than the TX_4X4 // transform, so `get_txb_ctx`'s chroma ctx_offset is 10, // not 7 -- our chroma tables carry the offset-10 rows at @@ -1743,7 +1589,6 @@ pub(super) fn decode_intra_sub8_leaf( py + oy, 4, TX4, - base_q_idx, None, None, Some(3), @@ -1754,7 +1599,6 @@ pub(super) fn decode_intra_sub8_leaf( // (`av1_set_contexts`); the tail's whole-leaf chroma // stamp below is skipped for this shape. neighbours.record_mi_chroma(tu_mi, 4, 4, plane_idx, &tu_grid); - hit!(CHROMA_SPLIT_TX_HITS); let dst = mu_units(if plane_idx == 1 { &mut uo } else { &mut vo }, bw * bh); for row in 0..4 { let start = (oy + row) * bw + ox; @@ -1763,7 +1607,6 @@ pub(super) fn decode_intra_sub8_leaf( } } chroma_stamped_per_unit = true; - hit!(LLSUB8RECT444_CHROMA_WALK_HITS); ( if uo.is_empty() { Grid::Zero(bw * bh) @@ -1801,7 +1644,6 @@ pub(super) fn decode_intra_sub8_leaf( skip_ctx, dc_sign_ctx(around.2), uv_tx, - plane, )?; let residual = dequant_and_inverse_typed_wh( &levels, @@ -1861,7 +1703,6 @@ pub(super) fn decode_intra_sub8_leaf( unit_y, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, @@ -1886,7 +1727,6 @@ pub(super) fn decode_intra_sub8_leaf( unit_y, 4, TX4, - base_q_idx, alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, @@ -2004,13 +1844,6 @@ pub(super) fn decode_inter_sub8_rect2( (8usize, 4usize) }; let (w_mi, h_mi) = (bw / MI, bh / MI); - hit_do! { - SUB8_INTER_RECT_HITS.with(|c| { - let mut h = c.get(); - h[usize::from(vert)] += 1; - c.set(h); - }); - } let (gr, gc) = group_mi; let (gpx, gpy) = (gc * MI, gr * MI); let (cpx, cpy) = (gpx >> ss_x(fctx), gpy >> ss_y(fctx)); @@ -2018,7 +1851,6 @@ pub(super) fn decode_inter_sub8_rect2( let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] = [None; 2]; let mut first_tx_type = TxType::DctDct; - let mut sub0_tx_type = TxType::DctDct; // lane-av1-444: `is_chroma_reference` is unconditional at subsampling 0/0 // (av1_common_int.h:1459), so every 8x4/4x8 piece is its own chroma // reference and codes its own 8x4/4x8 U/V units right after its luma -- @@ -2099,15 +1931,6 @@ pub(super) fn decode_inter_sub8_rect2( ); let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; if !is_inter { - if crate::envflags::env_flag!("EC_SUB8INTRA") { - eprintln!( - "EC_SUB8INTRA shape={}x{} sub={i} has_chroma={} skip={skip} mi={rmi},{cmi} tx_select={}", - bw, - bh, - piece_is_chroma_ref(i), - fctx.tx_select_inter.with(std::cell::Cell::get), - ); - } // lane-sub8x4 r2: refusal and bypass lifted -- see the split arm's // note above for the gate that proves this leaf. // Its chroma rule is `is_sub8x8_inter`'s: when the @@ -2128,7 +1951,6 @@ pub(super) fn decode_inter_sub8_rect2( y, u, v, - base_q_idx, fctx.enable_filter_intra_inter.with(std::cell::Cell::get), fctx.tx_select_inter.with(std::cell::Cell::get), reduced_tx_set, @@ -2139,12 +1961,6 @@ pub(super) fn decode_inter_sub8_rect2( } continue; } - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE mi_row={rmi} mi_col={cmi} rng={}", - dec.debug_state().0 - ); - } let ref_frame = read_single_ref( dec, cdfs, @@ -2158,9 +1974,6 @@ pub(super) fn decode_inter_sub8_rect2( let (ref_width, ref_height) = ref_dims(ref_frame, refpix)?; // lane-t900 r28: refusal lifted -- see the split arm above. let luma_scale = scale_of((ref_width, ref_height), frame_size); - if !luma_scale.is_unscaled() { - hit!(SCALED_SUB8_HITS); - } let gm_table = build_gm_mv_table( global_motion, rmi, @@ -2194,10 +2007,6 @@ pub(super) fn decode_inter_sub8_rect2( tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; - if !not_new { - crate::census::mode(0); - } - let mut is_globalmv = false; let (mv, is_new_mv) = if !not_new { let mut idx = 0usize; while idx < 2 && stack.entries.len() > idx + 1 { @@ -2221,15 +2030,10 @@ pub(super) fn decode_inter_sub8_rect2( ) } else { let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - if !not_zero { - crate::census::mode(1); - } - is_globalmv = !not_zero; let mv = if !not_zero { gm_table[(ref_frame - LAST_FRAME) as usize] } else { let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - crate::census::mode(if nearest { 2 } else { 3 }); if nearest { stack.nearest_mv } else { @@ -2245,15 +2049,6 @@ pub(super) fn decode_inter_sub8_rect2( }; (mv, false) }; - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}", - mv.0, - mv.1, - dec.debug_state().0 - ); - } - let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame || neighbours.above_ref1[cmi] == Some(ref_frame) { @@ -2272,9 +2067,6 @@ pub(super) fn decode_inter_sub8_rect2( // `is_nontrans_global_motion` returns 0 for // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model -- // so a GLOBALMV sub-block here always reads its interp filter. - if is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation { - hit!(GM_NONTRANS_SMALL_SIDE_HITS); - } let gm_nontrans = false; let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, @@ -2321,9 +2113,6 @@ pub(super) fn decode_inter_sub8_rect2( // exactly that population -- so an unconditional hit proves only // "a lossless sub-8 leaf was walked", not "the conjunct suppressed // a tree". Guard it on the same term the conjunct uses. - if fctx.tx_select_inter.with(std::cell::Cell::get) { - hit!(SUB8_LOSSLESS_NO_VARTX); - } // lane-lossless2: `read_block_tx_size` returns TX_4X4 before it // ever looks at `max_txsize_rect_lookup`, so an 8x4/4x8 leaf is // TWO 4x4 units, not one rect one. @@ -2337,17 +2126,6 @@ pub(super) fn decode_inter_sub8_rect2( leaves.push((0, 0, bw, bh)); set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip); } - if crate::envflags::env_flag!("EC_TRACE_MODE") { - eprintln!( - "EC_MODE_VALR mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \ - ref0={ref_frame} mv0=({},{}) stack={} leaves={} rng={}", - mv.0, - mv.1, - stack.entries.len(), - leaves.len(), - dec.debug_state().0 - ); - } grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv); piece[i] = Some((ref_frame, mv, h_filter, v_filter)); // Prediction over the leaf's true footprint, laid out at the group's @@ -2389,7 +2167,11 @@ pub(super) fn decode_inter_sub8_rect2( let pred_y: Vec; let sy = if pred_deferred(refpix) { push_pred(build); - Pred::Cur { plane: 0, stride: SIDE, off: 0 } + Pred::Cur { + plane: 0, + stride: SIDE, + off: 0, + } } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -2492,9 +2274,6 @@ pub(super) fn decode_inter_sub8_rect2( if idx == 0 { piece_tx_type = tu_tx_type; } - if idx == 0 && i == 0 { - sub0_tx_type = tu_tx_type; - } if idx == 0 && i == 1 { // `av1_get_tx_type` indexes `xd->tx_type_map`, which // `set_mi_offsets` (av1_common_int.h:1679) re-points to the @@ -2563,7 +2342,18 @@ pub(super) fn decode_inter_sub8_rect2( let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if pred_deferred(refpix) { push_pred(build_c); - (Pred::Cur { plane: 1, stride: SIDE, off: 0 }, Pred::Cur { plane: 2, stride: SIDE, off: 0 }) + ( + Pred::Cur { + plane: 1, + stride: SIDE, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: SIDE, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build_c(y, u, v, refpix, fctx, &mut built); @@ -2813,7 +2603,18 @@ pub(super) fn decode_inter_sub8_rect2( let (pred_cu, pred_cv): (Vec, Vec); let (su, sv) = if pred_deferred(refpix) { push_pred(build_c); - (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }) + ( + Pred::Cur { + plane: 1, + stride: B4, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: B4, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build_c(y, u, v, refpix, fctx, &mut built); @@ -2851,7 +2652,6 @@ pub(super) fn decode_inter_sub8_rect2( neighbours.record_mi_chroma(ctx_mi, 8, 4, 1, &ZERO_RESIDUAL[..B4 * B4]); neighbours.record_mi_chroma(ctx_mi, 8, 4, 2, &ZERO_RESIDUAL[..B4 * B4]); } else { - hit!(CHROMA422_INTER_SUB8_HITS); let (ug, _) = read_inter_plane( dec, cdfs, @@ -2956,15 +2756,6 @@ pub(super) fn decode_inter_sub8_rect2( // chroma-reference block's own mv, at the group's chroma origin // (`row_start`/`col_start` shift `pre_x`/`pre_y` there either way). let mixed = piece[0].is_none(); - if mixed { - hit_do! { - SUB8_INTRA_RECT_HITS.with(|h| { - let mut s = h.get(); - s[3] += 1; - h.set(s); - }); - } - } let (piece_w, piece_h) = match (mixed, vert) { (true, _) => (B4, B4), (false, true) => (2usize, 4usize), @@ -3038,7 +2829,18 @@ pub(super) fn decode_inter_sub8_rect2( let (pred_u, pred_v): (Vec, Vec); let (su, sv) = if pred_deferred(refpix) { push_pred(build); - (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 }) + ( + Pred::Cur { + plane: 1, + stride: B4, + off: 0, + }, + Pred::Cur { + plane: 2, + stride: B4, + off: 0, + }, + ) } else { let mut built: [Vec; 3] = Default::default(); build(y, u, v, refpix, fctx, &mut built); @@ -3116,8 +2918,6 @@ pub(super) fn decode_inter_sub8_rect2( fctx, )? .0; - let coded = ug.iter().chain(vg.iter()).any(|&c| c != 0); - note_sub8_chroma_tx(sub0_tx_type, first_tx_type, coded); (ug, vg) }; let round_up_even = |n: usize| n.div_ceil(2) * 2; diff --git a/crates/ec-av1/src/decode/tests.rs b/crates/ec-av1/src/decode/tests.rs index f937af8b..1efaca8a 100644 --- a/crates/ec-av1/src/decode/tests.rs +++ b/crates/ec-av1/src/decode/tests.rs @@ -1,329 +1,3 @@ -/// lane-av1unwritten r7: the STRUCTURAL invariant that r5 and r6 both broke. -/// -/// r5 put guards inside `PARTITION_HORZ_A..=PARTITION_VERT_B` arms, so they -/// could only ever see values 4..=7. r6 deleted the inter-16 guard and did not -/// replace it. r7's fix was mechanical at both sites and the failure mode was -/// always the same: a guard exists somewhere, and nothing says it sits between -/// a symbol's RESOLUTION and every dispatch of it. -/// -/// So the invariant is stated over the dispatch structure, not over a list. -/// Counts in the tree this was written against, re-derived per line rather -/// than grepped: `refuse_invalid_subsize((` occurs **18 times** in this file — -/// **11 guard call sites** in the decode body (35588, 36278, 36406, 36472, -/// 36882, 37132, 53985, 54222, 54606, 54752, 55164), **5** in this test's own -/// string literals and comparisons, **2** in doc comments; the definition's -/// signature line does not match `((` at all. The scan finds **10 resolutions**: -/// the eleventh guard is the inter-frame 128 one, whose resolution lives in -/// the shared `read_sb128_root`, so a guard has no resolution of its own here. -/// What is asserted, exactly: -/// -/// * every `partition_w[` level in the file appears among the resolutions -/// this scan finds -- a new level cannot be added without a guard check; -/// * each resolution is followed, within 220 lines, by a -/// `refuse_invalid_subsize((N, N), …)` for its OWN level (matched on the -/// level, not the variable, because the symbol is often bound to a -/// short-lived inner name `p` and dispatched by an outer `part64`); -/// * where that window contains a `match part…` dispatch, the guard precedes -/// it -- the bound r7's COMMENT claimed and r8 implements; -/// * no guard sits inside a `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. -/// -/// It does NOT prove a guard is at the exact dispatch point: the window is a -/// window. And the two cross-checks are weaker than they look — cross-check 1 -/// is level PRESENCE only, cross-check 2 is `>=` — so a SECOND unguarded site -/// at an already-covered level is caught ONLY by the per-site 220-line window, -/// which is a window and not a dispatch bound. That limit is why the AB-arm -/// invariant exists separately, and why `EC_AV1_SUBSIZE_GUARD_TRACE` records -/// what each site really sees over the corpus. -#[test] -fn every_partition_symbol_resolution_is_guarded_before_it_dispatches() { - let src = crate::test_source::module_source("decode"); - // Every partition-symbol RESOLUTION in the file, with the level read off - // the CDF name on the line itself. Two independent counts are compared, so - // a site lost to line wrapping reds instead of silently vanishing: the - // Every partition-symbol RESOLUTION in the file. The window is the line - // BEFORE as well as the line itself and the one after (r9), because a - // `let =` on one line with `dec.symbol(&mut cdfs.partition_w8[..])` - // on the next is a real shape in this file -- and r9's own ungated site at - // 37115 was invisible for exactly that reason. - let lines: Vec<&str> = src.lines().collect(); - let mut sites: Vec<(usize, String, usize)> = Vec::new(); - // Occurrences of `partition_w[` per level, counted from the FILE, used as - // the cross-check below. - let mut file_occurrences: std::collections::BTreeMap = Default::default(); - // Only the DECODE body: the test module below also builds `partition_w8` - // CDFs (an encoder round-trip at 58464/58521), and counting those would - // demand a guard for a site that does not exist. - let production = crate::test_source::module_production_source("decode"); - let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") { - Some(i) => &production[..i], - None => production, - }; - { - let mut rest = decode_body; - while let Some(i) = rest.find("partition_w") { - let after = &rest[i + "partition_w".len()..]; - let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); - rest = after; - if digits.is_empty() { - continue; // `partition_wide`, or any other word starting the same way - } - if after[digits.len()..].starts_with('[') { - *file_occurrences - .entry(digits.parse().expect("digits")) - .or_insert(0) += 1; - } - } - } - // r11 (lane-av1subsizesweep): a partition-symbol READ is a `dec.(..)` - // call whose OWN ARGUMENT LIST names a `partition_w[` CDF. That is the - // whole definition, and it is why the read spellings need no hand-list: - // `dec.symbol(..partition_w..)` qualifies, the frame-edge gather's - // `dec.symbol_fixed(&gather(..partition_w..))` qualifies, and - // `dec.debug_state()` does not -- it never names a partition CDF. A third - // spelling is covered the day somebody writes it. - // - // r11's hole was a SPELLING gap, not a shape gap: the old matcher named - // `dec.symbol(` literally, and `dec.symbol(` is not a substring of - // `dec.symbol_fixed(`. So the key-frame 16-level frame-edge arm -- which - // dispatches `decode_leaf_rect` straight off a gathered `edge_split` onto - // a BLOCK_8X16 chroma walk -- was never a site at all. - let is_partition_read = |window: &str| -> bool { - let mut at = 0usize; - while let Some(rel) = window[at..].find("dec.") { - let call = at + rel + "dec.".len(); - at = call; - let name: String = window[call..] - .chars() - .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') - .collect(); - if name.is_empty() { - continue; - } - let Some(open) = window[call + name.len()..].find('(') else { - continue; - }; - let arg_from = call + name.len() + open + 1; - let mut depth = 1usize; - let mut stop = None; - for (i, c) in window[arg_from..].char_indices() { - match c { - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - stop = Some(arg_from + i); - break; - } - } - _ => {} - } - } - let Some(stop) = stop else { continue }; - if window[arg_from..stop].contains("partition_w") { - return true; - } - } - false - }; - for (n, line) in lines.iter().enumerate() { - let t = line.trim_start(); - // A doc comment quoting the shape is not a site, and neither is the - // test's own example strings further down the file. - if t.starts_with("//") || !line.contains("partition_w") || n > 56000 { - continue; - } - let lo = n.saturating_sub(1); - let hi = (n + 2).min(lines.len()); - let window = lines[lo..hi].join(" "); - // r11: the read test is the DERIVED predicate above, not a spelling - // literal. Naming `dec.symbol(` here is what hid the frame-edge arm. - if !is_partition_read(&window) { - continue; - } - let Some(i) = window.find("partition_w") else { - continue; - }; - let after = &window[i + "partition_w".len()..]; - let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); - if digits.is_empty() { - continue; - } - let level: usize = digits.parse().expect("digits"); - // The bound variable is the token after `let `, looked for in the two - // lines the binding can occupy (r9: it may be the line above). - // r10: scan BACKWARDS from the closest line and take the nearest `let` - // whose binding is the one followed by this symbol read -- taking the - // first `let` upward named an unrelated binding above it. - let mut var = None; - for cand in (lo..=n).rev() { - let ct = lines[cand].trim_start(); - if ct.starts_with("//") { - continue; - } - let Some(v) = ct.strip_prefix("let ") else { - continue; - }; - let name = v - .split(|c: char| !(c.is_alphanumeric() || c == '_')) - .next() - .unwrap_or("") - .to_string(); - if name.is_empty() { - continue; - } - // This binding is followed by the symbol read if the SAME line - // completes `let = dec.(`, or if the next line - // starts the call. That is what separates `let part8 =` from an - // unrelated `let ec_dbg_pre =` two lines above it. - let next = lines.get(cand + 1).copied().unwrap_or(""); - let binds_here = ct.contains("= dec.") || next.contains("dec."); - if binds_here || cand == n { - var = Some(name); - break; - } - } - let Some(var) = var else { continue }; - // r11: the edge `gather` reads are SITES now, not skips. r10 skipped - // them on the reasoning that "the site is guarded at the level's own - // resolution instead" -- true for every arm that resolves into a - // `partN`, and FALSE for the one that does not: the key-frame 16-level - // frame-edge arm dispatches `decode_leaf_rect` straight off `edge_split`, - // and `BLOCK_8X16` is BLOCK_INVALID at 4:2:2. Every site therefore has - // to carry a guard for its OWN level between the read and the first - // chroma-walking dispatch after it -- see the per-site check below. - sites.push((n, var, level)); - } - - // ---- cross-check 1: every `partition_w` LEVEL in the decode body has - // at least one guarded resolution. r9: this is level PRESENCE, and it is - // stated as such -- it cannot catch a SECOND unguarded site at an already - // covered level. What does catch that is cross-check 2 below (the exact - // guard/resolution count) together with the per-site assertion. - let mut covered: std::collections::BTreeSet = Default::default(); - for (_, _, level) in &sites { - covered.insert(*level); - } - for level in file_occurrences.keys() { - assert!( - covered.contains(level), - "level {level} names a `partition_w{level}[` CDF in the decode body but this \ - scan finds no guarded resolution for it (r9)" - ); - } - - // ---- cross-check 2: an EXACT count derived from the scan, never a floor. - // Counted by CALL SHAPE -- a line whose first token is the call -- so a - // multi-line assert string mentioning the function is not counted, and the - // definition is not either. - let guarded_sites = decode_body - .lines() - .filter(|l| l.trim_start().starts_with("refuse_invalid_subsize((")) - .count(); - // r9: was `assert_eq!`, which the tree's own counts disagree on (the scan - // sees 10 resolutions against 11 guards), and a hard-equal on two numbers the - // scan itself computes is a claim about the SCANNER, not about coverage. It - // is `>=` plus the per-site assertion below: a resolution with no guard reds - // on its own line, which is the property that matters, and a guard with no - // resolution behind it is redundant rather than harmful. - assert!( - guarded_sites >= sites.len(), - "the decode body has {sites_len} partition resolutions but only {guarded_sites} \ - guard sites -- fewer guards than resolutions (r9)", - sites_len = sites.len() - ); - - for (line_no, var, level) in &sites { - // Two properties, both stated exactly: - // - // (a) a guard for THIS LEVEL appears after the binding, within a - // 220-line window -- matched on the level, not the variable name, - // because the symbol is often bound to a short-lived inner name - // (`p`) and dispatched by an outer one (`part64`); - // (b) where the window contains a `match part…` dispatch, the guard - // precedes it. - let window: Vec<&str> = lines[line_no + 1..(line_no + 221).min(lines.len())].to_vec(); - let guard_at = window - .iter() - .position(|l| l.contains(&format!("refuse_invalid_subsize(({level}, {level})"))); - assert!( - guard_at.is_some(), - "{} (decode.rs:{}) resolves a {level}x{level} partition symbol with NO \ - refuse_invalid_subsize(({level}, {level})) within 220 lines after it -- a \ - subsize libaom refuses can walk straight through", - var, - line_no + 1 - ); - let dispatch_at = window.iter().position(|l| { - let t = l.trim_start(); - !t.starts_with("//") && t.starts_with("match part") - }); - if let Some(d) = dispatch_at { - assert!( - guard_at.expect("checked above") < d, - "{} (decode.rs:{}) is DISPATCHED at window line {d} BEFORE its \ - refuse_invalid_subsize(({level}, {level})) -- the guard can never \ - observe that dispatch", - var, - line_no + 1 - ); - } - } - - // The r5 defect, as its own invariant: a guard must never sit INSIDE a - // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. Such an arm can only carry - // partition values 4..=7, and the offending values are PARTITION_VERT (2) - // and PARTITION_VERT_4 (9). Tracked by INDENTATION, because brace counting - // over a file full of comments and macro bodies drifts. - let indent_of = |l: &str| l.len() - l.trim_start().len(); - // (arm indent, arm BODY indent). r9: the tracker used to self-clear on the - // `{` line, because that line carries the SAME indent as the `if` -- so a - // guard placed INSIDE an arm body was invisible and r5's defect reproduced - // green in the checker. Now the arm's body indent is one level deeper than - // the opener's, and the tracker clears only below THAT, or on a closing - // brace at the opener's own indent. - let mut ab_arm: Option<(usize, bool)> = None; - for (n, line) in src.lines().enumerate() { - let t = line.trim_start(); - if t.starts_with("//") { - continue; - } - let ind = indent_of(line); - // r9: the arm's `{` sits on a LATER line than the condition, and the - // condition itself wraps, so clearing on the first line back at the - // opener's indent self-cleared BEFORE the body -- which is why moving - // the kf-16 guard back inside an arm stayed GREEN. Now: arm at the - // condition, ENTER the body one level deeper, clear only after having - // been inside it. - if line.contains("PARTITION_HORZ_A..=PARTITION_VERT_B") { - ab_arm = Some((ind + 4, false)); - } else if t == "{" { - // r10: the arm's own brace carries the OPENER's indent, not the - // body's, so treating it as "backed out" cleared the arm before a - // single body statement was seen -- which is why the mutation that - // moves a guard INSIDE an arm stayed GREEN at r8 AND r9. A lone `{` - // never changes the state. - } else if let Some((body, entered)) = ab_arm { - if !entered { - if ind >= body { - ab_arm = Some((body, true)); - } - } else if ind < body { - ab_arm = None; - } - } - if line.contains("refuse_invalid_subsize((") { - assert!( - ab_arm.is_none_or(|_| false), - "decode.rs:{} puts a refuse_invalid_subsize inside a \ - PARTITION_HORZ_A..=PARTITION_VERT_B arm (values 4..=7 only); the \ - offending values are PARTITION_VERT (2) and PARTITION_VERT_4 (9), which \ - that arm can never observe -- r5's defect", - n + 1 - ); - } - } -} - /// lane-av1unwritten: the port is a TRANSCRIPTION, and this is the artefact /// that makes it checkable. It re-writes `av1_ss_size_lookup`'s 22 rows /// (`common_data.c:17-41`) literally -- every shape, every subsampling @@ -454,886 +128,6 @@ fn chroma_plane_block_codable_matches_the_libaom_table() { ); } -/// lane-av1subsizesweep: the CENSUS, as an invariant. -/// -/// The merged `lane/av1unwritten` lane covers partition SYMBOLS: every -/// `dec.symbol(&mut cdfs.partition_w[..])` gets a -/// [`refuse_invalid_subsize`] within 220 lines, and -/// [`every_partition_symbol_resolution_is_guarded_before_it_dispatches`] -/// holds that shape against the source. Its own stated limit is exactly -/// the hole this lane found: the scan matches on `dec.symbol(`, so the -/// frame-edge GATHER reads (`dec.symbol_fixed(&gather(..))`) are invisible -/// to it, and its site list names RESOLUTIONS, not the chroma-plane WALKS -/// those resolutions descend into. -/// -/// So this test states the other half, over the WALK sites instead of the -/// symbol sites: -/// -/// * every `decode_*` call that walks a chroma plane is enumerated, with -/// the luma shape(s) it can be handed -- derived from the enclosing -/// dispatch, not typed in by hand; -/// * for each shape that libaom marks BLOCK_INVALID at some subsampling -/// mode, the walk must have a [`refuse_invalid_subsize`] for its OWN -/// level on its path -- either at the level that dispatched it -/// (`PARTITION_*` arms resolve into a `partN`) or at the dispatch site -/// itself; -/// * a walk reachable ONLY through a level whose guard already refuses the -/// offending subsize is CLOSED, and the reason is the level's own guard -/// line -- asserted, not commented. -/// -/// The residue the merged lane named, [`decode_rect4_16_intrabc`], is the -/// second case: it is reachable only from the 16x16-level 1:4 arms, and -/// `partition_subsize_dims((16,16), PARTITION_VERT_4) == (4,16)`, which is -/// in `PLANE_BLOCK_INVALID_422`. Both of its callers' guards refuse that -/// before the call, so it is CLOSED rather than guarded a third time -- -/// and this test is what makes that a checked claim instead of a comment. -#[test] -fn every_chroma_walking_leaf_dispatch_is_guarded_or_closed_with_a_reason() { - let src = crate::test_source::module_source("decode"); - // r2: `decode_body` is hoisted to the top of the test because the per-row - // guard check below needs it BEFORE the walk census it sits under, and a - // reader who has to hunt for a binding is a reader who will not notice - // when it is scoped to the wrong thing. - let production = crate::test_source::module_production_source("decode"); - let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") { - Some(i) => &production[..i], - None => production, - }; - // (a) The shapes libaom cannot code, transcribed from the same - // `av1_ss_size_lookup` cells `PLANE_BLOCK_INVALID_422` carries. A walk - // handed one of these at the matching subsampling mode is the defect. - let invalid_at = - |bw: usize, bh: usize, sx: usize, sy: usize| !chroma_plane_block_codable(bw, bh, sx, sy); - - // (b) The CENSUS: every chroma-plane walk in the decode body, with the - // luma footprint(s) each dispatch can hand it. `guarded_by` names the - // mechanism, which is what a reader has to be able to check: - // - // * `refuse_invalid_subsize` at the DISPATCH -- the guard sits on - // the walk's own path (the hole this lane fixed, and the 8x8 / - // 16-level sites); - // * `refuse_invalid_subsize` at the RESOLUTION -- the dispatch is a - // `PARTITION_*` arm, so the level's guard saw the symbol that - // selected this shape before the call; - // * `unreachable` -- proven-uncodable at every subsampling mode a - // `color_config` can select, closed with an assertion instead of - // a guard. - // - // Each row is (walk, shapes, mechanism). - // - // r2 (Main's review, and it was right): `AtResolution` used to assert - // only that SOME shape the walk handles is BLOCK_INVALID, which - // restates the libaom table and never mentions a guard -- deleting the - // inter 32-level guard left it green. So a resolution row now CARRIES - // the guard it depends on: `(walk, fn-scope, level)`, and the check - // below looks for `refuse_invalid_subsize((level, level))` inside that - // function and before the walk's first call site in it. A row that - // cannot be checked that way says so with `Prose` instead. - enum Mech { - AtDispatch, - /// Protected by `refuse_invalid_subsize((L, L))` in the named - /// function, above the walk's first call site there. - AtResolution(&'static str, usize), - /// The walk is reached INDIRECTLY -- this row's guard is asserted to - /// exist in `fscope`, and the ordering is asserted by the per-route - /// loop further down (which scopes to the enclosing function and - /// names this walk's real caller chain). Used only where the walk's - /// call site is not in the guard's own function. - AtResolutionVia(&'static str, usize), - Unreachable(&'static str), - } - // The key-frame tile decoder and the inter tile decoder. Every - // resolution guard lives in one of the two, which is what makes "the - // guard for THIS row" a scoped lookup rather than a global one. - const KF: &str = "decode_key_frame_tile_with_cdfs"; - const INTER: &str = "decode_inter_frame_tile_with_cdfs"; - let census: &[(&str, &[(usize, usize)], Mech)] = &[ - // ---- the residue the merged lane named ------------------- - // - // `decode_rect4_16_intrabc` reconstructs one 16x4 or 4x16 strip. - // It has exactly ONE caller (`decode_rect4_16_strip`, decode.rs - // 18934), which has exactly two (17595 from `decode_rect4_16`, - // 13810 from `decode_intra_rect_in_inter`), which have one each - // (36793 key frame, 45447 inter). BOTH are 16x16-level 1:4 arms, so - // both sit under a `refuse_invalid_subsize((16, 16), part16)`. - // - // The offending subsize is the VERT_4 one and ONLY that one: - // `partition_subsize_dims((16,16), PARTITION_VERT_4) == (4,16)`, - // and (4,16) is in `PLANE_BLOCK_INVALID_422`, while HORZ_4 gives - // (16,4) whose (1,0) cell is BLOCK_8X4 and is legal. So the - // 16x16-level guard refuses exactly the shape that would be - // BLOCK_INVALID, and the strip that survives -- 16x4 -- is the one - // this decoder's `own422` arm is written for. Part (d) below - // re-derives that split and part (f) pins the caller count, so the - // closure is checked rather than asserted in prose. - ( - "decode_rect4_16_intrabc", - &[(16, 4), (4, 16)], - Mech::AtResolutionVia(KF, 16), - ), - // ---- 1:4 and 2:1 rect walks, all resolved-symbol guarded -- - ( - "decode_rect4_16", - &[(16, 4), (4, 16)], - Mech::AtResolution(KF, 16), - ), - ( - "decode_rect4_16_strip", - &[(16, 4), (4, 16)], - Mech::AtResolutionVia(KF, 16), - ), - ( - "decode_block_rect", - &[(32, 16), (16, 32)], - Mech::AtResolution(KF, 32), - ), - ( - "decode_block_rect4", - &[(32, 8), (8, 32)], - Mech::AtResolution(KF, 32), - ), - ( - "decode_block_rect64", - &[(64, 16), (16, 64)], - Mech::AtResolution(KF, 64), - ), - // The 128-root guard lives in `read_sb128_root`, the shared - // resolver both tile decoders call -- not in the walker's own - // function. - ( - "decode_block_128rect", - &[(128, 64), (64, 128)], - Mech::AtResolutionVia("read_sb128_root", 128), - ), - // `decode_rect_split` is called from inside decode_block_rect / - // decode_leaf_rect / decode_block_rect4 / decode_block_rect64, none of - // which is the tile decoder -- so the guard it inherits is checked on - // its own callers' rows, not here. - ( - "decode_rect_split", - &[(64, 16), (16, 64), (32, 16), (16, 32)], - Mech::AtResolutionVia(KF, 32), - ), - ( - "decode_leaf_rect", - &[(16, 8), (8, 16)], - Mech::AtResolution(KF, 16), - ), - // ---- the INTER-side rect walks ----------------------------- - // - // r2: without these three rows the inter 32- and 64-level guards - // were claimed by NOTHING, and deleting either left the census - // green. They are load-bearing -- `decode_intra_rect_in_inter` - // dispatches `decode_block_rect4` on 32x8/8x32 (8x32 is - // BLOCK_INVALID at 4:2:2) and `decode_block_rect64` on - // 64x16/16x64 (16x64 likewise) -- so each gets its own row naming - // the guard that stands in front of it. - // - // These are `AtResolutionVia`, not `AtResolution`: the walk is - // dispatched from `decode_intra_rect_in_inter`, a helper, not from - // the tile decoder the guard lives in. The check is therefore guard - // EXISTENCE in that decoder -- which is what reds when the guard - // is deleted -- and the linkage is stated here rather than derived. - ( - "decode_block_rect4[inter]", - &[(32, 8), (8, 32)], - Mech::AtResolutionVia(INTER, 32), - ), - ( - "decode_block_rect64[inter]", - &[(64, 16), (16, 64)], - Mech::AtResolutionVia(INTER, 64), - ), - ( - "decode_intra_rect_in_inter", - &[(16, 8), (8, 16), (16, 4), (4, 16)], - Mech::AtResolutionVia(INTER, 16), - ), - // ---- sub-8 walks ------------------------------------------ - // (8,4) is legal at 4:2:2 (`av1_ss_size_lookup[8x4][1][0]` is - // BLOCK_4X4); (4,8) is BLOCK_INVALID there. Both come off a raw - // `part8`, and both 8x8 resolution sites carry the guard -- plus - // the redundant inline `chroma_plane_block_codable` check the - // merged lane left at 36904. - ( - "decode_leaf_rect8", - &[(8, 4), (4, 8)], - Mech::AtResolution(KF, 8), - ), - ( - "decode_inter_sub8_rect2", - &[(8, 4), (4, 8)], - Mech::AtResolution(INTER, 8), - ), - ( - "decode_leaf_split4", - &[(4, 4)], - Mech::Unreachable("4x4's plane block is 4x4 at EVERY subsampling cell"), - ), - ( - "decode_inter_sub8_split4", - &[(4, 4)], - Mech::Unreachable("4x4's plane block is 4x4 at EVERY subsampling cell"), - ), - ( - "decode_leaf8", - &[(8, 8)], - Mech::Unreachable("8x8's plane block is 8x8 / 4x8 / 4x4, never BLOCK_INVALID"), - ), - // The square walks take only square footprints, and every square - // in `BLOCK_SIZES_ALL` has a valid plane block at EVERY selectable - // mode (the whole BLOCK_INVALID column is 4x8 / 8x4 / 4x16 / 8x16 - // / ... -- all rect). So no guard is needed for them, and the - // level guards that exist protect the SYMBOL that would have to - // select one of those rect shapes, not the square decode itself. - ( - "decode_block", - &[(128, 128), (64, 64), (32, 32), (16, 16), (8, 8)], - Mech::Unreachable( - "every SQUARE footprint's plane block is valid at every selectable \ - subsampling mode; the whole BLOCK_INVALID column is rect", - ), - ), - ( - "decode_inter_block", - &[(128, 128), (64, 64), (32, 32), (16, 16), (8, 8)], - Mech::Unreachable( - "every SQUARE footprint's plane block is valid at every selectable \ - subsampling mode; the whole BLOCK_INVALID column is rect", - ), - ), - ( - "decode_inter_block8", - &[(8, 8)], - Mech::Unreachable("8x8's plane block is 8x8 / 4x8 / 4x4, never BLOCK_INVALID"), - ), - // ---- THE HOLE THIS LANE FIXED --------------------------- - // - // `decode_leaf_rect`'s key-frame FRAME-EDGE caller (the one - // `decode_leaf_rect`'s row above does not cover, because that arm - // dispatches on a gathered `edge_split` instead of resolving into - // `part16`). It is 8x16 when the COLUMN is short -- BLOCK_INVALID - // at 4:2:2 -- and 16x8 when the ROW is, which is legal and must - // keep decoding. Before this lane nothing sat on that path. - ( - "decode_leaf_rect[16-edge]", - &[(16, 8), (8, 16)], - Mech::AtDispatch, - ), - ]; - - // (c) Every row's mechanism must be a REAL one. This is what stops - // the census from being a list of good intentions: each claim is - // re-derived here, and the file is checked for the site it names. - for (walk, shapes, mech) in census { - let name = walk.split('[').next().expect("walk name"); - assert!( - src.contains(&format!("fn {name}(")), - "the census names `{name}`, which is not a function in this file -- the \ - walk was renamed or removed and this row is stale" - ); - // Only subsampling modes a `color_config` can actually SELECT - // count. `(0, 1)` 4:4:0 is excluded on libaom's own authority -- - // it asserts `subsampling_y == 0` whenever `subsampling_x == 0` - // (`color_config`, av1_decoder.c), so no frame in existence is - // 4:4:0 and `PLANE_BLOCK_INVALID_440` is transcribed only to keep - // the cell table whole. Counting it here would make `16x4` look - // like a shape that needs a guard at a mode no stream can carry - // -- the same class as the merged lane's r2, which refused a legal - // 4:2:2 shape by testing a cell no `color_config` can request. - let offending: Vec<(usize, usize, usize, usize)> = shapes - .iter() - .flat_map(|&(bw, bh)| { - [(1, 0), (1, 1), (0, 0)] - .into_iter() - .filter_map(move |(sx, sy)| { - invalid_at(bw, bh, sx, sy).then_some((bw, bh, sx, sy)) - }) - }) - .collect(); - match mech { - // A dispatch-time guard has to reduce to the SAME shape the - // dispatch hands the walk -- this is the claim that made the - // hole a hole, stated as an assertion. - Mech::AtDispatch => { - assert!( - !offending.is_empty(), - "{walk} is listed AtDispatch but libaom codes every shape it \ - walks at every subsampling mode -- then it needs no guard" - ); - for &(bw, bh, sx, sy) in &offending { - assert!( - invalid_at(bw, bh, sx, sy), - "{walk} is not actually handed {bw}x{bh} at ({sx},{sy})" - ); - } - } - // r2: the guard THIS row depends on, scoped to the function it - // lives in and ordered before the walk's first call there. - // Deleting that one guard -- and only that one -- reds this row, - // which is what r2's review showed the previous version could - // not do. - Mech::AtResolution(fscope, level) => { - assert!( - !offending.is_empty(), - "{walk} is listed AtResolution but no shape it walks is BLOCK_INVALID \ - -- then the level's guard is not what protects it" - ); - let fstart = decode_body - .find(&format!("\nfn {fscope}(")) - .or_else(|| decode_body.find(&format!("\npub(crate) fn {fscope}("))) - .or_else(|| decode_body.find(&format!("\npub fn {fscope}("))) - .unwrap_or_else(|| { - panic!("the census names `{fscope}`, which is not a function here") - }); - let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - let body = &decode_body[fstart..fend]; - let guard = format!("refuse_invalid_subsize(({level}, {level})"); - let gpos = body.find(&guard).unwrap_or_else(|| { - panic!( - "{walk} claims refuse_invalid_subsize(({level}, {level})) guards it, \ - but there is NO such guard in `{fscope}` -- the row's mechanism is \ - prose, not a check; re-derive it or mark the row Prose" - ) - }); - let call = body.find(&format!("{name}(")).unwrap_or_else(|| { - panic!("{walk} has no call site inside `{fscope}` to order the guard against") - }); - assert!( - gpos < call, - "{walk}: in `{fscope}` the ({level}, {level}) guard is at {gpos} and the \ - walk is dispatched at {call} -- a guard BELOW the dispatch can never \ - observe it" - ); - } - Mech::AtResolutionVia(fscope, level) => { - assert!( - !offending.is_empty(), - "{walk} is listed AtResolutionVia but no shape it walks is \ - BLOCK_INVALID" - ); - let fstart = decode_body - .find(&format!("\nfn {fscope}(")) - .or_else(|| decode_body.find(&format!("\npub(crate) fn {fscope}("))) - .or_else(|| decode_body.find(&format!("\npub fn {fscope}("))) - .unwrap_or_else(|| { - panic!("the census names `{fscope}`, which is not a function here") - }); - let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - assert!( - decode_body[fstart..fend] - .contains(&format!("refuse_invalid_subsize(({level}, {level})")), - "{walk} claims refuse_invalid_subsize(({level}, {level})) in `{fscope}` \ - guards it, but there is NO such guard there" - ); - } - Mech::Unreachable(reason) => { - assert!( - offending.is_empty(), - "{walk} claims it is unreachable, but libaom marks {} \ - BLOCK_INVALID -- the claim is stale", - offending - .iter() - .map(|(bw, bh, sx, sy)| format!("{bw}x{bh}@({sx},{sy})")) - .collect::>() - .join(", ") - ); - assert!( - reason.len() > 40, - "{walk}'s Unreachable reason is too short to name the symbol \ - or caller that makes it unreachable" - ); - } - } - } - - // (d) The residue's closure, derived rather than asserted in prose: - // the ONLY subsize its callers can hand it that libaom refuses at - // 4:2:2 is the 16x16-level VERT_4 one, and the level's own guard - // refuses exactly that. If either half stops holding -- a new caller - // at another level, or a change to `partition_subsize_dims` -- this - // reds instead of the comment going stale. - for &(part, want) in &[ - (PARTITION_HORZ_4, (16usize, 4usize)), - (PARTITION_VERT_4, (4, 16)), - ] { - let (bw, bh) = partition_subsize_dims((16, 16), part); - assert_eq!( - (bw, bh), - want, - "get_partition_subsize(BLOCK_16X16, {part}) moved" - ); - assert_eq!( - chroma_plane_block_codable(bw, bh, 1, 0), - part == PARTITION_HORZ_4, - "the 16x16 1:4 pair's (1,0) cells moved: HORZ_4 -> {bw}x{bh}, \ - VERT_4 -> {bw}x{bh}. decode_rect4_16_intrabc's Unreachable row \ - is written against exactly this split" - ); - } - // (e) The AtDispatch row, checked where it actually bites. This is - // the hole the merged lane's scan cannot see: its 220-line window is - // keyed on `dec.symbol(`, and the frame-edge arm reads - // `dec.symbol_fixed(&gather(..))` into `edge_split` and dispatches on - // THAT. The claim to check is ordering -- the guard has to sit between - // the read and the `decode_leaf_rect` it protects, which is r5's - // defect in a new place if it ever moves below. - let edge_read = src - .find("let edge_split = if has_cols16") - .expect("the key-frame 16-level frame-edge arm reads a gathered bit"); - let guard_at = src[edge_read..] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| edge_read + i) - .expect( - "the key-frame 16-level frame-edge arm dispatches decode_leaf_rect on an \ - 8x16 strip (BLOCK_INVALID at 4:2:2) with NO refuse_invalid_subsize on its \ - path -- every sibling edge arm resolves into a guarded partN, this one does not", - ); - let walk_at = src[edge_read..] - .find("decode_leaf_rect(") - .map(|i| edge_read + i) - .expect("the frame-edge arm's decode_leaf_rect call"); - assert!( - guard_at < walk_at, - "the 16-level frame-edge guard (offset {guard_at}) sits AFTER the \ - decode_leaf_rect it protects (offset {walk_at}) -- it can never observe it" - ); - - // (f) The residue's closure, by CALLER COUNT rather than by prose: a - // third caller at another level is what would make the residue row - // stale, and a count reds on that where a comment cannot. Counted over - // the DECODE BODY only -- this test's own string literals name the same - // functions, and the merged lane's own scan hit exactly that (five of - // its eighteen `refuse_invalid_subsize((` matches are its own). - for (name, calls) in [ - ("decode_rect4_16_intrabc", 1usize), - ("decode_rect4_16_strip", 2), - ("decode_rect4_16", 1), - ("decode_intra_rect_in_inter", 1), - ] { - let needle = format!("{name}("); - let decl = format!("fn {name}("); - // A doc-comment mention (`[`name`](..)`) is prose, not a call, so - // comment lines are dropped before counting. - let body: String = decode_body - .lines() - .filter(|l| !l.trim_start().starts_with("//")) - .collect::>() - .join("\n"); - let found = body.matches(&needle).count() - usize::from(body.contains(&decl)); - assert_eq!( - found, calls, - "{name} has {found} call site(s) in the decode body, the census expects \ - {calls}. A new caller is not automatically wrong, but it is not \ - automatically covered either: re-derive which level's guard it sits \ - under before this row stays green" - ); - } - // Both callers reach the 1:4 strips by a DIFFERENT route, so the - // closure is checked per route -- and per route it is the same shape: - // the 16x16-level guard must sit ABOVE the test that names VERT_4. - // - // key frame: `decode_rect4_16(...)` at 36793, inside an arm testing - // `part16 == PARTITION_HORZ_4 || part16 == PARTITION_VERT_4`. - // inter: the 1:4 strips reach `decode_intra_rect_in_inter` - // through `fctx.inter_strip_chroma`, whose ONLY writer is the inter - // 16-level 1:4 arm (55068) -- `strip16` is `None` without it. - // - // Ordering is the property (a guard BELOW the 1:4 test cannot observe - // it), which is why each pair is compared rather than merely counted. - for (what, test, call) in [ - ( - "the key-frame decode_rect4_16 caller", - "if part16 == PARTITION_HORZ_4", - "decode_rect4_16(", - ), - ( - "the inter-frame inter_strip_chroma writer", - "let horz = part16 == PARTITION_HORZ_4;", - "c.set(Some(InterStripChroma {", - ), - ] { - let fn_scope = |at: usize| -> std::ops::Range { - let head = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[..at].rfind(pat)) - .max() - .unwrap_or(0); - let tail = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[at..].find(pat).map(|i| at + i)) - .min() - .unwrap_or(decode_body.len()); - head..tail - }; - // The first occurrence of the test text can sit in another function (the files are - // concatenated in path order), so take the first occurrence whose own function holds - // the dispatch. The guard, the test and the dispatch must then share that function. - let (test_at, _, call_at) = decode_body - .match_indices(test) - .find_map(|(t, _)| { - let sc = fn_scope(t); - decode_body[sc.clone()] - .rfind(call) - .map(|i| (t, sc.clone(), sc.start + i)) - }) - .unwrap_or_else(|| panic!("the 1:4 arm test {test:?} for {what} is gone, or no function holds its dispatch {call:?}")); - // The dispatch is searched inside the 1:4 test's own function: the files are - // concatenated in path order, so the last occurrence in the whole text is no longer - // the key-frame call. The guard, test and dispatch must share that function. - // `decode_rect4_16(` also matches the DEFINITION, which is the - // first occurrence -- the call is the last one. - // r2 (Main's review, and it was right): the guard search is SCOPED - // to the anchor's own enclosing function. `find()` over the whole - // decode body returns the FIRST `refuse_invalid_subsize((16, 16)` -- - // the KEY-FRAME one -- so the inter pair's comparison was satisfied - // by a guard three quarters of the file away, and deleting the inter - // 16-level guard left this test green. Both routes live in - // different `fn` bodies (`decode_key_frame_tile_with_cdfs` and the - // inter tile decoder), so the enclosing function is the scope that - // tells the two apart. - let scope = fn_scope(test_at); - let guard_at = decode_body[scope.clone()] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| scope.start + i) - .unwrap_or_else(|| { - panic!( - "{what}: there is NO refuse_invalid_subsize((16, 16)) in the function \ - enclosing the 1:4 arm test -- so nothing refuses the VERT_4 symbol \ - this arm dispatches on, and decode_rect4_16_intrabc's closure is gone" - ) - }); - assert!( - guard_at < test_at && test_at < call_at, - "{what}: guard at {guard_at} (function scope {scope:?}), 1:4 arm test at \ - {test_at}, dispatch at {call_at}. The guard has to sit ABOVE the 1:4 arm \ - test INSIDE THE SAME FUNCTION, or the VERT_4 symbol it refuses has already \ - been dispatched on" - ); - assert!( - scope.contains(&guard_at) && scope.contains(&test_at) && scope.contains(&call_at), - "{what}: guard, 1:4 test and dispatch must share one enclosing function" - ); - } - // And the inter route really is the only one: `strip16` is built from - // `strip_chroma`, which is `inter_strip_chroma.take()`, so a missing - // writer would silently drop the arm rather than expose it. - assert_eq!( - decode_body.matches("inter_strip_chroma.with(|c| {").count(), - 1, - "inter_strip_chroma gained a second writer -- the inter 1:4 strips can now \ - come from a level whose guard this census has not checked" - ); - - // (g) PER-SITE rows. Everything above claims a guard by LEVEL -- - // "there is a `refuse_invalid_subsize((8, 8))` somewhere in the - // key-frame tile decoder" -- and that is exactly what makes two - // guards deletable: the key-frame 8x8 level has TWO resolution - // sites (37322 and 37621) and the walk census's `decode_leaf_rect8` - // row is satisfied by the first one, so deleting the SECOND left the - // test green; the inter decoder carries its OWN 128-root guard - // (54495) while the `decode_block_128rect` row names - // `read_sb128_root`, so deleting the inter copy also left it green. - // The merged scan's count cross-check is what reds them, and a - // count is not a location. - // - // So each row below names an ANCHOR that is unique in the decode - // body -- the code the site hangs off -- and requires the level's - // guard to sit between that anchor and the dispatch the site - // feeds, within the same function. A level guard elsewhere in that - // function cannot stand in, because the search starts AT the - // anchor. Deleting the named guard finds no guard after the anchor - // and reds; moving it below the dispatch reds the ordering assert. - // - // Row shape: (site label, guard's function, level, unique anchor, - // dispatch token the guard must precede, shapes the site walks). - let body_of = |name: &str| -> &str { - let start = decode_body - .find(&format!("\nfn {name}(")) - .or_else(|| decode_body.find(&format!("\npub(crate) fn {name}("))) - .or_else(|| decode_body.find(&format!("\npub fn {name}("))) - .unwrap_or_else(|| panic!("{name} is not a function in this file")); - let end = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[start + 1..].find(pat).map(|i| start + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - &decode_body[start..end] - }; - let site_rows: &[(&str, &str, usize, &str, &str, &[(usize, usize)])] = &[ - // The key-frame 8x8 level resolves TWICE (37322 for the frame - // interior, 37621 for the `pre8` probe path). Both feed - // `decode_leaf_rect8` on a raw `part8`, whose VERT shape is 4x8 -- - // BLOCK_INVALID at 4:2:2. The anchor `let pre8 = ...` is what - // makes this row about the SECOND site: with `find()` scoped to - // the function alone the search would return 37322 and never - // look here. - ( - "the key-frame 8x8 SECOND resolution", - KF, - 8, - "let pre8 = dec.debug_state().0;", - "decode_leaf_rect8(", - &[(8, 4), (4, 8)], - ), - // The inter decoder resolves its own 128 root at 54495 rather - // than routing through `read_sb128_root` (which is where the - // `decode_block_128rect` row's guard lives). The dispatch token - // is the `half128_inter!` arm that descends into a 128x64 / - // 64x128 rect -- both BLOCK_INVALID at 4:2:2 in - // `PLANE_BLOCK_INVALID_422`. `macro_rules! half128_inter` is - // unique in the file, so this row cannot drift onto the other - // one. - ( - "the inter decoder's own 128-root guard", - INTER, - 128, - "macro_rules! half128_inter", - "half128_inter!((br_mi, base_mi.1), 128, 64,", - &[(128, 64), (64, 128)], - ), - ]; - for (label, fscope, level, anchor, dispatch, shapes) in site_rows { - assert_eq!( - decode_body.matches(anchor).count(), - 1, - "{label}: the site anchor {anchor:?} is not unique in the decode body, so it \ - cannot name one site -- re-derive the anchor for this row" - ); - // Why the site needs a guard at all: something it dispatches is - // BLOCK_INVALID at a mode a `color_config` can select. (0, 1) is - // excluded for the same reason as the walk census above. - let offending: Vec<(usize, usize, usize, usize)> = shapes - .iter() - .flat_map(|&(bw, bh)| { - [(1, 0), (1, 1), (0, 0)] - .into_iter() - .filter_map(move |(sx, sy)| { - invalid_at(bw, bh, sx, sy).then_some((bw, bh, sx, sy)) - }) - }) - .collect(); - assert!( - !offending.is_empty(), - "{label} claims a guard but libaom codes every shape it walks at every \ - selectable subsampling mode -- then it needs none" - ); - let body = body_of(fscope); - let a = body.find(anchor).unwrap_or_else(|| { - panic!( - "{label}: the anchor {anchor:?} is not inside `{fscope}` -- the guard \ - moved to another function, and the row's scope is stale" - ) - }); - let gpat = format!("refuse_invalid_subsize(({level}, {level})"); - let g = body[a..].find(&gpat).map(|i| a + i).unwrap_or_else(|| { - panic!( - "{label}: `{fscope}` has NO {gpat} at or after the site anchor {anchor:?} \ - -- this site's guard is gone. The level claim elsewhere in this test is \ - still satisfied by the OTHER {level}x{level} guard in the file, which is \ - precisely why this row exists" - ) - }); - let gap = body[a..g].lines().count(); - assert!( - gap <= 40, - "{label}: the {gpat} sits {gap} lines below its own anchor {anchor:?} -- that is \ - a different site, so this row has stopped naming what it claims to name" - ); - let d = body[g..].find(dispatch).map(|i| g + i).unwrap_or_else(|| { - panic!( - "{label}: `{fscope}` dispatches {dispatch:?} nowhere AFTER its {gpat} -- \ - either the dispatch moved above the guard or the site was rewritten" - ) - }); - assert!( - g < d, - "{label}: guard at {g} sits at or after the dispatch at {d} -- a guard BELOW \ - the dispatch can never observe it" - ); - } -} - -/// lane/av1422rect4dead: the `(pw / 2, ph / 2)` / `MI / 2` origin `else` -/// arm of [`decode_rect4_16_intrabc`] is the 4:2:0 PAIR geometry. It is -/// still LIVE at ss (1, 1) -- a 1:4 strip's chroma lies inside its -/// 4:2:0 pair there -- so the arm is not deleted; it is CLOSED at ss -/// (1, 0), where it would run on a 4x16 VERT_4 strip whose chroma plane -/// block is BLOCK_INVALID, and where libaom's own -/// `is_chroma_reference` (av1_common_int.h:1454, `|| !subsampling_y`) -/// makes every strip its own chroma reference anyway (the `own422` arm -/// handles that). The proof: the sole caller `decode_rect4_16_strip` is -/// reached only via the two 16x16-level 1:4 arms, each under -/// `refuse_invalid_subsize((16, 16), part16)` -- at ss (1, 0) that guard -/// refuses `partition_subsize_dims((16, 16), PARTITION_VERT_4) == (4, 16)` -/// (in `PLANE_BLOCK_INVALID_422`), and the surviving HORZ_4 16x4 strip -/// takes `own422`. This test re-derives that chain from the file so it -/// REDS when any half stops holding: deleting the in-arm assertion, a -/// caller moving under a level whose guard does not refuse (4, 16) at -/// ss (1, 0), or the `(pw / 2, ph / 2)` form drifting. 4:2:0 and 4:4:4 -/// behaviour are unchanged: the gate runs only the file scan and the -/// closed cell's arithmetic, no decode. -#[test] -fn decode_rect4_16_intrabc_else_arm_stays_closed_at_422() { - let production = crate::test_source::module_production_source("decode"); - let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") { - Some(i) => &production[..i], - None => production, - }; - - // (a) The closure assertion must exist INSIDE the function, in the - // `else` arm of the `(cw, ch)` select, naming the shape and the - // subsampling. Deleting it -- or re-adding the bare halving without - // it -- reds here. - let fstart = decode_body - .find("\nfn decode_rect4_16_intrabc(") - .expect("decode_rect4_16_intrabc is gone -- this gate guards its else arm"); - let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - let body = &decode_body[fstart..fend]; - let else_arm = body - .find(" let (cw, ch) = if own_chroma {") - .expect("the (cw, ch) select moved out of decode_rect4_16_intrabc"); - let closure = &body[else_arm..]; - assert!( - closure.contains("assert!(") && closure.contains("ss_x(fctx) == 1 && ss_y(fctx) == 0"), - "the decode_rect4_16_intrabc else arm's ss (1, 0) closure assertion is \ - GONE -- the 4:2:0 pair geometry is unreachable at ss (1, 0) only while \ - that assert (and the guards below) stand; re-add it" - ); - - // (b) The sole-caller chain, re-derived from the file: exactly one - // call to `decode_rect4_16_intrabc(` outside its own definition, in - // `decode_rect4_16_strip`; exactly two calls to - // `decode_rect4_16_strip(` from the two 1:4 routes. - let code_lines: String = decode_body - .lines() - .filter(|l| !l.trim_start().starts_with("//")) - .collect::>() - .join("\n"); - let count_calls = |name: &str| -> usize { - code_lines.matches(&format!("{name}(")).count() - - usize::from(code_lines.contains(&format!("fn {name}("))) - }; - assert_eq!( - count_calls("decode_rect4_16_intrabc"), - 1, - "decode_rect4_16_intrabc gained a caller -- re-derive whether the new route \ - sits under a guard that refuses (4, 16) at ss (1, 0) before this gate \ - stays green" - ); - assert_eq!( - count_calls("decode_rect4_16_strip"), - 2, - "decode_rect4_16_strip's caller set moved -- both routes must be \ - 16x16-level 1:4 arms under a (16, 16) guard that refuses (4, 16) at \ - ss (1, 0)" - ); - - // (c) Both routes sit under a `refuse_invalid_subsize((16, 16), ...)`: - // the key-frame arm's guard ordered above the arm test, the inter - // arm's guard in the inter decoder above its own 1:4 test. Scoped to - // the enclosing function so the other decoder's guard cannot stand in - // (the r2 class this file already fixed once). - let fn_scope = |at: usize| -> std::ops::Range { - let head = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[..at].rfind(pat)) - .max() - .unwrap_or(0); - let tail = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[at..].find(pat).map(|i| at + i)) - .min() - .unwrap_or(decode_body.len()); - head..tail - }; - let kf_test = decode_body - .find("if part16 == PARTITION_HORZ_4") - .expect("the key-frame 16-level 1:4 arm test is gone"); - let kf_scope = fn_scope(kf_test); - let kf_guard = decode_body[kf_scope.clone()] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| kf_scope.start + i) - .unwrap_or_else(|| { - panic!( - "the key-frame 16-level 1:4 arm has NO \ - refuse_invalid_subsize((16, 16)) above it in its own \ - function -- the VERT_4 (4, 16) refusal that closed \ - decode_rect4_16_intrabc's else arm at ss (1, 0) is gone" - ) - }); - assert!( - kf_guard < kf_test, - "the key-frame (16, 16) guard sits below the 1:4 arm test -- it can never \ - observe the VERT_4 symbol that must be refused before \ - decode_rect4_16_intrabc's else arm can run at ss (1, 0)" - ); - let inter_writer = decode_body - .find("let horz = part16 == PARTITION_HORZ_4;") - .expect("the inter 16-level 1:4 arm is gone"); - let inter_scope = fn_scope(inter_writer); - let inter_guard = decode_body[inter_scope.clone()] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| inter_scope.start + i) - .unwrap_or_else(|| { - panic!( - "the inter-frame 16-level 1:4 arm has NO \ - refuse_invalid_subsize((16, 16)) in its function -- the VERT_4 \ - (4, 16) refusal that closed decode_rect4_16_intrabc's else arm \ - at ss (1, 0) is gone" - ) - }); - assert!( - inter_guard < inter_writer, - "the inter (16, 16) guard sits below the 1:4 arm test -- it can never \ - observe the VERT_4 symbol that must be refused before \ - decode_rect4_16_intrabc's else arm can run at ss (1, 0)" - ); - - // (d) The shape/subsampling cells the closure is written against, - // re-executed: (4, 16) must still be BLOCK_INVALID at ss (1, 0) while - // (16, 4) stays codable there, and at ss (1, 1) BOTH are codable -- - // which is what keeps the arm live at 4:2:0 and the assertion inert - // there. At ss (0, 0) everything is codable, so `own444` (and the - // assertion) never see the else arm. - assert!( - !chroma_plane_block_codable(4, 16, 1, 0), - "(4, 16) left PLANE_BLOCK_INVALID_422 -- the else arm is now REACHABLE at \ - ss (1, 0) with the halved pair geometry, which is a real defect, not a \ - closure: re-derive the whole chain, then fix the halving instead of the \ - assert" - ); - assert!( - chroma_plane_block_codable(16, 4, 1, 0), - "(16, 4) became BLOCK_INVALID at ss (1, 0) -- the surviving HORZ_4 strip \ - takes own422, and the closure assert would fire on a legal shape; \ - re-derive" - ); - assert!( - chroma_plane_block_codable(4, 16, 1, 1) && chroma_plane_block_codable(16, 4, 1, 1), - "a 1:4 strip's plane block moved at ss (1, 1) -- the else arm is LIVE there \ - and the pair geometry is what decodes it; the assertion must stay inert at \ - 4:2:0" - ); - assert!( - chroma_plane_block_codable(4, 16, 0, 0) && chroma_plane_block_codable(16, 4, 0, 0), - "a 1:4 strip's plane block became invalid at ss (0, 0) -- the assertion sits \ - after the own444 arm and must never fire at 4:4:4; re-derive" - ); -} - /// lane-av1chrtx: [`covering_leaf_tx_type`] resolves a chroma unit's /// `tx_type` from the luma leaf covering the unit's OWN quadrant, and /// reports "no leaf there" as `None` so the caller can fall back to the @@ -1749,13 +543,42 @@ fn cdef_filter_block_under_test( ) { if let Some(t) = archmage::X64V3Token::summon() { return super::cdef_simd::filter_block_avx2( - t, src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir, - pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax, + t, + src, + dst, + stride, + ox, + oy, + bw, + bh, + pri_strength, + sec_strength, + dir, + pri_damping, + sec_damping, + enable_primary, + enable_secondary, + coeff_shift, + smax, ); } super::cdef_filter_block_scalar( - src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir, - pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax, + src, + dst, + stride, + ox, + oy, + bw, + bh, + pri_strength, + sec_strength, + dir, + pri_damping, + sec_damping, + enable_primary, + enable_secondary, + coeff_shift, + smax, ) } @@ -2096,8 +919,8 @@ fn filter_intra_classes_carry_their_own_libaom_default_row() { ); } } -use archmage::SimdToken; use super::*; +use archmage::SimdToken; /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR -- /// `SCAN_4X16[i]` must name the transpose of the position @@ -2415,84 +1238,6 @@ fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() { ); } -/// lane-t900 r27, structural audit for "an OBMC neighbour whose switchable -/// interp filter was never recorded": the `[3, 3]` sentinel is only ever -/// PUBLISHED for a cell an OBMC blend cannot pick up. -/// -/// `Neighbours::record_inter_rect_mi` is the single writer of -/// `above_filter`/`left_filter` (every other recorder routes through it), -/// so the whole domain of published values is its call sites' 7th -/// argument. Two publications are safe: an INTRA cell (`is_inter = false`, -/// skipped by `overlappable_above`/`overlappable_left`'s own `is_inter` -/// gate) and a fixed-filter frame (`resolve_interp_filter` returns the -/// sentinel when `interp_fixed` is `Some`, which `neighbour_filter` -/// answers before ever looking at the symbols). What this scans for is the -/// third case -- an INTER cell stamped with a literal sentinel, which is -/// what the refusal actually fires on. Arguments are tokenised -/// positionally, never `contains()`d. -#[test] -fn every_inter_record_publishes_an_obmc_readable_filter() { - let src = crate::test_source::module_source("decode"); - let mut calls = 0usize; - for (start, _) in src.match_indices("record_inter_rect_mi(") { - // Skip the definition and the wrapper's own forwarding call. - let line_start = src[..start].rfind('\n').map_or(0, |i| i + 1); - let head = &src[line_start..start]; - // The definition, the wrapper's own forwarding call, and this - // test's own mentions of the name (doc comment, scan pattern, - // assert message) are not publication sites. - if head.contains("fn ") || head.contains("///") || head.ends_with('"') { - continue; - } - let mut i = start + "record_inter_rect_mi(".len(); - let (mut depth, mut arg, mut args) = (0i32, String::new(), Vec::new()); - let bytes = src.as_bytes(); - while i < bytes.len() { - let c = bytes[i] as char; - match c { - '(' | '[' => depth += 1, - ')' | ']' if depth == 0 && c == ')' => break, - ')' | ']' => depth -= 1, - ',' if depth == 0 => { - args.push(std::mem::take(&mut arg)); - i += 1; - continue; - } - _ => {} - } - arg.push(c); - i += 1; - } - if !arg.trim().is_empty() { - args.push(arg); - } - assert_eq!( - args.len(), - 8, - "record_inter_rect_mi gained an argument -- re-index this audit: {args:?}" - ); - calls += 1; - let (is_inter, filter) = (args[4].trim(), args[6].trim()); - if filter.starts_with('[') { - assert_eq!( - filter.replace(' ', ""), - "[3,3]", - "a literal filter other than the sentinel is published at call {calls}" - ); - assert_eq!( - is_inter, "false", - "an INTER cell is stamped with the [3, 3] sentinel (call {calls}): an OBMC \ - blend picking it up refuses by name. Publish the block's own resolved \ - switchable symbols instead." - ); - } - } - assert!( - calls >= 6, - "the audit found only {calls} publication sites -- it is broken, not the decoder" - ); -} - /// lane-t900 r27, negative gate for "a reference frame selected with no /// picture at this frame's own ref_frame_idx slot for it": every /// non-`LAST_FRAME` reference resolves through `ref_planes`, and an empty @@ -2797,7 +1542,6 @@ fn a_skipped_block_decodes_to_pure_prediction() { DC_PRED, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]], ); - crate::msac::SymbolDecoder::set_symr_cdf("uv_mode"); enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]); let data = enc.finish(); let decoded = decode_key_frame_tile( @@ -2842,7 +1586,6 @@ fn a_skipped_block_decodes_to_pure_prediction() { #[test] fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { let fctx = &crate::decode::FrameCtx::new(); - reset_skipped_intrabc_chroma_arm_hits(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); @@ -2883,10 +1626,6 @@ fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { true, fctx, ); - assert!( - skipped_intrabc_chroma_arm_hits() >= 1, - "the hand-written tile never reached the skipped-intrabc chroma-reference route" - ); assert!( fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(), "the inherited chroma transform slot must be disarmed when its block's chroma \ @@ -2901,7 +1640,6 @@ fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { #[test] fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { let fctx = &crate::decode::FrameCtx::new(); - reset_skipped_intrabc_chroma_arm_hits(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); @@ -2934,10 +1672,6 @@ fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx( true, fctx, ); - assert!( - skipped_intrabc_chroma_arm_hits() >= 1, - "the hand-written tile never reached the skipped-intrabc rect chroma-reference route" - ); assert!( fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(), "the inherited chroma transform slot must be disarmed when its block's chroma \ @@ -3012,7 +1746,6 @@ fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() { // helpers are `#[cfg(test)]`-private to it). use crate::probe::run_with_stdin; - /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0 /// frame's planes, at ffmpeg's own (coded, block-padded) size. fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { @@ -3124,7 +1857,8 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) { "-of", "csv=p=0", ]) - .arg(&path).output() + .arg(&path) + .output() .expect("ffprobe failed to run"); let _ = std::fs::remove_file(&path); assert!( @@ -3216,7 +1950,6 @@ fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { } let encoded = crate::encode::encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let (coded_w, coded_h) = ffprobe_size(&encoded.stream); - let before = filter_intra_hits(); let ours = decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, @@ -3235,12 +1968,6 @@ fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { fctx, ) .unwrap(); - let fired = filter_intra_hits() - before; - assert!( - fired > 0, - "no block took filter intra -- the gate is blind to the feature" - ); - eprintln!("a_filter_intra_key_frame: {fired} filter-intra blocks"); let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize); assert_eq!(ours.y, ffmpeg_decoded.y, "luma vs ffmpeg"); assert_eq!(ours.u, ffmpeg_decoded.u, "U vs ffmpeg"); diff --git a/crates/ec-av1/src/decode/tx4x8_table_tests.rs b/crates/ec-av1/src/decode/tx4x8_table_tests.rs deleted file mode 100644 index e3492876..00000000 --- a/crates/ec-av1/src/decode/tx4x8_table_tests.rs +++ /dev/null @@ -1,89 +0,0 @@ -use super::*; - -/// Asymmetric gate on the two new scan tables (class -/// `reference-layout-not-spec`): a transposed pair of tables passes any -/// "is a permutation" check, so this pins the pair AGAINST each other -- -/// `SCAN_8X4[k]` must be `SCAN_4X8[k]` reflected across the diagonal, and -/// both must be bijections of `0..32` in our own row-major indexing. -#[test] -fn the_rect_4x8_scans_are_each_other_transposed() { - let mut seen_a = [false; 32]; - let mut seen_b = [false; 32]; - for k in 0..32usize { - let a = SCAN_4X8[k] as usize; - let b = SCAN_8X4[k] as usize; - assert!(!seen_a[a] && !seen_b[b], "scan position {k} repeats"); - seen_a[a] = true; - seen_b[b] = true; - let (row, col) = (a / 4, a % 4); - assert_eq!( - b, - col * 8 + row, - "SCAN_8X4[{k}] is not SCAN_4X8[{k}] transposed" - ); - } - assert!(seen_a.iter().all(|&s| s) && seen_b.iter().all(|&s| s)); -} - -/// `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/`mcol_scan_8x4` -/// (libaom `scan.c`), converted out of their column-major encoding by -/// `(p % h) * w + p / h` -- the head of each, pinned so the rect -/// `V_DCT`/`H_DCT` walk cannot silently transpose. -#[test] -fn the_rect_class1_scans_match_libaom() { - assert_eq!( - class_scan_table_wh(4, 8, TxClass::Vert), - (0..32u16).collect::>() - ); - assert_eq!( - &class_scan_table_wh(4, 8, TxClass::Horiz)[..8], - &[0u16, 4, 8, 12, 16, 20, 24, 28] - ); - assert_eq!( - class_scan_table_wh(8, 4, TxClass::Vert), - (0..32u16).collect::>() - ); - assert_eq!( - &class_scan_table_wh(8, 4, TxClass::Horiz)[..8], - &[0u16, 8, 16, 24, 1, 9, 17, 25] - ); -} - -/// The 32-position `eob_pt` alphabet: six symbols (one more than the -/// 16-position table, one fewer than the 64-position one), strictly -/// increasing, terminated at 32768 with the adaptation counter after it. -#[test] -fn the_32_position_eob_tables_are_well_formed() { - for table in [ - &cdf::EOB_PT_32_LUMA_Q0, - &cdf::EOB_PT_32_LUMA_Q1, - &cdf::EOB_PT_32_LUMA, - &cdf::EOB_PT_32_LUMA_Q3, - &cdf::EOB_PT_32_LUMA_CLASS1_Q0, - &cdf::EOB_PT_32_LUMA_CLASS1_Q1, - &cdf::EOB_PT_32_LUMA_CLASS1, - &cdf::EOB_PT_32_LUMA_CLASS1_Q3, - ] { - assert_eq!(table.len(), 7); - assert_eq!(table[5], 32768); - assert_eq!(table[6], 0); - for w in table[..6].windows(2) { - assert!(w[0] < w[1], "{table:?} is not increasing"); - } - } -} - -/// `Reach::of_rect` must read libaom's own `has_tr_4x8`/`has_tr_8x4` -/// rows, not the 32x16 pair the two existing rect strips use: the two -/// shapes disagree at a position inside the superblock, which is what -/// makes this an asymmetric check rather than a tautology. -#[test] -fn the_sub8_rect_reach_tables_are_shape_specific() { - let fctx = &crate::decode::FrameCtx::new(); - let a = Reach::of_rect(4, 8, 4, 8, 64, 64, fctx); - let b = Reach::of_rect(8, 4, 8, 4, 64, 64, fctx); - assert!( - a.above_right != b.above_right || a.below_left != b.below_left, - "4x8 and 8x4 reach identically at mirrored positions -- one table is unused" - ); -} diff --git a/crates/ec-av1/src/dumpio.rs b/crates/ec-av1/src/dumpio.rs deleted file mode 100644 index 61394b1c..00000000 --- a/crates/ec-av1/src/dumpio.rs +++ /dev/null @@ -1,568 +0,0 @@ -//! Loud dump writing: a dump that cannot hold every byte it claims to hold is -//! a failure, not a diagnostic artefact. -//! -//! lane-av1dumploud: every dump site in this crate wrote through -//! `let _ = f.write_all(..)`. A full filesystem, an `RLIMIT_FSIZE`, or any other -//! `ENOSPC`/`EFBIG` therefore left a SHORT file on disk and nothing said so. -//! Measured consequence, twice in one day: a sentinel-vs-plain hash difference -//! that read as decoder nondeterminism reproduced bit-for-bit as a truncated -//! dump (`lanes/unwritten-dep.report.md`: frames 0..4 complete plus 13 320 192 -//! bytes of frame 5, with `EC_AV1_FINAL_DUMP`'s discarded write error), and an -//! empty dump read as instability. That artefact started a whole defect class, -//! and a silently wrong diagnostic is worse than a loud one, so every dump site -//! goes through [`LoudDump`]: the caller states the expected byte count from the -//! geometry it already has, the writer checks that count twice -- once against -//! the bytes it was handed, once against the file's own length on disk -- and -//! any shortfall aborts the decode with the file, the counts, and the OS error. -//! -//! The success path is byte-identical to the old `write_all` loop: same bytes, -//! same order, same file names. -//! -//! The failure path is a panic, not a returned `Result`: the dump sites sit in -//! the middle of `fn decode_*` functions with no error channel for them, and a -//! dump that failed IS a decode failure (the run's measurement is void). This -//! is a debug instrument -- it only runs when its env var is set -- so the -//! panic cannot affect a normal decode. - -use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -/// One dump file, with the byte count it owes accounted for as it goes. -pub struct LoudDump { - /// Human-readable label for the failure line: the env var, or - /// `VAR.suffix` when the file names something the var alone does not. - site: String, - path: PathBuf, - file: Option, - written: usize, - /// `None` only for a stream whose total length is genuinely unknowable at - /// open time (an append-mode text table). Short-write detection still - /// applies -- `write_all` reports a short write as `Err` -- but the failure - /// line then carries no expected count, because inventing one would be a - /// guess. - expected: Option, -} - -impl LoudDump { - /// Open `path` for `site`, expecting exactly `expected` bytes in total. - /// - /// Failing to CREATE is loud too: a requested dump that does not exist is - /// the same silent hole as one that is short (the reader sees no file, or - /// an empty one), and it is the more common of the two (a missing parent - /// directory, a path a sweep reused as a directory). - pub fn create(site: &str, path: impl AsRef, expected: usize) -> Self { - let path = path.as_ref().to_path_buf(); - let file = File::create(&path).unwrap_or_else(|e| { - abort( - site, - &path, - 0, - Some(expected), - &format!("could not create the dump file: {e}"), - ) - }); - Self { - site: site.to_string(), - path, - file: Some(file), - written: 0, - expected: Some(expected), - } - } - - /// Open `path` for `site` in APPEND mode with no knowable total length -- - /// the CDF-table text dump, whose file spans every frame of a run. Write - /// errors are still fatal; the length check is simply absent (see - /// [`LoudDump::expected`]). - pub fn append_unknown(site: &str, path: impl AsRef) -> Self { - let path = path.as_ref().to_path_buf(); - let file = OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .unwrap_or_else(|e| { - abort( - site, - &path, - 0, - None, - &format!("could not open the dump file: {e}"), - ) - }); - Self { - site: site.to_string(), - path, - file: Some(file), - written: 0, - expected: None, - } - } - - /// Hand `chunk` to the file. Overrunning `expected` is a caller bug (the - /// count and the writer disagree) and aborts just as loudly as a short - /// write, because one of the two is certainly lying. - pub fn write(&mut self, chunk: &[u8]) { - if let Some(exp) = self.expected - && self.written + chunk.len() > exp - { - abort( - &self.site, - &self.path, - self.written, - Some(exp), - &format!( - "the writer was handed {} bytes but only {} remained of the {} it declared", - chunk.len(), - exp - self.written, - exp - ), - ); - } - let r = self.file.as_mut().expect("live dump").write_all(chunk); - if let Err(e) = r { - // MEASURED, do not assume: under `RLIMIT_FSIZE` the kernel stores - // everything up to the cap and THEN returns `EFBIG` (measured: - // a 49 152 B frame under caps of 4 KiB / 10 KiB / 30 KiB left - // 4 096 / 10 240 / 30 720 B on disk, with `write_all` confirming - // none of it). So "bytes written" on this line is the file's real - // length, not the count `write_all` got to acknowledge -- the - // acknowledged count rides along in the reason. - let f = self.file.as_ref().expect("live dump"); - let on_disk = f - .metadata() - .map(|m| m.len() as usize) - .unwrap_or(self.written); - abort( - &self.site, - &self.path, - on_disk, - self.expected, - &format!( - "write failed with {} bytes confirmed in hand: {e}", - self.written - ), - ); - } - self.written += chunk.len(); - } - - /// Close the dump: flush, then check the file's own length on disk. - /// - /// The on-disk check is not redundant with the write loop. `write_all` - /// reports what the FILE ACCEPTED, and the reader's question is what the - /// filesystem ended up holding -- a sparse/short final flush, a quota, or a - /// filesystem-level reservation failure all land here rather than in - /// `write`. - pub fn finish(mut self) { - let Some(mut file) = self.file.take() else { - return; - }; - if let Err(e) = file.flush() { - abort( - &self.site, - &self.path, - self.written, - self.expected, - &format!("flush failed after {} bytes: {e}", self.written), - ); - } - let Some(exp) = self.expected else { - return; - }; - let on_disk = match file.metadata() { - Ok(m) => m.len() as usize, - Err(e) => abort( - &self.site, - &self.path, - self.written, - Some(exp), - &format!("could not stat the finished dump: {e}"), - ), - }; - if on_disk != exp { - abort( - &self.site, - &self.path, - on_disk, - Some(exp), - "the file on disk is not the length the writer declared", - ); - } - } -} - -/// The single failure line every short dump now ends on. `site`, the path, the -/// bytes on disk vs the bytes owed, and the reason. -fn abort(site: &str, path: &Path, got: usize, expected: Option, why: &str) -> ! { - panic!("{}", failure_line(site, path, got, expected, why)); -} - -/// The failure line itself, so the fatal and the reporting shapes cannot -/// drift apart. -fn failure_line(site: &str, path: &Path, got: usize, expected: Option, why: &str) -> String { - let owed = match expected { - Some(e) => format!("{e}"), - None => "an unknown number of".to_string(), - }; - format!( - "ec-av1 dump FAILED [{}] {}: wrote {} of {} bytes: {}", - site, - path.display(), - got, - owed, - why - ) -} - -/// Write `bytes` to `path` as a FATAL pin: [`pin`] IS a wrapper -- three -/// [`LoudDump`] calls (`create`/`write`/`finish`), so it inherits the flush and -/// the flush-then-stat ordering for free. -/// -/// lane-av1pinloud: the test-pin sites in `stream.rs` wrote with -/// `let _ = std::fs::write(..)` and then named the path in the panic that -/// followed ("stream pinned at {}"), so an `ENOSPC`/`EFBIG` left a TRUNCATED -/// stream at exactly the path the reader was told to replay -- the same -/// silent-truncation class as the dump path, one hop later. Success path is -/// byte-identical: same bytes, same path, truncate-then-write. -pub fn pin(site: &str, path: impl AsRef, bytes: &[u8]) { - let mut d = LoudDump::create(site, path, bytes.len()); - d.write(bytes); - d.finish(); -} - -/// [`pin`]'s NON-FATAL twin, for a site that must not die on a failed pin -- a -/// gate whose real failure is the assert that comes after the pin attempt, and -/// whose comment says so. -/// -/// This one RE-IMPLEMENTS the check rather than wrapping [`LoudDump`], whose -/// failure channel is `panic!`: it cannot report instead of dying. So it does -/// `fs::write` + `metadata` itself. Only the failure LINE is shared, via -/// [`failure_line`] -- the ordering (flush-then-stat) and the -/// write-error-handling are not shared with [`LoudDump`], and a reader must not -/// assume they are. -/// -/// Non-fatal, but not silent: a shortfall comes back as the very same failure -/// line [`pin`] would have panicked with, expected-vs-on-disk counts included, -/// for the caller to print as a warning. -#[cfg(test)] // only the self-test below calls it; keeps the non-test build free of dead code -pub fn pin_reporting(site: &str, path: impl AsRef, bytes: &[u8]) -> Result<(), String> { - let path = path.as_ref(); - let expected = bytes.len(); - if let Err(e) = std::fs::write(path, bytes) { - let on_disk = std::fs::metadata(path) - .map(|m| m.len() as usize) - .unwrap_or(0); - return Err(failure_line( - site, - path, - on_disk, - Some(expected), - &format!("could not write the pin: {e}"), - )); - } - let on_disk = match std::fs::metadata(path) { - Ok(m) => m.len() as usize, - Err(e) => { - return Err(failure_line( - site, - path, - expected, - Some(expected), - &format!("could not stat the written pin: {e}"), - )); - } - }; - if on_disk != expected { - return Err(failure_line( - site, - path, - on_disk, - Some(expected), - "the pinned file on disk is not the length of the stream", - )); - } - Ok(()) -} - -/// Write `planes` (already narrowed to their dump's sample width) as ONE dump -/// file, failing loudly on any shortfall. `expected` is the sum of the plane -/// lengths -- the same extents the writer iterates, so a plane that is shorter -/// than its geometry claims cannot hide here. -pub fn write_planes(site: &str, path: impl AsRef, planes: &[&[u8]]) { - let expected: usize = planes.iter().map(|p| p.len()).sum(); - let mut d = LoudDump::create(site, path, expected); - for p in planes { - d.write(p); - } - d.finish(); -} - -#[cfg(test)] -mod tests { - use super::*; - use std::process::Command; - - fn scratch(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!("ec-av1-dumpio-{tag}-{}", std::process::id())); - let _ = std::fs::remove_file(&p); - p - } - - fn caught(f: impl FnOnce() + std::panic::UnwindSafe) -> String { - let prev = std::panic::take_hook(); - std::panic::set_hook(Box::new(|_| {})); - let r = std::panic::catch_unwind(f); - std::panic::set_hook(prev); - let e = r.expect_err("the short dump must abort"); - e.downcast_ref::() - .cloned() - .or_else(|| e.downcast_ref::<&str>().map(|s| (*s).to_string())) - .expect("panic payload is a string") - } - - #[test] - fn success_path_is_byte_identical_to_the_old_write_all_loop() { - let p = scratch("ok"); - let planes: [&[u8]; 3] = [b"abc", b"", b"de"]; - write_planes("T", &p, &planes); - assert_eq!(std::fs::read(&p).unwrap(), b"abcde"); - let _ = std::fs::remove_file(&p); - } - - /// `/dev/full` accepts an `open` for write and returns `ENOSPC` from every - /// write -- the hermetic stand-in for the full filesystem that produced the - /// 13 320 192-byte truncated frame in `lanes/unwritten-dep.report.md`. - #[test] - #[cfg(unix)] - fn full_device_short_write_is_loud() { - let msg = caught(|| write_planes("EC_AV1_FINAL_DUMP", "/dev/full", &[b"abc", b"de"])); - assert!( - msg.starts_with("ec-av1 dump FAILED [EC_AV1_FINAL_DUMP] /dev/full: wrote "), - "{msg}" - ); - assert!(msg.contains("No space left on device"), "{msg}"); - // The counts must be there, or the line does not say what was lost. - assert!(msg.contains(" of 5 bytes"), "{msg}"); - } - - #[test] - fn uncreatable_dump_is_loud() { - let p = std::env::temp_dir().join(format!("ec-av1-nodir-{}/x", std::process::id())); - let msg = caught(|| write_planes("T", &p, &[b"abc"])); - assert!(msg.contains("could not create the dump file"), "{msg}"); - } - - /// A writer that under-declares its own expected length is the same silent - /// hole: the reader gets a file the site believes is complete. - #[test] - fn under_declared_expected_length_is_loud() { - let p = scratch("under"); - let msg = caught(|| { - let mut d = LoudDump::create("T", &p, 2); - d.write(b"abcdef"); - d.finish(); - }); - assert!( - msg.contains("was handed 6 bytes but only 2 remained of the 2 it declared"), - "{msg}" - ); - let _ = std::fs::remove_file(&p); - } - - #[test] - fn append_unknown_takes_no_length_claim() { - let p = scratch("append"); - { - let mut a = LoudDump::append_unknown("T", &p); - a.write(b"x"); - a.finish(); - let mut b = LoudDump::append_unknown("T", &p); - b.write(b"y"); - b.finish(); - } - assert_eq!(std::fs::read(&p).unwrap(), b"xy"); - let msg = caught(|| { - let mut a = LoudDump::append_unknown("T", "/dev/full"); - a.write(b"x"); - a.finish(); - }); - assert!(msg.contains("of an unknown number of bytes"), "{msg}"); - let _ = std::fs::remove_file(&p); - } - /// THE reproduction of the incident this module exists for: a real decode, - /// a real `RLIMIT_FSIZE`, a real truncated `EC_AV1_FINAL_DUMP` file left - /// on disk -- and the run stopping with the bytes-vs-bytes line instead of - /// carrying on to a measurement built on the fragment. - /// - /// `/dev/full` (the unit test above) proves the writer's check works but - /// never leaves a partial file behind, because `create` on it succeeds and - /// nothing is ever stored. `RLIMIT_FSIZE` is the shape - /// `lanes/unwritten-dep.report.md` actually measured: frames 0..4 complete - /// plus 13 320 192 bytes of frame 5. `SIGXFSZ` is IGNORED (`trap "" XFSZ`) - /// so the limit surfaces as `write`'s `EFBIG` -- exactly what a full - /// filesystem's `ENOSPC` does -- instead of killing the child outright. - #[test] - #[cfg(unix)] - fn a_real_decode_under_a_file_size_cap_fails_loudly() { - let dir = std::env::temp_dir().join(format!("ec-av1-dumpio-cap-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let prefix = dir.join("ours"); - // 8 blocks of 512 B = 4096 B: far below one 256x128 4:2:0 8-bit frame - // (49 152 B), far above the file header, so the write lands and fails - // PART way rather than at create. - let out = Command::new("bash") - .args([ - "-c", - "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"", - // $0 for `bash -c` is the test binary itself. - std::env::current_exe().unwrap().to_str().unwrap(), - "--exact", - "dumpio::tests::dumpio_child_decode", - "--nocapture", - ]) - .env("EC_AV1_DUMPLOUD_CHILD", "1") - .env("EC_AV1_FINAL_DUMP", &prefix) - // One thread, so the dump panic lands on the main thread and the - // child's exit status is the decode's own. - .env("EC_AV1_THREADS", "1") - .output() - .expect("spawning the capped child"); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - !out.status.success(), - "the decode must FAIL under a file-size cap, not finish with a truncated dump\n{stderr}" - ); - assert!( - stderr.contains("ec-av1 dump FAILED [EC_AV1_FINAL_DUMP]"), - "the failure line must name the dump site\n{stderr}" - ); - assert!( - stderr.contains("File too large"), - "the failure line must carry the OS error\n{stderr}" - ); - // One 256x128 4:2:0 8-bit frame is 256*128*3/2 = 49 152 B, and the - // failure line's "wrote N of 49152" must name the file's REAL length, - // not the count `write_all` managed to acknowledge: a line that - // under-reports is a line that sends the reader back to the dump to - // measure it themselves. - let frag = std::fs::metadata(format!("{}.f0", prefix.display())) - .unwrap() - .len(); - assert!( - frag < 49152, - "the capped child left a {frag}-byte frame where 49152 B was owed" - ); - assert!( - stderr.contains(&format!("wrote {frag} of 49152 bytes")), - "the failure line's written count must be the file's actual length ({frag})\n{stderr}" - ); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Child half of [`a_real_decode_under_a_file_size_cap_fails_loudly`]. It is - /// not a gate: with no `EC_AV1_DUMPLOUD_CHILD` guard it decodes nothing and - /// asserts nothing, so a plain `cargo test` run is unaffected. - #[test] - fn dumpio_child_decode() { - if std::env::var("EC_AV1_DUMPLOUD_CHILD").is_err() { - return; - } - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("fixtures/420_mixll_256x128_6f.obu"); - let bytes = std::fs::read(&path).expect("the pinned fixture"); - let _ = crate::stream::decode_stream(&bytes); - } - - #[test] - fn pin_success_path_is_byte_identical() { - let p = scratch("pin-ok"); - pin("TEST_PIN", &p, b"stream bytes"); - assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes"); - let _ = std::fs::remove_file(&p); - } - - #[test] - #[cfg(unix)] - fn pin_to_a_full_device_is_loud() { - let msg = caught(|| pin("TEST_PIN", "/dev/full", b"stream bytes")); - assert!( - msg.starts_with("ec-av1 dump FAILED [TEST_PIN] /dev/full: wrote "), - "{msg}" - ); - assert!(msg.contains("No space left on device"), "{msg}"); - assert!(msg.contains(" of 12 bytes"), "{msg}"); - } - - /// The reporting shape: same failure line, returned instead of panicked, - /// so a gate whose real failure is the assert after the pin keeps that - /// assert -- but the reader still learns the pin is short. - #[test] - #[cfg(unix)] - fn pin_reporting_is_loud_but_not_fatal() { - let line = pin_reporting("TEST_PIN", "/dev/full", b"stream bytes").unwrap_err(); - assert!( - line.contains("ec-av1 dump FAILED [TEST_PIN] /dev/full"), - "{line}" - ); - assert!(line.contains(" of 12 bytes"), "{line}"); - let p = scratch("pin-reporting-ok"); - pin_reporting("TEST_PIN", &p, b"stream bytes").expect("a healthy pin reports nothing"); - assert_eq!(std::fs::read(&p).unwrap(), b"stream bytes"); - let _ = std::fs::remove_file(&p); - } - - /// The pin path's own reproduction: a real `RLIMIT_FSIZE` leaves a real - /// truncated stream at the path the panic names. Without the check the - /// reader replays the fragment and blames the decoder. - #[test] - #[cfg(unix)] - fn a_pin_under_a_file_size_cap_fails_loudly() { - let dir = std::env::temp_dir().join(format!("ec-av1-pin-cap-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let out = Command::new("bash") - .args([ - "-c", - "ulimit -f 8; trap \"\" XFSZ; exec \"$0\" \"$@\"", - std::env::current_exe().unwrap().to_str().unwrap(), - "--exact", - "dumpio::tests::pin_child_under_cap", - "--nocapture", - ]) - .env("EC_AV1_PINLOUD_CHILD", &dir) - .output() - .expect("spawning the capped child"); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(!out.status.success(), "a short pin must fail\n{stderr}"); - assert!(stderr.contains("ec-av1 dump FAILED [TEST_PIN]"), "{stderr}"); - assert!(stderr.contains("File too large"), "{stderr}"); - let frag = std::fs::metadata(dir.join("cap-pinned.obu")).unwrap().len(); - assert!( - frag < 32768, - "the capped child left {frag} bytes where 32768 B was owed" - ); - assert!( - stderr.contains(&format!("wrote {frag} of 32768 bytes")), - "{stderr}" - ); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Child half of [`a_pin_under_a_file_size_cap_fails_loudly`]. Not a gate: - /// with no `EC_AV1_PINLOUD_CHILD` set it writes nothing and asserts nothing. - #[test] - fn pin_child_under_cap() { - let Ok(dir) = std::env::var("EC_AV1_PINLOUD_CHILD") else { - return; - }; - // `ulimit -f 8` is 8 KiB, so 4x that is guaranteed to run PAST the cap - // (a write of exactly the cap size succeeds) and land a fragment. - pin( - "TEST_PIN", - Path::new(&dir).join("cap-pinned.obu"), - &[7u8; 32768], - ); - } -} diff --git a/crates/ec-av1/src/encode/coef.rs b/crates/ec-av1/src/encode/coef.rs index f8e2174f..41f90eab 100644 --- a/crates/ec-av1/src/encode/coef.rs +++ b/crates/ec-av1/src/encode/coef.rs @@ -962,7 +962,13 @@ impl Plane<'_> { } /// Puts a snapshot back. - pub(super) fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec, Vec)) { + pub(super) fn restore( + &mut self, + x: usize, + y: usize, + side: usize, + saved: &(Vec, Vec), + ) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] .copy_from_slice(&saved.0[row * side..][..side]); @@ -1080,19 +1086,20 @@ impl Plane<'_> { }) .collect(); if let Some(k) = search.top_k - && k < scored.len() { - let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); - let dc_entry = dc_pos.map(|i| scored.remove(i)); - scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); - scored.truncate(if dc_entry.is_some() { - k.saturating_sub(1) - } else { - k - }); - if let Some(dc_entry) = dc_entry { - scored.push(dc_entry); - } + && k < scored.len() + { + let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); + let dc_entry = dc_pos.map(|i| scored.remove(i)); + scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); + scored.truncate(if dc_entry.is_some() { + k.saturating_sub(1) + } else { + k + }); + if let Some(dc_entry) = dc_entry { + scored.push(dc_entry); } + } let ranking: Vec<(f64, u8)> = if census_on() { scored .iter() @@ -1179,8 +1186,6 @@ impl Plane<'_> { trial = candidate; } } - ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize] - .fetch_add(1, std::sync::atomic::Ordering::Relaxed); } // lane-txset: the block's own transform type, searched on the mode // and angle the trials above settled -- the same ordering the angle @@ -1405,7 +1410,8 @@ pub(super) const HAS_TR_8X16: [u8; 16] = [ /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). pub(super) const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; /// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). -pub(super) const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; +pub(super) const HAS_TR_16X8: [u8; 16] = + [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). pub(super) const HAS_BL_16X8: [u8; 16] = [ 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0, @@ -1785,18 +1791,6 @@ impl Reach { Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) } - /// Marks every [`Reach::of`] made until the returned guard drops as being - /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` / - /// `get_has_bl_table` partition argument). Rectangular sub-blocks are - /// unaffected: libaom's own comment says vertical rectangles keep their - /// non-vert table, which is what [`Reach::of_rect`] already reads. - /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded - /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller - /// can count the sub-block work that partition creates (lane-ab16). - pub(crate) fn in_vert_ab() -> bool { - VERT_AB_PARTITION.with(std::cell::Cell::get) - } - pub(crate) fn vert_ab_partition() -> VertAbGuard { VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) } @@ -1814,7 +1808,12 @@ impl Reach { /// row of a superblock reads into the superblock above, which is decoded; /// the rightmost column would read into the superblock to the right, which /// is not; and everything between is the table's to answer. - pub(super) fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { + pub(super) fn top_right( + side: usize, + x: usize, + y: usize, + fctx: &crate::decode::FrameCtx, + ) -> bool { let (row, col, per_side) = Self::position(side, x, y, fctx); if row == 0 { return true; @@ -1851,7 +1850,12 @@ impl Reach { /// reads into the superblock to its left, which is decoded only as far /// down as its own bottom; the bottom row would read into the superblock /// below, which is not decoded at all; and the table answers the rest. - pub(super) fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { + pub(super) fn bottom_left( + side: usize, + x: usize, + y: usize, + fctx: &crate::decode::FrameCtx, + ) -> bool { let (row, col, per_side) = Self::position(side, x, y, fctx); if col == 0 { return row * side + side < reach_sb_px(fctx); @@ -2032,7 +2036,12 @@ pub(super) fn obmc_min_side() -> usize { /// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the /// search pay it, so the alphabet cancels out of a comparison and only its /// per-value spread decides. -pub(super) fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 { +pub(super) fn motion_mode_bits( + write_w: usize, + write_h: usize, + motion: u8, + warp_alphabet: bool, +) -> f64 { let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else { return 0.0; }; diff --git a/crates/ec-av1/src/encode/frame.rs b/crates/ec-av1/src/encode/frame.rs index db406a05..8d53ac09 100644 --- a/crates/ec-av1/src/encode/frame.rs +++ b/crates/ec-av1/src/encode/frame.rs @@ -52,7 +52,8 @@ pub(super) fn deltaq_res_log2() -> Option { /// sets it holds [`crate::speed::knob_write`], the same exclusive lock the /// speed presets take, because the streams every other test pins move under /// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]). -pub(super) static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); +pub(super) static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); /// Sets [`DELTAQ_OVERRIDE`]; `None` clears it. #[allow(dead_code)] // set only from the `#[cfg(test)]` gates @@ -270,13 +271,8 @@ pub(super) fn dq_summary(offsets: &[i32]) -> String { /// grid that is one flat value, i.e. on no delta_q at all). Process-global /// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which /// keeps the LARGEST count seen since the last read. -pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// [`DELTAQ_LEVELS`], reset to 0. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn take_deltaq_levels() -> usize { - DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed) -} +pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); /// This superblock's search state: the quantizer it is coded at, and the /// lambda that quantizer implies. RD lambda goes as the square of the step, @@ -404,7 +400,12 @@ pub(super) static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::A /// the left/above winners, first-best tie-break. Built once on the frame's /// own thread and read-only afterwards, so it cannot make a tile's bytes /// depend on the thread count. -pub(super) fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> { +pub(super) fn tpl_coarse_pass( + cur: &[u8], + next: &[u8], + width: usize, + height: usize, +) -> Vec<((i32, i32), u32)> { let (cells_x, cells_y) = (width / 16, height / 16); let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 { let (sx, sy) = (bx as i32 + mx, by as i32 + my); @@ -823,10 +824,11 @@ pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f ] { let mv = (from.0 + dy * step, from.1 + dx * step); if let Some(s) = sad(r, bx, by, mv) - && s.0 < best.0 { - best = s; - centre = mv; - } + && s.0 < best.0 + { + best = s; + centre = mv; + } } step /= 2; } @@ -1288,28 +1290,29 @@ pub(crate) fn encode_inter_frame( // the frame codes any delta syntax (`deltaq_res` is `None` with the lever // off, and the census then prices the default `res = 4` grid). if dq_census() - && let Some(f) = &tpl_factors { - let res = deltaq_res.unwrap_or(4); - let off = |libaom: Option| -> Vec { - (0..sb_cols * _sb_rows) - .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx)) - .collect() - }; - let strength = dq_tpl_strength(dq_level); - let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0)))); - let coded = match (deltaq_res.is_some(), strength) { - (false, _) => "none".to_string(), - (true, None) => "ours".to_string(), - (true, Some(k)) => format!("libaom k={k}"), - }; - eprintln!( - "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}", - sb_cols * _sb_rows, - r_frame.unwrap_or(f64::NAN), - dq_summary(&ours), - dq_summary(&aom), - ); - } + && let Some(f) = &tpl_factors + { + let res = deltaq_res.unwrap_or(4); + let off = |libaom: Option| -> Vec { + (0..sb_cols * _sb_rows) + .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx)) + .collect() + }; + let strength = dq_tpl_strength(dq_level); + let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0)))); + let coded = match (deltaq_res.is_some(), strength) { + (false, _) => "none".to_string(), + (true, None) => "ours".to_string(), + (true, Some(k)) => format!("libaom k={k}"), + }; + eprintln!( + "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}", + sb_cols * _sb_rows, + r_frame.unwrap_or(f64::NAN), + dq_summary(&ours), + dq_summary(&aom), + ); + } if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) { header.delta.q_present = true; header.delta.q_res = res.trailing_zeros() as u8; @@ -2332,9 +2335,19 @@ pub(crate) fn encode_inter_frame( // rectangles partition the frame, so the order does not change the bytes). let mut searched_blocks = Vec::new(); for (tile_blocks, pixels) in search_tiles(layout.count(), fctx, search_tile)? { - put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma); + put_rect( + &mut luma.reconstruction, + frame_width, + pixels.luma_rect, + &pixels.luma, + ); for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) { - put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes); + put_rect( + &mut plane.reconstruction, + frame_width / 2, + pixels.chroma_rect, + bytes, + ); } searched_blocks.push(tile_blocks); } diff --git a/crates/ec-av1/src/encode/inter_search.rs b/crates/ec-av1/src/encode/inter_search.rs index e32f83cb..221d12c8 100644 --- a/crates/ec-av1/src/encode/inter_search.rs +++ b/crates/ec-av1/src/encode/inter_search.rs @@ -212,7 +212,8 @@ pub(super) fn arfmode() -> u8 { } /// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it. -pub(super) static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); +pub(super) static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); /// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a /// process constant ([`crate::envflags`]), so an in-process witness needs @@ -279,11 +280,6 @@ thread_local! { const { std::cell::Cell::new(None) }; } -#[cfg(test)] -pub(super) fn set_test_top_k_override(value: Option) { - TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); -} - /// The default: unpruned, thirteen full trials per block, same as before this /// lever. Set from the sweep in the lane report if the quality gate clears it. pub(crate) const PRUNE_TOP_K: Option = None; @@ -317,11 +313,6 @@ thread_local! { const { std::cell::Cell::new(None) }; } -#[cfg(test)] -pub(super) fn set_test_top_k_override_inter(value: Option) { - TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); -} - /// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter` /// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the /// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes @@ -374,21 +365,6 @@ pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); } -#[cfg(test)] -pub(super) fn stage_reset() { - crate::par::set_stage_times(true); - STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); -} - -#[cfg(test)] -pub(super) fn stage_read() -> [std::time::Duration; 4] { - crate::par::set_stage_times(false); - STAGE_NS.with(|c| { - c.each_ref() - .map(|cell| std::time::Duration::from_nanos(cell.get())) - }) -} - /// One mode's coding of one block, before it is committed. #[derive(Clone)] pub(super) struct Trial { @@ -526,7 +502,11 @@ where /// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync` /// by design) and moved into the worker, exactly as the decoder's filter bands /// do it through [`crate::par::scope`]. -pub(super) fn search_tiles(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result> +pub(super) fn search_tiles( + tiles: usize, + fctx: &crate::decode::FrameCtx, + job: F, +) -> Result> where T: Send, F: Fn(usize, &crate::decode::FrameCtx) -> Result + Sync, @@ -600,7 +580,11 @@ pub(super) struct TilePixels { /// The rectangle `[x0, x1) x [y0, y1)` of a plane with `stride`, copied out as /// its rows back to back. -pub(super) fn take_rect(plane: &[u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize)) -> Vec { +pub(super) fn take_rect( + plane: &[u8], + stride: usize, + (x0, y0, x1, y1): (usize, usize, usize, usize), +) -> Vec { let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0)); for y in y0..y1 { out.extend_from_slice(&plane[y * stride + x0..y * stride + x1]); @@ -610,7 +594,12 @@ pub(super) fn take_rect(plane: &[u8], stride: usize, (x0, y0, x1, y1): (usize, u /// The inverse of [`take_rect`]: writes `rows` (as `take_rect` produced them) /// back into the rectangle of `plane`. -pub(super) fn put_rect(plane: &mut [u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize), rows: &[u8]) { +pub(super) fn put_rect( + plane: &mut [u8], + stride: usize, + (x0, y0, x1, y1): (usize, usize, usize, usize), + rows: &[u8], +) { let w = x1 - x0; for (row, y) in (y0..y1).enumerate() { plane[y * stride + x0..y * stride + x1].copy_from_slice(&rows[row * w..(row + 1) * w]); @@ -622,7 +611,10 @@ pub(super) fn put_rect(plane: &mut [u8], stride: usize, (x0, y0, x1, y1): (usize /// tables the frame stores (spec 7.20), which is what /// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops /// below publish. -pub(super) fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo { +pub(super) fn tile_info_of( + layout: &crate::tile::TileLayout, + tile_size_bytes: u32, +) -> ec_av1_syntax::TileInfo { ec_av1_syntax::TileInfo { uniform_spacing: true, cols: layout.cols(), @@ -1380,9 +1372,19 @@ pub(crate) fn encode_key_frame_inner( let searched = search_tiles(layout.count(), fctx, search_tile)?; let mut searched_coded = Vec::with_capacity(searched.len()); for (coded, pixels) in searched { - put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma); + put_rect( + &mut luma.reconstruction, + frame_width, + pixels.luma_rect, + &pixels.luma, + ); for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) { - put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes); + put_rect( + &mut plane.reconstruction, + frame_width / 2, + pixels.chroma_rect, + bytes, + ); } searched_coded.push(coded); } @@ -2104,7 +2106,8 @@ pub(super) fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option /// always), the shape [`set_frame_interp`] has: the witness that has to see /// `mv_hp` symbols coded turns it on through this while holding /// [`crate::speed::knob_write`]. -pub(super) static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); +pub(super) static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); /// Sets [`HP_MV_OVERRIDE`]; `None` clears it. #[allow(dead_code)] // set only from the `#[cfg(test)]` gates @@ -4448,9 +4451,10 @@ pub(super) fn search_inter_block( planes, (reference.width, reference.height), fctx, - ) { - candidates.push((1, pred)); - } + ) + { + candidates.push((1, pred)); + } if warp_alphabet && let Some(pred) = warp_prediction( grid, @@ -4462,9 +4466,10 @@ pub(super) fn search_inter_block( info.ref_frame, planes, fctx, - ) { - candidates.push((2, pred)); - } + ) + { + candidates.push((2, pred)); + } for (motion, pred) in candidates { let luma_trial = luma.code_from_prediction( x, diff --git a/crates/ec-av1/src/encode/mod.rs b/crates/ec-av1/src/encode/mod.rs index 83b96674..76c85b20 100644 --- a/crates/ec-av1/src/encode/mod.rs +++ b/crates/ec-av1/src/encode/mod.rs @@ -821,12 +821,6 @@ fn rectres() -> bool { static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Arms [`FORCE_B128_RECTRES`] for the rest of the process. -#[cfg(test)] -pub(crate) fn force_b128_rectres(on: bool) { - FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed); -} - /// How many rect/AB pieces the search left WITH a residual rather than /// skipped, since the last [`take_b128_rectres_hits`] (class /// `gate-blind-to-feature`). @@ -981,12 +975,6 @@ pub fn take_b128_vert_hits() -> usize { /// RD there prefers one whole block; the gate census is the unforced count. static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); -/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT). -#[cfg(test)] -pub(crate) fn force_b128_rect(which: u8) { - FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed); -} - /// lane-ab128: whether the 128 superblock root offers its four AB shapes -- /// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one /// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128 @@ -1029,12 +1017,6 @@ pub fn take_b128_ab_hits() -> [usize; 4] { /// prefers one whole block). static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); -/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7). -#[cfg(test)] -pub(crate) fn force_b128_ab(which: u8) { - FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed); -} - /// lane-ab128: the three pieces of an AB shape at a 128 root, in the order /// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm /// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B = @@ -1073,20 +1055,6 @@ static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool = /// for content on which the root also wins its own comparison. static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a -/// forced residual block only reaches the writer if its root is taken. -#[cfg(test)] -pub(crate) fn force_b128_residual(on: bool) { - FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed); - force_b128_root(on); -} - -/// Arms [`FORCE_B128_ROOT`] for the rest of the process. -#[cfg(test)] -pub(crate) fn force_b128_root(on: bool) { - FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed); -} - /// How many 128 roots came out cheaper WITH a residual than skipped, since /// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`). static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -1475,12 +1443,6 @@ fn partition_hit(which: usize) { PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } -/// Takes (and clears) the counts. -#[cfg(test)] -pub(crate) fn take_partition_hits() -> [usize; 4] { - [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full /// rate-distortion trials the block search actually runs, by kind, and where /// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by @@ -2002,12 +1964,6 @@ thread_local! { static IBC_SHARE: std::cell::Cell = const { std::cell::Cell::new(0.0) }; } -/// [`IBC_SHARE`] for the last key frame encoded on this thread. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intrabc_source_share() -> f64 { - IBC_SHARE.with(std::cell::Cell::get) -} - thread_local! { /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence /// header offers the per-frame `allow_screen_content_tools` bit at all. @@ -2043,12 +1999,6 @@ thread_local! { const { std::cell::Cell::new(None) }; } -/// The pyramid the last sequence coded on this thread was EFFECTIVELY under. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn last_sequence_pyramid() -> Option { - LAST_SEQ_PYRAMID.with(std::cell::Cell::get) -} - #[cfg(test)] pub(crate) fn force_screen(value: Option) { SCREEN_FORCE.with(|c| c.set(value)); diff --git a/crates/ec-av1/src/encode/more_tests.rs b/crates/ec-av1/src/encode/more_tests.rs index 5304d432..16d0aa84 100644 --- a/crates/ec-av1/src/encode/more_tests.rs +++ b/crates/ec-av1/src/encode/more_tests.rs @@ -1,1260 +1,575 @@ -use super::*; use super::tests::*; +use super::*; - - - /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two - /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`. - /// Five passes over the same `testsrc2` clip - /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders` - /// uses: each shape forced at every root ([`force_b128_ab`]), so every - /// context and every visit order the shape reads is exercised rather than - /// the handful the RD would pick, and then an UNFORCED pass whose - /// per-shape count is REPORTED (it is the number the gate rows are read - /// against). - /// - /// Each pass is sample-exact against the encoder's own reconstruction - /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch - /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED - /// before this lane by construction: `write_sb128_root` could only name - /// NONE / HORZ / VERT / SPLIT, so all four counts were 0. - /// - /// Runs only inside `superblock_size_global_suite`. - pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2-1280x768.y4m"); - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "testsrc2=size=1280x768:rate=24"]) - .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); - let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"]; - let mut unforced = [0usize; 4]; - for force in [4u8, 5, 6, 7, 0] { - force_b128_ab(force); - let label = if force == 0 { - "unforced" - } else { - names[usize::from(force) - 4] - }; - let _ = take_b128_ab_hits(); - let _ = crate::tile::take_sb128_ab_hits(); - let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); - let won = take_b128_ab_hits(); - let coded = crate::tile::take_sb128_ab_hits(); - eprintln!( - "{label}: search won {won:?} AB roots, writer coded {coded:?} \ - (HORZ_A/HORZ_B/VERT_A/VERT_B)" - ); - if force == 0 { - // The unforced counts are REPORTED, not asserted: a zero here - // would be an RD result, not a defect (the four forced passes - // already prove the writer and the reader agree on the shape). - unforced = won; - } else { - let i = usize::from(force) - 4; - assert!( - coded[i] > 0, - "no {label} root was coded with {label} forced" - ); - } - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - for (plane, got, want) in [ - ("luma", &dec.y, &frame.reconstruction.y), - ("U", &dec.u, &frame.reconstruction.u), - ("V", &dec.v, &frame.reconstruction.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - differ, 0, - "{label} frame {i}: {plane} -- {differ} samples differ" - ); - assert_eq!( - got.len(), - want.len(), - "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "{label}: frame count: ours vs ffmpeg" - ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!( - dec.y, frame.reconstruction.y, - "{label} frame {i}: ffmpeg luma" - ); - assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V"); - } - } - force_b128_ab(0); - eprintln!( - "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B", - unforced[0], unforced[1], unforced[2], unforced[3], - ); +#[test] +fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + // 256x128, not the 128x64 this started at: once a leaf could search + // its second reference (lane-av1comp4) the small card's every + // eligible block went to a compound winner, which commits its flat + // transform, and the split below stopped firing on content that + // still splits at every larger size ([[gate-blind-to-feature]] -- + // the guard is right, the fixture had shrunk under it). + let (width, height) = (256usize, 128usize); + let pictures: Vec = (0..5) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let _ = take_inter_tx_split_hits(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + let raw = take_inter_tx_split_hits(); + // Summed over the four block classes the census keys on (leaf/32x32 x + // single/compound): this assert is about the split firing at all. + let split = [ + raw.iter().step_by(2).sum::(), + raw.iter().skip(1).step_by(2).sum::(), + ]; + eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); + // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this + // content splits -- a green round trip in which the split never fires + // would prove only the flat path. + if tx_select() && tx_select_inter() { + assert!(split[1] > 0, "the inter var-tx split never fired"); } - - #[test] - fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - // 256x128, not the 128x64 this started at: once a leaf could search - // its second reference (lane-av1comp4) the small card's every - // eligible block went to a compound winner, which commits its flat - // transform, and the split below stopped firing on content that - // still splits at every larger size ([[gate-blind-to-feature]] -- - // the guard is right, the fixture had shrunk under it). - let (width, height) = (256usize, 128usize); - let pictures: Vec = (0..5) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let _ = take_inter_tx_split_hits(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - let raw = take_inter_tx_split_hits(); - // Summed over the four block classes the census keys on (leaf/32x32 x - // single/compound): this assert is about the split firing at all. - let split = [ - raw.iter().step_by(2).sum::(), - raw.iter().skip(1).step_by(2).sum::(), - ]; - eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); - // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this - // content splits -- a green round trip in which the split never fires - // would prove only the flat path. - if tx_select() && tx_select_inter() { - assert!(split[1] > 0, "the inter var-tx split never fired"); - } - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - let recon = &frame.reconstruction; - for (plane, got, want, stride) in [ - ("luma", &dec.y, &recon.y, width), - ("U", &dec.u, &recon.u, width / 2), - ("V", &dec.v, &recon.v, width / 2), - ] { - assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); - if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { - panic!( - "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ + let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + let recon = &frame.reconstruction; + for (plane, got, want, stride) in [ + ("luma", &dec.y, &recon.y, width), + ("U", &dec.u, &recon.u, width / 2), + ("V", &dec.v, &recon.v, width / 2), + ] { + assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); + if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { + panic!( + "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ reconstruction {} ({} of {} samples differ)", - at % stride, - at / stride, - got[at], - want[at], - got.iter().zip(want).filter(|(a, b)| a != b).count(), - got.len(), - ); - } - } - } - } - - /// The rate term the mode search ranks every decision by has to be the - /// rate the writer then spends. The search prices a block's coefficients - /// through `tile::coeff_bits` -- the writer's own symbol chain, but - /// against the default CDFs a tile starts from and the contexts of a - /// block whose neighbours coded nothing -- while the tile writer codes - /// them against a state that has been adapting all frame (the - /// price-the-narrowing class). This measures that drift: the sum of what - /// the search paid for the coefficients it kept, against the bytes the - /// writer actually emitted for the whole tile (which also carries the - /// partition/mode/skip/mv syntax the sum leaves out, so the writer is - /// expected to be the larger of the two). - #[test] - fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (256usize, 128usize); - let pictures: Vec = (0..5) - .map(|i| panned_test_card(width, height, i * 2)) - .collect(); - let _ = take_predicted_bits(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - let predicted = take_predicted_bits(); - assert_eq!(predicted.len(), encoded.frames.len()); - - eprintln!("frame predicted bits written bits drift"); - // Split by sign: a NEGATIVE drift is the search OVER-pricing (the - // defect this gate exists to catch), a positive one is the written - // side carrying syntax the coefficient sum leaves out -- and since - // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual - // on that side, so the two directions no longer share a bound. - let mut worst_over: f64 = 0.0; - let mut worst_under: f64 = 0.0; - // The census is per CODED frame, so it is zipped in coding order -- - // which is not display order under a pyramid. - let coded: Vec<&Encoded> = encoded - .coding_order - .iter() - .map(|&i| &encoded.frames[i]) - .collect(); - for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() { - let written = frame.tile.len() as f64 * 8.0; - let drift = (written - bits) / written; - worst_over = worst_over.max(-drift); - // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at - // all (150-250 bits of tile, nearly all of it partition/mode/mv - // syntax the coefficient sum never counts), so its ratio measures - // that floor rather than any drift. Frames under 512 written bits - // are left out of the under-price bound for that reason; the - // over-price bound -- the defect direction, where the search pays - // MORE than the writer -- still covers every frame. - if written >= 512.0 { - worst_under = worst_under.max(drift); + at % stride, + at / stride, + got[at], + want[at], + got.iter().zip(want).filter(|(a, b)| a != b).count(), + got.len(), + ); } - eprintln!( - "{i:5} {bits:14.0} {written:12.0} {:+6.2}%", - drift * 100.0 - ); } - // Measured 2026-09-06 on this sequence: -13.5% at the key frame, - // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search - // over-prices every frame but the last (its sum EXCLUDES the - // partition/mode/skip/mv syntax the written side carries, so the true - // coefficient over-price is larger still): the writer's CDFs adapt to - // the content while the search's stay at the defaults. The bound is - // set just above the worst measured point -- a widening drift is the - // thing this gate exists to catch. - assert!( - worst_over <= 0.16, - "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", - worst_over * 100.0 - ); - // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at - // the worst inter frame, where nearly every block now codes an MV - // residual and a reference the coefficient sum never counts. Re-measured - // at +29.6% once the encoder's grid published compound blocks properly - // (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: 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. That is - // the default on a non-screen frame since lane-av1price2 (this - // fixture is one), and it reads +32.6% here. - // lane-av1obmc: every eligible single-reference inter block now also - // carries a `motion_mode` symbol the coefficient sum never counts, - // and an OBMC block carries the more expensive of the two values -- - // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like - // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder - // decisions, so this bound and the byte pins above FAIL BY DESIGN - // under it; the default path (no motion_mode syntax at all) is the - // one they are measured on. - // lane-av1pyrdef: `encode_sequence` codes this fixture under the - // coding pyramid now, so the five frames are a key frame, a hidden - // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two - // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the - // near-empty leaves below it. Both bounds stand where they were. - // lane-av1rejudge: local warp is ON by default now, so every eligible - // single-reference block carries that same `motion_mode` symbol (a - // 3-value alphabet where a warp sample exists) on the DEFAULT path -- - // +34.9% here, one point past the OBMC reading above. The bound moves - // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number. - // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs` - // symbol and one or two magnitude symbols, none of which the - // coefficient sum counts either -- +36.9% here against the same - // fixture's +34.9% with `EC_AV1_CFL=0`. - // ... and a directional block whose `angle_delta_y` is no longer - // always ZERO codes a costlier symbol off the same CDF -- +39.1%. - assert!( - worst_under <= 0.40, - "the writer spent {:.2}% more than the search priced -- more than \ - the mode/mv syntax outside the coefficient sum explains", - worst_under * 100.0 - ); } - - /// The census behind step (1) of the pricer lane: for every transform - /// block the writer really codes, what the search priced those levels at - /// against what the writer spent on them, split by table set and non-zero - /// count. One average hides the interesting part -- the classes the - /// estimate is systematically wrong about (all-zero blocks, the - /// one-coefficient blocks the inter search lives on) -- so the split is - /// printed and only the total is asserted on. - #[test] - fn pricer_error_census_by_block_class() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (256usize, 128usize); - let pictures: Vec = (0..5) - .map(|i| panned_test_card(width, height, i * 2)) - .collect(); - crate::tile::pricer_census_on(); - let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - let rows = crate::tile::take_pricer_census(); - assert!(!rows.is_empty(), "the census saw no transform block"); - - 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 - } - ); +} + +/// The rate term the mode search ranks every decision by has to be the +/// rate the writer then spends. The search prices a block's coefficients +/// through `tile::coeff_bits` -- the writer's own symbol chain, but +/// against the default CDFs a tile starts from and the contexts of a +/// block whose neighbours coded nothing -- while the tile writer codes +/// them against a state that has been adapting all frame (the +/// price-the-narrowing class). This measures that drift: the sum of what +/// the search paid for the coefficients it kept, against the bytes the +/// writer actually emitted for the whole tile (which also carries the +/// partition/mode/skip/mv syntax the sum leaves out, so the writer is +/// expected to be the larger of the two). +#[test] +fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (256usize, 128usize); + let pictures: Vec = (0..5) + .map(|i| panned_test_card(width, height, i * 2)) + .collect(); + let _ = take_predicted_bits(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + let predicted = take_predicted_bits(); + assert_eq!(predicted.len(), encoded.frames.len()); + + eprintln!("frame predicted bits written bits drift"); + // Split by sign: a NEGATIVE drift is the search OVER-pricing (the + // defect this gate exists to catch), a positive one is the written + // side carrying syntax the coefficient sum leaves out -- and since + // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual + // on that side, so the two directions no longer share a bound. + let mut worst_over: f64 = 0.0; + let mut worst_under: f64 = 0.0; + // The census is per CODED frame, so it is zipped in coding order -- + // which is not display order under a pyramid. + let coded: Vec<&Encoded> = encoded + .coding_order + .iter() + .map(|&i| &encoded.frames[i]) + .collect(); + for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() { + let written = frame.tile.len() as f64 * 8.0; + let drift = (written - bits) / written; + worst_over = worst_over.max(-drift); + // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at + // all (150-250 bits of tile, nearly all of it partition/mode/mv + // syntax the coefficient sum never counts), so its ratio measures + // that floor rather than any drift. Frames under 512 written bits + // are left out of the under-price bound for that reason; the + // over-price bound -- the defect direction, where the search pays + // MORE than the writer -- still covers every frame. + if written >= 512.0 { + worst_under = worst_under.max(drift); } - println!( - "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", - rows.values().map(|r| r.0).sum::(), - (priced_all - written_all) / written_all * 100.0 + eprintln!( + "{i:5} {bits:14.0} {written:12.0} {:+6.2}%", + drift * 100.0 ); - assert!(written_all > 0.0); } - - /// 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 -- - /// a search that never picks an inter mode would still pass a rate gate - /// on a picture with no motion in it (the class this repo calls - /// gate-blind-to-feature), so the share is printed even though it is not - /// asserted on beyond being reachable at all. - #[test] - fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (256usize, 128usize); - let pictures: Vec = (0..5) - .map(|i| panned_test_card(width, height, i * 2)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - - let key_bytes = encoded.frames[0].stream.len(); - eprintln!("frame bytes inter share"); - for (i, frame) in encoded.frames.iter().enumerate() { - eprintln!( - "{i:5} {:5} {:11.2}", - frame.stream.len(), - frame.inter_block_share - ); - } - assert!( - encoded.frames[1..] - .iter() - .any(|f| f.stream.len() < key_bytes), - "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" - ); - assert!( - encoded.frames[1..] - .iter() - .any(|f| f.inter_block_share > 0.0), - "no inter frame coded a single inter block -- the search never fired" + // Measured 2026-09-06 on this sequence: -13.5% at the key frame, + // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search + // over-prices every frame but the last (its sum EXCLUDES the + // partition/mode/skip/mv syntax the written side carries, so the true + // coefficient over-price is larger still): the writer's CDFs adapt to + // the content while the search's stay at the defaults. The bound is + // set just above the worst measured point -- a widening drift is the + // thing this gate exists to catch. + assert!( + worst_over <= 0.16, + "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", + worst_over * 100.0 + ); + // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at + // the worst inter frame, where nearly every block now codes an MV + // residual and a reference the coefficient sum never counts. Re-measured + // at +29.6% once the encoder's grid published compound blocks properly + // (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: 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. That is + // the default on a non-screen frame since lane-av1price2 (this + // fixture is one), and it reads +32.6% here. + // lane-av1obmc: every eligible single-reference inter block now also + // carries a `motion_mode` symbol the coefficient sum never counts, + // and an OBMC block carries the more expensive of the two values -- + // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like + // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder + // decisions, so this bound and the byte pins above FAIL BY DESIGN + // under it; the default path (no motion_mode syntax at all) is the + // one they are measured on. + // lane-av1pyrdef: `encode_sequence` codes this fixture under the + // coding pyramid now, so the five frames are a key frame, a hidden + // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two + // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the + // near-empty leaves below it. Both bounds stand where they were. + // lane-av1rejudge: local warp is ON by default now, so every eligible + // single-reference block carries that same `motion_mode` symbol (a + // 3-value alphabet where a warp sample exists) on the DEFAULT path -- + // +34.9% here, one point past the OBMC reading above. The bound moves + // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number. + // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs` + // symbol and one or two magnitude symbols, none of which the + // coefficient sum counts either -- +36.9% here against the same + // fixture's +34.9% with `EC_AV1_CFL=0`. + // ... and a directional block whose `angle_delta_y` is no longer + // always ZERO codes a costlier symbol off the same CDF -- +39.1%. + assert!( + worst_under <= 0.40, + "the writer spent {:.2}% more than the search priced -- more than \ + the mode/mv syntax outside the coefficient sum explains", + worst_under * 100.0 + ); +} + +/// 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 -- +/// a search that never picks an inter mode would still pass a rate gate +/// on a picture with no motion in it (the class this repo calls +/// gate-blind-to-feature), so the share is printed even though it is not +/// asserted on beyond being reachable at all. +#[test] +fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (256usize, 128usize); + let pictures: Vec = (0..5) + .map(|i| panned_test_card(width, height, i * 2)) + .collect(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + + let key_bytes = encoded.frames[0].stream.len(); + eprintln!("frame bytes inter share"); + for (i, frame) in encoded.frames.iter().enumerate() { + eprintln!( + "{i:5} {:5} {:11.2}", + frame.stream.len(), + frame.inter_block_share ); } - - /// `frames` consecutive pictures out of a real clip, scaled to a whole - /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`] - /// to an arbitrary count for the fixture regression gate below. - pub(super) fn clip_frames( - clip: &str, - skip: &str, - width: usize, - height: usize, - frames: usize, - ) -> Vec { - clip_frames_vf( - clip, - skip, - &format!("scale={width}:{height}"), - width, - height, - frames, - ) - } - - /// [`clip_frames`] with the filter chain spelled out, so a caller can ask - /// for a native-resolution CROP instead of a downscale (the downscale is - /// what destroys a screen capture's exact repeats -- class - /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces. - pub(super) fn clip_frames_vf( - clip: &str, - skip: &str, - vf: &str, - width: usize, - height: usize, - frames: usize, - ) -> Vec { - // ONE definition of the gate's loader recipe, shared with - // `examples/enc_probe` so the instrument cannot arm a different source - // than the gate it reports on (class `instrument disagrees with the - // gate`; lane-probe). - crate::probe::source(clip, skip, vf, width, height, frames) - } - - // ----------------------------------------------------------------------- - // The encoder's standing BD-rate baseline against libaom and rav1e. - // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an - // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder - // agreeing with our encoder proves nothing about the bitstream. - // ----------------------------------------------------------------------- - - /// All-plane PSNR of a decoded picture against its source, on the same - /// 8-bit scale [`psnr`] uses. - pub(super) fn psnr_all(decoded: &Picture, source: &Picture) -> f64 { - let cat = |p: &Picture| { - let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len()); - v.extend_from_slice(&p.y); - v.extend_from_slice(&p.u); - v.extend_from_slice(&p.v); - v - }; - psnr(&cat(decoded), &cat(source)) - } - - /// The pictures back as the planar 8-bit bytes an encoder reads. - pub(super) fn raw_yuv420p(source: &[Picture]) -> Vec { - let mut raw = Vec::new(); - for p in source { - for plane in [&p.y, &p.u, &p.v] { - raw.extend(plane.iter().map(|&s| s as u8)); - } - } - raw - } - - /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven - /// through ffmpeg: one point per entry of `points`, each a quality flag - /// set. Returns the ladder ordered by fidelity and the total encode wall - /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`], - /// so both curves are measured by the same decoder. - pub(super) fn external_ladder( - source: &[Picture], - width: usize, - height: usize, - encoder: &str, - points: &[Vec], - ) -> (Vec<(f64, f64)>, f64) { - // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. - let dir = std::env::temp_dir(); - let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id())); - std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source"); - let mut ladder = Vec::new(); - let mut wall = 0.0; - for (i, params) in points.iter().enumerate() { - let obu = dir.join(format!( - "ec-av1-bd-{}-{encoder}-{i}.obu", - std::process::id() - )); - let start = std::time::Instant::now(); - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) - .arg(&raw_path) - .args(["-an", "-threads", "1"]) - .args(["-g", &source.len().to_string(), "-c:v", encoder]) - .args(params) - .args(["-f", "obu"]) - .arg(&obu).output() - .expect("ffmpeg failed to run"); - wall += start.elapsed().as_secs_f64(); - assert!( - out.status.success(), - "{encoder} {params:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stream = std::fs::read(&obu).expect("reference stream"); - let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); - // lane-dkey: every reference point must also decode through OUR - // decoder, sample-exact against ffmpeg's decode of the same bytes. - // A BD table computed off streams we cannot read is a table about - // an encoder we cannot check; this is the assertion that would - // have caught the `force_integer_mv` defect (its stream decoded to - // 25 dB garbage while this gate stayed green) and the crf-5 key - // frame desync. A failure names the encoder, the point's flags and - // the first differing frame/plane/sample. - // lane-dpm1: a failing reference point is COLLECTED, not panicked - // on, so one run still prints the whole BD table and names every - // bad point instead of stopping at the first. The collection is - // asserted empty by [`assert_ladder_decodes`] at the end of each - // gate. - match crate::stream::decode_stream(&stream) { - Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!( - "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}", - ours.len(), - decoded.len(), - )), - Ok(ours) => { - for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() { - if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) { - note_ladder_failure(format!( - "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \ - decoder decoded {got}, ffmpeg {want}" - )); - break; - } - } - } - Err(e) => note_ladder_failure(format!( - "{encoder} {params:?}: our decoder refused the stream ({e})" - )), - } - let mean: f64 = decoded - .iter() - .zip(source) - .map(|(d, s)| psnr_all(d, s)) - .sum::() - / source.len() as f64; - ladder.push((mean, (stream.len() as f64).log10())); - let _ = std::fs::remove_file(&obu); + assert!( + encoded.frames[1..] + .iter() + .any(|f| f.stream.len() < key_bytes), + "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" + ); + assert!( + encoded.frames[1..] + .iter() + .any(|f| f.inter_block_share > 0.0), + "no inter frame coded a single inter block -- the search never fired" + ); +} + +/// `frames` consecutive pictures out of a real clip, scaled to a whole +/// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`] +/// to an arbitrary count for the fixture regression gate below. +pub(super) fn clip_frames( + clip: &str, + skip: &str, + width: usize, + height: usize, + frames: usize, +) -> Vec { + clip_frames_vf( + clip, + skip, + &format!("scale={width}:{height}"), + width, + height, + frames, + ) +} + +/// [`clip_frames`] with the filter chain spelled out, so a caller can ask +/// for a native-resolution CROP instead of a downscale (the downscale is +/// what destroys a screen capture's exact repeats -- class +/// `gate-recipe-confound`). `width`/`height` must be what `vf` produces. +pub(super) fn clip_frames_vf( + clip: &str, + skip: &str, + vf: &str, + width: usize, + height: usize, + frames: usize, +) -> Vec { + // ONE definition of the gate's loader recipe, shared with + // `examples/enc_probe` so the instrument cannot arm a different source + // than the gate it reports on (class `instrument disagrees with the + // gate`; lane-probe). + crate::probe::source(clip, skip, vf, width, height, frames) +} + +// ----------------------------------------------------------------------- +// The encoder's standing BD-rate baseline against libaom and rav1e. +// Every PSNR below is measured on FFMPEG-DECODED pixels, never on an +// encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder +// agreeing with our encoder proves nothing about the bitstream. +// ----------------------------------------------------------------------- + +/// First differing sample between two pictures, as +/// `(plane, index, left, right)` -- so a gate failure names the plane and +/// the sample instead of just "differs". A length difference counts as a +/// mismatch of that plane at the first index past the shorter one. +pub(super) fn first_plane_mismatch( + a: &Picture, + b: &Picture, +) -> Option<(&'static str, usize, i64, i64)> { + for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { + if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { + return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); } - let _ = std::fs::remove_file(&raw_path); - ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); - (ladder, wall) - } - - /// Every reference ladder point that did not decode sample-exactly - /// through our own decoder, collected across a whole gate run so the BD - /// table still prints and EVERY bad point is named - /// (`encoder params frame plane sample`) instead of only the first. - static LADDER_FAILURES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - - pub(super) fn note_ladder_failure(msg: String) { - eprintln!("LADDER DECODE FAILURE: {msg}"); - LADDER_FAILURES.lock().expect("ladder failures").push(msg); - } - - /// Fail the gate at its END on everything [`external_ladder`] collected. - pub(super) fn assert_ladder_decodes() { - let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures")); - assert!( - failures.is_empty(), - "{} reference ladder point(s) did not decode exactly through our decoder:\n{}", - failures.len(), - failures.join("\n"), - ); - } - - /// First differing sample between two pictures, as - /// `(plane, index, left, right)` -- so a gate failure names the plane and - /// the sample instead of just "differs". A length difference counts as a - /// mismatch of that plane at the first index past the shorter one. - pub(super) fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> { - for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { - if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { - return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); - } - if l.len() != r.len() { - return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); - } + if l.len() != r.len() { + return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); } - None } - - /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR - /// comes from ffmpeg's decode of our own stream, and at EVERY point the - /// stream is decoded twice -- by ffmpeg and by our own - /// [`crate::stream::decode_stream`] -- and all three pictures (encoder - /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact - /// in Y, U and V over every shown frame in display order. That is itself - /// a gate: it proves the bitstream says what the encoder thinks, in the - /// only two decoders that read it. - pub(super) fn our_ladder( - name: &str, - source: &[Picture], - width: usize, - height: usize, - fctx: &crate::decode::FrameCtx, - ) -> (Vec<(f64, f64)>, f64) { - let mut ladder = Vec::new(); - let mut wall = 0.0; - for &q in &[150u8, 120, 90, 60] { - let start = std::time::Instant::now(); - // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so - // the gate has to be able to re-sweep it. 0.5 is the shipped one - // (`crate::encoder::DEADZONE`). - let deadzone = std::env::var("EC_AV1_DEADZONE") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0.5); - let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap(); - wall += start.elapsed().as_secs_f64(); - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len()); - let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!( - ours.len(), - source.len(), - "{name} q={q}: our decoder's display-order frame count" - ); - for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { - if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { - panic!( - "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ - {got}, the encoder reconstructed {want}" - ); - } - } - for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() { - if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) { - panic!( - "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \ - {got}, the encoder reconstructed {want}" - ); - } - } - let per_frame: Vec = decoded - .iter() - .zip(source) - .map(|(d, s)| psnr_all(d, s)) - .collect(); - // lane-txrd: does a tool's loss start at the FIRST inter frame - // (a local mispricing) or grow down the GOP (propagation into - // the reference chain)? One line per q point answers it. - if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { - let row: Vec = per_frame.iter().map(|p| format!("{p:.2}")).collect(); - eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" ")); - // lane-txrd: per PLANE, because an all-plane mean hides a - // collapse in one of them (class `metric blind to a plane`). - let plane = |pick: fn(&Picture) -> &Vec| -> String { - let v: Vec = decoded - .iter() - .zip(source) - .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s)))) - .collect(); - v.join(" ") - }; - eprintln!("{name}: q={q} Y {}", plane(|p| &p.y)); - eprintln!("{name}: q={q} U {}", plane(|p| &p.u)); - eprintln!("{name}: q={q} V {}", plane(|p| &p.v)); - } - let mean: f64 = per_frame.iter().sum::() / source.len() as f64; - ladder.push((mean, (encoded.stream.len() as f64).log10())); - } - // What this clip asked for and what the content gate left it coding - // under: a screen clip requests a pyramid and codes flat, and that - // difference is what keeps its row identical to the flat baseline - // (class `gate-blind-to-feature`). - eprintln!( - "{name}: sequence, pyramid requested {:?} effective {:?}", - crate::encoder::Pyramid::from_env(), - last_sequence_pyramid(), - ); - ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); - (ladder, wall) + None +} + +/// Byte-exactness gate for encoder work that is meant to change only +/// how long the encoder takes. +/// +/// The BD gate above measures quality, which a speed lane can move by a +/// hair without failing anything; this pins the streams themselves. +/// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 +/// `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. 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. Re-pinned again on +/// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the +/// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which +/// is the same kind of decision change. Re-pinned on lane-av1lambda: +/// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the +/// search moved with it. Re-pinned on lane-av1rejudge: local warp is on +/// by default ([`warp_on`], a sequence/frame header bit and a new +/// motion_mode symbol on eligible blocks) and +/// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl: +/// every inter frame's superblocks now code at their own lambda +/// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved. +/// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 +/// and the two var-tx depth searches ([`tx32_depth_search`], +/// [`compound_var_tx`]) are on by default, all three re-judged on the +/// native gate's real film rows. +/// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so +/// every block whose chroma takes it codes a different mode symbol, two +/// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0` +/// restores the previous streams. Re-pinned again in the same lane once +/// directional luma winners searched their `angle_delta_y` +/// (`EC_AV1_ANGLE=0` restores that half). +#[test] +fn the_encoders_own_streams_are_byte_identical_to_their_pins() { + // These are DEFAULT-PRESET pins: a speed preset switches search levers + // off, so it legitimately moves every byte. Encode at speed 0 whatever + // `EC_AV1_SPEED` says (write guard: the preset is process-global). + let _knobs = crate::speed::knob_write(); + let was = crate::speed::speed(); + crate::speed::set_speed(0); + // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape, + // so a tree with no root `fixtures/` reported this gate green having + // compared nothing at all. + let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4"); + let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4); + // FNV-1a over the stream: a witness that every coded bit is where it + // was, which a byte count alone is not. + let fnv = |b: &[u8]| { + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { + (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) + }) + }; + // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen) + // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP + // of 4, its leaves at q+8 and a `show_existing_frame` header per + // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over + // four frames; four pictures is one short mini-GOP, which is the + // shape that pays least (the ARF's own quality has no later group to + // carry it), so this is not the BD gate's number. + // Re-taken again on lane-av1cfl: the chroma search offers + // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`, + // so every block taking either codes different syntax and different + // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60. + // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half. + // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16 + // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]), + // so these four pictures code as one truncated group -- a hidden + // ALTREF at `q-24` and three leaves at `q+16` -- instead of one + // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and + // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these. + // Re-taken on lane-fintra: the sequence header sets + // `enable_filter_intra`, so every DC_PRED intra block of at most + // 32x32 without a luma palette carries a `use_filter_intra` flag and + // the blocks that take one code a filter-intra mode, a different + // prediction and different coefficients -- 7321 -> 7373 at q=150 and + // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these. + // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge + // (default pyramid `8:-32:16`, one truncated group of 8 with its + // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64 + // root can code a REAL residual now (one TX_64X64 luma transform and + // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548; + // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid. + // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at + // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and + // one of these four pictures is the key -- 8590 -> 9778 at q=150 and + // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these. + // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above + // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778 + // -> 9835 at q=150 and 35450 -> 35798 at q=60. + // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these. + // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0` + // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of + // these four pictures -- offers every superblock a 64x64 intra root + // now. `EC_AV1_I64=0` restores 8557 / 33345. + // Re-taken on lane-pricer: the inter RD search prices a single + // reference through the tree and the neighbour contexts the writer + // really codes it with, so every inter picture's reference decisions + // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60. + // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts + // for `skip`/`is_inter` and for the whole compound reference tree, so + // every inter block's cost -- and with it the skip and reference + // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087 + // at q=60. Re-taken on lane-ctx2: a single-reference candidate now + // pays the `comp_mode = 0` symbol the writer codes ahead of it, so + // single and compound are priced against the same syntax -- 8311 -> + // 8325 bytes at q=150 and 33087 -> 33014 at q=60. + // Re-taken on lane-newmv: the motion search charges its own rate term + // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`]) + // and each subpel stage re-runs from its own winner + // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector + // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150 + // and 33014 -> 33090 at q=60. + // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex` + // from libaom's objective tpl mapping, so every inter picture's + // quantizer grid -- and every decision priced against it -- moved + // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more + // at the merge of both lanes. + // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its + // per-superblock `delta_qindex` at 1.5x the preset's strength + // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer + // grids -- and every decision priced against them -- moved: + // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60. + // Re-taken on lane-arfpred: the top ARF is coded from a temporally + // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's + // pixels -- and the leaves that predict from them -- moved: + // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60. + // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so + // the shipped stream did not move. + // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every + // picture is coded in 128x128 superblocks now, the inter ones + // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at + // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053. + // Re-taken at the merge of lane-b128m onto main (128 superblocks on + // by default, on top of the ARF temporal filter). + // Re-taken on lane-b128r: the 128 root now offers the COMPOUND + // candidates the 64 root already did ([`b128_compound`]), so every + // inter frame that carries `reference_select` codes different blocks + // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60. + // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly. + // Re-taken on lane-arftf: that filter's strength swept on the deciding + // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered + // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and + // 33017 at q=60 (the same LENGTH, different bytes). + // Re-taken at the merge of lane-arftf (ARF filter strength 2) and + // lane-rlclamp onto the 128 compound default. + // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ + // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks, + // so every inter frame whose RD takes one codes a different partition + // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that + // quantizer the rect cut never wins its own comparison on this clip. + // `EC_AV1_B128HV=0` restores 8290 exactly. + let pins: [(u8, usize, u64); 2] = [ + (150, 23666, 11535713837929557386), + (60, 102035, 3886390906684528357), + ]; + let coded: Vec<(u8, usize, u64)> = pins + .iter() + .map(|&(q, _, _)| { + let e = encode_sequence(&source, q, 0.5).unwrap(); + (q, e.stream.len(), fnv(&e.stream)) + }) + .collect(); + crate::speed::set_speed(was); + for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) { + assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved"); } - - /// [`our_ladder`] through the streaming facade — the surface the editor's - /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`] - /// each stream is also reordered (hidden `ALTREF` first, - /// `show_existing_frame` last per group) and each level is coded at its - /// own quantizer offset; without one it is the flat ladder, which - /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` - /// pins byte-identical to [`our_ladder`]'s, so this arm must print the - /// same BD numbers. Returns the ladder, the wall, per pyramid level over - /// the whole ladder how many frames and how many bytes it spent, and the - /// pyramid the streams were EFFECTIVELY coded under — the content gate in - /// `Av1Encoder::encode_frames` drops a screen-content clip back to the - /// flat path, so a requested pyramid can come back `None` here. - pub(super) fn our_ladder_facade( - name: &str, - source: &[Picture], - width: usize, - height: usize, - pyramid: Option, - ) -> ( - Vec<(f64, f64)>, - f64, - [usize; 4], - [usize; 4], - Option, - ) { - use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; - let slot = |l: Level| match l { - Level::Key => 0, - Level::Arf => 1, - Level::Leaf => 2, - Level::ShowExisting => 3, - }; - let mut ladder = Vec::new(); - let mut wall = 0.0; - let mut effective = None; - let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); - for &q in &[150u8, 120, 90, 60] { - let config = EncoderConfig { - width, - height, - base_q_idx: q, - gop: source.len(), - colour: Colour::Unspecified, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let start = std::time::Instant::now(); - let mut enc = match pyramid { - None => Av1Encoder::new(config).unwrap(), - Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(), - }; - let mut packets = Vec::new(); - for picture in source { - packets.extend(enc.encode_frames(picture).unwrap()); - } - packets.extend(enc.flush().unwrap()); - wall += start.elapsed().as_secs_f64(); - effective = enc.pyramid(); - let mut stream = Vec::new(); - for p in &packets { - counts[slot(p.level)] += 1; - bytes[slot(p.level)] += p.data.len(); - stream.extend_from_slice(&p.data); - } - // [[gate-blind-to-hidden-frames]]: a reordered stream is only - // correct if the DISPLAY-order output still has one frame per - // source picture, in the right order -- checked against our own - // decoder as well as ffmpeg's, both below. - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); +} + +/// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to +/// hardwire the REGULAR kernel, so the encoder could not have coded a +/// SMOOTH or SHARP frame even if the header had said so -- the search, +/// the trials, the recon and the frame header now all read +/// `FrameCtx::interp_filter`. Each of the three kernels codes its own +/// distinct stream (a filter that never reached the prediction would code +/// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg +/// reconstructs every frame of each of them exactly, which is what proves +/// the header and the prediction agree. +#[test] +fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (256usize, 128usize); + // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so + // all three kernels would code the same bytes and the test would pass + // on a wiring that does nothing (class `fixture proves the symbol, not + // the signal`). `panned_test_card` shifts by whole pixels, so the + // search finds the sub-pel positions off the reconstruction instead: + // three frames of a slow diagonal pan. + let pictures: Vec = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let mut streams = Vec::new(); + for filter in [ + ec_av1_syntax::InterpolationFilter::Eighttap, + ec_av1_syntax::InterpolationFilter::EighttapSmooth, + ec_av1_syntax::InterpolationFilter::EighttapSharp, + ] { + set_frame_interp(Some(filter)); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) + .unwrap_or_else(|e| panic!("{filter:?}: {e}")); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); + assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { assert_eq!( - ours.len(), - source.len(), - "{name} q={q}: our display-order count" - ); - let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); - for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { - if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) { - panic!( - "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \ - decoded {got}, our decoder decoded {want}" - ); - } - } - let mean: f64 = decoded - .iter() - .zip(source) - .map(|(d, s)| psnr_all(d, s)) - .sum::() - / source.len() as f64; - ladder.push((mean, (stream.len() as f64).log10())); - } - ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); - (ladder, wall, counts, bytes, effective) - } - - /// Byte-exactness gate for encoder work that is meant to change only - /// how long the encoder takes. - /// - /// The BD gate above measures quality, which a speed lane can move by a - /// hair without failing anything; this pins the streams themselves. - /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 - /// `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. 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. Re-pinned again on - /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the - /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which - /// is the same kind of decision change. Re-pinned on lane-av1lambda: - /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the - /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on - /// by default ([`warp_on`], a sequence/frame header bit and a new - /// motion_mode symbol on eligible blocks) and - /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl: - /// every inter frame's superblocks now code at their own lambda - /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved. - /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 - /// and the two var-tx depth searches ([`tx32_depth_search`], - /// [`compound_var_tx`]) are on by default, all three re-judged on the - /// native gate's real film rows. - /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so - /// every block whose chroma takes it codes a different mode symbol, two - /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0` - /// restores the previous streams. Re-pinned again in the same lane once - /// directional luma winners searched their `angle_delta_y` - /// (`EC_AV1_ANGLE=0` restores that half). - #[test] - fn the_encoders_own_streams_are_byte_identical_to_their_pins() { - // These are DEFAULT-PRESET pins: a speed preset switches search levers - // off, so it legitimately moves every byte. Encode at speed 0 whatever - // `EC_AV1_SPEED` says (write guard: the preset is process-global). - let _knobs = crate::speed::knob_write(); - let was = crate::speed::speed(); - crate::speed::set_speed(0); - // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape, - // so a tree with no root `fixtures/` reported this gate green having - // compared nothing at all. - let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4"); - let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4); - // FNV-1a over the stream: a witness that every coded bit is where it - // was, which a byte count alone is not. - let fnv = |b: &[u8]| { - b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { - (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) - }) - }; - // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen) - // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP - // of 4, its leaves at q+8 and a `show_existing_frame` header per - // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over - // four frames; four pictures is one short mini-GOP, which is the - // shape that pays least (the ARF's own quality has no later group to - // carry it), so this is not the BD gate's number. - // Re-taken again on lane-av1cfl: the chroma search offers - // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`, - // so every block taking either codes different syntax and different - // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60. - // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half. - // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16 - // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]), - // so these four pictures code as one truncated group -- a hidden - // ALTREF at `q-24` and three leaves at `q+16` -- instead of one - // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and - // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these. - // Re-taken on lane-fintra: the sequence header sets - // `enable_filter_intra`, so every DC_PRED intra block of at most - // 32x32 without a luma palette carries a `use_filter_intra` flag and - // the blocks that take one code a filter-intra mode, a different - // prediction and different coefficients -- 7321 -> 7373 at q=150 and - // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these. - // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge - // (default pyramid `8:-32:16`, one truncated group of 8 with its - // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64 - // root can code a REAL residual now (one TX_64X64 luma transform and - // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548; - // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid. - // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at - // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and - // one of these four pictures is the key -- 8590 -> 9778 at q=150 and - // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these. - // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above - // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778 - // -> 9835 at q=150 and 35450 -> 35798 at q=60. - // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these. - // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0` - // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of - // these four pictures -- offers every superblock a 64x64 intra root - // now. `EC_AV1_I64=0` restores 8557 / 33345. - // Re-taken on lane-pricer: the inter RD search prices a single - // reference through the tree and the neighbour contexts the writer - // really codes it with, so every inter picture's reference decisions - // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60. - // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts - // for `skip`/`is_inter` and for the whole compound reference tree, so - // every inter block's cost -- and with it the skip and reference - // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087 - // at q=60. Re-taken on lane-ctx2: a single-reference candidate now - // pays the `comp_mode = 0` symbol the writer codes ahead of it, so - // single and compound are priced against the same syntax -- 8311 -> - // 8325 bytes at q=150 and 33087 -> 33014 at q=60. - // Re-taken on lane-newmv: the motion search charges its own rate term - // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`]) - // and each subpel stage re-runs from its own winner - // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector - // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150 - // and 33014 -> 33090 at q=60. - // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex` - // from libaom's objective tpl mapping, so every inter picture's - // quantizer grid -- and every decision priced against it -- moved - // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more - // at the merge of both lanes. - // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its - // per-superblock `delta_qindex` at 1.5x the preset's strength - // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer - // grids -- and every decision priced against them -- moved: - // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60. - // Re-taken on lane-arfpred: the top ARF is coded from a temporally - // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's - // pixels -- and the leaves that predict from them -- moved: - // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60. - // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so - // the shipped stream did not move. - // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every - // picture is coded in 128x128 superblocks now, the inter ones - // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at - // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053. - // Re-taken at the merge of lane-b128m onto main (128 superblocks on - // by default, on top of the ARF temporal filter). - // Re-taken on lane-b128r: the 128 root now offers the COMPOUND - // candidates the 64 root already did ([`b128_compound`]), so every - // inter frame that carries `reference_select` codes different blocks - // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60. - // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly. - // Re-taken on lane-arftf: that filter's strength swept on the deciding - // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered - // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and - // 33017 at q=60 (the same LENGTH, different bytes). - // Re-taken at the merge of lane-arftf (ARF filter strength 2) and - // lane-rlclamp onto the 128 compound default. - // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ - // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks, - // so every inter frame whose RD takes one codes a different partition - // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that - // quantizer the rect cut never wins its own comparison on this clip. - // `EC_AV1_B128HV=0` restores 8290 exactly. - let pins: [(u8, usize, u64); 2] = [ - (150, 23666, 11535713837929557386), - (60, 102035, 3886390906684528357), - ]; - let coded: Vec<(u8, usize, u64)> = pins - .iter() - .map(|&(q, _, _)| { - let e = encode_sequence(&source, q, 0.5).unwrap(); - (q, e.stream.len(), fnv(&e.stream)) - }) - .collect(); - crate::speed::set_speed(was); - for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) { - assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved"); - } - } - - /// A ladder is only a ladder if both axes rise together. - pub(super) fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { - assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); - for w in ladder.windows(2) { - assert!( - w[1].0 > w[0].0 && w[1].1 > w[0].1, - "{name}: not monotone, {ladder:?}" + decoded.y, frame.reconstruction.y, + "{filter:?} frame {i}: luma" ); + assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V"); } + streams.push((filter, encoded.stream)); } - - /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2, - /// split by block class in lane-av1txdepth): depth 0 is one transform over - /// the whole block, 1 its four halves; the classes are the 16x16/8x8 - /// leaves and the 32x32 root, each single-reference or compound. A class - /// with no counts at all never reached `commit_inter_luma` -- which is - /// what its knob being off looks like (class `gate-blind-to-feature`). - pub(super) fn print_inter_tx_census(name: &str) { - let splits = take_inter_tx_split_hits(); - let total: usize = splits.iter().sum(); - let row = |label: &str, base: usize| { - let (n0, n1) = (splits[base], splits[base + 1]); - format!( - "{label} 0={n0} 1={n1} ({:.1}% split)", - 100.0 * n1 as f64 / (n0 + n1).max(1) as f64 - ) - }; - eprintln!( - "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}", - row("leaf single", 0), - row("leaf compound", 2), - row("32x32 single", 4), - row("32x32 compound", 6), - ); - // lane-txrd: which types the two searches actually COMMITTED over - // this row's four encodes -- the gate could not say whether a type - // search fired at all (class `gate-blind-to-feature`). - const NAMES: [&str; 16] = [ - "IDTX", - "DCT_DCT", - "ADST_ADST", - "ADST_DCT", - "DCT_ADST", - "V_DCT", - "H_DCT", - "FLIPADST_DCT", - "DCT_FLIPADST", - "FLIPADST_FLIPADST", - "ADST_FLIPADST", - "FLIPADST_ADST", - "V_ADST", - "H_ADST", - "V_FLIPADST", - "H_FLIPADST", - ]; - let name_of = |t: usize| NAMES[t]; - for (label, hits) in [ - ("inter", take_inter_tx_type_hits()), - ("intra", take_tx_type_hits()), - ] { - let total: usize = hits.iter().sum(); - let live: Vec = hits - .iter() - .enumerate() - .filter(|&(_, &n)| n > 0) - .map(|(t, &n)| { - format!( - "{}={n} ({:.1}%)", - name_of(t), - 100.0 * n as f64 / total.max(1) as f64 - ) - }) - .collect(); - eprintln!( - "{name}: {label} tx_type of {total} units -- {}", - live.join(" ") - ); - } - let t = take_txrd_stats(); - if t[0] > 0 { - eprintln!( - "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \ - bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)", - t[0], - t[1], - t[3] as f64 / 64.0, - t[2], - t[4] as f64 / 64.0, - 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64, - 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64, - ); - eprintln!( - "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \ - flat: dsse {:+.2}%, dbits {:+.2}%)", - t[5], - t[6] as f64 / 64.0, - 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64, - 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64, - ); + set_frame_interp(None); + for (i, (fa, a)) in streams.iter().enumerate() { + for (fb, b) in &streams[i + 1..] { + assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes"); } } - - /// The video stream's coded size, from ffprobe. - pub(super) fn probe_dims(clip: &str) -> Option<(usize, usize)> { - crate::probe::dims(clip) - } - - /// `EC_AV1_NATIVE_CROP=x`: the native gate's window at a - /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s - /// superblock-aligned one, still centred and still even for 4:2:0. - /// - /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide - /// superblocks by design, so no default gate row has a block the frame - /// edge cuts through -- while every arbitrary export size does (3840x1608 - /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP= - /// 1920x1080` is the straddling arm the edge-clipped distortion score is - /// read on. - pub(super) fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> { - let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?; - let (w, h) = spec - .split_once('x') - .expect("EC_AV1_NATIVE_CROP is x"); - let (cw, ch): (usize, usize) = ( - w.parse().expect("crop width"), - h.parse().expect("crop height"), - ); - let (nw, nh) = crate::probe::dims(clip)?; - assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}"); - let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1); - Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch)) - } - - /// The probe arms the gate's source (lane-probe, class `instrument - /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg - /// command line and had no `-ss`, so it read film B from frame 0 -- a - /// black leader -- and coded 59 kB where the gate's own ladder point - /// coded 89 kB of the same title; every census taken through it was - /// probe-relative. Both now call [`crate::probe::source`]; this pins that - /// the shared loader honours the seek (arming the probe's way and the - /// gate's way gives byte-identical streams, and dropping the seek does - /// not), on a synthetic clip whose content moves over time. - #[test] - fn the_probe_arms_the_gates_source() { - let _knobs = crate::speed::knob_write(); - let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2.y4m"); - // 384x202: neither side is a multiple of 128, so the gate's centre - // window is a real derivation and not the frame itself -- exactly the - // shape film B has (3840x1608, never 3840x2160). - let ok = ec_testkit::ffmpeg() - .args([ - "-v", - "error", - "-y", - "-f", - "lavfi", - "-i", - "testsrc2=size=384x202:rate=10", - ]) - .args(["-frames:v", "20", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let path = clip.to_str().unwrap(); - - // The window: superblock-aligned, centred, even offsets. - let (vf, w, h) = crate::probe::gate_crop(path); - assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128)); - - let (seek, q) = ("00:00:01", 150u8); - let gate = clip_frames_vf(path, seek, &vf, w, h, 6); - let probe = crate::probe::source(path, seek, &vf, w, h, 6); - assert!( - gate.iter() - .zip(&probe) - .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v), - "the probe's source differs from the gate's at the same window" - ); - let bytes = |src: &[Picture]| { - encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder()) - .unwrap() - .stream - }; +} + +/// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With +/// `allow_high_precision_mv` off the writer refuses an odd eighth-pel +/// residual outright (`round_to_valid_mv` rounds it away first), so the +/// finest vector the encoder could commit to was a quarter pel. With the +/// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per +/// non-zero component and the search's fourth stage refines to the +/// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the +/// on arm, and -- the part that makes it a signal rather than a symbol +/// count (class `fixture proves the symbol, not the signal`) -- that some +/// of them come out ZERO, i.e. name a vector the off arm cannot code at +/// all. Both streams are decoded by ffmpeg AND by this crate's own +/// decoder and asserted sample-exact against the encoder's own +/// reconstruction, which is what proves the header bit and the symbols +/// agree. +#[test] +fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (256usize, 128usize); + let pictures: Vec = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let mut arms = Vec::new(); + for hp in [false, true] { + set_high_precision_mv(Some(hp)); + let _ = crate::tile::take_hp_symbols(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) + .unwrap_or_else(|e| panic!("hp={hp}: {e}")); + let (symbols, eighth) = crate::tile::take_hp_symbols(); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); + let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count"); assert_eq!( - bytes(&gate), - bytes(&probe), - "probe and gate code different bytes" - ); - // The two witnesses that both halves of the arming reach ffmpeg: the - // seek, and the crop's own offset (the film-B defect in miniature -- - // the probe was reading `crop=..:568` of a 1608-high frame). - let unseeked = crate::probe::source(path, "0", &vf, w, h, 6); - assert_ne!( - bytes(&gate), - bytes(&unseeked), - "seeked and unseeked arming coded the same bytes -- the seek is inert" + ours.len(), + pictures.len(), + "hp={hp}: our decoder frame count" ); - let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6); - assert_ne!( - bytes(&gate), - bytes(&offset), - "centred and top-aligned windows coded the same bytes -- the crop is inert" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to - /// hardwire the REGULAR kernel, so the encoder could not have coded a - /// SMOOTH or SHARP frame even if the header had said so -- the search, - /// the trials, the recon and the frame header now all read - /// `FrameCtx::interp_filter`. Each of the three kernels codes its own - /// distinct stream (a filter that never reached the prediction would code - /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg - /// reconstructs every frame of each of them exactly, which is what proves - /// the header and the prediction agree. - #[test] - fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (256usize, 128usize); - // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so - // all three kernels would code the same bytes and the test would pass - // on a wiring that does nothing (class `fixture proves the symbol, not - // the signal`). `panned_test_card` shifts by whole pixels, so the - // search finds the sub-pel positions off the reconstruction instead: - // three frames of a slow diagonal pan. - let pictures: Vec = (0..3) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let mut streams = Vec::new(); - for filter in [ - ec_av1_syntax::InterpolationFilter::Eighttap, - ec_av1_syntax::InterpolationFilter::EighttapSmooth, - ec_av1_syntax::InterpolationFilter::EighttapSharp, - ] { - set_frame_interp(Some(filter)); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) - .unwrap_or_else(|e| panic!("{filter:?}: {e}")); - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); - assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count"); - for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { - assert_eq!( - decoded.y, frame.reconstruction.y, - "{filter:?} frame {i}: luma" - ); - assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U"); - assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V"); - } - streams.push((filter, encoded.stream)); - } - set_frame_interp(None); - for (i, (fa, a)) in streams.iter().enumerate() { - for (fb, b) in &streams[i + 1..] { - assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes"); - } - } - } - - /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With - /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel - /// residual outright (`round_to_valid_mv` rounds it away first), so the - /// finest vector the encoder could commit to was a quarter pel. With the - /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per - /// non-zero component and the search's fourth stage refines to the - /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the - /// on arm, and -- the part that makes it a signal rather than a symbol - /// count (class `fixture proves the symbol, not the signal`) -- that some - /// of them come out ZERO, i.e. name a vector the off arm cannot code at - /// all. Both streams are decoded by ffmpeg AND by this crate's own - /// decoder and asserted sample-exact against the encoder's own - /// reconstruction, which is what proves the header bit and the symbols - /// agree. - #[test] - fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (256usize, 128usize); - let pictures: Vec = (0..3) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let mut arms = Vec::new(); - for hp in [false, true] { - set_high_precision_mv(Some(hp)); - let _ = crate::tile::take_hp_symbols(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) - .unwrap_or_else(|e| panic!("hp={hp}: {e}")); - let (symbols, eighth) = crate::tile::take_hp_symbols(); - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count"); - assert_eq!( - ours.len(), - pictures.len(), - "hp={hp}: our decoder frame count" - ); - for (i, e) in encoded.frames.iter().enumerate() { - for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] { - if let Some((plane, s, got, want)) = - first_plane_mismatch(got, &e.reconstruction) - { - panic!( - "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \ + for (i, e) in encoded.frames.iter().enumerate() { + for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] { + if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction) { + panic!( + "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \ the encoder reconstructed {want}" - ); - } + ); } } - arms.push((symbols, eighth, encoded.stream)); } - set_high_precision_mv(None); - let (off, on) = (&arms[0], &arms[1]); - assert_eq!( - off.0, 0, - "a frame without the header bit codes no hp symbol" - ); - assert!( - on.0 > 0, - "a high-precision frame codes hp symbols (got {})", - on.0 - ); - assert!( - on.1 > 0, - "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)", - on.0 - ); - assert_ne!(off.2, on.2, "the two arms coded the same bytes"); - println!( - "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B", - off.0, - off.2.len(), - on.0, - on.1, - on.2.len() - ); + arms.push((symbols, eighth, encoded.stream)); } + set_high_precision_mv(None); + let (off, on) = (&arms[0], &arms[1]); + assert_eq!( + off.0, 0, + "a frame without the header bit codes no hp symbol" + ); + assert!( + on.0 > 0, + "a high-precision frame codes hp symbols (got {})", + on.0 + ); + assert!( + on.1 > 0, + "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)", + on.0 + ); + assert_ne!(off.2, on.2, "the two arms coded the same bytes"); + println!( + "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B", + off.0, + off.2.len(), + on.0, + on.1, + on.2.len() + ); +} diff --git a/crates/ec-av1/src/encode/split.rs b/crates/ec-av1/src/encode/split.rs index 0b3f958a..7c24c7c2 100644 --- a/crates/ec-av1/src/encode/split.rs +++ b/crates/ec-av1/src/encode/split.rs @@ -312,13 +312,6 @@ pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [ std::sync::atomic::AtomicU64::new(0), ]; -/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib -/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`). -#[cfg(test)] -pub(crate) fn take_txrd_stats() -> [u64; 7] { - std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// Reads [`INTER_TX_TYPE_HITS`] and zeroes it. #[cfg(test)] pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] { @@ -969,7 +962,15 @@ thread_local! { static INTRABC_FORCE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates +/// Whether the luma search refines a directional winner's `angle_delta_y` +/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair). +pub(super) fn angle_delta_on() -> bool { + static ENV: std::sync::LazyLock> = + std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE)) +} + +#[cfg(test)] pub(crate) fn force_intrabc(value: Option) { INTRABC_FORCE.with(|c| c.set(value)); } @@ -1059,7 +1060,12 @@ pub(super) fn ibc_index( /// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact /// content appears at some other position, against [`intrabc_pct`]. Returns /// the share as well, for the gate's own print. -pub(super) fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) { +pub(super) fn intrabc_worth_it( + y: &[u8], + width: usize, + true_width: usize, + true_height: usize, +) -> (bool, f64) { if true_width < 4 * 64 || true_height < 2 * 64 { return (false, 0.0); } @@ -1075,9 +1081,9 @@ pub(super) fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_h && hits .iter() .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) - { - matched += 1; - } + { + matched += 1; + } bx += IBC_HASH; } by += IBC_HASH; @@ -1207,13 +1213,6 @@ impl Drop for Ibc { } } -/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to -/// its own encode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn take_intrabc_search() -> [usize; 3] { - std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// [`crate::tile::write_dv_component`]'s static price -- the same shape as /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv` /// infers rather than codes. @@ -1667,19 +1666,20 @@ pub(super) fn code_square( if let Some(ibc) = ibc && let Some((dv, cost_ibc, src)) = ibc_search(ibc, luma, chroma, (x, y), side, search.lambda) - && cost_ibc < cost { - ibc_commit(luma, chroma, (x, y), src, side); - ibc.last_dv = Some(dv); - ibc.hits += 1; - return ( - BlockCoeffs { - skip: true, - dv: Some(dv), - ..BlockCoeffs::default() - }, - cost_ibc, - ); - } + && cost_ibc < cost + { + ibc_commit(luma, chroma, (x, y), src, side); + ibc.last_dv = Some(dv); + ibc.hits += 1; + return ( + BlockCoeffs { + skip: true, + dv: Some(dv), + ..BlockCoeffs::default() + }, + cost_ibc, + ); + } // A palette or filter-intra block's luma was recoded through `DCT_DCT` // (its levels came from `code_from_prediction`), so the searched types // belong to a block this one no longer is. @@ -1722,53 +1722,6 @@ pub(super) const CHROMA_MODES: [u8; 7] = [ PAETH_PRED, ]; -/// The thirteen intra mode names, for the chroma fire count's print. -#[cfg(test)] -pub(super) const UV_MODE_NAMES: [&str; 14] = [ - "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H", - "PAETH", "CFL", -]; - -/// How many blocks each chroma mode has won, indexed by the mode itself -- -/// the fire count that says whether the search below reaches its candidates -/// at all (the `gate-blind-to-feature` class), printed once per gate run. -pub(super) static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] = - [const { std::sync::atomic::AtomicUsize::new(0) }; 14]; - -/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has -/// won, summed over both chroma planes -- the alpha histogram the gate prints -/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one -/// magnitude only is a search that never left its first candidate). -pub(super) static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] = - [const { std::sync::atomic::AtomicUsize::new(0) }; 17]; - -/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha -/// zero on a CfL block", `1..=16` the magnitudes. -#[cfg(test)] -pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] { - std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - -/// How many directional luma blocks won at each `angle_delta_y`, indexed -/// `delta + 3` -- the histogram that says whether the refinement below ever -/// leaves zero (`gate-blind-to-feature`). -pub(super) static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] = - [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; - -/// Reads [`ANGLE_DELTA_HITS`] and zeroes it. -#[cfg(test)] -pub(crate) fn take_angle_delta_hits() -> [usize; 7] { - std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - -/// Whether the luma search refines a directional winner's `angle_delta_y` -/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair). -pub(super) fn angle_delta_on() -> bool { - static ENV: std::sync::LazyLock> = - std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")); - ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE)) -} - /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0` /// switches it off, which is how the lane measured its own on/off pair). pub(super) fn cfl_on() -> bool { @@ -1834,14 +1787,6 @@ pub(crate) fn sb128_on() -> bool { } } -/// Forces [`sb128_on`] for the rest of the process -- the superblock size is -/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`), -/// exactly like the speed-preset gates. -#[cfg(test)] -pub(crate) fn force_sb128(on: bool) { - ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed); -} - /// The luma loop-restoration unit size this sequence codes: a 128 superblock /// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there, /// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is @@ -1863,13 +1808,6 @@ pub(crate) fn filter_intra_on() -> bool { ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA)) } -/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts -/// to its own encode. -#[cfg(test)] -pub(crate) fn take_uv_mode_hits() -> [usize; 14] { - std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode -- /// `uv_mode` is a single symbol covering U and V -- and commits the cheapest. /// Returns each plane's levels, the mode, and what the pair cost (squared @@ -2051,7 +1989,9 @@ pub(super) fn search_chroma( } let mut v_colors = [0u16; 8]; for k in 0..n { - v_colors[k] = (sums[k] + counts[k] / 2).checked_div(counts[k]).unwrap_or(0) as u16; + v_colors[k] = (sums[k] + counts[k] / 2) + .checked_div(counts[k]) + .unwrap_or(0) as u16; } let candidate = crate::tile::PaletteUv { size: pal.size, @@ -2229,17 +2169,10 @@ pub(super) fn search_chroma( } } } - if let Some((alpha_u, alpha_v)) = cfl_alphas { - for alpha in [alpha_u, alpha_v] { - CFL_ALPHA_HITS[alpha.unsigned_abs() as usize] - .fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } - } if census_on() { CHROMA_RANK[sad_rank(&ranking, mode).min(6)] .fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); chroma[0].commit(at.x, at.y, at.side, &u); chroma[1].commit(at.x, at.y, at.side, &v); ( @@ -2871,53 +2804,55 @@ pub(super) fn code_square_inter( } } if let Some(new_mv) = searched_new - && let Some(b0) = mv_residual_bits(new_mv, cbase.0) { - ccands.push(( - (new_mv, cstack.nearest_mv.1), - mode_bits_of(3) + b0, - InterInfo { - ref_frame: crate::mvstack::LAST_FRAME, - mode: InterMode::NewNearestMv, - mv: new_mv, - mv1: cstack.nearest_mv.1, - ref1: Some(ref1), - ref_mv_idx: 0, - }, - )); - } + && let Some(b0) = mv_residual_bits(new_mv, cbase.0) + { + ccands.push(( + (new_mv, cstack.nearest_mv.1), + mode_bits_of(3) + b0, + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NewNearestMv, + mv: new_mv, + mv1: cstack.nearest_mv.1, + ref1: Some(ref1), + ref_mv_idx: 0, + }, + )); + } // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two // searches this leaf ran, each residual priced against `cbase`. if let Some(mv1) = second_new - && let Some(b1) = mv_residual_bits(mv1, cbase.1) { + && let Some(b1) = mv_residual_bits(mv1, cbase.1) + { + ccands.push(( + (cstack.nearest_mv.0, mv1), + mode_bits_of(2) + b1, + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NearestNewMv, + mv: cstack.nearest_mv.0, + mv1, + ref1: Some(ref1), + ref_mv_idx: 0, + }, + )); + if let Some((new_mv, b0)) = + searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b))) + { ccands.push(( - (cstack.nearest_mv.0, mv1), - mode_bits_of(2) + b1, + (new_mv, mv1), + mode_bits_of(7) + b0 + b1, InterInfo { ref_frame: crate::mvstack::LAST_FRAME, - mode: InterMode::NearestNewMv, - mv: cstack.nearest_mv.0, + mode: InterMode::NewNewMv, + mv: new_mv, mv1, ref1: Some(ref1), ref_mv_idx: 0, }, )); - if let Some((new_mv, b0)) = - searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b))) - { - ccands.push(( - (new_mv, mv1), - mode_bits_of(7) + b0 + b1, - InterInfo { - ref_frame: crate::mvstack::LAST_FRAME, - mode: InterMode::NewNewMv, - mv: new_mv, - mv1, - ref1: Some(ref1), - ref_mv_idx: 0, - }, - )); - } } + } ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); ccands.dedup_by_key(|c| c.0); let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); @@ -3040,7 +2975,8 @@ pub(super) fn code_square_inter( ) >= 1; let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet); let mut candidates: Vec<(u8, [Vec; 3])> = Vec::new(); - if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() + if crate::envflags::env_flag!("EC_AV1_OBMC") + && side >= obmc_min_side() && let Some(pred) = obmc_prediction( grid, (mi_row, mi_col), @@ -3052,9 +2988,10 @@ pub(super) fn code_square_inter( planes, (reference.width, reference.height), fctx, - ) { - candidates.push((1, pred)); - } + ) + { + candidates.push((1, pred)); + } if warp_alphabet && let Some(pred) = warp_prediction( grid, @@ -3066,9 +3003,10 @@ pub(super) fn code_square_inter( info.ref_frame, planes, fctx, - ) { - candidates.push((2, pred)); - } + ) + { + candidates.push((2, pred)); + } for (motion, pred) in candidates { let luma_o = luma.code_from_prediction( x, @@ -3125,136 +3063,137 @@ pub(super) fn code_square_inter( } if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best - && cost < intra_cost { - // A compound winner commits the flat trial it was priced from: - // `commit_inter_luma`'s var-tx trial set is single-reference - // (`mc_trial`), so a compound leaf codes `tx_depth = 0`. - // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma` - // predicting each half-side trial from BOTH references, verified - // byte-identical to this when its split is disabled) and MEASURED - // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the - // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/ - // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A - // compound block's residual is small enough that the four extra - // per-unit txb_skip/eob symbols cost more ladder bytes than this - // encoder's static-CDF estimate prices them at, so the local RD - // win does not convert. lane-av1txbits REBUILT it on top of a - // search that prices against the tables the frame is really - // written with (`tile::arm_pricing_cdfs`, the estimate error on - // these very blocks measured down from +31% to +3%) and measured - // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/ - // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the - // same build without it. The static-CDF estimate was NOT what - // held the compound var-tx trial back. The flat trial stays. - // An OBMC winner commits the flat trial too: `commit_inter_luma` - // re-predicts each var-tx unit by plain translation, which is not - // the prediction this candidate was priced from. - // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE - // 0.05 (both rejections above were measured at 0.1, the weight - // the lambda lane showed was 2x too heavy): a compound winner is - // offered the same var-tx split, its units predicted from BOTH - // references (`mc_trial_compound`). RE-MEASURED native: film - // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4 - // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off -- - // one row 0.2 down, two flat, short of the two-down-one-flat keep - // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF) - // rather than change the default on a single 0.2 row. It fires: - // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for - // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against - // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is - // 1.3/1.2 down there, which is where the upgrade path is if this - // is picked up again. - let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| { - refs[r as usize].map(|g| { - ( - info.mv1, - (g.y.as_slice(), g.width, luma.true_width, luma.true_height), - ) - }) - }); - let (levels, tx_depth, dcost, luma_tx_types) = - if motion_won != 0 || (info.ref1.is_some() && second.is_none()) { - luma.commit(x, y, side, &luma_new); - (luma_new.levels.clone(), 0, 0.0, Vec::new()) - } else { - commit_inter_luma( - luma, - (x, y), - side, - info.mv, - (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), - search, - &luma_new, - skip_new, - second, - fctx, - ) - }; - // lane-txrd: chroma follows the luma type the search just chose. - let [u_new, v_new] = match luma_tx_types.first().copied() { - Some(t) => recode_inter_chroma( - chroma, + && cost < intra_cost + { + // A compound winner commits the flat trial it was priced from: + // `commit_inter_luma`'s var-tx trial set is single-reference + // (`mc_trial`), so a compound leaf codes `tx_depth = 0`. + // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma` + // predicting each half-side trial from BOTH references, verified + // byte-identical to this when its split is disabled) and MEASURED + // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the + // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/ + // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A + // compound block's residual is small enough that the four extra + // per-unit txb_skip/eob symbols cost more ladder bytes than this + // encoder's static-CDF estimate prices them at, so the local RD + // win does not convert. lane-av1txbits REBUILT it on top of a + // search that prices against the tables the frame is really + // written with (`tile::arm_pricing_cdfs`, the estimate error on + // these very blocks measured down from +31% to +3%) and measured + // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/ + // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the + // same build without it. The static-CDF estimate was NOT what + // held the compound var-tx trial back. The flat trial stays. + // An OBMC winner commits the flat trial too: `commit_inter_luma` + // re-predicts each var-tx unit by plain translation, which is not + // the prediction this candidate was priced from. + // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE + // 0.05 (both rejections above were measured at 0.1, the weight + // the lambda lane showed was 2x too heavy): a compound winner is + // offered the same var-tx split, its units predicted from BOTH + // references (`mc_trial_compound`). RE-MEASURED native: film + // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4 + // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off -- + // one row 0.2 down, two flat, short of the two-down-one-flat keep + // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF) + // rather than change the default on a single 0.2 row. It fires: + // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for + // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against + // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is + // 1.3/1.2 down there, which is where the upgrade path is if this + // is picked up again. + let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| { + refs[r as usize].map(|g| { + ( + info.mv1, + (g.y.as_slice(), g.width, luma.true_width, luma.true_height), + ) + }) + }); + let (levels, tx_depth, dcost, luma_tx_types) = + if motion_won != 0 || (info.ref1.is_some() && second.is_none()) { + luma.commit(x, y, side, &luma_new); + (luma_new.levels.clone(), 0, 0.0, Vec::new()) + } else { + commit_inter_luma( + luma, (x, y), side, info.mv, - [ - (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), - (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), - ], - info.ref1.filter(|_| motion_won == 0).and_then(|r| { - refs[r as usize].map(|g| { - ( - info.mv1, - [ - ( - g.u.as_slice(), - g.width / 2, - chroma[0].true_width, - chroma[0].true_height, - ), - ( - g.v.as_slice(), - g.width / 2, - chroma[1].true_width, - chroma[1].true_height, - ), - ], - ) - }) - }), + (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, - chroma_set, - t, + &luma_new, + skip_new, + second, fctx, ) - .unwrap_or([u_new, v_new]), - None => [u_new, v_new], }; - chroma[0].commit(x / 2, y / 2, side / 2, &u_new); - chroma[1].commit(x / 2, y / 2, side / 2, &v_new); - return ( - BlockCoeffs { - angle_delta_y: 0, - cfl_alphas: None, - filter_intra: None, - luma: coeffs(&levels, side), - u: coeffs(&u_new.levels, side / 2), - v: coeffs(&v_new.levels, side / 2), - mode: DC_PRED, - uv_mode: DC_PRED, - skip: skip_new, - eight: None, - dv: None, - palette: None, - palette_uv: None, - tx_depth, - luma_tx_types, - inter: Some(info), - motion_mode: motion_won, - }, - cost + dcost, - ); - } + // lane-txrd: chroma follows the luma type the search just chose. + let [u_new, v_new] = match luma_tx_types.first().copied() { + Some(t) => recode_inter_chroma( + chroma, + (x, y), + side, + info.mv, + [ + (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), + (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), + ], + info.ref1.filter(|_| motion_won == 0).and_then(|r| { + refs[r as usize].map(|g| { + ( + info.mv1, + [ + ( + g.u.as_slice(), + g.width / 2, + chroma[0].true_width, + chroma[0].true_height, + ), + ( + g.v.as_slice(), + g.width / 2, + chroma[1].true_width, + chroma[1].true_height, + ), + ], + ) + }) + }), + search, + chroma_set, + t, + fctx, + ) + .unwrap_or([u_new, v_new]), + None => [u_new, v_new], + }; + chroma[0].commit(x / 2, y / 2, side / 2, &u_new); + chroma[1].commit(x / 2, y / 2, side / 2, &v_new); + return ( + BlockCoeffs { + angle_delta_y: 0, + cfl_alphas: None, + filter_intra: None, + luma: coeffs(&levels, side), + u: coeffs(&u_new.levels, side / 2), + v: coeffs(&v_new.levels, side / 2), + mode: DC_PRED, + uv_mode: DC_PRED, + skip: skip_new, + eight: None, + dv: None, + palette: None, + palette_uv: None, + tx_depth, + luma_tx_types, + inter: Some(info), + motion_mode: motion_won, + }, + cost + dcost, + ); + } census_add(8, 1); if skip { diff --git a/crates/ec-av1/src/encode/tests.rs b/crates/ec-av1/src/encode/tests.rs index 87bb592b..c11e69c9 100644 --- a/crates/ec-av1/src/encode/tests.rs +++ b/crates/ec-av1/src/encode/tests.rs @@ -1,3783 +1,2542 @@ - /// Every (site, frame type, block side) the census can be called with - /// lands in its own ten-counter bucket, inside the array (class - /// `enumerate-table-domain`: an off-by-one here would silently add two - /// sites' trials together). - #[test] - fn the_split_census_buckets_are_distinct_and_in_bounds() { - let mut seen = std::collections::BTreeSet::new(); - for site in 0..2 { - for key in [true, false] { - for side in [8usize, 16, 32, 64] { - let base = super::split_census_base(site, key, side); - assert!( - base + 10 <= super::SPLIT_CENSUS.len(), - "{site} {key} {side}" - ); - assert!(seen.insert(base), "{site} {key} {side} collides"); - } - } +/// An [`crate::mvstack::MvStack`] with every context at zero and no +/// neighbours, for the pricer tests below to fill the one band each of +/// them is about. +/// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer +/// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL +/// against the same stack -- an offer the writer clamps prices the +/// residual against a predictor the decoder never derives, which is the +/// silent MV drift lane-sb128b root-caused (there fixed on the WRITER +/// side, so the stream stays legal; here the pricer's own offer set is +/// enumerated, class `enumerate-table-domain`). +/// +/// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt +/// r2, 2026-09-29). It replaces the clip gate +/// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`, +/// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a +/// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable +/// while the invariant above holds, so no recipe could ever satisfy it. +/// Deletion loses no coverage on either half: +/// * the clamp half -- this test IS the coverage, and it is strictly +/// stronger than any clip gate: it enumerates the pricer's whole offer +/// set against the writer's rule for every stack size 0..=4, and larger +/// stacks add entries the pricers never offer (`best_new_mv_syntax` +/// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are +/// unreachable at ANY stack size), which is why 0..=4 bounds the +/// domain rather than sampling it; +/// * the pixel half -- the deleted gate's own decode-vs-encoder- +/// reconstruction compare on a 1280x768 sb128 sequence is already made +/// four times over, by `a_128_superblock_clip_whose_root_search_codes_ +/// 128x128_blocks_decodes_exact`, +/// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`, +/// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact` +/// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders` +/// (same geometry, same `force_sb128(true)`, same own-reconstruction AND +/// ffmpeg compare). +/// +/// MEASURED before deleting (153 clip x size x frame-count x q combinations, +/// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF +/// the clip was never the variable: widening `best_new_mv_syntax`'s offer +/// set to `0..5` fires the counter immediately (9/2/2/1 on +/// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8, +/// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp` +/// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix +/// (`deferred(unblock: the DRL owner widens the pricer past the writer's +/// `start + 2` ceiling, or retires the counter)`) -- this test will go red +/// the moment either happens, which is the signal to re-open the cell. +/// +/// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer +#[test] +fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() { + for n in 0..=4usize { + let mut stack = bare_stack(); + for i in 0..n { + stack.entries.push(crate::mvstack::StackEntry { + mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)), + weight: 1, + }); + stack.drl_ctx.push(0); + } + stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv); + stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv); + stack.pred_mv = stack.nearest_mv; + // Aim the vector at each entry in turn, so every index the offer + // set holds is the one that wins at least once. + for target in 0..n.max(1) { + let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv); + let (_, idx) = + best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable"); + let idx = usize::from(idx); + assert_eq!( + crate::tile::signalled_drl_idx(n, 0, idx), + idx, + "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}", + ); } - assert_eq!(seen.len(), 16); - } - - /// An [`crate::mvstack::MvStack`] with every context at zero and no - /// neighbours, for the pricer tests below to fill the one band each of - /// them is about. - /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer - /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL - /// against the same stack -- an offer the writer clamps prices the - /// residual against a predictor the decoder never derives, which is the - /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER - /// side, so the stream stays legal; here the pricer's own offer set is - /// enumerated, class `enumerate-table-domain`). - /// - /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt - /// r2, 2026-09-29). It replaces the clip gate - /// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`, - /// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a - /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable - /// while the invariant above holds, so no recipe could ever satisfy it. - /// Deletion loses no coverage on either half: - /// * the clamp half -- this test IS the coverage, and it is strictly - /// stronger than any clip gate: it enumerates the pricer's whole offer - /// set against the writer's rule for every stack size 0..=4, and larger - /// stacks add entries the pricers never offer (`best_new_mv_syntax` - /// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are - /// unreachable at ANY stack size), which is why 0..=4 bounds the - /// domain rather than sampling it; - /// * the pixel half -- the deleted gate's own decode-vs-encoder- - /// reconstruction compare on a 1280x768 sb128 sequence is already made - /// four times over, by `a_128_superblock_clip_whose_root_search_codes_ - /// 128x128_blocks_decodes_exact`, - /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`, - /// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact` - /// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders` - /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND - /// ffmpeg compare). - /// - /// MEASURED before deleting (153 clip x size x frame-count x q combinations, - /// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF - /// the clip was never the variable: widening `best_new_mv_syntax`'s offer - /// set to `0..5` fires the counter immediately (9/2/2/1 on - /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8, - /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp` - /// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix - /// (`deferred(unblock: the DRL owner widens the pricer past the writer's - /// `start + 2` ceiling, or retires the counter)`) -- this test will go red - /// the moment either happens, which is the signal to re-open the cell. - /// - /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer - #[test] - fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() { - for n in 0..=4usize { - let mut stack = bare_stack(); - for i in 0..n { - stack.entries.push(crate::mvstack::StackEntry { - mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)), - weight: 1, - }); - stack.drl_ctx.push(0); - } - stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv); - stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv); - stack.pred_mv = stack.nearest_mv; - // Aim the vector at each entry in turn, so every index the offer - // set holds is the one that wins at least once. - for target in 0..n.max(1) { - let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv); - let (_, idx) = - best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable"); - let idx = usize::from(idx); + // The NEARMV arm's own offer set (`search_inter_block`, + // `search_skip_64`): indices 1 and 2, offered only when the stack + // really holds that entry. + for idx in 1..=2usize { + if stack.entries.get(idx).is_some() { assert_eq!( - crate::tile::signalled_drl_idx(n, 0, idx), + crate::tile::signalled_drl_idx(n, 1, idx), idx, - "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}", + "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}", ); } - // The NEARMV arm's own offer set (`search_inter_block`, - // `search_skip_64`): indices 1 and 2, offered only when the stack - // really holds that entry. - for idx in 1..=2usize { - if stack.entries.get(idx).is_some() { - assert_eq!( - crate::tile::signalled_drl_idx(n, 1, idx), - idx, - "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}", - ); - } - } } } +} - pub(super) fn bare_stack() -> crate::mvstack::MvStack { - crate::mvstack::MvStack { - entries: Default::default(), - nearest_mv: (0, 0), - near_mv: (0, 0), - pred_mv: (0, 0), - new_mv_ctx: 0, - ref_mv_ctx: 0, - zero_mv_ctx: 0, - drl_ctx: Default::default(), - above_refs: (None, None), - left_refs: (None, None), - above_nbr: None, - left_nbr: None, - above_skip: false, - left_skip: false, - } +pub(super) fn bare_stack() -> crate::mvstack::MvStack { + crate::mvstack::MvStack { + entries: Default::default(), + nearest_mv: (0, 0), + near_mv: (0, 0), + pred_mv: (0, 0), + new_mv_ctx: 0, + ref_mv_ctx: 0, + zero_mv_ctx: 0, + drl_ctx: Default::default(), + above_refs: (None, None), + left_refs: (None, None), + above_nbr: None, + left_nbr: None, + above_skip: false, + left_skip: false, } +} - /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs' - /// `write_compound_ref_frames` codes for a pair, each at that symbol's - /// own neighbour-derived context. Red before lane-ctx, where the pricer - /// spent four constants at CDF row 0 that assumed the pair was - /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as - /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely. - #[test] - fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() { - use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF}; - use crate::encode::symbol_bits as b; - use crate::mvstack::{ - ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, - LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx, - single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, - single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx, +/// [`super::compound_ref_bits`] pays exactly the symbols tile.rs' +/// `write_compound_ref_frames` codes for a pair, each at that symbol's +/// own neighbour-derived context. Red before lane-ctx, where the pricer +/// spent four constants at CDF row 0 that assumed the pair was +/// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as +/// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely. +#[test] +fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() { + use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF}; + use crate::encode::symbol_bits as b; + use crate::mvstack::{ + ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, + LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx, single_ref_p1_ctx, + single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, + single_ref_p6_ctx, uni_comp_ref_p1_ctx, + }; + // (pair, unidirectional?, the tree's symbols as (table, p index, + // context selector, value)) -- transcribed from the writer. + // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`. + type Sym = (char, usize, usize, usize); + let cases: [((i8, i8), bool, &[Sym]); 7] = [ + ( + (LAST_FRAME, LAST2_FRAME), + true, + &[('u', 0, 1, 0), ('u', 1, 7, 0)], + ), + ( + (LAST_FRAME, LAST3_FRAME), + true, + &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)], + ), + ( + (LAST_FRAME, GOLDEN_FRAME), + true, + &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)], + ), + ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]), + ( + (LAST_FRAME, ALTREF_FRAME), + false, + &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)], + ), + ( + (LAST_FRAME, BWDREF_FRAME), + false, + &[ + ('c', 0, 3, 0), + ('c', 1, 4, 0), + ('b', 0, 2, 0), + ('b', 1, 6, 0), + ], + ), + ( + (LAST_FRAME, ALTREF2_FRAME), + false, + &[ + ('c', 0, 3, 0), + ('c', 1, 4, 0), + ('b', 0, 2, 0), + ('b', 1, 6, 1), + ], + ), + ]; + let nbr = |ref0, ref1: Option| { + Some(NeighbourRef { + is_inter: true, + ref0, + ref1, + uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)), + }) + }; + // No neighbours (every context zero), then a mixed pair that puts the + // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0. + for (above_nbr, left_nbr, above_refs, left_refs) in [ + (None, None, (None, None), (None, None)), + ( + nbr(LAST_FRAME, None), + nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)), + (Some(LAST_FRAME), None), + (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)), + ), + ] { + let stack = crate::mvstack::MvStack { + above_nbr, + left_nbr, + above_refs, + left_refs, + ..bare_stack() }; - // (pair, unidirectional?, the tree's symbols as (table, p index, - // context selector, value)) -- transcribed from the writer. - // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`. - type Sym = (char, usize, usize, usize); - let cases: [((i8, i8), bool, &[Sym]); 7] = [ - ( - (LAST_FRAME, LAST2_FRAME), - true, - &[('u', 0, 1, 0), ('u', 1, 7, 0)], - ), - ( - (LAST_FRAME, LAST3_FRAME), - true, - &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)], - ), - ( - (LAST_FRAME, GOLDEN_FRAME), - true, - &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)], - ), - ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]), - ( - (LAST_FRAME, ALTREF_FRAME), - false, - &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)], - ), - ( - (LAST_FRAME, BWDREF_FRAME), - false, - &[ - ('c', 0, 3, 0), - ('c', 1, 4, 0), - ('b', 0, 2, 0), - ('b', 1, 6, 0), - ], - ), - ( - (LAST_FRAME, ALTREF2_FRAME), - false, - &[ - ('c', 0, 3, 0), - ('c', 1, 4, 0), - ('b', 0, 2, 0), - ('b', 1, 6, 1), - ], - ), - ]; - let nbr = |ref0, ref1: Option| { - Some(NeighbourRef { - is_inter: true, - ref0, - ref1, - uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)), - }) + let (a, a1) = above_refs; + let (l, l1) = left_refs; + let ctx_of = |sel: usize| match sel { + 1 => single_ref_p1_ctx(a, a1, l, l1), + 2 => single_ref_p2_ctx(a, a1, l, l1), + 3 => single_ref_p3_ctx(a, a1, l, l1), + 4 => single_ref_p4_ctx(a, a1, l, l1), + 5 => single_ref_p5_ctx(a, a1, l, l1), + 6 => single_ref_p6_ctx(a, a1, l, l1), + _ => uni_comp_ref_p1_ctx(a, a1, l, l1), }; - // No neighbours (every context zero), then a mixed pair that puts the - // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0. - for (above_nbr, left_nbr, above_refs, left_refs) in [ - (None, None, (None, None), (None, None)), - ( - nbr(LAST_FRAME, None), - nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)), - (Some(LAST_FRAME), None), - (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)), - ), - ] { - let stack = crate::mvstack::MvStack { - above_nbr, - left_nbr, - above_refs, - left_refs, - ..bare_stack() - }; - let (a, a1) = above_refs; - let (l, l1) = left_refs; - let ctx_of = |sel: usize| match sel { - 1 => single_ref_p1_ctx(a, a1, l, l1), - 2 => single_ref_p2_ctx(a, a1, l, l1), - 3 => single_ref_p3_ctx(a, a1, l, l1), - 4 => single_ref_p4_ctx(a, a1, l, l1), - 5 => single_ref_p5_ctx(a, a1, l, l1), - 6 => single_ref_p6_ctx(a, a1, l, l1), - _ => uni_comp_ref_p1_ctx(a, a1, l, l1), - }; - for (pair, unidir, symbols) in cases { - let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1) - + b( - &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)], - usize::from(!unidir), - ); - for &(table, p, sel, v) in symbols { - let row = ctx_of(sel); - want += match table { - 'u' => b(&UNI_COMP_REF[row][p], v), - 'c' => b(&COMP_REF[row][p], v), - _ => b(&COMP_BWDREF[row][p], v), - }; - } - let got = super::compound_ref_bits(pair, &stack); - assert!( - (got - want).abs() < 1e-9, - "pair {pair:?} above {above_refs:?} left {left_refs:?}: \ - priced {got} bits, writer codes {want}" + for (pair, unidir, symbols) in cases { + let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1) + + b( + &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)], + usize::from(!unidir), ); + for &(table, p, sel, v) in symbols { + let row = ctx_of(sel); + want += match table { + 'u' => b(&UNI_COMP_REF[row][p], v), + 'c' => b(&COMP_REF[row][p], v), + _ => b(&COMP_BWDREF[row][p], v), + }; } + let got = super::compound_ref_bits(pair, &stack); + assert!( + (got - want).abs() < 1e-9, + "pair {pair:?} above {above_refs:?} left {left_refs:?}: \ + priced {got} bits, writer codes {want}" + ); } } +} - /// The `skip` and `is_inter` symbols are priced at the SAME context - /// tile.rs codes them with -- `above_skip + left_skip` for the first and - /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx - /// on every neighbour configuration whose context is not zero (class - /// pricer-context-zero). - #[test] - fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() { - use crate::cdf::{INTRA_INTER, SKIP}; - use crate::encode::symbol_bits as b; - use crate::mvstack::NeighbourRef; - let nbr = |is_inter| NeighbourRef { - is_inter, - ref0: if is_inter { - crate::mvstack::LAST_FRAME - } else { - 0 - }, - ref1: None, - uni: false, +/// The `skip` and `is_inter` symbols are priced at the SAME context +/// tile.rs codes them with -- `above_skip + left_skip` for the first and +/// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx +/// on every neighbour configuration whose context is not zero (class +/// pricer-context-zero). +#[test] +fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() { + use crate::cdf::{INTRA_INTER, SKIP}; + use crate::encode::symbol_bits as b; + use crate::mvstack::NeighbourRef; + let nbr = |is_inter| NeighbourRef { + is_inter, + ref0: if is_inter { + crate::mvstack::LAST_FRAME + } else { + 0 + }, + ref1: None, + uni: false, + }; + for (above, left, above_skip, left_skip) in [ + (None, None, false, false), + (Some(nbr(true)), Some(nbr(true)), true, false), + (Some(nbr(false)), Some(nbr(false)), true, true), + (Some(nbr(false)), None, false, true), + (None, Some(nbr(true)), true, true), + ] { + let stack = crate::mvstack::MvStack { + above_nbr: above, + left_nbr: left, + above_skip, + left_skip, + ..bare_stack() }; - for (above, left, above_skip, left_skip) in [ - (None, None, false, false), - (Some(nbr(true)), Some(nbr(true)), true, false), - (Some(nbr(false)), Some(nbr(false)), true, true), - (Some(nbr(false)), None, false, true), - (None, Some(nbr(true)), true, true), - ] { - let stack = crate::mvstack::MvStack { - above_nbr: above, - left_nbr: left, - above_skip, - left_skip, - ..bare_stack() - }; - let skip_ctx = usize::from(above_skip) + usize::from(left_skip); - let ii_ctx = crate::tile::intra_inter_ctx( - above.is_some(), - left.is_some(), - above.is_some_and(|n| n.is_inter), - left.is_some_and(|n| n.is_inter), + let skip_ctx = usize::from(above_skip) + usize::from(left_skip); + let ii_ctx = crate::tile::intra_inter_ctx( + above.is_some(), + left.is_some(), + above.is_some_and(|n| n.is_inter), + left.is_some_and(|n| n.is_inter), + ); + for v in [false, true] { + let (got, want) = ( + super::skip_bits_at(&stack, v), + b(&SKIP[skip_ctx], usize::from(v)), + ); + assert!( + (got - want).abs() < 1e-9, + "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}" + ); + let (got, want) = ( + super::intra_inter_bits_at(&stack, v), + b(&INTRA_INTER[ii_ctx], usize::from(v)), + ); + assert!( + (got - want).abs() < 1e-9, + "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}" ); - for v in [false, true] { - let (got, want) = ( - super::skip_bits_at(&stack, v), - b(&SKIP[skip_ctx], usize::from(v)), - ); - assert!( - (got - want).abs() < 1e-9, - "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}" - ); - let (got, want) = ( - super::intra_inter_bits_at(&stack, v), - b(&INTRA_INTER[ii_ctx], usize::from(v)), - ); - assert!( - (got - want).abs() < 1e-9, - "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}" - ); - } } } +} - /// [`super::single_ref_bits`] pays exactly what tile.rs' - /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD - /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at - /// the context that symbol's own `single_ref_p*_ctx` derives from the - /// block's above/left neighbours. Red before lane-pricer, where every - /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0. - #[test] - fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() { - use crate::cdf::SINGLE_REF as SR; - use crate::encode::symbol_bits as b; - use crate::mvstack::{ - ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, - LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, - single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, - }; - let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack { - above_refs, - left_refs, - above_nbr, - left_nbr, - ..bare_stack() - }; - let nbr = |ref0, ref1| { - Some(crate::mvstack::NeighbourRef { - is_inter: true, - ref0, - ref1, - uni: false, - }) +/// [`super::single_ref_bits`] pays exactly what tile.rs' +/// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD +/// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at +/// the context that symbol's own `single_ref_p*_ctx` derives from the +/// block's above/left neighbours. Red before lane-pricer, where every +/// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0. +#[test] +fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() { + use crate::cdf::SINGLE_REF as SR; + use crate::encode::symbol_bits as b; + use crate::mvstack::{ + ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, + LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, + single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, + }; + let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack { + above_refs, + left_refs, + above_nbr, + left_nbr, + ..bare_stack() + }; + let nbr = |ref0, ref1| { + Some(crate::mvstack::NeighbourRef { + is_inter: true, + ref0, + ref1, + uni: false, + }) + }; + // (reference, the symbols `write_single_ref` emits as (p index, value)) + let cases: [(i8, &[(usize, usize)]); 7] = [ + (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]), + (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]), + (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]), + (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]), + (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]), + (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]), + (ALTREF_FRAME, &[(0, 1), (1, 1)]), + ]; + // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair + // that puts every p* context on a different row -- the second with a + // COMPOUND left neighbour, which is what takes `reference_mode_ctx` + // off row 0. + for (above_refs, left_refs, above_nbr, left_nbr) in [ + ((None, None), (None, None), None, None), + ( + (Some(LAST_FRAME), None), + (Some(ALTREF_FRAME), Some(LAST_FRAME)), + nbr(LAST_FRAME, None), + nbr(ALTREF_FRAME, Some(LAST_FRAME)), + ), + ] { + let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr); + let (a, a1) = above_refs; + let (l, l1) = left_refs; + let ctx_of = |p: usize| match p { + 0 => single_ref_p1_ctx(a, a1, l, l1), + 1 => single_ref_p2_ctx(a, a1, l, l1), + 2 => single_ref_p3_ctx(a, a1, l, l1), + 3 => single_ref_p4_ctx(a, a1, l, l1), + 4 => single_ref_p5_ctx(a, a1, l, l1), + _ => single_ref_p6_ctx(a, a1, l, l1), }; - // (reference, the symbols `write_single_ref` emits as (p index, value)) - let cases: [(i8, &[(usize, usize)]); 7] = [ - (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]), - (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]), - (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]), - (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]), - (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]), - (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]), - (ALTREF_FRAME, &[(0, 1), (1, 1)]), - ]; - // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair - // that puts every p* context on a different row -- the second with a - // COMPOUND left neighbour, which is what takes `reference_mode_ctx` - // off row 0. - for (above_refs, left_refs, above_nbr, left_nbr) in [ - ((None, None), (None, None), None, None), - ( - (Some(LAST_FRAME), None), - (Some(ALTREF_FRAME), Some(LAST_FRAME)), - nbr(LAST_FRAME, None), - nbr(ALTREF_FRAME, Some(LAST_FRAME)), - ), - ] { - let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr); - let (a, a1) = above_refs; - let (l, l1) = left_refs; - let ctx_of = |p: usize| match p { - 0 => single_ref_p1_ctx(a, a1, l, l1), - 1 => single_ref_p2_ctx(a, a1, l, l1), - 2 => single_ref_p3_ctx(a, a1, l, l1), - 3 => single_ref_p4_ctx(a, a1, l, l1), - 4 => single_ref_p5_ctx(a, a1, l, l1), - _ => single_ref_p6_ctx(a, a1, l, l1), - }; - for (ref_frame, symbols) in cases { - // Plus the `comp_mode = 0` symbol the writer codes ahead of - // the reference syntax on a `reference_select` frame. - let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum(); - if super::reference_select() { - want += b( - &crate::cdf::COMP_MODE - [crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)], - 0, - ); - } - let got = super::single_ref_bits(ref_frame, &stack); - assert!( - (got - want).abs() < 1e-9, - "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \ - priced {got} bits, writer codes {want}" + for (ref_frame, symbols) in cases { + // Plus the `comp_mode = 0` symbol the writer codes ahead of + // the reference syntax on a `reference_select` frame. + let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum(); + if super::reference_select() { + want += b( + &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)], + 0, ); } + let got = super::single_ref_bits(ref_frame, &stack); + assert!( + (got - want).abs() < 1e-9, + "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \ + priced {got} bits, writer codes {want}" + ); } } +} - /// lane-av1tpl2's propagated map, on the two properties every decision - /// under it rests on: a frame the whole lookahead window repeats exactly - /// (uniform texture) leans on every cell alike, so every factor is 1 and - /// the weighting is a no-op; and where the window really does save bits - /// by predicting -- the textured half of a frame whose other half is - /// flat -- the factor FALLS below 1, i.e. that half is coded more - /// distortion-averse than the half nothing gains from. - /// The distortion metric itself (lane-sse): a block the true frame edge - /// cuts through is scored over its INSIDE part only, so a difference that - /// lives entirely in the padding costs nothing and a block wholly past - /// the edge scores zero. Before this, the search ranked modes, - /// transforms and partition trees on samples the display crop throws - /// away -- which lane-b64b had fixed for the 64x64 root alone. - #[test] - fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() { - // A 40x40 true frame on a 64x64 padded coding surface. - let source = vec![10u8; 64 * 64]; - let plane = fresh_plane(&source, 64, 64, 40, 40); - let mut reconstruction = vec![10u8; 64 * 64]; - // Off by 190 at (50, 50) -- past the true edge in both axes. - reconstruction[50 * 64 + 50] = 200; - assert_eq!( - plane.block_sse(0, 0, 64, &reconstruction), - 0.0, - "padding was scored" - ); - // Off by 10 at (39, 39) -- the last sample the decoder shows. - reconstruction[39 * 64 + 39] = 20; - assert_eq!( - plane.block_sse(0, 0, 64, &reconstruction), - 100.0, - "inside was not scored" - ); - // A 16x16 block whose every sample is padding. - let block = vec![200u8; 16 * 16]; - assert_eq!( - plane.block_sse(48, 0, 16, &block), - 0.0, - "a block past the edge scored" - ); - // A 16x16 block the edge cuts: 8 of its columns are inside. - assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0); - } +/// lane-av1tpl2's propagated map, on the two properties every decision +/// under it rests on: a frame the whole lookahead window repeats exactly +/// (uniform texture) leans on every cell alike, so every factor is 1 and +/// the weighting is a no-op; and where the window really does save bits +/// by predicting -- the textured half of a frame whose other half is +/// flat -- the factor FALLS below 1, i.e. that half is coded more +/// distortion-averse than the half nothing gains from. +/// The distortion metric itself (lane-sse): a block the true frame edge +/// cuts through is scored over its INSIDE part only, so a difference that +/// lives entirely in the padding costs nothing and a block wholly past +/// the edge scores zero. Before this, the search ranked modes, +/// transforms and partition trees on samples the display crop throws +/// away -- which lane-b64b had fixed for the 64x64 root alone. +#[test] +fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() { + // A 40x40 true frame on a 64x64 padded coding surface. + let source = vec![10u8; 64 * 64]; + let plane = fresh_plane(&source, 64, 64, 40, 40); + let mut reconstruction = vec![10u8; 64 * 64]; + // Off by 190 at (50, 50) -- past the true edge in both axes. + reconstruction[50 * 64 + 50] = 200; + assert_eq!( + plane.block_sse(0, 0, 64, &reconstruction), + 0.0, + "padding was scored" + ); + // Off by 10 at (39, 39) -- the last sample the decoder shows. + reconstruction[39 * 64 + 39] = 20; + assert_eq!( + plane.block_sse(0, 0, 64, &reconstruction), + 100.0, + "inside was not scored" + ); + // A 16x16 block whose every sample is padding. + let block = vec![200u8; 16 * 16]; + assert_eq!( + plane.block_sse(48, 0, 16, &block), + 0.0, + "a block past the edge scored" + ); + // A 16x16 block the edge cuts: 8 of its columns are inside. + assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0); +} - /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must - /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the - /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound. - #[test] - fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() { - let (base, res) = (162u8, 4i32); - let rf = 2.0; - // A superblock the window leans on more than the frame average is - // coded FINER (lower qindex); a slack one coarser; the average one - // exactly at the base. - assert!( - super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, - "leaned-on SB must go finer" - ); - assert!( - super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, - "idle SB must go coarser" - ); - assert_eq!( - super::deltaq_libaom(base, rf, rf, 1.0, res), - base, - "the average SB moves 0" - ); - // Every offset is a whole number of steps and inside +-(res * 9 - 1). - let max = ((res * 9 - 1) / res) * res; - for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] { - for k in [0.5f64, 1.0, 1.5] { - let q = i32::from(super::deltaq_libaom(base, r, rf, k, res)); - let d = q - i32::from(base); - assert_eq!( - d % res, - 0, - "r={r} k={k}: offset {d} is not a whole {res}-step" - ); - assert!( - d.abs() <= max, - "r={r} k={k}: offset {d} past libaom's +-{max}" - ); - } +/// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must +/// spend WHERE THE WINDOW LEANS, stay congruent to the base on the +/// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound. +#[test] +fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() { + let (base, res) = (162u8, 4i32); + let rf = 2.0; + // A superblock the window leans on more than the frame average is + // coded FINER (lower qindex); a slack one coarser; the average one + // exactly at the base. + assert!( + super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, + "leaned-on SB must go finer" + ); + assert!( + super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, + "idle SB must go coarser" + ); + assert_eq!( + super::deltaq_libaom(base, rf, rf, 1.0, res), + base, + "the average SB moves 0" + ); + // Every offset is a whole number of steps and inside +-(res * 9 - 1). + let max = ((res * 9 - 1) / res) * res; + for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] { + for k in [0.5f64, 1.0, 1.5] { + let q = i32::from(super::deltaq_libaom(base, r, rf, k, res)); + let d = q - i32::from(base); + assert_eq!( + d % res, + 0, + "r={r} k={k}: offset {d} is not a whole {res}-step" + ); + assert!( + d.abs() <= max, + "r={r} k={k}: offset {d} past libaom's +-{max}" + ); } - // The clamp is REACHED from both ends, so the bound is a real bound - // and not a formula that never gets there. - assert_eq!( - i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), - -max - ); - assert_eq!( - i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), - max - ); - // A stronger `k` never moves less than a weaker one. - let d = |k: f64| { - (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs() - }; - assert!( - d(0.5) <= d(1.0) && d(1.0) <= d(1.5), - "strength must be monotone: {} {} {}", - d(0.5), - d(1.0), - d(1.5) - ); - // The frame reference is libaom's log-mean: flat in, the same value out. - assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9); } + // The clamp is REACHED from both ends, so the bound is a real bound + // and not a formula that never gets there. + assert_eq!( + i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), + -max + ); + assert_eq!( + i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), + max + ); + // A stronger `k` never moves less than a weaker one. + let d = + |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs(); + assert!( + d(0.5) <= d(1.0) && d(1.0) <= d(1.5), + "strength must be monotone: {} {} {}", + d(0.5), + d(1.0), + d(1.5) + ); + // The frame reference is libaom's log-mean: flat in, the same value out. + assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9); +} + +/// lane-arfq: the per-level `delta_q` strength -- the spec parses onto +/// [`super::DqLevel`]'s own indices, a missing or broken field keeps the +/// shipped default, and the multiplier reaches the strength. +#[test] +fn the_per_level_delta_q_strength_indexes_the_levels_it_names() { + let d = crate::speed::DQ_LEVEL_K; + assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table"); + assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]); + // Short and broken fields fall back per SLOT, not per spec. + assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]); + assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]); + assert_eq!(super::DqLevel::TopArf as usize, 0); + assert_eq!(super::DqLevel::MidArf as usize, 1); + assert_eq!(super::DqLevel::Leaf as usize, 2); +} - /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto - /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the - /// shipped default, and the multiplier reaches the strength. - #[test] - fn the_per_level_delta_q_strength_indexes_the_levels_it_names() { - let d = crate::speed::DQ_LEVEL_K; - assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table"); - assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]); - // Short and broken fields fall back per SLOT, not per spec. - assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]); - assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]); - assert_eq!(super::DqLevel::TopArf as usize, 0); - assert_eq!(super::DqLevel::MidArf as usize, 1); - assert_eq!(super::DqLevel::Leaf as usize, 2); +#[test] +fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { + // Four 64x64 superblocks across: the shipped map forms its ratio per + // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could + // only ever produce one ratio -- and one ratio, mean-normalised, is + // the flat map, whatever the content underneath it. + let (w, h) = (256usize, 64usize); + let uniform: Vec = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); + let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; + let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0); + assert_eq!(f.len(), 64, "16x4 cells of 16x16"); + for (i, &v) in f.iter().enumerate() { + assert!( + (v - 1.0).abs() < 1e-6, + "cell {i} factor {v}, a flat map must move no lambda" + ); } - #[test] - fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { - // Four 64x64 superblocks across: the shipped map forms its ratio per - // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could - // only ever produce one ratio -- and one ratio, mean-normalised, is - // the flat map, whatever the content underneath it. - let (w, h) = (256usize, 64usize); - let uniform: Vec = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); - let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; - let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0); - assert_eq!(f.len(), 64, "16x4 cells of 16x16"); - for (i, &v) in f.iter().enumerate() { + // Left half textured, right half constant: the window saves bits + // predicting the left half and nothing at all on the right. + let split: Vec = (0..w * h) + .map(|i| { + if i % w < w / 2 { + ((i * 37) % 251) as u8 + } else { + 128 + } + }) + .collect(); + let frames: Vec<&[u8]> = vec![&split, &split, &split]; + let cells_x = w / 16; + for k in [0.25f64, 0.5, 1.0, 2.0] { + let (f, _) = super::tpl_lambda_factors(&frames, w, h, k); + for r in 0..h / 16 { + let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); assert!( - (v - 1.0).abs() < 1e-6, - "cell {i} factor {v}, a flat map must move no lambda" + lean < 1.0, + "k={k} row {r}: leaned-on cell factor {lean} must be < 1" + ); + assert!( + idle > 1.0, + "k={k} row {r}: idle cell factor {idle} must be > 1" ); - } - - // Left half textured, right half constant: the window saves bits - // predicting the left half and nothing at all on the right. - let split: Vec = (0..w * h) - .map(|i| { - if i % w < w / 2 { - ((i * 37) % 251) as u8 - } else { - 128 - } - }) - .collect(); - let frames: Vec<&[u8]> = vec![&split, &split, &split]; - let cells_x = w / 16; - for k in [0.25f64, 0.5, 1.0, 2.0] { - let (f, _) = super::tpl_lambda_factors(&frames, w, h, k); - for r in 0..h / 16 { - let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); - assert!( - lean < 1.0, - "k={k} row {r}: leaned-on cell factor {lean} must be < 1" - ); - assert!( - idle > 1.0, - "k={k} row {r}: idle cell factor {idle} must be > 1" - ); - } } } +} - /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a - /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a - /// row holds `32 >> bw_in_mi_log2` bits and the table holds - /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that - /// superblock must therefore hit every bit of the table EXACTLY ONCE. - /// r4's `4 - bw_log2` index halved the row stride: the walk then covered - /// only a quarter of the 16x8 table and read the wrong byte for every - /// block row but the first (silently wrong above-right/below-left - /// availability -- wrong pixels, no error). - #[test] - fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { - for (bw, bh) in [ - (16usize, 8usize), - (8, 16), - (32, 16), - (16, 32), - (64, 32), - (32, 64), +/// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a +/// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a +/// row holds `32 >> bw_in_mi_log2` bits and the table holds +/// `32 >> bh_in_mi_log2` such rows. Walking every block position of that +/// superblock must therefore hit every bit of the table EXACTLY ONCE. +/// r4's `4 - bw_log2` index halved the row stride: the walk then covered +/// only a quarter of the 16x8 table and read the wrong byte for every +/// block row but the first (silently wrong above-right/below-left +/// availability -- wrong pixels, no error). +#[test] +fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { + for (bw, bh) in [ + (16usize, 8usize), + (8, 16), + (32, 16), + (16, 32), + (64, 32), + (32, 64), + ] { + let (bw_log2, bh_log2) = ( + (bw / 4).trailing_zeros() as usize, + (bh / 4).trailing_zeros() as usize, + ); + let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); + for (name, table) in [ + ("has_tr", rect_reach_tables(bw, bh).0), + ("has_bl", rect_reach_tables(bw, bh).1), ] { - let (bw_log2, bh_log2) = ( - (bw / 4).trailing_zeros() as usize, - (bh / 4).trailing_zeros() as usize, + assert_eq!( + table.len() * 8, + rows * cols, + "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" ); - let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); - for (name, table) in [ - ("has_tr", rect_reach_tables(bw, bh).0), - ("has_bl", rect_reach_tables(bw, bh).1), - ] { - assert_eq!( - table.len() * 8, - rows * cols, - "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" - ); - let mut seen = vec![0u32; table.len() * 8]; - for blk_row in 0..rows { - for blk_col in 0..cols { - let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); - assert!( - idx < seen.len(), - "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" - ); - seen[idx] += 1; - } + let mut seen = vec![0u32; table.len() * 8]; + for blk_row in 0..rows { + for blk_col in 0..cols { + let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); + assert!( + idx < seen.len(), + "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" + ); + seen[idx] += 1; } - assert!( - seen.iter().all(|&n| n == 1), - "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ - (row stride is not {cols})" - ); } + assert!( + seen.iter().all(|&n| n == 1), + "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ + (row stride is not {cols})" + ); } } - use super::*; - use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; - use crate::probe::run_with_stdin; - - /// Every rectangular shape this decoder codes, at every position a block - /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`] - /// must answer exactly what libaom's `has_top_right`/`has_bottom_left` - /// (`reconintra.c`) answer, whose bodies are ported below. - /// - /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): - /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the - /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right) - /// and 7 (below-left) of the 21 reachable positions with no gate seeing - /// it. The per-shape `(len, byte sum)` fingerprints below come from the - /// oracle's own arrays, so a re-routed or truncated table fails here even - /// where the two rows happen to agree. - /// - /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/ - /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the - /// callers handle by predicting each transform unit as its own block. - /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's - /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is - /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL - /// (the horizontal shapes, which those partitions never produce). - #[test] - fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { - // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so - // it pins the 64 reach explicitly instead of following the process's - // own superblock knob (`for_encoder`), which made it red under - // `EC_AV1_SB128=1` for no defect of the code under test. - let fctx = &crate::decode::FrameCtx::new(); - // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum). - const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ - (4, 8, 64, 9280, 64, 550), - (8, 4, 64, 3712, 64, 9630), - (8, 16, 16, 2352, 16, 134), - (16, 8, 16, 960, 16, 2400), - (16, 32, 4, 620, 4, 32), - (32, 16, 4, 32, 4, 184), - (32, 64, 1, 127, 1, 0), - (64, 32, 1, 19, 1, 34), - (4, 16, 32, 5472, 32, 14), - (16, 4, 32, 960, 32, 6464), - (8, 32, 8, 1400, 8, 2), - (32, 8, 8, 32, 8, 1136), - (16, 64, 2, 382, 2, 0), - (64, 16, 2, 4, 2, 84), - ]; - /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for - /// a block whose transform covers it whole (`row_off == col_off == 0`, - /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel - /// superblock (`sb_mi_size == 16`). - fn libaom_reach( - bw: usize, - bh: usize, - x: usize, - y: usize, - width: usize, - height: usize, - _fctx: &crate::decode::FrameCtx, - ) -> (bool, bool) { - let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); - let (_bw_unit, bh_unit) = (bw / 4, bh / 4); - let sb_mi_size = 16usize; - let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; - let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; - let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; - let (tr_table, bl_table) = rect_reach_tables(bw, bh); - let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; - // has_top_right: top_available && right_available, then row_off == 0. - let top_right = if y == 0 || x + bw >= width { - false - } else if blk_row_in_sb == 0 { - // (`col_off + tx_wide_unit < plane_bw_unit` above this is - // `bw_unit < bw_unit`, false for a whole-block transform.) - true - } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { - false - } else { - bit(tr_table) - }; - // has_bottom_left: bottom_available && left_available, col_off == 0. - let bottom_left = if x == 0 || y + bh >= height { - false - } else if blk_col_in_sb == 0 { - // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.) - (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size - } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { - false - } else { - bit(bl_table) - }; - (top_right, bottom_left) - } - for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { - let (tr, bl) = rect_reach_tables(bw, bh); - let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::(); - assert_eq!( - (tr.len(), sum(tr), bl.len(), sum(bl)), - (tr_len, tr_sum, bl_len, bl_sum), - "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" - ); - // Two superblocks across and down, so the superblock-relative - // position (and not the frame position) is what decides. - for sb_y in [0usize, 64] { - for sb_x in [0usize, 64] { - for y in (sb_y..sb_y + 64).step_by(bh) { - for x in (sb_x..sb_x + 64).step_by(bw) { - let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); - let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); - assert_eq!( - (got.above_right, got.below_left), - want, - "{bw}x{bh} at ({x}, {y})" - ); - } +} +use super::*; +use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; +use crate::probe::run_with_stdin; + +/// Every rectangular shape this decoder codes, at every position a block +/// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`] +/// must answer exactly what libaom's `has_top_right`/`has_bottom_left` +/// (`reconintra.c`) answer, whose bodies are ported below. +/// +/// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): +/// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the +/// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right) +/// and 7 (below-left) of the 21 reachable positions with no gate seeing +/// it. The per-shape `(len, byte sum)` fingerprints below come from the +/// oracle's own arrays, so a re-routed or truncated table fails here even +/// where the two rows happen to agree. +/// +/// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/ +/// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the +/// callers handle by predicting each transform unit as its own block. +/// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's +/// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is +/// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL +/// (the horizontal shapes, which those partitions never produce). +#[test] +fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { + // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so + // it pins the 64 reach explicitly instead of following the process's + // own superblock knob (`for_encoder`), which made it red under + // `EC_AV1_SB128=1` for no defect of the code under test. + let fctx = &crate::decode::FrameCtx::new(); + // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum). + const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ + (4, 8, 64, 9280, 64, 550), + (8, 4, 64, 3712, 64, 9630), + (8, 16, 16, 2352, 16, 134), + (16, 8, 16, 960, 16, 2400), + (16, 32, 4, 620, 4, 32), + (32, 16, 4, 32, 4, 184), + (32, 64, 1, 127, 1, 0), + (64, 32, 1, 19, 1, 34), + (4, 16, 32, 5472, 32, 14), + (16, 4, 32, 960, 32, 6464), + (8, 32, 8, 1400, 8, 2), + (32, 8, 8, 32, 8, 1136), + (16, 64, 2, 382, 2, 0), + (64, 16, 2, 4, 2, 84), + ]; + /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for + /// a block whose transform covers it whole (`row_off == col_off == 0`, + /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel + /// superblock (`sb_mi_size == 16`). + fn libaom_reach( + bw: usize, + bh: usize, + x: usize, + y: usize, + width: usize, + height: usize, + _fctx: &crate::decode::FrameCtx, + ) -> (bool, bool) { + let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); + let (_bw_unit, bh_unit) = (bw / 4, bh / 4); + let sb_mi_size = 16usize; + let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; + let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; + let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; + let (tr_table, bl_table) = rect_reach_tables(bw, bh); + let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; + // has_top_right: top_available && right_available, then row_off == 0. + let top_right = if y == 0 || x + bw >= width { + false + } else if blk_row_in_sb == 0 { + // (`col_off + tx_wide_unit < plane_bw_unit` above this is + // `bw_unit < bw_unit`, false for a whole-block transform.) + true + } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { + false + } else { + bit(tr_table) + }; + // has_bottom_left: bottom_available && left_available, col_off == 0. + let bottom_left = if x == 0 || y + bh >= height { + false + } else if blk_col_in_sb == 0 { + // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.) + (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size + } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { + false + } else { + bit(bl_table) + }; + (top_right, bottom_left) + } + for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { + let (tr, bl) = rect_reach_tables(bw, bh); + let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::(); + assert_eq!( + (tr.len(), sum(tr), bl.len(), sum(bl)), + (tr_len, tr_sum, bl_len, bl_sum), + "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" + ); + // Two superblocks across and down, so the superblock-relative + // position (and not the frame position) is what decides. + for sb_y in [0usize, 64] { + for sb_x in [0usize, 64] { + for y in (sb_y..sb_y + 64).step_by(bh) { + for x in (sb_x..sb_x + 64).step_by(bw) { + let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); + let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); + assert_eq!( + (got.above_right, got.below_left), + want, + "{bw}x{bh} at ({x}, {y})" + ); } } } } } +} - /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes. - pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { - let out = run_with_stdin( - ec_testkit::ffmpeg().args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width * height / 4); - assert_eq!( - out.stdout.len(), - luma + 2 * chroma, - "expected one 4:2:0 frame" - ); - Picture { - width, - height, - y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), - u: out.stdout[luma..luma + chroma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - v: out.stdout[luma + chroma..] - .iter() - .map(|&v| u16::from(v)) - .collect(), - } +/// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes. +pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { + let out = run_with_stdin( + ec_testkit::ffmpeg().args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", + ]), + stream, + ); + assert!( + out.status.success(), + "ffmpeg refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + assert_eq!( + out.stdout.len(), + luma + 2 * chroma, + "expected one 4:2:0 frame" + ); + Picture { + width, + height, + y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), + u: out.stdout[luma..luma + chroma] + .iter() + .map(|&v| u16::from(v)) + .collect(), + v: out.stdout[luma + chroma..] + .iter() + .map(|&v| u16::from(v)) + .collect(), } +} - /// A picture with something of everything in it: a gradient, an edge, a - /// ripple and a block of flat colour, none of them aligned to the block - /// grid. - /// The in-loop filters actually FIRE and the stream still decodes to - /// exactly what the encoder kept as its reconstruction - /// (gate-blind-to-feature: a filter search that always answered "off" - /// would leave every other test just as green, and the BD gate that - /// would notice is `#[ignore]`d). - /// - /// Run: - /// cargo test -p ec-av1 --release --lib -- \ - /// encode::tests::the_filter_search_picks_real_filters - #[test] - fn the_filter_search_picks_real_filters() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); - let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); - let fired = encoded +/// A picture with something of everything in it: a gradient, an edge, a +/// ripple and a block of flat colour, none of them aligned to the block +/// grid. +/// The in-loop filters actually FIRE and the stream still decodes to +/// exactly what the encoder kept as its reconstruction +/// (gate-blind-to-feature: a filter search that always answered "off" +/// would leave every other test just as green, and the BD gate that +/// would notice is `#[ignore]`d). +/// +/// Run: +/// cargo test -p ec-av1 --release --lib -- \ +/// encode::tests::the_filter_search_picks_real_filters +#[test] +fn the_filter_search_picks_real_filters() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); + let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); + let fired = encoded + .frames + .iter() + .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) + .count(); + assert!( + fired > 0, + "no frame of this sequence chose any in-loop filtering: {:?}", + encoded .frames .iter() - .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) - .count(); - assert!( - fired > 0, - "no frame of this sequence chose any in-loop filtering: {:?}", - encoded - .frames - .iter() - .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) - .collect::>() - ); - // The reconstruction the encoder predicts from is the FILTERED one, - // and it is what a decoder of the stream produces -- byte for byte, - // frame for frame. - let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); - assert_eq!(decoded.len(), encoded.frames.len()); - for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { - assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); - assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); - assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); - } + .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) + .collect::>() + ); + // The reconstruction the encoder predicts from is the FILTERED one, + // and it is what a decoder of the stream produces -- byte for byte, + // frame for frame. + let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); + assert_eq!(decoded.len(), encoded.frames.len()); + for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { + assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); + assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); + assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); } +} - pub(super) fn test_card(width: usize, height: usize) -> Picture { - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let gradient = x as f64 * 200.0 / width as f64; - let ripple = 30.0 - * (x as f64 * std::f64::consts::PI / 23.0).sin() - * (y as f64 * std::f64::consts::PI / 37.0).cos(); - let edge = if x > width * 3 / 7 && y > height / 3 { - 40.0 - } else { - 0.0 - }; - picture.y[y * width + x] = - (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; - } - } - for y in 0..height / 2 { - for x in 0..width / 2 { - let i = y * width / 2 + x; - picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; - picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; - } +pub(super) fn test_card(width: usize, height: usize) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let gradient = x as f64 * 200.0 / width as f64; + let ripple = 30.0 + * (x as f64 * std::f64::consts::PI / 23.0).sin() + * (y as f64 * std::f64::consts::PI / 37.0).cos(); + let edge = if x > width * 3 / 7 && y > height / 3 { + 40.0 + } else { + 0.0 + }; + picture.y[y * width + x] = (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; } - picture } - - pub(super) fn psnr(a: &[u16], b: &[u16]) -> f64 { - let squared: f64 = a - .iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum(); - if squared == 0.0 { - return f64::INFINITY; + for y in 0..height / 2 { + for x in 0..width / 2 { + let i = y * width / 2 + x; + picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; + picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; } - 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() } + picture +} + +pub(super) fn psnr(a: &[u16], b: &[u16]) -> f64 { + let squared: f64 = a + .iter() + .zip(b) + .map(|(&x, &y)| { + let d = f64::from(x) - f64::from(y); + d * d + }) + .sum(); + if squared == 0.0 { + return f64::INFINITY; + } + 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() +} + +/// lane-i64's witness: a smooth gradient is exactly the picture a whole +/// 64x64 intra block predicts as well as four 32x32 ones, so the key +/// frame's new root fires on most superblocks -- and what BOTH decoders +/// produce is the encoder's own reconstruction, sample for sample. +/// +/// The fire count is the `gate-blind-to-feature` guard: without it every +/// assert below passes on a stream that codes no whole superblock at all. +#[test] +fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + // 4 x 3 superblocks, all of them wholly inside the frame. + let (width, height) = (256usize, 192usize); + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16; + } + } + for y in 0..height / 2 { + for x in 0..width / 2 { + picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16; + picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16; + } + } + let _ = take_i64_root_hits(); + let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap(); + let [roots, _offered, _edge] = take_i64_root_hits(); + // The counters are process-global, so another test encoding in + // parallel can only ADD to them -- the per-FRAME fact is the mode + // list, which carries one entry per coded block and so exactly 12 + // when every superblock was coded as one 64x64 intra block. + assert_eq!( + encoded.modes.len(), + 12, + "not every superblock was coded as one 64x64 intra block" + ); + assert!( + roots >= 8, + "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12" + ); + eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12"); + + let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(ours.len(), 1, "our decoder's frames"); + assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma"); + assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U"); + assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V"); + + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); +} + +/// The claim the whole encoder rests on: what a decoder produces is what +/// the encoder said it would, sample for sample, on every plane. +/// +/// Prediction reads the reconstruction, so a single sample of drift +/// anywhere would spread into every block below and to the right of it — +/// which is why this is an equality and not a tolerance. +#[test] +fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + for &(width, height) in &[ + (64usize, 64usize), + (96, 64), + (160, 96), + (32, 48), + (248, 152), + ] { + let picture = test_card(width, height); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!( + decoded.y, encoded.reconstruction.y, + "{width}x{height}: luma" + ); + assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); + } + // One q index from each of the four coefficient-CDF contexts + // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size. + let (width, height) = (64usize, 64usize); + let picture = test_card(width, height); + let _ = take_tx_depth_hits(); + for &q in &[15u8, 45, 100, 200] { + let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); + } + // lane-av1tx: the exactness above is only a claim about SPLIT + // transforms if some block actually split one (`gate-blind-to-feature` + // -- with `tx_depth` stuck at 0 every assert here passes on the + // pre-lane stream). The test card's edges split at these four + // quantizers; the counter is per-process (another test encoding in + // parallel can only ADD to it, so this can be masked, never falsely + // failed), so it is read once for the whole q ladder. + let depths = take_tx_depth_hits(); + assert!( + depths[1] + depths[2] > 0, + "no block split its transform: depths {depths:?}" + ); +} - /// lane-i64's witness: a smooth gradient is exactly the picture a whole - /// 64x64 intra block predicts as well as four 32x32 ones, so the key - /// frame's new root fires on most superblocks -- and what BOTH decoders - /// produce is the encoder's own reconstruction, sample for sample. - /// - /// The fire count is the `gate-blind-to-feature` guard: without it every - /// assert below passes on a stream that codes no whole superblock at all. - #[test] - fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - // 4 x 3 superblocks, all of them wholly inside the frame. - let (width, height) = (256usize, 192usize); - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16; +/// A synthetic screen-content picture -- a few flat colours in a grid of +/// boxes with hard edges and text-like bars, the shape a desktop capture +/// has -- so the palette path is exercised on content it is for. +#[cfg(test)] +pub(super) fn screen_card(width: usize, height: usize) -> Picture { + const INK: [u16; 4] = [16, 90, 180, 235]; + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let cell = (x / 24 + y / 24) % 2; + let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); + picture.y[y * width + x] = INK[cell * 2 + bar]; + } + } + // Four chroma colours, not two: a two-colour chroma block only ever + // codes a `PaletteSizeUV` of 2, which leaves + // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking + // deltas and the neighbour cache flags, exercised only when + // neighbouring blocks share colours) unproven by the ffmpeg oracle. + const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; + const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; + for y in 0..height / 2 { + for x in 0..width / 2 { + let cell = (x / 12 + 2 * (y / 12)) % 4; + picture.u[y * (width / 2) + x] = CHROMA_U[cell]; + picture.v[y * (width / 2) + x] = CHROMA_V[cell]; + } + } + picture +} + +/// The lane's own end-to-end check: on screen content the detector fires, +/// blocks really take a palette (fire count, class +/// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every +/// symbol this lane writes -- reconstructs exactly what the encoder did. +/// The film-shaped `test_card` must NOT trip the detector, which is what +/// keeps every non-screen stream byte-identical. +#[test] +fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (192usize, 96usize); + let _ = crate::tile::take_palette_hits(); + let picture = screen_card(width, height); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + assert!( + encoded.screen, + "the detector did not fire on screen content -- no palette syntax was coded at all" + ); + let hits = crate::tile::take_palette_hits(); + assert!(hits[0] > 0, "no block took a palette: {hits:?}"); + eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); + // The chroma half is a claim about the plane-1 syntax only if some + // block really took a chroma palette (`gate-blind-to-feature`): every + // exactness assert below passes on a stream that codes + // `palette_uv_mode == 0` everywhere. + let uv_hits = crate::tile::take_palette_uv_hits(); + assert!( + uv_hits[0] > 0, + "no block took a chroma palette: {uv_hits:?}" + ); + let uv_cached = crate::tile::take_palette_uv_cache_hits(); + eprintln!( + "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", + uv_hits[0], + &uv_hits[2..] + ); + assert!( + uv_cached > 0, + "no chroma base colour came out of the neighbour cache -- \ + `write_palette_colors_uv`'s cache half is unproven by the oracle below" + ); + let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); + assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); + assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); + assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); + // A whole GOP: the inter frames' own intra blocks carry the palette + // syntax too (the three intra arms of the inter writers), which only + // ffmpeg reading the frames back can prove. + let moved: Vec = (0..4) + .map(|f| { + let base = screen_card(width, height); + let mut out = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let sx = (x + f * 7) % width; + out.y[y * width + x] = base.y[y * width + sx]; + } } - } - for y in 0..height / 2 { - for x in 0..width / 2 { - picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16; - picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16; + for y in 0..height / 2 { + for x in 0..width / 2 { + let sx = (x + f * 3) % (width / 2); + out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; + out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; + } } - } - let _ = take_i64_root_hits(); - let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap(); - let [roots, _offered, _edge] = take_i64_root_hits(); - // The counters are process-global, so another test encoding in - // parallel can only ADD to them -- the per-FRAME fact is the mode - // list, which carries one entry per coded block and so exactly 12 - // when every superblock was coded as one 64x64 intra block. + out + }) + .collect(); + let _ = crate::tile::take_palette_hits(); + let _ = crate::tile::take_palette_uv_hits(); + let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); + let gop_hits = crate::tile::take_palette_hits(); + let gop_uv_hits = crate::tile::take_palette_uv_hits(); + let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); + eprintln!( + "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ + {} chroma palette blocks", + inter_screen, gop_hits[0], gop_uv_hits[0] + ); + assert!( + gop_uv_hits[0] > 0, + "no block of the GOP took a chroma palette: {gop_uv_hits:?}" + ); + assert!( + inter_screen > 0, + "no inter frame set allow_screen_content_tools" + ); + let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); + assert_eq!( + gop_decoded.len(), + gop.frames.len(), + "our decoder: GOP frame count" + ); + for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { assert_eq!( - encoded.modes.len(), - 12, - "not every superblock was coded as one 64x64 intra block" - ); - assert!( - roots >= 8, - "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12" + ours.y, frame.reconstruction.y, + "our decoder: GOP frame {i} luma" ); - eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12"); - - let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(ours.len(), 1, "our decoder's frames"); - assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma"); - assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U"); - assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V"); - - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); } - - /// The claim the whole encoder rests on: what a decoder produces is what - /// the encoder said it would, sample for sample, on every plane. - /// - /// Prediction reads the reconstruction, so a single sample of drift - /// anywhere would spread into every block below and to the right of it — - /// which is why this is an equality and not a tolerance. - #[test] - fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for &(width, height) in &[ - (64usize, 64usize), - (96, 64), - (160, 96), - (32, 48), - (248, 152), - ] { - let picture = test_card(width, height); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let decoded = ffmpeg_decode(&encoded.stream, width, height); + { + let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); + assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count"); + for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { assert_eq!( - decoded.y, encoded.reconstruction.y, - "{width}x{height}: luma" + theirs.y, frame.reconstruction.y, + "ffmpeg: GOP frame {i} luma" ); - assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); - } - // One q index from each of the four coefficient-CDF contexts - // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size. - let (width, height) = (64usize, 64usize); - let picture = test_card(width, height); - let _ = take_tx_depth_hits(); - for &q in &[15u8, 45, 100, 200] { - let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); + assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); + assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); } - // lane-av1tx: the exactness above is only a claim about SPLIT - // transforms if some block actually split one (`gate-blind-to-feature` - // -- with `tx_depth` stuck at 0 every assert here passes on the - // pre-lane stream). The test card's edges split at these four - // quantizers; the counter is per-process (another test encoding in - // parallel can only ADD to it, so this can be masked, never falsely - // failed), so it is read once for the whole q ladder. - let depths = take_tx_depth_hits(); - assert!( - depths[1] + depths[2] > 0, - "no block split its transform: depths {depths:?}" - ); } - /// A synthetic screen-content picture -- a few flat colours in a grid of - /// boxes with hard edges and text-like bars, the shape a desktop capture - /// has -- so the palette path is exercised on content it is for. - #[cfg(test)] - pub(super) fn screen_card(width: usize, height: usize) -> Picture { - const INK: [u16; 4] = [16, 90, 180, 235]; - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let cell = (x / 24 + y / 24) % 2; - let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); - picture.y[y * width + x] = INK[cell * 2 + bar]; - } - } - // Four chroma colours, not two: a two-colour chroma block only ever - // codes a `PaletteSizeUV` of 2, which leaves - // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking - // deltas and the neighbour cache flags, exercised only when - // neighbouring blocks share colours) unproven by the ffmpeg oracle. - const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; - const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; - for y in 0..height / 2 { - for x in 0..width / 2 { - let cell = (x / 12 + 2 * (y / 12)) % 4; - picture.u[y * (width / 2) + x] = CHROMA_U[cell]; - picture.v[y * (width / 2) + x] = CHROMA_V[cell]; - } - } - picture - } - - /// The lane's own end-to-end check: on screen content the detector fires, - /// blocks really take a palette (fire count, class - /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every - /// symbol this lane writes -- reconstructs exactly what the encoder did. - /// The film-shaped `test_card` must NOT trip the detector, which is what - /// keeps every non-screen stream byte-identical. - #[test] - fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (192usize, 96usize); - let _ = crate::tile::take_palette_hits(); - let picture = screen_card(width, height); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - assert!( - encoded.screen, - "the detector did not fire on screen content -- no palette syntax was coded at all" - ); - let hits = crate::tile::take_palette_hits(); - assert!(hits[0] > 0, "no block took a palette: {hits:?}"); - eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); - // The chroma half is a claim about the plane-1 syntax only if some - // block really took a chroma palette (`gate-blind-to-feature`): every - // exactness assert below passes on a stream that codes - // `palette_uv_mode == 0` everywhere. - let uv_hits = crate::tile::take_palette_uv_hits(); - assert!( - uv_hits[0] > 0, - "no block took a chroma palette: {uv_hits:?}" - ); - let uv_cached = crate::tile::take_palette_uv_cache_hits(); - eprintln!( - "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", - uv_hits[0], - &uv_hits[2..] - ); - assert!( - uv_cached > 0, - "no chroma base colour came out of the neighbour cache -- \ - `write_palette_colors_uv`'s cache half is unproven by the oracle below" - ); - let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); - assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); - assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); - assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); - // A whole GOP: the inter frames' own intra blocks carry the palette - // syntax too (the three intra arms of the inter writers), which only - // ffmpeg reading the frames back can prove. - let moved: Vec = (0..4) - .map(|f| { - let base = screen_card(width, height); - let mut out = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let sx = (x + f * 7) % width; - out.y[y * width + x] = base.y[y * width + sx]; - } - } - for y in 0..height / 2 { - for x in 0..width / 2 { - let sx = (x + f * 3) % (width / 2); - out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; - out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; - } - } - out - }) - .collect(); - let _ = crate::tile::take_palette_hits(); - let _ = crate::tile::take_palette_uv_hits(); - let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); - let gop_hits = crate::tile::take_palette_hits(); - let gop_uv_hits = crate::tile::take_palette_uv_hits(); - let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); - eprintln!( - "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ - {} chroma palette blocks", - inter_screen, gop_hits[0], gop_uv_hits[0] - ); - assert!( - gop_uv_hits[0] > 0, - "no block of the GOP took a chroma palette: {gop_uv_hits:?}" - ); - assert!( - inter_screen > 0, - "no inter frame set allow_screen_content_tools" - ); - let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); - assert_eq!( - gop_decoded.len(), - gop.frames.len(), - "our decoder: GOP frame count" - ); - for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { - assert_eq!( - ours.y, frame.reconstruction.y, - "our decoder: GOP frame {i} luma" - ); - } - { - let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); - assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count"); - for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { - assert_eq!( - theirs.y, frame.reconstruction.y, - "ffmpeg: GOP frame {i} luma" - ); - assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); - assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); - } - } - - // The other half of the keep rule: film-shaped content leaves the - // detector (and so the whole sequence header) alone. - let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); - assert!( - !film.screen, - "the detector fired on the film-shaped test card" - ); - } - - /// lane-av1paletteuv: the census for `crate::tile::palette_uv_side`, the - /// `(side / 2).max(4)` named in `lanes/av1subsizesweep.report.md` as a - /// "4:2:2/4:4:0 palette map mis-sized" site. - /// - /// **What the site computes.** libaom reads the plane-1 colour-index map - /// at `av1_get_block_dimensions(bsize, 1, xd)` (blockd.h:1512): per axis, - /// `plane_block = block >> ss`, then `+2` when that came out under 4 - /// (the chroma sub-8x8 bump, blockd.h:1533-1541). For a SQUARE 4:2:0 - /// block both axes carry `ss = 1`, so both come to `side / 2` with the - /// bump -- which is exactly `(side / 2).max(4)`. The value is right. - /// - /// **What it is not.** At 4:2:2 the correct map is `(side >> 1) x side` - /// and at 4:4:4 it is `side x side` -- neither is square. So the value is - /// 4:2:0-only BY CONSTRUCTION, and this gate is what keeps it that way: - /// if an encoder that can emit another chroma shape ever appears, this - /// reds rather than the writer silently writing a half-height map. - /// - /// The three arms are (1) the value matches libaom's own per-axis - /// formula at 4:2:0 over every side the palette syntax admits, (2) no - /// reachable writer path can be handed another chroma shape, (3) a real - /// encode really fires chroma palettes, so arm 1 is not arithmetic on a - /// function nothing calls (class `gate-blind-to-feature`). - #[test] - fn the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it() { - const NAME: &str = - "the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it"; - let encode_src = crate::test_source::module_source("encode"); - - // ---- arm 1: the value, against libaom's formula -------------------- - // blockd.h:1530-1541, transcribed. A plane_block under 4 gains 2. - let libaom_plane1 = |block: usize, ss: usize| { - let plane_block = block >> ss; - plane_block + 2 * usize::from(plane_block < 4) - }; - let mut admitted = 0usize; - for side in 4usize..=64 { - // `palette_bsize_ctx`'s own domain: both sides <= 64 and - // bw * bh >= 64 (`av1_allow_palette`). A side outside it codes no - // palette syntax at all, so its map size is unobservable. - if side > 64 || side * side < 64 { - continue; - } - admitted += 1; - let want_x = libaom_plane1(side, 1); - let want_y = libaom_plane1(side, 1); - assert_eq!(want_x, want_y, "{NAME}: 4:2:0 arms the libaom formula"); - assert_eq!( - crate::tile::palette_uv_side(side), - want_x, - "{NAME}: side {side} -- palette_uv_side disagrees with libaom's plane-1 block" - ); - } - assert_eq!( - admitted, 57, - "{NAME}: the sweep admitted {admitted} sides, expected 57 (every integer 8..=64 -- \ - `palette_bsize_ctx`'s whole square domain, not just the powers of two a real block \ - takes) -- it must cover that domain, or it is not measuring it" - ); - - // Why `.max(4)` cannot fire, stated as a measurement rather than left - // for a reader to assume: `palette_bsize_ctx` refuses `bw * bh < 64`, - // so the smallest admitted square side is 8, whose halved plane block - // is already 4. The floor's only reachable input would be a side - // under 8, and libaom's own chroma sub-8x8 bump (+2) is likewise - // unreachable there. Dropping the floor is therefore NOT a witness - // mutation for this gate -- the mutation that bites is dropping the - // halving (measured, see the lane report) -- and this arm says why, - // so nobody later mistakes a green floor mutation for coverage. - for side in [8usize, 16, 32, 64] { - assert!( - side / 2 >= 4 && libaom_plane1(side, 1) == side / 2, - "{NAME}: side {side} -- the admitted domain moved, so `.max(4)` may now be \ - reachable and the floor needs a witness mutation of its own" - ); - } - - // The claim the gate rests on, stated as arithmetic so a future - // reader cannot mistake "correct" for "correct at any shape": at - // these shapes the per-axis answer is NOT this square. - for side in [8usize, 16, 32, 64] { - let square = crate::tile::palette_uv_side(side); - let want_422 = (libaom_plane1(side, 1), libaom_plane1(side, 0)); - let want_444 = (libaom_plane1(side, 0), libaom_plane1(side, 0)); - assert_ne!( - (square, square), - want_422, - "{NAME}: side {side} -- a square map IS the 4:2:2 map, so this gate's premise \ - (the site is 4:2:0-only) is wrong" - ); - assert_ne!( - (square, square), - want_444, - "{NAME}: side {side} -- a square map IS the 4:4:4 map" - ); - } - - // ---- arm 2: nothing can hand the writer another shape -------------- - // (a) Every non-test `ColorConfig` literal in the encoder names - // subsampling (1, 1). These are the two constructors the whole - // encoder reaches its colour config through; the test-module copies - // are excluded by scanning only the pre-`mod tests` prefix. The cut - // matches an inline `mod tests {` body only, so a `mod tests;` file - // declaration does not truncate the production files after it. - fn head(src: &str) -> &str { - let cut = src.find("\nmod tests {").unwrap_or(src.len()); - &src[..cut] - } - for (label, src) in [ - ("encode.rs", head(crate::test_source::module_production_source("encode"))), - ("encoder.rs", head(crate::test_source::module_production_source("encoder"))), - ] { - // Every `subsampling_*` the non-test encoder names, counted: a - // `(0, y)` or `(1, 0)` here is a chroma shape - // `palette_uv_side` cannot express. The one value allowed is 1 - // -- 4:2:0, the shape the square map is the right size for. - let mut shapes: std::collections::BTreeSet<(usize, usize)> = Default::default(); - for (sx, _) in src.match_indices("subsampling_x:") { - let rest = &src[sx + "subsampling_x:".len()..]; - let digits = |s: &str| { - s.trim_start() - .split(|c: char| !c.is_ascii_digit()) - .next() - .and_then(|d| d.parse::().ok()) - .unwrap_or(usize::MAX) - }; - let x = digits(rest); - let y = rest - .find("subsampling_y:") - .map(|y| digits(&rest[y + "subsampling_y:".len()..])) - .unwrap_or(usize::MAX); - shapes.insert((x, y)); - } - assert_eq!( - shapes, - std::collections::BTreeSet::from([(1usize, 1usize)]), - "{NAME}: the non-test {label} names chroma shapes {shapes:?} -- any shape other \ - than 4:2:0 is one palette_uv_side's square map cannot express (at 4:2:2 the \ - map is (side >> 1) x side, at 4:4:4 side x side)" - ); - } - - // (b) `key_frame_headers_colour` is the only PUBLIC entry that takes - // a caller-chosen ColorConfig -- it is how a 4:2:2 or 4:4:4 header is - // written at all -- so it is the one door a non-4:2:0 shape comes - // through. It builds HEADERS only: no tile writer is reachable from - // its body. (Its own doc says so; this measures it.) - let headers_at = encode_src - .find("pub fn key_frame_headers_colour(") - .expect("key_frame_headers_colour is gone -- re-derive this arm's scan anchor"); - let body_end = encode_src[headers_at..] - .find("\npub fn ") - .map(|n| headers_at + n) - .unwrap_or(encode_src.len()); - let headers_body = &encode_src[headers_at..body_end]; - for writer in [ - "write_palette_syntax", - "write_color_index_map", - "encode_key_frame_inner", - "tile::", - ] { - assert!( - !headers_body.contains(writer), - "{NAME}: key_frame_headers_colour now reaches {writer} -- a caller can pair a \ - 4:2:2/4:4:4 header with a tile, and palette_uv_side writes a square map into \ - the per-axis slot libaom reads as (side >> ss_x) x (side >> ss_y)" - ); - } - - // (c) Every tile-producing entry point goes through - // `encode_key_frame_inner`, whose five non-test call sites all pass - // one of the two 4:2:0 constructors above. Counted over the - // non-test source only, so a new road is a red rather than a line - // somebody has to notice. - let inner_calls = head(crate::test_source::module_production_source("encode")).matches("encode_key_frame_inner(").count() - + head(crate::test_source::module_production_source("encoder")).matches("encode_key_frame_inner(").count() - - 1; // the definition itself - assert_eq!( - inner_calls, 5, - "{NAME}: encode_key_frame_inner has {inner_calls} non-test call sites, expected 5 -- \ - a new one must pass a colour config this gate has read" - ); - - // (d) The picture itself is 4:2:0-shaped at the door, so a 4:2:2 or - // 4:4:4 frame cannot even be handed to an encode entry. Measured by - // calling `check`, not by reading it. - for (label, divisor) in [("4:2:2", 2usize), ("4:4:4", 1)] { - let p = Picture { - width: 64, - height: 64, - y: vec![0; 64 * 64], - u: vec![0; 64 * 64 / divisor], - v: vec![0; 64 * 64 / divisor], - }; - assert!( - p.check().is_err(), - "{NAME}: Picture::check accepted a {label}-shaped picture -- if the encoder can be \ - fed one, palette_uv_side's square map is wrong by construction" - ); - } - - // ---- arm 3: the site really fires --------------------------------- - // Without this, arms 1 and 2 are arithmetic and a source scan over a - // function no encode reaches (class `gate-blind-to-feature`). - // - // The fire count is the DECODER's thread-local one, not the writer's - // process-global `tile::take_palette_uv_hits`: that one is a - // swap-to-zero, so a parallel sibling test's encode steals this test's - // count (measured: it read `[0; 9]` under `cargo test palette`, and - // passed alone). Round-tripping the stream instead also proves the - // stronger half -- the reader took the map at the extent the WRITER - // sized, which is what makes the square value right rather than merely - // unchallenged. - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let before = crate::decode::palette_uv_hits(); - let encoded = encode_key_frame_with_ctx(&screen_card(192, 96), 100, 0.5, fctx).unwrap(); - let decoded = crate::stream::decode_stream(&encoded.stream) - .unwrap_or_else(|e| panic!("{NAME}: our own stream refused: {e}")); - let fired = crate::decode::palette_uv_hits() - before; - assert!( - fired > 0, - "{NAME}: no block took a chroma palette -- palette_uv_side was never exercised, so \ - this gate measures nothing" - ); - assert_eq!( - decoded[0].u, encoded.reconstruction.u, - "{NAME}: the decoder did not read the chroma map at the extent the writer sized it" - ); - assert_eq!( - decoded[0].v, encoded.reconstruction.v, - "{NAME}: the decoder did not read the chroma map at the extent the writer sized it" - ); - eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped"); - } - - /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card - /// sets `allow_intrabc` (so every in-loop filter is off), blocks really - /// take a block vector (fire count + DV histogram, class - /// `gate-blind-to-feature`), and both our own decoder and ffmpeg -- - /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct - /// exactly what the encoder did. - #[test] - fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4 - // superblocks of 64) and tall enough for a source superblock row - // above the blocks that copy from it. - let (width, height) = (512usize, 256usize); - let picture = screen_card(width, height); - let _ = crate::tile::take_intrabc_hits(); - // The default is OFF (it measured worse on the real screen capture -- - // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns - // the arm on for its own encode and puts it back straight after. - force_intrabc(Some(true)); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - force_intrabc(None); - assert!( - encoded.allow_intrabc, - "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)", - intrabc_source_share() * 100.0 - ); - let hits = crate::tile::take_intrabc_hits(); - eprintln!( - "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%", - hits[0], - &hits[1..], - intrabc_source_share() * 100.0 - ); - let search = take_intrabc_search(); - eprintln!( - "intrabc searches {} found-valid {} won-RD {}", - search[0], search[1], search[2] - ); - assert!( - hits[0] > 0, - "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}" - ); - let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); - assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); - assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); - assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); - } + // The other half of the keep rule: film-shaped content leaves the + // detector (and so the whole sequence header) alone. + let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); + assert!( + !film.screen, + "the detector fired on the film-shaped test card" + ); +} - /// The minimal repro that isolated the inter-residual desync: a key frame - /// followed by one inter frame whose single superblock carries one - /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma - /// coefficient, its three sibling blocks all `skip: true`. Before the - /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data - /// found when processing input") even though every symbol either block - /// codes is otherwise proven (all-skip inter blocks decode clean, and the - /// same coefficient syntax decodes clean on every intra key-frame gate). - #[test] - fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (64usize, 64usize); - let picture = Picture::grey(width, height); - let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - - let (seq, _) = key_frame_headers(width, height, 100).unwrap(); - let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); - - let residual_block = BlockCoeffs { - luma_tx_types: Vec::new(), - angle_delta_y: 0, - cfl_alphas: None, - filter_intra: None, - luma: vec![Coeff { - row: 0, - col: 0, - level: 4, - }], - u: Vec::new(), - v: Vec::new(), - mode: 0, - uv_mode: 0, - skip: false, - eight: None, - dv: None, - palette: None, - palette_uv: None, - tx_depth: 0, - inter: Some(InterInfo { - ref1: None, - mv1: (0, 0), - ref_frame: crate::mvstack::LAST_FRAME, - mode: InterMode::NearestMv, - mv: (0, 0), - ref_mv_idx: 0, - }), - motion_mode: 0, - }; - let skipped_block = BlockCoeffs { - skip: true, - inter: Some(InterInfo { - ref1: None, - mv1: (0, 0), - ref_frame: crate::mvstack::LAST_FRAME, - mode: InterMode::NearestMv, - mv: (0, 0), - ref_mv_idx: 0, - }), - ..BlockCoeffs::default() - }; - let blocks = vec![ - Quadrant::Whole(residual_block), - Quadrant::Whole(skipped_block.clone()), - Quadrant::Whole(skipped_block.clone()), - Quadrant::Whole(skipped_block), - ]; - // lane-av1obmc: the header this tile is decoded under carries - // `is_motion_mode_switchable`, so the writer must be armed with it - // too or the decoder reads a `motion_mode` symbol nobody wrote. - crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable); - crate::tile::arm_warped_motion(inter_header.allow_warped_motion); - let tile = crate::tile::sb_coeff_inter_frame_tile( - inter_header.mi_cols, - inter_header.mi_rows, - 100, - &blocks, - ) - .unwrap(); - - // `key.stream` is already a temporal delimiter, the sequence header - // and the key frame's own OBU (`encode_key_frame` built it from the - // same `key_frame_headers(width, height, 100)` this test calls), so - // the inter frame's OBU is appended straight onto it rather than - // re-deriving the key frame's tile bytes. - let mut stream = key.stream.clone(); - stream.extend_from_slice(&temporal_delimiter()); - stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); - - ffmpeg_decode_sequence(&stream, width, height, 2); - } +/// lane-av1ibc's own end-to-end check: a repeated-pattern screen card +/// sets `allow_intrabc` (so every in-loop filter is off), blocks really +/// take a block vector (fire count + DV histogram, class +/// `gate-blind-to-feature`), and both our own decoder and ffmpeg -- +/// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct +/// exactly what the encoder did. +#[test] +fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() { + let _knobs = crate::speed::knob_write(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4 + // superblocks of 64) and tall enough for a source superblock row + // above the blocks that copy from it. + let (width, height) = (512usize, 256usize); + let picture = screen_card(width, height); + // The default is OFF (it measured worse on the real screen capture -- + // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns + // the arm on for its own encode and puts it back straight after. + force_intrabc(Some(true)); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + force_intrabc(None); + assert!( + encoded.allow_intrabc, + "allow_intrabc was not set on a fully periodic screen card" + ); + let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); + assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); + assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); + assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); +} - /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded - /// frame size an AV1 decoder allocates, not necessarily the render size - /// (see [`a_frame_round_trips_at_its_own_size`]). - pub(super) fn ffprobe_size(stream: &[u8]) -> (u32, u32) { - // Distinct per call, not per process: the test binary runs callers on - // parallel threads, and a shared name lets one test's cleanup delete - // the stream another test's ffprobe is still reading. - static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let path = std::env::temp_dir().join(format!( - "ec-av1-probe-{}-{}.obu", - std::process::id(), - PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) - )); - let _ = std::fs::remove_file(&path); - std::fs::write(&path, stream).expect("writing the probe stream"); - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-f", - "obu", - "-select_streams", - "v:0", - "-show_entries", - "stream=width,height", - "-of", - "csv=p=0", - ]) - .arg(&path).output() - .expect("ffprobe failed to run"); - let _ = std::fs::remove_file(&path); - assert!( - out.status.success(), - "ffprobe refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let text = String::from_utf8_lossy(&out.stdout); - let mut fields = text.trim().split(','); - let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); - let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); - (width, height) - } +/// The minimal repro that isolated the inter-residual desync: a key frame +/// followed by one inter frame whose single superblock carries one +/// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma +/// coefficient, its three sibling blocks all `skip: true`. Before the +/// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data +/// found when processing input") even though every symbol either block +/// codes is otherwise proven (all-skip inter blocks decode clean, and the +/// same coefficient syntax decodes clean on every intra key-frame gate). +#[test] +fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { + let _knobs = crate::speed::knob_write(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (64usize, 64usize); + let picture = Picture::grey(width, height); + let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + + let (seq, _) = key_frame_headers(width, height, 100).unwrap(); + let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); + + let residual_block = BlockCoeffs { + luma_tx_types: Vec::new(), + angle_delta_y: 0, + cfl_alphas: None, + filter_intra: None, + luma: vec![Coeff { + row: 0, + col: 0, + level: 4, + }], + u: Vec::new(), + v: Vec::new(), + mode: 0, + uv_mode: 0, + skip: false, + eight: None, + dv: None, + palette: None, + palette_uv: None, + tx_depth: 0, + inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NearestMv, + mv: (0, 0), + ref_mv_idx: 0, + }), + motion_mode: 0, + }; + let skipped_block = BlockCoeffs { + skip: true, + inter: Some(InterInfo { + ref1: None, + mv1: (0, 0), + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NearestMv, + mv: (0, 0), + ref_mv_idx: 0, + }), + ..BlockCoeffs::default() + }; + let blocks = vec![ + Quadrant::Whole(residual_block), + Quadrant::Whole(skipped_block.clone()), + Quadrant::Whole(skipped_block.clone()), + Quadrant::Whole(skipped_block), + ]; + // lane-av1obmc: the header this tile is decoded under carries + // `is_motion_mode_switchable`, so the writer must be armed with it + // too or the decoder reads a `motion_mode` symbol nobody wrote. + crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable); + crate::tile::arm_warped_motion(inter_header.allow_warped_motion); + let tile = crate::tile::sb_coeff_inter_frame_tile( + inter_header.mi_cols, + inter_header.mi_rows, + 100, + &blocks, + ) + .unwrap(); + + // `key.stream` is already a temporal delimiter, the sequence header + // and the key frame's own OBU (`encode_key_frame` built it from the + // same `key_frame_headers(width, height, 100)` this test calls), so + // the inter frame's OBU is appended straight onto it rather than + // re-deriving the key frame's tile bytes. + let mut stream = key.stream.clone(); + stream.extend_from_slice(&temporal_delimiter()); + stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); + + ffmpeg_decode_sequence(&stream, width, height, 2); +} - /// lane-av1cap: the final filter replay against the capture decode it - /// replaced, at the block-padded and straddling sizes the whole-frame - /// tests cover -- `set_verify_final_replay` makes - /// [`pick_and_apply_filters`] run both on every frame and assert, per - /// frame, that the spliced picture and the two filter stages the - /// restoration search reads are bit-identical over the frame's own crop. - #[test] - fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - crate::decode::set_verify_final_replay(true); - for &(width, height) in &[ - (64usize, 56usize), - (216, 96), - (192, 120), - (640, 352), - (1280, 720), - ] { - eprintln!("--- {width}x{height}"); - let picture = test_card(width, height); - let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - } - crate::decode::set_verify_final_replay(false); - } +/// `ffprobe`'s reported `width,height` for one OBU stream -- the coded +/// frame size an AV1 decoder allocates, not necessarily the render size +/// (see [`a_frame_round_trips_at_its_own_size`]). +pub(super) fn ffprobe_size(stream: &[u8]) -> (u32, u32) { + // Distinct per call, not per process: the test binary runs callers on + // parallel threads, and a shared name lets one test's cleanup delete + // the stream another test's ffprobe is still reading. + static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "ec-av1-probe-{}-{}.obu", + std::process::id(), + PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let _ = std::fs::remove_file(&path); + std::fs::write(&path, stream).expect("writing the probe stream"); + let out = ec_testkit::ffprobe() + .args([ + "-v", + "error", + "-f", + "obu", + "-select_streams", + "v:0", + "-show_entries", + "stream=width,height", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "ffprobe refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let text = String::from_utf8_lossy(&out.stdout); + let mut fields = text.trim().split(','); + let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); + let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); + (width, height) +} - /// A key frame at an arbitrary even size round-trips through ffmpeg over - /// its own render rectangle: [`Encoded::reconstruction`] is exactly the - /// picture's own size, and what ffmpeg decodes over that same top-left - /// region equals it sample for sample. - /// - /// This does not check that `ffprobe` reports the picture's own size, - /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded - /// (block-padded) frame size, the same one libaom itself would code for - /// a non-block-aligned picture. `render_width`/`render_height` (which - /// this crate sets correctly, spec 5.9.6) is a display hint no AV1 - /// decoder is required to crop pixels by, and ffmpeg's does not -- - /// checked empirically against ffprobe here and against a real libaom - /// encode separately. So the coded size, not the render size, is what - /// `ffprobe` is asserted to report below. - #[test] - fn a_frame_round_trips_at_its_own_size() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - // 854x480 is covered separately by - // `an_854x480_picture_round_trips_through_its_padding`, which its own - // doc comment explains was worth keeping as its own test. - for &(width, height) in &[ - (1920usize, 1080usize), - (640, 352), - (1280, 720), - (64, 56), - (854, 480), - (216, 96), - (192, 120), - ] { - let picture = test_card(width, height); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - assert_eq!( - (encoded.reconstruction.width, encoded.reconstruction.height), - (width, height), - "{width}x{height}: reconstruction is cropped to the picture's own size" - ); - assert_eq!( - ffprobe_size(&encoded.stream), - (width as u32, height as u32), - "{width}x{height}: ffprobe reports the true (display) size, not the padded one" - ); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!( - decoded.y, encoded.reconstruction.y, - "{width}x{height}: luma" - ); - assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); - } +/// lane-av1cap: the final filter replay against the capture decode it +/// replaced, at the block-padded and straddling sizes the whole-frame +/// tests cover -- `set_verify_final_replay` makes +/// [`pick_and_apply_filters`] run both on every frame and assert, per +/// frame, that the spliced picture and the two filter stages the +/// restoration search reads are bit-identical over the frame's own crop. +#[test] +fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() { + let _knobs = crate::speed::knob_write(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + crate::decode::set_verify_final_replay(true); + for &(width, height) in &[ + (64usize, 56usize), + (216, 96), + (192, 120), + (640, 352), + (1280, 720), + ] { + eprintln!("--- {width}x{height}"); + let picture = test_card(width, height); + let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); } + crate::decode::set_verify_final_replay(false); +} - /// 854x480 (padded to 864x480, an edge-replication padded key frame) used - /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug - /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact - /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned - /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while - /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 + - /// col`) -- different bits of an 8-byte table, one true, one false. The - /// stride libaom indexes by is fixed at its compile-time maximum - /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock - /// size a stream uses, so the right stride for a 16x16 or 32x32 block is - /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s - /// row/col position within the (correctly 64-relative) superblock stayed - /// right, only the table's own row stride was wrong. Fixed in - /// `Reach::table_stride`; not an arithmetic-coder desync (an - /// EC_RNG-per-symbol trace against the same debug decoder found the - /// bitstream byte-for-byte identical to libaom's across all 51188 - /// symbols of this frame before this bug was found). - /// - /// Since the frame header started writing the true (unpadded) display - /// size into `frame_width`/`frame_height` rather than the padded coded - /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded - /// 864x480 and cropping ourselves now reads past what ffmpeg actually - /// emits (`av1_common_int.h`'s render/upscale path, mirrored by - /// `av1_frame_size` on the decode side, crops the loop-filtered picture to - /// the header's own size before output). - #[test] - fn an_854x480_picture_round_trips_through_its_padding() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (854usize, 480usize); +/// A key frame at an arbitrary even size round-trips through ffmpeg over +/// its own render rectangle: [`Encoded::reconstruction`] is exactly the +/// picture's own size, and what ffmpeg decodes over that same top-left +/// region equals it sample for sample. +/// +/// This does not check that `ffprobe` reports the picture's own size, +/// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded +/// (block-padded) frame size, the same one libaom itself would code for +/// a non-block-aligned picture. `render_width`/`render_height` (which +/// this crate sets correctly, spec 5.9.6) is a display hint no AV1 +/// decoder is required to crop pixels by, and ffmpeg's does not -- +/// checked empirically against ffprobe here and against a real libaom +/// encode separately. So the coded size, not the render size, is what +/// `ffprobe` is asserted to report below. +#[test] +fn a_frame_round_trips_at_its_own_size() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + // 854x480 is covered separately by + // `an_854x480_picture_round_trips_through_its_padding`, which its own + // doc comment explains was worth keeping as its own test. + for &(width, height) in &[ + (1920usize, 1080usize), + (640, 352), + (1280, 720), + (64, 56), + (854, 480), + (216, 96), + (192, 120), + ] { let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); - } - - /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left` - /// transform-unit path, for every 4x4 unit of every 8x8 block of a - /// superblock, both partition tables: - /// - /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the - /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so - /// wiring the TU sites onto it changes no existing stream; - /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is - /// NULL in libaom because that lookup never happens, and reading a - /// 4x4 row out of the three-row vert tables is what crashed a real - /// `--enable-tx-size-search=1` stream (r2); - /// 3. and it must be the BLOCK's vert answer where the two tables - /// disagree: the top-right 4x4 unit of the 8x8 block at superblock - /// row 1, column 0 reads its above-right samples from the 8x8 to its - /// upper right, which a vertical AB partition codes AFTER it - /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1). - #[test] - fn of_tu_follows_the_block_row_including_under_vert_ab() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - // The 8x8 square at superblock row 1, column 0, and the TX4 unit in - // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's - // above-right answer is the BLOCK's, which is the whole reason a unit - // asks the block instead of looking itself up (the - // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2). - let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); - assert_eq!( - Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, - plain.above_right, - "ordinary table: the top-right TX4 unit takes the block's row" - ); - let guard = Reach::vert_ab_partition(); - let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); assert_eq!( - Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, - vert.above_right, - "vert AB: the unit follows the vert row the block just picked" - ); - assert_ne!( - plain.above_right, vert.above_right, - "this position is the cell where the vert tables disagree; pick another if libaom's tables change" - ); - drop(guard); - } - - /// `Reach::top_right`/`bottom_left` against a from-scratch transcription - /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/ - /// reconintra.c`), for every 16x16 and 32x32 block position across three - /// superblocks square -- interior and every superblock edge (top row, - /// left column, right column, bottom row) both sizes reach. Written to - /// catch the class the `table_stride` bug was: an index stride silently - /// wrong for one block size while looking plausible for the other. - #[test] - fn reach_matches_libaom_has_top_right_and_has_bottom_left() { - // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so - // it pins the 64 reach explicitly instead of following the process's - // own superblock knob (`for_encoder`), which made it red under - // `EC_AV1_SB128=1` for no defect of the code under test. - let fctx = &crate::decode::FrameCtx::new(); - // Transcribed from has_top_right/has_bottom_left's row_off==0, - // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a - // 128px reference grid) pinned as libaom pins it, independent of the - // 64px superblock this crate actually codes. - fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { - if y == 0 || x + side >= width { - return false; - } - let (row, col, per_side) = ( - (y % SUPERBLOCK) / side, - (x % SUPERBLOCK) / side, - SUPERBLOCK / side, - ); - if row == 0 { - return true; - } - if col + 1 == per_side { - return false; - } - let stride = 128 / side; - let index = row * stride + col; - let table = if side == BLOCK { - [95u8, 87].to_vec() - } else { - vec![255, 85, 119, 85, 127, 85, 119, 85] - }; - (table[index / 8] >> (index % 8)) & 1 != 0 - } - - fn libaom_bottom_left( - side: usize, - x: usize, - y: usize, - height: usize, - _fctx: &crate::decode::FrameCtx, - ) -> bool { - if x == 0 || y + side >= height { - return false; - } - let (row, col, per_side) = ( - (y % SUPERBLOCK) / side, - (x % SUPERBLOCK) / side, - SUPERBLOCK / side, - ); - if col == 0 { - return row * side + side < SUPERBLOCK; - } - if row + 1 == per_side { - return false; - } - let stride = 128 / side; - let index = row * stride + col; - let table = if side == BLOCK { - [4u8, 4].to_vec() - } else { - vec![84, 16, 84, 0, 84, 16, 84, 0] - }; - (table[index / 8] >> (index % 8)) & 1 != 0 - } - - let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); - for side in [16usize, BLOCK] { - for y in (0..height).step_by(side) { - for x in (0..width).step_by(side) { - let reach = Reach::of(side, x, y, width, height, fctx); - assert_eq!( - reach.above_right, - libaom_top_right(side, x, y, width, height), - "side={side} x={x} y={y}: above_right" - ); - assert_eq!( - reach.below_left, - libaom_bottom_left(side, x, y, height, fctx), - "side={side} x={x} y={y}: below_left" - ); - } - } - } - } - - /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are - /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8 - /// column inside the superblock) may read the below-left samples the - /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots - /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe - /// swept in r6 produced a decodable 16x16-level VERT_B stream (every - /// stream that partitions that small first hits the still-refused - /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms). - /// [`Reach::of_tu`] against a from-scratch transcription of libaom's - /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma, - /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in - /// pixels -- lane-palette2 r12: the square multi-TU path used the - /// standalone-block tables instead of this rule and granted a 16x16 - /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses. - #[test] - fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { - // libaom, in MI units: bw_unit/bh_unit = block size / 4, - // *_count_unit = tx size / 4. - fn libaom_tr( - bw: usize, - bh: usize, - col_off: usize, - row_off: usize, - tx: usize, - blk: bool, - ) -> bool { - let (plane_bw_unit, count) = (bw / 4, tx / 4); - let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); - let _ = bh; - if row_off_u > 0 { - col_off_u + count < plane_bw_unit - } else if col_off_u + count < plane_bw_unit { - true - } else { - blk - } - } - fn libaom_bl( - bw: usize, - bh: usize, - col_off: usize, - row_off: usize, - tx: usize, - blk: bool, - ) -> bool { - let (plane_bh_unit, count) = (bh / 4, tx / 4); - let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); - let _ = bw; - if col_off_u > 0 { - false - } else if row_off_u + count < plane_bh_unit { - true - } else { - blk - } - } - for &(bw, bh) in &[ - (8, 8), - (16, 16), - (32, 32), - (64, 64), - (16, 8), - (8, 16), - (32, 16), - (16, 32), - (64, 32), - (32, 64), - ] { - for &tx in &[4usize, 8, 16, 32] { - if tx > bw.min(bh) { - continue; - } - for row_off in (0..bh).step_by(tx) { - for col_off in (0..bw).step_by(tx) { - for &blk in &[ - Reach { - above_right: false, - below_left: false, - }, - Reach { - above_right: true, - below_left: true, - }, - ] { - let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); - assert_eq!( - got.above_right, - libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), - "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" - ); - assert_eq!( - got.below_left, - libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), - "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" - ); - } - } - } - } - } - } - - #[test] - fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); - // Interior superblock, so neither the frame edge nor the col == 0 / - // last-row early returns answer instead of the table. - let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); - let mut flipped = 0; - for row in 0..8 { - for col in 1..8 { - let (x, y) = (sb_x + col * 8, sb_y + row * 8); - let raster = Reach::of(8, x, y, width, height, fctx).below_left; - let vert = { - let _guard = Reach::vert_ab_partition(); - Reach::of(8, x, y, width, height, fctx).below_left - }; - // The TR square of a VERT_A/_B sits at an even row, odd - // column; every other slot must be untouched by the guard. - if row % 2 == 0 && col % 2 == 1 { - assert!(!raster, "raster below_left at row={row} col={col}"); - assert!(vert, "vert below_left at row={row} col={col}"); - flipped += 1; - } else { - assert_eq!(raster, vert, "guard moved row={row} col={col}"); - } - } - } - assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); - // The guard is scoped: it must not leak past its own block. - assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); - } - - /// An odd width or height is refused by name, not by however the padder - /// or the block coder would happen to fail on it. - #[test] - fn odd_dimensions_are_refused() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { - let picture = Picture::grey(width, height); - let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) - .expect_err(&format!("{width}x{height} is odd and must be refused")); - assert!( - err.to_string().contains("even"), - "{width}x{height}: error was {err}" - ); - } - } - - /// A sequence at a size that is not a multiple of the block grid decodes - /// to the right frame count and the right size for every frame, - /// including the inter frames whose reference is the previous frame's - /// own (padded) reconstruction. - #[test] - fn sequence_round_trips_at_a_non_multiple_size() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (160usize, 96usize); - let pictures: Vec = (0..3) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - assert_eq!(encoded.frames.len(), 3); - for (i, frame) in encoded.frames.iter().enumerate() { - assert_eq!( - (frame.reconstruction.width, frame.reconstruction.height), - (width, height), - "frame {i}: reconstruction size" - ); - } - // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the - // true (display) size a sequence's frames share, not the padded one. - assert_eq!( - ffprobe_size(&encoded.stream), - (width as u32, height as u32), - "sequence: ffprobe reports the true (display) size" + (encoded.reconstruction.width, encoded.reconstruction.height), + (width, height), + "{width}x{height}: reconstruction is cropped to the picture's own size" ); - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); - assert_eq!(decoded.len(), 3, "decoded frame count"); - for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { - assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); - assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); - assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); - } - } - - /// 1280x720 -- the export size a real edith timeline hits -- is exactly - /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge - /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s - /// `pos + side_mi / 2 < bound` boundary), which is the case - /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than - /// refusing. A key frame alone already covered this size; this proves the - /// inter tile writer's parity with it across a real multi-frame export. - #[test] - fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (1280usize, 720usize); - let pictures: Vec = (0..3) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - assert_eq!(encoded.frames.len(), 3); - for (i, frame) in encoded.frames.iter().enumerate() { - assert_eq!( - (frame.reconstruction.width, frame.reconstruction.height), - (width, height), - "frame {i}: reconstruction size" - ); - } assert_eq!( ffprobe_size(&encoded.stream), (width as u32, height as u32), - "ffprobe reports the true (display) 1280x720 size" - ); - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); - assert_eq!(decoded.len(), 3, "decoded frame count"); - for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { - assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); - assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); - assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); - } - } - - /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16 - /// leaf's own half (`has_half` at the SUB level) itself straddles the - /// true edge on one axis only. lane-av1-rect r7 wired the key frame - /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly - /// this case; lane-av1inter8 extends the same leaf-8 path to inter - /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s - /// straddling-16x16 branch), so an inter frame no longer refuses this - /// size either. This only proves the encoder does not error out -- see - /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the - /// decoder-clean proof (a 3-frame sequence, so the inter path is - /// actually exercised). - #[test] - fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (640usize, 360usize); - let picture = Picture::grey(width, height); - encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) - .expect("key frame now codes the mod-32==8 straddle"); - - // `encode_sequence`'s second frame is the inter path: same size, now - // wired the same way. - let pictures = vec![picture.clone(), picture]; - encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) - .expect("inter frame now codes the mod-32==8 straddle too"); - } - - /// The r15 fix at production size: three 640x360 key frames (inter is - /// still refused at this size, per the test above, so this stands in for - /// the charter's "3-frame sequence" using three independent key frames of - /// shifted content), each proven decoder-clean through ffmpeg rather than - /// only encoder-clean. - #[test] - fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (640usize, 360usize); - for shift in [0i64, 7, 19] { - let picture = panned_test_card(width, height, shift); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); - } - } - - /// The 640x360 straddle class, but through the inter path an actual - /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)): - /// proves the leaf-8 inter stream this round wires up is not just - /// encoder-clean (the test above) but decoder-clean against ffmpeg too. - #[test] - fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (640usize, 360usize); - let pictures: Vec = (0..4) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - assert_eq!(encoded.frames.len(), 4); - if let Ok(path) = std::env::var("EC_AV1_DUMP") { - std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); - } - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); - assert_eq!(decoded.len(), 4, "decoded frame count"); - for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { - assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); - assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); - assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); - } - } - - /// One frame of a real clip, scaled to a whole number of 32x32 blocks. - pub(super) fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) - .args(["-vf", &format!("scale={width}:{height}")]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() - .expect("ffmpeg failed to run"); - assert!( - out.status.success(), - "ffmpeg: {}", - String::from_utf8_lossy(&out.stderr) + "{width}x{height}: ffprobe reports the true (display) size, not the padded one" ); - let (luma, chroma) = (width * height, width * height / 4); + let decoded = ffmpeg_decode(&encoded.stream, width, height); assert_eq!( - out.stdout.len(), - luma + 2 * chroma, - "expected one 4:2:0 frame" + decoded.y, encoded.reconstruction.y, + "{width}x{height}: luma" ); - Picture { - width, - height, - y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), - u: out.stdout[luma..luma + chroma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - v: out.stdout[luma + chroma..] - .iter() - .map(|&v| u16::from(v)) - .collect(), - } - } - - /// Prints what the mode search saves over DC prediction alone, for the - /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the - /// weight the search puts on rate can be swept. - #[test] - #[ignore = "a sweep, not a gate"] - fn probe_lambda() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let mut pictures = vec![ - ("test card".to_string(), test_card(160, 96)), - ("stripes".to_string(), stripes(160, 96, true)), - ]; - if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { - for entry in clips.split(':').filter(|e| !e.is_empty()) { - let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); - let name = path.rsplit('/').next().unwrap_or(path).to_string(); - pictures.push((name, clip_frame(path, skip, 640, 352))); - } - } - for (name, picture) in pictures { - let dc = ladder(&picture, &[DC_PRED], fctx); - let searched = ladder(&picture, &NON_DIRECTIONAL, fctx); - println!( - "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", - bd_rate(&dc, &searched) * 100.0, - 10f64.powf(searched[1].1), - searched[1].0, - 10f64.powf(dc[1].1), - dc[1].0, - ); - } - } - - /// Prints the whole mode-search ladder, so two builds of the search can be - /// compared against each other rather than each against its own baseline. - #[test] - #[ignore = "a sweep, not a gate"] - fn probe_ladder() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for (name, picture) in sweep_pictures() { - let all = ladder(&picture, &KEY_FRAME_MODES, fctx); - let points = all - .iter() - .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) - .collect::>() - .join(" "); - println!("ladder {name}: {points}"); - } - } - - /// Splitting a 32x32 block into four 16x16 ones, measured both ways over - /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what - /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report. - #[test] - // ROBUST-RED on this tree, and the red is in the MEASURE, not the codec: - // the `stripes` picture codes LOSSLESSLY at q110/90/70, so both ladders - // come back as three identical `(inf, 1.8260748027008264)` points and - // `bd_rate` has an empty trapezoid to integrate, which panics with - // "the two ladders have to overlap in PSNR". Row 1 (`test card`) still - // prints its number before the panic. Point `EC_AV1_CLIPS` at a real lossy - // clip, or read only row 1. - #[ignore = "a sweep, not a gate; PANICS on its own lossless synthetic rows (stripes is lossless at q110/90/70, so bd_rate has no PSNR overlap) -- point EC_AV1_CLIPS at a lossy clip"] - pub(super) fn probe_split() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for (name, picture) in sweep_pictures() { - let ladder = |split: bool| { - let mut points: Vec<(f64, f64)> = [110u8, 90, 70] - .iter() - .map(|&q| { - let encoded = encode_key_frame_inner( - &picture, - q, - 0.5, - &KEY_FRAME_MODES, - split, - (picture.width, picture.height), - unspecified_color_config(), - fctx, - ) - .unwrap(); - ( - psnr(&encoded.reconstruction.y, picture.y.as_slice()), - (encoded.stream.len() as f64).log10(), - ) - }) - .collect(); - points.sort_by(|a, b| a.0.total_cmp(&b.0)); - points - }; - let (whole, split) = (ladder(false), ladder(true)); - let blocks = encode_key_frame_inner( - &picture, - 90, - 0.5, - &KEY_FRAME_MODES, - true, - (picture.width, picture.height), - unspecified_color_config(), - fctx, - ) - .unwrap() - .modes - .len(); - let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); - println!( - "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", - bd_rate(&whole, &split) * 100.0 - ); - } - } - - /// A striped picture, running one way or the other. The stripes are what - /// separates a vertical predictor from a horizontal one: a mode search - /// reading a transposed edge would pick the wrong one of the pair, which no - /// symmetric picture would show. - pub(super) fn stripes(width: usize, height: usize, vertical: bool) -> Picture { - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let along = if vertical { x } else { y }; - picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; - } - } - picture - } - - /// Where two planes first disagree, and by how much: a mismatch reported as - /// a position says which block and which sample of it went wrong, which a - /// pair of thousand-sample arrays does not. A length difference counts as a - /// disagreement: `zip` stops at the shorter plane, so a short one would - /// otherwise compare exact over the prefix the two share. - pub(super) fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option { - if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) { - let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); - return Some(format!( - "{differ} samples differ, first at ({}, {}): ours {} theirs {}", - i % width, - i / width, - ours[i], - theirs[i] - )); - } - if ours.len() != theirs.len() { - return Some(format!( - "no sample in the shared prefix differs, but ours is {} samples and theirs is {}", - ours.len(), - theirs.len() - )); - } - None + assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); } +} - /// Every mode the encoder offers has to predict what the decoder predicts, - /// not just the ones a particular picture happens to choose: each is forced - /// over a whole picture and the reconstruction gated against ffmpeg. - #[test] - fn every_mode_decodes_to_what_the_encoder_predicted() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - // A mode ablation measures the MODE search: a filter-intra block is - // coded `DC_PRED` whatever mode the arm forces, so it would fail the - // "the encoder coded something else" check for a reason that is not - // about the mode search at all. - force_filter_intra(Some(false)); - // 128 wide is a whole number of superblocks and 160 is not: the last - // superblock of a 160-wide row is half a one, whose blocks have no - // above-right samples inside the frame at all. - for (width, height) in [(128, 96), (160, 96)] { - let picture = test_card(width, height); - for mode in KEY_FRAME_MODES { - let encoded = - encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx) - .unwrap(); - let decoded = ffmpeg_decode(&encoded.stream, width, height); - for (plane, ours, theirs, stride) in [ - ("luma", &encoded.reconstruction.y, &decoded.y, width), - ("U", &encoded.reconstruction.u, &decoded.u, width / 2), - ("V", &encoded.reconstruction.v, &decoded.v, width / 2), - ] { - assert!( - first_difference(ours, theirs, stride).is_none(), - "{width}x{height} mode {mode}, {plane}: {}", - first_difference(ours, theirs, stride).unwrap() - ); - } - assert!( - encoded.modes.iter().all(|&m| m == mode), - "mode {mode}: the encoder coded something else" - ); - } - } - } +/// 854x480 (padded to 864x480, an edge-replication padded key frame) used +/// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug +/// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact +/// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned +/// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while +/// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 + +/// col`) -- different bits of an 8-byte table, one true, one false. The +/// stride libaom indexes by is fixed at its compile-time maximum +/// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock +/// size a stream uses, so the right stride for a 16x16 or 32x32 block is +/// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s +/// row/col position within the (correctly 64-relative) superblock stayed +/// right, only the table's own row stride was wrong. Fixed in +/// `Reach::table_stride`; not an arithmetic-coder desync (an +/// EC_RNG-per-symbol trace against the same debug decoder found the +/// bitstream byte-for-byte identical to libaom's across all 51188 +/// symbols of this frame before this bug was found). +/// +/// Since the frame header started writing the true (unpadded) display +/// size into `frame_width`/`frame_height` rather than the padded coded +/// size, ffmpeg crops to 854x480 on its own -- decoding at the padded +/// 864x480 and cropping ourselves now reads past what ffmpeg actually +/// emits (`av1_common_int.h`'s render/upscale path, mirrored by +/// `av1_frame_size` on the decode side, crops the loop-filtered picture to +/// the header's own size before output). +#[test] +fn an_854x480_picture_round_trips_through_its_padding() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (854usize, 480usize); + let picture = test_card(width, height); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); +} - /// The search has to follow the picture: vertical stripes are cheapest - /// predicted from the row above, horizontal ones from the column to the - /// left. Reading the edges the other way round would swap the two answers - /// while leaving every fidelity gate intact. - #[test] - fn the_search_picks_the_direction_the_picture_runs() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]: - // a filter-intra block is coded `DC_PRED` whatever mode the arm - // offers, and these stripes are SCREEN content, where the filter arm - // now searches its own transform depth (lane-fitu) and wins outright - // -- which says nothing about the mode search this gate measures. - force_filter_intra(Some(false)); - for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { - let picture = stripes(128, 96, vertical); - // Only the pair, because on stripes a third mode predicts exactly - // what the right one of the pair does -- PAETH reads the corner and - // the left column, which a striped picture makes equal -- and the - // tie then goes to whichever is cheaper to name, which is not what - // this gate is about. - let encoded = - encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx) - .unwrap(); - // The first block of the picture has neither neighbour, so it - // cannot tell the modes apart; every other one can. - let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); - assert!( - picked * 2 > encoded.modes.len() - 1, - "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", - encoded.modes.len() - 1, - encoded.modes - ); - } - } +/// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left` +/// transform-unit path, for every 4x4 unit of every 8x8 block of a +/// superblock, both partition tables: +/// +/// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the +/// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so +/// wiring the TU sites onto it changes no existing stream; +/// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is +/// NULL in libaom because that lookup never happens, and reading a +/// 4x4 row out of the three-row vert tables is what crashed a real +/// `--enable-tx-size-search=1` stream (r2); +/// 3. and it must be the BLOCK's vert answer where the two tables +/// disagree: the top-right 4x4 unit of the 8x8 block at superblock +/// row 1, column 0 reads its above-right samples from the 8x8 to its +/// upper right, which a vertical AB partition codes AFTER it +/// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1). +#[test] +fn of_tu_follows_the_block_row_including_under_vert_ab() { + let fctx = &crate::decode::FrameCtx::for_encoder(); + // The 8x8 square at superblock row 1, column 0, and the TX4 unit in + // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's + // above-right answer is the BLOCK's, which is the whole reason a unit + // asks the block instead of looking itself up (the + // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2). + let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); + assert_eq!( + Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, + plain.above_right, + "ordinary table: the top-right TX4 unit takes the block's row" + ); + let guard = Reach::vert_ab_partition(); + let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); + assert_eq!( + Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, + vert.above_right, + "vert AB: the unit follows the vert row the block just picked" + ); + assert_ne!( + plain.above_right, vert.above_right, + "this position is the cell where the vert tables disagree; pick another if libaom's tables change" + ); + drop(guard); +} - /// What the search is for: the same picture, at the same quantizer, coded - /// smaller and more faithfully than DC alone can manage. - /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid - /// between the two rate-distortion curves in log-rate against PSNR, as a - /// fraction of the reference's rate. Negative means the second curve costs - /// less for the same picture. - pub(super) fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { - let low = reference[0].0.max(other[0].0); - let high = reference[reference.len() - 1] - .0 - .min(other[other.len() - 1].0); - // lane-av1tx: `TxMode::Select` moved the directional ladder clear of - // the non-directional one on the synthetic diagonals -- every point - // both higher in PSNR *and* lower in rate -- so there is no PSNR band - // to integrate over any more. A curve that dominates that way has - // saved everything the measure can express (the - // `instrument-at-bound` class: the answer is at the instrument's own - // edge, not undefined), so name it rather than panicking; anything - // less clean than strict dominance still is. - if high <= low { - let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); - let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); - let dominates = - other[0].0 > reference[reference.len() - 1].0 && other_hi_rate <= ref_lo_rate; - assert!( - dominates, - "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" - ); - return -1.0; - } - let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { - let i = curve - .windows(2) - .position(|w| psnr >= w[0].0 && psnr <= w[1].0) - .unwrap_or(0); - let (x0, y0) = curve[i]; - let (x1, y1) = curve[i + 1]; - y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) +/// `Reach::top_right`/`bottom_left` against a from-scratch transcription +/// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/ +/// reconintra.c`), for every 16x16 and 32x32 block position across three +/// superblocks square -- interior and every superblock edge (top row, +/// left column, right column, bottom row) both sizes reach. Written to +/// catch the class the `table_stride` bug was: an index stride silently +/// wrong for one block size while looking plausible for the other. +#[test] +fn reach_matches_libaom_has_top_right_and_has_bottom_left() { + // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so + // it pins the 64 reach explicitly instead of following the process's + // own superblock knob (`for_encoder`), which made it red under + // `EC_AV1_SB128=1` for no defect of the code under test. + let fctx = &crate::decode::FrameCtx::new(); + // Transcribed from has_top_right/has_bottom_left's row_off==0, + // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a + // 128px reference grid) pinned as libaom pins it, independent of the + // 64px superblock this crate actually codes. + fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { + if y == 0 || x + side >= width { + return false; + } + let (row, col, per_side) = ( + (y % SUPERBLOCK) / side, + (x % SUPERBLOCK) / side, + SUPERBLOCK / side, + ); + if row == 0 { + return true; + } + if col + 1 == per_side { + return false; + } + let stride = 128 / side; + let index = row * stride + col; + let table = if side == BLOCK { + [95u8, 87].to_vec() + } else { + vec![255, 85, 119, 85, 127, 85, 119, 85] }; - let steps = 64; - let mut area = 0.0; - for step in 0..steps { - let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); - area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); - } - 10f64.powf(area / f64::from(steps)) - 1.0 - } - - /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by - /// fidelity. - pub(super) fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { - // A mode ablation measures the MODE search: the palette would code - // these synthetic two-colour pictures losslessly under every arm and - // leave nothing to compare (see [`force_screen`]). - force_screen(Some(false)); - // Same reason, for the filter-intra candidate: it wins blocks under - // BOTH arms of a mode ablation and so cancels the difference the - // ablation measures (class `gate-recipe-confound`). - force_filter_intra(Some(false)); - let mut points: Vec<(f64, f64)> = [110u8, 90, 70] - .iter() - .map(|&q| { - let encoded = - encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap(); - ( - psnr(&encoded.reconstruction.y, picture.y.as_slice()), - (encoded.stream.len() as f64).log10(), - ) - }) - .collect(); - points.sort_by(|a, b| a.0.total_cmp(&b.0)); - points - } - - /// What the search is for: the same pictures cost less to code at the same - /// fidelity than DC prediction alone can manage. A picture that runs one - /// way saves far more than a busy one, which is the shape a working - /// directional pair has. - #[test] - fn the_search_beats_dc_alone() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for (name, picture, want) in [ - ("test card", test_card(160, 96), -0.05), - ("stripes", stripes(160, 96, true), -0.40), - ] { - let saved = bd_rate( - &ladder(&picture, &[DC_PRED], fctx), - &ladder(&picture, &NON_DIRECTIONAL, fctx), - ); - assert!( - saved < want, - "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", - saved * 100.0, - -want * 100.0 - ); - } + (table[index / 8] >> (index % 8)) & 1 != 0 } - /// The pictures a sweep is measured over: two synthetic ones, plus a frame - /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated. - pub(super) fn sweep_pictures() -> Vec<(String, Picture)> { - let mut pictures = vec![ - ("test card".to_string(), test_card(160, 96)), - ("stripes".to_string(), stripes(160, 96, true)), - ("diagonal".to_string(), diagonal(160, 96, true)), - ]; - if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { - for entry in clips.split(':').filter(|e| !e.is_empty()) { - let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); - let name = path.rsplit('/').next().unwrap_or(path).to_string(); - pictures.push((name, clip_frame(path, skip, 640, 352))); - } - } - pictures - } - - /// What the six directional modes are worth, per picture, at whatever - /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read - /// no further, and how often the search picks one. - #[test] - #[ignore = "a sweep, not a gate"] - fn probe_directional() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for (name, picture) in sweep_pictures() { - let dc = ladder(&picture, &[DC_PRED], fctx); - let flat = ladder(&picture, &NON_DIRECTIONAL, fctx); - let all = ladder(&picture, &KEY_FRAME_MODES, fctx); - let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap(); - let directional = encoded - .modes - .iter() - .filter(|&&m| (3..=8).contains(&m)) - .count(); - // A picture whose ladders sit at different fidelities altogether - // has no BD-rate to report -- see the flat-sample-window class. - let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { - a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) - }; - let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { - if overlap(a, b) { - format!("{:+.2}%", bd_rate(a, b) * 100.0) - } else { - "no overlap".to_string() - } - }; - println!( - "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", - against(&flat, &all), - against(&dc, &all), - encoded.modes.len(), - ); - } - } - - /// A picture whose stripes run along a diagonal, one way or the other. - /// This is to the directional modes what [`stripes`] is to the vertical and - /// horizontal pair: a predictor that walked the edge in the wrong direction - /// would answer the two pictures the same way round. - pub(super) fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let along = if down_right { x + height - y } else { x + y }; - picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; - } - } - picture - } - - /// The mode picked by the most blocks of a picture, ignoring the first - /// block, which has no neighbours to tell the modes apart with. - pub(super) fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { - // A mode ablation measures the MODE search: the palette would code - // these synthetic two-colour pictures losslessly under every arm and - // leave nothing to compare (see [`force_screen`]). - force_screen(Some(false)); - let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); - let blocks = &encoded.modes[1..]; - let mut counts = [0usize; 13]; - for &mode in blocks { - counts[usize::from(mode)] += 1; - } - let (mode, count) = counts - .iter() - .enumerate() - .max_by_key(|&(_, count)| *count) - .expect("thirteen modes"); - (mode as u8, *count, blocks.len()) - } - - /// The search has to follow a diagonal the way it runs: stripes down and to - /// the right are cheapest predicted at 135 degrees, stripes down and to the - /// left at 45. A walk that stepped the wrong way along the edge, or read - /// the above row where it should read the left column, would swap these. - #[test] - fn the_search_picks_the_diagonal_the_picture_runs() { - let _knobs = crate::speed::knob_write(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { - let picture = diagonal(160, 96, down_right); - let (mode, count, blocks) = favourite_mode(&picture, fctx); - assert_eq!( - mode, want, - "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" - ); - } - } - - /// What the directional modes are for: a picture that runs along a diagonal - /// costs far less to code with them than the seven that read only their own - /// edges can manage, and a picture that runs no particular way costs no - /// more. The second half is the one that bites: a mode set the search - /// cannot price is a mode set that loses rate on content that does not want - /// it, which is what costing the mode symbol is for. - #[test] - fn the_diagonals_beat_the_modes_that_read_no_further() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - for (name, picture, want) in [ - ("down-right", diagonal(160, 96, true), -0.20), - ("down-left", diagonal(160, 96, false), -0.20), - ("test card", test_card(160, 96), 0.01), - ] { - let saved = bd_rate( - &ladder(&picture, &NON_DIRECTIONAL, fctx), - &ladder(&picture, &KEY_FRAME_MODES, fctx), - ); - assert!( - saved < want, - "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", - saved * 100.0, - -want * 100.0 - ); - } - } - - /// A mode the encoder cannot predict must be refused rather than coded as - /// something else, and a search with nothing to choose from likewise. - #[test] - fn a_mode_the_encoder_cannot_predict_is_refused() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let picture = test_card(64, 64); - let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) - .unwrap_err() - .to_string(); - assert!( - message.contains("intra mode 13"), - "the refusal must name the mode, got {message}" - ); - assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); + fn libaom_bottom_left( + side: usize, + x: usize, + y: usize, + height: usize, + _fctx: &crate::decode::FrameCtx, + ) -> bool { + if x == 0 || y + side >= height { + return false; + } + let (row, col, per_side) = ( + (y % SUPERBLOCK) / side, + (x % SUPERBLOCK) / side, + SUPERBLOCK / side, + ); + if col == 0 { + return row * side + side < SUPERBLOCK; + } + if row + 1 == per_side { + return false; + } + let stride = 128 / side; + let index = row * stride + col; + let table = if side == BLOCK { + [4u8, 4].to_vec() + } else { + vec![84, 16, 84, 0, 84, 16, 84, 0] + }; + (table[index / 8] >> (index % 8)) & 1 != 0 } - /// The picture that comes back is the picture that went in, to within the - /// quantizer. A prediction that read the wrong neighbours, or a block - /// written into the wrong place, would still decode to what the encoder - /// reconstructed — it is this gate that says the reconstruction is of the - /// right picture. - #[test] - fn the_encoded_picture_is_the_one_that_went_in() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let picture = test_card(160, 96); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - let luma = psnr(&encoded.reconstruction.y, &picture.y); - assert!(luma > 36.0, "luma PSNR {luma} at q 100"); - for (plane, (got, want)) in [ - (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), - (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), - ] - .iter() - .enumerate() - { - let chroma = psnr(got, want); - assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); + let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); + for side in [16usize, BLOCK] { + for y in (0..height).step_by(side) { + for x in (0..width).step_by(side) { + let reach = Reach::of(side, x, y, width, height, fctx); + assert_eq!( + reach.above_right, + libaom_top_right(side, x, y, width, height), + "side={side} x={x} y={y}: above_right" + ); + assert_eq!( + reach.below_left, + libaom_bottom_left(side, x, y, height, fctx), + "side={side} x={x} y={y}: below_left" + ); + } } } +} - /// A finer quantizer costs bits and buys fidelity, and a wider deadzone - /// does the opposite. Both are monotone, which is what a rate-distortion - /// loop above this will assume. - #[test] - fn fidelity_and_rate_move_with_the_quantizer() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let picture = test_card(128, 128); - let mut previous: Option<(usize, f64)> = None; - for &q in &[70u8, 90, 110] { - let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); - let quality = psnr(&encoded.reconstruction.y, &picture.y); - if let Some((bytes, better)) = previous { - assert!( - encoded.stream.len() < bytes, - "q {q}: {} bytes", - encoded.stream.len() - ); - assert!(quality < better, "q {q}: PSNR {quality}"); +/// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are +/// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8 +/// column inside the superblock) may read the below-left samples the +/// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots +/// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe +/// swept in r6 produced a decodable 16x16-level VERT_B stream (every +/// stream that partitions that small first hits the still-refused +/// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms). +/// [`Reach::of_tu`] against a from-scratch transcription of libaom's +/// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma, +/// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in +/// pixels -- lane-palette2 r12: the square multi-TU path used the +/// standalone-block tables instead of this rule and granted a 16x16 +/// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses. +#[test] +fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { + // libaom, in MI units: bw_unit/bh_unit = block size / 4, + // *_count_unit = tx size / 4. + fn libaom_tr( + bw: usize, + bh: usize, + col_off: usize, + row_off: usize, + tx: usize, + blk: bool, + ) -> bool { + let (plane_bw_unit, count) = (bw / 4, tx / 4); + let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); + let _ = bh; + if row_off_u > 0 { + col_off_u + count < plane_bw_unit + } else if col_off_u + count < plane_bw_unit { + true + } else { + blk + } + } + fn libaom_bl( + bw: usize, + bh: usize, + col_off: usize, + row_off: usize, + tx: usize, + blk: bool, + ) -> bool { + let (plane_bh_unit, count) = (bh / 4, tx / 4); + let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); + let _ = bw; + if col_off_u > 0 { + false + } else if row_off_u + count < plane_bh_unit { + true + } else { + blk + } + } + for &(bw, bh) in &[ + (8, 8), + (16, 16), + (32, 32), + (64, 64), + (16, 8), + (8, 16), + (32, 16), + (16, 32), + (64, 32), + (32, 64), + ] { + for &tx in &[4usize, 8, 16, 32] { + if tx > bw.min(bh) { + continue; + } + for row_off in (0..bh).step_by(tx) { + for col_off in (0..bw).step_by(tx) { + for &blk in &[ + Reach { + above_right: false, + below_left: false, + }, + Reach { + above_right: true, + below_left: true, + }, + ] { + let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); + assert_eq!( + got.above_right, + libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), + "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" + ); + assert_eq!( + got.below_left, + libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), + "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" + ); + } + } } - previous = Some((encoded.stream.len(), quality)); } + } +} - // The deadzone half of this claim lives in - // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now: - // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding - // every zeroing, the deadzone no longer moves a coded stream - // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against - // fewer at 0.5 on this 128x128 card), and that is the pass doing its - // job, not a quantiser defect. - - // Bytes must not jump up across a q-context boundary: a wrong CDF - // table for the far side would show up as a rate discontinuity here, - // even though a coarser quantizer always codes no more than a finer - // one on the same picture. - // - // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since - // chroma searches its own mode, a coarser quantizer can pick a - // *different* uv_mode on a block whose modes now cost nearly the - // same, and the search prices that symbol against the static default - // CDF while the writer codes it against an adapted one -- 311 -> 319 - // bytes at q 120->121 on this picture. The table this gate is really - // watching would move the rate by far more than the mode churn does. - // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the - // same block can also change transform DEPTH between two neighbouring - // quantizers (297 -> 315 bytes at q 120->121 here), and the depth - // symbol is priced off the static CDF row 0 for the same reason the - // uv_mode one is. - // Ceiling: a q-context table wrong by under 10% would pass. Upgrade - // path is pricing through the adapting CDF state (what - // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the - // drift of), after which the exact bound comes back. - for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { - let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx) - .unwrap() - .stream - .len(); - let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx) - .unwrap() - .stream - .len(); - assert!( - hi_bytes as f64 <= lo_bytes as f64 * 1.10, - "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" - ); +#[test] +fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); + // Interior superblock, so neither the frame edge nor the col == 0 / + // last-row early returns answer instead of the table. + let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); + let mut flipped = 0; + for row in 0..8 { + for col in 1..8 { + let (x, y) = (sb_x + col * 8, sb_y + row * 8); + let raster = Reach::of(8, x, y, width, height, fctx).below_left; + let vert = { + let _guard = Reach::vert_ab_partition(); + Reach::of(8, x, y, width, height, fctx).below_left + }; + // The TR square of a VERT_A/_B sits at an even row, odd + // column; every other slot must be untouched by the guard. + if row % 2 == 0 && col % 2 == 1 { + assert!(!raster, "raster below_left at row={row} col={col}"); + assert!(vert, "vert below_left at row={row} col={col}"); + flipped += 1; + } else { + assert_eq!(raster, vert, "guard moved row={row} col={col}"); + } } } + assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); + // The guard is scoped: it must not leak past its own block. + assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); +} - /// A flat picture is a flat stream: every block predicts its neighbours' - /// average, which is the picture's own value, and codes nothing. - #[test] - fn a_flat_picture_costs_almost_nothing() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let mut picture = Picture::grey(128, 128); - picture.y.fill(97); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); - // The first block has no neighbour and predicts 128, so it carries a - // DC; every block after it predicts 97 and carries nothing. +/// An odd width or height is refused by name, not by however the padder +/// or the block coder would happen to fail on it. +#[test] +fn odd_dimensions_are_refused() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { + let picture = Picture::grey(width, height); + let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) + .expect_err(&format!("{width}x{height} is odd and must be refused")); assert!( - encoded.stream.len() < 100, - "{} bytes for a flat picture", - encoded.stream.len() + err.to_string().contains("even"), + "{width}x{height}: error was {err}" ); - for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { - assert_eq!(s, 97, "sample {i} of a flat picture"); - } } +} - /// The sizes the encoder refuses, refused for a reason rather than by - /// panicking somewhere below. Sizes off the 32x32 block grid encode fine - /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge - /// lands past the halfway point of whichever block it falls in, so - /// `PARTITION_NONE` or a single gathered split flag still says everything - /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16 - /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the - /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4 - /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred, - /// down to the in-frame 8x8s, no rectangular transform anywhere (the old - /// refusal here claimed otherwise and was wrong; see - /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_ - /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never - /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec - /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the - /// true edge always lands on an 8-luma-sample boundary in mi terms and a - /// 4x4 leaf -- which neither writer has -- is never asked for. What is - /// still refused is a malformed picture. - #[test] - fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) - .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split"); - encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx) - .expect("36 luma columns still round up to an even MiCols"); - - let mut short = Picture::grey(64, 64); - short.u.truncate(10); - assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); +/// A sequence at a size that is not a multiple of the block grid decodes +/// to the right frame count and the right size for every frame, +/// including the inter frames whose reference is the previous frame's +/// own (padded) reconstruction. +#[test] +fn sequence_round_trips_at_a_non_multiple_size() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (160usize, 96usize); + let pictures: Vec = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + assert_eq!(encoded.frames.len(), 3); + for (i, frame) in encoded.frames.iter().enumerate() { + assert_eq!( + (frame.reconstruction.width, frame.reconstruction.height), + (width, height), + "frame {i}: reconstruction size" + ); + } + // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the + // true (display) size a sequence's frames share, not the padded one. + assert_eq!( + ffprobe_size(&encoded.stream), + (width as u32, height as u32), + "sequence: ffprobe reports the true (display) size" + ); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); + assert_eq!(decoded.len(), 3, "decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { + assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } +} - /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own - /// column half only (`has_half` false on cols, true on rows) -- exactly - /// the single-axis straddle lane-av1-rect r7 wires through - /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean: - /// dav1d rejects the stream ("Invalid data found"). r7's falsification - /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is - /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own - /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every - /// `partition_context_lookup` entry this writer ever produces (no 4x4 - /// splits exist) has bit 0 clear, so the ctx is provably 0 for every - /// leaf regardless of neighbour state -- our writer already agreed with - /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise - /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a - /// spec-accurate fix in its own right (it matters once 4x4 exists), and - /// it does not regress the gate. r11 tell-for-tell traced two further, - /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read - /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both - /// leaves, when the second leaf's true above (or left) neighbour is the - /// first leaf itself -- fixed by threading the first leaf's mode into the - /// second leaf's context, mi-precise, like `record_mi` already does for - /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was - /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when - /// `reduced_tx_set` is false), but this crate's key frames set - /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts - /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2` - /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE` - /// symbol bits to desync everything after it. Fixed with a new - /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact - /// eset/size slot). Both fixes are provably correct against libaom - /// source and each closed part of the gap (leaf0's `eob` went from a - /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual - /// divergence remained in the `EOB_PT` symbol's decoded value despite an - /// aligned bit cost. r12 traced that residual with a fresh dual-trace - /// (do not reuse r11's committed logs, which predate its own fixes) and - /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded - /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but - /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` -- - /// every other `write_block` caller at 16x16 and up already passes - /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of - /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a - /// different amount of arithmetic range and derailed everything after - /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an - /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and - /// `write_leaf8` called only `record_mi` (the coefficient-context half), - /// never updating those coarse arrays itself -- so a *second* straddling - /// 16x16 quadrant stacked above or left of the first (never covered by - /// r11's same-call `prev_leaf` override, which only threads state - /// between the two leaves of one shared quadrant) read whatever stale - /// mode sat in that slot before either leaf ran. Fixed by writing the - /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing - /// (3) alone shrank the tell drift after leaf(0,8) from a decoder - /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell` - /// offset of a single unit; fixing (3)+(4) together still leaves a - /// residual divergence one leaf further in -- the decoder now reads - /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample - /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning - /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still - /// desyncs the stream by exactly the width of one earlier symbol -- not - /// yet isolated to a single named symbol. r15 found the last bug: the - /// header fix from r14 explained the rng skew fully, and the remaining - /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself -- - /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf - /// loop, once per leaf, so the first leaf's write clobbered the true - /// external neighbour mode the second leaf of the *same* straddling - /// quadrant still needed for its non-adjacency axis (a column-straddle - /// case: two leaves share one `outer_at` column index, so leaf 1's - /// write to `left_mode[r]` overwrote the real western neighbour before - /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and - /// doing it once, after the whole leaf loop, from the last (bottom/ - /// right-most) leaf's mode. The stream now round-trips through ffmpeg. - #[test] - fn a_single_axis_straddle_round_trips_through_ffmpeg() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (40usize, 32usize); - let picture = test_card(width, height); - let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); +/// 1280x720 -- the export size a real edith timeline hits -- is exactly +/// the "half straddle" class: 720 mod 32 == 16, so the true frame edge +/// falls at exactly half of the last row of 32x32 blocks (`has_half`'s +/// `pos + side_mi / 2 < bound` boundary), which is the case +/// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than +/// refusing. A key frame alone already covered this size; this proves the +/// inter tile writer's parity with it across a real multi-frame export. +#[test] +fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (1280usize, 720usize); + let pictures: Vec = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + assert_eq!(encoded.frames.len(), 3); + for (i, frame) in encoded.frames.iter().enumerate() { assert_eq!( - (encoded.reconstruction.width, encoded.reconstruction.height), - (width, height) - ); - if let Ok(path) = std::env::var("EC_AV1_DUMP") { - std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); - } - let decoded = ffmpeg_decode(&encoded.stream, width, height); - assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); - assert_eq!(decoded.u, encoded.reconstruction.u, "U"); - assert_eq!(decoded.v, encoded.reconstruction.v, "V"); + (frame.reconstruction.width, frame.reconstruction.height), + (width, height), + "frame {i}: reconstruction size" + ); + } + assert_eq!( + ffprobe_size(&encoded.stream), + (width as u32, height as u32), + "ffprobe reports the true (display) 1280x720 size" + ); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); + assert_eq!(decoded.len(), 3, "decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { + assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } +} - /// [`test_card`], panned `shift` samples to the right (wrapping), so a - /// sequence of these is a translation a motion search can actually find - /// — the content [`test_card`] itself draws, not a fresh pattern, so an - /// inter frame's rate against the key frame's is measuring the same - /// picture moving, not two different pictures. - pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; - let gradient = sx * 200.0 / width as f64; - let ripple = 30.0 - * (sx * std::f64::consts::PI / 23.0).sin() - * (y as f64 * std::f64::consts::PI / 37.0).cos(); - let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { - 40.0 - } else { - 0.0 - }; - picture.y[y * width + x] = - (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; - } - } - for y in 0..height / 2 { - for x in 0..width / 2 { - let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; - let i = y * width / 2 + x; - picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; - picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; - } - } - picture +/// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16 +/// leaf's own half (`has_half` at the SUB level) itself straddles the +/// true edge on one axis only. lane-av1-rect r7 wired the key frame +/// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly +/// this case; lane-av1inter8 extends the same leaf-8 path to inter +/// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s +/// straddling-16x16 branch), so an inter frame no longer refuses this +/// size either. This only proves the encoder does not error out -- see +/// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the +/// decoder-clean proof (a 3-frame sequence, so the inter path is +/// actually exercised). +#[test] +fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (640usize, 360usize); + let picture = Picture::grey(width, height); + encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) + .expect("key frame now codes the mod-32==8 straddle"); + + // `encode_sequence`'s second frame is the inter path: same size, now + // wired the same way. + let pictures = vec![picture.clone(), picture]; + encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) + .expect("inter frame now codes the mod-32==8 straddle too"); +} + +/// The r15 fix at production size: three 640x360 key frames (inter is +/// still refused at this size, per the test above, so this stands in for +/// the charter's "3-frame sequence" using three independent key frames of +/// shifted content), each proven decoder-clean through ffmpeg rather than +/// only encoder-clean. +#[test] +fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (640usize, 360usize); + for shift in [0i64, 7, 19] { + let picture = panned_test_card(width, height, shift); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); } +} - /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. - pub(super) fn ffmpeg_decode_sequence( - stream: &[u8], - width: usize, - height: usize, - frames: usize, - ) -> Vec { - let out = run_with_stdin( - ec_testkit::ffmpeg().args([ - "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", - ]), - stream, - ); - assert!( - out.status.success(), - "ffmpeg refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_bytes = luma + 2 * chroma; - assert_eq!( - out.stdout.len(), - frame_bytes * frames, - "expected {frames} 4:2:0 frames, ffmpeg said: {}", - String::from_utf8_lossy(&out.stderr) - ); - (0..frames) - .map(|i| { - let base = i * frame_bytes; - Picture { - width, - height, - y: out.stdout[base..base + luma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - u: out.stdout[base + luma..base + luma + chroma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - v: out.stdout[base + luma + chroma..base + frame_bytes] - .iter() - .map(|&v| u16::from(v)) - .collect(), - } - }) - .collect() +/// The 640x360 straddle class, but through the inter path an actual +/// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)): +/// proves the leaf-8 inter stream this round wires up is not just +/// encoder-clean (the test above) but decoder-clean against ffmpeg too. +#[test] +fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (640usize, 360usize); + let pictures: Vec = (0..4) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + assert_eq!(encoded.frames.len(), 4); + if let Ok(path) = std::env::var("EC_AV1_DUMP") { + std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); + } + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); + assert_eq!(decoded.len(), 4, "decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { + assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); } +} - /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`] - /// makes for a key frame, extended down the reference chain: each inter - /// frame's reconstruction predicts from the previous frame's own decoded - /// reconstruction, so a single sample of drift anywhere would propagate - /// into every frame after it -- which is why every frame is checked, not - /// just the last one, and why this is an equality and not a tolerance. - #[test] - fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let (width, height) = (128usize, 64usize); - let pictures: Vec = (0..5) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - assert_eq!(encoded.frames.len(), 5); - - let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); - assert_eq!( - encoded.frames.len(), - decoded.len(), - "frame count: ours vs ffmpeg" - ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); +/// A striped picture, running one way or the other. The stripes are what +/// separates a vertical predictor from a horizontal one: a mode search +/// reading a transposed edge would pick the wrong one of the pair, which no +/// symmetric picture would show. +pub(super) fn stripes(width: usize, height: usize, vertical: bool) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let along = if vertical { x } else { y }; + picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; } + } + picture +} - eprintln!("frame bytes luma PSNR (dB) inter share"); - for (i, frame) in encoded.frames.iter().enumerate() { - eprintln!( - "{i:5} {:5} {:14.2} {:11.2}", - frame.stream.len(), - psnr(&frame.reconstruction.y, &pictures[i].y), - frame.inter_block_share - ); - } +/// Where two planes first disagree, and by how much: a mismatch reported as +/// a position says which block and which sample of it went wrong, which a +/// pair of thousand-sample arrays does not. A length difference counts as a +/// disagreement: `zip` stops at the shorter plane, so a short one would +/// otherwise compare exact over the prefix the two share. +pub(super) fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option { + if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) { + let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); + return Some(format!( + "{differ} samples differ, first at ({}, {}): ours {} theirs {}", + i % width, + i / width, + ours[i], + theirs[i] + )); + } + if ours.len() != theirs.len() { + return Some(format!( + "no sample in the shared prefix differs, but ours is {} samples and theirs is {}", + ours.len(), + theirs.len() + )); } + None +} - // The same sequence through OUR OWN decoder, sample-exact against the - // encoder's reconstruction. ffmpeg stays the bitstream oracle - // ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no - // divergence point at all, while our decoder can be traced symbol by - // symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is - // the instrument the inter `TxMode::Select` hunt lacked; on failure it - // names the first differing frame, plane and position. - // lane-sb128b: the writer used to price a `NEWMV` residual against - // `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the - // write-time stack could not carry, while the drl symbols signalled the - // clamped index -- so the decoder derived a DIFFERENT motion vector with - // the entropy stream still in sync, and the drift only surfaced frames - // later as a drl desync (on film B, as the encoder's own trial decode - // refusing a reference slot). - // - // The clamp needs a stack that shrinks between search and write, which - // is what a 128x128 superblock's visit order does; the counter is the - // point (class `gate-blind-to-feature`): a green round trip on a clip - // that never clamps proves nothing. - // - // `#[ignore]`: [`force_sb128`] moves a process-global. - // - // The drl-clamp cell this gate's counter used to gate is no longer gated - // here: it is covered by - // [`every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`], - // which enumerates the pricer's offer set against the writer's rule (see - // its doc). The clamp needs a stack that shrinks between search and - // write, which is what a 128x128 superblock's visit order would do -- but - // the pricer never offers an index this tree's `write_drl_idx` cannot - // signal, so no clip can provoke it (lane-av1recipehunt: 153 attempts, 0; - // widening the pricer to `0..5` fires the counter immediately, reverting - // silences it). `drl_clamp_hits` is kept as the tripwire for that fix. - - /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode - /// and one motion vector where the four 64x64 roots below spend four of - /// each (cen3's L1). The counter is the gate on the fixture (class - /// `gate-blind-to-feature`): a green round trip on a clip that never - /// codes a 128x128 block proves nothing. RED before the search existed - /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every - /// root by construction). - /// - /// Both readers: our own decoder sample-exact against the encoder's - /// reconstruction (a writer/reader desync surfaces as a pixel miss or a - /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle. - /// - /// `#[ignore]`: [`force_sb128`] moves a process-global. - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("smpte-1280x768.y4m"); - // A slow horizontal pan over a still pattern: whole 128x128 regions - // share one motion vector, which is exactly what a 128 root can code - // as one block and four 64 roots cannot. - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "smptebars=size=1600x768:rate=24"]) - .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) - .args(["-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); - let _ = take_b128_none_hits(); - let _ = crate::tile::take_sb128_none_hits(); - let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); - let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits()); - eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}"); - assert!( - coded > 0, - "no 128x128 block was coded on this clip, so it cannot witness the root search", - ); - assert_eq!( - won, coded, - "every 128x128 root the search took must be coded as one" - ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - let recon = &frame.reconstruction; - for (plane, got, want) in [ - ("luma", &dec.y, &recon.y), - ("U", &dec.u, &recon.u), - ("V", &dec.v, &recon.v), +/// Every mode the encoder offers has to predict what the decoder predicts, +/// not just the ones a particular picture happens to choose: each is forced +/// over a whole picture and the reconstruction gated against ffmpeg. +#[test] +fn every_mode_decodes_to_what_the_encoder_predicted() { + let _knobs = crate::speed::knob_write(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + // A mode ablation measures the MODE search: a filter-intra block is + // coded `DC_PRED` whatever mode the arm forces, so it would fail the + // "the encoder coded something else" check for a reason that is not + // about the mode search at all. + force_filter_intra(Some(false)); + // 128 wide is a whole number of superblocks and 160 is not: the last + // superblock of a 160-wide row is half a one, whose blocks have no + // above-right samples inside the frame at all. + for (width, height) in [(128, 96), (160, 96)] { + let picture = test_card(width, height); + for mode in KEY_FRAME_MODES { + let encoded = + encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap(); + let decoded = ffmpeg_decode(&encoded.stream, width, height); + for (plane, ours, theirs, stride) in [ + ("luma", &encoded.reconstruction.y, &decoded.y, width), + ("U", &encoded.reconstruction.u, &decoded.u, width / 2), + ("V", &encoded.reconstruction.v, &decoded.v, width / 2), ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - differ, - 0, - "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ - own reconstruction", - got.len() - ); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() + assert!( + first_difference(ours, theirs, stride).is_none(), + "{width}x{height} mode {mode}, {plane}: {}", + first_difference(ours, theirs, stride).unwrap() ); } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" - ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); + assert!( + encoded.modes.iter().all(|&m| m == mode), + "mode {mode}: the encoder coded something else" + ); } } +} - /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma - /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The - /// same pan the skip-only witness above uses, with the arm FORCED - /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual - /// about once per frame, which witnesses the shape but not every context - /// it reads, and forcing codes all 420 roots of the clip through it. RED - /// before this lane by construction (`write_inter_block_128` refused - /// every non-skip 128 block, so no such block existed to decode), and RED - /// again on the first draft of the writer, whose neighbour band recorded - /// `skip = true` for a block that carries a residual -- the next root's - /// `skip` symbol then took CDF row 1 where the reader takes row 0. - /// - /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces - /// the skip arm's cost unconditionally (that is what makes the writer see - /// the residual), and the cost model moved under it since lane-b128r -- - /// lane-rectdq made every non-skipped root pay its delta_q group and the - /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root - /// lost its partition at ALL 420 roots and the writer coded none. q=60 - /// puts 52 written blocks back on this clip; the `coded > 0` assert below - /// is the guard that catches the next such drift. - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("smpte-pan-1280x768.y4m"); - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "smptebars=size=1600x768:rate=24"]) - .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) - .args(["-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); - let _ = take_b128_residual_hits(); - let _ = crate::tile::take_sb128_residual_hits(); - force_b128_residual(true); - let encoded = encode_sequence(&pictures, 60, 0.5).unwrap(); - let (won, coded) = ( - take_b128_residual_hits(), - crate::tile::take_sb128_residual_hits(), - ); - eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}"); +/// The search has to follow the picture: vertical stripes are cheapest +/// predicted from the row above, horizontal ones from the column to the +/// left. Reading the edges the other way round would swap the two answers +/// while leaving every fidelity gate intact. +#[test] +fn the_search_picks_the_direction_the_picture_runs() { + let _knobs = crate::speed::knob_write(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]: + // a filter-intra block is coded `DC_PRED` whatever mode the arm + // offers, and these stripes are SCREEN content, where the filter arm + // now searches its own transform depth (lane-fitu) and wins outright + // -- which says nothing about the mode search this gate measures. + force_filter_intra(Some(false)); + for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { + let picture = stripes(128, 96, vertical); + // Only the pair, because on stripes a third mode predicts exactly + // what the right one of the pair does -- PAETH reads the corner and + // the left column, which a striped picture makes equal -- and the + // tie then goes to whichever is cheaper to name, which is not what + // this gate is about. + let encoded = + encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx) + .unwrap(); + // The first block of the picture has neither neighbour, so it + // cannot tell the modes apart; every other one can. + let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); assert!( - coded > 0, - "no 128x128 block carried a residual on this clip, so it cannot witness the arm", - ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - let recon = &frame.reconstruction; - for (plane, got, want) in [ - ("luma", &dec.y, &recon.y), - ("U", &dec.u, &recon.u), - ("V", &dec.v, &recon.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - differ, - 0, - "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ - own reconstruction", - got.len() - ); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" + picked * 2 > encoded.modes.len() - 1, + "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", + encoded.modes.len() - 1, + encoded.modes ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); - } } +} - /// lane-edge128: a 128x128 root block WITH a residual on a clip whose - /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec - /// 5.11.56) codes ONE literal for the block that first reaches a unit and - /// copies it over every unit the block SPANS, so the four units of a 128 - /// root share one index -- while the encoder's CDEF search prices a - /// preset per unit and its filter replay applied all four. Only the first - /// reached the stream, so every decoder filtered the other three with the - /// origin's strengths and the encoder's reconstruction (the picture the - /// next frame predicts from) was a filter apart from what a decoder - /// produces. RED before this lane on the native BD gate's bars 2160p row - /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples, - /// the rows above the 128 superblock's own edge); the stream itself was - /// always right -- ffmpeg and our own decoder agreed with each other and - /// disagreed with the encoder. - /// - /// `take_cdef_covered_units` is the gate on the fixture (class - /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair - /// for the whole frame codes no literal at all and witnesses nothing. - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2-1280x768.y4m"); - // Detailed synthetic content: its CDEF search spends more than one - // strength pair, which is what puts a `cdef_idx` literal in the tile. - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "testsrc2=size=1280x768:rate=24"]) - .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); - force_b128_root(true); - force_b128_residual(true); - let _ = crate::tile::take_sb128_residual_hits(); - let _ = crate::filter_search::take_cdef_covered_units(); - let encoded = encode_sequence(&pictures, 90, 0.5).unwrap(); - let coded = crate::tile::take_sb128_residual_hits(); - let covered = crate::filter_search::take_cdef_covered_units(); - eprintln!( - "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \ - another unit's literal: {covered}" - ); +/// What the search is for: the same picture, at the same quantizer, coded +/// smaller and more faithfully than DC alone can manage. +/// Rate saved at matched fidelity, over a three-point ladder: the trapezoid +/// between the two rate-distortion curves in log-rate against PSNR, as a +/// fraction of the reference's rate. Negative means the second curve costs +/// less for the same picture. +pub(super) fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { + let low = reference[0].0.max(other[0].0); + let high = reference[reference.len() - 1] + .0 + .min(other[other.len() - 1].0); + // lane-av1tx: `TxMode::Select` moved the directional ladder clear of + // the non-directional one on the synthetic diagonals -- every point + // both higher in PSNR *and* lower in rate -- so there is no PSNR band + // to integrate over any more. A curve that dominates that way has + // saved everything the measure can express (the + // `instrument-at-bound` class: the answer is at the instrument's own + // edge, not undefined), so name it rather than panicking; anything + // less clean than strict dominance still is. + if high <= low { + let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); + let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); + let dominates = + other[0].0 > reference[reference.len() - 1].0 && other_hi_rate <= ref_lo_rate; assert!( - coded > 0, - "no 128x128 block carried a residual on this clip" + dominates, + "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" + ); + return -1.0; + } + let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { + let i = curve + .windows(2) + .position(|w| psnr >= w[0].0 && psnr <= w[1].0) + .unwrap_or(0); + let (x0, y0) = curve[i]; + let (x1, y1) = curve[i + 1]; + y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) + }; + let steps = 64; + let mut area = 0.0; + for step in 0..steps { + let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); + area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); + } + 10f64.powf(area / f64::from(steps)) - 1.0 +} + +/// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by +/// fidelity. +pub(super) fn ladder( + picture: &Picture, + modes: &[u8], + fctx: &crate::decode::FrameCtx, +) -> Vec<(f64, f64)> { + // A mode ablation measures the MODE search: the palette would code + // these synthetic two-colour pictures losslessly under every arm and + // leave nothing to compare (see [`force_screen`]). + force_screen(Some(false)); + // Same reason, for the filter-intra candidate: it wins blocks under + // BOTH arms of a mode ablation and so cancels the difference the + // ablation measures (class `gate-recipe-confound`). + force_filter_intra(Some(false)); + let mut points: Vec<(f64, f64)> = [110u8, 90, 70] + .iter() + .map(|&q| { + let encoded = + encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap(); + ( + psnr(&encoded.reconstruction.y, picture.y.as_slice()), + (encoded.stream.len() as f64).log10(), + ) + }) + .collect(); + points.sort_by(|a, b| a.0.total_cmp(&b.0)); + points +} + +/// What the search is for: the same pictures cost less to code at the same +/// fidelity than DC prediction alone can manage. A picture that runs one +/// way saves far more than a busy one, which is the shape a working +/// directional pair has. +#[test] +fn the_search_beats_dc_alone() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + for (name, picture, want) in [ + ("test card", test_card(160, 96), -0.05), + ("stripes", stripes(160, 96, true), -0.40), + ] { + let saved = bd_rate( + &ladder(&picture, &[DC_PRED], fctx), + &ladder(&picture, &NON_DIRECTIONAL, fctx), ); assert!( - covered > 0, - "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \ - cannot witness the rule", - ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - for (plane, got, want) in [ - ("luma", &dec.y, &frame.reconstruction.y), - ("U", &dec.u, &frame.reconstruction.u), - ("V", &dec.v, &frame.reconstruction.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" + saved < want, + "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", + saved * 100.0, + -want * 100.0 ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); - } } +} - /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves - /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a - /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now - /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own - /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the - /// rect partition with [`force_b128_rect`]) so every inter root of the - /// clip goes through it; the `coded > 0` assert is the guard that catches - /// the next fixture drift (the whole-128 twin of this witness went RED - /// twice that way). - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("smpte-pan-1280x768.y4m"); - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "smptebars=size=1600x768:rate=24"]) - .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) - .args(["-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); - force_b128_rect(1); - force_b128_rectres(true); - let _ = take_b128_rectres_hits(); - let _ = crate::tile::take_sb128_rectres_hits(); - let encoded = encode_sequence(&pictures, 60, 0.5).unwrap(); - let (won, coded) = ( - take_b128_rectres_hits(), - crate::tile::take_sb128_rectres_hits(), - ); - eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}"); - assert!( - coded > 0, - "no 128x64 half carried a residual on this clip, so it cannot witness the arm", - ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - let recon = &frame.reconstruction; - for (plane, got, want) in [ - ("luma", &dec.y, &recon.y), - ("U", &dec.u, &recon.u), - ("V", &dec.v, &recon.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - differ, - 0, - "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ - own reconstruction", - got.len() - ); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" - ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); +/// A picture whose stripes run along a diagonal, one way or the other. +/// This is to the directional modes what [`stripes`] is to the vertical and +/// horizontal pair: a predictor that walked the edge in the wrong direction +/// would answer the two pictures the same way round. +pub(super) fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let along = if down_right { x + height - y } else { x + y }; + picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; } } + picture +} - /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE - /// pieces carry residuals -- the 128x64 half through the two-chunk arm, - /// the two 64x64 squares through the one-chunk arm (the shape libaom's - /// own AB partitions earn their keep with). testsrc2 at 12 frames, the - /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose - /// reference picture the GOP has not produced yet, which refuses before - /// any AB root is coded. - /// - /// Runs only inside `superblock_size_global_suite`. - fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2-1280x768.y4m"); - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "testsrc2=size=1280x768:rate=24"]) - .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); - force_b128_ab(4); - force_b128_rectres(true); - let _ = take_b128_rectres_hits(); - let _ = crate::tile::take_sb128_rectres_hits(); - let encoded = encode_sequence(&pictures, 60, 0.5).unwrap(); - let (won, coded) = ( - take_b128_rectres_hits(), - crate::tile::take_sb128_rectres_hits(), - ); - eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}"); - assert!( - coded > 0, - "no AB piece carried a residual on this clip, so it cannot witness the arm", - ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - let recon = &frame.reconstruction; - for (plane, got, want) in [ - ("luma", &dec.y, &recon.y), - ("U", &dec.u, &recon.u), - ("V", &dec.v, &recon.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - differ, - 0, - "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ - own reconstruction", - got.len() - ); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); +/// The mode picked by the most blocks of a picture, ignoring the first +/// block, which has no neighbours to tell the modes apart with. +pub(super) fn favourite_mode( + picture: &Picture, + fctx: &crate::decode::FrameCtx, +) -> (u8, usize, usize) { + // A mode ablation measures the MODE search: the palette would code + // these synthetic two-colour pictures losslessly under every arm and + // leave nothing to compare (see [`force_screen`]). + force_screen(Some(false)); + let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); + let blocks = &encoded.modes[1..]; + let mut counts = [0usize; 13]; + for &mode in blocks { + counts[usize::from(mode)] += 1; + } + let (mode, count) = counts + .iter() + .enumerate() + .max_by_key(|&(_, count)| *count) + .expect("thirteen modes"); + (mode as u8, *count, blocks.len()) +} + +/// The search has to follow a diagonal the way it runs: stripes down and to +/// the right are cheapest predicted at 135 degrees, stripes down and to the +/// left at 45. A walk that stepped the wrong way along the edge, or read +/// the above row where it should read the left column, would swap these. +#[test] +fn the_search_picks_the_diagonal_the_picture_runs() { + let _knobs = crate::speed::knob_write(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { + let picture = diagonal(160, 96, down_right); + let (mode, count, blocks) = favourite_mode(&picture, fctx); assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" + mode, want, + "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); - } } +} - /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ - /// half WITH a residual under a clip whose CDEF search codes a - /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin - /// and the decoder stamps BOTH units it spans with it, so the owner map - /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to - /// collapse the pair -- exactly the bug class that broke bars 2160p at - /// the whole-128 root. RED before this lane by construction: no rect - /// piece could carry a residual, so no such literal existed. - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2-1280x768.y4m"); - // Detailed synthetic content: its CDEF search spends more than one - // strength pair, which is what puts a `cdef_idx` literal in the tile. - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "testsrc2=size=1280x768:rate=24"]) - .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); - force_b128_rect(1); - force_b128_rectres(true); - let _ = crate::tile::take_sb128_rectres_hits(); - let _ = crate::filter_search::take_cdef_covered_units(); - let encoded = encode_sequence(&pictures, 90, 0.5).unwrap(); - let coded = crate::tile::take_sb128_rectres_hits(); - let covered = crate::filter_search::take_cdef_covered_units(); - eprintln!( - "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \ - another unit's literal: {covered}" +/// What the directional modes are for: a picture that runs along a diagonal +/// costs far less to code with them than the seven that read only their own +/// edges can manage, and a picture that runs no particular way costs no +/// more. The second half is the one that bites: a mode set the search +/// cannot price is a mode set that loses rate on content that does not want +/// it, which is what costing the mode symbol is for. +#[test] +fn the_diagonals_beat_the_modes_that_read_no_further() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + for (name, picture, want) in [ + ("down-right", diagonal(160, 96, true), -0.20), + ("down-left", diagonal(160, 96, false), -0.20), + ("test card", test_card(160, 96), 0.01), + ] { + let saved = bd_rate( + &ladder(&picture, &NON_DIRECTIONAL, fctx), + &ladder(&picture, &KEY_FRAME_MODES, fctx), ); - assert!(coded > 0, "no 128x64 half carried a residual on this clip"); assert!( - covered > 0, - "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \ - cannot witness the rule", + saved < want, + "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", + saved * 100.0, + -want * 100.0 ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - for (plane, got, want) in [ - ("luma", &dec.y, &frame.reconstruction.y), - ("U", &dec.u, &frame.reconstruction.u), - ("V", &dec.v, &frame.reconstruction.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" - ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); - } } +} - /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block - /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same - /// `write_compound_block` chain every smaller compound block takes, at a - /// window it had never been exercised at. RED before this lane: the - /// search passed an empty compound list at the 128 root, so the count was - /// 0 and no such block existed to decode. - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_128_root_compound_block_decodes_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2-1280x768.y4m"); - // Moving objects that occlude each other: a pan is coded by one - // reference outright, and a compound pair only pays where the two - // references disagree. - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "testsrc2=size=1280x768:rate=24"]) - .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); - // The compound candidate wins the 128 block's own search on this pan - // but the root then loses to its four cells, so the root is forced - // (the residual arm is left at its default, off). - force_b128_root(true); - let _ = take_b128_compound_hits(); - let _ = crate::tile::take_sb128_compound_hits(); - let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); - let (won, coded) = ( - take_b128_compound_hits(), - crate::tile::take_sb128_compound_hits(), - ); - eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}"); - assert!( - coded > 0, - "no compound 128x128 block was coded on this clip" - ); - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - for (plane, got, want) in [ - ("luma", &dec.y, &frame.reconstruction.y), - ("U", &dec.u, &frame.reconstruction.u), - ("V", &dec.v, &frame.reconstruction.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); - assert_eq!( - got.len(), - want.len(), - "frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "frame count: ours vs ffmpeg" - ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); - assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); - } +/// A mode the encoder cannot predict must be refused rather than coded as +/// something else, and a search with nothing to choose from likewise. +#[test] +fn a_mode_the_encoder_cannot_predict_is_refused() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let picture = test_card(64, 64); + let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) + .unwrap_err() + .to_string(); + assert!( + message.contains("intra mode 13"), + "the refusal must name the mode, got {message}" + ); + assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); +} + +/// The picture that comes back is the picture that went in, to within the +/// quantizer. A prediction that read the wrong neighbours, or a block +/// written into the wrong place, would still decode to what the encoder +/// reconstructed — it is this gate that says the reconstruction is of the +/// right picture. +#[test] +fn the_encoded_picture_is_the_one_that_went_in() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let picture = test_card(160, 96); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + let luma = psnr(&encoded.reconstruction.y, &picture.y); + assert!(luma > 36.0, "luma PSNR {luma} at q 100"); + for (plane, (got, want)) in [ + (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), + (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), + ] + .iter() + .enumerate() + { + let chroma = psnr(got, want); + assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); } +} - /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT` - /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one - /// square. Three passes over one `testsrc2` clip: - /// - /// * HORZ forced at every root ([`force_b128_rect`]), so every context - /// the 128x64 shape reads is exercised rather than the handful the RD - /// would pick; - /// * VERT forced the same way; - /// * UNFORCED, which is the count the gate rows are read against -- the - /// same clip with the RD free to choose among NONE / HORZ / VERT / - /// four superblocks. - /// - /// Each pass is sample-exact against the encoder's own reconstruction - /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch - /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED - /// before this lane by construction: `write_sb128_root` could only name - /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three. - /// - /// Runs only inside `superblock_size_global_suite`. - fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - force_sb128(true); - let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let clip = dir.join("testsrc2-1280x768.y4m"); - let ok = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi"]) - .args(["-i", "testsrc2=size=1280x768:rate=24"]) - .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) - .arg(&clip) - .status() - .expect("ffmpeg failed to run") - .success(); - assert!(ok, "ffmpeg could not write the synthetic clip"); - let (width, height) = (1280usize, 768usize); - let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); - let mut unforced = (0usize, 0usize); - for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] { - force_b128_rect(force); - let _ = take_b128_horz_hits(); - let _ = take_b128_vert_hits(); - let _ = crate::tile::take_sb128_horz_hits(); - let _ = crate::tile::take_sb128_vert_hits(); - let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); - let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits()); - let (coded_h, coded_v) = ( - crate::tile::take_sb128_horz_hits(), - crate::tile::take_sb128_vert_hits(), - ); - eprintln!( - "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \ - {coded_h} 128x64 + {coded_v} 64x128 halves" - ); - match force { - 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"), - 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"), - // The unforced count is REPORTED, not asserted: it is the - // number the gate is read against, and a zero here would be - // an RD result, not a defect (the forced passes already prove - // the writer and the reader agree on the shape). - _ => unforced = (won_h, won_v), - } - let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); - assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count"); - for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { - for (plane, got, want) in [ - ("luma", &dec.y, &frame.reconstruction.y), - ("U", &dec.u, &frame.reconstruction.u), - ("V", &dec.v, &frame.reconstruction.v), - ] { - let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); - assert_eq!( - differ, 0, - "{label} frame {i}: {plane} -- {differ} samples differ" - ); - assert_eq!( - got.len(), - want.len(), - "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}", - got.len(), - want.len() - ); - } - } - let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); - assert_eq!( - encoded.frames.len(), - ff.len(), - "{label}: frame count: ours vs ffmpeg" +/// A finer quantizer costs bits and buys fidelity, and a wider deadzone +/// does the opposite. Both are monotone, which is what a rate-distortion +/// loop above this will assume. +#[test] +fn fidelity_and_rate_move_with_the_quantizer() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let picture = test_card(128, 128); + let mut previous: Option<(usize, f64)> = None; + for &q in &[70u8, 90, 110] { + let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); + let quality = psnr(&encoded.reconstruction.y, &picture.y); + if let Some((bytes, better)) = previous { + assert!( + encoded.stream.len() < bytes, + "q {q}: {} bytes", + encoded.stream.len() ); - for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { - assert_eq!( - dec.y, frame.reconstruction.y, - "{label} frame {i}: ffmpeg luma" - ); - assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U"); - assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V"); - } + assert!(quality < better, "q {q}: PSNR {quality}"); } - force_b128_rect(0); - eprintln!( - "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames", - unforced.0, unforced.1 + previous = Some((encoded.stream.len(), quality)); + } + + // The deadzone half of this claim lives in + // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now: + // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding + // every zeroing, the deadzone no longer moves a coded stream + // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against + // fewer at 0.5 on this 128x128 card), and that is the pass doing its + // job, not a quantiser defect. + + // Bytes must not jump up across a q-context boundary: a wrong CDF + // table for the far side would show up as a rate discontinuity here, + // even though a coarser quantizer always codes no more than a finer + // one on the same picture. + // + // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since + // chroma searches its own mode, a coarser quantizer can pick a + // *different* uv_mode on a block whose modes now cost nearly the + // same, and the search prices that symbol against the static default + // CDF while the writer codes it against an adapted one -- 311 -> 319 + // bytes at q 120->121 on this picture. The table this gate is really + // watching would move the rate by far more than the mode churn does. + // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the + // same block can also change transform DEPTH between two neighbouring + // quantizers (297 -> 315 bytes at q 120->121 here), and the depth + // symbol is priced off the static CDF row 0 for the same reason the + // uv_mode one is. + // Ceiling: a q-context table wrong by under 10% would pass. Upgrade + // path is pricing through the adapting CDF state (what + // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the + // drift of), after which the exact bound comes back. + for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { + let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx) + .unwrap() + .stream + .len(); + let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx) + .unwrap() + .stream + .len(); + assert!( + hi_bytes as f64 <= lo_bytes as f64 * 1.10, + "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" ); } +} -/// Restores the process-global 128-superblock state the folded cases move: -/// the sb128 mode back to its prior value, and every `force_b128_*` arm back -/// to off, so one case cannot leak into the next. -fn restore_superblock_globals(prior_sb128: u8) { - super::split::ENC_SB128.store(prior_sb128, std::sync::atomic::Ordering::Relaxed); - force_b128_residual(false); - force_b128_root(false); - force_b128_rectres(false); - force_b128_rect(0); - force_b128_ab(0); +/// A flat picture is a flat stream: every block predicts its neighbours' +/// average, which is the picture's own value, and codes nothing. +#[test] +fn a_flat_picture_costs_almost_nothing() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let mut picture = Picture::grey(128, 128); + picture.y.fill(97); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + // The first block has no neighbour and predicts 128, so it carries a + // DC; every block after it predicts 97 and carries nothing. + assert!( + encoded.stream.len() < 100, + "{} bytes for a flat picture", + encoded.stream.len() + ); + for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { + assert_eq!(s, 97, "sample {i} of a flat picture"); + } } -/// The ten cases that set the process-global superblock size, folded into -/// one ignored test so they never share a process with another such test. -/// Each case runs under `catch_unwind`; every failing name is reported. -/// -/// cargo test -p ec-av1 --release --lib -- --ignored \ -/// superblock_size_global_suite --nocapture +/// The sizes the encoder refuses, refused for a reason rather than by +/// panicking somewhere below. Sizes off the 32x32 block grid encode fine +/// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge +/// lands past the halfway point of whichever block it falls in, so +/// `PARTITION_NONE` or a single gathered split flag still says everything +/// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16 +/// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the +/// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4 +/// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred, +/// down to the in-frame 8x8s, no rectangular transform anywhere (the old +/// refusal here claimed otherwise and was wrong; see +/// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_ +/// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never +/// straddle either, because `MiCols`/`MiRows` are always EVEN (spec +/// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the +/// true edge always lands on an 8-luma-sample boundary in mi terms and a +/// 4x4 leaf -- which neither writer has -- is never asked for. What is +/// still refused is a malformed picture. #[test] -#[ignore = "sets the process-global superblock size: run it alone"] -fn superblock_size_global_suite() { - let prior = super::split::ENC_SB128.load(std::sync::atomic::Ordering::Relaxed); - let cases: [(&str, fn()); 10] = [ - ( - "a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact", - a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact, - ), - ( - "a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders", - a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders, - ), - ( - "a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact", - a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact, - ), - ( - "a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders", - a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders, - ), - ( - "an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders", - an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders, - ), - ( - "a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact", - a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact, - ), - ( - "a_128_root_compound_block_decodes_exact_through_both_decoders", - a_128_root_compound_block_decodes_exact_through_both_decoders, - ), - ( - "a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders", - a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders, - ), - ( - "a_128_root_ab_shapes_decode_exact_through_both_decoders", - super::more_tests::a_128_root_ab_shapes_decode_exact_through_both_decoders, - ), - ( - "a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact", - crate::encoder::tests::a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact, - ), - ]; - let mut failures = Vec::new(); - for (name, case) in cases { - if std::panic::catch_unwind(std::panic::AssertUnwindSafe(case)).is_err() { - failures.push(name); +fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) + .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split"); + encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx) + .expect("36 luma columns still round up to an even MiCols"); + + let mut short = Picture::grey(64, 64); + short.u.truncate(10); + assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); +} + +/// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own +/// column half only (`has_half` false on cols, true on rows) -- exactly +/// the single-axis straddle lane-av1-rect r7 wires through +/// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean: +/// dav1d rejects the stream ("Invalid data found"). r7's falsification +/// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is +/// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own +/// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every +/// `partition_context_lookup` entry this writer ever produces (no 4x4 +/// splits exist) has bit 0 clear, so the ctx is provably 0 for every +/// leaf regardless of neighbour state -- our writer already agreed with +/// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise +/// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a +/// spec-accurate fix in its own right (it matters once 4x4 exists), and +/// it does not regress the gate. r11 tell-for-tell traced two further, +/// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read +/// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both +/// leaves, when the second leaf's true above (or left) neighbour is the +/// first leaf itself -- fixed by threading the first leaf's mode into the +/// second leaf's context, mi-precise, like `record_mi` already does for +/// coefficients; (2) `TxbSet::Luma8`'s transform-type table was +/// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when +/// `reduced_tx_set` is false), but this crate's key frames set +/// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts +/// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2` +/// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE` +/// symbol bits to desync everything after it. Fixed with a new +/// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact +/// eset/size slot). Both fixes are provably correct against libaom +/// source and each closed part of the gap (leaf0's `eob` went from a +/// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual +/// divergence remained in the `EOB_PT` symbol's decoded value despite an +/// aligned bit cost. r12 traced that residual with a fresh dual-trace +/// (do not reuse r11's committed logs, which predate its own fixes) and +/// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded +/// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but +/// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` -- +/// every other `write_block` caller at 16x16 and up already passes +/// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of +/// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a +/// different amount of arithmetic range and derailed everything after +/// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an +/// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and +/// `write_leaf8` called only `record_mi` (the coefficient-context half), +/// never updating those coarse arrays itself -- so a *second* straddling +/// 16x16 quadrant stacked above or left of the first (never covered by +/// r11's same-call `prev_leaf` override, which only threads state +/// between the two leaves of one shared quadrant) read whatever stale +/// mode sat in that slot before either leaf ran. Fixed by writing the +/// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing +/// (3) alone shrank the tell drift after leaf(0,8) from a decoder +/// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell` +/// offset of a single unit; fixing (3)+(4) together still leaves a +/// residual divergence one leaf further in -- the decoder now reads +/// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample +/// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning +/// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still +/// desyncs the stream by exactly the width of one earlier symbol -- not +/// yet isolated to a single named symbol. r15 found the last bug: the +/// header fix from r14 explained the rng skew fully, and the remaining +/// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself -- +/// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf +/// loop, once per leaf, so the first leaf's write clobbered the true +/// external neighbour mode the second leaf of the *same* straddling +/// quadrant still needed for its non-adjacency axis (a column-straddle +/// case: two leaves share one `outer_at` column index, so leaf 1's +/// write to `left_mode[r]` overwrote the real western neighbour before +/// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and +/// doing it once, after the whole leaf loop, from the last (bottom/ +/// right-most) leaf's mode. The stream now round-trips through ffmpeg. +#[test] +fn a_single_axis_straddle_round_trips_through_ffmpeg() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (40usize, 32usize); + let picture = test_card(width, height); + let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); + assert_eq!( + (encoded.reconstruction.width, encoded.reconstruction.height), + (width, height) + ); + if let Ok(path) = std::env::var("EC_AV1_DUMP") { + std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); + } + let decoded = ffmpeg_decode(&encoded.stream, width, height); + assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); + assert_eq!(decoded.u, encoded.reconstruction.u, "U"); + assert_eq!(decoded.v, encoded.reconstruction.v, "V"); +} + +/// [`test_card`], panned `shift` samples to the right (wrapping), so a +/// sequence of these is a translation a motion search can actually find +/// — the content [`test_card`] itself draws, not a fresh pattern, so an +/// inter frame's rate against the key frame's is measuring the same +/// picture moving, not two different pictures. +pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; + let gradient = sx * 200.0 / width as f64; + let ripple = 30.0 + * (sx * std::f64::consts::PI / 23.0).sin() + * (y as f64 * std::f64::consts::PI / 37.0).cos(); + let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { + 40.0 + } else { + 0.0 + }; + picture.y[y * width + x] = (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; + } + } + for y in 0..height / 2 { + for x in 0..width / 2 { + let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; + let i = y * width / 2 + x; + picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; + picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; } - restore_superblock_globals(prior); } - assert!(failures.is_empty(), "failed cases: {failures:?}"); + picture +} + +/// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. +pub(super) fn ffmpeg_decode_sequence( + stream: &[u8], + width: usize, + height: usize, + frames: usize, +) -> Vec { + let out = run_with_stdin( + ec_testkit::ffmpeg().args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", + ]), + stream, + ); + assert!( + out.status.success(), + "ffmpeg refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + let frame_bytes = luma + 2 * chroma; + assert_eq!( + out.stdout.len(), + frame_bytes * frames, + "expected {frames} 4:2:0 frames, ffmpeg said: {}", + String::from_utf8_lossy(&out.stderr) + ); + (0..frames) + .map(|i| { + let base = i * frame_bytes; + Picture { + width, + height, + y: out.stdout[base..base + luma] + .iter() + .map(|&v| u16::from(v)) + .collect(), + u: out.stdout[base + luma..base + luma + chroma] + .iter() + .map(|&v| u16::from(v)) + .collect(), + v: out.stdout[base + luma + chroma..base + frame_bytes] + .iter() + .map(|&v| u16::from(v)) + .collect(), + } + }) + .collect() +} + +/// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`] +/// makes for a key frame, extended down the reference chain: each inter +/// frame's reconstruction predicts from the previous frame's own decoded +/// reconstruction, so a single sample of drift anywhere would propagate +/// into every frame after it -- which is why every frame is checked, not +/// just the last one, and why this is an equality and not a tolerance. +#[test] +fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let (width, height) = (128usize, 64usize); + let pictures: Vec = (0..5) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + assert_eq!(encoded.frames.len(), 5); + + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); + assert_eq!( + encoded.frames.len(), + decoded.len(), + "frame count: ours vs ffmpeg" + ); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); + } + + eprintln!("frame bytes luma PSNR (dB) inter share"); + for (i, frame) in encoded.frames.iter().enumerate() { + eprintln!( + "{i:5} {:5} {:14.2} {:11.2}", + frame.stream.len(), + psnr(&frame.reconstruction.y, &pictures[i].y), + frame.inter_block_share + ); + } } + +// The same sequence through OUR OWN decoder, sample-exact against the +// encoder's reconstruction. ffmpeg stays the bitstream oracle +// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no +// divergence point at all, while our decoder can be traced symbol by +// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is +// the instrument the inter `TxMode::Select` hunt lacked; on failure it +// names the first differing frame, plane and position. +// lane-sb128b: the writer used to price a `NEWMV` residual against +// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the +// write-time stack could not carry, while the drl symbols signalled the +// clamped index -- so the decoder derived a DIFFERENT motion vector with +// the entropy stream still in sync, and the drift only surfaced frames +// later as a drl desync (on film B, as the encoder's own trial decode +// refusing a reference slot). +// +// The clamp needs a stack that shrinks between search and write, which +// is what a 128x128 superblock's visit order does; the counter is the +// point (class `gate-blind-to-feature`): a green round trip on a clip +// that never clamps proves nothing. +// +// `#[ignore]`: [`force_sb128`] moves a process-global. +// +// The drl-clamp cell this gate's counter used to gate is no longer gated +// here: it is covered by +// [`every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`], +// which enumerates the pricer's offer set against the writer's rule (see +// its doc). The clamp needs a stack that shrinks between search and +// write, which is what a 128x128 superblock's visit order would do -- but +// the pricer never offers an index this tree's `write_drl_idx` cannot +// signal, so no clip can provoke it (lane-av1recipehunt: 153 attempts, 0; +// widening the pricer to `0..5` fires the counter immediately, reverting +// silences it). `drl_clamp_hits` is kept as the tripwire for that fix. diff --git a/crates/ec-av1/src/encoder/tests.rs b/crates/ec-av1/src/encoder/tests.rs index a21cf532..2ee5f15c 100644 --- a/crates/ec-av1/src/encoder/tests.rs +++ b/crates/ec-av1/src/encoder/tests.rs @@ -1,1437 +1,2379 @@ - use super::*; - fn test_card(width: usize, height: usize, shift: usize) -> Picture { - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let sx = (x + shift) % width; - picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; - } - } - for y in 0..height / 2 { - for x in 0..width / 2 { - let i = y * (width / 2) + x; - picture.u[i] = ((100 + shift * 4) % 256) as u16; - picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; - } - } - picture - } +use super::*; - /// Drives a whole stream through the facade the way a caller must since - /// it holds one picture of lookahead: every picture through - /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`]. - fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec { - let mut packets = Vec::with_capacity(pictures.len()); - for (i, picture) in pictures.iter().enumerate() { - packets.extend( - enc.encode_frames(picture) - .unwrap_or_else(|e| panic!("picture {i}: {e}")), - ); +fn test_card(width: usize, height: usize, shift: usize) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let sx = (x + shift) % width; + picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; } - packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}"))); - packets - } - - /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden - /// counts and leaf count match the packets a real run emits, at three - /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends - /// the run's budget exactly (`gop` frame targets, no more and no less). - /// - /// Both halves matter: a shape that misses a level (the old model priced - /// ONE hidden frame per group when the mid level had made it two) splits - /// the budget by weights that do not add up to the run. - #[test] - fn the_rate_loop_prices_the_frames_the_pyramid_codes() { - let _knobs = crate::speed::knob_read(); - let pictures: Vec = (0..48).map(|i| test_card(64, 64, i)).collect(); - let quarters = Pyramid { - quarter_q_offset: Some(-20), - ..Pyramid::default() - }; - let two_level = Pyramid { - mid_q_offset: None, - ..Pyramid::default() - }; - for (gop, pyramid) in [ - (48, Pyramid::default()), - (12, Pyramid::default()), - (48, quarters), - (48, two_level), - ] { - let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let rate = RateTarget::BytesPerFrame(2_000); - let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap(); - let packets = encode_all(&mut enc, &pictures[..gop]); - let coded = |level: Level| packets.iter().filter(|p| p.level == level).count(); - let (hidden, leaves) = gop_shape(pyramid, gop); - let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum(); - assert_eq!( - (hidden_frames, leaves, 1), - (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)), - "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves" - ); - assert_eq!( - hidden_frames + leaves + 1, - gop, - "gop {gop}: every picture is coded exactly once" - ); - // The plan adds up: one leaf's target times the run's whole - // weight is the run's whole budget. - let target_bytes = 2_000.0; - let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); - let planned = loop_.target[0] - + loop_.target[2] - * (leaves as f64 - + hidden - .iter() - .map(|&(o, n)| n as f64 * loop_.weight(o)) - .sum::()); - assert!( - (planned - target_bytes * gop as f64).abs() < 1.0, - "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run", - target_bytes * gop as f64 - ); + } + for y in 0..height / 2 { + for x in 0..width / 2 { + let i = y * (width / 2) + x; + picture.u[i] = ((100 + shift * 4) % 256) as u16; + picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; } } + picture +} - /// A level at its quantizer BOUND hands its unspent bytes to the levels - /// that can still move ([[vorbis-rate-loop-windup]]'s class in the - /// small), and it does so AT ONCE, not once the bound level's frames are - /// all coded: the loop is driven by a synthetic per-level model where the - /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255 - /// clamp) and spends half its plan, and the leaves' target must jump to - /// the run's remainder with EVERY remaining hidden frame priced at that - /// measured rate. The old division -- whole remainder over whole - /// remaining weight -- handed most of the shortfall straight back to the - /// hidden slot (which carries most of the pyramid's weight and cannot - /// spend it), so the leaves only saw the surplus at the end of the run, - /// when there was nothing left to code with it. - #[test] - fn a_bound_level_hands_its_unspent_bytes_to_the_others() { - let pyramid = Pyramid::default(); - let (gop, target_bytes) = (48usize, 2_000.0); +/// Drives a whole stream through the facade the way a caller must since +/// it holds one picture of lookahead: every picture through +/// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`]. +fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec { + let mut packets = Vec::with_capacity(pictures.len()); + for (i, picture) in pictures.iter().enumerate() { + packets.extend( + enc.encode_frames(picture) + .unwrap_or_else(|e| panic!("picture {i}: {e}")), + ); + } + packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}"))); + packets +} + +/// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden +/// counts and leaf count match the packets a real run emits, at three +/// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends +/// the run's budget exactly (`gop` frame targets, no more and no less). +/// +/// Both halves matter: a shape that misses a level (the old model priced +/// ONE hidden frame per group when the mid level had made it two) splits +/// the budget by weights that do not add up to the run. +#[test] +fn the_rate_loop_prices_the_frames_the_pyramid_codes() { + let _knobs = crate::speed::knob_read(); + let pictures: Vec = (0..48).map(|i| test_card(64, 64, i)).collect(); + let quarters = Pyramid { + quarter_q_offset: Some(-20), + ..Pyramid::default() + }; + let two_level = Pyramid { + mid_q_offset: None, + ..Pyramid::default() + }; + for (gop, pyramid) in [ + (48, Pyramid::default()), + (12, Pyramid::default()), + (48, quarters), + (48, two_level), + ] { + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let rate = RateTarget::BytesPerFrame(2_000); + let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap(); + let packets = encode_all(&mut enc, &pictures[..gop]); + let coded = |level: Level| packets.iter().filter(|p| p.level == level).count(); let (hidden, leaves) = gop_shape(pyramid, gop); - let run_bytes = target_bytes * gop as f64; - let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); - let scale0 = rl.target[2]; - let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum(); - // The key codes exactly its plan; the first hidden frame is at the - // floor and spends half of its. - let key_bytes = rl.target[0].round(); - rl.update(Level::Key, 0, 100, key_bytes as usize); - let (offset, n0) = hidden[0]; - let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round(); - rl.update(Level::Arf, offset, 0, arf_bytes as usize); - // Every frame of THAT LEVEL still to come is priced at what the bound - // one measured -- and only that level: its slot-mates (the mid ARF) - // sit at their own offset and are still free to follow the plan. - // Everything else shares the rest. - let want = (run_bytes - key_bytes - arf_bytes * n0 as f64) - / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset)); - assert!( - want < scale0 * RateLoop::REPLAN_CLAMP, - "this arm must not reach the windup bound: {want:.1} vs {:.1}", - scale0 * RateLoop::REPLAN_CLAMP + let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum(); + assert_eq!( + (hidden_frames, leaves, 1), + (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)), + "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves" ); - assert!( - (rl.target[2] - want).abs() < 1e-6, - "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \ - give {:.3})", - rl.target[2], - (run_bytes - key_bytes - arf_bytes) - / (leaves as f64 + hidden_weight - rl.weight(offset)) + assert_eq!( + hidden_frames + leaves + 1, + gop, + "gop {gop}: every picture is coded exactly once" ); - // And the re-plan stays BOUNDED: hidden levels that spend nothing at - // all cannot run the leaves' target away. - let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); - rl.update(Level::Key, 0, 100, key_bytes as usize); - for &(offset, n) in &hidden { - for _ in 0..n { - rl.update(Level::Arf, offset, 0, 1); - } - } + // The plan adds up: one leaf's target times the run's whole + // weight is the run's whole budget. + let target_bytes = 2_000.0; + let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); + let planned = loop_.target[0] + + loop_.target[2] + * (leaves as f64 + + hidden + .iter() + .map(|&(o, n)| n as f64 * loop_.weight(o)) + .sum::()); assert!( - rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9, - "the re-plan is unbounded: leaf target {:.1} past {:.1}", - rl.target[2], - scale0 * RateLoop::REPLAN_CLAMP + (planned - target_bytes * gop as f64).abs() < 1.0, + "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run", + target_bytes * gop as f64 ); - // ... and BOTH ways: a re-plan that reached zero would stop the loop - // dead (`update` returns on a non-positive target). - let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); - rl.update(Level::Key, 0, 100, key_bytes as usize); - for &(offset, n) in &hidden { - for _ in 0..n { - rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize); + } +} + +/// A level at its quantizer BOUND hands its unspent bytes to the levels +/// that can still move ([[vorbis-rate-loop-windup]]'s class in the +/// small), and it does so AT ONCE, not once the bound level's frames are +/// all coded: the loop is driven by a synthetic per-level model where the +/// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255 +/// clamp) and spends half its plan, and the leaves' target must jump to +/// the run's remainder with EVERY remaining hidden frame priced at that +/// measured rate. The old division -- whole remainder over whole +/// remaining weight -- handed most of the shortfall straight back to the +/// hidden slot (which carries most of the pyramid's weight and cannot +/// spend it), so the leaves only saw the surplus at the end of the run, +/// when there was nothing left to code with it. +#[test] +fn a_bound_level_hands_its_unspent_bytes_to_the_others() { + let pyramid = Pyramid::default(); + let (gop, target_bytes) = (48usize, 2_000.0); + let (hidden, leaves) = gop_shape(pyramid, gop); + let run_bytes = target_bytes * gop as f64; + let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); + let scale0 = rl.target[2]; + let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum(); + // The key codes exactly its plan; the first hidden frame is at the + // floor and spends half of its. + let key_bytes = rl.target[0].round(); + rl.update(Level::Key, 0, 100, key_bytes as usize); + let (offset, n0) = hidden[0]; + let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round(); + rl.update(Level::Arf, offset, 0, arf_bytes as usize); + // Every frame of THAT LEVEL still to come is priced at what the bound + // one measured -- and only that level: its slot-mates (the mid ARF) + // sit at their own offset and are still free to follow the plan. + // Everything else shares the rest. + let want = (run_bytes - key_bytes - arf_bytes * n0 as f64) + / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset)); + assert!( + want < scale0 * RateLoop::REPLAN_CLAMP, + "this arm must not reach the windup bound: {want:.1} vs {:.1}", + scale0 * RateLoop::REPLAN_CLAMP + ); + assert!( + (rl.target[2] - want).abs() < 1e-6, + "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \ + give {:.3})", + rl.target[2], + (run_bytes - key_bytes - arf_bytes) / (leaves as f64 + hidden_weight - rl.weight(offset)) + ); + // And the re-plan stays BOUNDED: hidden levels that spend nothing at + // all cannot run the leaves' target away. + let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); + rl.update(Level::Key, 0, 100, key_bytes as usize); + for &(offset, n) in &hidden { + for _ in 0..n { + rl.update(Level::Arf, offset, 0, 1); + } + } + assert!( + rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9, + "the re-plan is unbounded: leaf target {:.1} past {:.1}", + rl.target[2], + scale0 * RateLoop::REPLAN_CLAMP + ); + // ... and BOTH ways: a re-plan that reached zero would stop the loop + // dead (`update` returns on a non-positive target). + let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); + rl.update(Level::Key, 0, 100, key_bytes as usize); + for &(offset, n) in &hidden { + for _ in 0..n { + rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize); + } + } + assert!( + rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9, + "the re-plan froze the loop: leaf target {:.1} under {:.1}", + rl.target[2], + scale0 * RateLoop::REPLAN_FLOOR + ); +} + +/// The mini-GOP layout leaves no short tail group, and leaves the long +/// GOP the fixed rule already coded alone: 47 inter pictures are +/// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical), +/// while a 12-picture GOP stops being 8 + 3 (lane-gopad). +#[test] +fn the_mini_gop_layout_leaves_no_short_tail() { + let groups = |remaining: usize, mini_gop: usize, absorb: bool| { + let (mut left, mut out) = (remaining, Vec::new()); + while left > 0 { + let g = group_target(left, mini_gop, absorb).min(left); + assert!(g > 0); + out.push(g); + left -= g; + } + out + }; + // gop 48: what mini_gop 8 already coded, under either rule. + assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]); + assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]); + // gop 12: 8 + 3 becomes one group of 11. + assert_eq!(groups(11, 8, false), vec![8, 3]); + assert_eq!(groups(11, 8, true), vec![11]); + // A run shorter than a group is one group, as before (the 4-picture + // pin clip). + assert_eq!(groups(3, 8, true), vec![3]); + // No group is ever below half the shape, and none is over 1.5x it. + for mini_gop in 2..=16 { + for remaining in 1..=64 { + for g in groups(remaining, mini_gop, true) { + assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}"); + assert!( + g * 2 >= mini_gop || remaining < mini_gop, + "{remaining}/{mini_gop}: short tail {g}" + ); } } - assert!( - rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9, - "the re-plan froze the loop: leaf target {:.1} under {:.1}", - rl.target[2], - scale0 * RateLoop::REPLAN_FLOOR - ); } - - /// The mini-GOP layout leaves no short tail group, and leaves the long - /// GOP the fixed rule already coded alone: 47 inter pictures are - /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical), - /// while a 12-picture GOP stops being 8 + 3 (lane-gopad). - #[test] - fn the_mini_gop_layout_leaves_no_short_tail() { - let groups = |remaining: usize, mini_gop: usize, absorb: bool| { - let (mut left, mut out) = (remaining, Vec::new()); - while left > 0 { - let g = group_target(left, mini_gop, absorb).min(left); - assert!(g > 0); - out.push(g); - left -= g; +} + +/// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated +/// in order. +fn concat(packets: &[Packet]) -> Vec { + packets.iter().flat_map(|p| p.data.clone()).collect() +} + +/// The facade's latency contract (lane-av1facade, deepened on +/// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold +/// their picture back and return an empty packet, every later call +/// returns the packet of the picture that many frames earlier, and +/// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets +/// exactly one non-empty packet per picture, `depth - 1` calls later. +#[test] +fn one_in_one_out_delayed_by_the_lookahead_depth() { + let _knobs = crate::speed::knob_read(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 2, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let delay = crate::encode::tpl_depth() as u64 - 1; + let pictures = delay + 5; + let mut enc = Av1Encoder::new(config).unwrap(); + for t in 0..pictures { + let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); + if t < delay { + assert!(packet.data.is_empty(), "call {t} holds its picture back"); + continue; + } + assert!(!packet.data.is_empty(), "picture {t}: empty packet"); + assert_eq!(packet.order, t - delay, "picture {t}: order"); + } + let tail = enc.flush().unwrap(); + assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); + for (i, p) in tail.iter().enumerate() { + assert_eq!( + p.order, + pictures - delay + i as u64, + "flushed packet {i}: order" + ); + assert!(!p.data.is_empty(), "flushed packet {i}: empty"); + } + assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); +} + +/// A screen-like card: hard-edged 4-pixel bands of two flat luma values +/// with a moving block over the lower half — few colours per 16x16 block +/// at high variance, which is exactly what +/// [`crate::encode::picture_is_screen`] separates. Used unforced, so the +/// gate below runs the real detector rather than an override. +fn screen_card(width: usize, height: usize, shift: usize) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; + let over = y >= height / 2 && (x + shift) % width < width / 3; + picture.y[y * width + x] = if over { 128 } else { band }; + } + } + picture +} + +/// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on +/// lane-av1pyrdef): the streaming facade — what the editor's export +/// drives — codes byte for byte what [`crate::encode::encode_sequence`] +/// codes, which is the path the BD gate measures. Both now drive ONE +/// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the +/// identity is by construction; this pins it anyway, over both content +/// classes the content gate splits: +/// +/// * film-like (the gate's own clip when the fixture is there, a +/// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the +/// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two +/// paths' whole streams are identical; +/// * screen-like: the content gate drops BOTH paths back to flat, one +/// packet per picture, identical frame by frame as well as whole. +/// +/// Never skipped, since a skipped identity gate is the defect it is meant +/// to catch. +#[test] +fn the_facade_codes_the_same_bytes_as_encode_sequence() { + let _knobs = crate::speed::knob_read(); + let frames = 12usize; + let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { + // The probe inside already printed the ONE line naming the + // resolved path and the escape hatch, so this is a note about + // what runs instead — not a second SKIP. + eprintln!(" ...so the film arm runs on a synthetic card, not real film"); + (0..frames).map(|t| test_card(64, 64, t)).collect() + }); + let screen: Vec = (0..frames).map(|t| screen_card(64, 64, t)).collect(); + let pyramid = Pyramid::from_env().expect("the pyramid is this build's default"); + for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] { + let (width, height) = (pictures[0].width, pictures[0].height); + for q in [150u8, 60] { + let config = EncoderConfig { + width, + height, + base_q_idx: q, + // One key frame then all inter, which is + // `encode_sequence`'s only shape, and the gate's recipe. + gop: frames, + // `encode_sequence` writes an unspecified colour config. + colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let mut packets = Vec::new(); + for picture in pictures { + packets.extend(enc.encode_frames(picture).unwrap()); } - out - }; - // gop 48: what mini_gop 8 already coded, under either rule. - assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]); - assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]); - // gop 12: 8 + 3 becomes one group of 11. - assert_eq!(groups(11, 8, false), vec![8, 3]); - assert_eq!(groups(11, 8, true), vec![11]); - // A run shorter than a group is one group, as before (the 4-picture - // pin clip). - assert_eq!(groups(3, 8, true), vec![3]); - // No group is ever below half the shape, and none is over 1.5x it. - for mini_gop in 2..=16 { - for remaining in 1..=64 { - for g in groups(remaining, mini_gop, true) { - assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}"); - assert!( - g * 2 >= mini_gop || remaining < mini_gop, - "{remaining}/{mini_gop}: short tail {g}" + packets.extend(enc.flush().unwrap()); + assert_eq!( + enc.pyramid().is_none(), + is_screen, + "{content} q={q}: the content gate read this clip the other way round" + ); + let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); + assert_eq!( + ( + packets.iter().map(|p| p.data.len()).sum::(), + concat(&packets) + ), + (sequence.stream.len(), sequence.stream.clone()), + "{content} q={q}: the facade's stream is not the sequence path's" + ); + assert_eq!( + sequence.frames.len(), + frames, + "{content} q={q}: one entry per picture, in display order" + ); + if is_screen { + assert_eq!( + packets.len(), + frames, + "{content} q={q}: one packet per picture" + ); + for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { + let cropped = crate::encode::crop_encoded(coded, width, height); + assert_eq!( + (packet.data.len(), packet.data.clone()), + (cropped.stream.len(), cropped.stream.clone()), + "{content} q={q} frame {i}: the facade's bytes are not the \ + sequence path's" ); } + } else { + assert!( + packets.iter().any(|p| p.level == Level::Arf), + "{content} q={q}: a non-screen stream coded no hidden frame" + ); } } } - - /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated - /// in order. - fn concat(packets: &[Packet]) -> Vec { - packets.iter().flat_map(|p| p.data.clone()).collect() +} + +/// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by +/// the caller but applied only to camera material. Over screen content +/// the encoder must drop back to the flat path and code byte for byte +/// what a flat encoder codes — that is what keeps the BD gate's screen +/// row identical to the flat baseline — and over non-screen content the +/// same request must still reorder (class `gate-blind-to-feature`: a gate +/// that only checked the screen half would pass with the pyramid deleted). +#[test] +fn the_content_gate_keeps_screen_streams_flat() { + let _knobs = crate::speed::knob_read(); + let frames = 8usize; + let pictures: Vec = (0..frames).map(|t| test_card(64, 64, t)).collect(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 120, + gop: frames, + colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + crate::encode::force_screen(Some(true)); + let mut flat = Av1Encoder::new(config).unwrap(); + let flat_packets = encode_all(&mut flat, &pictures); + let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + let gated_packets = encode_all(&mut gated, &pictures); + assert_eq!( + gated.pyramid(), + None, + "the gate left a screen stream on the pyramid" + ); + assert_eq!( + concat(&gated_packets), + concat(&flat_packets), + "a screen stream's bytes are not the flat path's" + ); + crate::encode::force_screen(Some(false)); + let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + let kept_packets = encode_all(&mut kept, &pictures); + assert_eq!( + kept.pyramid(), + Some(Pyramid::default()), + "the gate ate a film stream" + ); + assert!( + kept_packets.iter().any(|p| p.level == Level::Arf), + "a non-screen stream coded no hidden frame" + ); + crate::encode::force_screen(None); +} + +/// A key frame every `gop` pictures, inter otherwise — checked against +/// what the facade itself reports, and (below) against what `ffprobe` +/// reads back out of the coded bytes. +#[test] +fn gop_cadence_is_honored() { + let _knobs = crate::speed::knob_read(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 3, + colour: Colour::Unspecified, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let pictures: Vec = (0..7).map(|t| test_card(64, 64, t)).collect(); + let keys: Vec = encode_all(&mut enc, &pictures) + .iter() + .map(|p| p.key) + .collect(); + assert_eq!(keys, vec![true, false, false, true, false, false, true]); +} + +fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { + let path = std::env::temp_dir().join(format!( + "ec-av1-facade-probe-{}-{}.obu", + std::process::id(), + std::ptr::addr_of!(stream) as usize + )); + std::fs::write(&path, stream).expect("writing the probe stream"); + let out = ec_testkit::ffprobe() + .args([ + "-v", + "error", + "-f", + "obu", + "-select_streams", + "v:0", + "-show_entries", + "frame=key_frame,width,height", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "ffprobe refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|line| { + let mut f = line.trim().split(','); + let key: u32 = f.next().unwrap().parse().unwrap(); + let width: u32 = f.next().unwrap().parse().unwrap(); + let height: u32 = f.next().unwrap().parse().unwrap(); + (key == 1, width, height) + }) + .collect() +} + +fn ffprobe_colour(stream: &[u8]) -> String { + let path = std::env::temp_dir().join(format!( + "ec-av1-facade-colour-probe-{}-{}.obu", + std::process::id(), + std::ptr::addr_of!(stream) as usize + )); + std::fs::write(&path, stream).expect("writing the probe stream"); + let out = ec_testkit::ffprobe() + .args([ + "-v", + "error", + "-f", + "obu", + "-select_streams", + "v:0", + "-show_entries", + "stream=color_primaries,color_transfer,color_space,color_range", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "ffprobe refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +/// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15) +/// and 28 inter ones, at an odd-ish (not superblock-multiple) size that +/// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and +/// coded size confirm what the facade already reported. +#[test] +fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { + let _knobs = crate::speed::knob_read(); + let (width, height) = (96usize, 96usize); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 15, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + assert_eq!(enc.display_size(), (width, height)); + let (coded_w, coded_h) = enc.coded_size(); + assert_eq!( + (coded_w, coded_h), + ( + width.next_multiple_of(SUPERBLOCK), + height.next_multiple_of(SUPERBLOCK) + ) + ); + + let pictures: Vec = (0..30).map(|t| test_card(width, height, t)).collect(); + let packets: Vec = encode_all(&mut enc, &pictures); + let expect_key: Vec = (0..30).map(|t| t % 15 == 0).collect(); + assert_eq!( + packets.iter().map(|p| p.key).collect::>(), + expect_key, + "facade's own key/inter flags" + ); + + let stream = concat(&packets); + let frames = ffprobe_frames(&stream); + assert_eq!(frames.len(), 30, "ffprobe frame count"); + for (t, (key, w, h)) in frames.iter().enumerate() { + assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); + assert_eq!( + (*w, *h), + (width as u32, height as u32), + "picture {t}: ffprobe reports the true (display) size, not the padded coded one" + ); } - - /// The facade's latency contract (lane-av1facade, deepened on - /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold - /// their picture back and return an empty packet, every later call - /// returns the packet of the picture that many frames earlier, and - /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets - /// exactly one non-empty packet per picture, `depth - 1` calls later. - #[test] - fn one_in_one_out_delayed_by_the_lookahead_depth() { - let _knobs = crate::speed::knob_read(); +} + +/// The configured colour properties are what `ffprobe` reports back, +/// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it +/// is the default a player assumes and the one this test would silently +/// pass without wiring for (`ffprobe` reports "unknown" for the +/// hardcoded "unspecified" this crate wrote before the facade existed, +/// which is a visibly different string). +#[test] +fn bt709_limited_colour_is_reported_by_ffprobe() { + let _knobs = crate::speed::knob_read(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); + let colour = ffprobe_colour(&packets[0].data); + assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); +} + +/// The same, for BT.601: a different set of CICP integers must produce a +/// different string, or the wiring could be a no-op that happens to read +/// as BT.709 for every input. +#[test] +fn bt601_limited_colour_is_reported_by_ffprobe() { + let _knobs = crate::speed::knob_read(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 4, + colour: Colour::Bt601Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); + let colour = ffprobe_colour(&packets[0].data); + assert_eq!( + colour, "tv,smpte170m,smpte170m,smpte170m", + "ffprobe colour fields" + ); +} + +/// A frame whose size does not match the encoder's configured geometry +/// is refused by name. +#[test] +fn geometry_mismatch_is_refused() { + let _knobs = crate::speed::knob_read(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); + assert!(err.to_string().contains("64x64"), "{err}"); +} + +/// `gop == 0` is refused at construction, not the first `encode()` call. +#[test] +fn zero_gop_is_refused() { + let _knobs = crate::speed::knob_read(); + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 0, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let err = Av1Encoder::new(config).unwrap_err(); + assert!(err.to_string().contains("gop"), "{err}"); +} + +/// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget` +/// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down +/// to this facade's own input size, and re-coded through the facade so the +/// rate-target surface is exercised at the entry point a caller actually +/// drives. +fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option> { + h264_clip_frames_at(20, width, height, frames) +} + +fn h264_clip_frames_at( + start: u32, + width: usize, + height: usize, + frames: usize, +) -> Option> { + // lane-av1speed3: the wall tables below are read on REAL film as + // well as on the colour-bar fixture (`bars` vs `film` in the BD + // gate's own vocabulary), and the film crop lives outside the repo -- + // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other + // caller still gets the fixture. + // + // lane-av1clipprobe: the default path resolves through `EC_FIXTURES` + // first, which is the root `scripts/verify-fixture-library.sh` + // validates -- so the preflight's verdict and these bytes are the same + // tree, and GREEN-with-an-absent-root is no longer reachable by + // pointing EC_FIXTURES somewhere the gates do not read. + let clip = match std::env::var("EC_AV1_WALL_CLIP") { + Ok(p) => std::path::PathBuf::from(p), + Err(_) => ec_testkit::fixture("open/sintel_trailer-1080p.mp4"), + }; + // `what` is the CALLING GATE's name, carried in so that both exits from + // this function print exactly one line naming it: the ffmpeg line + // above, and the probe's line naming the resolved path. Callers + // therefore `return` on `None` WITHOUT printing a second one -- the + // second "no fixture" line per gate was the noise that hid this defect. + let out = ec_testkit::ffmpeg() + .args([ + "-v", + "error", + "-ss", + &start.to_string(), + "-i", + clip.to_str().unwrap(), + ]) + .args(["-frames:v", &frames.to_string()]) + .args(["-vf", &format!("scale={width}:{height}")]) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg failed to run"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + let frame_len = luma + 2 * chroma; + assert_eq!( + out.stdout.len(), + frame_len * frames, + "expected {frames} 4:2:0 frames" + ); + Some( + (0..frames) + .map(|i| { + let bytes = &out.stdout[i * frame_len..][..frame_len]; + Picture { + width, + height, + y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), + u: bytes[luma..luma + chroma] + .iter() + .map(|&v| u16::from(v)) + .collect(), + v: bytes[luma + chroma..] + .iter() + .map(|&v| u16::from(v)) + .collect(), + } + }) + .collect(), + ) +} + +/// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total +/// coded size within ±20% of `frames * target` once the first few +/// frames' settling has been discarded (the key frame's own reference +/// state and the controller's first couple of steps). +#[test] +fn bytes_per_frame_target_settles_within_20_percent() { + let _knobs = crate::speed::knob_read(); + let Some(pictures) = h264_clip_frames(640, 384, 24) else { + return; + }; + let target_bytes = 4_000u32; + let config = EncoderConfig { + width: 640, + height: 384, + base_q_idx: 100, + gop: 24, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = + Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); + let sizes: Vec = encode_all(&mut enc, &pictures) + .iter() + .map(|p| p.data.len()) + .collect(); + // Discard the key frame (always far larger than an inter target) and + // the next 4 inter frames the loop needs to step toward it. + let settled = &sizes[5..]; + let mean = settled.iter().sum::() as f64 / settled.len() as f64; + let low = f64::from(target_bytes) * 0.8; + let high = f64::from(target_bytes) * 1.2; + assert!( + mean >= low && mean <= high, + "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" + ); +} + +/// One (bitrate, pyramid) arm's tally, built on the worker thread and +/// handed back through the progress channel +/// (`bitrate_target_lands_within_5_percent_over_48_frames`). Per LEVEL, +/// so a miss reads as WHICH level's model is off rather than as one +/// aggregate percentage. +struct ArmResult { + /// [`RateLoop::target`] as the arm's own encoder computed it. + targets: [f64; 3], + coded: usize, + bytes: [usize; 4], + count: [usize; 4], +} + +impl ArmResult { + fn take(&mut self, packets: Vec) { + for packet in packets { + self.coded += packet.data.len(); + let i = match packet.level { + Level::Key => 0, + Level::Arf => 1, + Level::Leaf => 2, + Level::ShowExisting => 3, + }; + self.bytes[i] += packet.data.len(); + self.count[i] += 1; + } + } +} + +/// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the +/// target over 48 frames of a real clip, flat and under a pyramid alike, +/// across a 5x span of bitrates. This is the accuracy claim of the +/// target-bitrate mode: no two-pass, no lookahead, just each frame's size +/// predicted from the previous frame of its own level, one clamped +/// proportional step, and the level model +/// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits. +/// +/// The tolerance was ±10% and every arm was inside ±3.0% when it was cut +/// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the +/// ENCODER'S OWN CEILING showing through, not the loop's aim: at that +/// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a +/// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12 +/// `leaf_q_offset`, so this clip cannot be made to spend much past +/// 2.4 Mbit/s under the default pyramid however the budget is split. +/// +/// # Bounded +/// +/// Each arm's encode runs on a worker thread under a per-CALL +/// wall-clock ceiling, so this gate FAILS rather than hanging when an +/// encode stops terminating (lane-av1enchang: a 3h20m wedge on one host +/// and 30min on another, both here, both with the test thread spinning +/// and no child process for the crate's child timeout to reap). The cost +/// is real and is why the budget is not tight: the two high bitrate arms +/// walk `q_idx` from the seed 100 down into the 20s to spend an +/// 8000-byte budget on a 640x384 clip, and a frame at `q_idx` 25 costs +/// ~15s in a debug build (~1s optimized) against ~0.5s at `q_idx` 100. +/// lane-av1enchang: the PYRAMID CONSTRUCTORS fit on a tight stack. +/// +/// `Av1Encoder` used to be 139960 bytes BY VALUE, because each of the +/// eight `DpbSlot`s held a 15 KB `CdfSnapshot` inline. The pyramid +/// constructors nest three deep -- `with_pyramid_and_rate_target` -> +/// `with_pyramid` -> `new` -- and each level materialises the struct in +/// an unoptimized build, so ~840 KB of stack was live at the innermost +/// `Ok(Self { .. })`. On libtest's default 2 MiB test thread that aborts: +/// `fatal runtime error: stack overflow, aborting`, reproduced on the +/// pre-fix binary at `crates/ec-av1/src/encoder.rs:1519` via +/// `coredumpctl debug`. +/// +/// Boxing the snapshot brought the struct to 18168 bytes. This gate pins +/// that: it builds BOTH constructors on a thread with a deliberately +/// tight stack, so the old layout ABORTS THE PROCESS and the new one +/// returns. It runs in milliseconds, where proving the same thing through +/// the 48-frame gate takes 6m35s. +/// +/// Both thresholds were swept, in an unoptimized build: +/// +/// | stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) | +/// |---|---|---| +/// | 256 KiB | overflow | overflow | +/// | 384 KiB | overflow | ok | +/// | 512 KiB | overflow | ok | +/// | 1 MiB | **overflow** | **ok** | +/// | 2 MiB | **overflow** (libtest's default) | ok | +/// | 3 MiB | ok | ok | +/// +/// 1 MiB is the gate: 2.7x what the boxed layout needs and 2x below what +/// the old one did, so it is nowhere near either threshold and cannot +/// flake. The pre-fix row at 1 MiB is the red -- which is also why +/// `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, a +/// workspace-local band-aid this gate makes unnecessary for this struct. +/// +/// `EC_AV1_TIGHT_STACK_BYTES` overrides the size, which is how the sweep +/// above is reproduced. +#[test] +fn the_pyramid_constructors_fit_on_a_tight_stack() { + // 1 MiB: see the threshold table on this test. Red before the Box, + // green after, with 2.7x margin either way. + const STACK: usize = 1024 * 1024; + let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(STACK); + let config = EncoderConfig { + width: 640, + height: 384, + base_q_idx: 100, + gop: 48, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let rate = RateTarget::Bitrate { + bits_per_second: 1_536_000, + frames_per_second: 24.0, + }; + let handle = std::thread::Builder::new() + .stack_size(stack) + .spawn(move || { + let flat = Av1Encoder::with_rate_target(config, rate) + .expect("with_rate_target") + .rate_loop + .is_some(); + let pyr = Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate) + .expect("with_pyramid_and_rate_target") + .pyramid + .is_some(); + (flat, pyr) + }) + .expect("spawn tight-stack thread"); + let (flat, pyr) = handle + .join() + .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack")); + assert!(flat, "with_rate_target lost its rate loop"); + assert!(pyr, "with_pyramid_and_rate_target lost its pyramid"); + eprintln!( + "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned", + std::mem::size_of::() + ); +} + +const CLEAN_START: u32 = 23; + +#[test] +fn bitrate_target_lands_within_5_percent_over_48_frames() { + let _knobs = crate::speed::knob_read(); + let (width, height, frames) = (640usize, 384usize, 48usize); + let Some(pictures) = h264_clip_frames_at(CLEAN_START, width, height, frames) else { + return; + }; + let fps = 24.0; + let pictures = std::sync::Arc::new(pictures); + for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { let config = EncoderConfig { - width: 64, - height: 64, + width, + height, base_q_idx: 100, - gop: 2, + gop: frames, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - let delay = crate::encode::tpl_depth() as u64 - 1; - let pictures = delay + 5; - let mut enc = Av1Encoder::new(config).unwrap(); - for t in 0..pictures { - let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); - if t < delay { - assert!(packet.data.is_empty(), "call {t} holds its picture back"); - continue; - } - assert!(!packet.data.is_empty(), "picture {t}: empty packet"); - assert_eq!(packet.order, t - delay, "picture {t}: order"); - } - let tail = enc.flush().unwrap(); - assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); - for (i, p) in tail.iter().enumerate() { - assert_eq!( - p.order, - pictures - delay + i as u64, - "flushed packet {i}: order" + let rate = RateTarget::Bitrate { + bits_per_second, + frames_per_second: fps, + }; + for pyramid in [None, Some(Pyramid::default())] { + let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some()); + // Shared, not cloned: the 48 decoded frames are ~35 MB of + // `u16` luma+chroma, and all eight arms want the same ones. + let pictures = std::sync::Arc::clone(&pictures); + // `None` is a progress ticket: THIS call returned. `Some` is + // the arm's result, sent after `flush` -- which is itself a + // call that can spin, so it needs a ticket too, not a bare + // `join` that would block forever. + let (tx, rx) = std::sync::mpsc::channel::>(); + let worker = std::thread::spawn(move || { + let mut enc = match pyramid { + None => Av1Encoder::with_rate_target(config, rate).unwrap(), + Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), + }; + let targets = enc.rate_loop.as_ref().unwrap().target; + let mut out = ArmResult { + targets, + coded: 0, + bytes: [0; 4], + count: [0; 4], + }; + for picture in pictures.iter() { + out.take(enc.encode_frames(picture).unwrap()); + if tx.send(None).is_err() { + return; + } + } + out.take(enc.flush().unwrap()); + let _ = tx.send(Some(out)); + }); + let out = loop { + match rx.recv() { + Ok(Some(out)) => break out, + Ok(None) => {} + Err(_) => { + worker.join().expect("encode worker panicked"); + panic!("AV1 encode worker for {arm} died without a result"); + } + } + }; + let ArmResult { + targets, + coded, + bytes, + count, + } = out; + let seconds = frames as f64 / fps; + let achieved = coded as f64 * 8.0 / seconds; + let error = achieved / f64::from(bits_per_second) - 1.0; + let per = |i: usize| match count[i] { + 0 => "-".to_string(), + n => format!("{n}x{}", bytes[i] / n), + }; + eprintln!( + "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ + = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \ + coded key {} arf {} leaf {}", + pyramid.is_some(), + 100.0 * error, + targets[0], + targets[1], + targets[2], + per(0), + per(1), + per(2), + ); + assert!( + error.abs() <= 0.05, + "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ + (pyramid {})", + 100.0 * error, + pyramid.is_some(), ); - assert!(!p.data.is_empty(), "flushed packet {i}: empty"); } - assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); } - - /// A screen-like card: hard-edged 4-pixel bands of two flat luma values - /// with a moving block over the lower half — few colours per 16x16 block - /// at high variance, which is exactly what - /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the - /// gate below runs the real detector rather than an override. - fn screen_card(width: usize, height: usize, shift: usize) -> Picture { +} +/// The `BytesPerFrame` controller's own windup bound: no frame's coded +/// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real +/// clip's full range of content (so a scene cut can't be the one frame +/// that breaks the bound). +/// +/// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot +/// that has coded nothing yet is still sitting on the caller's +/// `base_q_idx` guess, and its first step is the acquisition jump, not +/// windup. Exactly one frame is exempt -- the loop below asserts the +/// bound on every frame after it, which is where a scene cut would +/// break it. +#[test] +fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { + let _knobs = crate::speed::knob_read(); + let Some(pictures) = h264_clip_frames(640, 384, 24) else { + return; + }; + let config = EncoderConfig { + width: 640, + height: 384, + base_q_idx: 100, + gop: 24, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); + let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); + // The first frame this encoder EMITS is several `encode_frames` calls + // in (the lookahead queue holds the earlier ones), so the seeding + // step is not frame zero -- it is the first frame `q` moves at all. + let mut seeded = false; + let mut seed_frame = None; + for (frame, picture) in pictures.iter().enumerate() { + enc.encode_frames(picture).unwrap(); + let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); + let step = (i32::from(q) - i32::from(prev_q)).abs(); + if step > 0 && !seeded { + seeded = true; + seed_frame = Some(frame); + } else { + assert!( + f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding + "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp", + RateLoop::STEP_CLAMP + ); + } + prev_q = q; + } + assert!( + seed_frame.is_some(), + "the controller never steered at all -- the bound below is vacuous" + ); +} + +fn psnr(a: &[u16], b: &[u16]) -> f64 { + let squared: f64 = a + .iter() + .zip(b) + .map(|(&x, &y)| { + let d = f64::from(x) - f64::from(y); + d * d + }) + .sum(); + if squared == 0.0 { + return f64::INFINITY; + } + 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() +} + +/// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one +/// entry per coded frame, in order — this facade's own equivalent of +/// `encode::tests::ffmpeg_decode_sequence`, needed here too since a +/// PSNR check needs the decoded pixels, not just the coded byte count. +fn ffmpeg_decode_planes( + stream: &[u8], + width: usize, + height: usize, +) -> Vec<(Vec, Vec, Vec)> { + let path = std::env::temp_dir().join(format!( + "ec-av1-facade-rate-decode-{}-{}.obu", + std::process::id(), + std::ptr::addr_of!(stream) as usize + )); + std::fs::write(&path, stream).expect("writing the decode probe stream"); + let out = ec_testkit::ffmpeg() + .args(["-v", "error", "-f", "obu", "-i"]) + .arg(&path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let (luma, chroma) = (width * height, width * height / 4); + let frame_len = luma + 2 * chroma; + out.stdout + .chunks_exact(frame_len) + .map(|f| { + ( + f[..luma].to_vec(), + f[luma..luma + chroma].to_vec(), + f[luma + chroma..].to_vec(), + ) + }) + .collect() +} + +/// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare. +fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec> { + ffmpeg_decode_planes(stream, width, height) + .into_iter() + .map(|(y, _, _)| y) + .collect() +} + +/// lane-palw: OUR encoder's own witness for the writer half of the +/// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall, +/// so the bottom superblock row's palette blocks hang 8 luma rows off the +/// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN +/// corner only and replicates it outward, and the writer used to code the +/// full block grid -- symbols a conformant decoder never reads, so +/// ffmpeg/dav1d desynced the rest of the tile while our own trial decode +/// (unclamped on both sides) agreed with itself. Class +/// `writer-phantom-units-past-edge`. +/// +/// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's +/// export calls), and compared on EVERY plane -- a chroma palette map is +/// cut by the same edge. `palette_cut_maps_written` is asserted non-zero +/// so the row cannot pass on a stream that cuts no palette map (class +/// gate-blind-to-feature). +#[test] +fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() { + const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg"; + let _knobs = crate::speed::knob_read(); + let (width, height) = (384usize, 152usize); + // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at + // most two luma values, so the palette arm wins across the WHOLE + // frame -- including the bottom superblock row, whose 16x16 blocks at + // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid. + // `screen_card`'s 4-px bands fire only 9 palettes here and none of + // them at the cut edge (class gate-blind-to-feature). + let card = |shift: usize| -> Picture { let mut picture = Picture::grey(width, height); for y in 0..height { for x in 0..width { - let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; - let over = y >= height / 2 && (x + shift) % width < width / 3; - picture.y[y * width + x] = if over { 128 } else { band }; + let cell = ((x + shift) / 8 + y / 8) % 2; + picture.y[y * width + x] = if cell == 0 { 40 } else { 200 }; } } picture - } - - /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on - /// lane-av1pyrdef): the streaming facade — what the editor's export - /// drives — codes byte for byte what [`crate::encode::encode_sequence`] - /// codes, which is the path the BD gate measures. Both now drive ONE - /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the - /// identity is by construction; this pins it anyway, over both content - /// classes the content gate splits: - /// - /// * film-like (the gate's own clip when the fixture is there, a - /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the - /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two - /// paths' whole streams are identical; - /// * screen-like: the content gate drops BOTH paths back to flat, one - /// packet per picture, identical frame by frame as well as whole. - /// - /// Never skipped, since a skipped identity gate is the defect it is meant - /// to catch. - #[test] - fn the_facade_codes_the_same_bytes_as_encode_sequence() { - let _knobs = crate::speed::knob_read(); - let frames = 12usize; - let film = h264_clip_frames(640, 384, frames) - .unwrap_or_else(|| { - // The probe inside already printed the ONE line naming the - // resolved path and the escape hatch, so this is a note about - // what runs instead — not a second SKIP. - eprintln!(" ...so the film arm runs on a synthetic card, not real film"); - (0..frames).map(|t| test_card(64, 64, t)).collect() - }); - let screen: Vec = (0..frames).map(|t| screen_card(64, 64, t)).collect(); - let pyramid = Pyramid::from_env().expect("the pyramid is this build's default"); - for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] { - let (width, height) = (pictures[0].width, pictures[0].height); - for q in [150u8, 60] { - let config = EncoderConfig { - width, - height, - base_q_idx: q, - // One key frame then all inter, which is - // `encode_sequence`'s only shape, and the gate's recipe. - gop: frames, - // `encode_sequence` writes an unspecified colour config. - colour: Colour::Unspecified, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); - let mut packets = Vec::new(); - for picture in pictures { - packets.extend(enc.encode_frames(picture).unwrap()); - } - packets.extend(enc.flush().unwrap()); - assert_eq!( - enc.pyramid().is_none(), - is_screen, - "{content} q={q}: the content gate read this clip the other way round" - ); - let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); - assert_eq!( - ( - packets.iter().map(|p| p.data.len()).sum::(), - concat(&packets) - ), - (sequence.stream.len(), sequence.stream.clone()), - "{content} q={q}: the facade's stream is not the sequence path's" - ); - assert_eq!( - sequence.frames.len(), - frames, - "{content} q={q}: one entry per picture, in display order" + }; + let sources: Vec = (0..2).map(|t| card(t * 16)).collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 60, + gop: 2, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + crate::tile::reset_palette_cut_maps_written(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + eprintln!( + "{NAME}: {} cut colour-index maps written", + crate::tile::palette_cut_maps_written() + ); + assert!( + crate::tile::palette_cut_maps_written() > 0, + "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind" + ); + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames"); + let theirs = ffmpeg_decode_planes(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] { + let got: Vec = got.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) { + let w = if plane == "luma" { width } else { width / 2 }; + panic!( + "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}", + at % w, + at / w, + got[at], + want[at], ); - if is_screen { - assert_eq!( - packets.len(), - frames, - "{content} q={q}: one packet per picture" - ); - for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { - let cropped = crate::encode::crop_encoded(coded, width, height); - assert_eq!( - (packet.data.len(), packet.data.clone()), - (cropped.stream.len(), cropped.stream.clone()), - "{content} q={q} frame {i}: the facade's bytes are not the \ - sequence path's" - ); - } - } else { - assert!( - packets.iter().any(|p| p.level == Level::Arf), - "{content} q={q}: a non-screen stream coded no hidden frame" - ); - } } + assert_eq!( + got.len(), + want.len(), + "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}", + got.len(), + want.len() + ); } } - - /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by - /// the caller but applied only to camera material. Over screen content - /// the encoder must drop back to the flat path and code byte for byte - /// what a flat encoder codes — that is what keeps the BD gate's screen - /// row identical to the flat baseline — and over non-screen content the - /// same request must still reorder (class `gate-blind-to-feature`: a gate - /// that only checked the screen half would pass with the pyramid deleted). - #[test] - fn the_content_gate_keeps_screen_streams_flat() { - let _knobs = crate::speed::knob_read(); - let frames = 8usize; - let pictures: Vec = (0..frames).map(|t| test_card(64, 64, t)).collect(); +} + +/// A pyramid stream reorders pictures: the hidden `ALTREF` of each +/// mini-GOP is coded before the leaves that precede it in display order, +/// and a `show_existing_frame` header puts it back. This pins the shape +/// (one packet per source picture plus one `show_existing_frame` per +/// group, `dts` monotone, `order` NOT monotone) and then decodes the +/// whole stream through OUR decoder and through ffmpeg/dav1d and requires +/// the two display-order outputs to agree sample for sample — the +/// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never +/// output, or output twice, or output in the wrong position, changes the +/// display-order list and fails here. +#[test] +fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { + // `take_ref_frame_hits` is a process-global counter: a reader-locked + // sibling encoding at the same time zeroes it between our encode and + // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the + // exclusive lock. + let _knobs = crate::speed::knob_write(); + pyramid_round_trip( + Pyramid { + mini_gop: 4, + mid_q_offset: None, + ..Pyramid::default() + }, + 2, + ); +} + +/// The same round trip over a THREE-level group (`mid_q_offset`): each +/// mini-GOP now codes two hidden frames -- the top ARF at the group's +/// last picture and the mid ARF at the middle of the leaf run -- and +/// re-outputs both with `show_existing_frame`, so a mid frame emitted in +/// the wrong display position, or twice, fails the display-order compare +/// against ffmpeg exactly as a top ARF does. +#[test] +fn a_three_level_pyramid_stream_decodes_in_display_order() { + let _knobs = crate::speed::knob_write(); + pyramid_round_trip( + Pyramid { + mini_gop: 8, + mid_q_offset: Some(-8), + ..Pyramid::default() + }, + 2, + ); +} + +/// The same round trip over a FOUR-level group +/// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four +/// hidden frames -- the top ARF at picture 8, the mid at 4 and the two +/// quarters at 2 and 6 -- each re-output by its own +/// `show_existing_frame`. Every leaf reads a different pair of DPB slots +/// than it did at three levels, so a slot map that lets one level +/// overwrite a picture another is still reading shows up here as a +/// display-order mismatch against ffmpeg. +#[test] +fn a_four_level_pyramid_stream_decodes_in_display_order() { + let _knobs = crate::speed::knob_write(); + pyramid_round_trip( + Pyramid { + mini_gop: 8, + mid_q_offset: Some(-8), + quarter_q_offset: Some(4), + ..Pyramid::default() + }, + 4, + ); +} + +/// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads +/// the key, so an offset that never arrived would be invisible in the BD +/// table except as "no change" (class symbol-consumption-gap). A finer +/// key must cost strictly more bytes than the same picture at base q. +#[test] +fn the_key_q_offset_reaches_the_key_frame() { + let _knobs = crate::speed::knob_read(); + crate::encode::force_screen(Some(false)); + let key_bytes = |offset: i16| { let config = EncoderConfig { - width: 64, - height: 64, + width: 128, + height: 128, base_q_idx: 120, - gop: frames, - colour: Colour::Unspecified, + gop: 32, + colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - crate::encode::force_screen(Some(true)); - let mut flat = Av1Encoder::new(config).unwrap(); - let flat_packets = encode_all(&mut flat, &pictures); - let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); - let gated_packets = encode_all(&mut gated, &pictures); - assert_eq!( - gated.pyramid(), - None, - "the gate left a screen stream on the pyramid" - ); - assert_eq!( - concat(&gated_packets), - concat(&flat_packets), - "a screen stream's bytes are not the flat path's" - ); - crate::encode::force_screen(Some(false)); - let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); - let kept_packets = encode_all(&mut kept, &pictures); - assert_eq!( - kept.pyramid(), - Some(Pyramid::default()), - "the gate ate a film stream" - ); - assert!( - kept_packets.iter().any(|p| p.level == Level::Arf), - "a non-screen stream coded no hidden frame" - ); - crate::encode::force_screen(None); - } - - /// A key frame every `gop` pictures, inter otherwise — checked against - /// what the facade itself reports, and (below) against what `ffprobe` - /// reads back out of the coded bytes. - #[test] - fn gop_cadence_is_honored() { - let _knobs = crate::speed::knob_read(); + let pyramid = Pyramid { + key_q_offset: offset, + ..Pyramid::default() + }; + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap(); + let key = packets + .iter() + .find(|p| p.level == Level::Key) + .expect("key frame"); + key.data.len() + }; + let (base, finer) = (key_bytes(0), key_bytes(-48)); + eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes"); + assert!( + finer > base, + "key_q_offset -48 did not reach the key frame ({finer} <= {base})" + ); +} + +/// lane-last2's witness: a clip whose pictures ALTERNATE between two +/// textures, so for every leaf the picture two back is an exact match and +/// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf +/// chain alternates its refresh over [`LEAF_SLOTS`] and names the older +/// slot `LAST2_FRAME`; blocks must actually be CODED off it +/// ([[gate-blind-to-feature]]: a slot that is retained but never chosen +/// proves only that the bookkeeping compiles), the stream must decode +/// sample-exact through OUR decoder and through ffmpeg, and the hidden +/// frames must still come out in display order. With the lever OFF the +/// same clip codes ZERO `LAST2` blocks, which is what makes the counter a +/// measurement of this lane and not of the reference set we already had. +#[test] +fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() { + let _knobs = crate::speed::knob_write(); + crate::encode::force_screen(Some(false)); + let (width, height) = (128usize, 128usize); + let sources: Vec = (0..9) + .map(|t| test_card(width, height, (t % 2) * 24)) + .collect(); + let run = |on: bool| -> ([usize; 8], Vec, Vec) { + set_last2(Some(on)); let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop: 3, - colour: Colour::Unspecified, + width, + height, + base_q_idx: 120, + gop: 32, + colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - let mut enc = Av1Encoder::new(config).unwrap(); - let pictures: Vec = (0..7).map(|t| test_card(64, 64, t)).collect(); - let keys: Vec = encode_all(&mut enc, &pictures) - .iter() - .map(|p| p.key) - .collect(); - assert_eq!(keys, vec![true, false, false, true, false, false, true]); - } - - fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { - let path = std::env::temp_dir().join(format!( - "ec-av1-facade-probe-{}-{}.obu", - std::process::id(), - std::ptr::addr_of!(stream) as usize - )); - std::fs::write(&path, stream).expect("writing the probe stream"); - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-f", - "obu", - "-select_streams", - "v:0", - "-show_entries", - "frame=key_frame,width,height", - "-of", - "csv=p=0", - ]) - .arg(&path).output() - .expect("ffprobe failed to run"); - let _ = std::fs::remove_file(&path); - assert!( - out.status.success(), - "ffprobe refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - String::from_utf8_lossy(&out.stdout) - .lines() - .map(|line| { - let mut f = line.trim().split(','); - let key: u32 = f.next().unwrap().parse().unwrap(); - let width: u32 = f.next().unwrap().parse().unwrap(); - let height: u32 = f.next().unwrap().parse().unwrap(); - (key == 1, width, height) - }) - .collect() - } - - fn ffprobe_colour(stream: &[u8]) -> String { - let path = std::env::temp_dir().join(format!( - "ec-av1-facade-colour-probe-{}-{}.obu", - std::process::id(), - std::ptr::addr_of!(stream) as usize - )); - std::fs::write(&path, stream).expect("writing the probe stream"); - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-f", - "obu", - "-select_streams", - "v:0", - "-show_entries", - "stream=color_primaries,color_transfer,color_space,color_range", - "-of", - "csv=p=0", - ]) - .arg(&path).output() - .expect("ffprobe failed to run"); - let _ = std::fs::remove_file(&path); - assert!( - out.status.success(), - "ffprobe refused the stream: {}", - String::from_utf8_lossy(&out.stderr) - ); - String::from_utf8_lossy(&out.stdout).trim().to_string() + let pyramid = Pyramid { + mini_gop: 4, + mid_q_offset: None, + ..Pyramid::default() + }; + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let _ = crate::encode::take_ref_frame_hits(); + let mut packets = Vec::new(); + for picture in &sources { + packets.extend(enc.encode_frames(picture).unwrap()); + } + packets.extend(enc.flush().unwrap()); + let hits = crate::encode::take_ref_frame_hits(); + (hits, concat(&packets), packets) + }; + let (off_hits, off_stream, _) = run(false); + let (on_hits, stream, packets) = run(true); + set_last2(None); + eprintln!( + "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \ + on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)", + off_hits[1], + off_hits[2], + off_hits[4], + off_hits[7], + off_stream.len(), + on_hits[1], + on_hits[2], + on_hits[4], + on_hits[7], + stream.len(), + ); + assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF"); + assert!( + on_hits[2] >= 8, + "the picture two back matches exactly and only {} blocks were coded off LAST2", + on_hits[2], + ); + + // Display order and sample-exactness, both decoders (the same shape + // `pyramid_round_trip` gates the hidden frames with). + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!( + ours.len(), + sources.len(), + "our decoder's display-order count" + ); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(got.len(), b.len(), "frame {i}: luma size"); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } } - - /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15) - /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that - /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and - /// coded size confirm what the facade already reported. - #[test] - fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { - let _knobs = crate::speed::knob_read(); - let (width, height) = (96usize, 96usize); + // The reordering itself is unchanged by the second leaf slot. + let shown = packets + .iter() + .filter(|p| p.level == Level::ShowExisting) + .count(); + let arfs = packets.iter().filter(|p| p.level == Level::Arf).count(); + assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); +} + +/// A picture whose content is a static gradient plus a per-picture +/// pseudo-random +-2 of noise: motion search matches the neighbours +/// almost exactly, so the ARF temporal filter's weights are near 1 and +/// the filter actually changes the source (a moving test card gives every +/// neighbour a large MSE, weight ~0, and the filter is a no-op that would +/// make the future-window witness below pass blind). +fn noisy_card(width: usize, height: usize, t: usize) -> Picture { + let mut picture = Picture::grey(width, height); + let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15); + for y in 0..height { + for x in 0..width { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + let noise = ((seed >> 33) % 5) as i32 - 2; + let base = 40 + (x + y) as i32 / 2; + picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16; + } + } + for i in 0..(width / 2) * (height / 2) { + picture.u[i] = 110; + picture.v[i] = 140; + } + picture +} + +/// lane-lookahead's correctness witness. One group of lookahead +/// (`Av1Encoder::drain_pending` hands the closed group to `ready` and +/// codes the group before it) must not change WHAT is coded: +/// +/// * with the future half of the filter window empty AND the top ARF's +/// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream +/// is byte for byte the one the encoder coded without a lookahead, at +/// every run length -- 1 picture (no hidden frame at all), 7 (a short +/// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 -- +/// and at a GOP short enough (8) that key frames drain the buffer +/// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so +/// the identity arm pins the lambda window off or this witness tests +/// a different lever; +/// * every run decodes to exactly its picture count through OUR decoder +/// and through ffmpeg, sample-exact between the two, so the flush and +/// the `show_existing_frame` order survive the delay; +/// * and with ONE future neighbour the top ARF's source filter actually +/// reads it -- the stream MOVES (class gate-blind-to-feature: a +/// buffered picture nothing consumes would pass every check above). +#[test] +fn the_lookahead_holds_one_group_and_still_codes_every_picture() { + let _knobs = crate::speed::knob_write(); + // The preset is PROCESS-GLOBAL and another test may have left it + // anywhere: at a high one every block of this fixture codes as skip + // (17 pictures in 493 bytes) and the source filter cannot change a + // byte, which failed the future-half assertion below in the suite and + // passed it standalone (class process-global-knob-races-tests). + let was = crate::speed::speed(); + crate::speed::set_speed(0); + crate::encode::force_screen(Some(false)); + let (width, height) = (128usize, 128usize); + let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec, Vec) { + set_lookahead(Some(on)); + set_arf_tf_future(Some(fut)); + set_tpl_fut(Some(0)); let config = EncoderConfig { + // FINE (not the 120 the other facade tests use): at a coarse + // quantizer this fixture's ARF codes almost pure skip (17 + // pictures in 493 bytes) and a filtered source quantizes back + // to the same bytes, which made the future-half assertion + // below depend on where the suite's other tests had left the + // process-global preset. At q=60 the anchor carries real + // coefficients and the filter must move them. + base_q_idx: 60, width, height, - base_q_idx: 120, - gop: 15, + gop, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - let mut enc = Av1Encoder::new(config).unwrap(); - assert_eq!(enc.display_size(), (width, height)); - let (coded_w, coded_h) = enc.coded_size(); - assert_eq!( - (coded_w, coded_h), - ( - width.next_multiple_of(SUPERBLOCK), - height.next_multiple_of(SUPERBLOCK) - ) - ); - - let pictures: Vec = (0..30).map(|t| test_card(width, height, t)).collect(); - let packets: Vec = encode_all(&mut enc, &pictures); - let expect_key: Vec = (0..30).map(|t| t % 15 == 0).collect(); - assert_eq!( - packets.iter().map(|p| p.key).collect::>(), - expect_key, - "facade's own key/inter flags" + let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + let sources: Vec = (0..n).map(|t| noisy_card(width, height, t)).collect(); + let packets = encode_all(&mut enc, &sources); + // The content gate is process-global and so is the preset: if + // either has been flipped under this test the pyramid is gone and + // there is no ARF to filter, which is a different failure from + // "the future neighbour changed nothing" (the suite reported the + // second when it meant the first). + assert!( + enc.pyramid().is_some(), + "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})", + crate::speed::speed(), ); - - let stream = concat(&packets); - let frames = ffprobe_frames(&stream); - assert_eq!(frames.len(), 30, "ffprobe frame count"); - for (t, (key, w, h)) in frames.iter().enumerate() { - assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); + (concat(&packets), packets) + }; + for gop in [32usize, 8] { + for n in [1usize, 7, 8, 9, 17] { + let (flat, flat_packets) = run(n, gop, false, 0); + let (held, packets) = run(n, gop, true, 0); + assert_eq!( + flat.len(), + held.len(), + "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH" + ); + assert!( + flat == held, + "{n} pictures at gop {gop}: the stream is not byte-identical" + ); + assert_eq!( + packets + .iter() + .map(|p| (p.order, p.key, p.level)) + .collect::>(), + flat_packets + .iter() + .map(|p| (p.order, p.key, p.level)) + .collect::>(), + "{n} pictures at gop {gop}: coding order/levels moved" + ); + let ours = crate::stream::decode_stream(&held).expect("our decoder"); assert_eq!( - (*w, *h), - (width as u32, height as u32), - "picture {t}: ffprobe reports the true (display) size, not the padded coded one" + ours.len(), + n, + "{n} pictures at gop {gop}: our decoder's count" + ); + let theirs = ffmpeg_decode_luma(&held, width, height); + assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert!( + got == *b, + "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg" + ); + } + } + } + // The future half REACHES the filter, and what it produces still + // decodes exactly. + let (base, _) = run(17, 32, true, 0); + let (symmetric, _) = run(17, 32, true, 1); + set_lookahead(None); + set_arf_tf_future(None); + set_tpl_fut(None); + assert!( + base != symmetric, + "one display-future neighbour left the top ARF's filter unchanged \ + ({} B vs {} B, preset {})", + base.len(), + symmetric.len(), + crate::speed::speed() + ); + let ours = crate::stream::decode_stream(&symmetric).expect("our decoder"); + assert_eq!(ours.len(), 17, "the symmetric arm's display-order count"); + { + let theirs = ffmpeg_decode_luma(&symmetric, width, height); + assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert!( + got == *b, + "symmetric arm, display frame {i}: ours differs from ffmpeg" ); } } - - /// The configured colour properties are what `ffprobe` reports back, - /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it - /// is the default a player assumes and the one this test would silently - /// pass without wiring for (`ffprobe` reports "unknown" for the - /// hardcoded "unspecified" this crate wrote before the facade existed, - /// which is a visibly different string). - #[test] - fn bt709_limited_colour_is_reported_by_ffprobe() { - let _knobs = crate::speed::knob_read(); + crate::speed::set_speed(was); +} + +/// lane-tplfut's correctness witness, the sibling of +/// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with +/// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next +/// group (`speed::TPL_FUT`), every picture is still coded, the streams +/// decode exactly through our decoder and ffmpeg, and the stream MOVES +/// against the knob off wherever a next group exists (class +/// gate-blind-to-feature). Coded at q=60, not 120: at a coarse +/// quantizer this fixture's ARF is almost pure skip and a different +/// lambda map re-quantises to identical bytes. +#[test] +fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() { + let _knobs = crate::speed::knob_write(); + let was = crate::speed::speed(); + crate::speed::set_speed(0); + crate::encode::force_screen(Some(false)); + let (width, height) = (128usize, 128usize); + let run = |n: usize, gop: usize, fut: usize| -> (Vec, Vec) { + set_lookahead(Some(true)); + set_arf_tf_future(Some(0)); + set_tpl_fut(Some(fut)); let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop: 4, + base_q_idx: 60, + width, + height, + gop, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - let mut enc = Av1Encoder::new(config).unwrap(); - let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); - let colour = ffprobe_colour(&packets[0].data); - assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); - } - - /// The same, for BT.601: a different set of CICP integers must produce a - /// different string, or the wiring could be a no-op that happens to read - /// as BT.709 for every input. - #[test] - fn bt601_limited_colour_is_reported_by_ffprobe() { - let _knobs = crate::speed::knob_read(); - let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop: 4, - colour: Colour::Bt601Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); - let colour = ffprobe_colour(&packets[0].data); - assert_eq!( - colour, "tv,smpte170m,smpte170m,smpte170m", - "ffprobe colour fields" - ); - } - - /// A frame whose size does not match the encoder's configured geometry - /// is refused by name. - #[test] - fn geometry_mismatch_is_refused() { - let _knobs = crate::speed::knob_read(); - let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop: 4, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); - assert!(err.to_string().contains("64x64"), "{err}"); - } - - /// `gop == 0` is refused at construction, not the first `encode()` call. - #[test] - fn zero_gop_is_refused() { - let _knobs = crate::speed::knob_read(); - let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop: 0, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let err = Av1Encoder::new(config).unwrap_err(); - assert!(err.to_string().contains("gop"), "{err}"); - } - - /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget` - /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down - /// to this facade's own input size, and re-coded through the facade so the - /// rate-target surface is exercised at the entry point a caller actually - /// drives. - fn h264_clip_frames( - width: usize, - height: usize, - frames: usize, - ) -> Option> { - h264_clip_frames_at(20, width, height, frames) - } - - fn h264_clip_frames_at( - start: u32, - width: usize, - height: usize, - frames: usize, - ) -> Option> { - // lane-av1speed3: the wall tables below are read on REAL film as - // well as on the colour-bar fixture (`bars` vs `film` in the BD - // gate's own vocabulary), and the film crop lives outside the repo -- - // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other - // caller still gets the fixture. - // - // lane-av1clipprobe: the default path resolves through `EC_FIXTURES` - // first, which is the root `scripts/verify-fixture-library.sh` - // validates -- so the preflight's verdict and these bytes are the same - // tree, and GREEN-with-an-absent-root is no longer reachable by - // pointing EC_FIXTURES somewhere the gates do not read. - let clip = match std::env::var("EC_AV1_WALL_CLIP") { - Ok(p) => std::path::PathBuf::from(p), - Err(_) => ec_testkit::fixture("open/sintel_trailer-1080p.mp4"), - }; - // `what` is the CALLING GATE's name, carried in so that both exits from - // this function print exactly one line naming it: the ffmpeg line - // above, and the probe's line naming the resolved path. Callers - // therefore `return` on `None` WITHOUT printing a second one -- the - // second "no fixture" line per gate was the noise that hid this defect. - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-ss", &start.to_string(), "-i", clip.to_str().unwrap()]) - .args(["-frames:v", &frames.to_string()]) - .args(["-vf", &format!("scale={width}:{height}")]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() - .expect("ffmpeg failed to run"); + let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + let sources: Vec = (0..n).map(|t| noisy_card(width, height, t)).collect(); + let packets = encode_all(&mut enc, &sources); assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) + enc.pyramid().is_some(), + "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})", + crate::speed::speed(), ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_len = luma + 2 * chroma; - assert_eq!( - out.stdout.len(), - frame_len * frames, - "expected {frames} 4:2:0 frames" + (concat(&packets), packets) + }; + for gop in [32usize, 8] { + for n in [1usize, 7, 8, 9, 17] { + let (off, off_packets) = run(n, gop, 0); + for mode in [1usize, 2, 3] { + let (on, packets) = run(n, gop, mode); + assert_eq!( + packets + .iter() + .map(|p| (p.order, p.key, p.level)) + .collect::>(), + off_packets + .iter() + .map(|p| (p.order, p.key, p.level)) + .collect::>(), + "{n} pictures at gop {gop} mode {mode}: coding order/levels moved" + ); + let ours = crate::stream::decode_stream(&on).expect("our decoder"); + assert_eq!( + ours.len(), + n, + "{n} pictures at gop {gop} mode {mode}: our count" + ); + let theirs = ffmpeg_decode_luma(&on, width, height); + assert_eq!( + theirs.len(), + n, + "{n} pictures at gop {gop} mode {mode}: ffmpeg count" + ); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert!( + got == *b, + "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg" + ); + } + } + let _ = &off; + } + } + // The future window REACHES the lambda map: 17 pictures at gop 32 is + // three groups, so the first two top ARFs each have a next group + // buffered and their windows really are display-future. + let (off, _) = run(17, 32, 0); + // Mode 2 is NOT in this list: at its default split it keeps the three + // NEAREST past neighbours, and those dominate the propagation -- on + // this 128x128 fixture the map moves too little to flip an RD + // decision and the stream comes back byte-identical to mode 0. Not a + // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past + // neighbour, six future) does move the stream, and the gate below + // measures mode 2 on real content. + for mode in [1usize, 3] { + let (on, _) = run(17, 32, mode); + assert!( + off != on, + "mode {mode} left the top ARF's temporal lambda map unchanged \ + ({} B vs {} B, preset {})", + off.len(), + on.len(), + crate::speed::speed() ); - Some( - (0..frames) - .map(|i| { - let bytes = &out.stdout[i * frame_len..][..frame_len]; - Picture { - width, - height, - y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), - u: bytes[luma..luma + chroma] - .iter() - .map(|&v| u16::from(v)) - .collect(), - v: bytes[luma + chroma..] - .iter() - .map(|&v| u16::from(v)) - .collect(), - } - }) - .collect(), - ) } - - /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total - /// coded size within ±20% of `frames * target` once the first few - /// frames' settling has been discarded (the key frame's own reference - /// state and the controller's first couple of steps). - #[test] - fn bytes_per_frame_target_settles_within_20_percent() { - let _knobs = crate::speed::knob_read(); - let Some(pictures) = h264_clip_frames(640, - 384, - 24, - ) else { - return; - }; - let target_bytes = 4_000u32; + set_lookahead(None); + set_arf_tf_future(None); + set_tpl_fut(None); + crate::speed::set_speed(was); +} + +/// lane-arfmode: the top ARF's leaf offer set. Three guards in one +/// witness, over 17 pictures at gop 32 (three groups, so several top +/// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the +/// anchor carries real coefficients, so a cut that moves only the +/// hidden frame's internal decisions cannot hide behind "everything +/// quantized to the same bytes": +/// +/// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the +/// shipped table is 0 and the lever is bit-exact when off; +/// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really +/// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter +/// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM; +/// 3. the coding order and levels never change, and every armed stream +/// decodes sample-exact through `decode_stream` AND ffmpeg. +#[test] +fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let was = crate::speed::speed(); + crate::speed::set_speed(0); + crate::encode::force_screen(Some(false)); + let (width, height) = (128usize, 128usize); + let run = |mode: Option| -> (Vec, Vec) { + crate::encode::set_arfmode(mode); + let _ = crate::encode::take_arfmode_hits(); let config = EncoderConfig { - width: 640, - height: 384, - base_q_idx: 100, - gop: 24, + base_q_idx: 60, + width, + height, + gop: 32, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - let mut enc = - Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); - let sizes: Vec = encode_all(&mut enc, &pictures) - .iter() - .map(|p| p.data.len()) + let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + // Groups at three luma LEVELS (the base ramp 40/110/180): the + // middle group's top ARF sits halfway between the two dark/light + // anchors its slots hold, which is exactly where neither + // single-reference prediction nor intra wins by default -- the + // AVERAGE of two references (compound) and the DC of the new + // level (intra) do. Without this the synthetic cards' noise + // quantizes to skip and no arm can move anything (measured: + // 516 intra trials skipped, zero won, stream identical). + let sources: Vec = (0..17) + .map(|t| { + let mut p = noisy_card(width, height, t); + let shift = 70i32 * (t / 8) as i32; + for v in p.y.iter_mut() { + *v = (i32::from(*v) + shift).clamp(0, 255) as u16; + } + p + }) .collect(); - // Discard the key frame (always far larger than an inter target) and - // the next 4 inter frames the loop needs to step toward it. - let settled = &sizes[5..]; - let mean = settled.iter().sum::() as f64 / settled.len() as f64; - let low = f64::from(target_bytes) * 0.8; - let high = f64::from(target_bytes) * 1.2; + let packets = encode_all(&mut enc, &sources); + (concat(&packets), packets) + }; + let (off, off_packets) = run(None); + let (explicit_off, _) = run(Some(0)); + assert_eq!( + off, explicit_off, + "mode 0 is not bit-exact with the default" + ); + for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] { + let (on, packets) = run(Some(mode)); + let hits = crate::encode::take_arfmode_hits(); + assert_eq!( + packets + .iter() + .map(|p| (p.order, p.key, p.level)) + .collect::>(), + off_packets + .iter() + .map(|p| (p.order, p.key, p.level)) + .collect::>(), + "mode {mode}: coding order/levels moved" + ); assert!( - mean >= low && mean <= high, - "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" + hits[arm] > 0, + "mode {mode}: its counter never fired ({hits:?}) -- the lever is \ + gate-blind on this fixture", ); + assert_ne!( + off, on, + "mode {mode} left the stream byte-identical despite {} firing hits", + hits[arm], + ); + eprintln!( + "mode {mode}: {} -> {} B, hits {hits:?}", + off.len(), + on.len() + ); + let ours = crate::stream::decode_stream(&on).expect("our decoder"); + assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count"); + let theirs = ffmpeg_decode_luma(&on, width, height); + assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert!( + got == *b, + "mode {mode}, frame {i}: ours differs from ffmpeg" + ); + } } - - /// One (bitrate, pyramid) arm's tally, built on the worker thread and - /// handed back through the progress channel - /// (`bitrate_target_lands_within_5_percent_over_48_frames`). Per LEVEL, - /// so a miss reads as WHICH level's model is off rather than as one - /// aggregate percentage. - struct ArmResult { - /// [`RateLoop::target`] as the arm's own encoder computed it. - targets: [f64; 3], - coded: usize, - bytes: [usize; 4], - count: [usize; 4], - } - - impl ArmResult { - fn take(&mut self, packets: Vec) { - for packet in packets { - self.coded += packet.data.len(); - let i = match packet.level { - Level::Key => 0, - Level::Arf => 1, - Level::Leaf => 2, - Level::ShowExisting => 3, - }; - self.bytes[i] += packet.data.len(); - self.count[i] += 1; - } + crate::encode::set_arfmode(None); + crate::speed::set_speed(was); +} + +fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { + let (width, height) = (128usize, 128usize); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 32, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + // The content gate ([`Av1Encoder::encode_frames`]) would drop a + // screen-content stream to the flat path, and a synthetic test card + // is exactly the few-colour picture the detector fires on: this gate + // is about the reordering, so it asks for camera content explicitly. + crate::encode::force_screen(Some(false)); + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let sources: Vec = (0..9).map(|t| test_card(width, height, t * 3)).collect(); + let _ = crate::encode::take_ref_frame_hits(); + let mut packets = Vec::new(); + for picture in &sources { + packets.extend(enc.encode_frames(picture).unwrap()); + } + packets.extend(enc.flush().unwrap()); + + // Shape: every source picture is coded exactly once, and each closed + // group adds one `show_existing_frame` packet. + let coded: Vec = packets + .iter() + .filter(|p| p.level != Level::ShowExisting) + .map(|p| p.order) + .collect(); + let mut sorted = coded.clone(); + sorted.sort_unstable(); + assert_eq!( + sorted, + (0..9).collect::>(), + "one packet per picture" + ); + assert_ne!(coded, sorted, "the pyramid never reordered anything"); + let shown = packets + .iter() + .filter(|p| p.level == Level::ShowExisting) + .count(); + assert_eq!(shown, hidden, "one show_existing_frame per hidden frame"); + for (i, p) in packets.iter().enumerate() { + assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); + } + let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); + eprintln!( + "pyramid levels: key {} arf {} leaf {} show_existing {}", + hist(Level::Key), + hist(Level::Arf), + hist(Level::Leaf), + hist(Level::ShowExisting), + ); + assert_eq!(hist(Level::Arf), hidden, "hidden frames"); + let refs = crate::encode::take_ref_frame_hits(); + eprintln!( + "blocks per reference: LAST {} GOLDEN {} ALTREF {}", + refs[crate::mvstack::LAST_FRAME as usize], + refs[crate::mvstack::GOLDEN_FRAME as usize], + refs[crate::mvstack::ALTREF_FRAME as usize], + ); + // [[gate-blind-to-feature]]: the whole point of the hidden frame is + // that the leaves predict BACKWARD off it, which is also the only + // thing that exercises `ref_frame_sign_bias` in the MV stack. A green + // round trip in which `ALTREF_FRAME` never won a block would prove + // only that a hidden frame can be written and re-output. + assert!( + refs[crate::mvstack::ALTREF_FRAME as usize] > 0, + "no block predicted off the hidden ALTREF" + ); + + let stream = concat(&packets); + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!( + ours.len(), + sources.len(), + "our decoder's display-order count" + ); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(got.len(), b.len(), "frame {i}: luma size"); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); } } - - /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the - /// target over 48 frames of a real clip, flat and under a pyramid alike, - /// across a 5x span of bitrates. This is the accuracy claim of the - /// target-bitrate mode: no two-pass, no lookahead, just each frame's size - /// predicted from the previous frame of its own level, one clamped - /// proportional step, and the level model - /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits. - /// - /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut - /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the - /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that - /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a - /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12 - /// `leaf_q_offset`, so this clip cannot be made to spend much past - /// 2.4 Mbit/s under the default pyramid however the budget is split. - /// - /// # Bounded - /// - /// Each arm's encode runs on a worker thread under a per-CALL - /// wall-clock ceiling, so this gate FAILS rather than hanging when an - /// encode stops terminating (lane-av1enchang: a 3h20m wedge on one host - /// and 30min on another, both here, both with the test thread spinning - /// and no child process for the crate's child timeout to reap). The cost - /// is real and is why the budget is not tight: the two high bitrate arms - /// walk `q_idx` from the seed 100 down into the 20s to spend an - /// 8000-byte budget on a 640x384 clip, and a frame at `q_idx` 25 costs - /// ~15s in a debug build (~1s optimized) against ~0.5s at `q_idx` 100. - /// lane-av1enchang: the PYRAMID CONSTRUCTORS fit on a tight stack. - /// - /// `Av1Encoder` used to be 139960 bytes BY VALUE, because each of the - /// eight `DpbSlot`s held a 15 KB `CdfSnapshot` inline. The pyramid - /// constructors nest three deep -- `with_pyramid_and_rate_target` -> - /// `with_pyramid` -> `new` -- and each level materialises the struct in - /// an unoptimized build, so ~840 KB of stack was live at the innermost - /// `Ok(Self { .. })`. On libtest's default 2 MiB test thread that aborts: - /// `fatal runtime error: stack overflow, aborting`, reproduced on the - /// pre-fix binary at `crates/ec-av1/src/encoder.rs:1519` via - /// `coredumpctl debug`. - /// - /// Boxing the snapshot brought the struct to 18168 bytes. This gate pins - /// that: it builds BOTH constructors on a thread with a deliberately - /// tight stack, so the old layout ABORTS THE PROCESS and the new one - /// returns. It runs in milliseconds, where proving the same thing through - /// the 48-frame gate takes 6m35s. - /// - /// Both thresholds were swept, in an unoptimized build: - /// - /// | stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) | - /// |---|---|---| - /// | 256 KiB | overflow | overflow | - /// | 384 KiB | overflow | ok | - /// | 512 KiB | overflow | ok | - /// | 1 MiB | **overflow** | **ok** | - /// | 2 MiB | **overflow** (libtest's default) | ok | - /// | 3 MiB | ok | ok | - /// - /// 1 MiB is the gate: 2.7x what the boxed layout needs and 2x below what - /// the old one did, so it is nowhere near either threshold and cannot - /// flake. The pre-fix row at 1 MiB is the red -- which is also why - /// `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, a - /// workspace-local band-aid this gate makes unnecessary for this struct. - /// - /// `EC_AV1_TIGHT_STACK_BYTES` overrides the size, which is how the sweep - /// above is reproduced. - #[test] - fn the_pyramid_constructors_fit_on_a_tight_stack() { - // 1 MiB: see the threshold table on this test. Red before the Box, - // green after, with 2.7x margin either way. - const STACK: usize = 1024 * 1024; - let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(STACK); - let config = EncoderConfig { - width: 640, - height: 384, - base_q_idx: 100, - gop: 48, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let rate = RateTarget::Bitrate { - bits_per_second: 1_536_000, - frames_per_second: 24.0, - }; - let handle = std::thread::Builder::new() - .stack_size(stack) - .spawn(move || { - let flat = Av1Encoder::with_rate_target(config, rate) - .expect("with_rate_target") - .rate_loop - .is_some(); - let pyr = - Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate) - .expect("with_pyramid_and_rate_target") - .pyramid - .is_some(); - (flat, pyr) - }) - .expect("spawn tight-stack thread"); - let (flat, pyr) = handle - .join() - .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack")); - assert!(flat, "with_rate_target lost its rate loop"); - assert!(pyr, "with_pyramid_and_rate_target lost its pyramid"); - eprintln!( - "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned", - std::mem::size_of::() +} + +// Every tile layout this encoder can write decodes SAMPLE-EXACT +// through both decoders -- ours and ffmpeg's -- and the frames really +// carry the tiles the header claims (the OBU parser locates one payload +// per tile, so a stream that quietly stayed single-tile fails here +// rather than passing on a green round trip). +// +// The bytes are what the gate is on: an encoder that clipped its +// neighbour availability wrong writes a stream whose two decoders agree +// with each other and disagree with nothing -- so the ffmpeg half is +// the one that catches a tile boundary the writer respected and the +// spec does not, and the parser half catches the reverse. + +#[test] +fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (256usize, 128usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..3).map(|_| still.clone()).collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_root_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let roots = crate::encode::take_b64_root_hits(); + // 8 superblocks per frame, two inter frames. + assert!( + roots > 0, + "a static clip coded no 64x64 root at all (of 16 inter superblocks)" + ); + eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } + assert_eq!( + got.len(), + b.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + b.len() ); } - - const CLEAN_START: u32 = 23; - - #[test] - fn bitrate_target_lands_within_5_percent_over_48_frames() { - let _knobs = crate::speed::knob_read(); - let (width, height, frames) = (640usize, 384usize, 48usize); - let Some(pictures) = h264_clip_frames_at(CLEAN_START, width, - height, - frames, - ) else { - return; - }; - let fps = 24.0; - let pictures = std::sync::Arc::new(pictures); - for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { - let config = EncoderConfig { - width, - height, - base_q_idx: 100, - gop: frames, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let rate = RateTarget::Bitrate { - bits_per_second, - frames_per_second: fps, - }; - for pyramid in [None, Some(Pyramid::default())] { - let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some()); - // Shared, not cloned: the 48 decoded frames are ~35 MB of - // `u16` luma+chroma, and all eight arms want the same ones. - let pictures = std::sync::Arc::clone(&pictures); - // `None` is a progress ticket: THIS call returned. `Some` is - // the arm's result, sent after `flush` -- which is itself a - // call that can spin, so it needs a ticket too, not a bare - // `join` that would block forever. - let (tx, rx) = std::sync::mpsc::channel::>(); - let worker = std::thread::spawn(move || { - let mut enc = match pyramid { - None => Av1Encoder::with_rate_target(config, rate).unwrap(), - Some(p) => { - Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap() - } - }; - let targets = enc.rate_loop.as_ref().unwrap().target; - let mut out = ArmResult { - targets, - coded: 0, - bytes: [0; 4], - count: [0; 4], - }; - for picture in pictures.iter() { - out.take(enc.encode_frames(picture).unwrap()); - if tx.send(None).is_err() { - return; - } - } - out.take(enc.flush().unwrap()); - let _ = tx.send(Some(out)); - }); - let out = loop { - match rx.recv() { - Ok(Some(out)) => break out, - Ok(None) => {} - Err(_) => { - worker.join().expect("encode worker panicked"); - panic!("AV1 encode worker for {arm} died without a result"); - } - } - }; - let ArmResult { - targets, - coded, - bytes, - count, - } = out; - let seconds = frames as f64 / fps; - let achieved = coded as f64 * 8.0 / seconds; - let error = achieved / f64::from(bits_per_second) - 1.0; - let per = |i: usize| match count[i] { - 0 => "-".to_string(), - n => format!("{n}x{}", bytes[i] / n), - }; - eprintln!( - "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ - = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \ - coded key {} arf {} leaf {}", - pyramid.is_some(), - 100.0 * error, - targets[0], - targets[1], - targets[2], - per(0), - per(1), - per(2), - ); - assert!( - error.abs() <= 0.05, - "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ - (pyramid {})", - 100.0 * error, - pyramid.is_some(), - ); +} + +/// The same clip with a DC step between frames (lane-tx64): the 64x64 +/// root still predicts the whole superblock from the last frame, but the +/// prediction is uniformly off, so the root's NON-skip arm -- one +/// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below +/// its skip arm and a 64x64 residual is really written. The counter is +/// the gate (class `gate-blind-to-feature`; the static clip above cannot +/// reach this arm at all because its prediction is exact), and both +/// decoders have to reconstruct those coefficients sample-exact -- a +/// writer that names the wrong coefficient set or the wrong `txfm_split` +/// desyncs the whole tile here. +#[test] +fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (256usize, 128usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..3) + .map(|t| { + let mut p = still.clone(); + let step = (t * 6) as u16; + for v in &mut p.y { + *v = (*v + step).min(255); } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_residual_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let residuals = crate::encode::take_b64_residual_hits(); + assert!( + residuals > 0, + "a DC-stepped clip coded no 64x64 root with a residual at all" + ); + eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); } + assert_eq!( + got.len(), + b.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + b.len() + ); } - /// The `BytesPerFrame` controller's own windup bound: no frame's coded - /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real - /// clip's full range of content (so a scene cut can't be the one frame - /// that breaks the bound). - /// - /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot - /// that has coded nothing yet is still sitting on the caller's - /// `base_q_idx` guess, and its first step is the acquisition jump, not - /// windup. Exactly one frame is exempt -- the loop below asserts the - /// bound on every frame after it, which is where a scene cut would - /// break it. - #[test] - fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { - let _knobs = crate::speed::knob_read(); - let Some(pictures) = h264_clip_frames(640, - 384, - 24, - ) else { - return; - }; - let config = EncoderConfig { - width: 640, - height: 384, - base_q_idx: 100, - gop: 24, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = - Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); - let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); - // The first frame this encoder EMITS is several `encode_frames` calls - // in (the lookahead queue holds the earlier ones), so the seeding - // step is not frame zero -- it is the first frame `q` moves at all. - let mut seeded = false; - let mut seed_frame = None; - for (frame, picture) in pictures.iter().enumerate() { - enc.encode_frames(picture).unwrap(); - let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); - let step = (i32::from(q) - i32::from(prev_q)).abs(); - if step > 0 && !seeded { - seeded = true; - seed_frame = Some(frame); - } else { - assert!( - f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding - "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp", - RateLoop::STEP_CLAMP - ); - } - prev_q = q; +} + +/// A frame whose size is NOT a multiple of a superblock (lane-b64b): +/// 232x168 leaves the last superblock column and row cut by the true +/// frame edge, with more than half of each inside -- which is exactly +/// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films +/// are superblock-aligned, so nothing but a synthetic size reaches this +/// path at all (class `gate-blind-to-feature`), and the user's own +/// exports are arbitrary sizes. +#[test] +fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (232usize, 168usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..3).map(|_| still.clone()).collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_edge_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let edges = crate::encode::take_b64_edge_hits(); + assert!( + edges > 0, + "no 64x64 root was taken at a superblock the frame edge cuts" + ); + eprintln!("edge 64x64 roots: {edges}"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + theirs_i[at], + ); } - assert!( - seed_frame.is_some(), - "the controller never steered at all -- the bound below is vacuous" + assert_eq!( + got.len(), + theirs_i.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + theirs_i.len() ); } - - fn psnr(a: &[u16], b: &[u16]) -> f64 { - let squared: f64 = a - .iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum(); - if squared == 0.0 { - return f64::INFINITY; +} + +/// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three +/// whole superblock columns and 1.6875 superblock rows, so the bottom +/// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b +/// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8) +/// leaves it did not. Every one of them is now scored over its inside +/// part alone, and a distortion change that moved a partition or a +/// transform decision the writer did not follow would desync the tile, so +/// both decoders reconstruct it sample-exact. +#[test] +fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (384usize, 216usize); + let sources: Vec = (0..3).map(|i| test_card(width, height, i)).collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + theirs_i[at], + ); } - 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() - } - - /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one - /// entry per coded frame, in order — this facade's own equivalent of - /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a - /// PSNR check needs the decoded pixels, not just the coded byte count. - fn ffmpeg_decode_planes( - stream: &[u8], - width: usize, - height: usize, - ) -> Vec<(Vec, Vec, Vec)> { - let path = std::env::temp_dir().join(format!( - "ec-av1-facade-rate-decode-{}-{}.obu", - std::process::id(), - std::ptr::addr_of!(stream) as usize - )); - std::fs::write(&path, stream).expect("writing the decode probe stream"); - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-f", "obu", "-i"]) - .arg(&path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() - .expect("ffmpeg failed to run"); - let _ = std::fs::remove_file(&path); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) + assert_eq!( + got.len(), + theirs_i.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + theirs_i.len() ); - let (luma, chroma) = (width * height, width * height / 4); - let frame_len = luma + 2 * chroma; - out.stdout - .chunks_exact(frame_len) - .map(|f| { - ( - f[..luma].to_vec(), - f[luma..luma + chroma].to_vec(), - f[luma + chroma..].to_vec(), - ) - }) - .collect() - } - - /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare. - fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec> { - ffmpeg_decode_planes(stream, width, height) - .into_iter() - .map(|(y, _, _)| y) - .collect() - } - - /// lane-palw: OUR encoder's own witness for the writer half of the - /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall, - /// so the bottom superblock row's palette blocks hang 8 luma rows off the - /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN - /// corner only and replicates it outward, and the writer used to code the - /// full block grid -- symbols a conformant decoder never reads, so - /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode - /// (unclamped on both sides) agreed with itself. Class - /// `writer-phantom-units-past-edge`. - /// - /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's - /// export calls), and compared on EVERY plane -- a chroma palette map is - /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero - /// so the row cannot pass on a stream that cuts no palette map (class - /// gate-blind-to-feature). - #[test] - fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() { - const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg"; - let _knobs = crate::speed::knob_read(); - let (width, height) = (384usize, 152usize); - // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at - // most two luma values, so the palette arm wins across the WHOLE - // frame -- including the bottom superblock row, whose 16x16 blocks at - // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid. - // `screen_card`'s 4-px bands fire only 9 palettes here and none of - // them at the cut edge (class gate-blind-to-feature). - let card = |shift: usize| -> Picture { - let mut picture = Picture::grey(width, height); - for y in 0..height { - for x in 0..width { - let cell = ((x + shift) / 8 + y / 8) % 2; - picture.y[y * width + x] = if cell == 0 { 40 } else { 200 }; - } + } +} + +/// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every +/// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is +/// off by exactly the detail a TX_64X64 throws away (it codes only the +/// top-left 32x32 corner of its coefficient space) and the root's var-tx +/// arm splits its luma into four TX_32X32 units instead. The counter is +/// the gate (class `gate-blind-to-feature`), and a `txfm_split` the +/// reader does not expect desyncs the whole tile, so both decoders have +/// to reconstruct it sample-exact. +#[test] +fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (256usize, 128usize); + let still = test_card(width, height, 0); + let sources: Vec = (0..4) + .map(|t| { + let mut p = still.clone(); + for (i, v) in p.y.iter_mut().enumerate() { + let checker = ((i % width) / 4 + (i / width) / 4) % 2; + let bump = (t * 5 * (checker + 1)) as u16; + *v = (*v + bump).min(255); } - picture - }; - let sources: Vec = (0..2).map(|t| card(t * 16)).collect(); + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 8, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_var_tx_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let split = crate::encode::take_b64_var_tx_hits(); + assert!(split > 0, "no 64x64 root split its luma transform at all"); + eprintln!("64x64 roots with a SPLIT luma transform: {split}"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + theirs_i[at], + ); + } + assert_eq!( + got.len(), + theirs_i.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + theirs_i.len() + ); + } +} + +/// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two +/// stills, so on a leaf frame the average of its past (`LAST`) and future +/// (`ALTREF`) references IS the source and neither reference alone is -- +/// exactly the content a COMPOUND 64x64 root pays on. The counter is the +/// gate (class `gate-blind-to-feature`): without it a green three-way +/// compare says nothing about whether one compound root was written, and +/// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no +/// `motion_mode` symbol) desyncs the whole tile if it is wrong. +#[test] +fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (256usize, 128usize); + let (a, b) = (test_card(width, height, 0), test_card(width, height, 24)); + let sources: Vec = (0..9) + .map(|t| { + let mut p = a.clone(); + let w = t as u32; + for (v, &other) in p.y.iter_mut().zip(&b.y) { + *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16; + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 9, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + let _ = crate::encode::take_b64_compound_hits(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let compound = crate::encode::take_b64_compound_hits(); + assert!( + compound > 0, + "a crossfade clip coded no COMPOUND 64x64 root at all" + ); + eprintln!("compound 64x64 roots on a crossfade clip: {compound}"); + + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); + for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { + panic!( + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + theirs_i[at], + ); + } + assert_eq!( + got.len(), + theirs_i.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + theirs_i.len() + ); + } +} + +#[test] +fn every_tile_layout_decodes_sample_exact_through_both_decoders() { + let _knobs = crate::speed::knob_read(); + let (width, height) = (640usize, 384usize); + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + let mut sizes = Vec::new(); + for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { let config = EncoderConfig { width, height, - base_q_idx: 60, - gop: 2, + base_q_idx: 120, + gop: 4, colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, }; + let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); + // lane-b128m: the SPEC's uniform spacing derives the tile count + // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`), + // so a frame with fewer superblock columns than the requested + // count codes fewer tiles -- which is what a 128-superblock + // sequence does here. The grid the encoder itself computes is the + // expectation; at 64 superblocks it is `1 << log2` exactly. + let grid = crate::tile::TileLayout::new( + (width as u32).div_ceil(4), + (height as u32).div_ceil(4), + cols_log2, + rows_log2, + ); + let (want_cols, want_rows) = (grid.cols(), grid.rows()); let mut enc = Av1Encoder::new(config).unwrap(); - crate::tile::reset_palette_cut_maps_written(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } - eprintln!( - "{NAME}: {} cut colour-index maps written", - crate::tile::palette_cut_maps_written() - ); - assert!( - crate::tile::palette_cut_maps_written() > 0, - "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind" - ); - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames"); - let theirs = ffmpeg_decode_planes(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] { - let got: Vec = got.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) { - let w = if plane == "luma" { width } else { width / 2 }; - panic!( - "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}", - at % w, - at / w, - got[at], - want[at], + sizes.push((layout.clone(), stream.len())); + + // The frames carry the tiles their headers claim. + let mut parser = ec_av1_syntax::Av1Parser::new(); + let mut frames = 0usize; + let mut offset = 0usize; + while offset < stream.len() { + let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); + let unit: usize = obus.iter().map(|o| o.total_size).sum(); + for obu in &obus { + if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { + assert_eq!( + (parsed.tile_info.cols, parsed.tile_info.rows), + (want_cols, want_rows), + "{layout}: the header's own tile grid" + ); + assert_eq!( + tiles.len(), + (want_cols * want_rows) as usize, + "{layout}: tile payloads located in the tile group" ); + frames += 1; } - assert_eq!( - got.len(), - want.len(), - "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}", - got.len(), - want.len() - ); } + offset += unit; } - } - - /// A pyramid stream reorders pictures: the hidden `ALTREF` of each - /// mini-GOP is coded before the leaves that precede it in display order, - /// and a `show_existing_frame` header puts it back. This pins the shape - /// (one packet per source picture plus one `show_existing_frame` per - /// group, `dts` monotone, `order` NOT monotone) and then decodes the - /// whole stream through OUR decoder and through ffmpeg/dav1d and requires - /// the two display-order outputs to agree sample for sample — the - /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never - /// output, or output twice, or output in the wrong position, changes the - /// display-order list and fails here. - #[test] - fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { - // `take_ref_frame_hits` is a process-global counter: a reader-locked - // sibling encoding at the same time zeroes it between our encode and - // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the - // exclusive lock. - let _knobs = crate::speed::knob_write(); - pyramid_round_trip( - Pyramid { - mini_gop: 4, - mid_q_offset: None, - ..Pyramid::default() - }, - 2, - ); - } - - /// The same round trip over a THREE-level group (`mid_q_offset`): each - /// mini-GOP now codes two hidden frames -- the top ARF at the group's - /// last picture and the mid ARF at the middle of the leaf run -- and - /// re-outputs both with `show_existing_frame`, so a mid frame emitted in - /// the wrong display position, or twice, fails the display-order compare - /// against ffmpeg exactly as a top ARF does. - #[test] - fn a_three_level_pyramid_stream_decodes_in_display_order() { - let _knobs = crate::speed::knob_write(); - pyramid_round_trip( - Pyramid { - mini_gop: 8, - mid_q_offset: Some(-8), - ..Pyramid::default() - }, - 2, - ); - } - - /// The same round trip over a FOUR-level group - /// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four - /// hidden frames -- the top ARF at picture 8, the mid at 4 and the two - /// quarters at 2 and 6 -- each re-output by its own - /// `show_existing_frame`. Every leaf reads a different pair of DPB slots - /// than it did at three levels, so a slot map that lets one level - /// overwrite a picture another is still reading shows up here as a - /// display-order mismatch against ffmpeg. - #[test] - fn a_four_level_pyramid_stream_decodes_in_display_order() { - let _knobs = crate::speed::knob_write(); - pyramid_round_trip( - Pyramid { - mini_gop: 8, - mid_q_offset: Some(-8), - quarter_q_offset: Some(4), - ..Pyramid::default() - }, - 4, - ); - } - - /// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads - /// the key, so an offset that never arrived would be invisible in the BD - /// table except as "no change" (class symbol-consumption-gap). A finer - /// key must cost strictly more bytes than the same picture at base q. - #[test] - fn the_key_q_offset_reaches_the_key_frame() { - let _knobs = crate::speed::knob_read(); - crate::encode::force_screen(Some(false)); - let key_bytes = |offset: i16| { - let config = EncoderConfig { - width: 128, - height: 128, - base_q_idx: 120, - gop: 32, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let pyramid = Pyramid { - key_q_offset: offset, - ..Pyramid::default() - }; - let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); - let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap(); - let key = packets - .iter() - .find(|p| p.level == Level::Key) - .expect("key frame"); - key.data.len() - }; - let (base, finer) = (key_bytes(0), key_bytes(-48)); - eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes"); - assert!( - finer > base, - "key_q_offset -48 did not reach the key frame ({finer} <= {base})" - ); - } - - /// lane-last2's witness: a clip whose pictures ALTERNATE between two - /// textures, so for every leaf the picture two back is an exact match and - /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf - /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older - /// slot `LAST2_FRAME`; blocks must actually be CODED off it - /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen - /// proves only that the bookkeeping compiles), the stream must decode - /// sample-exact through OUR decoder and through ffmpeg, and the hidden - /// frames must still come out in display order. With the lever OFF the - /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a - /// measurement of this lane and not of the reference set we already had. - #[test] - fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() { - let _knobs = crate::speed::knob_write(); - crate::encode::force_screen(Some(false)); - let (width, height) = (128usize, 128usize); - let sources: Vec = (0..9) - .map(|t| test_card(width, height, (t % 2) * 24)) - .collect(); - let run = |on: bool| -> ([usize; 8], Vec, Vec) { - set_last2(Some(on)); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 32, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let pyramid = Pyramid { - mini_gop: 4, - mid_q_offset: None, - ..Pyramid::default() - }; - let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); - let _ = crate::encode::take_ref_frame_hits(); - let mut packets = Vec::new(); - for picture in &sources { - packets.extend(enc.encode_frames(picture).unwrap()); - } - packets.extend(enc.flush().unwrap()); - let hits = crate::encode::take_ref_frame_hits(); - (hits, concat(&packets), packets) - }; - let (off_hits, off_stream, _) = run(false); - let (on_hits, stream, packets) = run(true); - set_last2(None); - eprintln!( - "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \ - on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)", - off_hits[1], - off_hits[2], - off_hits[4], - off_hits[7], - off_stream.len(), - on_hits[1], - on_hits[2], - on_hits[4], - on_hits[7], - stream.len(), - ); - assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF"); - assert!( - on_hits[2] >= 8, - "the picture two back matches exactly and only {} blocks were coded off LAST2", - on_hits[2], - ); + assert_eq!(frames, sources.len(), "{layout}: coded frames"); - // Display order and sample-exactness, both decoders (the same shape - // `pyramid_round_trip` gates the hidden frames with). let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!( - ours.len(), - sources.len(), - "our decoder's display-order count" - ); + assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); + assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert_eq!(got.len(), b.len(), "frame {i}: luma size"); + assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( - "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], @@ -1439,592 +2381,174 @@ ); } } - // The reordering itself is unchanged by the second leaf slot. - let shown = packets - .iter() - .filter(|p| p.level == Level::ShowExisting) - .count(); - let arfs = packets.iter().filter(|p| p.level == Level::Arf).count(); - assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); - } - - /// A picture whose content is a static gradient plus a per-picture - /// pseudo-random +-2 of noise: motion search matches the neighbours - /// almost exactly, so the ARF temporal filter's weights are near 1 and - /// the filter actually changes the source (a moving test card gives every - /// neighbour a large MSE, weight ~0, and the filter is a no-op that would - /// make the future-window witness below pass blind). - fn noisy_card(width: usize, height: usize, t: usize) -> Picture { - let mut picture = Picture::grey(width, height); - let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15); - for y in 0..height { - for x in 0..width { - seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); - let noise = ((seed >> 33) % 5) as i32 - 2; - let base = 40 + (x + y) as i32 / 2; - picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16; - } - } - for i in 0..(width / 2) * (height / 2) { - picture.u[i] = 110; - picture.v[i] = 140; - } - picture } - - /// lane-lookahead's correctness witness. One group of lookahead - /// (`Av1Encoder::drain_pending` hands the closed group to `ready` and - /// codes the group before it) must not change WHAT is coded: - /// - /// * with the future half of the filter window empty AND the top ARF's - /// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream - /// is byte for byte the one the encoder coded without a lookahead, at - /// every run length -- 1 picture (no hidden frame at all), 7 (a short - /// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 -- - /// and at a GOP short enough (8) that key frames drain the buffer - /// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so - /// the identity arm pins the lambda window off or this witness tests - /// a different lever; - /// * every run decodes to exactly its picture count through OUR decoder - /// and through ffmpeg, sample-exact between the two, so the flush and - /// the `show_existing_frame` order survive the delay; - /// * and with ONE future neighbour the top ARF's source filter actually - /// reads it -- the stream MOVES (class gate-blind-to-feature: a - /// buffered picture nothing consumes would pass every check above). - #[test] - fn the_lookahead_holds_one_group_and_still_codes_every_picture() { - let _knobs = crate::speed::knob_write(); - // The preset is PROCESS-GLOBAL and another test may have left it - // anywhere: at a high one every block of this fixture codes as skip - // (17 pictures in 493 bytes) and the source filter cannot change a - // byte, which failed the future-half assertion below in the suite and - // passed it standalone (class process-global-knob-races-tests). - let was = crate::speed::speed(); - crate::speed::set_speed(0); - crate::encode::force_screen(Some(false)); - let (width, height) = (128usize, 128usize); - let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec, Vec) { - set_lookahead(Some(on)); - set_arf_tf_future(Some(fut)); - set_tpl_fut(Some(0)); - let config = EncoderConfig { - // FINE (not the 120 the other facade tests use): at a coarse - // quantizer this fixture's ARF codes almost pure skip (17 - // pictures in 493 bytes) and a filtered source quantizes back - // to the same bytes, which made the future-half assertion - // below depend on where the suite's other tests had left the - // process-global preset. At q=60 the anchor carries real - // coefficients and the filter must move them. - base_q_idx: 60, - width, - height, - gop, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); - let sources: Vec = (0..n).map(|t| noisy_card(width, height, t)).collect(); - let packets = encode_all(&mut enc, &sources); - // The content gate is process-global and so is the preset: if - // either has been flipped under this test the pyramid is gone and - // there is no ARF to filter, which is a different failure from - // "the future neighbour changed nothing" (the suite reported the - // second when it meant the first). - assert!( - enc.pyramid().is_some(), - "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})", - crate::speed::speed(), - ); - (concat(&packets), packets) - }; - for gop in [32usize, 8] { - for n in [1usize, 7, 8, 9, 17] { - let (flat, flat_packets) = run(n, gop, false, 0); - let (held, packets) = run(n, gop, true, 0); - assert_eq!( - flat.len(), - held.len(), - "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH" - ); - assert!( - flat == held, - "{n} pictures at gop {gop}: the stream is not byte-identical" - ); - assert_eq!( - packets - .iter() - .map(|p| (p.order, p.key, p.level)) - .collect::>(), - flat_packets - .iter() - .map(|p| (p.order, p.key, p.level)) - .collect::>(), - "{n} pictures at gop {gop}: coding order/levels moved" - ); - let ours = crate::stream::decode_stream(&held).expect("our decoder"); - assert_eq!( - ours.len(), - n, - "{n} pictures at gop {gop}: our decoder's count" - ); - let theirs = ffmpeg_decode_luma(&held, width, height); - assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert!( - got == *b, - "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg" - ); - } - } - } - // The future half REACHES the filter, and what it produces still - // decodes exactly. - let (base, _) = run(17, 32, true, 0); - let (symmetric, _) = run(17, 32, true, 1); - set_lookahead(None); - set_arf_tf_future(None); - set_tpl_fut(None); - assert!( - base != symmetric, - "one display-future neighbour left the top ARF's filter unchanged \ - ({} B vs {} B, preset {})", - base.len(), - symmetric.len(), - crate::speed::speed() + let base = sizes[0].1 as f64; + for (layout, bytes) in &sizes { + eprintln!( + "{layout}: {bytes} bytes ({:+.2}% vs one tile)", + (*bytes as f64 / base - 1.0) * 100.0 ); - let ours = crate::stream::decode_stream(&symmetric).expect("our decoder"); - assert_eq!(ours.len(), 17, "the symmetric arm's display-order count"); - { - let theirs = ffmpeg_decode_luma(&symmetric, width, height); - assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert!( - got == *b, - "symmetric arm, display frame {i}: ours differs from ffmpeg" - ); - } - } - crate::speed::set_speed(was); - } - - /// lane-tplfut's correctness witness, the sibling of - /// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with - /// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next - /// group (`speed::TPL_FUT`), every picture is still coded, the streams - /// decode exactly through our decoder and ffmpeg, and the stream MOVES - /// against the knob off wherever a next group exists (class - /// gate-blind-to-feature). Coded at q=60, not 120: at a coarse - /// quantizer this fixture's ARF is almost pure skip and a different - /// lambda map re-quantises to identical bytes. - #[test] - fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() { - let _knobs = crate::speed::knob_write(); - let was = crate::speed::speed(); - crate::speed::set_speed(0); - crate::encode::force_screen(Some(false)); - let (width, height) = (128usize, 128usize); - let run = |n: usize, gop: usize, fut: usize| -> (Vec, Vec) { - set_lookahead(Some(true)); - set_arf_tf_future(Some(0)); - set_tpl_fut(Some(fut)); - let config = EncoderConfig { - base_q_idx: 60, - width, - height, - gop, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); - let sources: Vec = (0..n).map(|t| noisy_card(width, height, t)).collect(); - let packets = encode_all(&mut enc, &sources); - assert!( - enc.pyramid().is_some(), - "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})", - crate::speed::speed(), - ); - (concat(&packets), packets) - }; - for gop in [32usize, 8] { - for n in [1usize, 7, 8, 9, 17] { - let (off, off_packets) = run(n, gop, 0); - for mode in [1usize, 2, 3] { - let (on, packets) = run(n, gop, mode); - assert_eq!( - packets - .iter() - .map(|p| (p.order, p.key, p.level)) - .collect::>(), - off_packets - .iter() - .map(|p| (p.order, p.key, p.level)) - .collect::>(), - "{n} pictures at gop {gop} mode {mode}: coding order/levels moved" - ); - let ours = crate::stream::decode_stream(&on).expect("our decoder"); - assert_eq!( - ours.len(), - n, - "{n} pictures at gop {gop} mode {mode}: our count" - ); - let theirs = ffmpeg_decode_luma(&on, width, height); - assert_eq!( - theirs.len(), - n, - "{n} pictures at gop {gop} mode {mode}: ffmpeg count" - ); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert!( - got == *b, - "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg" - ); - } + } +} + +/// lane-deltaq's three-way witness: a clip with a real gradient of tpl +/// factors -- a moving detail region over a flat background, so the +/// superblocks the NEXT picture predicts from are worth more than the +/// ones it does not -- codes at least two distinct per-superblock +/// quantizer levels (the fire count, class `gate-blind-to-feature`), and +/// both decoders reconstruct every frame sample-exact from the +/// `delta_qindex` syntax that carries them. +#[test] +fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() { + // `knob_write`, not `knob_read`: the override below is + // process-global and every other test's bytes move under it. + let _knobs = crate::speed::knob_write(); + crate::encode::set_deltaq_res(Some(2)); + let (width, height) = (640usize, 384usize); + // The gate's own moving test card, with a 128x128 patch of fine + // detail travelling right by 32 samples a frame laid over it: the + // patch is what the tpl pass finds worth propagating and the card + // around it is not, so the map -- and with it the quantizer grid -- + // is a gradient and not one flat number. + let sources: Vec = (0..4) + .map(|t| { + let mut p = test_card(width, height, t * 3); + let x0 = 32 + t * 32; + for y in 128..256 { + for x in x0..x0 + 128 { + p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 }; } - let _ = &off; - } - } - // The future window REACHES the lambda map: 17 pictures at gop 32 is - // three groups, so the first two top ARFs each have a next group - // buffered and their windows really are display-future. - let (off, _) = run(17, 32, 0); - // Mode 2 is NOT in this list: at its default split it keeps the three - // NEAREST past neighbours, and those dominate the propagation -- on - // this 128x128 fixture the map moves too little to flip an RD - // decision and the stream comes back byte-identical to mode 0. Not a - // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past - // neighbour, six future) does move the stream, and the gate below - // measures mode 2 on real content. - for mode in [1usize, 3] { - let (on, _) = run(17, 32, mode); - assert!( - off != on, - "mode {mode} left the top ARF's temporal lambda map unchanged \ - ({} B vs {} B, preset {})", - off.len(), - on.len(), - crate::speed::speed() - ); - } - set_lookahead(None); - set_arf_tf_future(None); - set_tpl_fut(None); - crate::speed::set_speed(was); - } - - /// lane-arfmode: the top ARF's leaf offer set. Three guards in one - /// witness, over 17 pictures at gop 32 (three groups, so several top - /// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the - /// anchor carries real coefficients, so a cut that moves only the - /// hidden frame's internal decisions cannot hide behind "everything - /// quantized to the same bytes": - /// - /// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the - /// shipped table is 0 and the lever is bit-exact when off; - /// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really - /// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter - /// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM; - /// 3. the coding order and levels never change, and every armed stream - /// decodes sample-exact through `decode_stream` AND ffmpeg. - #[test] - fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let was = crate::speed::speed(); - crate::speed::set_speed(0); - crate::encode::force_screen(Some(false)); - let (width, height) = (128usize, 128usize); - let run = |mode: Option| -> (Vec, Vec) { - crate::encode::set_arfmode(mode); - let _ = crate::encode::take_arfmode_hits(); - let config = EncoderConfig { - base_q_idx: 60, - width, - height, - gop: 32, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); - // Groups at three luma LEVELS (the base ramp 40/110/180): the - // middle group's top ARF sits halfway between the two dark/light - // anchors its slots hold, which is exactly where neither - // single-reference prediction nor intra wins by default -- the - // AVERAGE of two references (compound) and the DC of the new - // level (intra) do. Without this the synthetic cards' noise - // quantizes to skip and no arm can move anything (measured: - // 516 intra trials skipped, zero won, stream identical). - let sources: Vec = (0..17) - .map(|t| { - let mut p = noisy_card(width, height, t); - let shift = 70i32 * (t / 8) as i32; - for v in p.y.iter_mut() { - *v = (i32::from(*v) + shift).clamp(0, 255) as u16; - } - p - }) - .collect(); - let packets = encode_all(&mut enc, &sources); - (concat(&packets), packets) - }; - let (off, off_packets) = run(None); - let (explicit_off, _) = run(Some(0)); - assert_eq!( - off, explicit_off, - "mode 0 is not bit-exact with the default" - ); - for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] { - let (on, packets) = run(Some(mode)); - let hits = crate::encode::take_arfmode_hits(); - assert_eq!( - packets - .iter() - .map(|p| (p.order, p.key, p.level)) - .collect::>(), - off_packets - .iter() - .map(|p| (p.order, p.key, p.level)) - .collect::>(), - "mode {mode}: coding order/levels moved" - ); - assert!( - hits[arm] > 0, - "mode {mode}: its counter never fired ({hits:?}) -- the lever is \ - gate-blind on this fixture", - ); - assert_ne!( - off, on, - "mode {mode} left the stream byte-identical despite {} firing hits", - hits[arm], - ); - eprintln!( - "mode {mode}: {} -> {} B, hits {hits:?}", - off.len(), - on.len() - ); - let ours = crate::stream::decode_stream(&on).expect("our decoder"); - assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count"); - let theirs = ffmpeg_decode_luma(&on, width, height); - assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert!( - got == *b, - "mode {mode}, frame {i}: ours differs from ffmpeg" - ); } - } - crate::encode::set_arfmode(None); - crate::speed::set_speed(was); - } - - fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { - let (width, height) = (128usize, 128usize); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 32, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - // The content gate ([`Av1Encoder::encode_frames`]) would drop a - // screen-content stream to the flat path, and a synthetic test card - // is exactly the few-colour picture the detector fires on: this gate - // is about the reordering, so it asks for camera content explicitly. - crate::encode::force_screen(Some(false)); - let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); - let sources: Vec = (0..9).map(|t| test_card(width, height, t * 3)).collect(); - let _ = crate::encode::take_ref_frame_hits(); - let mut packets = Vec::new(); - for picture in &sources { - packets.extend(enc.encode_frames(picture).unwrap()); - } - packets.extend(enc.flush().unwrap()); - - // Shape: every source picture is coded exactly once, and each closed - // group adds one `show_existing_frame` packet. - let coded: Vec = packets - .iter() - .filter(|p| p.level != Level::ShowExisting) - .map(|p| p.order) - .collect(); - let mut sorted = coded.clone(); - sorted.sort_unstable(); - assert_eq!( - sorted, - (0..9).collect::>(), - "one packet per picture" - ); - assert_ne!(coded, sorted, "the pyramid never reordered anything"); - let shown = packets - .iter() - .filter(|p| p.level == Level::ShowExisting) - .count(); - assert_eq!(shown, hidden, "one show_existing_frame per hidden frame"); - for (i, p) in packets.iter().enumerate() { - assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); - } - let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); - eprintln!( - "pyramid levels: key {} arf {} leaf {} show_existing {}", - hist(Level::Key), - hist(Level::Arf), - hist(Level::Leaf), - hist(Level::ShowExisting), - ); - assert_eq!(hist(Level::Arf), hidden, "hidden frames"); - let refs = crate::encode::take_ref_frame_hits(); - eprintln!( - "blocks per reference: LAST {} GOLDEN {} ALTREF {}", - refs[crate::mvstack::LAST_FRAME as usize], - refs[crate::mvstack::GOLDEN_FRAME as usize], - refs[crate::mvstack::ALTREF_FRAME as usize], - ); - // [[gate-blind-to-feature]]: the whole point of the hidden frame is - // that the leaves predict BACKWARD off it, which is also the only - // thing that exercises `ref_frame_sign_bias` in the MV stack. A green - // round trip in which `ALTREF_FRAME` never won a block would prove - // only that a hidden frame can be written and re-output. - assert!( - refs[crate::mvstack::ALTREF_FRAME as usize] > 0, - "no block predicted off the hidden ALTREF" - ); - - let stream = concat(&packets); - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!( - ours.len(), - sources.len(), - "our decoder's display-order count" - ); + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + { let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert_eq!(got.len(), b.len(), "frame {i}: luma size"); if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( - "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], b[at], ); } + assert_eq!( + got.len(), + b.len(), + "frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + b.len() + ); } } - - // Every tile layout this encoder can write decodes SAMPLE-EXACT - // through both decoders -- ours and ffmpeg's -- and the frames really - // carry the tiles the header claims (the OBU parser locates one payload - // per tile, so a stream that quietly stayed single-tile fails here - // rather than passing on a green round trip). - // - // The bytes are what the gate is on: an encoder that clipped its - // neighbour availability wrong writes a stream whose two decoders agree - // with each other and disagree with nothing -- so the ffmpeg half is - // the one that catches a tile boundary the writer respected and the - // spec does not, and the parser half catches the reverse. - - /// A STATIC clip: every inter frame predicts perfectly from the last, so - /// the search takes the 64x64 root ([`crate::encode::B64_ROOT`]) instead - /// of coding four 32x32 quadrants, and the stream both decoders - /// reconstruct is still sample-exact against the encoder's own - /// reconstruction. The counter is the point (class - /// `gate-blind-to-feature`): without it a green three-way compare says - /// nothing about whether a single 64x64 block was ever written. - /// lane-sb128 step 1: the same static clip under a 128x128 SUPERBLOCK. - /// Every partition decision below the root is the one the 64-superblock - /// encoder makes -- the root itself is always `PARTITION_SPLIT` into the - /// four 64x64 superblocks -- so the only thing this proves is the - /// structural syntax: the root's own partition symbol, its loop - /// restoration read once over the 128 span at the 128 unit size, and - /// libaom's TL/TR/BL/BR visit order. 256x128 is 2x1 128x128 superblocks - /// per frame over three frames, so the root fires 6 times. - /// - /// `#[ignore]`: [`crate::encode::force_sb128`] moves a process-global - /// (the superblock size is a sequence field), so this gate runs alone: - /// - /// Runs only inside `superblock_size_global_suite`. - pub(crate) fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - crate::encode::force_sb128(true); - let (width, height) = (256usize, 128usize); - let still = test_card(width, height, 0); - let sources: Vec = (0..3).map(|_| still.clone()).collect(); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - let _ = crate::tile::take_sb128_root_hits(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let roots = crate::tile::take_sb128_root_hits(); - assert!( - roots >= 4, - "a 128x128-superblock clip coded {roots} superblock roots, wanted at least 4" - ); - eprintln!("128x128 superblock roots: {roots}"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + crate::encode::set_deltaq_res(None); +} + +/// lane-txset's witness: a clip of hard directional edges makes the intra +/// luma search take EVERY type of the five-type reduced set +/// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`, +/// `IDTX`) at least once -- the fire count, class `gate-blind-to-feature` +/// -- and both decoders reconstruct every frame sample-exact from the +/// `tx_type` symbols that name them. Before the lane the writer coded +/// `DCT_DCT` for every luma transform unit ever written, so this is also +/// the statement that the other four are REACHABLE at all. +#[test] +fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() { + // `knob_write`: the screen override below is process-global, and the + // type search is SCREEN-ONLY (`encode::tx_type_candidates`). + let _knobs = crate::speed::knob_write(); + crate::encode::force_screen(Some(true)); + let (width, height) = (320usize, 192usize); + // Sharp horizontal and vertical steps: a vertical edge is what an + // `ADST` column pass beats a `DCT` one on, a horizontal edge the + // mirror, and the flat/ramp areas between them are where `IDTX` wins. + let sources: Vec = (0..2) + .map(|t| { + let mut p = test_card(width, height, t * 3); + for y in 0..height { + for x in 0..width { + let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) { + (0, 0) => 16u16, + (1, 0) => 235, + (0, 1) => (x % 64 * 3) as u16, + _ => (y % 64 * 3) as u16, + }; + p.y[y * width + x] = v; + } + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 2, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::encode::take_tx_type_hits(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let hits = crate::encode::take_tx_type_hits(); + // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above + // the presets that carry it only `DCT_DCT` is offered, and the + // exactness half below is what still runs there. The FULL five-type + // fire count is preset 0's to make: a faster preset prunes modes and + // partitions before a type is ever priced on them, so `ADST_ADST` and + // `IDTX` stop winning on this clip at preset 6 (measured: hits + // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever + // still has to reach SOME non-`DCT_DCT` type -- that is the + // "reachable at all" statement, class `gate-blind-to-feature`. + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) { + let non_dct: usize = + hits.iter().sum::() - hits[crate::transform::TxType::DctDct as usize]; assert!( - crate::decode::part128_split_hits() >= 4, - "our decoder read no 128x128 superblock root" + non_dct > 0, + "every luma transform unit took DCT_DCT: {hits:?}" ); - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert_eq!(&got, b, "frame {i}: ffmpeg and our decoder disagree"); - } } - - #[test] - fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (256usize, 128usize); - let still = test_card(width, height, 0); - let sources: Vec = (0..3).map(|_| still.clone()).collect(); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - let _ = crate::encode::take_b64_root_hits(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { + for (name, ty) in [ + ("DCT_DCT", crate::transform::TxType::DctDct), + ("ADST_ADST", crate::transform::TxType::AdstAdst), + ("ADST_DCT", crate::transform::TxType::AdstDct), + ("DCT_ADST", crate::transform::TxType::DctAdst), + ("IDTX", crate::transform::TxType::Idtx), + ] { + assert!( + hits[ty as usize] > 0, + "no luma transform unit took {name}: {hits:?}" + ); } - let roots = crate::encode::take_b64_root_hits(); - // 8 superblocks per frame, two inter frames. - assert!( - roots > 0, - "a static clip coded no 64x64 root at all (of 16 inter superblocks)" - ); - eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + { let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { @@ -2047,56 +2571,73 @@ ); } } - - /// The same clip with a DC step between frames (lane-tx64): the 64x64 - /// root still predicts the whole superblock from the last frame, but the - /// prediction is uniformly off, so the root's NON-skip arm -- one - /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below - /// its skip arm and a 64x64 residual is really written. The counter is - /// the gate (class `gate-blind-to-feature`; the static clip above cannot - /// reach this arm at all because its prediction is exact), and both - /// decoders have to reconstruct those coefficients sample-exact -- a - /// writer that names the wrong coefficient set or the wrong `txfm_split` - /// desyncs the whole tile here. - #[test] - fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (256usize, 128usize); - let still = test_card(width, height, 0); - let sources: Vec = (0..3) - .map(|t| { - let mut p = still.clone(); - let step = (t * 6) as u16; - for v in &mut p.y { - *v = (*v + step).min(255); + crate::encode::force_screen(None); + eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len()); +} + +/// lane-txset2's witness: an INTER frame's luma transform units take BOTH +/// types of the two-type inter set the writer already codes a symbol for +/// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire +/// count, class `gate-blind-to-feature` -- and both decoders reconstruct +/// every frame sample-exact from the `tx_type` symbols that name them. +/// Before this lane every inter luma unit was coded `DCT_DCT`. +#[test] +fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() { + // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so + // this turns it on process-globally under the same exclusive lock the + // presets take. + let _knobs = crate::speed::knob_write(); + crate::encode::set_inter_tx_search(Some(true)); + let (width, height) = (320usize, 192usize); + // Sharp steps that MOVE: the motion-compensated residual along a + // moving edge is exactly where the identity transform beats a DCT, + // and the flat plateaus between them predict to nothing at all. + let sources: Vec = (0..4) + .map(|t| { + let mut p = test_card(width, height, t * 3); + for y in 0..height { + for x in 0..width { + let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { + (0, 0) => 16u16, + (1, 0) => 235, + (0, 1) => ((x + t) % 64 * 3) as u16, + _ => ((y + t) % 64 * 3) as u16, + }; + p.y[y * width + x] = v; } - p - }) - .collect(); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - let _ = crate::encode::take_b64_residual_hits(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let residuals = crate::encode::take_b64_residual_hits(); + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::encode::take_inter_tx_type_hits(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let hits = crate::encode::take_inter_tx_type_hits(); + crate::encode::set_inter_tx_search(None); + for (name, ty) in [ + ("DCT_DCT", crate::transform::TxType::DctDct), + ("IDTX", crate::transform::TxType::Idtx), + ] { assert!( - residuals > 0, - "a DC-stepped clip coded no 64x64 root with a residual at all" + hits[ty as usize] > 0, + "no inter luma transform unit was CODED {name}: {hits:?}" ); - eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + { let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { @@ -2119,1582 +2660,513 @@ ); } } - - /// A frame whose size is NOT a multiple of a superblock (lane-b64b): - /// 232x168 leaves the last superblock column and row cut by the true - /// frame edge, with more than half of each inside -- which is exactly - /// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films - /// are superblock-aligned, so nothing but a synthetic size reaches this - /// path at all (class `gate-blind-to-feature`), and the user's own - /// exports are arbitrary sizes. - #[test] - fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (232usize, 168usize); - let still = test_card(width, height, 0); - let sources: Vec = (0..3).map(|_| still.clone()).collect(); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, + eprintln!( + "inter tx_type witness: hits {hits:?}, {} bytes", + stream.len() + ); +} + +/// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER +/// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra +/// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below -- +/// and both decoders reconstruct every frame sample-exact from them. The +/// statement is that the types only those alphabets can NAME (`V_DCT`, +/// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are +/// reachable at all, and that the header bit, the writer's set map and +/// the search's pricer agree on which alphabet a symbol was coded into +/// (class `wrong-alphabet-same-value`: a disagreement here changes no +/// symbol VALUE and desyncs the arithmetic coder anyway). +#[test] +#[ignore = "sets process-global search levers: run it alone"] +fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() { + // Every lever below is process-global: the same exclusive lock the + // presets take. + let _knobs = crate::speed::knob_write(); + crate::encode::set_intra_tx_search(Some(true)); + crate::encode::set_inter_tx_search(Some(true)); + crate::encode::set_wide_tx_set(Some(true)); + let (width, height) = (320usize, 192usize); + // The same moving hard-edge card the two narrow-set witnesses use: + // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the + // ramps are `ADST`'s and the moving plateaus `IDTX`'s. + let sources: Vec = (0..4) + .map(|t| { + let mut p = test_card(width, height, t * 3); + for y in 0..height { + for x in 0..width { + let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { + (0, 0) => 16u16, + (1, 0) => 235, + (0, 1) => ((x + t) % 64 * 3) as u16, + _ => ((y + t) % 64 * 3) as u16, + }; + p.y[y * width + x] = v; + } + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::encode::take_tx_type_hits(); + let _ = crate::encode::take_inter_tx_type_hits(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let (intra, inter) = ( + crate::encode::take_tx_type_hits(), + crate::encode::take_inter_tx_type_hits(), + ); + crate::encode::set_wide_tx_set(None); + crate::encode::set_inter_tx_search(None); + crate::encode::set_intra_tx_search(None); + eprintln!( + "wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes", + stream.len() + ); + // The fire count is preset 0's, for the reason the five-type witness + // spells out: a faster preset prunes the modes and partitions a type + // wins on before it is ever priced (class `gate-blind-to-feature`). + if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { + use crate::transform::TxType; + let wide_only = |hits: &[usize; 16]| -> usize { + hits[TxType::VDct as usize] + hits[TxType::HDct as usize] }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - let _ = crate::encode::take_b64_edge_hits(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let edges = crate::encode::take_b64_edge_hits(); assert!( - edges > 0, - "no 64x64 root was taken at a superblock the frame edge cuts" + wide_only(&intra) > 0, + "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}" ); - eprintln!("edge 64x64 roots: {edges}"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + // The INTER units of this same frame are coded into the + // twelve/sixteen-symbol alphabets too (the header bit widens + // every luma set at once), but their SEARCH still offers the + // two-type list -- see `encode::inter_luma_set`'s note on the + // reference-slot refusal the wider inter candidates trip. So the + // statement here is that those units still decode sample-exact + // out of the wider alphabet, which the two decoders below make. + assert!( + inter.iter().sum::() > 0, + "the clip coded no inter luma transform unit at all: {inter:?}" + ); + } + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + { let theirs = ffmpeg_decode_luma(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { panic!( "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", at % width, at / width, got[at], - theirs_i[at], + b[at], ); } assert_eq!( got.len(), - theirs_i.len(), + b.len(), "frame {i}: luma is {} samples, ffmpeg's is {}", got.len(), - theirs_i.len() + b.len() ); } } - - /// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three - /// whole superblock columns and 1.6875 superblock rows, so the bottom - /// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b - /// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8) - /// leaves it did not. Every one of them is now scored over its inside - /// part alone, and a distortion change that moved a partition or a - /// transform decision the writer did not follow would desync the tile, so - /// both decoders reconstruct it sample-exact. - #[test] - fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (384usize, 216usize); - let sources: Vec = (0..3).map(|i| test_card(width, height, i)).collect(); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - let theirs = ffmpeg_decode_luma(&stream, width, height); +} +/// lane-intertx's witness: on a clip the screen detector calls +/// NON-screen, the inter luma search offers the wider +/// `reduced_tx_set = 0` alphabets and CODES a 1-D `V_DCT`/`H_DCT` unit +/// (a `coded > 0` guard on the committed-winners census, class +/// `gate-blind-to-feature`), the block's chroma transforms inherit that +/// type reduced to the chroma size's set against the frame's own honest +/// header bit, and BOTH decoders reconstruct every frame sample-exact on +/// ALL THREE planes -- chroma is the plane the inheritance desync +/// corrupts, so luma-only comparisons cannot see it. +#[test] +#[ignore = "sets process-global search levers: run it alone"] +fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() { + let _knobs = crate::speed::knob_write(); + crate::encode::set_intra_tx_search(Some(true)); + crate::encode::set_inter_tx_search(Some(true)); + crate::encode::set_wide_tx_set(Some(true)); + crate::encode::force_screen(Some(false)); + let (width, height) = (320usize, 192usize); + // The wide witness's moving card: vertical steps (where a 1-D + // `V_DCT`/`H_DCT` beats the 2-D DCT on the motion-compensated + // residual), ramps (`ADST`) and moving plateaus (`IDTX`), translated + // a few samples per frame so the inter search sees real motion. + let sources: Vec = (0..4) + .map(|t| { + let mut p = test_card(width, height, t * 3); + for y in 0..height { + for x in 0..width { + let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { + (0, 0) => 16u16, + (1, 0) => 235, + (0, 1) => ((x + t) % 64 * 3) as u16, + _ => ((y + t) % 64 * 3) as u16, + }; + p.y[y * width + x] = v; + } + } + p + }) + .collect(); + let config = EncoderConfig { + width, + height, + base_q_idx: 90, + gop: 4, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let _ = crate::encode::take_inter_tx_type_hits(); + let mut stream = Vec::new(); + for packet in encode_all(&mut enc, &sources) { + stream.extend_from_slice(&packet.data); + } + let hits = crate::encode::take_inter_tx_type_hits(); + crate::encode::force_screen(None); + crate::encode::set_wide_tx_set(None); + crate::encode::set_inter_tx_search(None); + crate::encode::set_intra_tx_search(None); + use crate::transform::TxType; + eprintln!( + "inter wide-set witness: inter hits {hits:?}, {} bytes", + stream.len() + ); + assert!( + hits[TxType::Idtx as usize] > 0, + "no inter luma unit was CODED IDTX: {hits:?}" + ); + assert!( + hits[TxType::VDct as usize] + hits[TxType::HDct as usize] > 0, + "no inter luma unit was CODED a 1-D type -- the wider search \ + never fired on non-screen content (class gate-blind-to-feature): {hits:?}" + ); + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's frames"); + { + let theirs = ffmpeg_decode_planes(&stream, width, height); assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - theirs_i[at], - ); + let (cw, ch) = (width / 2, height / 2); + for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() { + for (name, got16, want, w) in [ + ("y", &a.y, y, width), + ("u", &a.u, u, cw), + ("v", &a.v, v, ch), + ] { + let got: Vec = got16.iter().map(|&s| s as u8).collect(); + assert_eq!(got.len(), want.len(), "frame {i} {name} plane size"); + if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) { + panic!( + "frame {i}: {name} differs first at ({}, {}): ours {} vs ffmpeg {}", + at % w, + at / w, + got[at], + want[at], + ); + } } - assert_eq!( - got.len(), - theirs_i.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - theirs_i.len() - ); } } +} - /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every - /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is - /// off by exactly the detail a TX_64X64 throws away (it codes only the - /// top-left 32x32 corner of its coefficient space) and the root's var-tx - /// arm splits its luma into four TX_32X32 units instead. The counter is - /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the - /// reader does not expect desyncs the whole tile, so both decoders have - /// to reconstruct it sample-exact. - #[test] - fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (256usize, 128usize); - let still = test_card(width, height, 0); - let sources: Vec = (0..4) - .map(|t| { - let mut p = still.clone(); - for (i, v) in p.y.iter_mut().enumerate() { - let checker = ((i % width) / 4 + (i / width) / 4) % 2; - let bump = (t * 5 * (checker + 1)) as u16; - *v = (*v + bump).min(255); - } - p - }) - .collect(); +/// The tiles of a frame are entropy-independent, so the bytes must not +/// depend on how many workers wrote them: the same stream at one tile +/// thread and at four, per layout. +#[test] +fn tile_bytes_do_not_depend_on_the_thread_count() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (320usize, 192usize); + let sources: Vec = (0..3).map(|t| test_card(width, height, t * 3)).collect(); + let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { + crate::par::set_tile_threads(threads); let config = EncoderConfig { width, height, - base_q_idx: 90, - gop: 8, + base_q_idx: 120, + gop: 3, colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); - let _ = crate::encode::take_b64_var_tx_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } - let split = crate::encode::take_b64_var_tx_hits(); - assert!(split > 0, "no 64x64 root split its luma transform at all"); - eprintln!("64x64 roots with a SPLIT luma transform: {split}"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - theirs_i[at], - ); - } - assert_eq!( - got.len(), - theirs_i.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - theirs_i.len() - ); - } + stream + }; + for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { + let one = coded(1, cols_log2, rows_log2); + let four = coded(4, cols_log2, rows_log2); + assert_eq!( + one, + four, + "{}x{} tiles: {} bytes at one thread, {} at four", + 1 << cols_log2, + 1 << rows_log2, + one.len(), + four.len() + ); } - - /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two - /// stills, so on a leaf frame the average of its past (`LAST`) and future - /// (`ALTREF`) references IS the source and neither reference alone is -- - /// exactly the content a COMPOUND 64x64 root pays on. The counter is the - /// gate (class `gate-blind-to-feature`): without it a green three-way - /// compare says nothing about whether one compound root was written, and - /// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no - /// `motion_mode` symbol) desyncs the whole tile if it is wrong. - #[test] - fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (256usize, 128usize); - let (a, b) = (test_card(width, height, 0), test_card(width, height, 24)); - let sources: Vec = (0..9) - .map(|t| { - let mut p = a.clone(); - let w = t as u32; - for (v, &other) in p.y.iter_mut().zip(&b.y) { - *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16; - } - p - }) - .collect(); + crate::par::set_tile_threads(1); +} + +/// lane-av1fpar: the frame-level FILTER stage is banded across the same +/// workers the tile search uses (`par::override_filter_threads`), so the +/// deblock/CDEF replays, the per-64 SSE and the plane copies all run in +/// pieces. Every piece is a disjoint band of the same integers, so the +/// stream must not move -- at a size that crops and is several superblock +/// rows tall, which is what makes the bands non-trivial. +#[test] +fn filter_stage_bytes_do_not_depend_on_the_thread_count() { + let _knobs = crate::speed::knob_write(); + let (width, height) = (384usize, 288usize); + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + let coded = |threads: usize| { + crate::par::set_tile_threads(threads); let config = EncoderConfig { width, height, base_q_idx: 120, - gop: 9, + gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); - let _ = crate::encode::take_b64_compound_hits(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } - let compound = crate::encode::take_b64_compound_hits(); - assert!( - compound > 0, - "a crossfade clip coded no COMPOUND 64x64 root at all" + stream + }; + // One tile, so only the filter stage can differ between these. + let one = coded(1); + for threads in [2usize, 4, 8] { + assert_eq!( + one, + coded(threads), + "the filter stage moved at {threads} threads" ); - eprintln!("compound 64x64 roots on a crossfade clip: {compound}"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = ours_i.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - theirs_i[at], - ); - } - assert_eq!( - got.len(), - theirs_i.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - theirs_i.len() - ); - } } - - #[test] - fn every_tile_layout_decodes_sample_exact_through_both_decoders() { - let _knobs = crate::speed::knob_read(); - let (width, height) = (640usize, 384usize); + crate::par::set_tile_threads(1); +} + +/// lane-av1fpar: the filter search scores its ~30 candidates by replaying +/// the loop filters on one captured reconstruction instead of decoding +/// the coded tile again per candidate. The replay must be that decode, +/// byte for byte -- including at a size that CROPS (1080 and 1608 both +/// pad to a superblock row, i.e. every export size the editor uses), +/// which is the arm this lane opened. +#[test] +fn filter_replay_codes_the_same_stream_as_a_full_decode() { + let _knobs = crate::speed::knob_read(); + let run = |width: usize, height: usize, off: bool| { let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); - let mut sizes = Vec::new(); - for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 4, - colour: Colour::Bt709Limited, - tile_cols_log2: cols_log2, - tile_rows_log2: rows_log2, - }; - let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); - // lane-b128m: the SPEC's uniform spacing derives the tile count - // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`), - // so a frame with fewer superblock columns than the requested - // count codes fewer tiles -- which is what a 128-superblock - // sequence does here. The grid the encoder itself computes is the - // expectation; at 64 superblocks it is `1 << log2` exactly. - let grid = crate::tile::TileLayout::new( - (width as u32).div_ceil(4), - (height as u32).div_ceil(4), - cols_log2, - rows_log2, - ); - let (want_cols, want_rows) = (grid.cols(), grid.rows()); - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - sizes.push((layout.clone(), stream.len())); - - // The frames carry the tiles their headers claim. - let mut parser = ec_av1_syntax::Av1Parser::new(); - let mut frames = 0usize; - let mut offset = 0usize; - while offset < stream.len() { - let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); - let unit: usize = obus.iter().map(|o| o.total_size).sum(); - for obu in &obus { - if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { - assert_eq!( - (parsed.tile_info.cols, parsed.tile_info.rows), - (want_cols, want_rows), - "{layout}: the header's own tile grid" - ); - assert_eq!( - tiles.len(), - (want_cols * want_rows) as usize, - "{layout}: tile payloads located in the tile group" - ); - frames += 1; - } - } - offset += unit; - } - assert_eq!(frames, sources.len(), "{layout}: coded frames"); - - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - b[at], - ); - } - } - } - let base = sizes[0].1 as f64; - for (layout, bytes) in &sizes { - eprintln!( - "{layout}: {bytes} bytes ({:+.2}% vs one tile)", - (*bytes as f64 / base - 1.0) * 100.0 - ); - } - } - - /// lane-deltaq's three-way witness: a clip with a real gradient of tpl - /// factors -- a moving detail region over a flat background, so the - /// superblocks the NEXT picture predicts from are worth more than the - /// ones it does not -- codes at least two distinct per-superblock - /// quantizer levels (the fire count, class `gate-blind-to-feature`), and - /// both decoders reconstruct every frame sample-exact from the - /// `delta_qindex` syntax that carries them. - #[test] - fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() { - // `knob_write`, not `knob_read`: the override below is - // process-global and every other test's bytes move under it. - let _knobs = crate::speed::knob_write(); - crate::encode::set_deltaq_res(Some(2)); - let (width, height) = (640usize, 384usize); - // The gate's own moving test card, with a 128x128 patch of fine - // detail travelling right by 32 samples a frame laid over it: the - // patch is what the tpl pass finds worth propagating and the card - // around it is not, so the map -- and with it the quantizer grid -- - // is a gradient and not one flat number. - let sources: Vec = (0..4) - .map(|t| { - let mut p = test_card(width, height, t * 3); - let x0 = 32 + t * 32; - for y in 128..256 { - for x in x0..x0 + 128 { - p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 }; - } - } - p - }) - .collect(); + crate::decode::set_filter_replay_disabled(off); let config = EncoderConfig { width, height, base_q_idx: 120, - gop: 4, + gop: 2, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; let mut enc = Av1Encoder::new(config).unwrap(); - let _ = crate::encode::take_deltaq_levels(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } - let levels = crate::encode::take_deltaq_levels(); - // The quantizer grid rides the tpl map, and `speed::TPL_DEPTH` cuts - // the lookahead window to one picture at the top presets, so there IS - // no map -- and no delta_q syntax -- there. The exactness half below - // still runs; only the fire count needs a window (lane-tplwin: the - // predicate is the window, not preset 0, since presets 1..6 have one). - if crate::speed::at(&crate::speed::TPL_DEPTH) > 1 { - assert!( - levels >= 2, - "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded" - ); - } - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - { - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - b[at], - ); - } - assert_eq!( - got.len(), - b.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - b.len() - ); - } - } - crate::encode::set_deltaq_res(None); - eprintln!( - "delta_q witness: {levels} quantizer levels, {} bytes", - stream.len() + crate::decode::set_filter_replay_disabled(false); + stream + }; + // 320x160 crops (the coding surface is 320x192, one superblock row + // taller); 320x192 is a whole number of superblocks, the shape the + // replay already covered. + for (width, height) in [(320usize, 160usize), (320, 192)] { + let replayed = run(width, height, false); + let decoded = run(width, height, true); + assert_eq!( + replayed, + decoded, + "{width}x{height}: the filter replay is not the decode it stands in for \ + ({} bytes replayed, {} decoded)", + replayed.len(), + decoded.len(), ); } - - /// lane-txset's witness: a clip of hard directional edges makes the intra - /// luma search take EVERY type of the five-type reduced set - /// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`, - /// `IDTX`) at least once -- the fire count, class `gate-blind-to-feature` - /// -- and both decoders reconstruct every frame sample-exact from the - /// `tx_type` symbols that name them. Before the lane the writer coded - /// `DCT_DCT` for every luma transform unit ever written, so this is also - /// the statement that the other four are REACHABLE at all. - #[test] - fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() { - // `knob_write`: the screen override below is process-global, and the - // type search is SCREEN-ONLY (`encode::tx_type_candidates`). - let _knobs = crate::speed::knob_write(); - crate::encode::force_screen(Some(true)); - let (width, height) = (320usize, 192usize); - // Sharp horizontal and vertical steps: a vertical edge is what an - // `ADST` column pass beats a `DCT` one on, a horizontal edge the - // mirror, and the flat/ramp areas between them are where `IDTX` wins. - let sources: Vec = (0..2) - .map(|t| { - let mut p = test_card(width, height, t * 3); - for y in 0..height { - for x in 0..width { - let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) { - (0, 0) => 16u16, - (1, 0) => 235, - (0, 1) => (x % 64 * 3) as u16, - _ => (y % 64 * 3) as u16, - }; - p.y[y * width + x] = v; - } - } - p - }) - .collect(); +} + +/// lane-av1cap: the filter stage's FINAL replay -- the one that replaced +/// the capture decode -- against that decode. `set_verify_final_replay` +/// makes `encode::pick_and_apply_filters` run both on every frame and +/// assert, per frame, that the spliced picture and the two filter stages +/// the loop-restoration search reads are bit-identical. +#[test] +fn filter_replay_final_matches_the_capture_decode() { + let _knobs = crate::speed::knob_read(); + let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { let config = EncoderConfig { width, height, - base_q_idx: 90, + base_q_idx: 120, gop: 2, colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, + tile_cols_log2: tiles.0, + tile_rows_log2: tiles.1, }; let mut enc = Av1Encoder::new(config).unwrap(); - let _ = crate::encode::take_tx_type_hits(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let hits = crate::encode::take_tx_type_hits(); - // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above - // the presets that carry it only `DCT_DCT` is offered, and the - // exactness half below is what still runs there. The FULL five-type - // fire count is preset 0's to make: a faster preset prunes modes and - // partitions before a type is ever priced on them, so `ADST_ADST` and - // `IDTX` stop winning on this clip at preset 6 (measured: hits - // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever - // still has to reach SOME non-`DCT_DCT` type -- that is the - // "reachable at all" statement, class `gate-blind-to-feature`. - if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) { - let non_dct: usize = - hits.iter().sum::() - hits[crate::transform::TxType::DctDct as usize]; - assert!( - non_dct > 0, - "every luma transform unit took DCT_DCT: {hits:?}" - ); - } - if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { - for (name, ty) in [ - ("DCT_DCT", crate::transform::TxType::DctDct), - ("ADST_ADST", crate::transform::TxType::AdstAdst), - ("ADST_DCT", crate::transform::TxType::AdstDct), - ("DCT_ADST", crate::transform::TxType::DctAdst), - ("IDTX", crate::transform::TxType::Idtx), - ] { - assert!( - hits[ty as usize] > 0, - "no luma transform unit took {name}: {hits:?}" - ); - } - } - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - { - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - b[at], - ); - } - assert_eq!( - got.len(), - b.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - b.len() - ); - } - } - crate::encode::force_screen(None); - eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len()); - } - - /// lane-txset2's witness: an INTER frame's luma transform units take BOTH - /// types of the two-type inter set the writer already codes a symbol for - /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire - /// count, class `gate-blind-to-feature` -- and both decoders reconstruct - /// every frame sample-exact from the `tx_type` symbols that name them. - /// Before this lane every inter luma unit was coded `DCT_DCT`. - #[test] - fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() { - // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so - // this turns it on process-globally under the same exclusive lock the - // presets take. - let _knobs = crate::speed::knob_write(); - crate::encode::set_inter_tx_search(Some(true)); - let (width, height) = (320usize, 192usize); - // Sharp steps that MOVE: the motion-compensated residual along a - // moving edge is exactly where the identity transform beats a DCT, - // and the flat plateaus between them predict to nothing at all. - let sources: Vec = (0..4) - .map(|t| { - let mut p = test_card(width, height, t * 3); - for y in 0..height { - for x in 0..width { - let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { - (0, 0) => 16u16, - (1, 0) => 235, - (0, 1) => ((x + t) % 64 * 3) as u16, - _ => ((y + t) % 64 * 3) as u16, - }; - p.y[y * width + x] = v; - } - } - p - }) - .collect(); + for packet in encode_all(&mut enc, sources) { + assert!(!packet.data.is_empty()); + } + }; + crate::decode::set_verify_final_replay(true); + // 320x160 crops (its coding surface is one superblock row taller); + // 320x192 is a whole number of superblocks. + for (width, height) in [(320usize, 160usize), (320, 192)] { + let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); + run(&sources, width, height, (0, 0)); + } + // Real gate content, where the CDEF preset search actually chooses + // `bits > 0` and the tile is re-coded, one tile and four. + if let Some(sources) = h264_clip_frames(640, 384, 3) { + run(&sources, 640, 384, (0, 0)); + run(&sources, 640, 384, (1, 1)); + } + crate::decode::set_verify_final_replay(false); +} + +/// The same round trip at a real 1920x1080 crop of the gate's own clip +/// -- the size the editor's export actually runs at, where a tile grid +/// is worth having. +/// +/// UN-IGNORED by lane-av1probes: it was `#[ignore]`d only for its wall +/// ("1080p encode: minutes"), and it is the only 1080p arm in the ignored +/// set that actually ASSERTS. Measured 30.6 s in release on the +/// workstation (12 cores) and 64 s on a 4-core server, so it is affordable +/// in the suite. Evidence for the un-ignore: the three tile grids 2x1, +/// 2x2 and 4x2 each decode sample-exact through BOTH our decoder and +/// ffmpeg (84488 / 84208 / 84685 bytes), and the check is a per-frame +/// first-differing-luma-sample comparison, not a length or non-empty +/// smoke. +/// +#[test] +fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { + let _knobs = crate::speed::knob_read(); + let (width, height) = (1920usize, 1080usize); + let Some(sources) = h264_clip_frames(width, height, 3) else { + return; + }; + for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { let config = EncoderConfig { width, height, - base_q_idx: 90, - gop: 4, + base_q_idx: 120, + gop: 3, colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, + tile_cols_log2: cols_log2, + tile_rows_log2: rows_log2, }; + let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); let mut enc = Av1Encoder::new(config).unwrap(); - let _ = crate::encode::take_inter_tx_type_hits(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { stream.extend_from_slice(&packet.data); } - let hits = crate::encode::take_inter_tx_type_hits(); - crate::encode::set_inter_tx_search(None); - for (name, ty) in [ - ("DCT_DCT", crate::transform::TxType::DctDct), - ("IDTX", crate::transform::TxType::Idtx), - ] { - assert!( - hits[ty as usize] > 0, - "no inter luma transform unit was CODED {name}: {hits:?}" - ); - } let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - { - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - b[at], - ); - } - assert_eq!( - got.len(), - b.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - b.len() + assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "1080p {layout} frame {i}: luma differs first at ({}, {})", + at % width, + at / width ); } - } - eprintln!( - "inter tx_type witness: hits {hits:?}, {} bytes", - stream.len() - ); - } - - /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER - /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra - /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below -- - /// and both decoders reconstruct every frame sample-exact from them. The - /// statement is that the types only those alphabets can NAME (`V_DCT`, - /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are - /// reachable at all, and that the header bit, the writer's set map and - /// the search's pricer agree on which alphabet a symbol was coded into - /// (class `wrong-alphabet-same-value`: a disagreement here changes no - /// symbol VALUE and desyncs the arithmetic coder anyway). - #[test] - #[ignore = "sets process-global search levers: run it alone"] - fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() { - // Every lever below is process-global: the same exclusive lock the - // presets take. - let _knobs = crate::speed::knob_write(); - crate::encode::set_intra_tx_search(Some(true)); - crate::encode::set_inter_tx_search(Some(true)); - crate::encode::set_wide_tx_set(Some(true)); - let (width, height) = (320usize, 192usize); - // The same moving hard-edge card the two narrow-set witnesses use: - // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the - // ramps are `ADST`'s and the moving plateaus `IDTX`'s. - let sources: Vec = (0..4) - .map(|t| { - let mut p = test_card(width, height, t * 3); - for y in 0..height { - for x in 0..width { - let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { - (0, 0) => 16u16, - (1, 0) => 235, - (0, 1) => ((x + t) % 64 * 3) as u16, - _ => ((y + t) % 64 * 3) as u16, - }; - p.y[y * width + x] = v; - } - } - p - }) - .collect(); - let config = EncoderConfig { - width, - height, - base_q_idx: 90, - gop: 4, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let _ = crate::encode::take_tx_type_hits(); - let _ = crate::encode::take_inter_tx_type_hits(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let (intra, inter) = ( - crate::encode::take_tx_type_hits(), - crate::encode::take_inter_tx_type_hits(), - ); - crate::encode::set_wide_tx_set(None); - crate::encode::set_inter_tx_search(None); - crate::encode::set_intra_tx_search(None); - eprintln!( - "wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes", - stream.len() - ); - // The fire count is preset 0's, for the reason the five-type witness - // spells out: a faster preset prunes the modes and partitions a type - // wins on before it is ever priced (class `gate-blind-to-feature`). - if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 { - use crate::transform::TxType; - let wide_only = |hits: &[usize; 16]| -> usize { - hits[TxType::VDct as usize] + hits[TxType::HDct as usize] - }; - assert!( - wide_only(&intra) > 0, - "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}" - ); - // The INTER units of this same frame are coded into the - // twelve/sixteen-symbol alphabets too (the header bit widens - // every luma set at once), but their SEARCH still offers the - // two-type list -- see `encode::inter_luma_set`'s note on the - // reference-slot refusal the wider inter candidates trip. So the - // statement here is that those units still decode sample-exact - // out of the wider alphabet, which the two decoders below make. - assert!( - inter.iter().sum::() > 0, - "the clip coded no inter luma transform unit at all: {inter:?}" + assert_eq!( + got.len(), + b.len(), + "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}", + got.len(), + b.len() ); } - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - { - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - b[at], - ); - } - assert_eq!( - got.len(), - b.len(), - "frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - b.len() - ); - } - } - } - /// lane-intertx's witness: on a clip the screen detector calls - /// NON-screen, the inter luma search offers the wider - /// `reduced_tx_set = 0` alphabets and CODES a 1-D `V_DCT`/`H_DCT` unit - /// (a `coded > 0` guard on the committed-winners census, class - /// `gate-blind-to-feature`), the block's chroma transforms inherit that - /// type reduced to the chroma size's set against the frame's own honest - /// header bit, and BOTH decoders reconstruct every frame sample-exact on - /// ALL THREE planes -- chroma is the plane the inheritance desync - /// corrupts, so luma-only comparisons cannot see it. - #[test] - #[ignore = "sets process-global search levers: run it alone"] - fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() { - let _knobs = crate::speed::knob_write(); - crate::encode::set_intra_tx_search(Some(true)); - crate::encode::set_inter_tx_search(Some(true)); - crate::encode::set_wide_tx_set(Some(true)); - crate::encode::force_screen(Some(false)); - let (width, height) = (320usize, 192usize); - // The wide witness's moving card: vertical steps (where a 1-D - // `V_DCT`/`H_DCT` beats the 2-D DCT on the motion-compensated - // residual), ramps (`ADST`) and moving plateaus (`IDTX`), translated - // a few samples per frame so the inter search sees real motion. - let sources: Vec = (0..4) - .map(|t| { - let mut p = test_card(width, height, t * 3); - for y in 0..height { - for x in 0..width { - let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) { - (0, 0) => 16u16, - (1, 0) => 235, - (0, 1) => ((x + t) % 64 * 3) as u16, - _ => ((y + t) % 64 * 3) as u16, - }; - p.y[y * width + x] = v; - } - } - p - }) - .collect(); + eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); + } +} + +/// [`RateTarget::Quality`] is monotone: a higher quality dial never +/// produces a smaller stream or a worse mean PSNR than a lower one, on +/// the same real clip. +#[test] +fn quality_target_is_monotone_in_bytes_and_psnr() { + let _knobs = crate::speed::knob_read(); + let (width, height) = (640, 384); + let Some(pictures) = h264_clip_frames(width, height, 8) else { + return; + }; + let mut prev_bytes = 0usize; + let mut prev_psnr = 0.0f64; + for quality in [20u8, 50, 80] { let config = EncoderConfig { width, height, - base_q_idx: 90, - gop: 4, + base_q_idx: 100, + gop: 8, colour: Colour::Bt709Limited, tile_cols_log2: 0, tile_rows_log2: 0, }; - let mut enc = Av1Encoder::new(config).unwrap(); - let _ = crate::encode::take_inter_tx_type_hits(); + let mut enc = Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { + let mut total_bytes = 0usize; + for packet in encode_all(&mut enc, &pictures) { + total_bytes += packet.data.len(); stream.extend_from_slice(&packet.data); } - let hits = crate::encode::take_inter_tx_type_hits(); - crate::encode::force_screen(None); - crate::encode::set_wide_tx_set(None); - crate::encode::set_inter_tx_search(None); - crate::encode::set_intra_tx_search(None); - use crate::transform::TxType; - eprintln!( - "inter wide-set witness: inter hits {hits:?}, {} bytes", - stream.len() + let decoded = ffmpeg_decode_luma(&stream, width, height); + assert_eq!( + decoded.len(), + pictures.len(), + "quality {quality}: dav1d frame count" ); + let mean_psnr: f64 = decoded + .iter() + .zip(&pictures) + .map(|(d, p)| { + let d16: Vec = d.iter().map(|&v| u16::from(v)).collect(); + psnr(&d16, &p.y) + }) + .sum::() + / decoded.len() as f64; assert!( - hits[TxType::Idtx as usize] > 0, - "no inter luma unit was CODED IDTX: {hits:?}" + total_bytes >= prev_bytes, + "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" ); assert!( - hits[TxType::VDct as usize] + hits[TxType::HDct as usize] > 0, - "no inter luma unit was CODED a 1-D type -- the wider search \ - never fired on non-screen content (class gate-blind-to-feature): {hits:?}" - ); - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "our decoder's frames"); - { - let theirs = ffmpeg_decode_planes(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); - let (cw, ch) = (width / 2, height / 2); - for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() { - for (name, got16, want, w) in [ - ("y", &a.y, y, width), - ("u", &a.u, u, cw), - ("v", &a.v, v, ch), - ] { - let got: Vec = got16.iter().map(|&s| s as u8).collect(); - assert_eq!(got.len(), want.len(), "frame {i} {name} plane size"); - if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) { - panic!( - "frame {i}: {name} differs first at ({}, {}): ours {} vs ffmpeg {}", - at % w, - at / w, - got[at], - want[at], - ); - } - } - } - } - } - - /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct - /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from - /// its neighbour (a preset that changes no byte is a preset that buys no - /// wall: class `gate-blind-to-feature`). Preset 0's bytes are the - /// full-search ones, which is the cheap in-suite statement of the byte - /// pins' rule. - /// - /// Ignored by default because the preset is PROCESS-GLOBAL - /// ([`crate::speed`]): flipping it while the suite's other tests encode - /// in parallel would move their bytes under them. Run it on its own: - /// `cargo test -p ec-av1 --release -- --ignored every_speed_preset`. - #[test] - #[ignore = "sets the process-global speed preset: run it alone"] - fn every_speed_preset_decodes_sample_exact_through_both_decoders() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (640usize, 384usize); - let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); - let mut sizes: Vec<(u8, usize)> = Vec::new(); - for speed in [0u8, 3, 6, 10] { - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 4, - colour: Colour::Bt709Limited, - tile_cols_log2: 1, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::with_speed(config, speed).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!( - ours.len(), - sources.len(), - "speed {speed}: our decoder's frames" - ); - { - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!( - theirs.len(), - sources.len(), - "speed {speed}: ffmpeg's frames" - ); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "speed {speed} frame {i}: luma differs first at ({}, {}): \ - ours {} vs ffmpeg {}", - at % width, - at / width, - got[at], - b[at], - ); - } - assert_eq!( - got.len(), - b.len(), - "speed {speed} frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - b.len() - ); - } - } - eprintln!( - "speed {speed}: {} bytes [{}]", - stream.len(), - crate::speed::levers(speed).join(", ") - ); - sizes.push((speed, stream.len())); - } - crate::speed::set_speed(0); - for w in sizes.windows(2) { - assert_ne!( - w[0].1, w[1].1, - "speed {} and {} coded the same bytes: the preset changed no decision", - w[0].0, w[1].0 - ); - } - } - - /// What tiles and tile threads are worth at the size the editor exports - /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall - /// per cell. Ignored by default (minutes). - #[test] - #[ignore = "wall table, 16 cells x 2 passes at 1080p: 27 min measured; needs a host with >=8 cores"] - fn tile_wall_table_at_1080p() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (1920usize, 1080usize); - let Some(sources) = h264_clip_frames(width, height, 8) else { - return; - }; - let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; - let threadings = [1usize, 2, 4, 8]; - let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); - for pass in 0..2 { - for &(cols_log2, rows_log2) in &layouts { - for &threads in &threadings { - crate::par::set_tile_threads(threads); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: cols_log2, - tile_rows_log2: rows_log2, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let start = std::time::Instant::now(); - let mut bytes = 0usize; - for packet in encode_all(&mut enc, &sources) { - bytes += packet.data.len(); - } - let wall = start.elapsed().as_secs_f64(); - let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); - match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { - Some(row) => row.2 = row.2.min(wall), - None => table.push((name, threads, wall, bytes)), - } - let _ = pass; - } - } - } - crate::par::set_tile_threads(1); - eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); - for (name, threads, wall, bytes) in &table { - eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); - } - } - - /// The tiles of a frame are entropy-independent, so the bytes must not - /// depend on how many workers wrote them: the same stream at one tile - /// thread and at four, per layout. - #[test] - fn tile_bytes_do_not_depend_on_the_thread_count() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (320usize, 192usize); - let sources: Vec = (0..3).map(|t| test_card(width, height, t * 3)).collect(); - let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { - crate::par::set_tile_threads(threads); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 3, - colour: Colour::Bt709Limited, - tile_cols_log2: cols_log2, - tile_rows_log2: rows_log2, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - stream - }; - for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { - let one = coded(1, cols_log2, rows_log2); - let four = coded(4, cols_log2, rows_log2); - assert_eq!( - one, - four, - "{}x{} tiles: {} bytes at one thread, {} at four", - 1 << cols_log2, - 1 << rows_log2, - one.len(), - four.len() - ); - } - crate::par::set_tile_threads(1); - } - - /// What the per-tile search (lane-av1tsearch) is worth in wall and in - /// frames per second at the editor's own export sizes: every tile layout - /// crossed with every tile-thread count, plus librav1e at the matching - /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes - /// over the whole table (A,B,A,B... rather than AA,BB) with the best of - /// the two kept, so a thermal drift cannot order the rows. - /// - /// Measurement, not a pass/fail gate: it asserts only that every cell - /// produced a stream. - #[test] - // MEASURED 1243 s in release on a 12-core workstation. A 4-core server - // cannot finish it at all: the same run TIMED OUT at 2400 s there - // (12 frames x 2 passes x 12 cells), so the 8- and 12-thread rows are - // only meaningful on a host with the cores to run them. Do not schedule - // it on a 4-core fleet box. - #[ignore = "wall measurement: 20 min at 1080p and it TIMES OUT on a 4-core host -- run it on >=8 cores"] - fn tile_search_wall_1080p() { - let _knobs = crate::speed::knob_write(); - tile_search_wall( - 1920, - 1080, - 12, - &[(0, 0), (1, 0), (1, 1), (2, 1)], - &[1, 2, 4, 8], + mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours + "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" ); + prev_bytes = total_bytes; + prev_psnr = mean_psnr; } - - /// The same table at the 4K frame size the editor exports (3840x1608), - /// at the two layouts with enough tiles to fill this box. - #[test] - #[ignore = "wall measurement: 12 min at 4K (732 s measured); run it with --ignored --nocapture"] - fn tile_search_wall_4k() { - let _knobs = crate::speed::knob_write(); - tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); - } - - /// lane-av1fpar: the frame-level FILTER stage is banded across the same - /// workers the tile search uses (`par::override_filter_threads`), so the - /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in - /// pieces. Every piece is a disjoint band of the same integers, so the - /// stream must not move -- at a size that crops and is several superblock - /// rows tall, which is what makes the bands non-trivial. - #[test] - fn filter_stage_bytes_do_not_depend_on_the_thread_count() { - let _knobs = crate::speed::knob_write(); - let (width, height) = (384usize, 288usize); - let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); - let coded = |threads: usize| { - crate::par::set_tile_threads(threads); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 2, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - stream - }; - // One tile, so only the filter stage can differ between these. - let one = coded(1); - for threads in [2usize, 4, 8] { - assert_eq!( - one, - coded(threads), - "the filter stage moved at {threads} threads" - ); - } - crate::par::set_tile_threads(1); - } - - /// lane-av1fpar: the filter search scores its ~30 candidates by replaying - /// the loop filters on one captured reconstruction instead of decoding - /// the coded tile again per candidate. The replay must be that decode, - /// byte for byte -- including at a size that CROPS (1080 and 1608 both - /// pad to a superblock row, i.e. every export size the editor uses), - /// which is the arm this lane opened. - #[test] - fn filter_replay_codes_the_same_stream_as_a_full_decode() { - let _knobs = crate::speed::knob_read(); - let run = |width: usize, height: usize, off: bool| { - let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); - crate::decode::set_filter_replay_disabled(off); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 2, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - crate::decode::set_filter_replay_disabled(false); - stream - }; - // 320x160 crops (the coding surface is 320x192, one superblock row - // taller); 320x192 is a whole number of superblocks, the shape the - // replay already covered. - for (width, height) in [(320usize, 160usize), (320, 192)] { - let replayed = run(width, height, false); - let decoded = run(width, height, true); - assert_eq!( - replayed, - decoded, - "{width}x{height}: the filter replay is not the decode it stands in for \ - ({} bytes replayed, {} decoded)", - replayed.len(), - decoded.len(), - ); - } - } - - /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced - /// the capture decode -- against that decode. `set_verify_final_replay` - /// makes `encode::pick_and_apply_filters` run both on every frame and - /// assert, per frame, that the spliced picture and the two filter stages - /// the loop-restoration search reads are bit-identical. - #[test] - fn filter_replay_final_matches_the_capture_decode() { - let _knobs = crate::speed::knob_read(); - let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 2, - colour: Colour::Bt709Limited, - tile_cols_log2: tiles.0, - tile_rows_log2: tiles.1, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - for packet in encode_all(&mut enc, sources) { - assert!(!packet.data.is_empty()); - } - }; - crate::decode::set_verify_final_replay(true); - // 320x160 crops (its coding surface is one superblock row taller); - // 320x192 is a whole number of superblocks. - for (width, height) in [(320usize, 160usize), (320, 192)] { - let sources: Vec = (0..4).map(|t| test_card(width, height, t * 3)).collect(); - run(&sources, width, height, (0, 0)); - } - // Real gate content, where the CDEF preset search actually chooses - // `bits > 0` and the tile is re-coded, one tile and four. - if let Some(sources) = h264_clip_frames(640, 384, 3) { - run(&sources, 640, 384, (0, 0)); - run(&sources, 640, 384, (1, 1)); - } - crate::decode::set_verify_final_replay(false); - } - - /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- - /// the per-tile search, the tile write, the frame-level filter search - /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture - /// decode the loop-restoration search rides on, and that search itself. - /// Measurement, not a pass/fail gate. - #[test] - #[ignore = "wall measurement: 36 s at 1080p; run it with --ignored --nocapture"] - fn filter_stage_wall_1080p() { - let _knobs = crate::speed::knob_write(); - filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); - } - - #[test] - #[ignore = "wall measurement: 62 s at 4K; run it with --ignored --nocapture"] - fn filter_stage_wall_4k() { - let _knobs = crate::speed::knob_write(); - filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); - } - - /// The same breakdown at the real films' own crop size. With - /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with - /// it unset it is the colour-bar fixture at the same size, which is what - /// makes the pair a comparison rather than a number. - #[test] - // MEASURED 16 s WITHOUT `EC_AV1_WALL_CLIP`, and what it measures then is - // the COLOUR-BAR fixture, not a film: `h264_clip_frames` falls back to - // `fixtures/video/h264-1080p-23.976-8bit.mp4` when the var is unset. A - // reader who takes the name for the content reads a bars number as a - // film number, so the precondition belongs in the reason. - #[ignore = "wall measurement: 16 s; MEASURES THE BARS FIXTURE unless EC_AV1_WALL_CLIP names a real film window"] - fn filter_stage_wall_film() { - let _knobs = crate::speed::knob_write(); - filter_stage_wall(1920, 768, 4, (2, 1), &[8]); - } - - fn filter_stage_wall( - width: usize, - height: usize, - frames: usize, - (cols_log2, rows_log2): (u32, u32), - threads: &[usize], - ) { - let Some(sources) = h264_clip_frames(width, height, frames) - else { - return; - }; - crate::par::set_stage_times(true); - for &t in threads { - crate::par::set_tile_threads(t); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: frames, - colour: Colour::Bt709Limited, - tile_cols_log2: cols_log2, - tile_rows_log2: rows_log2, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let _ = crate::par::take_stage_ns(); - let start = std::time::Instant::now(); - for packet in encode_all(&mut enc, &sources) { - assert!(!packet.data.is_empty()); - } - let wall = start.elapsed().as_secs_f64(); - let ns = crate::par::take_stage_ns(); - let ms = |i: usize| ns[i] as f64 / 1e6; - eprintln!( - "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ - {wall:.2}s wall, {:.2} fps", - 1 << cols_log2, - 1 << rows_log2, - frames as f64 / wall, - ); - eprintln!("| stage | ms | ms/frame | % of wall |"); - for (i, name) in crate::par::STAGES.iter().enumerate() { - eprintln!( - "| {name} | {:.0} | {:.1} | {:.1}% |", - ms(i), - ms(i) / frames as f64, - 100.0 * ms(i) / (wall * 1e3), - ); - } - // Top-level stages only (the deblock/CDEF/SSE rows are inside - // the filter-search total); the rest is per-frame setup, the - // source conversion and the splice. - let top: f64 = [ - crate::par::S_TILE_SEARCH, - crate::par::S_TILE_WRITE, - crate::par::S_FILTER, - crate::par::S_CAPTURE, - crate::par::S_LR, - ] - .iter() - .map(|&i| ms(i)) - .sum(); - eprintln!( - "accounted {:.1}% of wall; outside the tile search {:.1}%", - 100.0 * top / (wall * 1e3), - 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), - ); - } - crate::par::set_stage_times(false); - crate::par::set_tile_threads(1); - } - - fn tile_search_wall( - width: usize, - height: usize, - frames: usize, - layouts: &[(u32, u32)], - threads: &[usize], - ) { - let Some(sources) = h264_clip_frames(width, height, frames) - else { - return; - }; - let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) { - crate::par::set_tile_threads(t); - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: frames, - colour: Colour::Bt709Limited, - tile_cols_log2: cols_log2, - tile_rows_log2: rows_log2, - }; - let mut enc = Av1Encoder::new(config).unwrap(); - let start = std::time::Instant::now(); - let mut bytes = 0usize; - for packet in encode_all(&mut enc, &sources) { - bytes += packet.data.len(); - } - (start.elapsed(), bytes) - }; - let cells: Vec<((u32, u32), usize)> = layouts - .iter() - .flat_map(|&l| threads.iter().map(move |&t| (l, t))) - .collect(); - let mut best: Vec> = vec![None; cells.len()]; - for _pass in 0..2 { - for (i, &((c, r), t)) in cells.iter().enumerate() { - let got = run(c, r, t); - assert!( - got.1 > 0, - "{}x{} tiles at {t} threads: empty stream", - 1 << c, - 1 << r - ); - if best[i].is_none_or(|(w, _)| got.0 < w) { - best[i] = Some(got); - } - } - } - crate::par::set_tile_threads(1); - eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes"); - eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |"); - let base = best[0].expect("the first cell ran").0.as_secs_f64(); - for (i, &((c, r), t)) in cells.iter().enumerate() { - let (wall, bytes) = best[i].expect("every cell ran"); - let secs = wall.as_secs_f64(); - eprintln!( - "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |", - 1 << c, - 1 << r, - 1 << (c + r), - frames as f64 / secs, - base / secs, - ); - } - // Parallel efficiency per layout: what the extra threads actually - // took off that layout's own single-threaded wall, and so what share - // of the added cores sat idle. - for &(c, r) in layouts { - let one = cells - .iter() - .position(|&(l, t)| l == (c, r) && t == threads[0]) - .map(|i| best[i].expect("cell").0.as_secs_f64()); - let Some(one) = one else { continue }; - for &t in &threads[1..] { - let i = cells - .iter() - .position(|&(l, tt)| l == (c, r) && tt == t) - .expect("cell"); - let secs = best[i].expect("cell").0.as_secs_f64(); - let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64; - let speedup = one / secs; - eprintln!( - "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \ - idle share {:.0}%", - 1 << c, - 1 << r, - threads[0], - 100.0 * (1.0 - speedup / workers).max(0.0), - ); - } - } - rav1e_wall_reference(width, height, frames, layouts, threads); - } - - /// librav1e at the same sizes, layouts and thread counts, through ffmpeg - /// -- the reference the wall table is read against. - fn rav1e_wall_reference( - width: usize, - height: usize, - frames: usize, - layouts: &[(u32, u32)], - threads: &[usize], - ) { - let listed = ec_testkit::ffmpeg() - .args(["-hide_banner", "-encoders"]).output(); - let has_rav1e = listed - .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) - .unwrap_or(false); - // lane-av1clipprobe: this was `!has_rav1e || !clip.exists()` behind ONE - // line, which is how the clip's absence hid inside a tool-absence - // message and could not fail under any require env. The two causes are - // now separate, and only the clip goes through the fixture probe, so - // either way this helper prints exactly ONE line. - assert!(has_rav1e, "ffmpeg has no librav1e encoder"); - let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4"); - eprintln!("| rav1e layout | threads | wall | fps | bytes |"); - for &(c, r) in layouts { - for &t in threads { - let out = - std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id())); - let params = format!( - "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}", - 1 << c, - 1 << r - ); - let start = std::time::Instant::now(); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-ss", "20", "-i", clip.to_str().unwrap()]) - .args(["-frames:v", &frames.to_string()]) - .args(["-vf", &format!("scale={width}:{height}")]) - .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) - .arg(out.to_str().unwrap()).output() - .expect("ffmpeg failed to run"); - let secs = start.elapsed().as_secs_f64(); - if !status.status.success() { - eprintln!( - "| {}x{} | {t} | FAILED: {} |", - 1 << c, - 1 << r, - String::from_utf8_lossy(&status.stderr) - .lines() - .last() - .unwrap_or("") - ); - continue; - } - let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); - let _ = std::fs::remove_file(&out); - eprintln!( - "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |", - 1 << c, - 1 << r, - frames as f64 / secs - ); - } - } - } - - /// The same round trip at a real 1920x1080 crop of the gate's own clip - /// -- the size the editor's export actually runs at, where a tile grid - /// is worth having. - /// - /// UN-IGNORED by lane-av1probes: it was `#[ignore]`d only for its wall - /// ("1080p encode: minutes"), and it is the only 1080p arm in the ignored - /// set that actually ASSERTS. Measured 30.6 s in release on the - /// workstation (12 cores) and 64 s on a 4-core server, so it is affordable - /// in the suite. Evidence for the un-ignore: the three tile grids 2x1, - /// 2x2 and 4x2 each decode sample-exact through BOTH our decoder and - /// ffmpeg (84488 / 84208 / 84685 bytes), and the check is a per-frame - /// first-differing-luma-sample comparison, not a length or non-empty - /// smoke. - /// - #[test] - fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { - let _knobs = crate::speed::knob_read(); - let (width, height) = (1920usize, 1080usize); - let Some(sources) = h264_clip_frames(width, - height, - 3, - ) else { - return; - }; - for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { - let config = EncoderConfig { - width, - height, - base_q_idx: 120, - gop: 3, - colour: Colour::Bt709Limited, - tile_cols_log2: cols_log2, - tile_rows_log2: rows_log2, - }; - let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); - let mut enc = Av1Encoder::new(config).unwrap(); - let mut stream = Vec::new(); - for packet in encode_all(&mut enc, &sources) { - stream.extend_from_slice(&packet.data); - } - let ours = crate::stream::decode_stream(&stream).expect("our decoder"); - assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); - let theirs = ffmpeg_decode_luma(&stream, width, height); - assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); - for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { - let got: Vec = a.y.iter().map(|&v| v as u8).collect(); - if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { - panic!( - "1080p {layout} frame {i}: luma differs first at ({}, {})", - at % width, - at / width - ); - } - assert_eq!( - got.len(), - b.len(), - "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}", - got.len(), - b.len() - ); - } - eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); - } - } - - /// [`RateTarget::Quality`] is monotone: a higher quality dial never - /// produces a smaller stream or a worse mean PSNR than a lower one, on - /// the same real clip. - #[test] - fn quality_target_is_monotone_in_bytes_and_psnr() { - let _knobs = crate::speed::knob_read(); - let (width, height) = (640, 384); - let Some(pictures) = h264_clip_frames(width, - height, - 8, - ) else { - return; - }; - let mut prev_bytes = 0usize; - let mut prev_psnr = 0.0f64; - for quality in [20u8, 50, 80] { - let config = EncoderConfig { - width, - height, - base_q_idx: 100, - gop: 8, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let mut enc = - Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); - let mut stream = Vec::new(); - let mut total_bytes = 0usize; - for packet in encode_all(&mut enc, &pictures) { - total_bytes += packet.data.len(); - stream.extend_from_slice(&packet.data); - } - let decoded = ffmpeg_decode_luma(&stream, width, height); - assert_eq!( - decoded.len(), - pictures.len(), - "quality {quality}: dav1d frame count" - ); - let mean_psnr: f64 = decoded - .iter() - .zip(&pictures) - .map(|(d, p)| { - let d16: Vec = d.iter().map(|&v| u16::from(v)).collect(); - psnr(&d16, &p.y) - }) - .sum::() - / decoded.len() as f64; - assert!( - total_bytes >= prev_bytes, - "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" - ); - assert!( - mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours - "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" - ); - prev_bytes = total_bytes; - prev_psnr = mean_psnr; - } - } +} diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index 5f26850b..1718a1b7 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -22,7 +22,6 @@ //! the frame it pushes onto its output `Vec`, after saving the //! clean decode into the reference slot bank. use archmage::SimdToken; -use crate::hits::hit; use crate::decode::WithRef; use crate::encode::Picture; @@ -790,7 +789,11 @@ fn chroma_noise_row_scalar( pair: bool, ) { if pair { - for ((c, lpair), &g) in chroma.iter_mut().zip(luma.as_chunks::<2>().0.iter()).zip(grain) { + for ((c, lpair), &g) in chroma + .iter_mut() + .zip(luma.as_chunks::<2>().0.iter()) + .zip(grain) + { let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1; let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset) .clamp(0, p.index_max); @@ -1288,12 +1291,6 @@ thread_local! { static GRAIN_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Current value of [`GRAIN_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn grain_hits() -> usize { - GRAIN_HITS.with(|c| c.get()) -} - /// Copies the clean rows `*lcur..l_to` (luma) and `*ccur..c_to` (chroma) of /// `src` into `out`, advancing the cursors. [`apply_grain`]'s bands fill /// their own uninitialised destination rows with this before adding noise. @@ -1351,28 +1348,8 @@ struct GrainBand<'a> { /// the disjoint band slices' split does; the byte-exact 1-vs-4-thread /// gate is what checks it. Upgrade path: `Box<[MaybeUninit]>` plumbed /// through the kernels. -/// -/// # lane-av1graincensus: the fill under the census arm -/// -/// That corner-cut is also why the buffer must be POISONED, not merely -/// uninitialised, whenever the sentinel is live. Counting `== plane_poison()` -/// over ambient garbage is a census that can only ever report ~0: a hole -/// survives with probability ~1/65536 rather than always, so -/// [`crate::decode::census_unwritten_grained`] would report 0 whether or not -/// the band copy covered every row. Filling here makes "the band copy wrote -/// every sample" a measurement. It is the same predicate -/// [`crate::decode::fresh_plane`] honours, and with the sentinel off -- every -/// shipped build -- this is the same zeroed buffer, so nothing changes where it -/// is paid for. fn uninit_plane(n: usize) -> Vec { - // `vec![0; n]` is `alloc_zeroed`, which for a plane-sized buffer is a - // fresh `calloc`/mmap: the zero pages are not touched until the band copy - // writes them, so no extra full-buffer pass is paid. Safe, and no `set_len`. - let mut v: Vec = vec![0; n]; - if crate::decode::plane_sentinel_on() { - v.fill(crate::decode::plane_poison()); - } - v + vec![0; n] } /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and @@ -1440,14 +1417,9 @@ pub(crate) fn apply_grain( ) -> Picture { if !fg.apply_grain { let clean = picture.clone(); - // lane-av1graincensus: this exit censuses too, so "the picture - // `apply_grain` hands back is censused in its final form" is a property - // of the FUNCTION rather than of one branch. - crate::decode::census_unwritten_grained(&clean.y, &clean.u, &clean.v); return clean; } fctx.grain_bit_depth.with(|c| c.set(bit_depth)); - hit!(GRAIN_HITS); // lane-av1422grain: the chroma geometry is per-axis. `FrameCtx` already // carries the sequence header's pair (`decode::set_subsampling`), and // `apply_grain` runs inside the same frame context, so the chroma @@ -2142,16 +2114,6 @@ pub(crate) fn apply_grain( }); drop(parts); - // lane-av1graincensus: the post-grain census, at the point the caller takes - // the picture. `census_unwritten_final` runs in `stream.rs` BEFORE this - // function, over the clean planes, and every filter writes in place into - // that same buffer -- so the destination allocated above by `uninit_plane` - // is the ONLY picture between that census and the caller that no census has - // ever looked at. `lanes/unwritten-dep.report.md` §6/§8 declined to claim - // anything about it; this measures it. `uninit_plane` poisons the buffer - // under the same predicate, so the count is a measurement rather than a - // coin flip on ambient garbage. - crate::decode::census_unwritten_grained(&out.y, &out.u, &out.v); out } @@ -2587,16 +2549,18 @@ mod ragged_grain_tests { } for col in 0..w { let mut g = sl[(i * w + col) as usize]; - if overlap && i < 2 - && let Some((p, _, _)) = &prev { - let old = p[((i + 32) * w + col) as usize]; - g = if i == 0 { - old * 27 + g * 17 - } else { - old * 17 + g * 27 - }; - g = round2(g, 5).clamp(gmin, gmax); - } + if overlap + && i < 2 + && let Some((p, _, _)) = &prev + { + let old = p[((i + 32) * w + col) as usize]; + g = if i == 0 { + old * 27 + g * 17 + } else { + old * 17 + g * 27 + }; + g = round2(g, 5).clamp(gmin, gmax); + } nl[(row * w + col) as usize] = g; } } diff --git a/crates/ec-av1/src/hits.rs b/crates/ec-av1/src/hits.rs deleted file mode 100644 index 16d891fb..00000000 --- a/crates/ec-av1/src/hits.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! Gate-counter bumps, compiled out when the `gate-counters` feature is off. -//! -//! The ~550 `*_HITS` thread-locals in this crate exist only so the test gates -//! (and the probe's census print) can prove a coding path fired; every bump is -//! a TLS access plus a `Cell` read-modify-write on the parse thread. Routing -//! all of them through [`hit!`]/[`hit_do!`] lets a shipped decoder drop them -//! (`--no-default-features`) while the accessors keep compiling and returning -//! whatever the counters hold (0 when the feature is off), so no caller needs -//! a `cfg`. - -/// Bumps counter `$name` by one -- nothing at all without `gate-counters`. -/// Usable in expression position (it evaluates to `()`). -#[cfg(feature = "gate-counters")] -macro_rules! hit { - ($name:ident) => {{ - $name.with(|c| c.set(c.get() + 1)); - }}; -} - -#[cfg(not(feature = "gate-counters"))] -macro_rules! hit { - ($name:ident) => {{}}; -} - -/// Same, for a bump that is not a plain `+= 1` (array/tuple buckets, the -/// `inter_last_mc` stamp, the counter-only scan loops): the whole statement -/// list disappears without `gate-counters`. -#[cfg(feature = "gate-counters")] -macro_rules! hit_do { - ($($t:tt)*) => {{ - $($t)* - }}; -} - -// Without the feature the statements stay type-checked but unreachable, so the -// values they read (bucket indices, filter kinds) still count as used and the -// optimiser drops the whole branch. -#[cfg(not(feature = "gate-counters"))] -macro_rules! hit_do { - ($($t:tt)*) => {{ - if false { - $($t)* - } - }}; -} - -pub(crate) use {hit, hit_do}; diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index a1d354d5..1351e86d 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -7,7 +7,6 @@ //! not this module's business -- the caller passes the samples it has, and the //! edge is extended by repeating the last one, which is what the decoder does //! with its own `BlockDecoded` bookkeeping (spec 7.11.2.2). -use crate::hits::hit; /// The average of the neighbours (spec 7.11.2.5). pub const DC_PRED: u8 = 0; @@ -153,7 +152,8 @@ impl Edges { left: Option<&[u16]>, corner: Option, bw: usize, - bh: usize, fctx: &crate::decode::FrameCtx, + bh: usize, + fctx: &crate::decode::FrameCtx, ) -> Self { let want = bw + bh; // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)` @@ -250,25 +250,6 @@ thread_local! { static EDGE_FILTER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// How many blocks were predicted with SMOOTH/SMOOTH_V/SMOOTH_H on this thread. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn smooth_pred_hits() -> usize { - SMOOTH_PRED_HITS.with(|c| c.get()) -} - -/// How many blocks were predicted with PAETH_PRED on this thread. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn paeth_pred_hits() -> usize { - PAETH_PRED_HITS.with(|c| c.get()) -} - -/// How many directional edges [`filter_intra_edge`] actually smoothed -/// (strength != 0) on this thread -- the `--enable-intra-edge-filter` proof. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn intra_edge_filter_hits() -> usize { - EDGE_FILTER_HITS.with(|c| c.get()) -} - #[allow(clippy::too_many_arguments)] pub(crate) fn predict( mode: u8, @@ -280,16 +261,10 @@ pub(crate) fn predict( bh: usize, enable_edge_filter: bool, smooth_neighbor: bool, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(dst.len(), bw * bh, "the destination is the block"); - match mode { - SMOOTH_PRED | SMOOTH_V_PRED | SMOOTH_H_PRED => { - hit!(SMOOTH_PRED_HITS); - } - PAETH_PRED => hit!(PAETH_PRED_HITS), - _ => {} - } let edges = Edges::build(above, left, corner, bw, bh, fctx); let is_directional = matches!( mode, @@ -314,7 +289,8 @@ pub(crate) fn predict( smooth_neighbor, n_top, n_left, - dst, fctx, + dst, + fctx, ); return; } @@ -484,7 +460,6 @@ fn filter_intra_edge(buf: &mut [i32], strength: i32) { if strength == 0 { return; } - hit!(EDGE_FILTER_HITS); const KERNEL: [[i32; 5]; 3] = [[0, 4, 8, 4, 0], [0, 5, 6, 5, 0], [2, 4, 4, 4, 2]]; let filt = usize::try_from(strength - 1).expect("a filter strength is never negative"); let sz = buf.len() as i32; @@ -539,7 +514,8 @@ fn directional( smooth_neighbor: bool, n_top: usize, n_left: usize, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { let (w, h) = (bw as i32, bh as i32); let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach. @@ -551,7 +527,10 @@ fn directional( // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner: // that is exactly `Edges`' own layout (lane-alloc), so take the buffers // rather than copying them into two fresh ones per directional block. - let Edges { mut above, mut left } = edges; + let Edges { + mut above, + mut left, + } = edges; if enable_edge_filter && angle != 90 && angle != 180 { if need_above && need_left && reach >= 24 { @@ -608,7 +587,10 @@ fn directional( // the blend's `&dyn Fn` indirection all used to sit inside the pixel // loop; they are per-block (per-row for the shift) constants. let blend = |edge: &[i32], off: i32, base: i32, shift: i32| { - round2(edge[(base + off) as usize] * (32 - shift) + edge[(base + off + 1) as usize] * shift, 5) + round2( + edge[(base + off) as usize] * (32 - shift) + edge[(base + off + 1) as usize] * shift, + 5, + ) }; if angle < 90 { let dx = dr_intra_derivative(angle); @@ -665,7 +647,12 @@ fn directional( blend(above_buf, above_off, base, ((x << up_a) & 0x3F) >> 1) } else { let y2 = yrow - (col as i32 + 1) * dy; - blend(left_buf, left_off, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1) + blend( + left_buf, + left_off, + y2 >> frac_bits_y, + ((y2 << up_l) & 0x3F) >> 1, + ) }; *d = value.clamp(0, max) as u16; } @@ -682,7 +669,13 @@ fn directional( /// before `dc_predictor` averages, so a slice truncated short by the true /// frame edge must be extended by repetition here too, not averaged over its /// own shorter length. -fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> i32 { +fn dc( + above: Option<&[u16]>, + left: Option<&[u16]>, + bw: usize, + bh: usize, + fctx: &crate::decode::FrameCtx, +) -> i32 { // lane-perf4: the replication is only ever *summed*, never indexed, so // the extended edge is a sum rather than the `Vec` it used to be // built as (two allocations per intra block, 0.9% of a 1080p decode's @@ -816,7 +809,8 @@ pub(crate) fn predict_filter_intra( corner: Option, bw: usize, bh: usize, - dst: &mut [u16], fctx: &crate::decode::FrameCtx, + dst: &mut [u16], + fctx: &crate::decode::FrameCtx, ) { assert_eq!(dst.len(), bw * bh, "the destination is the block"); assert_eq!(bw % 4, 0, "filter intra patches are 4 wide"); @@ -851,7 +845,8 @@ pub(crate) fn predict_filter_intra( for k in 0..8 { let (r_off, c_off) = (k >> 2, k & 3); let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum(); - let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max(fctx)); + let value = + round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max(fctx)); let idx = (r + r_off) * (bw + 1) + c + c_off; buffer[idx] = value; } @@ -1030,7 +1025,7 @@ mod tests { /// on three seeded random edges. #[test] fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); // xorshift64*: a seeded stream, so a failure names one (shape, mode, // seed) triple that reproduces. let rng = |state: &mut u64| { @@ -1073,9 +1068,7 @@ mod tests { let mut want = vec![0u16; bw * bh]; let mut c_above = vec![corner]; c_above.extend_from_slice(&above); - libaom_filter_intra_predictor( - &mut want, bw, bh, &c_above, &left, mode, bd, - ); + libaom_filter_intra_predictor(&mut want, bw, bh, &c_above, &left, mode, bd); let mut got = vec![0u16; bw * bh]; predict_filter_intra( mode, @@ -1084,7 +1077,8 @@ mod tests { Some(corner), bw, bh, - &mut got, fctx, + &mut got, + fctx, ); assert_eq!( got, want, @@ -1096,7 +1090,11 @@ mod tests { } } crate::decode::set_bit_depth(8, fctx); - assert_eq!(compared, 2 * 14 * 5 * 3, "every shape/mode/seed was compared"); + assert_eq!( + compared, + 2 * 14 * 5 * 3, + "every shape/mode/seed was compared" + ); } /// Spec 7.11.2.5 divides the rect DC average exactly. A 4x16 block (a 1:4 @@ -1135,7 +1133,7 @@ mod tests { /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`). #[test] fn rect_predictors_match_c_dump() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::new(); let expected_txt = std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/../../lanes/intrarect_dump.expected.txt" @@ -1212,7 +1210,11 @@ mod tests { let left = fill(reach, 2); let corner = ((bw * 3 + bh * 5) % 256) as u16; - for (name, mode) in [("DC", DC_PRED), ("SMOOTH", SMOOTH_PRED), ("PAETH", PAETH_PRED)] { + for (name, mode) in [ + ("DC", DC_PRED), + ("SMOOTH", SMOOTH_PRED), + ("PAETH", PAETH_PRED), + ] { let mut dst = vec![0u16; bw * bh]; predict( mode, @@ -1224,7 +1226,8 @@ mod tests { bh, false, false, - &mut dst, fctx, + &mut dst, + fctx, ); let got = if name == "DC" { u64::from(dst[0]) @@ -1252,12 +1255,15 @@ mod tests { bh, ef, sn, - &mut dst, fctx, + &mut dst, + fctx, ); let got = checksum(&dst); let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn)); let want = *expected.get(&key).unwrap_or_else(|| { - panic!("missing DR {bw}x{bh} angle={angle} ef={ef} sn={sn} in the C dump") + panic!( + "missing DR {bw}x{bh} angle={angle} ef={ef} sn={sn} in the C dump" + ) }); assert_eq!( got, want, diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 28b9c83a..360a6707 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -24,11 +24,9 @@ pub mod bits; mod autothreads; pub mod cdf; mod cdf_state; -pub mod census; mod compound; pub mod decode; pub mod encode; -mod dumpio; pub mod encoder; #[doc(hidden)] pub mod fault; @@ -37,7 +35,6 @@ mod film_grain; pub use film_grain::apply_film_grain; mod filter_search; pub mod frame; -mod hits; pub mod intra; pub mod mc; pub mod motion; @@ -53,11 +50,8 @@ pub mod quant; mod restoration; pub mod sequence; pub mod speed; -mod stack_budget; pub mod stream; mod superres; -#[cfg(test)] -mod test_source; pub mod tile; mod timeline; pub mod transform; diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index c1ba4578..9265cc32 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -9,7 +9,6 @@ //! land on an even step; chroma vectors, once scaled for subsampling, can //! land on any of the 16. use archmage::SimdToken; -use crate::hits::hit; /// `Round2` (spec 4.7): halves round up. fn round2(value: i32, shift: u32) -> i32 { @@ -516,7 +515,16 @@ mod simd { c += 16; } if c < block_w { - hpass_sse2(t.v2(), &sp[c..], 0, 1, block_w - c, t16, &mut op[c..], round0); + hpass_sse2( + t.v2(), + &sp[c..], + 0, + 1, + block_w - c, + t16, + &mut op[c..], + round0, + ); } } } @@ -967,7 +975,17 @@ mod simd { round1: u32, ) { let t = archmage::X64V3Token::summon().expect("avx2 entry on a CPU without avx2"); - super::vpass_row_u16_avx2(t, intermediate, block_w, src_stride, rows, taps, max, dst, round1) + super::vpass_row_u16_avx2( + t, + intermediate, + block_w, + src_stride, + rows, + taps, + max, + dst, + round1, + ) } #[allow(unused_variables, clippy::too_many_arguments)] @@ -982,7 +1000,17 @@ mod simd { round1: u32, ) { let t = archmage::X64V2Token::summon().expect("sse4.1 entry on a CPU without sse4.1"); - super::vpass_row_u16_sse41(t, intermediate, block_w, src_stride, rows, taps, max, dst, round1) + super::vpass_row_u16_sse41( + t, + intermediate, + block_w, + src_stride, + rows, + taps, + max, + dst, + round1, + ) } } } @@ -1473,7 +1501,6 @@ pub(crate) fn predict_with_filters_kern( ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); - hit!(INTER_PRED_HITS); #[cfg(test)] let stage_t = crate::encode::stage_start(); @@ -1535,7 +1562,6 @@ pub(crate) fn predict_with_filters_kern( let (h_wide, h_narrow) = h_kind.tables(); let (v_wide, v_narrow) = v_kind.tables(); - note_narrow_kern(block_w, block_h, kern_w, kern_h); let h_filter = if kern_w <= 4 { &h_narrow[xfrac] } else { @@ -1569,9 +1595,6 @@ pub(crate) fn predict_with_filters_kern( // clamped read. if xfrac != 0 || yfrac == 0 { // fall through to the two-pass path - if xfrac != 0 || yfrac != 0 { - hit!(MC_SUBPEL_HITS); - } } else { let top = y0 - 3; if top >= 0 @@ -1758,14 +1781,6 @@ pub fn reset_rect_narrow_kern_hits() { RECT_NARROW_KERN_HITS.with(|c| c.set(0)); } -/// Bumps [`RECT_NARROW_KERN_HITS`] when the block's true dims pick a kernel -/// the destination buffer's dims would not have. -fn note_narrow_kern(block_w: usize, block_h: usize, kern_w: usize, kern_h: usize) { - if (kern_w <= 4) != (block_w <= 4) || (kern_h <= 4) != (block_h <= 4) { - hit!(RECT_NARROW_KERN_HITS); - } -} - /// Current value of [`INTER_PRED_HITS`]. pub fn inter_pred_hits() -> usize { INTER_PRED_HITS.with(|c| c.get()) @@ -2052,8 +2067,6 @@ pub(crate) fn predict_scaled_kern( ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); - hit!(INTER_PRED_HITS); - hit!(PREDICT_SCALED_HITS); let max = crate::decode::sample_max(fctx); let (round0, round1) = round_pair(u32::from(crate::decode::bit_depth(fctx))); @@ -2091,7 +2104,6 @@ pub(crate) fn predict_scaled_kern( // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10 // grid (spec 7.11.3.3's `dec_calc_subpel_params`). let (v_wide, v_narrow) = v_kind.tables(); - note_narrow_kern(block_w, block_h, kern_w, kern_h); let v_filter = if kern_h <= 4 { &v_narrow[yfrac] } else { @@ -2279,11 +2291,7 @@ pub(crate) fn predict_compound_intermediate_kern( ) { assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); assert!(!reference.is_empty(), "a reference plane has samples"); - hit!(INTER_PRED_HITS); - if !scale.is_unscaled() { - hit!(PREDICT_SCALED_HITS); - } let x_scale_fp = scale.x; if scale.y != REF_NO_SCALE { let (round0, _) = round_pair(u32::from(crate::decode::bit_depth(fctx))); @@ -2319,7 +2327,6 @@ pub(crate) fn predict_compound_intermediate_kern( } let (v_wide, v_narrow) = v_kind.tables(); - note_narrow_kern(block_w, block_h, kern_w, kern_h); let v_filter = if kern_h <= 4 { &v_narrow[yfrac] } else { diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index 51a81ff1..1c94c28b 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -5,7 +5,6 @@ //! (`av1/common/mvref_common.c`) and the projection math `add_tpl_ref_mv` //! (same file) applies a second time, per query block, against the block's //! own single reference frame. -use crate::hits::hit; use crate::mvstack::{ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME}; @@ -77,18 +76,6 @@ impl MotionField { } } - /// lane-mergefix r5 rung (`EC_TRACE_TPL`): occupancy map of the SAVED - /// field, the input side of [`setup_motion_field`]'s projection. - pub fn occupancy(&self) -> Vec { - (0..self.rows) - .map(|r| { - (0..self.cols) - .map(|c| if self.cells[r * self.cols + c].is_some() { '#' } else { '.' }) - .collect() - }) - .collect() - } - /// lane-mf: the cell grid itself (`cols`, `rows`, cells in row-major /// order), so [`crate::decode::build_motion_field`] can fill disjoint /// row bands of it in parallel. Cell row `r` owns `cells[r * cols..][..cols]`. @@ -127,7 +114,6 @@ impl TplField { pub fn filled_cells(&self) -> usize { self.cells.iter().filter(|c| c.1 != 0).count() } - } /// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range @@ -353,25 +339,6 @@ fn motion_field_projection( true } -thread_local! { - /// Frames whose `av1_setup_motion_field` saw at least one forward - /// references holding a key/intra-only frame -- the `ref_stamp` path - /// [`motion_field_projection`]'s intra early return governs. - static REFSTAMP_INTRA_FRAMES: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// The subset of those frames with TWO or more such references. - static REFSTAMP_INTRA2_FRAMES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Reads the counter above (gate -/// `a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact`). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub fn refstamp_intra_frames() -> (usize, usize) { - ( - REFSTAMP_INTRA_FRAMES.with(std::cell::Cell::get), - REFSTAMP_INTRA2_FRAMES.with(std::cell::Cell::get), - ) -} - /// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to /// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order /// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when @@ -414,27 +381,6 @@ pub fn setup_motion_field>( let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1 - // Gate counter (lane-refstamp): frames whose forward references include at - // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the - // early return above fixes. - let intra_forward_refs = [ - BWDREF_FRAME, - crate::mvstack::ALTREF2_FRAME, - ALTREF_FRAME, - ] - .into_iter() - .filter(|&rf| { - get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0 - && slot_of(rf).is_some_and(|m| m.is_intra) - }) - .count(); - if intra_forward_refs >= 1 { - hit!(REFSTAMP_INTRA_FRAMES); - } - if intra_forward_refs >= 2 { - hit!(REFSTAMP_INTRA2_FRAMES); - } - if let Some(last) = slot_of(LAST_FRAME) { let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize]; let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME); @@ -561,7 +507,9 @@ pub fn add_tpl_ref_mv( let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col); if crate::envflags::env_flag!("EC_TRACE_TPL") { match probe { - None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"), + None => eprintln!( + "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID" + ), Some((m, rfo)) => eprintln!( "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}", m.0, m.1 @@ -662,8 +610,16 @@ mod tests { for blk_row in -4isize..=16 { for blk_col in -4isize..=16 { // the spec's own derivation (7.10.2.8) - let pos_row = if mi_row & 1 != 0 { blk_row } else { blk_row + 1 }; - let pos_col = if mi_col & 1 != 0 { blk_col } else { blk_col + 1 }; + let pos_row = if mi_row & 1 != 0 { + blk_row + } else { + blk_row + 1 + }; + let pos_col = if mi_col & 1 != 0 { + blk_col + } else { + blk_col + 1 + }; let row8 = mi_row as isize + pos_row; let col8 = mi_col as isize + pos_col; let want = if row8 < 0 || col8 < 0 { @@ -747,8 +703,16 @@ mod tests { // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts // the offset, landing at 8x8 cell (2, 0). - let cand = - add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true, false); + let cand = add_tpl_ref_mv( + &tpl, + 4, + 0, + 0isize, + 0isize, + get_relative_dist(7, 4, 2), + true, + false, + ); assert!(cand.is_some(), "expected a projected temporal candidate"); } diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 55694552..58233236 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -144,9 +144,6 @@ impl SymbolEncoder { /// shorter than a two-symbol alphabet's three entries. pub fn symbol_fixed(&mut self, symbol: usize, cdf: &[u16]) { assert!(cdf.len() >= 3, "a CDF covers at least two symbols"); - if !self.pricing && symtrace::dir().is_some() { - symtrace::push(symbol, cdf.len() - 1, cdf[0]); - } let nsyms = cdf.len() - 1; assert!(symbol < nsyms, "symbol {symbol} is outside the alphabet"); @@ -204,7 +201,6 @@ impl SymbolEncoder { /// payload end on a byte boundary with no terminator. pub fn finish(mut self) -> Vec { assert!(!self.pricing, "a pricer holds no bytes to flush"); - symtrace::flush('w'); // Round the interval's low end up to a value with 14 low zero bits, // then set bit 14: the result is inside the interval (the interval is // at least 2^15 wide before normalisation) and its tail bits are all @@ -316,37 +312,7 @@ pub struct SymbolDecoder<'a> { } impl Drop for SymbolDecoder<'_> { - fn drop(&mut self) { - symtrace::flush('r'); - } -} - -thread_local! { - /// The `(mi_row, mi_col)` the enclosing block reader is inside, for the - /// `EC_SYMR` trace. A symbol read carries no mi of its own, so without it - /// the per-read stream can only be located by correlating it against a - /// SEPARATE trace -- and that correlation is what mis-attributed reads in - /// rounds 22 and 23. Set by the mode readers at entry; `(-1,-1)` outside. - pub(crate) static SYMR_MI: std::cell::Cell<(i64, i64)> = - const { std::cell::Cell::new((-1, -1)) }; - /// A short tag for the READER PHASE ("intra", "inter", "mv", ...), printed - /// on every `EC_SYMR` line. The coefficient rungs stop well before some - /// divergences, so the per-read stream is the only instrument that covers - /// the inter path; without a phase its reads are unattributable. - pub(crate) static SYMR_PHASE: std::cell::Cell<&'static str> = - const { std::cell::Cell::new("") }; - /// The CDF TABLE NAME for the NEXT read, mirroring the oracle's - /// `ec_symr_cdf_tag`. `cdf0` alone cannot identify a table -- two rows - /// can share a first entry -- so this is what turns "two 2-symbol reads" - /// into a named pair. - /// - /// ONE-SHOT, consumed by the next `symbol()`. Round 30: it used to be - /// sticky, so every read after a tagged one carried that tag -- which is - /// how an 8-symbol read came to be labelled `interintra`, a 2-symbol - /// table. An EMPTY `cdf=` therefore means "no table set for this read", - /// never "the previous read's table". - pub(crate) static SYMR_CDF: std::cell::Cell<&'static str> = - const { std::cell::Cell::new("") }; + fn drop(&mut self) {} } impl<'a> SymbolDecoder<'a> { @@ -425,53 +391,8 @@ impl<'a> SymbolDecoder<'a> { /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. /// - pub(crate) fn set_symr_cdf(t: &'static str) { - SYMR_CDF.with(|c| c.set(t)); - } - - pub(crate) fn set_symr_phase(p: &'static str) { - SYMR_PHASE.with(|c| c.set(p)); - } - - pub(crate) fn set_symr_mi(mi_r: i64, mi_c: i64) { - SYMR_MI.with(|c| c.set((mi_r, mi_c))); - } - - /// The `(mi_row, mi_col)` the enclosing block reader last stamped, READ - /// back. `set_symr_mi` only writes; a per-unit interval rung needs to print - /// the mi, and a coefficient read carries none of its own -- without this a - /// ladder cannot be attributed to the block that read it. A copy, not a - /// borrow: the rungs call it from a `&SymbolDecoder`. - pub(crate) fn symr_mi() -> (i64, i64) { - SYMR_MI.with(std::cell::Cell::get) - } - - /// `EC_SYMR=1` dumps every symbol read's PRE state (before the read and - /// before the adaptation) together with the symbol and the post-read - /// range, so a divergence against a reference decoder can be bisected - /// read by read. `cdf0` is the PRE-adapt row[0] -- the reference's own - /// print of the same row is POST-adapt, so compare `32768 - ours_cdf0` - /// against its `cdf0`, never the raw numbers. #[inline] pub fn symbol(&mut self, cdf: &mut [u16]) -> usize { - // lane-av1422warp r33 (reviewer P2): this ran on EVERY symbol read of - // EVERY stream, production formats included, and `std::env::var_os` - // is a real environment scan each time (~30ns x every symbol). - // `env_flag!` keeps one `LazyLock` per call SITE, so the check - // compiles to an atomic load. The trace is byte-identical: same - // condition, same format, same fields. - let symr = crate::envflags::env_flag!("EC_SYMR"); - let (pre_value, pre_range, pre_bit) = (self.value, self.range, self.bit); - let pre_cdf0 = cdf.first().copied().unwrap_or(0); - // lane-census: the syntax census charges this symbol's bits to the - // TABLE it read, so every coding tool is accounted without a - // per-call-site label. Off (`EC_AV1_BITCENSUS` unset) this is one - // relaxed load. - let t0 = if crate::census::armed() { - self.tell_bits() - } else { - 0.0 - }; let s = self.symbol_fixed(cdf); // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets // it codes every symbol against the tables it started with, so this @@ -481,25 +402,6 @@ impl<'a> SymbolDecoder<'a> { if self.adapt { update_cdf(cdf, s); } - if crate::census::armed() { - crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0); - } - if symr { - eprintln!( - "EC_SYMR ph={} cdf={} mi=({},{}) pre=({},{},{}) cdf0={} n={} s={} post_rng={}", - SYMR_PHASE.with(std::cell::Cell::get), - SYMR_CDF.with(|c| c.replace("")), - SYMR_MI.with(std::cell::Cell::get).0, - SYMR_MI.with(std::cell::Cell::get).1, - pre_value, - pre_range, - pre_bit, - pre_cdf0, - cdf.len() - 1, - s, - self.range - ); - } s } @@ -517,20 +419,12 @@ impl<'a> SymbolDecoder<'a> { /// [`SymbolEncoder::symbol_fixed`]. #[inline] pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { - if symtrace::dir().is_some() { - let s = self.symbol_fixed_raw(cdf); - symtrace::push(s, cdf.len() - 1, cdf[0]); - return s; - } self.symbol_fixed_raw(cdf) } #[inline] fn symbol_fixed_raw(&mut self, cdf: &[u16]) -> usize { let nsyms = cdf.len() - 1; - if symtrace::ecdump_armed() { - symtrace::ecdump(0, self.value, self.range, self.bit as i64); - } // Two-symbol alphabets are most of the stream (every flag, every bit of // a literal), and their walk has exactly one boundary: computing it // straight skips the loop and its bounds work. @@ -595,17 +489,11 @@ impl<'a> SymbolDecoder<'a> { self.max_bits -= bits as i32; } - /// Debug-only: the current bit offset into `data`, for cross-checking - /// against a reference decoder's own `aom_reader_tell()` while chasing a - /// desync (see `EC_AV1_TRACE`). Not spec state, just `self.bit`. - pub(crate) fn debug_bitpos(&self) -> usize { - self.bit - } - /// Debug-only: the raw coder state (`range`, `value`) entering the next /// read, for a byte-for-byte diff against a reference decoder's own /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields. + #[cfg(test)] pub(crate) fn debug_state(&self) -> (u32, u32) { (self.range, self.value) } @@ -618,18 +506,12 @@ impl<'a> SymbolDecoder<'a> { /// the coefficient sign pass and the Golomb tail read one bit at a time. #[inline] pub fn literal(&mut self, bits: u32) -> u32 { - if crate::census::armed() { - crate::census::charge_literal(bits); - } let mut v = 0; for _ in 0..bits { // `EQUIPROBABLE`'s single boundary: `f >> EC_PROB_SHIFT` is 256, so // the range multiply is a shift. let cur = ((self.range >> 8) << 7) + EC_MIN_PROB; let bit = self.bool_cur(cur); - if symtrace::dir().is_some() { - symtrace::push(bit, 2, EQUIPROBABLE[0]); - } v = (v << 1) | bit as u32; } v @@ -981,169 +863,3 @@ pub(crate) mod tests { ); } } - -/// Symbol-by-symbol writer/reader trace (`EC_AV1_SYMTRACE=`), the -/// instrument a desync between OUR writer and OUR reader is bisected with: -/// every non-pricing [`SymbolEncoder`] and every [`SymbolDecoder`] dumps one -/// line per symbol (`index value nsyms cdf0`) into `/w-.txt` / -/// `/r-.txt`, and the first line where the two differ names the -/// divergent symbol. `EC_AV1_SYMTRACE_AT=` additionally prints a -/// backtrace at that index on both sides, which names the syntax element. -/// Off (the variable unset) this is one relaxed load per symbol. -pub(crate) mod symtrace { - use std::cell::RefCell; - use std::collections::VecDeque; - use std::sync::OnceLock; - - static DIR: OnceLock> = OnceLock::new(); - static AT: OnceLock> = OnceLock::new(); - static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - - thread_local! { - static BUF: RefCell<(String, usize)> = const { RefCell::new((String::new(), 0)) }; - static ECD: RefCell> = const { RefCell::new(VecDeque::new()) }; - // lane-av1dumploud: the file's PATH travels with it, so a short write - // can name the file it truncated instead of reconstructing a name. - static ECD_READER: RefCell> = const { RefCell::new(None) }; - static ECD_IDX: RefCell = const { RefCell::new(0) }; - } - - /// lane-av1mix: `(low, value, rng, bitpos)` state register dump, one line - /// per symbol read, byte-for-byte diffable against libaom's `EC_ECDUMP` - /// (`decodetxb.c`, `r->ec.dif` masked to 16 bits / `r->ec.rng` / - /// `od_ec_dec_tell`). Reader-only, `EC_AV1_ECDUMP=`: each reader - /// writes `/ecdump-.txt`. - pub(crate) fn ecdump(low: u32, value: u32, rng: u32, bitpos: i64) { - if !ecdump_armed() { - return; - } - let dir = std::env::var("EC_AV1_ECDUMP").unwrap_or_else(|_| "/tmp".to_string()); - let idx = ECD_IDX.with(|c| { - let mut g = c.borrow_mut(); - let n = *g; - *g += 1; - n - }); - let _ = idx; - let line = format!("{idx} ({low},{value},{rng},{bitpos})\n"); - ECD_READER.with(|f| { - use std::io::Write; - let mut slot = f.borrow_mut(); - if slot.is_none() { - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let path = format!("{dir}/ecdump-{seq:05}.txt"); - eprintln!("ECDUMP -> {path}"); - *slot = Some((std::fs::File::create(&path).expect("ecdump file"), path)); - } - // lane-av1dumploud: loud on a short write. This file is one line - // per symbol for a whole run, so its total length is unknowable at - // open time -- the failure line says "an unknown number of" rather - // than declaring a length it would have to invent. - let (file, path) = slot.as_mut().expect("just opened"); - if let Err(e) = file.write_all(line.as_bytes()) { - panic!( - "ec-av1 dump FAILED [EC_AV1_ECDUMP] {path}: \ - write failed after a partial line of {} bytes: {e}", - line.len() - ); - } - }); - ECD.with(|q| { - let mut q = q.borrow_mut(); - q.push_back((low, value, rng, bitpos as u32)); - if q.len() > 512 { - q.pop_front(); - } - }); - } - - /// lane-av1mix: the last `n` dumped register states (most recent last). - #[allow(dead_code)] // diagnostic helper for lane sessions - pub(crate) fn ecdump_recent(n: usize) -> Vec<(u32, u32, u32, u32)> { - if std::env::var_os("EC_AV1_ECDUMP").is_none() { - return Vec::new(); - } - ECD.with(|q| { - let q = q.borrow(); - let skip = q.len().saturating_sub(n); - q.iter().skip(skip).copied().collect() - }) - } - - pub(crate) fn dir() -> Option<&'static str> { - DIR.get_or_init(|| { - crate::envflags::var("EC_AV1_SYMTRACE") - .ok() - .filter(|v| !v.is_empty()) - }) - .as_deref() - } - - /// lane-av1mix: `EC_AV1_ECDUMP=` arms the decoder state-register dump. - pub(crate) fn ecdump_armed() -> bool { - static ARMED: std::sync::LazyLock = - std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_ECDUMP").is_some()); - *ARMED - } - - /// `EC_AV1_SYMTRACE_AT=` or `=:` (inclusive). - fn at() -> Option<(usize, usize)> { - *AT.get_or_init(|| { - let v = crate::envflags::var("EC_AV1_SYMTRACE_AT").ok()?; - let (a, b) = v.split_once(':').unwrap_or((v.as_str(), v.as_str())); - Some((a.parse().ok()?, b.parse().ok()?)) - }) - } - - /// A caller's own annotation, interleaved with this coder's symbol lines - /// (`# ...`) so the writer/reader diff shows the state around a desync. - pub(crate) fn note(line: &str) { - if dir().is_none() { - return; - } - BUF.with(|b| { - let (buf, _) = &mut *b.borrow_mut(); - buf.push_str("# "); - buf.push_str(line); - buf.push('\n'); - }); - } - - pub(crate) fn push(value: usize, nsyms: usize, cdf0: u16) { - BUF.with(|b| { - let (buf, n) = &mut *b.borrow_mut(); - if at().is_some_and(|(a, b)| (a..=b).contains(n)) { - eprintln!( - "SYMTRACE at {n}: {}", - std::backtrace::Backtrace::force_capture() - ); - } - buf.push_str(&format!("{n} {value} {nsyms} {cdf0}\n")); - *n += 1; - }); - } - - /// Flushes this coder's lines as `/-.txt` and starts the - /// next coder's trace. - pub(crate) fn flush(side: char) { - let Some(dir) = dir() else { return }; - BUF.with(|b| { - let (buf, n) = &mut *b.borrow_mut(); - if !buf.is_empty() { - // lane-av1dumploud: loud on a short write. `std::fs::write` - // returned a `Result` this used to discard, and the check was - // hand-rolled against the buffer length only; lane-av1pinloud - // folded it into the shared writer so this site also gets the - // on-disk length check the dump path already had. - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - crate::dumpio::pin( - "EC_AV1_SYMTRACE", - format!("{dir}/{side}-{seq:05}.txt"), - buf.as_bytes(), - ); - } - buf.clear(); - *n = 0; - }); - } -} diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index f16d1067..986bf677 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -77,7 +77,6 @@ //! added by the row/col scan), and the "extra search" that pads a short //! stack to two entries (spec 7.10.2.12) — this module's stack can be //! shorter than two candidates where libaom's never is. -use crate::hits::hit; thread_local! { /// How many query blocks [`find_mv_stack_with_sign_bias`] has folded at @@ -93,14 +92,6 @@ thread_local! { static TMV_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The number of query blocks that received at least one temporal MV -/// candidate so far, across every [`find_mv_stack_with_sign_bias`] call in -/// this process. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tmv_hits() -> usize { - TMV_HITS.with(|c| c.get()) -} - thread_local! { /// lane-mvtwin r1 firing counters, one per divergence this round closed. /// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot @@ -118,24 +109,6 @@ thread_local! { static TILE_REACH_CLIPS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// [`COMP_GM_FILL_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn comp_gm_fill_hits() -> usize { - COMP_GM_FILL_HITS.with(|c| c.get()) -} - -/// [`STACK_FULL_DROPS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn stack_full_drops() -> usize { - STACK_FULL_DROPS.with(|c| c.get()) -} - -/// [`TILE_REACH_CLIPS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn tile_reach_clips() -> usize { - TILE_REACH_CLIPS.with(|c| c.get()) -} - /// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV /// candidates into a block's stack (spec 7.10.2.8, only reached when the /// frame header's own `use_ref_frame_mvs` is set): the current frame's own @@ -432,10 +405,8 @@ impl MiGrid { for r in row..(row + h).min(self.rows) { let c1 = (col + w).min(self.cols); let n = c1 - col; - self.cells[r * self.cols + col..r * self.cols + c1] - .copy_from_slice(&snap.0[i..i + n]); - self.skips[r * self.cols + col..r * self.cols + c1] - .copy_from_slice(&snap.1[i..i + n]); + self.cells[r * self.cols + col..r * self.cols + c1].copy_from_slice(&snap.0[i..i + n]); + self.skips[r * self.cols + col..r * self.cols + c1].copy_from_slice(&snap.1[i..i + n]); i += n; } } @@ -693,7 +664,6 @@ fn add_candidate(candidates: &mut StackVec, mv: (i32, i32), weight: u32) { if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) { entry.weight += weight; } else if candidates.len() >= MAX_STACK_SIZE { - hit!(STACK_FULL_DROPS); } else { // libaom `add_ref_mv_candidate` (mvref_common.c:100) and // `add_tpl_ref_mv` (:388) only push when @@ -862,8 +832,11 @@ fn scan_row( }; // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf). - let col_shift: usize = - if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { 1 } else { 0 }; + let col_shift: usize = if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { + 1 + } else { + 0 + }; let use_step_16 = bw4 >= 16; let end_mi = bw4.min(16); let mut found = false; @@ -950,8 +923,11 @@ fn scan_col( }; // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row // under a 4-high block. - let row_shift: usize = - if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { 1 } else { 0 }; + let row_shift: usize = if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { + 1 + } else { + 0 + }; let use_step_16 = bh4 >= 16; let end_mi = bh4.min(16); let mut found = false; @@ -1023,7 +999,13 @@ fn top_right_scan_allowed(bw4: usize, bh4: usize) -> bool { /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A /// partition whose warp-sample top-right probe may answer 1 where libaom says /// 0; upgrade path = thread `partition` into this call. -pub(crate) fn has_top_right(mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, fctx: &crate::decode::FrameCtx) -> bool { +pub(crate) fn has_top_right( + mi_row: usize, + mi_col: usize, + bw4: usize, + bh4: usize, + fctx: &crate::decode::FrameCtx, +) -> bool { let sb_mi_size = crate::decode::sb_mi_cur(fctx) as usize; let bs0 = bw4.max(bh4); if bs0 > 16 { @@ -1170,14 +1152,6 @@ fn clamp_mv_ref( let to_right = signed(mi_cols, bw4, mi_col); let to_top = -to_subpel(mi_row); let to_bottom = signed(mi_rows, bh4, mi_row); - if to_right < 0 || to_bottom < 0 { - let (row, col) = mv; - let clamped_row = row.clamp(to_top - bh8 - MV_BORDER, to_bottom + bh8 + MV_BORDER); - let clamped_col = col.clamp(to_left - bw8 - MV_BORDER, to_right + bw8 + MV_BORDER); - if clamped_row != row || clamped_col != col { - hit!(MV_CLAMP_EDGE_OVERHANG_HITS); - } - } let (row, col) = mv; ( @@ -1414,9 +1388,6 @@ pub fn find_mv_stack_with_sign_bias( // (and so the stack ORDER) even though `MiGrid::get` already returns // `None` for the cells outside the tile. let (tile_row0, tile_col0) = grid.tile_origin(); - if tile_row0 > 0 || tile_col0 > 0 { - hit!(TILE_REACH_CLIPS); - } let max_row_offset: isize = if mi_row > tile_row0 { let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); reach.max(tile_row0 as isize - mi_row as isize) @@ -1511,7 +1482,6 @@ pub fn find_mv_stack_with_sign_bias( force_integer_mv, }) = tpl { - let mut any_hit = false; let voffset = bh4.max(2); let hoffset = bw4.max(2); let blk_row_end = bh4.min(16); @@ -1547,12 +1517,11 @@ pub fn find_mv_stack_with_sign_bias( let mut blk_col = 0usize; while blk_col < blk_col_end { if let Some(mv) = sample(blk_row as isize, blk_col as isize) { - any_hit = true; if blk_row == 0 && blk_col == 0 { first_sample_missing = false; let this_gm_mv = gm_mv(gm, ref_frame); - first_sample_far = (mv.0 - this_gm_mv.0).abs() >= 16 - || (mv.1 - this_gm_mv.1).abs() >= 16; + first_sample_far = + (mv.0 - this_gm_mv.0).abs() >= 16 || (mv.1 - this_gm_mv.1).abs() >= 16; } add_candidate(&mut candidates, mv, 2); } @@ -1578,14 +1547,10 @@ pub fn find_mv_stack_with_sign_bias( continue; } if let Some(mv) = sample(row_off, col_off) { - any_hit = true; add_candidate(&mut candidates, mv, 2); } } } - if any_hit { - hit!(TMV_HITS); - } zero_mv_ctx = usize::from(first_sample_missing || first_sample_far); } @@ -1863,24 +1828,6 @@ pub fn find_mv_stack_with_sign_bias( .checked_sub(1) .is_some_and(|c| grid.skip_at(mi_row, c)); - // lane-sb128b: the writer/reader stack diff instrument (`EC_AV1_MVDBG=1`) - // -- one line per built stack, in build order, so the two sides' logs - // diff to the first block whose candidate list differs. - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - "MVDBG mi=({mi_row},{mi_col}) b=({bw4}x{bh4}) ref={ref_frame} n={} mv={:?}", - candidates.len(), - candidates.iter().map(|e| (e.mv, e.weight)).collect::>(), - )); - let row = mi_row.checked_sub(1).map(|r| { - (mi_col..mi_col + bw4).map(|c| grid.get(r, c).map(|m| (m.ref_frame, m.mv))).collect::>() - }); - let col = mi_col.checked_sub(1).map(|c| { - (mi_row..mi_row + bh4).map(|r| grid.get(r, c).map(|m| (m.ref_frame, m.mv))).collect::>() - }); - crate::msac::symtrace::note(&format!(" above={row:?}")); - crate::msac::symtrace::note(&format!(" left={col:?}")); - } MvStack { entries: candidates, nearest_mv, @@ -1949,7 +1896,6 @@ fn add_compound_candidate( if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) { entry.weight += weight; } else if candidates.len() >= MAX_STACK_SIZE { - hit!(STACK_FULL_DROPS); } else { // Same insertion cap as [`add_candidate`]: libaom's compound branch // of `add_ref_mv_candidate` (mvref_common.c:128) and `add_tpl_ref_mv` @@ -1985,8 +1931,11 @@ fn scan_row_compound( }; // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf). - let col_shift: usize = - if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { 1 } else { 0 }; + let col_shift: usize = if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { + 1 + } else { + 0 + }; let use_step_16 = bw4 >= 16; let end_mi = bw4.min(16); let mut found = false; @@ -2012,12 +1961,24 @@ fn scan_row_compound( weight = weight.max(inc as u32); *processed_rows = (inc as isize - row_offset - 1).max(0) as usize; } - if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1 { + if info.is_inter + && info.ref_frame == ref_frame.0 + && info.ref_frame1 > 0 + && info.ref_frame1 == ref_frame.1 + { found = true; add_compound_candidate( candidates, - if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) }, - if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) }, + if info.is_global_mv0 { + gm_mv(gm, ref_frame.0) + } else { + mv32(info.mv) + }, + if info.is_global_mv1 { + gm_mv(gm, ref_frame.1) + } else { + mv32(info.mv1) + }, len as u32 * weight, ); *newmv_count += u32::from(info.is_new_mv); @@ -2048,8 +2009,11 @@ fn scan_col_compound( }; // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row // under a 4-high block. - let row_shift: usize = - if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { 1 } else { 0 }; + let row_shift: usize = if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { + 1 + } else { + 0 + }; let use_step_16 = bh4 >= 16; let end_mi = bh4.min(16); let mut found = false; @@ -2075,12 +2039,24 @@ fn scan_col_compound( weight = weight.max(inc as u32); *processed_cols = (inc as isize - col_offset - 1).max(0) as usize; } - if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1 { + if info.is_inter + && info.ref_frame == ref_frame.0 + && info.ref_frame1 > 0 + && info.ref_frame1 == ref_frame.1 + { found = true; add_compound_candidate( candidates, - if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) }, - if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) }, + if info.is_global_mv0 { + gm_mv(gm, ref_frame.0) + } else { + mv32(info.mv) + }, + if info.is_global_mv1 { + gm_mv(gm, ref_frame.1) + } else { + mv32(info.mv1) + }, len as u32 * weight, ); *newmv_count += u32::from(info.is_new_mv); @@ -2109,12 +2085,21 @@ fn scan_top_right_compound( if let Some(info) = grid.get(row, col) && info.is_inter && info.ref_frame == ref_frame.0 - && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1 + && info.ref_frame1 > 0 + && info.ref_frame1 == ref_frame.1 { add_compound_candidate( candidates, - if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) }, - if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) }, + if info.is_global_mv0 { + gm_mv(gm, ref_frame.0) + } else { + mv32(info.mv) + }, + if info.is_global_mv1 { + gm_mv(gm, ref_frame.1) + } else { + mv32(info.mv1) + }, CORNER_WEIGHT, ); *newmv_count += u32::from(info.is_new_mv); @@ -2139,12 +2124,21 @@ fn scan_corner_compound( if let Some(info) = grid.get(row, col) && info.is_inter && info.ref_frame == ref_frame.0 - && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1 + && info.ref_frame1 > 0 + && info.ref_frame1 == ref_frame.1 { add_compound_candidate( candidates, - if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) }, - if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) }, + if info.is_global_mv0 { + gm_mv(gm, ref_frame.0) + } else { + mv32(info.mv) + }, + if info.is_global_mv1 { + gm_mv(gm, ref_frame.1) + } else { + mv32(info.mv1) + }, CORNER_WEIGHT, ); *newmv_count += u32::from(info.is_new_mv); @@ -2232,12 +2226,10 @@ fn combine_compound_candidates( .copied() .collect(); std::array::from_fn(|i| { - merged.get(i).copied().unwrap_or_else(|| { - if gm_mv_candidates[side] != (0, 0) { - hit!(COMP_GM_FILL_HITS); - } - gm_mv_candidates[side] - }) + merged + .get(i) + .copied() + .unwrap_or_else(|| gm_mv_candidates[side]) }) }; let side0 = side_slots(0); @@ -2292,9 +2284,6 @@ pub fn find_mv_stack_compound( // (and so the stack ORDER) even though `MiGrid::get` already returns // `None` for the cells outside the tile. let (tile_row0, tile_col0) = grid.tile_origin(); - if tile_row0 > 0 || tile_col0 > 0 { - hit!(TILE_REACH_CLIPS); - } let max_row_offset: isize = if mi_row > tile_row0 { let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); reach.max(tile_row0 as isize - mi_row as isize) @@ -2381,7 +2370,6 @@ pub fn find_mv_stack_compound( force_integer_mv, }) = tpl { - let mut any_hit = false; let blk_row_end = bh4.min(16); let blk_col_end = bw4.min(16); let step_h = if bh4 >= 16 { 4 } else { 2 }; @@ -2415,7 +2403,6 @@ pub fn find_mv_stack_compound( let mut blk_col = 0usize; while blk_col < blk_col_end { if let Some((mv0, mv1)) = sample(blk_row as isize, blk_col as isize) { - any_hit = true; if blk_row == 0 && blk_col == 0 { first_sample_missing = false; let this_gm0 = gm_mv(gm, ref_frame.0); @@ -2454,14 +2441,10 @@ pub fn find_mv_stack_compound( continue; } if let Some((mv0, mv1)) = sample(row_off, col_off) { - any_hit = true; add_compound_candidate(&mut candidates, mv0, mv1, 2); } } } - if any_hit { - hit!(TMV_HITS); - } zero_mv_ctx = usize::from(first_sample_missing || first_sample_far); } @@ -2730,8 +2713,16 @@ fn ref_ctx( b_set: &[i8], ) -> usize { let refs = [above0, above1, left0, left1]; - let a = refs.into_iter().flatten().filter(|r| a_set.contains(r)).count(); - let b = refs.into_iter().flatten().filter(|r| b_set.contains(r)).count(); + let a = refs + .into_iter() + .flatten() + .filter(|r| a_set.contains(r)) + .count(); + let b = refs + .into_iter() + .flatten() + .filter(|r| b_set.contains(r)) + .count(); match a.cmp(&b) { std::cmp::Ordering::Less => 0, std::cmp::Ordering::Equal => 1, @@ -2807,7 +2798,14 @@ pub(crate) fn single_ref_p5_ctx( left0: Option, left1: Option, ) -> usize { - ref_ctx(above0, above1, left0, left1, &[LAST3_FRAME], &[GOLDEN_FRAME]) + ref_ctx( + above0, + above1, + left0, + left1, + &[LAST3_FRAME], + &[GOLDEN_FRAME], + ) } /// `av1_get_pred_context_single_ref_p6` @@ -2818,7 +2816,14 @@ pub(crate) fn single_ref_p6_ctx( left0: Option, left1: Option, ) -> usize { - ref_ctx(above0, above1, left0, left1, &[BWDREF_FRAME], &[ALTREF2_FRAME]) + ref_ctx( + above0, + above1, + left0, + left1, + &[BWDREF_FRAME], + &[ALTREF2_FRAME], + ) } /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`, @@ -2960,7 +2965,6 @@ mod tests { use super::*; - /// lane-mvstack2: the mi grid is one cell per 4x4 unit of the frame and /// `find_mv_stack` walks it for every inter block, so the cell's SIZE is /// the scan's memory traffic. `ref_frame1`/`mv1` are validity-tagged by @@ -3555,7 +3559,19 @@ mod tests { let (mv0, mv1) = ((2, 2), (-6, 3)); grid.set(2, 1, comp_inter(mv0, mv1)); - let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None); + let stack = find_mv_stack_compound( + &grid, + 2, + 2, + 2, + 2, + COMP_PAIR, + 8, + 8, + &NO_SIGN_BIAS, + &NO_GM_MV, + None, + ); // The exact-pair immediate scan lands one boosted entry; the // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES) @@ -3579,7 +3595,19 @@ mod tests { grid.set(2, 1, comp_inter(mv0, mv1)); grid.set(3, 1, comp_inter(mv0, mv1)); - let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None); + let stack = find_mv_stack_compound( + &grid, + 2, + 2, + 2, + 2, + COMP_PAIR, + 8, + 8, + &NO_SIGN_BIAS, + &NO_GM_MV, + None, + ); // Exact libaom `is_dup` port: with exactly one entry already in the // stack (the four identical-pair neighbours deduped by the @@ -3611,7 +3639,19 @@ mod tests { grid.set(4, 2, comp_inter(left.0, left.1)); grid.set(5, 2, comp_inter(left.0, left.1)); - let stack = find_mv_stack_compound(&grid, 3, 3, 2, 3, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None); + let stack = find_mv_stack_compound( + &grid, + 3, + 3, + 2, + 3, + COMP_PAIR, + 8, + 8, + &NO_SIGN_BIAS, + &NO_GM_MV, + None, + ); assert_eq!(stack.entries.len(), 2); assert_eq!(stack.entries[0].mv0, left.0); @@ -3700,7 +3740,19 @@ mod tests { }, ); - let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None); + let stack = find_mv_stack_compound( + &grid, + 2, + 2, + 2, + 2, + COMP_PAIR, + 8, + 8, + &NO_SIGN_BIAS, + &NO_GM_MV, + None, + ); // The combine step (libaom's real "Handle compound reference frame // extension") zips each side's ref_id-then-ref_diff lists @@ -3750,11 +3802,9 @@ mod tests { for i in 0..MAX_STACK_SIZE as i32 { add_candidate(&mut candidates, (i, i), 2); } - let before = stack_full_drops(); add_candidate(&mut candidates, (99, 99), 10_000); assert_eq!(candidates.len(), MAX_STACK_SIZE); assert!(!candidates.iter().any(|e| e.mv == (99, 99))); - assert_eq!(stack_full_drops(), before + 1); // A full stack still takes the dedup weight bump libaom applies // before the cap check. add_candidate(&mut candidates, (0, 0), 6); @@ -3821,7 +3871,9 @@ mod tests { let clamped = clamp_mv_ref((384, -320), 400, 368, 16, 16, 960, 402); assert_eq!(clamped, (192, -320)); // A block fully inside the frame keeps the wide window. - assert_eq!(clamp_mv_ref((384, -320), 100, 368, 16, 16, 960, 402), (384, -320)); + assert_eq!( + clamp_mv_ref((384, -320), 100, 368, 16, 16, 960, 402), + (384, -320) + ); } - } diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs index 1e0aabb6..7668c018 100644 --- a/crates/ec-av1/src/par.rs +++ b/crates/ec-av1/src/par.rs @@ -86,14 +86,6 @@ pub(crate) fn filter_threads() -> usize { } } -/// Test-only override of [`filter_threads`]. Process-global, so a gate using -/// it must hold `stream.rs`'s gate-counter lock (which also keeps the -/// counter-delta gates from decoding while the workers are on). -#[cfg(test)] -pub(crate) fn set_filter_threads(n: usize) { - FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); -} - /// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's /// tiles across -- both the RD/motion SEARCH (`encode::search_tiles`) and the /// entropy WRITE (`encode::write_tiles`); default 1 = the shipped @@ -196,7 +188,10 @@ pub(crate) fn run_bands_mut( /// Carves `data` into one `&mut` slice per element range, `ranges` ascending /// and non-overlapping (`split_at_mut` only, so no `unsafe`). Elements outside /// every range are left alone. -pub(crate) fn carve_ranges<'a, T>(data: &'a mut [T], ranges: &[(usize, usize)]) -> Vec<&'a mut [T]> { +pub(crate) fn carve_ranges<'a, T>( + data: &'a mut [T], + ranges: &[(usize, usize)], +) -> Vec<&'a mut [T]> { split_bands_mut(ranges, 1, data) } @@ -341,12 +336,6 @@ pub(crate) fn recon_threads() -> usize { } } -/// Test-only override of [`recon_threads`] -- see [`set_filter_threads`]. -#[cfg(test)] -pub(crate) fn set_recon_threads(n: usize) { - RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); -} - // --- lane-pool1: persistent worker pools --------------------------------- // // Every threaded stage of the decoder used to spawn its threads per unit of @@ -687,8 +676,7 @@ pub(crate) const S_FIRST: usize = 9; static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] = [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()]; -/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or -/// [`set_stage_times`] from a gate (the env snapshot is process-constant). +/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES` (the env snapshot is process-constant). static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); pub(crate) fn stage_times() -> bool { @@ -702,12 +690,6 @@ pub(crate) fn stage_times() -> bool { } } -/// Test-only override of [`stage_times`]; process-global. -#[cfg(test)] -pub(crate) fn set_stage_times(on: bool) { - STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed); -} - /// A live stage measurement: added to stage `i` when it drops. `None` when /// the breakdown is off, so a call site is `let _t = par::timer(S_X);`. pub(crate) struct Timer(usize, std::time::Instant); @@ -719,13 +701,9 @@ pub(crate) fn timer(i: usize) -> Option { impl Drop for Timer { fn drop(&mut self) { - STAGE_NS[self.0] - .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + STAGE_NS[self.0].fetch_add( + self.1.elapsed().as_nanos() as u64, + std::sync::atomic::Ordering::Relaxed, + ); } } - -/// Takes and clears the breakdown, in [`STAGES`] order. -#[cfg(test)] -pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] { - std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} diff --git a/crates/ec-av1/src/probe.rs b/crates/ec-av1/src/probe.rs index 9cd42902..4fc2a6ec 100644 --- a/crates/ec-av1/src/probe.rs +++ b/crates/ec-av1/src/probe.rs @@ -12,47 +12,6 @@ use crate::encode::Picture; #[cfg(test)] use std::process::Command; -/// The video stream's coded size, from ffprobe. -#[must_use] -pub fn dims(clip: &str) -> Option<(usize, usize)> { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-select_streams", "v:0"]) - .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"]) - .arg(clip) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stdout); - let mut f = text.trim().split(','); - Some(( - f.next()?.trim().parse().ok()?, - f.next()?.trim().parse().ok()?, - )) -} - -/// The native BD gate's window on `clip`: a whole number of 128-wide -/// superblocks, at most 1920x1024, out of the MIDDLE of the coded frame, with -/// even offsets for 4:2:0 -- as an ffmpeg `crop` filter plus its size. -/// -/// This lives here because the probe used to be handed the crop by hand, and -/// a hand-written `crop=1920:1024:960:568` (a 2160-high frame that film B, -/// coded 3840x1608, is not) put the instrument on different pixels than the -/// gate: 60 kB where the gate's own q=150 point coded 90 kB. -/// -/// # Panics -/// When ffprobe cannot read the size, or the frame is under one superblock. -#[must_use] -pub fn gate_crop(clip: &str) -> (String, usize, usize) { - let (nw, nh) = dims(clip).expect("ffprobe gave no size"); - let cw = nw.min(1920) / 128 * 128; - let ch = nh.min(1024) / 128 * 128; - assert!( - cw >= 128 && ch >= 128, - "{nw}x{nh} is smaller than a superblock" - ); - let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1); - (format!("crop={cw}:{ch}:{x}:{y}"), cw, ch) -} - /// `frames` pictures of `clip` from `skip` through the filter chain `vf`, as /// planar 8-bit 4:2:0 at `width`x`height` -- the BD gate's loader recipe. /// diff --git a/crates/ec-av1/src/quant.rs b/crates/ec-av1/src/quant.rs index 87a0c037..1b65f18c 100644 --- a/crates/ec-av1/src/quant.rs +++ b/crates/ec-av1/src/quant.rs @@ -216,8 +216,6 @@ pub fn dequant_coeff_wh( dq2.clamp(-bound, bound - 1) as i32 } -use crate::hits::hit_do; - thread_local! { /// lane-av1-qmatrix: transform units whose dequantisation actually /// scaled at least one NONZERO level through a quantisation matrix -- @@ -227,18 +225,6 @@ thread_local! { static QM_SCALED_UNITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Current value of [`QM_SCALED_UNITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn qm_scaled_units() -> usize { - QM_SCALED_UNITS.with(|c| c.get()) -} - -/// Zeroes [`QM_SCALED_UNITS`] (the witness gate's per-arm reset). -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn reset_qm_scaled_units() { - QM_SCALED_UNITS.with(|c| c.set(0)); -} - /// Dequantize a whole raster-order coefficient grid of a `side` x `side` /// transform. pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec { @@ -304,11 +290,6 @@ pub fn dequant_wh_into( let dq2 = sign * ((dq.abs() & 0xFF_FFFF) / denom); dq2.clamp(-bound, bound - 1) as i32 }; - hit_do! { - if qm.is_some() && levels.iter().any(|&l| l != 0) { - QM_SCALED_UNITS.with(|c| c.set(c.get() + 1)); - } - } out.clear(); out.reserve(levels.len()); out.extend( diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index 239dde13..696dc6a2 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -4,7 +4,6 @@ //! two pixel filters (Wiener, self-guided/SGR). See `lanes/lr.report.md` for //! the full derivation (libaom `decodeframe.c`/`restoration.c` line refs). use archmage::SimdToken; -use crate::hits::hit; use crate::msac::SymbolDecoder; use ec_av1_syntax::obu::floor_log2; @@ -610,35 +609,6 @@ thread_local! { const MI_SIZE_8PX: u32 = 8; /// `SCALE_NUMERATOR` (aom_scale.h): the superres scale's fixed point, 8. const SCALE_NUMERATOR: u32 = 8; -/// Current value of [`LR_STRIPE0_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lr_stripe0_hits() -> usize { - LR_STRIPE0_HITS.with(|c| c.get()) -} -/// Current value of [`LR_LAST_STRIPE_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn lr_last_stripe_hits() -> usize { - LR_LAST_STRIPE_HITS.with(|c| c.get()) -} - -/// Current value of [`WIENER_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn wiener_hits() -> usize { - WIENER_HITS.with(|c| c.get()) -} -/// Current value of [`SGRPROJ_HITS`]. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn sgrproj_hits() -> usize { - SGRPROJ_HITS.with(|c| c.get()) -} -/// Current value of [`SWITCHABLE_HITS`] -- bumped once per unit whose frame -/// `restoration_type` is `Switchable`, regardless of which `RestoreType` -/// (`None`/Wiener/Sgrproj) that unit's own symbol resolved to. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn switchable_hits() -> usize { - SWITCHABLE_HITS.with(|c| c.get()) -} - fn read_lr_unit( dec: &mut SymbolDecoder, cdfs: &mut crate::cdf_state::Cdfs, @@ -648,23 +618,15 @@ fn read_lr_unit( ) -> UnitFilter { match ftype { RestorationType::Switchable => { - hit!(SWITCHABLE_HITS); let t = dec.symbol(&mut cdfs.restore_switchable); match t { 0 => UnitFilter::None, - 1 => { - hit!(WIENER_HITS); - UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)) - } - _ => { - hit!(SGRPROJ_HITS); - UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)) - } + 1 => UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)), + _ => UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)), } } RestorationType::Wiener => { if dec.symbol(&mut cdfs.restore_wiener) != 0 { - hit!(WIENER_HITS); UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)) } else { UnitFilter::None @@ -673,7 +635,6 @@ fn read_lr_unit( RestorationType::Sgrproj => { let bit = dec.symbol(&mut cdfs.restore_sgrproj); if bit != 0 { - hit!(SGRPROJ_HITS); UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)) } else { UnitFilter::None @@ -1187,7 +1148,7 @@ fn ab_row( /// [`ab_row`]'s AVX2 kernel. #[cfg(target_arch = "x86_64")] mod sgr_simd { - use super::{SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS, SGR_X_BY_XPLUS1}; + use super::{SGR_X_BY_XPLUS1, SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS}; use archmage::{X64V3Token, arcane}; use std::arch::x86_64::*; @@ -1467,8 +1428,8 @@ fn apply_sgrproj_stripe( } } let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, smax) as u16; - out[(v_start as i64 + i - row0 as i64) as usize * stride + (h_start as i64 + j) as usize] = - out_v; + out[(v_start as i64 + i - row0 as i64) as usize * stride + + (h_start as i64 + j) as usize] = out_v; } } SGR_AB_SCRATCH.with(|c| *c.borrow_mut() = (buf0, buf1)); @@ -1508,14 +1469,6 @@ fn filter_restoration_unit( let nominal_h = full_stripe_height - if frame_stripe == 0 { runit_offset } else { 0 }; let h = nominal_h.min(unit_h - i); let stripe_v_end = stripe_v_start + h; - if !matches!(filter, UnitFilter::None) { - if stripe_v_start == 0 { - hit!(LR_STRIPE0_HITS); - } - if stripe_v_end == plane_h && h < nominal_h { - hit!(LR_LAST_STRIPE_HITS); - } - } match filter { UnitFilter::Wiener(info) => apply_wiener_stripe( out, @@ -1596,20 +1549,27 @@ pub(crate) fn apply_loop_restoration_plane( } // Each band's RU rows write one contiguous run of `out` rows (the // rows run `v_start..v_end` back to back), so a band owns its own slice. - let pbands: Vec<(usize, usize)> = crate::par::bands(rows.len(), crate::par::filter_threads()) - .into_iter() - .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize)) - .collect(); - crate::par::run_bands_mut(&pbands, stride, fctx, out.as_mut_slice(), |lo, hi, mine, fctx| { - let r_lo = rows.partition_point(|r| (r.0 as usize) < lo); - let r_hi = rows.partition_point(|r| (r.0 as usize) < hi); - for rrow in r_lo..r_hi { - lr_unit_row( - mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, - plane, rrow, &rows, fctx, - ); - } - }); + let pbands: Vec<(usize, usize)> = + crate::par::bands(rows.len(), crate::par::filter_threads()) + .into_iter() + .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize)) + .collect(); + crate::par::run_bands_mut( + &pbands, + stride, + fctx, + out.as_mut_slice(), + |lo, hi, mine, fctx| { + let r_lo = rows.partition_point(|r| (r.0 as usize) < lo); + let r_hi = rows.partition_point(|r| (r.0 as usize) < hi); + for rrow in r_lo..r_hi { + lr_unit_row( + mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, + plane, rrow, &rows, fctx, + ); + } + }, + ); debug_assert_eq!( rows.len(), grid.vert_units[plane], @@ -1622,8 +1582,8 @@ pub(crate) fn apply_loop_restoration_plane( let (a, b) = (v_start as usize * stride, v_end as usize * stride); out[a..b].copy_from_slice(&cdef[a..b]); lr_unit_row( - out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, - rrow, &rows, fctx, + out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow, + &rows, fctx, ); } } diff --git a/crates/ec-av1/src/stack_budget.rs b/crates/ec-av1/src/stack_budget.rs deleted file mode 100644 index d57e2d3a..00000000 --- a/crates/ec-av1/src/stack_budget.rs +++ /dev/null @@ -1,990 +0,0 @@ -#![cfg(test)] -//! A measured bound on the crate's BY-VALUE types, and a gate that bites. -//! -//! # The class -//! -//! A large struct returned BY VALUE from a public constructor is a stack cost, -//! not a heap cost, and the cost is paid by the CALLER. The constructors here -//! nest -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the -//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` -> -//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a -//! frame -- and in an unoptimized build each level materialises its whole -//! `Result` return slot before the inner call returns. So one value's -//! `size_of` is the MULTIPLIER, and the chain length is the other factor. -//! -//! That is not hypothetical. `Av1Encoder` was 139960 bytes by value (eight -//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error: -//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified -//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it -//! from this workspace's own runs -- a band-aid a library consumer does not -//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and -//! gated the constructors on a 1 MiB thread. -//! -//! # Why this module exists when that gate already exists -//! -//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the -//! next 15 KB inline table from landing, and nothing said which types had been -//! checked. This module is the sweep: -//! -//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate -//! that a public `fn` can return by value, with a measured `size_of` floor -//! recorded as of this commit. -//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so -//! the table cannot rot into a list of stale small numbers. -//! 2. [`STACK_BUDGET`] is the bound, and -//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for -//! every row, so a regression reds naming the type that caused it. -//! 3. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the -//! capability arm: it really constructs the heavy types on a deliberately -//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly -//! costing margin. Red/green in milliseconds. -//! 4. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's -//! teeth against NEW types: a source scan re-derives the set of by-value -//! public returns from the crate source, so a lane that adds a 40 KB struct -//! to a `pub fn` return reds here until it is measured and listed. -//! [`the_inventory_scan_is_not_vacuous`] is its control. -//! -//! # The bound, and why this number -//! -//! [`STACK_BUDGET`] = 8192 bytes (8 KiB). It is bounded from BOTH sides by -//! measurement, and both sides are asserted in -//! [`every_by_value_type_fits_the_stack_budget`] so neither can rot silently. -//! -//! **The quantity being bounded.** Not `size_of` in the abstract, but *what a -//! caller can be made to owe*: the size of one by-value return, multiplied by -//! how many constructor levels hold a copy of it at once. Three inputs: -//! -//! 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.** -//! Measured, not assumed, by -//! [`test_threads_get_the_stack_they_are_given`] reading -//! `/proc/self/task//maps`. That is libtest's default test thread and -//! also what `std::thread::Builder::new()` gives a caller who does not ask -//! for a size. A library consumer gets no `.cargo/config.toml`. -//! 2. **The deepest PUBLIC by-value chain is 4** ([`DEEPEST_PUBLIC_CHAIN`]): -//! `encode_key_frame` -> `encode_key_frame_with_ctx` -> -//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner`. The -//! encoder's own nest is 3. The test asserts -//! `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- i.e. the by-value return -//! slots may claim at most an EIGHTH of a caller's stack, leaving the rest -//! for the encode search, which is the thing that actually needs it. -//! 3. **The budget applies only to types a `pub fn` returns.** The -//! crate-private 15,232-byte `Cdfs` / `CdfSnapshot` are measured and listed -//! but are NOT bounded, because no caller can reach them by value -- every -//! field that holds one is a `Box`, which -//! [`the_crate_private_cdf_tables_stay_behind_a_box`] pins by source. -//! Bounding them would calibrate the number to something unreachable. -//! -//! **Where the number sits.** At 8 KiB with the worst public return at 2,944 -//! bytes ([`Av1Encoder`]), the worst a caller owes is -//! `4 x 2944 = 11,776` bytes -- **0.56%** of a 2 MiB thread -- and the budget -//! itself is 2.78x above the incumbent. Both directions have room, which is -//! the point: a bound the largest type sits just under is a bound the next -//! lane will quietly raise. -//! -//! **What it catches.** A pre-fix `Av1Encoder` (139,960 B) is **17.1x over**. -//! `Encoded` as it stood before this lane boxed its two inline snapshots -//! (30,728 B) is **3.75x over**. `ec_opus::Encoder`, measured in a sibling -//! crate by the same sweep, is **10.6x over**. The historical defect, the -//! near-miss, and the largest live instance of the class in the workspace all -//! red by a factor, not by a hair. -//! -//! **What it does not claim.** `size_of` is layout, not stack depth. The -//! measured stack/size ratio on a by-value constructor is ~4.4x -//! (`ec_opus::Encoder`: 87,024 B of struct, ~384 KiB of live stack), which is -//! the nesting multiplier made visible. That residual is why -//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs for -//! real instead of trusting the arithmetic. - -#![cfg(test)] -//! A measured bound on the crate's BY-VALUE types, and a gate that bites. -//! -//! # The class -//! -//! A large struct returned BY VALUE from a public constructor is a stack cost, -//! not a heap cost, and the cost is paid by the CALLER. The constructors here -//! nest -- `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` for the -//! encoder, and `encode_key_frame` -> `encode_key_frame_with_ctx` -> -//! `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` for a -//! frame -- and in an unoptimized build each level materialises its whole -//! `Result` return slot before the inner call returns. So one value's -//! `size_of` is the MULTIPLIER, and the chain length is the other factor. -//! -//! That is not hypothetical. `Av1Encoder` was 139960 bytes by value (eight -//! inline `CdfSnapshot` DPB slots) and aborted with `fatal runtime error: -//! stack overflow, aborting` on libtest's 2 MiB thread, twice, on an unmodified -//! `main`. `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864` to hide it -//! from this workspace's own runs -- a band-aid a library consumer does not -//! get. lane-av1enchang boxed the per-slot snapshot (139960 -> 18168) and -//! gated the constructors on a 1 MiB thread. -//! -//! # Why this module exists when that gate already exists -//! -//! lane-av1enchang gated ONE type. The class was not swept: nothing stopped the -//! next 15 KB inline table from landing, and nothing said which types had been -//! checked. This module is the sweep: -//! -//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate -//! that a public `fn` can return by value, with a measured `size_of` floor -//! recorded as of this commit. -//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so -//! the table cannot rot into a list of stale small numbers. -//! 2. [`STACK_BUDGET`] is the bound, and -//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for -//! every row, so a regression reds naming the type that caused it. -//! 3. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the -//! capability arm: it really constructs the heavy types on a deliberately -//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly -//! costing margin. Red/green in milliseconds. -//! 4. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's -//! teeth against NEW types: a source scan re-derives the set of by-value -//! public returns from the crate source, so a lane that adds a 40 KB struct -//! to a `pub fn` return reds here until it is measured and listed. -//! [`the_inventory_scan_is_not_vacuous`] is its control. -//! -//! # The bound, and why this number -//! -//! [`STACK_BUDGET`] = 32768 bytes (32 KiB). The reasoning, from measured -//! numbers rather than taste: -//! -//! * The smallest stack a caller can hand this crate is **2101248 bytes**, -//! measured by [`test_threads_get_the_stack_they_are_given`] reading -//! `/proc/self/task//maps` for the region containing a running frame. -//! That is libtest's default test thread and also what -//! `std::thread::Builder::new()` hands a caller who does not ask for a size. -//! A library consumer gets no `.cargo/config.toml`. -//! * The deepest public by-value chain in this crate is FOUR frames, so the -//! worst live stack from return slots alone is `4 * size_of::()`. -//! * At 32 KiB that is 128 KiB: **6.1%** of a 2 MiB thread. A type at the -//! budget still leaves 94% of the caller's stack for its own work. -//! * 32 KiB is above every type here with headroom, and it is 2.14x below the -//! pre-fix `Av1Encoder`, so the historical defect reds by a factor rather -//! than by a hair. -//! -//! `Encoded` is at 30728, i.e. **93.8% of budget** and the one row with no -//! margin left. It is 99.2% two inline `CdfSnapshot`s, and boxing those two -//! fields is the next move in this class; the report says so. A budget the -//! current tree already violates is not a budget, it is a to-do list, and the -//! fix belongs in the lane that does the boxing. - -use crate::encode::Encoded; -use crate::encoder::Av1Encoder; - -/// The per-type ceiling for a type a CALLER can be made to hold by value, in -/// bytes. See the module docs for the derivation; it is two-sided, and both -/// sides are measured. -pub(crate) const STACK_BUDGET: usize = 8192; - -/// The deepest PUBLIC by-value constructor chain in this crate, counted from -/// the source: `encode_key_frame` -> `encode_key_frame_with_ctx` -> -/// `encode_key_frame_with_modes_with_ctx` -> `encode_key_frame_inner` is four, -/// and `with_pyramid_and_rate_target` -> `with_pyramid` -> `new` is three. The -/// budget is checked against four, the worse of the two. -#[cfg(test)] -const DEEPEST_PUBLIC_CHAIN: usize = 4; - -/// Every public type in this crate a public `fn` can return BY VALUE, with the -/// `size_of` measured at the commit that wrote this table. `None` means "not -/// yet measured", which [`the_measured_inventory_is_accurate`] rejects. -/// -/// The third column names the return path, so a reader can see why a type is -/// here rather than a coincidence of the type system. -pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ - // -- encoder.rs ------------------------------------------------------- - ( - "Av1Encoder", - Some(2728), - true, - "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \ - with_pyramid_and_rate_target, all `Result`, nesting three deep", - ), - ("EncoderConfig", Some(40), true, "EncoderConfig::new"), - ( - "Pyramid", - Some(24), - true, - "Pyramid's own ctor + Av1Encoder::pyramid", - ), - ( - "RateTarget", - Some(16), - true, - "constructor by value; carried in every Av1Encoder", - ), - ( - "Packet", - Some(48), - true, - "Av1Encoder::encode -> Result", - ), - // -- encode.rs -------------------------------------------------------- - ( - "Encoded", - Some(280), - true, - "encode_key_frame / encode_key_frame_with_modes / \ - encode_key_frame_at_size -> Result, nesting four deep", - ), - ( - "EncodedSequence", - Some(72), - true, - "encode_sequence -> Result", - ), - ("Picture", Some(88), true, "Picture::grey -> Self"), - // -- crate-private: never a public return, and every one of them is - // -- behind a Box now. The budget does not apply to these; the pin that - // -- does is `the_crate_private_cdf_tables_stay_behind_a_box`. - ( - "Cdfs", - Some(15232), - false, - "Cdfs::new(q_ctx) -> Cdfs; the payload of every CdfSnapshot. Not \ - reachable from a pub fn, and boxed everywhere it is stored", - ), - ( - "CdfSnapshot", - Some(15232), - false, - "crate-private newtype over Cdfs. Boxed in DpbSlot (lane-av1enchang), \ - in Av1Encoder::carried_cdfs and in both of Encoded's fields \ - (lane-av1stacksweep)", - ), - ( - "TxbTables", - Some(112), - false, - "Cdfs::txb -> TxbTables<'_>; nine BORROWED table slices, so the move \ - copies pointers, not tables", - ), - // -- decode.rs -------------------------------------------------------- - ( - "FrameCtx", - Some(1056), - false, - "FrameCtx::for_encoder() -> Self, pub(crate); one inline per Av1Encoder", - ), - // -- the small public surface ---------------------------------------- - ( - "SymbolEncoder", - Some(56), - true, - "msac::SymbolEncoder::new / pricer", - ), - ("SymbolDecoder", Some(64), true, "msac::SymbolDecoder::new"), - ( - "MiInfo", - Some(16), - true, - "mvstack::MvStack::get -> Option", - ), - ( - "WarpParams", - Some(32), - true, - "warp::global_warp_params -> Option", - ), - ("Iqm", Some(24), true, "qm::iwt_matrix -> Option"), - ("MvStack", Some(240), true, "mvstack::MvStack::new -> Self"), - ( - "Frame", - Some(352), - true, - "census::Frame rows, moved by value", - ), - ( - "InterpFilterKind", - Some(1), - true, - "mc::InterpFilterKind::from_switchable_symbol / from_header", - ), - ( - "TplProbe", - Some(48), - false, - "a borrowed-view handle the tile search passes around by value", - ), -]; - -/// The live `size_of` for every inventoried type, keyed BY NAME. -/// -/// Keyed rather than positional on purpose: `Packet` and `TplProbe` are both -/// 48 bytes, so a row inserted into [`BY_VALUE_TYPES`] without a matching -/// insert here would zip cleanly and assert the wrong type's size against the -/// wrong recorded one. A name key makes that mistake loud instead. -#[cfg(test)] -fn measured_by_name() -> Vec<(&'static str, usize)> { - vec![ - ("Av1Encoder", std::mem::size_of::()), - ( - "EncoderConfig", - std::mem::size_of::(), - ), - ("Pyramid", std::mem::size_of::()), - ( - "RateTarget", - std::mem::size_of::(), - ), - ("Packet", std::mem::size_of::()), - ("Encoded", std::mem::size_of::()), - ( - "EncodedSequence", - std::mem::size_of::(), - ), - ("Picture", std::mem::size_of::()), - ("Cdfs", std::mem::size_of::()), - ( - "CdfSnapshot", - std::mem::size_of::(), - ), - ( - "TxbTables", - std::mem::size_of::>(), - ), - ("FrameCtx", std::mem::size_of::()), - ( - "SymbolEncoder", - std::mem::size_of::(), - ), - ( - "SymbolDecoder", - std::mem::size_of::>(), - ), - ("MiInfo", std::mem::size_of::()), - ("WarpParams", std::mem::size_of::()), - ("Iqm", std::mem::size_of::()), - ("MvStack", std::mem::size_of::()), - ("Frame", std::mem::size_of::()), - ( - "InterpFilterKind", - std::mem::size_of::(), - ), - ( - "TplProbe", - std::mem::size_of::>(), - ), - ] -} - -/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] -/// constructs on. -/// -/// 1 MiB: half of what an unconfigured caller gives this crate, and 2.7x what -/// the deepest measured chain needs in a debug build. Both thresholds were -/// swept in an unoptimized build and are reproducible with -/// `EC_AV1_TIGHT_STACK_BYTES`. -const TIGHT_STACK: usize = 1024 * 1024; - -#[cfg(test)] -mod tests { - use super::{ - BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name, - }; - use crate::encode::Encoded; - - /// Return types that are not a by-value copy of anything the caller has to - /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the - /// stack), or a primitive. `Self` is a by-value copy of the impl's type, - /// which the inventory rows already cover, so it is exempt from the scan - /// and not from the table. - const THIN: &[&str] = &[ - "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap", - "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16", - "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self", - ]; - - /// The type name a `pub fn` line returns BY VALUE, or `None` when the line - /// returns a pointer, a `Vec`, a primitive, or nothing. - /// - /// One function, shared by the sweep and its control, so the control - /// cannot pass while the sweep's copy of the logic rotted. - fn by_value_return_name(line: &str) -> Option { - let trimmed = line.trim_start(); - if !trimmed.starts_with("pub fn ") { - return None; - } - let arrow = line.find("->")?; - let rest = &line[arrow + 2..]; - let end = rest.find('{').unwrap_or(rest.len()); - let ret = rest[..end].trim(); - if ret.is_empty() { - return None; - } - // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is - // not a shape this crate uses, and flagging one as uninventoried is - // the safe direction to be wrong in. - let inner = { - let t = ret - .strip_prefix("Result<") - .or_else(|| ret.strip_prefix("Option<")) - .unwrap_or(ret); - t.split('>').next().unwrap_or(t) - }; - // Drop the error type and any lifetime or generic argument: - // `Result`, `SymbolDecoder<'a>` and `TxbTables<'_>` - // are all the bare name for this purpose. Splitting on the comma is - // load-bearing: the first version of this matcher cut only at `>` and - // so read `Result` as the name "Decoder, Error". - // `the_inventory_scan_is_not_vacuous` caught exactly that, which is - // why the control is not optional. - let name = inner.split(['<', ',']).next().unwrap_or(inner).trim(); - if name.is_empty() || THIN.contains(&name) { - return None; - } - // A generic parameter, not a concrete type. - if !name.chars().next().is_some_and(char::is_uppercase) { - return None; - } - Some(name.to_string()) - } - - /// The source files the by-value scan reads. Every module that can expose - /// a `pub fn` returning a named type; a new module added to `lib.rs` needs - /// adding here, and - /// [`every_by_value_module_is_scanned`] is what keeps that honest. - fn files() -> Vec<(&'static str, &'static str)> { - vec![ - ("bits.rs", include_str!("bits.rs")), - ("cdf.rs", crate::test_source::module_source("cdf")), - ("cdf_state.rs", include_str!("cdf_state.rs")), - ("census.rs", include_str!("census.rs")), - ("compound.rs", include_str!("compound.rs")), - ("decode.rs", crate::test_source::module_source("decode")), - ("dumpio.rs", include_str!("dumpio.rs")), - ("encode.rs", crate::test_source::module_source("encode")), - ("encoder.rs", crate::test_source::module_source("encoder")), - ("envflags.rs", include_str!("envflags.rs")), - ("film_grain.rs", include_str!("film_grain.rs")), - ("filter_search.rs", include_str!("filter_search.rs")), - ("frame.rs", include_str!("frame.rs")), - ("hits.rs", include_str!("hits.rs")), - ("intra.rs", include_str!("intra.rs")), - ("mc.rs", include_str!("mc.rs")), - ("motion.rs", include_str!("motion.rs")), - ("motion_field.rs", include_str!("motion_field.rs")), - ("msac.rs", include_str!("msac.rs")), - ("mvstack.rs", include_str!("mvstack.rs")), - ("obu.rs", include_str!("obu.rs")), - ("par.rs", include_str!("par.rs")), - ("autothreads.rs", include_str!("autothreads.rs")), - ("probe.rs", include_str!("probe.rs")), - ("qm.rs", crate::test_source::module_source("qm")), - ("quant.rs", include_str!("quant.rs")), - ("restoration.rs", include_str!("restoration.rs")), - ("sequence.rs", include_str!("sequence.rs")), - ("speed.rs", include_str!("speed.rs")), - ("stream.rs", crate::test_source::module_source("stream")), - ("superres.rs", include_str!("superres.rs")), - ("test_source.rs", include_str!("test_source.rs")), - ("tile.rs", crate::test_source::module_source("tile")), - ("timeline.rs", include_str!("timeline.rs")), - ("transform.rs", include_str!("transform.rs")), - ("warp.rs", include_str!("warp.rs")), - ("wedge.rs", include_str!("wedge.rs")), - ("stack_budget.rs", include_str!("stack_budget.rs")), - ("fault.rs", include_str!("fault.rs")), - ] - } - - /// Every module `lib.rs` declares, so the scan's file list cannot silently - /// fall behind a new module. A new `mod foo;` with a by-value `pub fn` - /// that the scan never reads is exactly the hole this class would come - /// back through, so the list is derived, not curated. - #[test] - fn every_by_value_module_is_scanned() { - let lib = include_str!("lib.rs"); - let mut declared: Vec<&str> = Vec::new(); - for line in lib.lines() { - let t = line.trim(); - let rest = t - .strip_prefix("pub mod ") - .or_else(|| t.strip_prefix("mod ")) - .unwrap_or(""); - if rest.is_empty() { - continue; - } - let name = rest.split([';', ' ']).next().unwrap_or(""); - if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - declared.push(name); - } - } - assert!( - declared.len() > 10, - "only {} module declarations parsed out of lib.rs, so the \ - derived file list is broken rather than small", - declared.len() - ); - let scanned: Vec<&str> = files().iter().map(|(n, _)| *n).collect(); - let mut missing: Vec = declared - .iter() - .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs"))) - .map(|d| (*d).to_string()) - .collect(); - missing.sort(); - assert!( - missing.is_empty(), - "lib.rs declares modules the by-value scan never reads: {:?}. Add \ - them to files(), or the sweep cannot see a new by-value return that \ - lands in one of them.", - missing - ); - } - - /// The inventory, printed as a sorted table, and checked against the - /// types' real sizes. - /// - /// The print is the instrument: one command - /// (`cargo test -p ec-av1 --lib -- stack_budget -- --nocapture`) - /// reproduces the whole table, biggest first, so "what is the largest - /// by-value type in this crate" has an answer that is a measurement - /// rather than a grep. - /// - /// The check reds on ANY change with both numbers. That is deliberate: a - /// by-value type that grew raises the question of whether it should have - /// been boxed instead, and auto-accepting the new number would answer - /// that question by default. - #[test] - fn the_measured_inventory_is_accurate() { - let live = measured_by_name(); - assert_eq!( - BY_VALUE_TYPES.len(), - live.len(), - "the inventory names {} types but {} are measured; every row needs \ - a measured size or the sweep is a list of hopes", - BY_VALUE_TYPES.len(), - live.len() - ); - let mut rows: Vec<(&str, usize)> = live.clone(); - rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size)); - eprintln!( - "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)", - rows.len(), - STACK_BUDGET / 1024 - ); - eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET"); - for (name, size) in &rows { - eprintln!( - "{size:>8} {:>6.1}% {name}", - *size as f64 * 100.0 / STACK_BUDGET as f64 - ); - } - for (name, recorded, _public, _path) in BY_VALUE_TYPES { - let recorded = recorded.expect("every inventory row carries a measured size"); - let actual = live - .iter() - .find(|(n, _)| n == name) - .map(|(_, size)| *size) - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); - assert_eq!( - recorded, actual, - "{name} is {actual} bytes, the inventory records {recorded}; \ - update the table deliberately -- a by-value type that changed \ - is a stack cost every caller of its constructor now pays" - ); - } - } - - /// The bound, asserted BY NAME. A regression in any inventoried type reds - /// here naming the type, not "some type is too big". - #[test] - fn every_by_value_type_fits_the_stack_budget() { - let live = measured_by_name(); - let mut checked = 0usize; - for (name, _, public, path) in BY_VALUE_TYPES { - if !public { - continue; - } - checked += 1; - let size = live - .iter() - .find(|(n, _)| n == name) - .map(|(_, size)| *size) - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); - assert!( - size <= STACK_BUDGET, - "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ - stack budget ({:.2}x). It is returned by value from {path}, so \ - every caller pays it on its own stack, and the constructors \ - nest -- one value's size is the multiplier, not the cost. \ - Box the large field (lane-av1enchang did exactly this for \ - Av1Encoder::dpb, and lane-av1stacksweep for Encoded's two \ - inline CdfSnapshots) or hand back a reference.", - size as f64 / STACK_BUDGET as f64 - ); - } - assert!( - checked >= 10, - "only {checked} rows were bound-checked; the budget must apply to \ - every type a caller can be made to hold by value" - ); - // The other half of the derivation, asserted so it cannot rot: the - // worst a caller can owe is DEEPEST_CHAIN x the worst public return. - let worst = live - .iter() - .filter(|(n, _)| { - BY_VALUE_TYPES - .iter() - .any(|(row, _, public, _)| row == n && *public) - }) - .map(|(_, size)| *size) - .max() - .expect("at least one public row"); - assert!( - DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, - "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ - public by-value return ({worst} B) is {} B, over an eighth of the \ - 2101248-byte stack an unconfigured caller hands this crate; \ - re-derive STACK_BUDGET", - DEEPEST_PUBLIC_CHAIN * worst - ); - } - - /// The crate-private CDF tables stay BEHIND A BOX. - /// - /// The budget does not apply to `Cdfs` / `CdfSnapshot` (15,232 B each) - /// because no `pub fn` returns them, so bounding them would calibrate the - /// number to something no caller can reach. What keeps them off the stack - /// is that every field holding one is a `Box`, and THIS is the pin for - /// that -- a source scan over the four declarations. - /// - /// It earned its place during this lane: `Av1Encoder` was 18,168 B after - /// lane-av1enchang boxed the DPB slot, and 15,232 of that was - /// `carried_cdfs: Option` sitting inline on the very same - /// struct. Nothing had measured it. Unboxing any of the four puts the - /// stack cost straight back. - #[test] - fn the_crate_private_cdf_tables_stay_behind_a_box() { - const PINS: &[(&str, &str, &str)] = &[ - ( - "encoder.rs", - "DpbSlot::cdfs", - "cdfs: Box", - ), - ( - "encoder.rs", - "Av1Encoder::carried_cdfs", - "carried_cdfs: Option>", - ), - ( - "encode.rs", - "Encoded::start_cdfs", - "start_cdfs: Box", - ), - ( - "encode.rs", - "Encoded::next_cdfs", - "next_cdfs: Box", - ), - ]; - let files: [(&str, &str); 2] = [ - ("encoder.rs", crate::test_source::module_source("encoder")), - ("encode.rs", crate::test_source::module_source("encode")), - ]; - for (file, field, spelling) in PINS { - let src = files - .iter() - .find(|(name, _)| name == file) - .map(|(_, src)| *src) - .unwrap_or_else(|| panic!("no source pinned for {file}")); - let where_ = format!("{file}::{field}"); - assert!( - src.contains(spelling), - "{where_} is no longer declared `{spelling}`. An inline \ - CdfSnapshot there puts {field}'s 15232 bytes back on every \ - caller's stack -- that is how Av1Encoder was 139960 bytes \ - before lane-av1enchang, and how it was still 18168 after it, \ - because carried_cdfs was missed.", - ); - } - // And the negative control: the unboxed spellings must NOT all still - // be present, or the scan above would be matching a comment. - let encoder = files[0].1; - assert!( - !encoder.contains("cdfs: crate::encode::CdfSnapshot,"), - "the box pin is matching a spelling that is not the live \ - declaration" - ); - } - - /// CAPABILITY: really construct the heavy types on a tight stack, so a - /// regression ABORTS THE PROCESS instead of costing invisible margin. - /// - /// Both arms are the deepest public chains in the crate: the encoder's - /// three-deep `Result` constructor nest, and the four-deep - /// `Result` chain, the longest by-value return path here. - /// - /// Measured stack need, **debug** build, 64x64, one process per point so a - /// SIGABRT cannot truncate the sweep: - /// - /// | stack | before this lane boxed `Encoded` | after | - /// |---|---|---| - /// | 131072 | overflow | overflow | - /// | 262144 | overflow | overflow | - /// | 327680 | overflow | overflow | - /// | 466944 | overflow | **overflow** | - /// | 475136 | overflow | **ok** | - /// | 524288 | overflow | **ok** | - /// | 786432 | **overflow** | ok | - /// | 1048576 | **ok** | **ok** | - /// - /// The gate sits at 1 MiB, now **2.2x** the deepest measured need rather - /// than 1.33x. Boxing `Encoded`'s two inline `CdfSnapshot`s (99.2% of its - /// 30,728 bytes) and `Av1Encoder::carried_cdfs` (15,232 of its 18,168) is - /// what moved the threshold. The ~470 KB that remains is the encode - /// search's own frames, which this module does not claim to shrink. - /// - /// Pre-fix (`CdfSnapshot` by value in the DPB) the encoder arm overflowed - /// at 1 MiB and at 2 MiB. `EC_AV1_TIGHT_STACK_BYTES` overrides the size, - /// which is how the table above is reproduced. - #[test] - fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { - use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Pyramid, RateTarget}; - let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(TIGHT_STACK); - let config = EncoderConfig { - width: 64, - height: 64, - base_q_idx: 100, - gop: 48, - colour: Colour::Bt709Limited, - tile_cols_log2: 0, - tile_rows_log2: 0, - }; - let rate = RateTarget::Bitrate { - bits_per_second: 1_536_000, - frames_per_second: 24.0, - }; - let handle = std::thread::Builder::new() - .stack_size(stack) - .spawn(move || { - // Arm 1: the three-deep Result constructor nest. - let encoder = - Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate) - .expect("with_pyramid_and_rate_target"); - let pyramid = encoder.pyramid().is_some(); - drop(encoder); - // Arm 2: the four-deep Result chain, the crate's - // largest by-value return. - let grey = crate::encode::Picture::grey(64, 64); - let encoded = - crate::encode::encode_key_frame(&grey, 100, 0.0).expect("encode_key_frame"); - (pyramid, encoded.stream.len()) - }) - .expect("spawn tight-stack thread"); - let (pyramid, bytes) = handle.join().unwrap_or_else(|_| { - panic!( - "a by-value constructor overflowed a {stack}-byte stack; the \ - threshold table on this test says what that costs" - ) - }); - assert!(pyramid, "with_pyramid_and_rate_target lost its pyramid"); - assert!(bytes > 0, "encode_key_frame produced no stream"); - eprintln!( - "TIGHTSTACK {stack} bytes: Av1Encoder={} Encoded={} bytes, both chains returned", - std::mem::size_of::(), - std::mem::size_of::(), - ); - } - - /// The sweep's teeth against a NEW by-value return: re-derive the set from - /// the crate source and require every name to be inventoried. - /// - /// Without this the inventory is a list of what someone remembered to - /// measure, and a lane that adds `pub fn make() -> HugeThing` where - /// `HugeThing` is 200 KB of inline tables passes every other test here. - #[test] - fn every_by_value_public_return_is_in_the_inventory() { - let mut found: Vec<(String, String)> = Vec::new(); - for (file, src) in files() { - for (n, line) in src.lines().enumerate() { - if let Some(name) = by_value_return_name(line) { - found.push((name, format!("{file}:{}", n + 1))); - } - } - } - found.sort(); - found.dedup(); - assert!( - found.len() > 5, - "the by-value return scan found {} names across {} files, which is \ - too few to be a real sweep -- the matcher, not the crate, is broken", - found.len(), - files().len() - ); - - let mut missing = Vec::new(); - for (name, site) in &found { - if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { - missing.push(format!("{name} ({site})")); - } - } - assert!( - missing.is_empty(), - "these types are returned BY VALUE from a public fn and are not in \ - the inventory: {}. Either they are thin enough not to be a stack \ - cost -- say so by adding a row with its measured size -- or they \ - are the next instance of the class this module exists for.", - missing.join(", ") - ); - } - - /// The control for the scan above, on synthetic text rather than by - /// trusting the live tree to happen to contain a case. - /// - /// If the matcher silently stopped recognising a shape, the sweep would - /// pass everything and this would still be asserting nothing. So: every - /// by-value spelling the crate uses must yield its type name, and every - /// pointer/Vec/primitive/`Self` spelling must yield nothing. - #[test] - fn the_inventory_scan_is_not_vacuous() { - for synthetic in [ - "pub fn zz_a() -> ZzNotInventoried { todo!() }", - "pub fn zz_b() -> Result { todo!() }", - "pub fn zz_c() -> Result { todo!() }", - "pub fn zz_d() -> Option { todo!() }", - "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", - ] { - let name = by_value_return_name(synthetic) - .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); - assert_eq!( - name, "ZzNotInventoried", - "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ - cannot see a new by-value return and its green is vacuous" - ); - assert!( - !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), - "the synthetic control name is in the inventory, so the control \ - proves nothing" - ); - } - for thin in [ - "pub fn zz_t() -> Box { todo!() }", - "pub fn zz_u() -> Result, Error> { todo!() }", - "pub fn zz_v() -> Option<&Path> { todo!() }", - "pub fn zz_w() -> usize { todo!() }", - "pub fn zz_x() -> Self { todo!() }", - "pub fn zz_y() -> Result, Error> { todo!() }", - "pub fn zz_z() { todo!() }", - "fn zz_private() -> ZzNotInventoried { todo!() }", - ] { - assert_eq!( - by_value_return_name(thin), - None, - "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ - above already cover, or not a `pub fn` -- the matcher must not \ - read it as an uninventoried by-value return" - ); - } - } - - /// The stack mapping containing `addr` in `/proc/self/task//maps`. - /// - /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES - /// adjacent VMAs that share protections, and a merged region is - /// indistinguishable from a single one in the maps file -- a thread whose - /// 1 MiB stack abutted a neighbour's read back here as 69218304 bytes with - /// nothing to indicate the join. Two earlier versions of this test tried to - /// be exact anyway (asserting a byte count, then detecting the merge by - /// looking for an abutting same-protection neighbour) and both were wrong - /// for that reason. - /// - /// A lower bound is what the budget's reasoning needs: the claim is "no - /// caller gets less than 2 MiB", and `size >= 2 MiB` is exactly that, - /// whether the region is one mapping or three. - /// - /// The third field is whether the mapping is writable. Merging only joins - /// VMAs whose protections match, so a merged thread stack is still - /// writable. Its size can grow without bound, which is why the tests check - /// this flag and never an upper bound on the size. - fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize, bool)> { - let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?; - for line in maps.lines() { - let (range, perms) = line.split_once(' ')?; - let (lo, hi) = range.split_once('-')?; - let (lo, hi) = ( - usize::from_str_radix(lo, 16).ok()?, - usize::from_str_radix(hi, 16).ok()?, - ); - if addr >= lo && addr < hi { - // `perms` is `rwxp`-style: the second character is write. - let writable = perms.as_bytes().get(1) == Some(&b'w'); - return Some((lo, hi, writable)); - } - } - None - } - - /// What a thread's stack ACTUALLY is, read from - /// `/proc/self/task//maps` rather than assumed from a default. - /// - /// The number the budget's reasoning rests on, measured two ways: - /// - /// * a thread spawned with an EXPLICIT size gets AT LEAST that size -- - /// the control that says the parse finds stacks at all, and the shape - /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on; - /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's - /// `std::thread::spawn` gets, and what libtest gives a test thread when - /// `RUST_MIN_STACK` is unset -- is at least 2 MiB. - /// - /// Both are floors, because [`stack_region`] can only report a lower bound. - /// That is the right direction: the budget's claim is that no caller gets - /// LESS than 2 MiB, and a floor is what proves it. - /// - /// Exact figures measured on this runtime, for the report: 2101248 bytes - /// with the repo's `.cargo/config.toml` cap lifted, 67112960 with it - /// applied. A library consumer gets the first, and that is the one the - /// budget is sized for. - #[test] - fn test_threads_get_the_stack_they_are_given() { - const EXPLICIT: usize = 1024 * 1024; - let handle = std::thread::Builder::new() - .stack_size(EXPLICIT) - .spawn(|| { - let tid = std::process::id(); - let marker = 0u8; - let here = &marker as *const u8 as usize; - let (lo, hi, rw) = - stack_region(tid, here).expect("this thread's own stack is in its maps"); - (lo, hi, rw) - }) - .expect("spawn"); - let (lo, hi, rw) = handle.join().expect("the probe thread returned"); - let size = hi - lo; - assert!( - size >= EXPLICIT, - "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \ - stack mapping; the runtime gave it less than it was promised, so \ - the maps parse is finding the wrong region" - ); - assert!( - rw, - "the mapping holding an explicitly-1-MiB thread's frame is not \ - writable -- a thread stack is read-write, so the maps parse found \ - the wrong region" - ); - - let tid = std::process::id(); - let marker = 0u8; - let here = &marker as *const u8 as usize; - let (lo, hi, rw) = - stack_region(tid, here).expect("this test thread's stack is in its maps"); - let size = hi - lo; - assert!( - rw, - "a default test thread's stack mapping is not writable -- the maps \ - parse found the wrong region" - ); - assert!( - size >= 2 * 1024 * 1024, - "a default test thread's stack measured {size} bytes, under the \ - 2 MiB floor the by-value budget is derived from; the smallest \ - stack a caller can hand this crate just got smaller and the bound \ - needs re-deriving" - ); - eprintln!( - "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \ - (2101248 measured exactly with the repo cap lifted, 67112960 with it)" - ); - } -} diff --git a/crates/ec-av1/src/stream/mod.rs b/crates/ec-av1/src/stream/mod.rs index 8b9d9089..36f01240 100644 --- a/crates/ec-av1/src/stream/mod.rs +++ b/crates/ec-av1/src/stream/mod.rs @@ -29,345 +29,6 @@ use crate::decode; use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of}; use crate::encode::Picture; -/// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a -/// mid-film mismatch splits into "reconstruction" (compare against -/// `ffmpeg -c:v libdav1d -filmgrain 0`) and "grain synthesis" in one run. -fn no_grain() -> bool { - std::env::var_os("EC_AV1_NO_GRAIN").is_some() -} - -// lane-hidden r1: where `EC_AV1_FINAL_DUMP`'s per-frame dump goes for the -// current thread, overriding the environment variable. Every ffmpeg/aomdec -// pixel gate in this repo compares SHOWN frames only (class -// gate-blind-to-hidden-frames), so the hidden alt-ref frames a real aomenc -// stream carries were never compared at all; the gate that does compare -// them needs a dump path that cannot race a sibling test's decode on -// another thread, which a process-global env var cannot give. -thread_local! { - static FINAL_DUMP_PREFIX: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; -} - -/// Sets (or with `None` clears) this thread's `EC_AV1_FINAL_DUMP` prefix. -#[allow(dead_code)] -pub(crate) fn set_final_dump_prefix(prefix: Option) { - FINAL_DUMP_PREFIX.with(|c| *c.borrow_mut() = prefix); -} - -fn final_dump_prefix() -> Option { - FINAL_DUMP_PREFIX - .with(|c| c.borrow().clone()) - .or_else(|| std::env::var("EC_AV1_FINAL_DUMP").ok()) -} - -/// 32x32-level 1:4 strip counters, for `decode_probe`'s fixture search: -/// (HORZ_4 strips, VERT_4 strips, strips that read coefficients). -/// lane-inter4 r1: the INTER-frame partition counters this lane's gates -/// assert -- `(32x8, 8x32, 64x32, 32x64, 64x16, 16x64)` strips decoded. -pub fn inter_rect_counters() -> (usize, usize, usize, usize, usize, usize) { - ( - crate::decode::rect4_32_horz_inter_hits(), - crate::decode::rect4_32_vert_inter_hits(), - crate::decode::inter_sb_horz_hits(), - crate::decode::inter_sb_vert_hits(), - crate::decode::inter_sb_horz4_hits(), - crate::decode::inter_sb_vert4_hits(), - ) -} - -/// lane-r14 r2: luma transform units of an inter strip with a 64-px axis, -/// coded as the truncated low-32 coefficient corner. -pub fn rect64_inter_tu_hits() -> usize { - crate::decode::rect64_inter_tu_hits() -} - -/// lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4 -/// inter strip (`TX_32X8`/`TX_8X32`), `[32x8, 8x32]`. -pub fn rect32x8_inter_tu_hits() -> [usize; 2] { - crate::decode::rect32x8_inter_tu_hits() -} - -/// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherited a -/// `tx_type` different from the group's FIRST sub-block, i.e. groups that can -/// only decode right under `av1_get_tx_type`'s chroma-reference rule. -pub fn sub8_chroma_tx_from_ref_hits() -> usize { - crate::decode::sub8_chroma_tx_from_ref_hits() -} - -/// lane-intra16x4: `(16x4, 4x16, chroma-reference)` INTRA strips decoded inside -/// an inter 16x16-level 1:4 partition. -pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) { - crate::decode::intra16x4_in_inter_hits() -} - -/// lane-sub8intra: INTRA 8x4/4x8 leaves inside an inter frame's sub-8x8 -/// HORZ/VERT partition, `(8x4, 4x8, chroma-reference, mixed groups, split -/// 4x4 leaves)`. -pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) { - crate::decode::sub8_intra_rect_hits() -} - -/// lane-r14 r3: RECTANGULAR var-tx leaf transform units, `[32x16, 16x32]` -- -/// the leaves `sub_tx_size_map` produces when a 1:4 strip with a 64-px axis -/// splits its transform (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`). -pub fn vartx_rect_leaf_hits() -> [usize; 2] { - crate::decode::vartx_rect_leaf_hits() -} - -/// How many rect intra strips read the `use_intrabc` symbol on the last decode. -pub fn rect_intrabc_reads() -> usize { - crate::decode::rect_intrabc_reads() -} - -/// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose luma a lossless -/// frame walked as per-4x4 inter units. -pub fn intrabc_rect8_lossless_luma_hits() -> usize { - crate::decode::intrabc_rect8_lossless_luma_hits() -} - -/// lane-av1-ibc444rect: unskipped intrabc 8x4/4x8 leaves whose chroma a -/// lossless 4:4:4 frame walked as per-4x4 `Chroma4` units. -pub fn intrabc_rect8_lossless_chroma_hits() -> usize { - crate::decode::intrabc_rect8_lossless_chroma_hits() -} - -/// Gate-side reset for the lane-av1-ibc444rect counters above. -pub fn reset_ibc444rect_hits() { - crate::decode::reset_ibc444rect_hits() -} - -/// lane-av1chromarect: 128-root intra-BC HORZ/VERT strips whose chroma plane -/// block was sized `bw >> ss_x` by `bh >> ss_y` rather than the hardcoded -/// 4:2:0 halving -- i.e. the 4:4:4 (and 4:4:0) cells, where -/// `av1_get_max_uv_txsize` (`ss_size_lookup[bsize]`, blockd.h:1372) applies no -/// halving of its own. At 4:2:0 the two forms are the same arithmetic, so a -/// `>= 1` witness can only come from a stream that is not 4:2:0. EXCLUSIVE to -/// `decode_intrabc_owned_rect`: no other caller sizes a 128-root intra-BC -/// strip's chroma plane block. -pub fn ibc_owned_rect_chroma_footprint_444_hits() -> usize { - crate::decode::ibc_owned_rect_chroma_footprint_444_hits() -} - -/// Gate-side reset for the lane-av1chromarect counter above. -pub fn reset_ibc_owned_rect_chroma_footprint_444_hits() { - crate::decode::reset_ibc_owned_rect_chroma_footprint_444_hits() -} - -/// lane-av1chromadc: chroma units of a skipped block whose intra-BC / UV -/// palette override had to be windowed to the unit's own extent -- `cn_cols * -/// cn_rows > 1`, which at 4:2:0 never happens and at 4:4:4 is every block of -/// 64 and above. Counts UNITS. EXCLUSIVE to `decode_block`'s skipped square -/// block chroma walk. -pub fn skip_chroma_override_window_hits() -> usize { - crate::decode::skip_chroma_override_window_hits() -} - -/// Gate-side reset for the lane-av1chromadc counter above. -pub fn reset_skip_chroma_override_window_hits() { - crate::decode::reset_skip_chroma_override_window_hits() -} - -/// lane-av1rectreach: the `chroma_tiled` walk's per-unit reach and grid-shape -/// counters, as `(unit_reach_differs_from_block, 2x1 units, 1x2 units, other -/// multi-unit units)`. See [`crate::decode::rect_tiled_chroma_grid_hits`]. -pub fn rect_tiled_chroma_grid_hits() -> (usize, usize, usize, usize) { - crate::decode::rect_tiled_chroma_grid_hits() -} - -/// Gate-side reset for the lane-av1rectreach counters above. -pub fn reset_rect_tiled_chroma_grid_hits() { - crate::decode::reset_rect_tiled_chroma_grid_hits() -} - -/// `(y, uv)` palette blocks RECONSTRUCTED inside an inter frame (lane-t900 -/// r22) -- the counter a screen-content witness gate reads to prove it -/// exercises the inter-frame palette path, not the key frame's. -pub fn intra_in_inter_palette_hits() -> (usize, usize) { - crate::decode::intra_in_inter_palette_hits() -} - -/// `(y, uv)` palette blocks reconstructed on an 8x8 LEAF inside an inter -/// frame (lane-t900 r23) -- the site-specific half of -/// [`intra_in_inter_palette_hits`], which a >=16 block also moves. -pub fn inter8_palette_hits() -> (usize, usize) { - crate::decode::inter8_palette_hits() -} - -/// lane-rect64port r1: coded 64-level HORZ/VERT intra strips whose luma -/// transform unit is the un-split TX_64X32 (orient 0) / TX_32X64 (orient 1). -pub fn rect64_corner_tu_hits(orient: usize) -> usize { - crate::decode::rect64_corner_tu_hits(orient) -} - -/// lane-inter16ab r4: RECTANGULAR var-tx leaves with a 4-px axis, `[8x4, 4x8]` -/// -- what `sub_tx_size_map[TX_16X4] == TX_8X4` produces when a 16x16-level -/// 1:4 inter strip splits its transform. -pub fn vartx_rect_leaf4_hits() -> [usize; 2] { - crate::decode::vartx_rect_leaf4_hits() -} - -/// lane-inter16ab r5: COMPOUND_WEDGE / wedge-INTERINTRA blocks that used a -/// RECTANGULAR wedge codebook row, per shape (`RECT_WEDGE_SHAPES` order: -/// 8x16, 16x8, 16x32, 32x16, 8x32, 32x8). -pub fn rect_wedge_hits() -> [usize; 6] { - crate::decode::rect_wedge_hits() -} - -/// lane-inter16ab r5: the wedge-interintra half of [`rect_wedge_hits`]. -pub fn rect_wii_hits() -> [usize; 6] { - crate::decode::rect_wii_hits() -} - -/// lane-sb128c r7: the 128 root's rect arms -- (gathered edge HORZ, gathered -/// edge VERT, inter 128x64 blocks, inter 64x128 blocks). -pub fn sb128_rect_counters() -> (usize, usize, usize, usize) { - ( - crate::decode::part128_edge_horz_hits(), - crate::decode::part128_edge_vert_hits(), - crate::decode::inter_sb128_horz_hits(), - crate::decode::inter_sb128_vert_hits(), - ) -} - -/// lane-av1-ibcrect: the 128 root's interior partition arms plus the key-frame -/// intra 128-axis blocks -- (split, none, horz, vert, ab[4], intra_horz, -/// intra_vert). Non-zero horz/vert mean a stream carried real PARTITION_HORZ/ -/// VERT at the 128 root, so an intrabc-rect hunt can tell "the partition was -/// never chosen" from "chosen and decoded intra (or refused)". -pub fn part128_census() -> (usize, usize, usize, usize, [usize; 4], usize, usize) { - ( - crate::decode::part128_split_hits(), - crate::decode::part128_none_hits(), - crate::decode::part128_horz_hits(), - crate::decode::part128_vert_hits(), - crate::decode::part128_ab_hits(), - crate::decode::intra_sb128_hits().0, - crate::decode::intra_sb128_hits().1, - ) -} - -/// lane-av1-ibcrect: `use_intrabc` blocks on a 128-root HORZ/VERT strip whose -/// reconstruction ([`crate::decode::decode_intrabc_128rect`]) ran -- the -/// engagement counter the sb128 intrabc-rect gate asserts on. -pub fn intrabc_128rect_hits() -> usize { - crate::decode::intrabc_128rect_hits() -} - -/// lane-av1-ibc128chunk: chroma transform units the 128-root intrabc strip's -/// mu-chunk walk read, one per `read_inter_plane` chroma call. At 4:2:2 a -/// 64x64 mu chunk's chroma plane block is 32x64 and holds TWO STACKED -/// TX_32X32 units per plane; the square-cut walk this gate witnesses read -/// one. Measured on the pinned witness: 8 before, 48 after. -pub fn intrabc_128rect_chroma_chunk_hits() -> usize { - crate::decode::intrabc_128rect_chroma_chunk_hits() -} - -/// lane-av1-ibc128chunk: the 128-root intrabc strip's per-axis chroma chunk -/// extents as `(64 >> ss_x) << 8 | (64 >> ss_y)` on the last chunk walked -- -/// 32|32 at 4:2:0, 32|64 at 4:2:2, 64|64 at 4:4:4. -pub fn intrabc_128rect_chunk_shape() -> usize { - crate::decode::intrabc_128rect_chunk_shape() -} - -/// Blocks reconstructed with intra block copy at an 8x8 LEAF specifically -/// (lane-kf900 r7's shape); [`crate::decode::intrabc_hits`] counts every shape. -pub fn leaf8_intrabc_hits() -> usize { - crate::decode::leaf8_intrabc_hits() -} - -/// Blocks whose `use_intrabc` symbol came out 1 and took the DV path, at ANY -/// shape -- the engagement counter the intrabc gates assert on. It counts -/// "read a `use_intrabc` DV", not "reconstructed": a block the rect-strip -/// reader REFUSES for an unported shape bumps it too (the symbol and the DV -/// are parsed before the refusal). [`leaf8_intrabc_hits`] is its 8x8-leaf -/// subset. -pub fn intrabc_hits() -> usize { - crate::decode::intrabc_hits() -} - -/// lane-av1txbands: sub-8x8 group chroma-reference leaves that USED intrabc and -/// were SKIPPED -- the route that armed [`crate::decode::intrabc_hits`]'s chroma -/// transform slot and then read no chroma coefficient. A non-zero value is what -/// makes the disarm at that route load-bearing on a real stream. -pub fn skipped_intrabc_chroma_arm_hits() -> usize { - crate::decode::skipped_intrabc_chroma_arm_hits() -} - -/// lane-sb128c r8: the 128 root's INTRA (key-frame) rect arm -- (128x64 -/// blocks, 64x128 blocks, blocks per resolved intra `tx_depth` 0/1/2). -pub fn intra_sb128_counters() -> (usize, usize, [usize; 3]) { - crate::decode::intra_sb128_hits() -} - -/// lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA inside an -/// INTER frame -- (128x64 blocks, 64x128 blocks). -pub fn intra128_in_inter_counters() -> [usize; 2] { - crate::decode::intra128_in_inter_hits() -} - -/// lane-lossless128: intra 128-axis blocks decoded on a LOSSLESS frame, where -/// every plane is a TX_4X4 unit. The engagement counter for -/// `a_lossless_sb128_rect_intra_block_decodes_sample_exact`. -pub fn intra128_lossless_counters() -> usize { - crate::decode::intra128_lossless_hits() -} - -/// lane-av1-128rectspan: chroma transform units re-stamped by -/// `decode_block_128rect`'s end-of-block replay, and how many of those -/// replays stamped a height that was not the unit's own. -/// lane-av1422lift: the second half was described as "the 4:2:2 signature -- -/// zero on every stream this decoder admits, since 4:2:2 is refused by name -/// at the sequence header", and that was TRUE. 4:2:2 is decoded now and the -/// mismatch is NOT zero: measured on this branch's tip, the two -/// `422_intrabc_sb128_strip*` pins each read `(72, 9)` while the other 19 -/// committed 4:2:2 cells read `(0, 0)`. Those two pins are byte-exact -/// against ffmpeg, so the non-zero half counts the arm's own designed case -/// and is not a defect. lane-av1422mismatch9: the predicate is -/// `luma_span != luma_span_h` (`chroma_tx << ss_x` vs `<< ss_y`), true by -/// CONSTRUCTION at ss (1,0), and the replay re-stamps with the same per-axis -/// pair the in-loop walk used, so the counter is a 4:2:2 shape test, not a -/// divergence test (`record_mi_chroma` writes only the left/above context -/// arrays, never a pixel). One 4:2:2 gate now reads the pair and asserts the -/// measured `(72, 9)`: -/// `the_422_block_128rect_chroma_chunk_gather_stays_per_axis`; the other -/// reader is on a 4:4:4 stream, where the mismatch half is structurally zero. -pub fn sb128rect_chroma_replay_counters() -> (usize, usize) { - crate::decode::sb128rect_chroma_replay_hits() -} - -/// lane-sb128c r9: the four AB shapes at the 128 root, in `PARTITION_HORZ_A`, -/// `_HORZ_B`, `_VERT_A`, `_VERT_B` order (key and inter tile paths share the -/// counter -- it is bumped where the root symbol resolves). -pub fn sb128_ab_counters() -> [usize; 4] { - crate::decode::part128_ab_hits() -} - -/// lane-obmcrec r1: OBMC neighbours taken from the second half of a 1:4-strip -/// chroma pair -- the shape whose filter record the r1 fix re-sourced. -pub fn obmc_pair_filter_hits() -> usize { - crate::decode::obmc_pair_filter_hits() -} - -/// Gate counters for the 4x32/32x4 rectangular strips: `(horz, vert, coeff)` hits. -pub fn rect4_32_counters() -> (usize, usize, usize) { - ( - crate::decode::rect4_32_horz_hits(), - crate::decode::rect4_32_vert_hits(), - crate::decode::rect4_coeff_hits(), - ) -} - -/// lane-inter4 r4: rectangular inter transform units coded whole, rect -/// var-tx trees that split, and OBMC blends run on a 16x8/8x16 leaf -- the -/// three counters a recipe sweep needs to see from outside the crate. -pub fn rect_inter_tu_counters() -> (usize, usize, usize) { - ( - crate::decode::rect_inter_tu_hits(), - crate::decode::rect_inter_txsplit_hits(), - crate::decode::obmc_rect_leaf_hits(), - ) -} - /// Decode every frame in a raw AV1 OBU stream, in coding order. /// /// A key frame becomes the reference for the inter frames that follow it, @@ -855,7 +516,6 @@ fn collect_one( /// A persistent AV1 stream decoder: feed it temporal units in decode order. pub struct StreamDecoder { threads: usize, - final_dump: Option, parser: Av1Parser, pictures_shown: usize, pictures_decoded: usize, @@ -935,7 +595,6 @@ impl StreamDecoder { let (tx, rx) = std::sync::mpsc::channel::(); Self { threads, - final_dump: final_dump_prefix(), parser: Av1Parser::new(), pictures_shown: 0, pictures_decoded: 0, @@ -995,7 +654,6 @@ impl StreamDecoder { let mut pending_tiles = std::mem::take(&mut self.pending_tiles); let threads = self.threads; let StreamDecoder { - final_dump, parser, ref_slots, motion_field_slots, @@ -1100,7 +758,7 @@ impl StreamDecoder { let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let value = promise.wait()?; let shown_picture = value.pixels.wait()?; - let output = if grain.apply_grain && !no_grain() { + let output = if grain.apply_grain { std::sync::Arc::new(crate::film_grain::apply_grain( &shown_picture, &grain, @@ -1147,7 +805,7 @@ impl StreamDecoder { } picture }; - let output = if header.film_grain.apply_grain && !no_grain() { + let output = if header.film_grain.apply_grain { // lane-hbd10 r1: grain synthesis is bit-depth generic // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3). let bit_depth = parser @@ -1320,7 +978,7 @@ impl StreamDecoder { } } } - let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown); + let (job_seq, decode_idx) = (emit_seq, pictures_decoded); emit_seq += 1; pictures_decoded += 1; let shown = header.show_frame; @@ -1328,7 +986,6 @@ impl StreamDecoder { pictures_shown += 1; } let tx = tx.clone(); - let dump = final_dump.clone(); crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown); // The job outlives this call, so it owns its tile bytes (a copy of // this frame's compressed tiles) instead of borrowing `data`. @@ -1489,8 +1146,6 @@ impl StreamDecoder { seq, snap, decode_idx, - shown_idx, - dump.as_deref(), // lane-twostage publishes a frame's meta at its tile // boundary instead of after its filters, so a consumer // parses over its producer's filter tail. It is ON by @@ -1530,7 +1185,7 @@ impl StreamDecoder { // Grain is synthesised for OUTPUT only: a hidden frame is // reported to the sink clean, exactly as the inline path // below reports it (spec 7.18.3.1). - let output = if shown && header.film_grain.apply_grain && !no_grain() { + let output = if shown && header.film_grain.apply_grain { std::sync::Arc::new(crate::film_grain::apply_grain( &picture, &header.film_grain, @@ -1594,17 +1249,7 @@ impl StreamDecoder { stored_cdfs, motion_field, seg_map: decoded_seg_map, - } = decode_frame( - fctx, - &header, - &tile_bufs, - seq, - snap, - pictures_decoded, - pictures_shown, - final_dump.as_deref(), - None, - )?; + } = decode_frame(fctx, &header, &tile_bufs, seq, snap, pictures_decoded, None)?; let motion_field = motion_field.expect("the inline path passes no stage-1 sink"); pictures_decoded += 1; // lane-pool1: one allocation, then every slot store and the output @@ -1655,7 +1300,7 @@ impl StreamDecoder { decode::note_fwd_kf(); } if header.show_frame { - let output = if header.film_grain.apply_grain && !no_grain() { + let output = if header.film_grain.apply_grain { let mc_identity = seq.mc_identity; std::sync::Arc::new(crate::film_grain::apply_grain( &picture, @@ -1838,16 +1483,6 @@ impl<'a> RefSnapshot<'a> { header.mi_cols as usize, ) }); - if std::env::var_os("EC_TPL").is_some() { - eprintln!( - "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}", - header.order_hint, - header.use_ref_frame_mvs, - tpl_field - .as_ref() - .map_or(0, crate::motion_field::TplField::filled_cells) - ); - } Self { refpix, primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()), @@ -1908,12 +1543,9 @@ fn decode_frame( seq: SeqFlags, snap: RefSnapshot<'_>, decode_idx: usize, - shown_idx: usize, - final_dump: Option<&str>, // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`. stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>, ) -> Result { - crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx); if header.segmentation.enabled { // lane-hdrlossless: libaom IMPLEMENTS these three -- they rewrite a // block's reference / skip / mode BEFORE the symbols are read @@ -2279,14 +1911,6 @@ fn decode_frame( // 4:2:0 one never inherits the wrong plane count. crate::decode::set_mono(seq.mono_chrome, fctx); crate::decode::set_subsampling(seq.subsampling_x, seq.subsampling_y, fctx); - // lane-av1readcensus: the coefficient-unit census is armed here, off the - // same sequence-header subsampling. lane-av1422census422 widened it from - // 4:4:4-only to "any format with an unsubsampled luma axis", so a 4:2:2 - // cell's per-plane unit counts are readable and a 4:2:2 gate can assert - // a non-vacuous walk; 4:2:0 still reads zero, so the 4:2:0 control in - // `a_pixel_exact_444_stream_walks_the_same_coefficient_units_the_oracle_does` - // keeps asserting exactly that. - crate::decode::set_census_nonsub(seq.subsampling_x, seq.subsampling_y); // lane-av1txr: spec 5.9.2 `disable_cdf_update` -- a frame that sets it // codes every tile symbol against the CDFs it started with, so the tile // readers must not adapt (libaom `decodeframe.c:2909`: @@ -2336,34 +1960,9 @@ fn decode_frame( }; let started_from = initial_cdfs.clone(); // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame. - decode::set_coeff_trace_frame(decode_idx); // lane-t900 r9: one line per DECODE-order frame naming the header // fields a desync cliff is usually keyed on (frame type, base q, // primary_ref, the 7 ref slots, refresh mask, order hints). - if std::env::var_os("EC_PROBE_HDR").is_some() { - eprintln!( - "EC_HDR decode_idx={decode_idx} type={:?} show={} show_existing={} base_q={} primary_ref={} ref_idx={:?} refresh=0x{:02x} order_hint={} tiles={}x{} txmode={:?} interp={:?} reduced_tx={} allow_warp={} switchable_mo={} ref_mvs={} skip_mode={} cdef={:?} lr={:?}", - header.frame_type, - header.show_frame, - header.show_existing_frame, - header.quantization.base_q_idx, - header.primary_ref_frame, - header.ref_frame_idx, - header.refresh_frame_flags, - header.order_hint, - header.tile_info.cols, - header.tile_info.rows, - header.tx_mode, - header.interpolation_filter, - header.reduced_tx_set, - header.allow_warped_motion, - header.is_motion_mode_switchable, - header.use_ref_frame_mvs, - header.skip_mode_present, - header.cdef.bits, - header.loop_restoration.frame_restoration_type, - ); - } let order_hint_bits = seq.order_hint_bits; // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint @@ -2533,120 +2132,6 @@ fn decode_frame( // *initial* table into the slots it refreshes, not the adapted // end-of-tile one. let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from); - if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") { - // lane-av1dumploud: loud on a short write. This one is APPEND-mode and - // spans every frame of a run, so there is no total length to declare - // (`append_unknown` says so on the failure line rather than guessing - // one); the per-line writes are still checked, so an ENOSPC halfway - // through a table no longer passes as a complete one. - let mut f = crate::dumpio::LoudDump::append_unknown("EC_AV1_DUMP_TABLES", &path); - let mut line = |s: String| f.write(s.as_bytes()); - line(format!("=== frame idx={shown_idx} ===\n")); - line(format!("partition_w64 {:?}\n", stored_cdfs.partition_w64)); - line(format!("partition_w32 {:?}\n", stored_cdfs.partition_w32)); - line(format!("partition_w16 {:?}\n", stored_cdfs.partition_w16)); - line(format!("skip {:?}\n", stored_cdfs.skip)); - line(format!("new_mv {:?}\n", stored_cdfs.new_mv)); - line(format!("zero_mv {:?}\n", stored_cdfs.zero_mv)); - line(format!("ref_mv {:?}\n", stored_cdfs.ref_mv)); - line(format!("mv_joint {:?}\n", stored_cdfs.mv_joint)); - f.finish(); - } - // lane-comppin r3: decode-order (not display-order) dump of every - // frame's own post-deblock buffer -- the pre-existing pixel diff - // (`scratch_isolate_pinned_mismatch`) only ever compares *shown* - // frames, so a hidden reference (altref/bwdref) that DPB-corrupts a - // later shown frame is otherwise invisible; diff this byte-for-byte - // against `EC_AV1_POSTDEBLOCK_DUMP.fN` from the instrumented aomdec build - // (rung 6, `scripts/instrument-aom-oracle.sh`; 1 byte per sample, so it is - // byte-comparable only at 8-bit -- for HBD use rung 12 `EC_AV1_FINAL_DUMP`) - // to isolate whether the defect is in a hidden frame's own - // reconstruction or downstream of it. - if let Ok(path) = std::env::var("EC_AV1_DECODE_ORDER_DUMP") { - // lane-hbd r4: debug dump narrows to u8 -- this diagnostic - // predates 10-bit support and is an 8-bit-oracle comparison - // only (aomdec's own dump is 8-bit here too). - // - // lane-av1dumploud: loud on a short write; expected length is the three - // planes' own lengths (narrowing is 1 byte per sample, so the count is - // unchanged). - let narrow = |v: &[u16]| -> Vec { v.iter().map(|&s| s as u8).collect() }; - crate::dumpio::write_planes( - "EC_AV1_DECODE_ORDER_DUMP", - format!("{path}.f{decode_idx}"), - &[ - &narrow(&picture.y), - &narrow(&picture.u), - &narrow(&picture.v), - ], - ); - } - // lane-hidden r1: the frame exactly as it is about to be stored into - // the reference slots -- after deblock/CDEF/LR/superres, in DECODE - // order, hidden (`show_frame == 0`) alt-ref frames included, and - // bit-depth correct (8-bit as u8, 10/12-bit as u16 LE) unlike the - // u8-narrowing diagnostic dumps above. Matches the instrumented - // aomdec's own `EC_AV1_FINAL_DUMP` rung byte for byte - // (scripts/instrument-aom-oracle.sh rung 12), which is what makes a - // hidden frame's pixels comparable at all. - // lane-unwritten-dep: the census AT the output point, beside the dump that - // defines "the output" -- the same bytes, so the claim is about the frame the - // caller receives rather than about an intermediate stage. - // - // WHAT THIS IS FOR, corrected: an earlier revision of this comment said the - // pre-deblock plane was byte-identical plain-vs-sentinel and that deblock - // creates the dependence. That was wrong, and it was `dump_stage16`'s fault: - // it cropped chroma as `(fw/2, fh/2)`, a 4:2:0 assumption, so on a 64x64 - // 4:2:2 frame 2048 chroma samples appeared in no stage dump at all -- exactly - // the region the difference lives in. With per-axis extents the corrected - // measurement on `440_request_is_422` is that the PRE-DEBLOCK dump already - // differs by 2158 bytes and an exact u16 census finds 224 unwritten samples - // (U 112, V 112, rows 36..63) -- the same count `lanes/av1unwritten.report.md` - // reports. The hole is present before any filter runs, and the pre-deblock - // census SEES it. - // - // So this second census is not a patch for a blind pre-deblock scan. It is - // the measurement taken where the reference-bank bytes are taken, which - // covers the whole span from the tile walk to those bytes: every filter - // writes IN PLACE into the very buffer this scans, so nothing a later - // filter does can open a hole outside its extent. - // - // lane-av1graincensus, the scope correction this comment needed: "to the - // caller's frame" was WRONG, and this call is not what makes it right. - // `apply_grain` runs after this and ALLOCATES a fresh picture - // (`film_grain::uninit_plane`, `with_capacity` + `set_len`, no fill), so - // that destination never passes through here. The claim over the PRE-GRAIN - // planes -- the bytes the reference bank stores and every later frame - // predicts from -- is what this line supports; the grained picture the - // caller receives is censused by `decode::census_unwritten_grained`, at - // `apply_grain`'s own return, over its own counters. - decode::census_unwritten_final(&picture.y, &picture.u, &picture.v); - if let Some(prefix) = final_dump { - // lane-av1dumploud: this is the site that produced the 13 320 192-byte - // truncated frame in `lanes/unwritten-dep.report.md` -- `let _ = - // f.write_all(&buf)` swallowed the ENOSPC. Expected length is derived - // from the PLANES and the sample width, independently of `buf`, so a - // writer that builds the wrong buffer still gets caught. - let sample_width = if bit_depth == 8 { 1 } else { 2 }; - let expected = (picture.y.len() + picture.u.len() + picture.v.len()) * sample_width; - let mut f = crate::dumpio::LoudDump::create( - "EC_AV1_FINAL_DUMP", - format!("{prefix}.f{decode_idx}"), - expected, - ); - for plane in [&picture.y, &picture.u, &picture.v] { - if bit_depth == 8 { - f.write(&plane.iter().map(|&s| s as u8).collect::>()); - } else { - let mut row = Vec::with_capacity(plane.len() * 2); - for &s in plane { - row.extend_from_slice(&s.to_le_bytes()); - } - f.write(&row); - } - } - f.finish(); - } if let Some(why) = fctx.corrupt.get() { return Err(Error::corrupt(format!("AV1 frame {decode_idx}: {why}"))); } @@ -2658,29 +2143,5 @@ fn decode_frame( }) } -/// lane-intra14 r1: INTRA-coded 1:4 strips decoded on the INTER block path -/// (64x16, 16x64, 32x8, 8x32) -- the counters a recipe sweep needs from -/// outside the crate. -pub fn intra_rect4_in_inter_counters() -> (usize, usize, usize, usize) { - ( - crate::decode::intra_rect4_strip_in_inter_hits(0), - crate::decode::intra_rect4_strip_in_inter_hits(1), - crate::decode::intra_rect4_strip_in_inter_hits(2), - crate::decode::intra_rect4_strip_in_inter_hits(3), - ) -} - -/// lane-av1recipehunt: the recipe sweep's view of the `delta_q` story from -/// OUTSIDE the crate -- `(delta_q symbol groups read, rect64 dequant calls that -/// saw `CURRENT_Q_IDX != base_q_idx`)`. A recipe that reads delta_q but never -/// lands one inside a rect64 root is a different failure from one that reads -/// neither, and the gate can only tell them apart with both numbers. -pub fn rect64_qidx_drift_counters() -> (usize, usize) { - ( - crate::decode::delta_q_hits(), - crate::decode::rect64_qidx_drift_hits(), - ) -} - #[cfg(test)] pub(crate) mod tests; diff --git a/crates/ec-av1/src/superres.rs b/crates/ec-av1/src/superres.rs index 6859f38c..97b18c30 100644 --- a/crates/ec-av1/src/superres.rs +++ b/crates/ec-av1/src/superres.rs @@ -10,7 +10,6 @@ //! Every constant and the 64x8 `av1_resize_filter_normative` coefficient //! table below is copied verbatim from libaom `aom_dsp/aom_filter.h` and //! `av1/common/resize.c` (`AOM_VERSION=v3.13.3`, `~/.cache/aom-oracle`). -use crate::hits::hit; /// `RS_SUBPEL_BITS`. const RS_SUBPEL_BITS: u32 = 6; @@ -185,7 +184,6 @@ pub(crate) fn superres_hits() -> usize { /// Counts one whole upscaled picture (all three planes) for [`SUPERRES_HITS`]. pub(crate) fn note_upscaled_picture() { - hit!(SUPERRES_HITS); } #[cfg(test)] diff --git a/crates/ec-av1/src/test_source.rs b/crates/ec-av1/src/test_source.rs deleted file mode 100644 index a969374e..00000000 --- a/crates/ec-av1/src/test_source.rs +++ /dev/null @@ -1,103 +0,0 @@ -#![cfg(test)] -//! Test-only access to a crate module's SOURCE TEXT. -//! -//! The source-scanning gates used to `include_str!("decode.rs")`, which names -//! one file. Once a module is split into a directory (`decode/mod.rs` plus its -//! children) that include stops compiling, and every gate pinning it goes stale -//! on the next move. These helpers read the module's files at test run time -//! instead: `src/.rs` when it exists, then every `*.rs` under -//! `src//` recursively, concatenated in sorted path order. A file added to -//! that directory is therefore scanned without touching any gate. -//! -//! [`module_production_source`] is the same text minus the test-only files -//! (`tests.rs` and `*_tests.rs`), for gates that must not count their own test -//! fixtures. An inline `mod tests { .. }` in a single file is not removed by -//! that function; a gate that needs the production prefix cuts it itself. - -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; - -type Cache = Mutex>; -static CACHE: OnceLock = OnceLock::new(); - -/// The whole source text of module `name`: `src/.rs` and every `*.rs` -/// under `src//`, in sorted path order. -pub fn module_source(name: &str) -> &'static str { - cached(name, false) -} - -/// [`module_source`] without the test-only files (`tests.rs`, `*_tests.rs`). -pub fn module_production_source(name: &str) -> &'static str { - cached(name, true) -} - -/// Each module is read once per test process. The text is leaked, which is -/// bounded by the handful of modules the gates name and is test-only. -fn cached(name: &str, production_only: bool) -> &'static str { - let cache = CACHE.get_or_init(|| Mutex::new(BTreeMap::new())); - let mut map = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - let key = (name.to_string(), production_only); - if let Some(&text) = map.get(&key) { - return text; - } - let text: &'static str = Box::leak(read_module(name, production_only).into_boxed_str()); - map.insert(key, text); - text -} - -fn read_module(name: &str, production_only: bool) -> String { - assert!( - !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), - "{name:?} is not a module name" - ); - let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut files: Vec = Vec::new(); - let single = src.join(format!("{name}.rs")); - if single.is_file() { - files.push(single); - } - let dir = src.join(name); - if dir.is_dir() { - collect_rs(&dir, &mut files); - } - assert!( - !files.is_empty(), - "module {name} has neither src/{name}.rs nor src/{name}/" - ); - files.sort(); - // A split moved some top-level fns to `pub(super) fn` so sibling modules can call them. The - // scanners match header text (`\nfn name(`); normalize only that visibility so they see the - // same headers as before the split. Bodies and assertions are unchanged. - let mut text = String::new(); - for path in files { - if production_only && is_test_file(&path) { - continue; - } - let body = std::fs::read_to_string(&path) - .unwrap_or_else(|e| panic!("reading {}: {e}", path.display())); - text.push_str(&body); - if !body.ends_with('\n') { - text.push('\n'); - } - } - text.replace("\npub(super) fn ", "\nfn ").replace("\n pub(super) fn ", "\n fn ") -} - -fn collect_rs(dir: &Path, out: &mut Vec) { - let entries = - std::fs::read_dir(dir).unwrap_or_else(|e| panic!("reading {}: {e}", dir.display())); - for entry in entries { - let path = entry.expect("reading a directory entry").path(); - if path.is_dir() { - collect_rs(&path, out); - } else if path.extension().is_some_and(|ext| ext == "rs") { - out.push(path); - } - } -} - -fn is_test_file(path: &Path) -> bool { - let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); - stem == "tests" || stem.ends_with("_tests") -} diff --git a/crates/ec-av1/src/tile/blocks.rs b/crates/ec-av1/src/tile/blocks.rs index 1cb20814..49db2629 100644 --- a/crates/ec-av1/src/tile/blocks.rs +++ b/crates/ec-av1/src/tile/blocks.rs @@ -19,7 +19,8 @@ pub(super) static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] = /// i.e. palette blocks this writer cut at the frame's right/bottom mi edge. /// A gate asserts it non-zero so it cannot pass on a stream that never cuts /// one (class `gate-blind-to-feature`). -pub(super) static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +pub(super) static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); /// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps). pub fn palette_cut_maps_written() -> usize { @@ -291,10 +292,6 @@ pub(super) fn write_block_planes( } else { usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded) }; - #[cfg(test)] - let before = enc.tell(); - #[cfg(test)] - let q_ctx = cdfs.q_ctx; let mut coding = cdfs.txb(planes[plane], mode); let tx_type = if plane == 0 { luma_tx_type @@ -318,15 +315,6 @@ pub(super) fn write_block_planes( Some(plane), tx_type, ); - #[cfg(test)] - census_record( - planes[plane], - q_ctx, - grid, - f64::from(enc.tell() - before), - skip_ctx, - dc_sign_ctx(around[plane].dc_vote), - ); ec_rng_trace(|| { format!( "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", @@ -432,10 +420,6 @@ pub(super) fn write_luma_tus( neighbours.luma_skip_ctx(tu_mi, tx / MI) }; let around = neighbours.around_mi(tu_mi, tx)[0]; - #[cfg(test)] - let before = enc.tell(); - #[cfg(test)] - let q_ctx = cdfs.q_ctx; write_coeffs( enc, &mut cdfs.txb(set, mode), @@ -449,15 +433,6 @@ pub(super) fn write_luma_tus( .copied() .unwrap_or(TxType::DctDct), ); - #[cfg(test)] - census_record( - set, - q_ctx, - &unit, - f64::from(enc.tell() - before), - skip_ctx, - dc_sign_ctx(around.dc_vote), - ); if n > 1 { neighbours.record_mi_luma(tu_mi, tx, &unit); } @@ -1320,7 +1295,6 @@ pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) { 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) @@ -1328,100 +1302,6 @@ pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) { }); } -/// 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 -/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a -/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the -/// eob of a one-coefficient block, a whole size) shows up on its own row -/// rather than inside one average. -/// Thread-local, so a census cannot pick up the blocks of another test's -/// encode running beside it; a multi-tile, multi-threaded encode would -/// therefore only census the tiles this thread wrote, which is every tile of -/// the one-tile-one-thread encodes the gates print it from. -#[cfg(test)] -pub(super) type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>; -#[cfg(test)] -thread_local! { - pub(super) static CENSUS: RefCell> = const { RefCell::new(None) }; -} - -/// Starts a census on this thread, discarding anything a previous one left. -#[cfg(test)] -pub(crate) fn pricer_census_on() { - CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new())); -} - -/// Stops the census and hands back its rows: (set, non-zero bucket) -> -/// (blocks, priced bits, written bits). -#[cfg(test)] -pub(crate) fn take_pricer_census() -> CensusRows { - CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default() -} - -/// The label of a non-zero bucket, for the tables the gates print. -#[cfg(test)] -pub(crate) fn census_bucket_label(bucket: usize) -> &'static str { - ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket] -} - -#[cfg(test)] -pub(super) fn census_record( - set: TxbSet, - q_ctx: usize, - grid: &[i32], - written: f64, - // The writer's own neighbour contexts for this very transform block: the - // census prices the search's estimate the way the search now takes it - // (lane-av1skipctx), so a row's error is the table/adaptation drift that - // is left once the context is right. - skip_ctx: usize, - sign_ctx: usize, -) { - if CENSUS.with_borrow(|c| c.is_none()) { - return; - } - let nz = grid.iter().filter(|&&l| l != 0).count(); - let bucket = match nz { - 0 => 0, - 1 => 1, - 2 => 2, - 3..=4 => 3, - 5..=8 => 4, - 9..=16 => 5, - _ => 6, - }; - let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx); - CENSUS.with_borrow_mut(|rows| { - let rows = rows.as_mut().expect("the census is on"); - let row = rows.entry((format!("{set:?}"), bucket)).or_default(); - row.0 += 1; - row.1 += priced; - row.2 += written; - }); -} - -/// What the partition symbol of a block of `side` samples costs, in bits, when -/// it says the block is split (or that it is not). -/// -/// The price is taken at context zero — a block whose neighbours are no finer -/// than it is — because the search that reads it runs before the tile knows /// what its neighbours will be. pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { // Read-only, and the same tables every call: built once (see @@ -1998,7 +1878,11 @@ pub(super) fn mv_class_of(z: i32) -> usize { /// # Errors /// Returns an error when `diff` needs eighth-pel precision in a frame coded /// without `allow_high_precision_mv`. -pub(super) fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> { +pub(super) fn write_mv_component( + enc: &mut SymbolEncoder, + c: &mut MvComponentCdfs, + diff: i32, +) -> Result<()> { debug_assert_ne!(diff, 0); let hp_frame = high_precision_mv(); let sign = diff < 0; @@ -2176,18 +2060,13 @@ pub(super) static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [ std::sync::atomic::AtomicUsize::new(0), ]; -/// Takes and clears the per-reference histogram. -#[cfg(test)] -pub(crate) fn take_ref_hits() -> [usize; 7] { - std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// Bumps the two histograms for one coded inter block. /// How many blocks this process wrote whose search-chosen `ref_mv_idx` the /// write-time stack could not carry, so the writer signalled a SMALLER index /// (lane-sb128b). Every one of these used to price its residual against a /// predictor the decoder never derives. -pub(super) static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +pub(super) static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); /// Counts one clamped DRL index whose predictor differs from the one the /// search asked for -- the harmful case, and the only one a witness can see. @@ -2214,18 +2093,6 @@ pub(super) fn note_inter_mode(mode: usize, drl: usize) { DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } -/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW). -#[cfg(test)] -pub(crate) fn take_inter_mode_hits() -> [usize; 4] { - [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - -/// Takes and clears the DRL-index histogram (0, 1, 2, 3+). -#[cfg(test)] -pub(crate) fn take_drl_hits() -> [usize; 4] { - [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// Writes the DRL index of one block: the loop the decoder runs (spec /// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one /// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to @@ -2713,13 +2580,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( + usize::from(neighbours.left_skip[mi_r]); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip); - write_delta_q( - &mut enc, - cdfs, - (mi_r, mi_c), - !sb128_armed(), - block.skip, - ); + write_delta_q(&mut enc, cdfs, (mi_r, mi_c), !sb128_armed(), block.skip); let ii_ctx = intra_inter_ctx( has_above, has_left, @@ -2771,12 +2632,6 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( mi_rows as usize, ); let (mv, is_new_mv) = write_inter_mode(&mut enc, cdfs, info, &stack)?; - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}", - info.mode, info.ref_mv_idx, info.mv - )); - } (mv, (0, 0), is_new_mv) }; for dr in 0..SB_MI as usize { @@ -3202,12 +3057,6 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( ); let (mv, is_new_mv) = write_inter_mode(&mut enc, cdfs, info, &stack)?; - if crate::msac::symtrace::dir().is_some() { - crate::msac::symtrace::note(&format!( - " MODE mi=({mi_r},{mi_c}) mode={:?} idx={} mv={mv:?} info_mv={:?}", - info.mode, info.ref_mv_idx, info.mv - )); - } grid.set( mi_row, mi_col, diff --git a/crates/ec-av1/src/tile/mod.rs b/crates/ec-av1/src/tile/mod.rs index 6ff8264e..0233c250 100644 --- a/crates/ec-av1/src/tile/mod.rs +++ b/crates/ec-av1/src/tile/mod.rs @@ -10,10 +10,8 @@ //! off as they arrive. use std::cell::RefCell; -#[cfg(test)] -use std::collections::BTreeMap; use std::sync::LazyLock; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, Ordering}; use ec_core::{Error, Result}; @@ -1275,13 +1273,6 @@ fn filter_intra_armed() -> bool { static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] = [const { std::sync::atomic::AtomicUsize::new(0) }; 6]; -/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the -/// counts to its own encode. -#[cfg(test)] -pub(crate) fn take_filter_intra_hits() -> [usize; 6] { - std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for /// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every /// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <= @@ -1347,13 +1338,6 @@ fn note_intrabc(dv: (i32, i32)) { INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } -/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts -/// to its own encode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn take_intrabc_hits() -> [usize; 7] { - std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - thread_local! { /// This frame header's own `reference_select` bit (spec 5.9.22), armed /// the same way `arm_sign_bias` arms the sign-bias table rather than @@ -1415,13 +1399,6 @@ pub(crate) fn arm_motion_mode(on: bool) { static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] = [const { std::sync::atomic::AtomicUsize::new(0) }; 9]; -/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the -/// counts to its own encode. -#[allow(dead_code)] // read only from the `#[cfg(test)]` gates -pub(crate) fn take_motion_mode_hits() -> [usize; 9] { - std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// What the 3-symbol `motion_mode` symbol costs, in bits, against the same /// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off -- /// which alphabet a block reads is `motion_mode_allowed`'s own choice @@ -1726,19 +1703,6 @@ static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] = static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] = [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; -/// Takes and clears the compound mode histogram. -#[cfg(test)] -pub(crate) fn take_compound_mode_hits() -> [usize; 8] { - std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - -/// Takes and clears the compound pair histogram, indexed by the SECOND -/// reference (`LAST` = 0 .. `ALTREF` = 6). -#[cfg(test)] -pub(crate) fn take_compound_pair_hits() -> [usize; 7] { - std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// Per-SIZE fire counts of [`write_compound_block`], indexed by /// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a /// 32x32-only tool, so the share by size is what says whether the leaf @@ -1746,12 +1710,6 @@ pub(crate) fn take_compound_pair_hits() -> [usize; 7] { static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] = [const { std::sync::atomic::AtomicUsize::new(0) }; 4]; -/// Takes and clears the compound size histogram. -#[cfg(test)] -pub(crate) fn take_compound_size_hits() -> [usize; 4] { - std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) -} - /// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and /// below). The frame-wide histogram above cannot say whether a mode reaches /// the leaves at all, which is exactly the question every leaf compound step @@ -1761,14 +1719,6 @@ pub(crate) fn take_compound_size_hits() -> [usize; 4] { static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] = [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; -/// Takes and clears the leaf-only compound mode histogram. -#[cfg(test)] -pub(crate) fn take_compound_leaf_mode_hits() -> [usize; 8] { - std::array::from_fn(|i| { - COMPOUND_LEAF_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed) - }) -} - /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` / /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that @@ -2493,7 +2443,6 @@ pub fn split_dc_key_frame_tile( mod syntax; pub use self::syntax::*; - mod blocks; pub use self::blocks::*; mod leaf; diff --git a/crates/ec-av1/tests/real_library.rs b/crates/ec-av1/tests/real_library.rs deleted file mode 100644 index d474843c..00000000 --- a/crates/ec-av1/tests/real_library.rs +++ /dev/null @@ -1,287 +0,0 @@ -use std::io::Read; -use std::path::{Path, PathBuf}; -use std::process::{Child, ChildStdout, Stdio}; - -use ec_av1::encode::Picture; - -const FRAMES: usize = 300; - -const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"]; - -fn scratch(tag: &str) -> PathBuf { - let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); - let dir = base.join(format!("ec-av1-{tag}-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir -} - -struct Entry { - path: PathBuf, - container: String, - width: String, - height: String, - pix_fmt: String, -} - -fn open_entries() -> Vec { - vec![Entry { - path: ec_testkit::fixture("derived/sintel720-svtav1.ivf"), - container: "ivf".to_string(), - width: "1280".to_string(), - height: "720".to_string(), - pix_fmt: "yuv420p".to_string(), - }] -} - -fn frame_bytes(pic: &Picture, bps: usize) -> Vec { - let mut out = Vec::with_capacity((pic.y.len() + pic.u.len() + pic.v.len()) * bps); - for plane in [&pic.y, &pic.u, &pic.v] { - for &s in plane.iter() { - if bps == 1 { - out.push(s as u8); - } else { - out.extend_from_slice(&s.to_le_bytes()); - } - } - } - out -} - -fn locate(offset: usize, bps: usize, pic: &Picture) -> (&'static str, usize, usize) { - let s = offset / bps; - let (w, cw) = (pic.width, pic.u.len() / pic.height.div_ceil(2).max(1)); - let luma = pic.y.len(); - if s < luma { - ("Y", s % w, s / w) - } else if s < luma + pic.u.len() { - let c = s - luma; - ("U", c % cw.max(1), c / cw.max(1)) - } else { - let c = s - luma - pic.u.len(); - ("V", c % cw.max(1), c / cw.max(1)) - } -} - -struct Sweep { - out: ChildStdout, - child: Child, - open: bool, - compared: usize, - differing_frames: usize, - first_diff: Option, - oracle_short: bool, - index: usize, - frame_len: usize, - bps: usize, - max_sample: u16, -} - -impl Sweep { - fn take(&mut self, pic: &Picture) { - let index = self.index; - self.index += 1; - if !self.open || self.index > FRAMES { - return; - } - if let Some(&s) = pic.y.iter().chain(&pic.u).chain(&pic.v).max() - && s > self.max_sample - { - self.differing_frames += 1; - self.first_diff.get_or_insert(format!( - "frame {index}: sample {s} above the maximum {}", - self.max_sample - )); - } - let want = frame_bytes(pic, self.bps); - self.frame_len = want.len(); - let mut oracle = vec![0u8; want.len()]; - if self.out.read_exact(&mut oracle).is_err() { - self.open = false; - self.oracle_short = true; - return; - } - self.compared += 1; - if want != oracle { - self.differing_frames += 1; - if self.first_diff.is_none() { - let at = want - .iter() - .zip(&oracle) - .position(|(a, b)| a != b) - .unwrap_or(0); - let (plane, x, y) = locate(at, self.bps, pic); - self.first_diff = Some(format!("frame {index} plane {plane} x={x} y={y}")); - } - } - } - - fn finish(mut self) -> Sweep { - if self.open && self.frame_len > 0 { - let mut probe = vec![0u8; self.frame_len]; - if self.out.read_exact(&mut probe).is_ok() { - self.first_diff.get_or_insert(format!( - "decoder produced {} frames, ffmpeg produced more", - self.index - )); - self.differing_frames += 1; - } - } - let _ = self.child.kill(); - let _ = self.child.wait(); - self - } -} - -fn short_name(path: &Path) -> String { - path.file_name() - .map(|n| n.to_string_lossy().chars().take(38).collect()) - .unwrap_or_default() -} - -fn extract(src: &Path, dst: &Path) -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(src) - .args([ - "-map", - "0:v:0", - "-c", - "copy", - "-frames:v", - &FRAMES.to_string(), - "-f", - "obu", - ]) - .arg(dst) - .status() - .is_ok_and(|s| s.success()) -} - -fn sweep_file(es: &Path, pix_fmt: &str, bit_depth: u32) -> Result { - let bps = if bit_depth > 8 { 2 } else { 1 }; - let mut child = ec_testkit::ffmpeg() - .args(["-v", "error", "-c:v", "libdav1d", "-i"]) - .arg(es) - .args([ - "-frames:v", - &FRAMES.to_string(), - "-f", - "rawvideo", - "-pix_fmt", - pix_fmt, - "-", - ]) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .map_err(|e| e.to_string())?; - let out = child.stdout.take().expect("piped stdout"); - let mut sweep = Sweep { - out, - child, - open: true, - compared: 0, - differing_frames: 0, - first_diff: None, - oracle_short: false, - index: 0, - frame_len: 0, - bps, - max_sample: ((1u32 << bit_depth) - 1) as u16, - }; - let data = std::fs::read(es).map_err(|e| e.to_string())?; - let result = ec_av1::stream::decode_stream_with(&data, |pic, _decode_index, shown| { - if shown { - sweep.take(pic); - } - Ok(()) - }); - let sweep = sweep.finish(); - if let Err(e) = result { - return Err(format!("{e}")); - } - Ok(sweep) -} - -#[test] -fn sintel_av1_stream_matches_ffmpeg() { - let entries = open_entries(); - let dir = scratch("real-library-av1"); - let mut table = String::new(); - let mut decoded = 0usize; - let mut refused = 0usize; - let mut failures = Vec::new(); - - for entry in &entries { - let name = short_name(&entry.path); - let res = format!("{}x{}", entry.width, entry.height); - let bit_depth: u32 = if entry.pix_fmt == "yuv420p10le" { - 10 - } else { - 8 - }; - if !IN_SCOPE_PIX_FMTS.contains(&entry.pix_fmt.as_str()) { - refused += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: pixel format {} is outside 4:2:0 8/10-bit\n", - entry.container, "-", entry.pix_fmt - )); - continue; - } - let es = dir.join("stream.obu"); - if !extract(&entry.path, &es) { - failures.push(format!("{name}: extraction failed")); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR extraction\n", - entry.container, "-" - )); - continue; - } - match sweep_file(&es, &entry.pix_fmt, bit_depth) { - Ok(s) if s.differing_frames > 0 => { - failures.push(format!("{name}: {} frames differ", s.differing_frames)); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} MISMATCH {} of {} frames; first: {}\n", - entry.container, s.compared, s.differing_frames, s.compared, - s.first_diff.clone().unwrap_or_default() - )); - } - Ok(s) => { - decoded += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} bit-exact{}\n", - entry.container, - s.compared, - if s.oracle_short { - " (ffmpeg stopped early)" - } else { - "" - } - )); - } - Err(e) if e.contains("unsupported") => { - refused += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: {e}\n", - entry.container, "-" - )); - } - Err(e) => { - failures.push(format!("{name}: {e}")); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR {e}\n", - entry.container, "-" - )); - } - } - let _ = std::fs::remove_file(&es); - } - let _ = std::fs::remove_dir_all(&dir); - eprintln!("{table}"); - eprintln!( - "real library av1: {decoded} bit-exact, {refused} refused by name, {} failed", - failures.len() - ); - assert!(failures.is_empty(), "{failures:#?}"); - assert!(decoded >= 1, "no real AV1 file was swept end to end"); -}