diff --git a/crates/ec-av1/examples/enc_probe.rs b/crates/ec-av1/examples/enc_probe.rs index 637f3106..8b9da7ca 100644 --- a/crates/ec-av1/examples/enc_probe.rs +++ b/crates/ec-av1/examples/enc_probe.rs @@ -21,7 +21,12 @@ fn main() { let out = Command::new("ffmpeg") .args(["-v", "error", "-i", &clip, "-frames:v", &frames.to_string()]) - .args(["-vf", &format!("scale={width}:{height}")]) + // lane-census: the BD gate's native rows CROP, they do not scale, so + // the census can ask for the gate's own recipe (`EC_ENC_VF`). + .args([ + "-vf", + &std::env::var("EC_ENC_VF").unwrap_or_else(|_| format!("scale={width}:{height}")), + ]) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) .output() .expect("ffmpeg failed to run"); @@ -51,6 +56,11 @@ fn main() { h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); } println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len()); + // lane-census: keep the stream itself when asked, so `syntax_census` + // can read the very bytes this point measured. + if let Ok(dir) = std::env::var("EC_ENC_OUT") { + std::fs::write(format!("{dir}/ours-q{q}.obu"), &e.stream).expect("stream out"); + } if ec_av1::encode::census_on() { let (kinds, luma_rank, chroma_rank) = ec_av1::encode::take_census(); for (name, n) in ec_av1::encode::CENSUS_KINDS.iter().zip(kinds) { diff --git a/crates/ec-av1/examples/syntax_census.rs b/crates/ec-av1/examples/syntax_census.rs new file mode 100644 index 00000000..e578c73a --- /dev/null +++ b/crates/ec-av1/examples/syntax_census.rs @@ -0,0 +1,295 @@ +//! 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) +} + +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), + ); + const REFS: [&str; 8] = + ["INTRA", "LAST", "LAST2", "LAST3", "GOLDEN", "BWDREF", "ALTREF2", "ALTREF"]; + 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(" "), + ); + // 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)); + println!( + " top tables: {}", + tables + .iter() + .take(8) + .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. + 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(); + let p = psnr(&pic.y, &want); + 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(), + ); + } + + 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 new file mode 100644 index 00000000..d5afe15f --- /dev/null +++ b/crates/ec-av1/src/census.rs @@ -0,0 +1,307 @@ +//! 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(); + let armed = *INIT.get_or_init(|| { + let armed = crate::envflags::var("EC_AV1_BITCENSUS").ok().as_deref() == Some("1"); + ON.store(armed, Ordering::Relaxed); + armed + }); + 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, + /// 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, + 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.rs b/crates/ec-av1/src/decode.rs index fe67d29f..ff96665e 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -6158,6 +6158,7 @@ fn read_coeffs( eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}"); } 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}"); @@ -6389,6 +6390,7 @@ 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 { @@ -7273,6 +7275,7 @@ impl Neighbours { 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) @@ -7331,6 +7334,9 @@ 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( @@ -7485,6 +7491,7 @@ 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` @@ -7587,6 +7594,7 @@ 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; @@ -21741,6 +21749,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( ); } let mut dec = SymbolDecoder::new(tile_bytes); + 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, @@ -23989,6 +23998,7 @@ fn read_mv( if joint == 1 || joint == 3 { diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv); } + crate::census::mv(pred.0 + diff.0, pred.1 + diff.1); (pred.0 + diff.0, pred.1 + diff.1) } @@ -27458,6 +27468,7 @@ 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 @@ -27491,6 +27502,7 @@ 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 @@ -27499,6 +27511,7 @@ 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 @@ -29831,6 +29844,7 @@ 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; @@ -29854,11 +29868,13 @@ 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 { @@ -30856,6 +30872,7 @@ 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; @@ -30879,11 +30896,13 @@ 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 { @@ -32301,6 +32320,7 @@ 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 { // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): @@ -32330,6 +32350,7 @@ 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 @@ -32339,6 +32360,7 @@ 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 { @@ -33973,6 +33995,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( fctx.quant_deltas.with(|c| c.set(deltas)); fctx.current_delta_lf.with(|c| c.set([0; 4])); let mut dec = SymbolDecoder::new(data); + 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/lib.rs b/crates/ec-av1/src/lib.rs index 37bea30a..497cca04 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -26,6 +26,7 @@ pub mod bits; 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 61b9cc17..ab975d5b 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -370,11 +370,28 @@ impl<'a> SymbolDecoder<'a> { /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. #[inline] pub fn symbol(&mut self, cdf: &mut [u16]) -> usize { + // 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); update_cdf(cdf, s); + if crate::census::armed() { + crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0); + } s } + /// Bits consumed so far, fractionally -- the read position less the + /// information still held in the range (`log2(range)`, which starts at + /// 15). Differences between two of these are one read's cost; the + /// absolute value carries a constant offset (class `compare-range-not-tell`). + #[must_use] + pub fn tell_bits(&self) -> f64 { + self.bit as f64 - f64::from(self.range).log2() + } + /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec /// uses for the literal and equiprobable reads, mirroring /// [`SymbolEncoder::symbol_fixed`]. @@ -468,6 +485,9 @@ 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.rs b/crates/ec-av1/src/stream.rs index e225c38f..8af6ab4e 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -1382,6 +1382,7 @@ 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 { for segment in 0..MAX_SEGMENTS { for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { diff --git a/lanes/census-filmB.md b/lanes/census-filmB.md new file mode 100644 index 00000000..40796daf --- /dev/null +++ b/lanes/census-filmB.md @@ -0,0 +1,137 @@ +# Syntax census: film B against rav1e speed 6, at matched PSNR + +What this is: a decode-side census of the streams themselves. Both encoders' +output is read by OUR decoder (`examples/syntax_census.rs` + +`crates/ec-av1/src/census.rs`, `EC_AV1_BITCENSUS=1`), so every number below is +the same measurement applied to both sides. Bits are charged per CDF TABLE -- +the accountant maps a symbol's table address to its `Cdfs` field name, so a +coding tool joins the census the day its CDF does, with no call-site labels +(class `gate-blind-to-feature`). The census total tracks the tile payload to +within 0.03% on every stream measured here (e.g. film B ours 596,540 bits +censused vs 596,712 payload bits), and the block funnel covers 100.00% of the +frame area on all four streams -- both printed by the tool. + +Recipe (the native BD gate's own, `native_gate_clips`): 12 frames, gop 12, +one tile, threads 1, 4:2:0 8-bit. +Film A = 1920x768 crop of a 1080p film at 00:35:00. Film B = 1920x1024 crop of +a 2160p HDR film at 00:40:00, converted to 8-bit. Both clips are extracted +once, losslessly, and BOTH encoders read those exact 12 frames. +Ours: `base_q_idx {150,120,90,60}`. rav1e: `speed=6:quantizer={50,100,150,200}: +tile_cols=1:tile_rows=1:threads=1`. + +## Matched points + +Mean luma PSNR over the 12 displayed pictures, computed in the census tool +(ffmpeg's PSNR of an OBU stream is unusable -- no timing; ledger dead-end): + +| clip | ours | rav1e | matched pair | bytes ours | bytes rav1e | delta | +|---|---|---|---|---|---|---| +| film B | q120 46.774 dB | q100 46.636 dB | +0.138 dB apart | 74,589 | 47,256 | **+57.8%** | +| film A | q120 44.602 dB | q100 44.149 dB | +0.453 dB apart (ours better) | 121,888 | 89,386 | +36.4% | +| film A | q90 46.151 dB | q50 46.366 dB | -0.215 dB apart (rav1e better) | 218,303 | 199,850 | +9.2% | + +The film B pair is inside the 0.2 dB window; the film A control has no pair +inside it (the ladders interleave), so both bracketing pairs are given. Film A +at the SAME recipe pair (q120 vs q100) is +36.4% while ours is 0.45 dB ahead +-- i.e. film A's gap is smaller than film B's and is measured with a quality +credit in our favour, which only widens the difference between the two clips. + +## Where the bytes are, per frame type + +| clip | frame type | ours | rav1e | delta | +|---|---|---|---|---| +| film B | key (1) | 14,572 | 25,146 | **-10,574** (ours smaller) | +| film B | arf (3 ours / 5 rav1e) | 37,433 | 20,143 | +17,290 | +| film B | leaf (8 ours / 6 rav1e) | 22,584 | 1,967 | +20,617 (**11.5x**) | +| film A | key (1) | 31,488 | 49,342 | -17,854 (ours smaller) | +| film A | arf | 52,386 | 28,091 | +24,295 | +| film A | leaf | 38,014 | 11,953 | +26,061 (3.2x) | + +The gap is entirely in the INTER frames on both clips, and our key frame is +always the smaller one -- because it is also the worse one: rav1e codes its +key at qindex 68/70 and ours at 120. rav1e's frame-0 luma PSNR on film B is +48.38 dB against our 46.78 dB. + +What separates film B from film A is the LEAF ratio: 11.5x against 3.2x. +Film B is a near-static, dark clip; rav1e's leaves cost 328 bytes each and are +99.2% skip area. Ours cost 2,823 bytes each at 70.0% skip. + +## The census, ours vs rav1e (whole stream, matched point) + +| | film B ours q120 | film B rav1e q100 | film A ours q120 | film A rav1e q100 | +|---|---|---|---|---| +| bytes | 74,589 | 47,256 | 121,888 | 89,386 | +| qindex key/arf/leaf | 120 / 104 / 128 | 68 / 95-112 / 129 | 120 / 104 / 128 | 70 / 97-114 / 131 | +| coded blocks | 27,747 | 10,980 | 24,459 | 14,268 | +| block sizes | 32x32 78.2%, 16x16 18.7%, 8x8 3.1% | **64x64 45.2%**, 16x16 27.2%, 32x32 22.0%, 8x8 5.6% | 32x32 62.4%, 16x16 31.3%, 8x8 6.3% | 16x16 39.7%, 32x32 22.4%, **64x64 22.0%**, 8x8 16.0% | +| luma tx | 32x32 77.6%, 16x16 18.7% | **64x64 45.2%**, 16x16 27.2%, 32x32 22.0% | 32x32 62.4%, 16x16 31.3% | 16x16 39.7%, 32x32 22.4%, 64x64 22.0% | +| area intra / single / compound | 15.2 / 59.7 / 25.1% | 9.0 / 56.4 / 34.6% | 17.0 / 46.3 / 36.6% | 12.1 / 50.9 / 37.0% | +| **skip area** | **52.5%** | **84.8%** | 38.9% | 76.4% | +| refs (area) | LAST 48.8 GOLDEN 28.8 ALTREF 7.3 | LAST 75.1 LAST2 3.0 ALTREF 12.9 | LAST 66.3 GOLDEN 9.0 ALTREF 7.7 | LAST 70.5 LAST2 3.5 ALTREF 13.8 | +| single-ref modes | NEW 11.7 GLOBAL 1.8 NEAREST 79.6 NEAR 7.0 | NEW 22.8 GLOBAL 1.1 NEAREST 58.2 NEAR 17.9 | NEW 16.7 GLOBAL 1.6 NEAREST 72.3 NEAR 9.4 | NEW 20.1 GLOBAL 1.1 NEAREST 57.0 NEAR 21.9 | +| coded mv \|max\| (1/8 pel) | <=8 8.8, <=32 36.0, <=128 44.6, <=512 10.4% | <=8 4.2, <=32 25.8, <=128 55.9, <=512 14.0% | <=8 35.7, <=32 42.7, <=128 20.0% | <=8 27.3, <=32 45.1, <=128 26.9% | +| tx_type symbols | 12,660 (set3/1 78%, set6/1 22%) | 2,108 | 15,511 | 3,762 | +| coeff bits | 329,971 (55.3%) | 230,617 (61.0%) | 610,650 (62.6%) | 471,565 (66.0%) | +| mode bits | 114,631 (19.2%) | 33,154 (8.8%) | 118,197 (12.1%) | 56,582 (7.9%) | +| mv bits | 28,291 (4.7%) | 22,760 (6.0%) | 30,445 (3.1%) | 22,229 (3.1%) | +| partition bits | 16,507 (2.8%) | 6,074 (1.6%) | 19,331 (2.0%) | 9,923 (1.4%) | +| tx_size bits | 3,240 (5,908 symbols) | 0 (no `tx_size` symbol coded) | 3,083 (6,097 symbols) | 0 | +| literal (raw) bits | 101,867 (17.1%) | 84,706 (22.4%) | 190,425 (19.5%) | 153,593 (21.5%) | +| biggest tables | base_luma_32 25.9%, base_luma_16 10.0% | **base_luma_64 28.1%**, base_luma_32 13.0% | base_luma_32 25.2%, base_luma_16 14.1% | base_luma_64 20.1%, base_luma_32 13.1% | +| segmentation / LR | off / off-or-luma-Wiener | on / switchable on all 3 planes | off / luma only | on / all 3 planes | + +Tool fire counts: our streams code no palette, CfL-only chroma aside, no +filter-intra, no warp, no OBMC, no interintra and no wedge symbols on these +two film clips at all -- every one of those tables is absent from the family +list, which is the census saying the tool never fired (film content, screen +tools off). rav1e's streams likewise show no palette/intrabc; it does code +`comp_group_idx`/`inter_compound_mode` (compound 34.6% of area on film B +against our 25.1%). + +## Top 3 differences, ranked by bytes at stake on film B (gap = 27,333 B) + +The three overlap -- they are three views of the same inter-frame failure -- +so the byte figures must not be added. + +1. **Anchor quality and the rate ladder: ~20,600 B (75% of the gap) sits in + the leaves.** rav1e spends its bits on the key frame (53% of its whole + stream) and coasts: qindex 68 key -> 129 leaf, a 61-step spread, leaves + 99.2% skip at 328 B each. Ours codes the key at 120, the ARFs at 104 and + the leaves at 128 -- a 24-step spread with the ARF only 16 below the key -- + so no frame is ever a good enough reference for the next one to skip, and + every leaf re-codes residual (70% skip, 2,823 B each). Mechanism: our + pyramid q offsets are nearly flat and our key is far too coarse. This is + also exactly why film B is twice as far as film A: a near-static clip pays + for a good anchor once and coasts for 11 frames, which is the regime our + allocation cannot enter. +2. **No 64x64 (or 128x128) coded blocks or transforms: ~12,600 B (46%).** + Our largest coded block on both clips is 32x32; rav1e codes 45.2% of film + B's blocks as 64x64 (73.8% of its leaf blocks) and takes 28.1% of its + coefficient bits through `base_luma_64`. We therefore code 27,747 blocks + where rav1e codes 10,980, and our mode+mv+partition+tx_size bits are + 162,669 against rav1e's 61,988: +100,681 bits = +12.6 kB of pure per-block + overhead. On film A the same term is +79k bits (30% of that gap), so the + missing large blocks cost film B relatively more -- flat, static content is + exactly what a 64x64 block is for. +3. **Skip share 52.5% vs 84.8% -> coefficient bits +99,354 bits (+12.4 kB).** + We code residual over ~32 points more of the frame area than rav1e does + (leaves: 70.0% vs 99.2%). Partly a consequence of (1) -- a worse reference + leaves a real residual -- and partly the decision itself: our streams code + 12,660 tx_type symbols against rav1e's 2,108, i.e. we are choosing coded + transforms where rav1e chooses none at all. + +Two smaller, unpriced differences the census also shows, both of which our +encoder simply does not use: segmentation (rav1e enables it on every frame) +and loop restoration on all three planes (rav1e: switchable everywhere; ours: +off, or luma Wiener on about half the frames). + +## Reproducing + +``` +EC_ENC_VF=null EC_ENC_OUT= cargo run --release -p ec-av1 --example enc_probe \ + -- 1920 1024 12 150,120,90,60 +ffmpeg -f rawvideo -pix_fmt yuv420p -s 1920x1024 -r 24 -i clip.yuv -an -threads 1 -g 12 \ + -c:v librav1e -rav1e-params speed=6:quantizer=100:tile_cols=1:tile_rows=1:threads=1 \ + -f obu rav1e-q100.obu +EC_AV1_BITCENSUS=1 cargo run --release -p ec-av1 --example syntax_census -- clip.yuv +```