forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

syntax_census.rs375 lines, 12.9 KiBHistoryRawDownload
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
15use ec_av1::census::Frame;
16use 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.
20fn 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
39fn 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.
55fn 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.
80fn 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
115fn pct(n: u64, total: u64) -> String {
116 format!("{:.1}%", 100.0 * n as f64 / total.max(1) as f64)
117}
118
119const REFS: [&str; 8] =
120 ["INTRA", "LAST", "LAST2", "LAST3", "GOLDEN", "BWDREF", "ALTREF2", "ALTREF"];
121
122fn report(label: &str, f: &Frame, frames: usize) {
123 let area = f.area.iter().sum::<u64>().max(1);
124 println!("\n== {label} ({frames} frames, {} bytes) ==", f.bytes);
125 println!(
126 " area: intra {} single-ref {} compound {} | skip {}",
127 pct(f.area[0], area),
128 pct(f.area[1], area),
129 pct(f.area[2], area),
130 pct(f.skip_area, area),
131 );
132 println!(
133 " refs (area): {}",
134 REFS.iter()
135 .enumerate()
136 .filter(|(i, _)| f.refs[*i] > 0)
137 .map(|(i, n)| format!("{n} {}", pct(f.refs[i], area)))
138 .collect::<Vec<_>>()
139 .join(" "),
140 );
141 let modes = f.modes.iter().sum::<u64>();
142 println!(
143 " single-ref modes: NEW {} GLOBAL {} NEAREST {} NEAR {} (of {modes})",
144 pct(f.modes[0], modes),
145 pct(f.modes[1], modes),
146 pct(f.modes[2], modes),
147 pct(f.modes[3], modes),
148 );
149 let mvs = f.mv.iter().sum::<u64>();
150 println!(
151 " coded mv |max| (1/8 pel): 0 {} <=8 {} <=32 {} <=128 {} <=512 {} >512 {} (of {mvs})",
152 pct(f.mv[0], mvs),
153 pct(f.mv[1], mvs),
154 pct(f.mv[2], mvs),
155 pct(f.mv[3], mvs),
156 pct(f.mv[4], mvs),
157 pct(f.mv[5], mvs),
158 );
159 let blocks: u64 = f.blocks.values().sum();
160 let mut by_size: Vec<_> = f.blocks.iter().collect();
161 by_size.sort_by_key(|(_, n)| std::cmp::Reverse(**n));
162 println!(
163 " blocks ({blocks} total): {}",
164 by_size
165 .iter()
166 .take(10)
167 .map(|((w, h), n)| format!("{w}x{h} {}", pct(**n, blocks)))
168 .collect::<Vec<_>>()
169 .join(" "),
170 );
171 let txs: u64 = f.tx.values().sum();
172 let mut by_tx: Vec<_> = f.tx.iter().collect();
173 by_tx.sort_by_key(|(_, n)| std::cmp::Reverse(**n));
174 println!(
175 " published luma tx ({txs}): {}",
176 by_tx
177 .iter()
178 .take(8)
179 .map(|((w, h), n)| format!("{w}x{h} {}", pct(**n, txs)))
180 .collect::<Vec<_>>()
181 .join(" "),
182 );
183 let tts: u64 = f.tx_type.values().sum();
184 println!(
185 " tx_type symbols ({tts}): {}",
186 f.tx_type
187 .iter()
188 .map(|((len, sym), n)| format!("set{len}/{sym} {}", pct(*n, tts)))
189 .collect::<Vec<_>>()
190 .join(" "),
191 );
192 // lane-libcen: the coding TOOLS, by name, so a level row says which of
193 // them the stream codes at all -- a table absent here is a tool this
194 // encoder never wrote (class `gate-blind-to-feature`).
195 const TOOLS: [&str; 16] = [
196 "motion_mode",
197 "obmc",
198 "interintra",
199 "wedge_interintra",
200 "wedge_idx",
201 "compound_type",
202 "comp_group_idx",
203 "compound_idx",
204 "switchable_interp",
205 "palette_y_mode",
206 "palette_uv_mode",
207 "intrabc",
208 "filter_intra",
209 "cfl_alpha",
210 "delta_q",
211 "segment_id",
212 ];
213 println!(
214 " tools (symbols/bits): {}",
215 TOOLS
216 .iter()
217 .map(|t| {
218 let (n, bits) = f.families.get(t).copied().unwrap_or((0, 0.0));
219 format!("{t} {n}/{bits:.0}")
220 })
221 .collect::<Vec<_>>()
222 .join(" "),
223 );
224
225 // Bits by family group, then the ten biggest tables inside them.
226 let mut groups: BTreeMap<&str, (u64, f64)> = BTreeMap::new();
227 for (name, (n, bits)) in &f.families {
228 let e = groups.entry(family_group(name)).or_default();
229 e.0 += n;
230 e.1 += bits;
231 }
232 let total_bits: f64 = groups.values().map(|g| g.1).sum();
233 println!(" bits by family (census total {:.0} bits vs {} payload bits):", total_bits, f.bytes * 8);
234 for (g, (n, bits)) in &groups {
235 println!(
236 " {g:<10} {:>12.0} bits {:>6} ({n} symbols)",
237 bits,
238 format!("{:.1}%", 100.0 * bits / total_bits.max(1.0))
239 );
240 }
241 let mut tables: Vec<_> = f.families.iter().collect();
242 tables.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
243 // lane-cen3: how many tables the row names. The default 8 hides the
244 // mode family's own split (a level can spend 40% of its bits on `mode`
245 // with no mode table in its top 8), so a census that has to rank
246 // per-table gaps between two encoders sets `EC_CENSUS_TABLES`.
247 let top = std::env::var("EC_CENSUS_TABLES")
248 .ok()
249 .and_then(|v| v.parse().ok())
250 .unwrap_or(8usize);
251 println!(
252 " top tables: {}",
253 tables
254 .iter()
255 .take(top)
256 .map(|(name, (_, bits))| format!("{name} {:.1}%", 100.0 * bits / total_bits.max(1.0)))
257 .collect::<Vec<_>>()
258 .join(" "),
259 );
260}
261
262fn main() {
263 let args: Vec<String> = std::env::args().skip(1).collect();
264 let Some(path) = args.first() else {
265 eprintln!("usage: syntax_census <stream.obu|stream.ivf> [source.yuv]");
266 std::process::exit(2);
267 };
268 assert!(ec_av1::census::on(), "set EC_AV1_BITCENSUS=1");
269 let data = unwrap_ivf(&std::fs::read(path).expect("stream"));
270 let pictures = ec_av1::stream::decode_stream(&data).expect("decode");
271 let frames = ec_av1::census::take();
272
273 println!("# syntax census of {path} ({} bytes)", data.len());
274 println!("\n| frame | kind | q | bytes | lf | cdef bits/y/uv | lr | dq | seg |");
275 println!("|---|---|---|---|---|---|---|---|---|");
276 for f in &frames {
277 println!(
278 "| {} | {} | {} | {} | {}/{} | {}/{}/{} | {:?} | {} | {} |",
279 f.idx,
280 f.kind,
281 f.qindex,
282 f.bytes,
283 f.lf[0],
284 f.lf[1],
285 f.cdef[0],
286 f.cdef[1],
287 f.cdef[2],
288 f.lr,
289 u8::from(f.delta_q),
290 u8::from(f.segmentation),
291 );
292 }
293 // PSNR is per DISPLAYED picture, in display order, which is not the order
294 // the frames above are coded in (a pyramid codes a hidden ARF ahead of the
295 // leaves that predict from it, and re-outputs it later with
296 // `show_existing_frame`) -- so it is its own table rather than a column.
297 let mut psnrs: Vec<(f64, f64, f64)> = Vec::new();
298 if let Some(src) = args.get(1).map(|p| std::fs::read(p).expect("source")) {
299 let mut sum = 0.0;
300 let mut rows = Vec::new();
301 for (i, pic) in pictures.iter().enumerate() {
302 let (luma, chroma) = (pic.width * pic.height, pic.width * pic.height / 4);
303 let frame_len = luma + 2 * chroma;
304 let Some(b) = src.get(i * frame_len..(i + 1) * frame_len) else { break };
305 let want: Vec<u16> = b[..luma].iter().map(|&v| u16::from(v)).collect();
306 // lane-arfpred: the chroma planes too -- an anchor's byte gap can
307 // sit in a plane the luma-only line cannot see (class
308 // `metric blind to a plane`).
309 let wu: Vec<u16> = b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect();
310 let wv: Vec<u16> = b[luma + chroma..frame_len].iter().map(|&v| u16::from(v)).collect();
311 let p = psnr(&pic.y, &want);
312 psnrs.push((p, psnr(&pic.u, &wu), psnr(&pic.v, &wv)));
313 sum += p;
314 rows.push(format!("{i}:{p:.2}"));
315 }
316 println!(
317 "\nPSNR-Y display order ({} pictures): {}\nPSNR-Y mean {:.3} dB over {} pictures",
318 pictures.len(),
319 rows.join(" "),
320 sum / rows.len() as f64,
321 rows.len(),
322 );
323 }
324
325 // lane-arfcen: one full report PER CODED FRAME, so an ARF of ours can be
326 // put next to the reference encoder's ARF at the same display position.
327 if std::env::var("EC_CENSUS_PERFRAME").as_deref() == Ok("1") {
328 for f in &frames {
329 let (p, pu, pv) =
330 psnrs.get(f.order_hint as usize).copied().unwrap_or((f64::NAN, f64::NAN, f64::NAN));
331 let refs: Vec<String> = (0..7)
332 .filter(|i| f.refs[i + 1] > 0)
333 .map(|i| {
334 format!(
335 "{}@{:+}",
336 REFS[i + 1],
337 i64::from(f.ref_hints[i]) - i64::from(f.order_hint),
338 )
339 })
340 .collect();
341 report(
342 &format!(
343 "frame {} {} hint {} q {} PSNR-Y {p:.2} U {pu:.2} V {pv:.2} dB refs [{}]",
344 f.idx,
345 f.kind,
346 f.order_hint,
347 f.qindex,
348 refs.join(" "),
349 ),
350 f,
351 1,
352 );
353 }
354 }
355
356 for kind in ["key", "arf", "leaf"] {
357 let set: Vec<&Frame> = frames.iter().filter(|f| f.kind == kind).collect();
358 if !set.is_empty() {
359 report(kind, &merge(&set), set.len());
360 }
361 }
362 report("ALL", &merge(&frames.iter().collect::<Vec<_>>()), frames.len());
363 // The self-check: every coded block is published exactly once, so the
364 // censused area must be the frame's own mi area (a funnel that misses a
365 // block class would silently under-count every share above).
366 if let Some(pic) = pictures.first() {
367 let all = merge(&frames.iter().collect::<Vec<_>>());
368 let want = (pic.width.div_ceil(4) * pic.height.div_ceil(4) * frames.len()) as u64;
369 let got = all.area.iter().sum::<u64>();
370 println!(
371 "\ncoverage: censused block area {got} of {want} mi ({:.2}%)",
372 100.0 * got as f64 / want as f64
373 );
374 }
375}