forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

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