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/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/coeffs.rs b/crates/ec-av1/src/decode/coeffs.rs index 1aaa5056..ca5635a7 100644 --- a/crates/ec-av1/src/decode/coeffs.rs +++ b/crates/ec-av1/src/decode/coeffs.rs @@ -192,7 +192,6 @@ pub(super) fn read_coeffs( } 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}"); @@ -477,7 +476,6 @@ 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}")) })?; @@ -1638,7 +1636,6 @@ impl Neighbours { "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) @@ -1753,9 +1750,6 @@ impl Neighbours { 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( @@ -1971,7 +1965,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 +2070,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; diff --git a/crates/ec-av1/src/decode/frame_tile.rs b/crates/ec-av1/src/decode/frame_tile.rs index 18b9f4b2..092539f1 100644 --- a/crates/ec-av1/src/decode/frame_tile.rs +++ b/crates/ec-av1/src/decode/frame_tile.rs @@ -542,7 +542,6 @@ 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. diff --git a/crates/ec-av1/src/decode/inter_block.rs b/crates/ec-av1/src/decode/inter_block.rs index a1884b0b..d8cfd153 100644 --- a/crates/ec-av1/src/decode/inter_block.rs +++ b/crates/ec-av1/src/decode/inter_block.rs @@ -2246,7 +2246,6 @@ pub(super) fn decode_inter_block( ); 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, @@ -2283,7 +2282,6 @@ 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 { @@ -2293,7 +2291,6 @@ pub(super) fn decode_inter_block( 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 diff --git a/crates/ec-av1/src/decode/inter_block8.rs b/crates/ec-av1/src/decode/inter_block8.rs index 9111aa85..830431cd 100644 --- a/crates/ec-av1/src/decode/inter_block8.rs +++ b/crates/ec-av1/src/decode/inter_block8.rs @@ -1419,7 +1419,6 @@ pub(super) fn decode_inter_block8( 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 { @@ -1452,7 +1451,6 @@ 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 { @@ -1463,7 +1461,6 @@ pub(super) fn decode_inter_block8( 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 { diff --git a/crates/ec-av1/src/decode/inter_ctx.rs b/crates/ec-av1/src/decode/inter_ctx.rs index 1ee02746..9731874f 100644 --- a/crates/ec-av1/src/decode/inter_ctx.rs +++ b/crates/ec-av1/src/decode/inter_ctx.rs @@ -227,7 +227,6 @@ pub(super) fn read_mv( mv.1.clamp(-MV_LIMIT + 1, MV_LIMIT - 1), ); } - crate::census::mv(mv.0, mv.1); mv } diff --git a/crates/ec-av1/src/decode/key_tile.rs b/crates/ec-av1/src/decode/key_tile.rs index e9fa6c99..d201b4a1 100644 --- a/crates/ec-av1/src/decode/key_tile.rs +++ b/crates/ec-av1/src/decode/key_tile.rs @@ -614,7 +614,6 @@ pub(crate) fn decode_key_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); 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, diff --git a/crates/ec-av1/src/decode/sub8_inter.rs b/crates/ec-av1/src/decode/sub8_inter.rs index b36c1a3b..9c3a403f 100644 --- a/crates/ec-av1/src/decode/sub8_inter.rs +++ b/crates/ec-av1/src/decode/sub8_inter.rs @@ -246,7 +246,6 @@ pub(super) fn decode_inter_sub8_split4( ); 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 { @@ -273,14 +272,12 @@ 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 { @@ -2195,7 +2192,6 @@ pub(super) fn decode_inter_sub8_rect2( ); 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 { @@ -2222,14 +2218,12 @@ 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 { diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index ce7d0062..d78b83c3 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -24,7 +24,6 @@ pub mod bits; mod autothreads; pub mod cdf; mod cdf_state; -pub mod census; mod compound; pub mod decode; pub mod encode; diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 99653ccc..e29af06a 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -458,15 +458,6 @@ impl<'a> SymbolDecoder<'a> { 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 @@ -476,9 +467,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={}", @@ -605,9 +593,6 @@ 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 diff --git a/crates/ec-av1/src/stream/mod.rs b/crates/ec-av1/src/stream/mod.rs index 8201483d..fa6d5a92 100644 --- a/crates/ec-av1/src/stream/mod.rs +++ b/crates/ec-av1/src/stream/mod.rs @@ -1884,7 +1884,6 @@ fn decode_frame( // 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