forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

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