forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

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