forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

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