forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

decode_probe.rs475 lines, 20.0 KiBHistoryRawDownload
1//! Where does a real stream stop? Decode one AV1 file and print the answer.
2//!
3//! The gates in [`ec_av1::stream`] each pin one capability against one encoder
4//! recipe. This asks the complementary question -- given a stream someone
5//! actually produced, which refusal comes first -- and it is how the refusal
6//! distribution in commit 2be815f was measured rather than reasoned about:
7//!
8//! ```text
9//! aomenc --codec=av1 --obu -o s.obu --passes=1 --cpu-used=4 --limit=4 in.y4m
10//! cargo run -p ec-av1 --example decode_probe -- s.obu
11//! ```
12//!
13//! Note `--obu`: [`ec_av1::stream::decode_stream`] takes a raw OBU stream, and
14//! an IVF file decodes as zero frames rather than as an error.
15//!
16//! That run is also what disproved three refusal strings claiming an encoder
17//! never writes a case it demonstrably writes, so this is a first-class
18//! instrument, not a scratch file.
19fn main() {
20 let Some(path) = std::env::args().nth(1) else {
21 eprintln!("usage: decode_probe <stream.obu>");
22 std::process::exit(2);
23 };
24 let data = match std::fs::read(&path) {
25 Ok(data) => data,
26 Err(e) => {
27 eprintln!("{path}: {e}");
28 std::process::exit(2);
29 }
30 };
31 let report = || {
32 // The census below reads ec-av1's gate counters; without the crate's
33 // `gate-counters` feature every one of them is compiled out and reads 0.
34 if !cfg!(feature = "gate-counters") {
35 println!("counters disabled (built without the gate-counters feature)");
36 }
37 let (sc, dp) = ec_av1::decode::reelc_chroma_counters();
38 println!("reelc_chroma: skip_cfl={sc} dir_1to4_pairs={dp}");
39 println!(
40 "chroma422_square: {}",
41 ec_av1::decode::chroma422_square_hits()
42 );
43 println!("chroma422_rect: {}", ec_av1::decode::chroma422_rect_hits());
44 println!("chroma422_sub8: {}", ec_av1::decode::chroma422_sub8_hits());
45 println!(
46 "chroma422_chunk: {}",
47 ec_av1::decode::chroma422_chunk_hits()
48 );
49 println!(
50 "chroma422_pair_wide: {}",
51 ec_av1::decode::chroma422_pair_wide_hits()
52 );
53 let (h, v, c) = ec_av1::stream::rect4_32_counters();
54 println!("rect4_32: horz={h} vert={v} coded={c}");
55 println!(
56 "rect_intrabc_reads: {}",
57 ec_av1::stream::rect_intrabc_reads()
58 );
59 let (pal_y, pal_uv) = ec_av1::stream::intra_in_inter_palette_hits();
60 println!("intra_in_inter_palette: y={pal_y} uv={pal_uv}");
61 println!(
62 "rect64_corner_tu: 64x32={} 32x64={}",
63 ec_av1::stream::rect64_corner_tu_hits(0),
64 ec_av1::stream::rect64_corner_tu_hits(1)
65 );
66 println!(
67 "leaf8_intrabc_hits: {}",
68 ec_av1::stream::leaf8_intrabc_hits()
69 );
70 println!("intrabc_hits: {}", ec_av1::stream::intrabc_hits());
71 println!(
72 "intrabc_vartx_trees: {}",
73 ec_av1::decode::intrabc_vartx_hits()
74 );
75 println!(
76 "intrabc_vartx_mixed_leaves: {}",
77 ec_av1::decode::intrabc_vartx_mixed_leaves_hits()
78 );
79 println!(
80 "skipped_intrabc_chroma_arm_hits: {}",
81 ec_av1::stream::skipped_intrabc_chroma_arm_hits()
82 );
83 println!(
84 "intrabc_rect: {} (var-tx tree: {})",
85 ec_av1::decode::intrabc_rect_hits(),
86 ec_av1::decode::intrabc_rect_vartx_hits()
87 );
88 // lane-av1-ibcrect: `use_intrabc` on a 128-root HORZ/VERT strip --
89 // the shape `decode_block_128rect` used to refuse.
90 println!(
91 "intrabc_128rect: {}",
92 ec_av1::stream::intrabc_128rect_hits()
93 );
94 // lane-av1-ibc128chunk: the 128-root intrabc strip's per-axis chroma
95 // mu-chunk walk -- unit count and the `(64>>ss_x)|(64>>ss_y)` extent.
96 println!(
97 "intrabc_128rect_chroma_chunk: units={} shape=0x{:x}",
98 ec_av1::stream::intrabc_128rect_chroma_chunk_hits(),
99 ec_av1::stream::intrabc_128rect_chunk_shape()
100 );
101 let (rtu, rsplit, robmc) = ec_av1::stream::rect_inter_tu_counters();
102 println!("rect_inter: tu={rtu} txsplit={rsplit} obmc_leaf={robmc}");
103 println!(
104 "sub8_inter_split: groups={}",
105 ec_av1::decode::sub8_inter_split_hits()
106 );
107 println!(
108 "skip_split_tx_override: {}",
109 ec_av1::decode::skip_split_tx_override_hits()
110 );
111 println!(
112 "interintra_rect: {}",
113 ec_av1::decode::interintra_rect_hits()
114 );
115 println!(
116 "gm_nontrans_small_side: {}",
117 ec_av1::decode::gm_nontrans_small_side_hits()
118 );
119 println!(
120 "tr_reach_longer_side: {}",
121 ec_av1::decode::tr_reach_longer_side_hits()
122 );
123 println!(
124 "mv_clamp_edge_overhang: {}",
125 ec_av1::mvstack::mv_clamp_edge_overhang_hits()
126 );
127 let (h84, h48) = ec_av1::decode::sub8_inter_rect_hits();
128 println!("sub8_inter_rect: horz8x4={h84} vert4x8={h48}");
129 println!(
130 "llintra8_chroma_walk: {}",
131 ec_av1::decode::llintra8_chroma_walk_hits()
132 );
133 println!(
134 "sub8rect444_chroma_walk: {}",
135 ec_av1::decode::llsub8rect444_chroma_walk_hits()
136 );
137 let si = ec_av1::stream::sub8_intra_rect_hits();
138 println!(
139 "sub8_intra_rect: horz8x4={} vert4x8={} chroma_ref={} mixed={} split4x4={}",
140 si.0, si.1, si.2, si.3, si.4
141 );
142 let leaf = ec_av1::stream::vartx_rect_leaf_hits();
143 println!("vartx_rect_leaf: 32x16={} 16x32={}", leaf[0], leaf[1]);
144 // lane-inter16ab r1: the 16x16-level inter AB arms, so a recipe sweep
145 // can tell "aomenc never picked one" from "it did and we decoded it".
146 let ab = ec_av1::decode::ab16_inter_hits_by_arm();
147 println!(
148 "inter_ab16: horz_a={} horz_b={} vert_a={} vert_b={}",
149 ab[0], ab[1], ab[2], ab[3]
150 );
151 // lane-kf900 r1: the counter the skipped-8x8-split-transform gate
152 // asserts -- printed here so a recipe sweep can see it fire without a
153 // test-binary rebuild.
154 println!("skip_split_tx: {}", ec_av1::decode::skip_split_tx_hits());
155 let es = ec_av1::decode::inter_edge_strip_hits();
156 println!(
157 "inter_edge_strip: h64={} v64={} h32={} v32={} h16={} v16={}",
158 es[0], es[1], es[2], es[3], es[4], es[5]
159 );
160 let (h4, v4, pairs, sub8) = ec_av1::decode::inter16_rect4_counters();
161 println!("inter16_1to4: horz4={h4} vert4={v4} chroma_pairs={pairs} sub8_pieces={sub8}");
162 let leaf4 = ec_av1::stream::vartx_rect_leaf4_hits();
163 println!("vartx_rect_leaf4: 8x4={} 4x8={}", leaf4[0], leaf4[1]);
164 // lane-av1txr: intrabc 4x8/8x4 leaves that read the inter var-tx tree
165 // (the symbol whose absence desynced `warped.obu`).
166 println!(
167 "rect_intrabc_vartx: {}",
168 ec_av1::decode::rect_intrabc_vartx_hits()
169 );
170 let rw = ec_av1::stream::rect_wedge_hits();
171 let rwi = ec_av1::stream::rect_wii_hits();
172 println!("rect_wedge(8x16,16x8,16x32,32x16,8x32,32x8): compound={rw:?} interintra={rwi:?}");
173 // lane-inter128intra r1: the 128 root's HORZ/VERT half coded INTRA in
174 // an INTER frame -- the arm this round implemented.
175 let i128 = ec_av1::stream::intra128_in_inter_counters();
176 println!("intra128_in_inter: 128x64={} 64x128={}", i128[0], i128[1]);
177 // lane-lossless128: intra 128-axis blocks on a LOSSLESS frame (every
178 // plane TX_4X4) -- the shape whose reconstruction used to panic.
179 println!(
180 "intra128_lossless: {}",
181 ec_av1::stream::intra128_lossless_counters()
182 );
183 let sb = ec_av1::stream::sb128_rect_counters();
184 println!(
185 "sb128_rect: edge_horz={} edge_vert={} inter_128x64={} inter_64x128={}",
186 sb.0, sb.1, sb.2, sb.3
187 );
188 // lane-av1-ibcrect: the interior 128-root partition arms and the key
189 // frame's intra 128-axis blocks, so a recipe sweep can tell "the
190 // encoder never chose HORZ/VERT at the 128 root" from "it did".
191 let p128 = ec_av1::stream::part128_census();
192 println!(
193 "part128: split={} none={} horz={} vert={} ab={:?} intra_horz={} intra_vert={}",
194 p128.0, p128.1, p128.2, p128.3, p128.4, p128.5, p128.6
195 );
196 // lane-sbab r1: the superblock-level inter AB arms.
197 let sbab = ec_av1::decode::sb_ab_inter_hits_by_arm();
198 println!(
199 "inter_ab64: horz_a={} horz_b={} vert_a={} vert_b={}",
200 sbab[0], sbab[1], sbab[2], sbab[3]
201 );
202 let i4 = ec_av1::stream::intra_rect4_in_inter_counters();
203 println!(
204 "intra_rect4_in_inter: 64x16={} 16x64={} 32x8={} 8x32={}",
205 i4.0, i4.1, i4.2, i4.3
206 );
207 // lane-cdefstrip r1: 8x8 CDEF units whose skip band no coded block
208 // wrote this frame -- non-zero means a decode arm forgot
209 // `fill_skip_grid_rect`, and CDEF filtered a unit libaom may skip.
210 println!(
211 "cdef_unwritten_skip_units: {}",
212 ec_av1::decode::cdef_unwritten_skip_units()
213 );
214 println!(
215 "cdef_band: rect_skip_writes={} mixed_skip_units={}",
216 ec_av1::decode::rect_skip_band_hits(),
217 ec_av1::decode::cdef_mixed_skip_units()
218 );
219 let ir = ec_av1::stream::inter_rect_counters();
220 println!(
221 "inter_rect: 32x8={} 8x32={} 64x32={} 32x64={} 64x16={} 16x64={}",
222 ir.0, ir.1, ir.2, ir.3, ir.4, ir.5
223 );
224 // lane-rectres r1: how many of those 32x8/8x32 strips coded a real
225 // rectangular residual transform unit (a skipped one codes none).
226 println!(
227 "sub8_chroma_tx_from_ref: {}",
228 ec_av1::stream::sub8_chroma_tx_from_ref_hits()
229 );
230 let r328 = ec_av1::stream::rect32x8_inter_tu_hits();
231 println!("rect32x8_inter_tu: 32x8={} 8x32={}", r328[0], r328[1]);
232 // lane-intra16x4: INTRA strips of an inter 16x16-level 1:4 partition.
233 let i164 = ec_av1::stream::intra16x4_in_inter_hits();
234 println!(
235 "intra16x4_in_inter: 16x4={} 4x16={} chroma_ref={}",
236 i164.0, i164.1, i164.2
237 );
238 println!(
239 "rect4_16_pair: lossless_chroma={} intrabc={}",
240 ec_av1::decode::rect4_16_lossless_chroma_hits(),
241 ec_av1::decode::rect4_16_intrabc_hits(),
242 );
243 println!(
244 "loss64: chroma_edge_tu_clip={} skip_lossless_band_reset={}",
245 ec_av1::decode::chroma_edge_tu_clip_hits(),
246 ec_av1::decode::skip_lossless_band_reset_hits(),
247 );
248 println!(
249 "llband: rect_split_lossless_chroma444={}",
250 ec_av1::decode::rect_split_lossless_chroma444_hits()
251 );
252 // lane-t900 r12: chroma edge-filter neighbour answered from the mi-granular
253 // uv_mode grid instead of the coarse one-slot-per-column map.
254 println!(
255 "scaled: leaf8={} sub8={} warpfb={} predict_scaled={}",
256 ec_av1::decode::scaled_leaf8_hits(),
257 ec_av1::decode::scaled_sub8_hits(),
258 ec_av1::decode::scaled_warp_fallback_hits(),
259 ec_av1::mc::predict_scaled_hits()
260 );
261 println!(
262 "uv_mode_grid_override: {}",
263 ec_av1::decode::uv_mode_grid_override_hits()
264 );
265 // lane-thread2: proof the frame-parallel path actually fired (0 at
266 // the default EC_AV1_THREADS=1).
267 println!("frames_dispatched: {}", ec_av1::stream::frames_dispatched());
268 };
269 // lane-tiles: the tiling a real stream actually uses is a decision input
270 // (every gate in `stream.rs` picks its own `--tile-columns`), so report it
271 // from the frame headers before saying anything about pixels.
272 let mut parser = ec_av1_syntax::Av1Parser::new();
273 let mut seen: Vec<(u32, u32, bool, u32)> = Vec::new();
274 let mut pos = 0usize;
275 let mut frames_seen = 0usize;
276 // OBU at a time, so one unparseable OBU late in the stream still leaves
277 // every earlier frame header's tiling reported.
278 while pos < data.len() {
279 let Ok(obu) = parser.parse_obu(&data[pos..]) else {
280 break;
281 };
282 pos += obu.total_size.max(1);
283 let header = match &obu.kind {
284 ec_av1_syntax::ObuKind::FrameHeader(h) => h,
285 ec_av1_syntax::ObuKind::Frame(h, _) => h,
286 _ => continue,
287 };
288 frames_seen += 1;
289 // lane-frame36: `EC_PROBE_HDR=1` prints one line per frame header, so a
290 // silent wall can be triaged by "which header field is new at frame N"
291 // before any pixel work (class: a header field parsed then never consumed).
292 if std::env::var("EC_PROBE_HDR").is_ok() {
293 let h = header;
294 let gm: Vec<String> = h
295 .global_motion
296 .iter()
297 .map(|w| format!("{:?}", w.model))
298 .collect();
299 println!(
300 "HDR {}: type={:?} show={} showable={} show_existing={}({}) intra={} \
301 size={}x{} up={} superres={}/{} order_hint={} primary_ref={} refresh={:#04x} \
302 refs={:?} order_hints={:?} sign_bias={:?} err_res={} disable_cdf={} \
303 screen_tools={} int_mv={} intrabc={} hp_mv={} interp={:?} switchable_motion={} \
304 ref_mvs={} base_q={} seg={} deltaq={} deltalf={} lf_level={:?} lf_deltas={:?}/{:?} \
305 cdef_bits={} lr={:?} tx_mode={:?} ref_sel={} skip_mode={}({:?}) warp={} \
306 reduced_tx={} gm={:?} grain={}/seed={} lossless={}",
307 frames_seen - 1,
308 h.frame_type,
309 h.show_frame,
310 h.showable_frame,
311 h.show_existing_frame,
312 h.frame_to_show_map_idx,
313 h.frame_is_intra,
314 h.frame_width,
315 h.frame_height,
316 h.upscaled_width,
317 h.use_superres,
318 h.superres_denom,
319 h.order_hint,
320 h.primary_ref_frame,
321 h.refresh_frame_flags,
322 h.ref_frame_idx,
323 h.order_hints,
324 h.ref_frame_sign_bias,
325 h.error_resilient_mode,
326 h.disable_cdf_update,
327 h.allow_screen_content_tools,
328 h.force_integer_mv,
329 h.allow_intrabc,
330 h.allow_high_precision_mv,
331 h.interpolation_filter,
332 h.is_motion_mode_switchable,
333 h.use_ref_frame_mvs,
334 h.quantization.base_q_idx,
335 h.segmentation.enabled,
336 h.delta.q_present,
337 h.delta.lf_present,
338 h.loop_filter.level,
339 h.loop_filter.ref_deltas,
340 h.loop_filter.mode_deltas,
341 h.cdef.bits,
342 h.loop_restoration.frame_restoration_type,
343 h.tx_mode,
344 h.reference_select,
345 h.skip_mode_present,
346 h.skip_mode_frame,
347 h.allow_warped_motion,
348 h.reduced_tx_set,
349 gm,
350 h.film_grain.apply_grain,
351 h.film_grain.grain_seed,
352 h.coded_lossless,
353 );
354 }
355 let t = &header.tile_info;
356 let entry = (t.cols, t.rows, t.uniform_spacing, t.context_update_tile_id);
357 if !seen.contains(&entry) {
358 seen.push(entry);
359 }
360 }
361 println!("TILING: {frames_seen} frame headers parsed");
362 // lane-sb128 r4: the superblock size decides the whole partition tree, so
363 // report it next to the tiling -- it is the first thing a film blocker
364 // triage needs.
365 if let Some(seq) = parser.sequence_header() {
366 println!(
367 "SEQ: use_128x128_superblock={} bit_depth={} mono_chrome={} max_frame={}x{}",
368 seq.use_128x128_superblock,
369 seq.color_config.bit_depth,
370 seq.color_config.mono_chrome,
371 seq.max_frame_width,
372 seq.max_frame_height
373 );
374 }
375 for (cols, rows, uniform, ctx_id) in &seen {
376 println!(
377 "TILING: cols={cols} rows={rows} uniform_spacing={uniform} context_update_tile_id={ctx_id}"
378 );
379 }
380 if seen.is_empty() {
381 println!("TILING: no frame header parsed");
382 }
383
384 // lane-streamsink r1: decode through the streaming entry point and write
385 // each shown frame out as it completes. The old path collected every
386 // picture in a Vec and then built a second full copy of the raw dump
387 // before one `fs::write`, so peak RSS was 2x the whole decoded segment (a
388 // 4K 8 s window needed >20 GiB, a whole film terabytes). Here at most one
389 // frame is held beyond the decoder's own DPB, and the printed lines are
390 // byte-identical to the old ones.
391 // `EC_PROBE_OUT16` is yuv420p10le (u16 LE); `EC_PROBE_OUT` / argv[2] is
392 // 8-bit (planes are u16, low byte taken). Either target may be a FIFO.
393 use std::io::Write;
394 let open = |path: &str| {
395 std::fs::OpenOptions::new()
396 .write(true)
397 .create(true)
398 .truncate(true)
399 .open(path)
400 .unwrap_or_else(|e| panic!("opening {path}: {e}"))
401 };
402 let out16 = std::env::var("EC_PROBE_OUT16").ok();
403 let out8 = std::env::args()
404 .nth(2)
405 .or_else(|| std::env::var("EC_PROBE_OUT").ok());
406 let null16 = out16.as_deref() == Some("/dev/null");
407 let mut f16 = out16.as_deref().map(open);
408 let mut f8 = out8.as_deref().map(open);
409 let mut written16 = 0usize;
410 let mut written8 = 0usize;
411 let mut shown = 0usize;
412 let mut dims = (0usize, 0usize);
413 let mut buf: Vec<u8> = Vec::new();
414 // lane-av1mono: a monochrome stream is luma only, so the raw dump is a
415 // single plane -- exactly what `ffmpeg -pix_fmt gray -f rawvideo` writes.
416 let mono = parser
417 .sequence_header()
418 .is_some_and(|s| s.color_config.mono_chrome);
419 let result = ec_av1::stream::decode_stream_with(&data, |f, _idx, is_shown| {
420 if !is_shown {
421 return Ok(());
422 }
423 shown += 1;
424 if shown == 1 {
425 dims = (f.width, f.height);
426 }
427 let planes: &[&Vec<u16>] = if mono { &[&f.y] } else { &[&f.y, &f.u, &f.v] };
428 if let Some(w) = f16.as_mut() {
429 let n = 2 * planes.iter().map(|p| p.len()).sum::<usize>();
430 if null16 {
431 // Timing runs point EC_PROBE_OUT16 at /dev/null; the u16->LE
432 // conversion was ~2% of the main thread for bytes nobody reads.
433 written16 += n;
434 } else {
435 buf.clear();
436 buf.resize(n, 0);
437 let mut off = 0;
438 for p in planes {
439 let end = off + 2 * p.len();
440 for (d, &s) in buf[off..end].chunks_exact_mut(2).zip(p.iter()) {
441 d.copy_from_slice(&s.to_le_bytes());
442 }
443 off = end;
444 }
445 w.write_all(&buf).expect("writing raw planes");
446 written16 += buf.len();
447 }
448 }
449 if let Some(w) = f8.as_mut() {
450 buf.clear();
451 for p in planes {
452 buf.extend(p.iter().map(|&s| s as u8));
453 }
454 w.write_all(&buf).expect("writing raw planes");
455 written8 += buf.len();
456 }
457 Ok(())
458 });
459 match result {
460 Ok(()) if shown == 0 => {
461 println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");
462 }
463 Ok(()) => {
464 if let Some(out) = &out16 {
465 println!("wrote {written16} bytes of yuv420p10le to {out}");
466 }
467 if let Some(out) = &out8 {
468 println!("wrote {written8} bytes of yuv420p to {out}");
469 }
470 println!("OK: {shown} frames decoded, {}x{}", dims.0, dims.1);
471 }
472 Err(e) => println!("REFUSED: {e}"),
473 }
474 report();
475}