Merge branch 'lane-census' (eee03662): decode-side syntax and bit census (EC_AV1_BITCENSUS), and the film B answer
Browse files at this commit8 changed files +795 -1
- crates/ec-av1/examples/enc_probe.rs +11 -1
- crates/ec-av1/examples/syntax_census.rs +295 -0
- crates/ec-av1/src/census.rs +307 -0
- crates/ec-av1/src/decode.rs +23 -0
- crates/ec-av1/src/lib.rs +1 -0
- crates/ec-av1/src/msac.rs +20 -0
- crates/ec-av1/src/stream.rs +1 -0
- lanes/census-filmB.md +137 -0
crates/ec-av1/examples/enc_probe.rsmodified+11 -1
| @@ -21,7 +21,12 @@ fn main() { | ||
| 21 | 21 | |
| 22 | 22 | let out = Command::new("ffmpeg") |
| 23 | 23 | .args(["-v", "error", "-i", &clip, "-frames:v", &frames.to_string()]) |
| 24 | - .args(["-vf", &format!("scale={width}:{height}")]) | |
| 24 | + // lane-census: the BD gate's native rows CROP, they do not scale, so | |
| 25 | + // the census can ask for the gate's own recipe (`EC_ENC_VF`). | |
| 26 | + .args([ | |
| 27 | + "-vf", | |
| 28 | + &std::env::var("EC_ENC_VF").unwrap_or_else(|_| format!("scale={width}:{height}")), | |
| 29 | + ]) | |
| 25 | 30 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 26 | 31 | .output() |
| 27 | 32 | .expect("ffmpeg failed to run"); |
| @@ -51,6 +56,11 @@ fn main() { | ||
| 51 | 56 | h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); |
| 52 | 57 | } |
| 53 | 58 | println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len()); |
| 59 | + // lane-census: keep the stream itself when asked, so `syntax_census` | |
| 60 | + // can read the very bytes this point measured. | |
| 61 | + if let Ok(dir) = std::env::var("EC_ENC_OUT") { | |
| 62 | + std::fs::write(format!("{dir}/ours-q{q}.obu"), &e.stream).expect("stream out"); | |
| 63 | + } | |
| 54 | 64 | if ec_av1::encode::census_on() { |
| 55 | 65 | let (kinds, luma_rank, chroma_rank) = ec_av1::encode::take_census(); |
| 56 | 66 | for (name, n) in ec_av1::encode::CENSUS_KINDS.iter().zip(kinds) { |
crates/ec-av1/examples/syntax_census.rsadded+295 -0
| @@ -0,0 +1,295 @@ | ||
| 1 | +//! Syntax census of one AV1 stream: what it actually codes, per frame type. | |
| 2 | +//! | |
| 3 | +//! `EC_AV1_BITCENSUS=1 cargo run --release -p ec-av1 --example syntax_census \ | |
| 4 | +//! -- stream.obu [source.yuv]` | |
| 5 | +//! | |
| 6 | +//! The stream may be a raw OBU stream or an IVF file (unwrapped here). The | |
| 7 | +//! optional second argument is the ENCODER'S INPUT as planar 8-bit yuv420p at | |
| 8 | +//! the coded size, and turns on a per-displayed-frame PSNR -- computed here, | |
| 9 | +//! against the decoded pictures, because ffmpeg's own PSNR of an OBU stream | |
| 10 | +//! reads a constant ~28.8 dB (no timing in an OBU stream; ledger dead-end). | |
| 11 | +//! | |
| 12 | +//! Every number comes from `ec_av1::census`, i.e. from the decoder, so our | |
| 13 | +//! stream and any other encoder's stream are measured by the same reader. | |
| 14 | + | |
| 15 | +use ec_av1::census::Frame; | |
| 16 | +use std::collections::BTreeMap; | |
| 17 | + | |
| 18 | +/// The payloads of an IVF file's frames concatenated, or the data unchanged | |
| 19 | +/// when it is already a raw OBU stream. | |
| 20 | +fn unwrap_ivf(data: &[u8]) -> Vec<u8> { | |
| 21 | + if data.len() < 32 || &data[..4] != b"DKIF" { | |
| 22 | + return data.to_vec(); | |
| 23 | + } | |
| 24 | + let header = u16::from_le_bytes([data[6], data[7]]) as usize; | |
| 25 | + let (mut pos, mut out) = (header, Vec::new()); | |
| 26 | + while pos + 12 <= data.len() { | |
| 27 | + let len = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) | |
| 28 | + as usize; | |
| 29 | + pos += 12; | |
| 30 | + if pos + len > data.len() { | |
| 31 | + break; | |
| 32 | + } | |
| 33 | + out.extend_from_slice(&data[pos..pos + len]); | |
| 34 | + pos += len; | |
| 35 | + } | |
| 36 | + out | |
| 37 | +} | |
| 38 | + | |
| 39 | +fn psnr(a: &[u16], b: &[u16]) -> f64 { | |
| 40 | + let se: f64 = a | |
| 41 | + .iter() | |
| 42 | + .zip(b) | |
| 43 | + .map(|(&x, &y)| { | |
| 44 | + let d = f64::from(x) - f64::from(y); | |
| 45 | + d * d | |
| 46 | + }) | |
| 47 | + .sum(); | |
| 48 | + match se { | |
| 49 | + 0.0 => 99.0, | |
| 50 | + _ => 10.0 * (255.0 * 255.0 * a.len() as f64 / se).log10(), | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// Which broad syntax family a CDF table belongs to. | |
| 55 | +fn family_group(name: &str) -> &'static str { | |
| 56 | + const COEFF: [&str; 7] = | |
| 57 | + ["txb_skip", "eob_pt", "eob_extra", "base_", "base_eob", "br_", "dc_sign"]; | |
| 58 | + if name.contains("tx_type") { | |
| 59 | + return "txtype"; | |
| 60 | + } | |
| 61 | + if COEFF.iter().any(|p| name.starts_with(p)) { | |
| 62 | + return "coeff"; | |
| 63 | + } | |
| 64 | + if name.starts_with("mv_") || name.starts_with("dv_") { | |
| 65 | + return "mv"; | |
| 66 | + } | |
| 67 | + if name.starts_with("partition") || name.starts_with("txfm_partition") { | |
| 68 | + return "partition"; | |
| 69 | + } | |
| 70 | + if name.starts_with("tx_size") { | |
| 71 | + return "txsize"; | |
| 72 | + } | |
| 73 | + if name == "literal" || name == "unregistered" { | |
| 74 | + return "literal"; | |
| 75 | + } | |
| 76 | + "mode" | |
| 77 | +} | |
| 78 | + | |
| 79 | +/// Sums a set of frames into one row's worth of census. | |
| 80 | +fn merge(frames: &[&Frame]) -> Frame { | |
| 81 | + let mut out = Frame::default(); | |
| 82 | + for f in frames { | |
| 83 | + out.bytes += f.bytes; | |
| 84 | + for (k, v) in &f.blocks { | |
| 85 | + *out.blocks.entry(*k).or_default() += v; | |
| 86 | + } | |
| 87 | + for (k, v) in &f.tx { | |
| 88 | + *out.tx.entry(*k).or_default() += v; | |
| 89 | + } | |
| 90 | + for (k, v) in &f.tx_type { | |
| 91 | + *out.tx_type.entry(*k).or_default() += v; | |
| 92 | + } | |
| 93 | + for (k, v) in &f.families { | |
| 94 | + let e = out.families.entry(k).or_default(); | |
| 95 | + e.0 += v.0; | |
| 96 | + e.1 += v.1; | |
| 97 | + } | |
| 98 | + for i in 0..3 { | |
| 99 | + out.area[i] += f.area[i]; | |
| 100 | + } | |
| 101 | + for i in 0..8 { | |
| 102 | + out.refs[i] += f.refs[i]; | |
| 103 | + } | |
| 104 | + for i in 0..4 { | |
| 105 | + out.modes[i] += f.modes[i]; | |
| 106 | + } | |
| 107 | + for i in 0..6 { | |
| 108 | + out.mv[i] += f.mv[i]; | |
| 109 | + } | |
| 110 | + out.skip_area += f.skip_area; | |
| 111 | + } | |
| 112 | + out | |
| 113 | +} | |
| 114 | + | |
| 115 | +fn pct(n: u64, total: u64) -> String { | |
| 116 | + format!("{:.1}%", 100.0 * n as f64 / total.max(1) as f64) | |
| 117 | +} | |
| 118 | + | |
| 119 | +fn report(label: &str, f: &Frame, frames: usize) { | |
| 120 | + let area = f.area.iter().sum::<u64>().max(1); | |
| 121 | + println!("\n== {label} ({frames} frames, {} bytes) ==", f.bytes); | |
| 122 | + println!( | |
| 123 | + " area: intra {} single-ref {} compound {} | skip {}", | |
| 124 | + pct(f.area[0], area), | |
| 125 | + pct(f.area[1], area), | |
| 126 | + pct(f.area[2], area), | |
| 127 | + pct(f.skip_area, area), | |
| 128 | + ); | |
| 129 | + const REFS: [&str; 8] = | |
| 130 | + ["INTRA", "LAST", "LAST2", "LAST3", "GOLDEN", "BWDREF", "ALTREF2", "ALTREF"]; | |
| 131 | + println!( | |
| 132 | + " refs (area): {}", | |
| 133 | + REFS.iter() | |
| 134 | + .enumerate() | |
| 135 | + .filter(|(i, _)| f.refs[*i] > 0) | |
| 136 | + .map(|(i, n)| format!("{n} {}", pct(f.refs[i], area))) | |
| 137 | + .collect::<Vec<_>>() | |
| 138 | + .join(" "), | |
| 139 | + ); | |
| 140 | + let modes = f.modes.iter().sum::<u64>(); | |
| 141 | + println!( | |
| 142 | + " single-ref modes: NEW {} GLOBAL {} NEAREST {} NEAR {} (of {modes})", | |
| 143 | + pct(f.modes[0], modes), | |
| 144 | + pct(f.modes[1], modes), | |
| 145 | + pct(f.modes[2], modes), | |
| 146 | + pct(f.modes[3], modes), | |
| 147 | + ); | |
| 148 | + let mvs = f.mv.iter().sum::<u64>(); | |
| 149 | + println!( | |
| 150 | + " coded mv |max| (1/8 pel): 0 {} <=8 {} <=32 {} <=128 {} <=512 {} >512 {} (of {mvs})", | |
| 151 | + pct(f.mv[0], mvs), | |
| 152 | + pct(f.mv[1], mvs), | |
| 153 | + pct(f.mv[2], mvs), | |
| 154 | + pct(f.mv[3], mvs), | |
| 155 | + pct(f.mv[4], mvs), | |
| 156 | + pct(f.mv[5], mvs), | |
| 157 | + ); | |
| 158 | + let blocks: u64 = f.blocks.values().sum(); | |
| 159 | + let mut by_size: Vec<_> = f.blocks.iter().collect(); | |
| 160 | + by_size.sort_by_key(|(_, n)| std::cmp::Reverse(**n)); | |
| 161 | + println!( | |
| 162 | + " blocks ({blocks} total): {}", | |
| 163 | + by_size | |
| 164 | + .iter() | |
| 165 | + .take(10) | |
| 166 | + .map(|((w, h), n)| format!("{w}x{h} {}", pct(**n, blocks))) | |
| 167 | + .collect::<Vec<_>>() | |
| 168 | + .join(" "), | |
| 169 | + ); | |
| 170 | + let txs: u64 = f.tx.values().sum(); | |
| 171 | + let mut by_tx: Vec<_> = f.tx.iter().collect(); | |
| 172 | + by_tx.sort_by_key(|(_, n)| std::cmp::Reverse(**n)); | |
| 173 | + println!( | |
| 174 | + " published luma tx ({txs}): {}", | |
| 175 | + by_tx | |
| 176 | + .iter() | |
| 177 | + .take(8) | |
| 178 | + .map(|((w, h), n)| format!("{w}x{h} {}", pct(**n, txs))) | |
| 179 | + .collect::<Vec<_>>() | |
| 180 | + .join(" "), | |
| 181 | + ); | |
| 182 | + let tts: u64 = f.tx_type.values().sum(); | |
| 183 | + println!( | |
| 184 | + " tx_type symbols ({tts}): {}", | |
| 185 | + f.tx_type | |
| 186 | + .iter() | |
| 187 | + .map(|((len, sym), n)| format!("set{len}/{sym} {}", pct(*n, tts))) | |
| 188 | + .collect::<Vec<_>>() | |
| 189 | + .join(" "), | |
| 190 | + ); | |
| 191 | + // Bits by family group, then the ten biggest tables inside them. | |
| 192 | + let mut groups: BTreeMap<&str, (u64, f64)> = BTreeMap::new(); | |
| 193 | + for (name, (n, bits)) in &f.families { | |
| 194 | + let e = groups.entry(family_group(name)).or_default(); | |
| 195 | + e.0 += n; | |
| 196 | + e.1 += bits; | |
| 197 | + } | |
| 198 | + let total_bits: f64 = groups.values().map(|g| g.1).sum(); | |
| 199 | + println!(" bits by family (census total {:.0} bits vs {} payload bits):", total_bits, f.bytes * 8); | |
| 200 | + for (g, (n, bits)) in &groups { | |
| 201 | + println!( | |
| 202 | + " {g:<10} {:>12.0} bits {:>6} ({n} symbols)", | |
| 203 | + bits, | |
| 204 | + format!("{:.1}%", 100.0 * bits / total_bits.max(1.0)) | |
| 205 | + ); | |
| 206 | + } | |
| 207 | + let mut tables: Vec<_> = f.families.iter().collect(); | |
| 208 | + tables.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1)); | |
| 209 | + println!( | |
| 210 | + " top tables: {}", | |
| 211 | + tables | |
| 212 | + .iter() | |
| 213 | + .take(8) | |
| 214 | + .map(|(name, (_, bits))| format!("{name} {:.1}%", 100.0 * bits / total_bits.max(1.0))) | |
| 215 | + .collect::<Vec<_>>() | |
| 216 | + .join(" "), | |
| 217 | + ); | |
| 218 | +} | |
| 219 | + | |
| 220 | +fn main() { | |
| 221 | + let args: Vec<String> = std::env::args().skip(1).collect(); | |
| 222 | + let Some(path) = args.first() else { | |
| 223 | + eprintln!("usage: syntax_census <stream.obu|stream.ivf> [source.yuv]"); | |
| 224 | + std::process::exit(2); | |
| 225 | + }; | |
| 226 | + assert!(ec_av1::census::on(), "set EC_AV1_BITCENSUS=1"); | |
| 227 | + let data = unwrap_ivf(&std::fs::read(path).expect("stream")); | |
| 228 | + let pictures = ec_av1::stream::decode_stream(&data).expect("decode"); | |
| 229 | + let frames = ec_av1::census::take(); | |
| 230 | + | |
| 231 | + println!("# syntax census of {path} ({} bytes)", data.len()); | |
| 232 | + println!("\n| frame | kind | q | bytes | lf | cdef bits/y/uv | lr | dq | seg |"); | |
| 233 | + println!("|---|---|---|---|---|---|---|---|---|"); | |
| 234 | + for f in &frames { | |
| 235 | + println!( | |
| 236 | + "| {} | {} | {} | {} | {}/{} | {}/{}/{} | {:?} | {} | {} |", | |
| 237 | + f.idx, | |
| 238 | + f.kind, | |
| 239 | + f.qindex, | |
| 240 | + f.bytes, | |
| 241 | + f.lf[0], | |
| 242 | + f.lf[1], | |
| 243 | + f.cdef[0], | |
| 244 | + f.cdef[1], | |
| 245 | + f.cdef[2], | |
| 246 | + f.lr, | |
| 247 | + u8::from(f.delta_q), | |
| 248 | + u8::from(f.segmentation), | |
| 249 | + ); | |
| 250 | + } | |
| 251 | + // PSNR is per DISPLAYED picture, in display order, which is not the order | |
| 252 | + // the frames above are coded in (a pyramid codes a hidden ARF ahead of the | |
| 253 | + // leaves that predict from it, and re-outputs it later with | |
| 254 | + // `show_existing_frame`) -- so it is its own table rather than a column. | |
| 255 | + if let Some(src) = args.get(1).map(|p| std::fs::read(p).expect("source")) { | |
| 256 | + let mut sum = 0.0; | |
| 257 | + let mut rows = Vec::new(); | |
| 258 | + for (i, pic) in pictures.iter().enumerate() { | |
| 259 | + let (luma, chroma) = (pic.width * pic.height, pic.width * pic.height / 4); | |
| 260 | + let frame_len = luma + 2 * chroma; | |
| 261 | + let Some(b) = src.get(i * frame_len..(i + 1) * frame_len) else { break }; | |
| 262 | + let want: Vec<u16> = b[..luma].iter().map(|&v| u16::from(v)).collect(); | |
| 263 | + let p = psnr(&pic.y, &want); | |
| 264 | + sum += p; | |
| 265 | + rows.push(format!("{i}:{p:.2}")); | |
| 266 | + } | |
| 267 | + println!( | |
| 268 | + "\nPSNR-Y display order ({} pictures): {}\nPSNR-Y mean {:.3} dB over {} pictures", | |
| 269 | + pictures.len(), | |
| 270 | + rows.join(" "), | |
| 271 | + sum / rows.len() as f64, | |
| 272 | + rows.len(), | |
| 273 | + ); | |
| 274 | + } | |
| 275 | + | |
| 276 | + for kind in ["key", "arf", "leaf"] { | |
| 277 | + let set: Vec<&Frame> = frames.iter().filter(|f| f.kind == kind).collect(); | |
| 278 | + if !set.is_empty() { | |
| 279 | + report(kind, &merge(&set), set.len()); | |
| 280 | + } | |
| 281 | + } | |
| 282 | + report("ALL", &merge(&frames.iter().collect::<Vec<_>>()), frames.len()); | |
| 283 | + // The self-check: every coded block is published exactly once, so the | |
| 284 | + // censused area must be the frame's own mi area (a funnel that misses a | |
| 285 | + // block class would silently under-count every share above). | |
| 286 | + if let Some(pic) = pictures.first() { | |
| 287 | + let all = merge(&frames.iter().collect::<Vec<_>>()); | |
| 288 | + let want = (pic.width.div_ceil(4) * pic.height.div_ceil(4) * frames.len()) as u64; | |
| 289 | + let got = all.area.iter().sum::<u64>(); | |
| 290 | + println!( | |
| 291 | + "\ncoverage: censused block area {got} of {want} mi ({:.2}%)", | |
| 292 | + 100.0 * got as f64 / want as f64 | |
| 293 | + ); | |
| 294 | + } | |
| 295 | +} |
crates/ec-av1/src/census.rsadded+307 -0
| @@ -0,0 +1,307 @@ | ||
| 1 | +//! Syntax census: what a stream actually codes, per frame, read off the | |
| 2 | +//! decoder itself (`EC_AV1_BITCENSUS=1`). | |
| 3 | +//! | |
| 4 | +//! Every number here is a decode-side observation, so OUR stream and any | |
| 5 | +//! other encoder's stream are measured by the same reader -- which is the | |
| 6 | +//! whole point: a BD-rate gap says our stream is bigger, it never says which | |
| 7 | +//! syntax it is bigger in. The accountant is off by default and costs one | |
| 8 | +//! relaxed atomic load per symbol when off. | |
| 9 | +//! | |
| 10 | +//! Bits are charged per CDF TABLE, not per hand-labelled call site: a tile | |
| 11 | +//! registers the address range of every field of its `Cdfs` (see | |
| 12 | +//! [`register_cdfs`]), and [`charge`] maps the table a symbol read to that | |
| 13 | +//! field's name. So a new coding tool joins the census the day its CDF joins | |
| 14 | +//! the struct, with no call-site edits (class `gate-blind-to-feature`). | |
| 15 | +//! | |
| 16 | +//! Run it through `examples/syntax_census.rs`; `EC_AV1_THREADS` must be 1 | |
| 17 | +//! (the default) so the frame the counters attribute to is the frame being | |
| 18 | +//! parsed. | |
| 19 | + | |
| 20 | +use std::collections::BTreeMap; | |
| 21 | +use std::sync::atomic::{AtomicBool, Ordering}; | |
| 22 | +use std::sync::{Mutex, OnceLock}; | |
| 23 | + | |
| 24 | +static ON: AtomicBool = AtomicBool::new(false); | |
| 25 | + | |
| 26 | +/// Whether the accountant is armed (`EC_AV1_BITCENSUS=1`, read once). | |
| 27 | +#[inline] | |
| 28 | +pub fn on() -> bool { | |
| 29 | + static INIT: OnceLock<bool> = OnceLock::new(); | |
| 30 | + let armed = *INIT.get_or_init(|| { | |
| 31 | + let armed = crate::envflags::var("EC_AV1_BITCENSUS").ok().as_deref() == Some("1"); | |
| 32 | + ON.store(armed, Ordering::Relaxed); | |
| 33 | + armed | |
| 34 | + }); | |
| 35 | + armed | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// The per-symbol fast path: one relaxed load, nothing else, when off. | |
| 39 | +#[inline] | |
| 40 | +pub(crate) fn armed() -> bool { | |
| 41 | + ON.load(Ordering::Relaxed) | |
| 42 | +} | |
| 43 | + | |
| 44 | +/// One coded frame's census. | |
| 45 | +#[derive(Default, Debug, Clone)] | |
| 46 | +pub struct Frame { | |
| 47 | + /// Decode-order index. | |
| 48 | + pub idx: usize, | |
| 49 | + /// `key` (intra), `arf` (coded but not shown) or `leaf` (coded and shown). | |
| 50 | + pub kind: &'static str, | |
| 51 | + /// `base_q_idx`. | |
| 52 | + pub qindex: u8, | |
| 53 | + /// Tile payload bytes of this frame. | |
| 54 | + pub bytes: usize, | |
| 55 | + /// `delta_q_present`. | |
| 56 | + pub delta_q: bool, | |
| 57 | + /// `segmentation_enabled`. | |
| 58 | + pub segmentation: bool, | |
| 59 | + /// `loop_filter_level[0..2]`. | |
| 60 | + pub lf: [u8; 2], | |
| 61 | + /// `cdef_bits`, `cdef_y_pri_strength[0]`, `cdef_uv_pri_strength[0]`. | |
| 62 | + pub cdef: [u8; 3], | |
| 63 | + /// `FrameRestorationType` per plane. | |
| 64 | + pub lr: [u8; 3], | |
| 65 | + /// Coded block shapes: (width, height) in pixels -> block count. | |
| 66 | + pub blocks: BTreeMap<(u16, u16), u64>, | |
| 67 | + /// Luma area (in 4x4 units) coded intra / single-ref inter / compound. | |
| 68 | + pub area: [u64; 3], | |
| 69 | + /// Luma area per reference frame slot (index 0 = intra, 1..=7 = | |
| 70 | + /// LAST..ALTREF as `ref_frame` names them). | |
| 71 | + pub refs: [u64; 8], | |
| 72 | + /// Luma area with `skip` set. | |
| 73 | + pub skip_area: u64, | |
| 74 | + /// NEWMV / GLOBALMV / NEARESTMV / NEARMV blocks (single-ref reads). | |
| 75 | + pub modes: [u64; 4], | |
| 76 | + /// Coded motion vectors bucketed by max(|x|,|y|) in eighth-pel: | |
| 77 | + /// 0, <=8 (1px), <=32, <=128, <=512, >512. | |
| 78 | + pub mv: [u64; 6], | |
| 79 | + /// Published luma transform shapes: (width, height) in pixels -> count. | |
| 80 | + pub tx: BTreeMap<(u16, u16), u64>, | |
| 81 | + /// Coded `tx_type` symbols: (CDF row length, symbol) -> count. The row | |
| 82 | + /// length names the transform SET (17 = all 16 types, 13, 8, 6 = the | |
| 83 | + /// reduced sets); symbol 0 is that set's first inverse-table entry. | |
| 84 | + pub tx_type: BTreeMap<(u8, u8), u64>, | |
| 85 | + /// Per-CDF-table (symbol count, bits). | |
| 86 | + pub families: BTreeMap<&'static str, (u64, f64)>, | |
| 87 | +} | |
| 88 | + | |
| 89 | +#[derive(Default)] | |
| 90 | +struct State { | |
| 91 | + frames: Vec<Frame>, | |
| 92 | + /// Sorted (start address, end address, field name) of the live tile's | |
| 93 | + /// `Cdfs`. | |
| 94 | + tables: Vec<(usize, usize, &'static str)>, | |
| 95 | + /// Area of the block most recently published, so `compound` can move it. | |
| 96 | + last_block_area: u64, | |
| 97 | +} | |
| 98 | + | |
| 99 | +fn state() -> &'static Mutex<State> { | |
| 100 | + static S: OnceLock<Mutex<State>> = OnceLock::new(); | |
| 101 | + S.get_or_init(|| Mutex::new(State::default())) | |
| 102 | +} | |
| 103 | + | |
| 104 | +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { | |
| 105 | + f(&mut state().lock().unwrap_or_else(std::sync::PoisonError::into_inner)) | |
| 106 | +} | |
| 107 | + | |
| 108 | +fn cur(s: &mut State) -> &mut Frame { | |
| 109 | + if s.frames.is_empty() { | |
| 110 | + s.frames.push(Frame::default()); | |
| 111 | + } | |
| 112 | + s.frames.last_mut().expect("pushed above") | |
| 113 | +} | |
| 114 | + | |
| 115 | +/// Every frame censused since the last call, and clears the record. | |
| 116 | +pub fn take() -> Vec<Frame> { | |
| 117 | + with(|s| std::mem::take(&mut s.frames)) | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// Opens a new frame's row -- called once per coded frame, before its tiles. | |
| 121 | +pub(crate) fn frame_start(header: &ec_av1_syntax::FrameHeader, bytes: usize, idx: usize) { | |
| 122 | + if !armed() { | |
| 123 | + return; | |
| 124 | + } | |
| 125 | + let kind = match (header.frame_is_intra, header.show_frame) { | |
| 126 | + (true, _) => "key", | |
| 127 | + (false, false) => "arf", | |
| 128 | + (false, true) => "leaf", | |
| 129 | + }; | |
| 130 | + with(|s| { | |
| 131 | + s.frames.push(Frame { | |
| 132 | + idx, | |
| 133 | + kind, | |
| 134 | + qindex: header.quantization.base_q_idx, | |
| 135 | + bytes, | |
| 136 | + delta_q: header.delta.q_present, | |
| 137 | + segmentation: header.segmentation.enabled, | |
| 138 | + lf: [header.loop_filter.level[0], header.loop_filter.level[1]], | |
| 139 | + cdef: [ | |
| 140 | + header.cdef.bits, | |
| 141 | + header.cdef.y_pri_strength[0], | |
| 142 | + header.cdef.uv_pri_strength[0], | |
| 143 | + ], | |
| 144 | + lr: [ | |
| 145 | + header.loop_restoration.frame_restoration_type[0] as u8, | |
| 146 | + header.loop_restoration.frame_restoration_type[1] as u8, | |
| 147 | + header.loop_restoration.frame_restoration_type[2] as u8, | |
| 148 | + ], | |
| 149 | + ..Frame::default() | |
| 150 | + }); | |
| 151 | + }); | |
| 152 | +} | |
| 153 | + | |
| 154 | +/// Registers the address range of every CDF table of the tile's own `Cdfs`, | |
| 155 | +/// so [`charge`] can name the family a symbol was read with. Called once per | |
| 156 | +/// tile, right where the tile's symbol decoder is built. | |
| 157 | +pub(crate) fn register_cdfs(c: &crate::cdf_state::Cdfs) { | |
| 158 | + if !armed() { | |
| 159 | + return; | |
| 160 | + } | |
| 161 | + macro_rules! ranges { | |
| 162 | + ($($name:ident),* $(,)?) => { | |
| 163 | + vec![$({ | |
| 164 | + let start = std::ptr::addr_of!(c.$name) as usize; | |
| 165 | + (start, start + std::mem::size_of_val(&c.$name), stringify!($name)) | |
| 166 | + }),*] | |
| 167 | + }; | |
| 168 | + } | |
| 169 | + let mut tables: Vec<(usize, usize, &'static str)> = ranges![ | |
| 170 | + partition_w128, partition_w64, partition_w32, txfm_partition, skip, kf_y_mode, | |
| 171 | + uv_mode_no_cfl, uv_mode_cfl, cfl_sign, cfl_alpha, angle_delta, txb_skip_luma_16, | |
| 172 | + txb_skip_luma_8, txb_skip_luma_4, txb_skip_chroma_8, txb_skip_chroma_4, eob_pt_256_luma, eob_pt_64_luma, | |
| 173 | + 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, | |
| 174 | + 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, | |
| 175 | + 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, | |
| 176 | + eob_extra_luma_16, eob_extra_luma_8, eob_extra_luma_4, eob_extra_chroma_8, eob_extra_chroma_4, base_luma_16, | |
| 177 | + base_luma_8, base_luma_4, base_chroma_8, base_chroma_4, base_eob_luma_16, base_eob_luma_8, | |
| 178 | + base_eob_luma_4, base_eob_chroma_8, base_eob_chroma_4, br_luma_16, br_luma_8, br_luma_4, | |
| 179 | + br_chroma_8, br_chroma_4, partition_w16, partition_w8, txb_skip_luma_32, txb_skip_luma_64, | |
| 180 | + txb_skip_chroma_16, txb_skip_chroma_32, eob_pt_1024_luma, eob_pt_1024_chroma, eob_pt_256_chroma, eob_pt_512_luma, | |
| 181 | + eob_pt_128_chroma, eob_pt_512_chroma, eob_pt_128_luma, eob_pt_32_chroma, eob_extra_luma_32, eob_extra_luma_64, | |
| 182 | + eob_extra_chroma_16, eob_extra_chroma_32, base_luma_32, base_luma_64, base_chroma_16, base_chroma_32, | |
| 183 | + base_eob_luma_32, base_eob_luma_64, base_eob_chroma_16, base_eob_chroma_32, br_luma_32, br_chroma_16, | |
| 184 | + br_chroma_32, dc_sign_luma, intra_tx_type_16, intra_tx_type_8, intra_tx_type_8_set1, intra_tx_type_4, | |
| 185 | + 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, | |
| 186 | + inter_tx_type_4, inter_tx_type_4_set1, dc_sign_chroma, intra_inter, single_ref, comp_mode, | |
| 187 | + skip_mode, obmc, motion_mode, interintra, interintra_mode, wedge_interintra, | |
| 188 | + compound_type, wedge_idx, inter_compound_mode, comp_ref_type, uni_comp_ref, comp_ref, | |
| 189 | + comp_bwdref, comp_group_idx, compound_idx, y_mode, new_mv, zero_mv, | |
| 190 | + ref_mv, drl_mode, mv_joint, mv_comp, dv_joint, dv_comp, | |
| 191 | + filter_intra, filter_intra_mode, tx_size_cat0, tx_size_cat1, tx_size_cat2, tx_size_cat3, | |
| 192 | + switchable_interp, palette_y_mode, palette_y_size, palette_uv_mode, palette_uv_size, palette_y_color_index, | |
| 193 | + palette_uv_color_index, intrabc, restore_wiener, restore_sgrproj, restore_switchable, segment_id, | |
| 194 | + segment_pred, delta_q, delta_lf, delta_lf_multi | |
| 195 | + ]; | |
| 196 | + tables.sort_unstable(); | |
| 197 | + with(|s| s.tables = tables); | |
| 198 | +} | |
| 199 | + | |
| 200 | +/// Charges `bits` to whichever CDF table `addr` falls inside. | |
| 201 | +pub(crate) fn charge(addr: usize, bits: f64) { | |
| 202 | + with(|s| { | |
| 203 | + let name = match s.tables.partition_point(|t| t.0 <= addr) { | |
| 204 | + 0 => "unregistered", | |
| 205 | + i if s.tables[i - 1].1 > addr => s.tables[i - 1].2, | |
| 206 | + _ => "unregistered", | |
| 207 | + }; | |
| 208 | + let e = cur(s).families.entry(name).or_default(); | |
| 209 | + e.0 += 1; | |
| 210 | + e.1 += bits; | |
| 211 | + }); | |
| 212 | +} | |
| 213 | + | |
| 214 | +/// Charges raw (equiprobable) bits, which no CDF names. | |
| 215 | +pub(crate) fn charge_literal(bits: u32) { | |
| 216 | + with(|s| { | |
| 217 | + let e = cur(s).families.entry("literal").or_default(); | |
| 218 | + e.0 += u64::from(bits); | |
| 219 | + e.1 += f64::from(bits); | |
| 220 | + }); | |
| 221 | +} | |
| 222 | + | |
| 223 | +/// One coded block, from the neighbour publisher every block routes through. | |
| 224 | +pub(crate) fn block(w_mi: usize, h_mi: usize, is_inter: bool, ref_frame: i8, skip: bool) { | |
| 225 | + if !armed() { | |
| 226 | + return; | |
| 227 | + } | |
| 228 | + let area = (w_mi * h_mi) as u64; | |
| 229 | + with(|s| { | |
| 230 | + s.last_block_area = area; | |
| 231 | + let f = cur(s); | |
| 232 | + *f.blocks.entry(((w_mi * 4) as u16, (h_mi * 4) as u16)).or_default() += 1; | |
| 233 | + f.area[usize::from(is_inter)] += area; | |
| 234 | + f.refs[(ref_frame.max(0) as usize).min(7)] += area; | |
| 235 | + if skip { | |
| 236 | + f.skip_area += area; | |
| 237 | + } | |
| 238 | + }); | |
| 239 | +} | |
| 240 | + | |
| 241 | +/// The block just published is compound (two references) -- called from the | |
| 242 | +/// compound-context publisher, which runs right after [`block`]. | |
| 243 | +pub(crate) fn compound() { | |
| 244 | + if !armed() { | |
| 245 | + return; | |
| 246 | + } | |
| 247 | + with(|s| { | |
| 248 | + let area = s.last_block_area; | |
| 249 | + let f = cur(s); | |
| 250 | + f.area[1] = f.area[1].saturating_sub(area); | |
| 251 | + f.area[2] += area; | |
| 252 | + }); | |
| 253 | +} | |
| 254 | + | |
| 255 | +/// One block's published luma transform shape. | |
| 256 | +pub(crate) fn tx(w_px: u8, h_px: u8) { | |
| 257 | + if !armed() { | |
| 258 | + return; | |
| 259 | + } | |
| 260 | + with(|s| *cur(s).tx.entry((u16::from(w_px), u16::from(h_px))).or_default() += 1); | |
| 261 | +} | |
| 262 | + | |
| 263 | +/// One coded motion vector (a NEWMV read). | |
| 264 | +pub(crate) fn mv(x: i32, y: i32) { | |
| 265 | + if !armed() { | |
| 266 | + return; | |
| 267 | + } | |
| 268 | + let m = x.abs().max(y.abs()); | |
| 269 | + let bucket = match m { | |
| 270 | + 0 => 0, | |
| 271 | + 1..=8 => 1, | |
| 272 | + 9..=32 => 2, | |
| 273 | + 33..=128 => 3, | |
| 274 | + 129..=512 => 4, | |
| 275 | + _ => 5, | |
| 276 | + }; | |
| 277 | + with(|s| cur(s).mv[bucket] += 1); | |
| 278 | +} | |
| 279 | + | |
| 280 | +/// One single-ref inter mode decision: 0 NEWMV, 1 GLOBALMV, 2 NEARESTMV, | |
| 281 | +/// 3 NEARMV. | |
| 282 | +pub(crate) fn mode(which: usize) { | |
| 283 | + if !armed() { | |
| 284 | + return; | |
| 285 | + } | |
| 286 | + with(|s| cur(s).modes[which] += 1); | |
| 287 | +} | |
| 288 | + | |
| 289 | +/// One coded `tx_type` symbol, with the CDF row length that names its set. | |
| 290 | +pub(crate) fn tx_type(len: usize, symbol: usize) { | |
| 291 | + if !armed() { | |
| 292 | + return; | |
| 293 | + } | |
| 294 | + with(|s| *cur(s).tx_type.entry((len as u8, symbol as u8)).or_default() += 1); | |
| 295 | +} | |
| 296 | + | |
| 297 | +/// One coded block of an INTRA frame, from the `blk_grid` publisher every | |
| 298 | +/// block writes -- a no-op on an inter frame, where [`block`] (the inter | |
| 299 | +/// neighbour publisher, which knows the reference) counts instead. | |
| 300 | +pub(crate) fn block_intra_frame(w_mi: usize, h_mi: usize, skip: bool) { | |
| 301 | + if !armed() { | |
| 302 | + return; | |
| 303 | + } | |
| 304 | + if with(|s| cur(s).kind == "key") { | |
| 305 | + block(w_mi, h_mi, false, 0, skip); | |
| 306 | + } | |
| 307 | +} |
crates/ec-av1/src/decode.rsmodified+23 -0
| @@ -6158,6 +6158,7 @@ fn read_coeffs( | ||
| 6158 | 6158 | eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}"); |
| 6159 | 6159 | } |
| 6160 | 6160 | let t = dec.symbol(tx_type_cdf); |
| 6161 | + crate::census::tx_type(len, t); | |
| 6161 | 6162 | if coeff_trace_on() { |
| 6162 | 6163 | let (rng, _) = dec.debug_state(); |
| 6163 | 6164 | eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}"); |
| @@ -6389,6 +6390,7 @@ fn read_coeffs_rect( | ||
| 6389 | 6390 | if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() { |
| 6390 | 6391 | let len = tx_type_cdf.len(); |
| 6391 | 6392 | let t = dec.symbol(tx_type_cdf); |
| 6393 | + crate::census::tx_type(len, t); | |
| 6392 | 6394 | tx_type = tx_type_from_symbol(len, t) |
| 6393 | 6395 | .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?; |
| 6394 | 6396 | if rect_trace { |
| @@ -7273,6 +7275,7 @@ impl Neighbours { | ||
| 7273 | 7275 | if crate::envflags::env_flag!("EC_TXGRID_TRACE") { |
| 7274 | 7276 | 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}"); |
| 7275 | 7277 | } |
| 7278 | + crate::census::tx(tx_px, tx_h_px); | |
| 7276 | 7279 | let cur = fctx.current_delta_lf.with(|c| c.get()); |
| 7277 | 7280 | let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) { |
| 7278 | 7281 | std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8) |
| @@ -7331,6 +7334,9 @@ impl Neighbours { | ||
| 7331 | 7334 | if skip && w_mi != h_mi { |
| 7332 | 7335 | hit!(RECT_SKIP_BAND_HITS); |
| 7333 | 7336 | } |
| 7337 | + // lane-census: an INTRA frame's blocks never reach the inter | |
| 7338 | + // publisher, and this one is what every coded block writes. | |
| 7339 | + crate::census::block_intra_frame(w_mi, h_mi, skip); | |
| 7334 | 7340 | for rr in 0..h_mi { |
| 7335 | 7341 | let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c; |
| 7336 | 7342 | fill_span( |
| @@ -7485,6 +7491,7 @@ impl Neighbours { | ||
| 7485 | 7491 | skip_mode: bool, |
| 7486 | 7492 | ) { |
| 7487 | 7493 | let (r, c) = at_mi; |
| 7494 | + crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip); | |
| 7488 | 7495 | // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY |
| 7489 | 7496 | // writes for a whole block class): an INTER block left the luma mode |
| 7490 | 7497 | // map untouched, so a later intra block's `get_intra_edge_filter_type` |
| @@ -7587,6 +7594,7 @@ impl Neighbours { | ||
| 7587 | 7594 | compound_idx: u8, |
| 7588 | 7595 | ) { |
| 7589 | 7596 | let (r, c) = at_mi; |
| 7597 | + crate::census::compound(); | |
| 7590 | 7598 | for cell in 0..w_mi { |
| 7591 | 7599 | self.above_ref1[c + cell] = Some(ref1); |
| 7592 | 7600 | self.above_comp_group_idx[c + cell] = comp_group_idx; |
| @@ -21741,6 +21749,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( | ||
| 21741 | 21749 | ); |
| 21742 | 21750 | } |
| 21743 | 21751 | let mut dec = SymbolDecoder::new(tile_bytes); |
| 21752 | + crate::census::register_cdfs(&cdfs); | |
| 21744 | 21753 | neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx); |
| 21745 | 21754 | y.set_tile_origin( |
| 21746 | 21755 | mi_col0 as usize * 4, |
| @@ -23989,6 +23998,7 @@ fn read_mv( | ||
| 23989 | 23998 | if joint == 1 || joint == 3 { |
| 23990 | 23999 | diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv); |
| 23991 | 24000 | } |
| 24001 | + crate::census::mv(pred.0 + diff.0, pred.1 + diff.1); | |
| 23992 | 24002 | (pred.0 + diff.0, pred.1 + diff.1) |
| 23993 | 24003 | } |
| 23994 | 24004 | |
| @@ -27458,6 +27468,7 @@ fn decode_inter_block( | ||
| 27458 | 27468 | tpl, |
| 27459 | 27469 | ); |
| 27460 | 27470 | let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; |
| 27471 | + if !not_new { crate::census::mode(0); } | |
| 27461 | 27472 | let mut is_globalmv = false; |
| 27462 | 27473 | // lane-interbis r1: which single-ref mode this block resolved to, |
| 27463 | 27474 | // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for |
| @@ -27491,6 +27502,7 @@ fn decode_inter_block( | ||
| 27491 | 27502 | ) |
| 27492 | 27503 | } else { |
| 27493 | 27504 | let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; |
| 27505 | + if !not_zero { crate::census::mode(1); } | |
| 27494 | 27506 | is_globalmv = !not_zero; |
| 27495 | 27507 | let mv = if !not_zero { |
| 27496 | 27508 | // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already |
| @@ -27499,6 +27511,7 @@ fn decode_inter_block( | ||
| 27499 | 27511 | gm_table[(ref_frame - LAST_FRAME) as usize] |
| 27500 | 27512 | } else { |
| 27501 | 27513 | let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; |
| 27514 | + crate::census::mode(if nearest { 2 } else { 3 }); | |
| 27502 | 27515 | dbg_mode = if nearest { 13 } else { 14 }; |
| 27503 | 27516 | if nearest { |
| 27504 | 27517 | stack.nearest_mv |
| @@ -29831,6 +29844,7 @@ fn decode_inter_sub8_split4( | ||
| 29831 | 29844 | tpl, |
| 29832 | 29845 | ); |
| 29833 | 29846 | let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; |
| 29847 | + if !not_new { crate::census::mode(0); } | |
| 29834 | 29848 | let mut is_globalmv = false; |
| 29835 | 29849 | let (mv, is_new_mv) = if !not_new { |
| 29836 | 29850 | let mut idx = 0usize; |
| @@ -29854,11 +29868,13 @@ fn decode_inter_sub8_split4( | ||
| 29854 | 29868 | ) |
| 29855 | 29869 | } else { |
| 29856 | 29870 | let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; |
| 29871 | + if !not_zero { crate::census::mode(1); } | |
| 29857 | 29872 | is_globalmv = !not_zero; |
| 29858 | 29873 | let mv = if !not_zero { |
| 29859 | 29874 | gm_table[(ref_frame - LAST_FRAME) as usize] |
| 29860 | 29875 | } else { |
| 29861 | 29876 | let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; |
| 29877 | + crate::census::mode(if nearest { 2 } else { 3 }); | |
| 29862 | 29878 | if nearest { |
| 29863 | 29879 | stack.nearest_mv |
| 29864 | 29880 | } else { |
| @@ -30856,6 +30872,7 @@ fn decode_inter_sub8_rect2( | ||
| 30856 | 30872 | tpl, |
| 30857 | 30873 | ); |
| 30858 | 30874 | let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; |
| 30875 | + if !not_new { crate::census::mode(0); } | |
| 30859 | 30876 | let mut is_globalmv = false; |
| 30860 | 30877 | let (mv, is_new_mv) = if !not_new { |
| 30861 | 30878 | let mut idx = 0usize; |
| @@ -30879,11 +30896,13 @@ fn decode_inter_sub8_rect2( | ||
| 30879 | 30896 | ) |
| 30880 | 30897 | } else { |
| 30881 | 30898 | let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; |
| 30899 | + if !not_zero { crate::census::mode(1); } | |
| 30882 | 30900 | is_globalmv = !not_zero; |
| 30883 | 30901 | let mv = if !not_zero { |
| 30884 | 30902 | gm_table[(ref_frame - LAST_FRAME) as usize] |
| 30885 | 30903 | } else { |
| 30886 | 30904 | let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; |
| 30905 | + crate::census::mode(if nearest { 2 } else { 3 }); | |
| 30887 | 30906 | if nearest { |
| 30888 | 30907 | stack.nearest_mv |
| 30889 | 30908 | } else { |
| @@ -32301,6 +32320,7 @@ fn decode_inter_block8( | ||
| 32301 | 32320 | } |
| 32302 | 32321 | |
| 32303 | 32322 | let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; |
| 32323 | + if !not_new { crate::census::mode(0); } | |
| 32304 | 32324 | let mut is_globalmv = false; |
| 32305 | 32325 | let (mv, is_new_mv) = if !not_new { |
| 32306 | 32326 | // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): |
| @@ -32330,6 +32350,7 @@ fn decode_inter_block8( | ||
| 32330 | 32350 | ) |
| 32331 | 32351 | } else { |
| 32332 | 32352 | let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; |
| 32353 | + if !not_zero { crate::census::mode(1); } | |
| 32333 | 32354 | is_globalmv = !not_zero; |
| 32334 | 32355 | let mv = if !not_zero { |
| 32335 | 32356 | // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same |
| @@ -32339,6 +32360,7 @@ fn decode_inter_block8( | ||
| 32339 | 32360 | gm_table[(ref_frame - LAST_FRAME) as usize] |
| 32340 | 32361 | } else { |
| 32341 | 32362 | let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; |
| 32363 | + crate::census::mode(if nearest { 2 } else { 3 }); | |
| 32342 | 32364 | if nearest { |
| 32343 | 32365 | stack.nearest_mv |
| 32344 | 32366 | } else { |
| @@ -33973,6 +33995,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( | ||
| 33973 | 33995 | fctx.quant_deltas.with(|c| c.set(deltas)); |
| 33974 | 33996 | fctx.current_delta_lf.with(|c| c.set([0; 4])); |
| 33975 | 33997 | let mut dec = SymbolDecoder::new(data); |
| 33998 | + crate::census::register_cdfs(&cdfs); | |
| 33976 | 33999 | // lane-comppin r9: tile-entry range, the earliest point comparable |
| 33977 | 34000 | // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the |
| 33978 | 34001 | // first ladder rung before any symbol (partition or otherwise) is read. |
crates/ec-av1/src/lib.rsmodified+1 -0
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | pub mod bits; |
| 27 | 27 | pub mod cdf; |
| 28 | 28 | mod cdf_state; |
| 29 | +pub mod census; | |
| 29 | 30 | mod compound; |
| 30 | 31 | pub mod decode; |
| 31 | 32 | pub mod encode; |
crates/ec-av1/src/msac.rsmodified+20 -0
| @@ -370,11 +370,28 @@ impl<'a> SymbolDecoder<'a> { | ||
| 370 | 370 | /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. |
| 371 | 371 | #[inline] |
| 372 | 372 | pub fn symbol(&mut self, cdf: &mut [u16]) -> usize { |
| 373 | + // lane-census: the syntax census charges this symbol's bits to the | |
| 374 | + // TABLE it read, so every coding tool is accounted without a | |
| 375 | + // per-call-site label. Off (`EC_AV1_BITCENSUS` unset) this is one | |
| 376 | + // relaxed load. | |
| 377 | + let t0 = if crate::census::armed() { self.tell_bits() } else { 0.0 }; | |
| 373 | 378 | let s = self.symbol_fixed(cdf); |
| 374 | 379 | update_cdf(cdf, s); |
| 380 | + if crate::census::armed() { | |
| 381 | + crate::census::charge(cdf.as_ptr() as usize, self.tell_bits() - t0); | |
| 382 | + } | |
| 375 | 383 | s |
| 376 | 384 | } |
| 377 | 385 | |
| 386 | + /// Bits consumed so far, fractionally -- the read position less the | |
| 387 | + /// information still held in the range (`log2(range)`, which starts at | |
| 388 | + /// 15). Differences between two of these are one read's cost; the | |
| 389 | + /// absolute value carries a constant offset (class `compare-range-not-tell`). | |
| 390 | + #[must_use] | |
| 391 | + pub fn tell_bits(&self) -> f64 { | |
| 392 | + self.bit as f64 - f64::from(self.range).log2() | |
| 393 | + } | |
| 394 | + | |
| 378 | 395 | /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec |
| 379 | 396 | /// uses for the literal and equiprobable reads, mirroring |
| 380 | 397 | /// [`SymbolEncoder::symbol_fixed`]. |
| @@ -468,6 +485,9 @@ impl<'a> SymbolDecoder<'a> { | ||
| 468 | 485 | /// the coefficient sign pass and the Golomb tail read one bit at a time. |
| 469 | 486 | #[inline] |
| 470 | 487 | pub fn literal(&mut self, bits: u32) -> u32 { |
| 488 | + if crate::census::armed() { | |
| 489 | + crate::census::charge_literal(bits); | |
| 490 | + } | |
| 471 | 491 | let mut v = 0; |
| 472 | 492 | for _ in 0..bits { |
| 473 | 493 | // `EQUIPROBABLE`'s single boundary: `f >> EC_PROB_SHIFT` is 256, so |
crates/ec-av1/src/stream.rsmodified+1 -0
| @@ -1382,6 +1382,7 @@ fn decode_frame( | ||
| 1382 | 1382 | // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`. |
| 1383 | 1383 | stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>, |
| 1384 | 1384 | ) -> Result<FrameOutput> { |
| 1385 | + crate::census::frame_start(header, tile_bufs.iter().map(|t| t.len()).sum(), decode_idx); | |
| 1385 | 1386 | if header.segmentation.enabled { |
| 1386 | 1387 | for segment in 0..MAX_SEGMENTS { |
| 1387 | 1388 | for feature in [SEG_LVL_REF_FRAME, SEG_LVL_SKIP, SEG_LVL_GLOBALMV] { |
lanes/census-filmB.mdadded+137 -0
| @@ -0,0 +1,137 @@ | ||
| 1 | +# Syntax census: film B against rav1e speed 6, at matched PSNR | |
| 2 | + | |
| 3 | +What this is: a decode-side census of the streams themselves. Both encoders' | |
| 4 | +output is read by OUR decoder (`examples/syntax_census.rs` + | |
| 5 | +`crates/ec-av1/src/census.rs`, `EC_AV1_BITCENSUS=1`), so every number below is | |
| 6 | +the same measurement applied to both sides. Bits are charged per CDF TABLE -- | |
| 7 | +the accountant maps a symbol's table address to its `Cdfs` field name, so a | |
| 8 | +coding tool joins the census the day its CDF does, with no call-site labels | |
| 9 | +(class `gate-blind-to-feature`). The census total tracks the tile payload to | |
| 10 | +within 0.03% on every stream measured here (e.g. film B ours 596,540 bits | |
| 11 | +censused vs 596,712 payload bits), and the block funnel covers 100.00% of the | |
| 12 | +frame area on all four streams -- both printed by the tool. | |
| 13 | + | |
| 14 | +Recipe (the native BD gate's own, `native_gate_clips`): 12 frames, gop 12, | |
| 15 | +one tile, threads 1, 4:2:0 8-bit. | |
| 16 | +Film A = 1920x768 crop of a 1080p film at 00:35:00. Film B = 1920x1024 crop of | |
| 17 | +a 2160p HDR film at 00:40:00, converted to 8-bit. Both clips are extracted | |
| 18 | +once, losslessly, and BOTH encoders read those exact 12 frames. | |
| 19 | +Ours: `base_q_idx {150,120,90,60}`. rav1e: `speed=6:quantizer={50,100,150,200}: | |
| 20 | +tile_cols=1:tile_rows=1:threads=1`. | |
| 21 | + | |
| 22 | +## Matched points | |
| 23 | + | |
| 24 | +Mean luma PSNR over the 12 displayed pictures, computed in the census tool | |
| 25 | +(ffmpeg's PSNR of an OBU stream is unusable -- no timing; ledger dead-end): | |
| 26 | + | |
| 27 | +| clip | ours | rav1e | matched pair | bytes ours | bytes rav1e | delta | | |
| 28 | +|---|---|---|---|---|---|---| | |
| 29 | +| film B | q120 46.774 dB | q100 46.636 dB | +0.138 dB apart | 74,589 | 47,256 | **+57.8%** | | |
| 30 | +| film A | q120 44.602 dB | q100 44.149 dB | +0.453 dB apart (ours better) | 121,888 | 89,386 | +36.4% | | |
| 31 | +| film A | q90 46.151 dB | q50 46.366 dB | -0.215 dB apart (rav1e better) | 218,303 | 199,850 | +9.2% | | |
| 32 | + | |
| 33 | +The film B pair is inside the 0.2 dB window; the film A control has no pair | |
| 34 | +inside it (the ladders interleave), so both bracketing pairs are given. Film A | |
| 35 | +at the SAME recipe pair (q120 vs q100) is +36.4% while ours is 0.45 dB ahead | |
| 36 | +-- i.e. film A's gap is smaller than film B's and is measured with a quality | |
| 37 | +credit in our favour, which only widens the difference between the two clips. | |
| 38 | + | |
| 39 | +## Where the bytes are, per frame type | |
| 40 | + | |
| 41 | +| clip | frame type | ours | rav1e | delta | | |
| 42 | +|---|---|---|---|---| | |
| 43 | +| film B | key (1) | 14,572 | 25,146 | **-10,574** (ours smaller) | | |
| 44 | +| film B | arf (3 ours / 5 rav1e) | 37,433 | 20,143 | +17,290 | | |
| 45 | +| film B | leaf (8 ours / 6 rav1e) | 22,584 | 1,967 | +20,617 (**11.5x**) | | |
| 46 | +| film A | key (1) | 31,488 | 49,342 | -17,854 (ours smaller) | | |
| 47 | +| film A | arf | 52,386 | 28,091 | +24,295 | | |
| 48 | +| film A | leaf | 38,014 | 11,953 | +26,061 (3.2x) | | |
| 49 | + | |
| 50 | +The gap is entirely in the INTER frames on both clips, and our key frame is | |
| 51 | +always the smaller one -- because it is also the worse one: rav1e codes its | |
| 52 | +key at qindex 68/70 and ours at 120. rav1e's frame-0 luma PSNR on film B is | |
| 53 | +48.38 dB against our 46.78 dB. | |
| 54 | + | |
| 55 | +What separates film B from film A is the LEAF ratio: 11.5x against 3.2x. | |
| 56 | +Film B is a near-static, dark clip; rav1e's leaves cost 328 bytes each and are | |
| 57 | +99.2% skip area. Ours cost 2,823 bytes each at 70.0% skip. | |
| 58 | + | |
| 59 | +## The census, ours vs rav1e (whole stream, matched point) | |
| 60 | + | |
| 61 | +| | film B ours q120 | film B rav1e q100 | film A ours q120 | film A rav1e q100 | | |
| 62 | +|---|---|---|---|---| | |
| 63 | +| bytes | 74,589 | 47,256 | 121,888 | 89,386 | | |
| 64 | +| qindex key/arf/leaf | 120 / 104 / 128 | 68 / 95-112 / 129 | 120 / 104 / 128 | 70 / 97-114 / 131 | | |
| 65 | +| coded blocks | 27,747 | 10,980 | 24,459 | 14,268 | | |
| 66 | +| 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% | | |
| 67 | +| 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% | | |
| 68 | +| 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% | | |
| 69 | +| **skip area** | **52.5%** | **84.8%** | 38.9% | 76.4% | | |
| 70 | +| 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 | | |
| 71 | +| 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 | | |
| 72 | +| 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% | | |
| 73 | +| tx_type symbols | 12,660 (set3/1 78%, set6/1 22%) | 2,108 | 15,511 | 3,762 | | |
| 74 | +| coeff bits | 329,971 (55.3%) | 230,617 (61.0%) | 610,650 (62.6%) | 471,565 (66.0%) | | |
| 75 | +| mode bits | 114,631 (19.2%) | 33,154 (8.8%) | 118,197 (12.1%) | 56,582 (7.9%) | | |
| 76 | +| mv bits | 28,291 (4.7%) | 22,760 (6.0%) | 30,445 (3.1%) | 22,229 (3.1%) | | |
| 77 | +| partition bits | 16,507 (2.8%) | 6,074 (1.6%) | 19,331 (2.0%) | 9,923 (1.4%) | | |
| 78 | +| tx_size bits | 3,240 (5,908 symbols) | 0 (no `tx_size` symbol coded) | 3,083 (6,097 symbols) | 0 | | |
| 79 | +| literal (raw) bits | 101,867 (17.1%) | 84,706 (22.4%) | 190,425 (19.5%) | 153,593 (21.5%) | | |
| 80 | +| 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% | | |
| 81 | +| segmentation / LR | off / off-or-luma-Wiener | on / switchable on all 3 planes | off / luma only | on / all 3 planes | | |
| 82 | + | |
| 83 | +Tool fire counts: our streams code no palette, CfL-only chroma aside, no | |
| 84 | +filter-intra, no warp, no OBMC, no interintra and no wedge symbols on these | |
| 85 | +two film clips at all -- every one of those tables is absent from the family | |
| 86 | +list, which is the census saying the tool never fired (film content, screen | |
| 87 | +tools off). rav1e's streams likewise show no palette/intrabc; it does code | |
| 88 | +`comp_group_idx`/`inter_compound_mode` (compound 34.6% of area on film B | |
| 89 | +against our 25.1%). | |
| 90 | + | |
| 91 | +## Top 3 differences, ranked by bytes at stake on film B (gap = 27,333 B) | |
| 92 | + | |
| 93 | +The three overlap -- they are three views of the same inter-frame failure -- | |
| 94 | +so the byte figures must not be added. | |
| 95 | + | |
| 96 | +1. **Anchor quality and the rate ladder: ~20,600 B (75% of the gap) sits in | |
| 97 | + the leaves.** rav1e spends its bits on the key frame (53% of its whole | |
| 98 | + stream) and coasts: qindex 68 key -> 129 leaf, a 61-step spread, leaves | |
| 99 | + 99.2% skip at 328 B each. Ours codes the key at 120, the ARFs at 104 and | |
| 100 | + the leaves at 128 -- a 24-step spread with the ARF only 16 below the key -- | |
| 101 | + so no frame is ever a good enough reference for the next one to skip, and | |
| 102 | + every leaf re-codes residual (70% skip, 2,823 B each). Mechanism: our | |
| 103 | + pyramid q offsets are nearly flat and our key is far too coarse. This is | |
| 104 | + also exactly why film B is twice as far as film A: a near-static clip pays | |
| 105 | + for a good anchor once and coasts for 11 frames, which is the regime our | |
| 106 | + allocation cannot enter. | |
| 107 | +2. **No 64x64 (or 128x128) coded blocks or transforms: ~12,600 B (46%).** | |
| 108 | + Our largest coded block on both clips is 32x32; rav1e codes 45.2% of film | |
| 109 | + B's blocks as 64x64 (73.8% of its leaf blocks) and takes 28.1% of its | |
| 110 | + coefficient bits through `base_luma_64`. We therefore code 27,747 blocks | |
| 111 | + where rav1e codes 10,980, and our mode+mv+partition+tx_size bits are | |
| 112 | + 162,669 against rav1e's 61,988: +100,681 bits = +12.6 kB of pure per-block | |
| 113 | + overhead. On film A the same term is +79k bits (30% of that gap), so the | |
| 114 | + missing large blocks cost film B relatively more -- flat, static content is | |
| 115 | + exactly what a 64x64 block is for. | |
| 116 | +3. **Skip share 52.5% vs 84.8% -> coefficient bits +99,354 bits (+12.4 kB).** | |
| 117 | + We code residual over ~32 points more of the frame area than rav1e does | |
| 118 | + (leaves: 70.0% vs 99.2%). Partly a consequence of (1) -- a worse reference | |
| 119 | + leaves a real residual -- and partly the decision itself: our streams code | |
| 120 | + 12,660 tx_type symbols against rav1e's 2,108, i.e. we are choosing coded | |
| 121 | + transforms where rav1e chooses none at all. | |
| 122 | + | |
| 123 | +Two smaller, unpriced differences the census also shows, both of which our | |
| 124 | +encoder simply does not use: segmentation (rav1e enables it on every frame) | |
| 125 | +and loop restoration on all three planes (rav1e: switchable everywhere; ours: | |
| 126 | +off, or luma Wiener on about half the frames). | |
| 127 | + | |
| 128 | +## Reproducing | |
| 129 | + | |
| 130 | +``` | |
| 131 | +EC_ENC_VF=null EC_ENC_OUT=<dir> cargo run --release -p ec-av1 --example enc_probe \ | |
| 132 | + -- <clip.mkv> 1920 1024 12 150,120,90,60 | |
| 133 | +ffmpeg -f rawvideo -pix_fmt yuv420p -s 1920x1024 -r 24 -i clip.yuv -an -threads 1 -g 12 \ | |
| 134 | + -c:v librav1e -rav1e-params speed=6:quantizer=100:tile_cols=1:tile_rows=1:threads=1 \ | |
| 135 | + -f obu rav1e-q100.obu | |
| 136 | +EC_AV1_BITCENSUS=1 cargo run --release -p ec-av1 --example syntax_census -- <stream> clip.yuv | |
| 137 | +``` |