forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

instrument-aom-oracle.sh1528 lines, 69.1 KiBHistoryRawDownload
1#!/usr/bin/env bash
2# Add the decode-localization instrumentation to the libaom oracle's aomdec.
3#
4# These patches used to live only in the hand-built /tmp tree; the 2026-08-30
5# tmpfs reclaim destroyed them along with the tree (see memory
6# oracle-in-reaped-dir). They are re-derived here so `build-aom-oracle.sh` +
7# this script reproduce the full ladder from scratch.
8#
9# Rungs provided (both env-gated, so an uninstrumented run is unchanged):
10# DEPTH TRAP (lane-av1oraclerungdepth): the DUMP rungs 1 / 6 / 7 / 15 write
11# 1 byte per sample with no YV12_FLAG_HIGHBITDEPTH check (they are paired
12# with decoder-side dumps that narrow to u8 on purpose). On a 10/12-bit
13# stream they crash the oracle, or where they survive produce a file of
14# EXACTLY HALF w*h*bps -- which looks like a truncated decode but is the
15# rung's depth assumption. Each of those four carries a
16# `DEPTH ASSUMPTION` block naming its decoder-side pair; rung 12
17# (EC_AV1_FINAL_DUMP) is the depth-correct one.
18# EC_AV1_PREFILT_DUMP=<prefix> -> <prefix>.f<N> per frame, Y then U then V,
19# crop-sized rows, written after tile decode and BEFORE any loop filter,
20# CDEF or LR. Diff against our own EC_AV1_PREFILT_DUMP to separate a
21# reconstruction mismatch from a filtering one.
22# EC_TRACE=1 -> "EC_PART mi_row=.. mi_col=.. bsize=.. ctx=.. tell=.. rng=.."
23# before every partition symbol, "EC_PART_VAL .. value=.." after. The
24# range ladder: compare rng element-by-element against our own
25# `TRACE part32_pre` (class compare-range-not-tell -- ranges, never tell).
26# EC_TRACE_COEFF=1 -> "EC_COEFF plane=.. row=.. col=.. tx_size=.. rng=.."
27# before every coefficient block, "EC_COEFF_VAL .. rng=.." after.
28# Partition granularity is too coarse to localize a coefficient desync;
29# two lanes stalled on 2026-08-30 because this rung did not exist.
30# EC_TRACE_MODE=1 -> "EC_MODE mi_row=.. mi_col=.. rng=.." before every inter
31# block's mode info, "EC_MODE_VAL .. mode=.. ref0/1=.. mv0=.. rng=.."
32# (rung 13 adds "stack=" to that line and an "EC_MODE_MV" line right
33# after assign_mv)
34# after -- the mv-stack/DRL/mv reads EC_PART cannot see. The same flag
35# also emits "EC_IMODE .. rng=.." / "EC_IMODE_VAL .. mode=.. uv_mode=..
36# skip=.. tx=.. rng=.." around every INTRA key-frame block: without it
37# the key-frame path has no traced symbol at all between the partition
38# read and the first coefficient block, which is precisely the gap a
39# rect-strip desync hides in.
40# EC_AV1_POSTDEBLOCK_DUMP=<prefix> -> <prefix>.f<N> per frame, Y then U then
41# V, full ALIGNED-buffer rows (y_width/y_height, not y_crop_width --
42# cm->cur_frame->buf at this point is still the pre-superres buffer,
43# but its aligned width already extends past FrameWidth out to the
44# mi-aligned true width, which is exactly the margin content we need).
45# Written right after av1_loop_filter_frame_mt returns and before
46# CDEF/superres run -- ground truth for the post-deblock, pre-superres
47# row content over frame_width..true_width that decode.rs stashes as
48# its superres margin (lane-superres r5: hand-tracing the arithmetic
49# could only prove our own self-consistency, not correctness against
50# libaom).
51# EC_AV1_POSTCDEF_DUMP=<prefix> -> <prefix>.f<N> per frame, same shape as
52# the POSTDEBLOCK rung (full ALIGNED-buffer rows), written right after
53# the CDEF pass and before superres/LR -- splits a final-output
54# mismatch into "already in CDEF" vs "introduced by loop restoration"
55# without the 16-bit-only DUMP16 rungs (lane-av1422filter: on the
56# pinned 4:2:2 keyframe this named the 251/259-sample CDEF chroma
57# defect whose first samples were the ticket's first final samples).
58# EC_TRACE_MODE_STEP=1 -> per-symbol range ladder inside
59# ec_read_intra_frame_mode_info_impl (rung 5's renamed body):
60# "EC_ISTEP mi_row=.. mi_col=.. name=skip val=.. rng=.." after
61# read_skip_txfm, name=cdef/dq after read_cdef/read_delta_q_params,
62# name=mode after mbmi->mode, name=angle_y after the Y angle_delta read,
63# name=uv_mode after mbmi->uv_mode, name=angle_uv after the UV
64# angle_delta read (rung 10, lane-sbpart r6). EC_TRACE_MODE's own
65# before/after prints only bracket the WHOLE block; this is the
66# per-symbol ladder the charter asked for to localize block2's first
67# wrong read.
68# Rung 9 (unconditional, no env gate) -- SGR per-tap ground truth
69# (lane-lr r7): `calculate_intermediate_result` in
70# av1/common/restoration.c is `static`, so a standalone harness cannot
71# call it to get real A[]/B[] intermediate arrays, only the final
72# flt0/flt1 via the public av1_selfguided_restoration_c. This rung
73# drops `static` so an external harness can call it directly with a
74# `dgd32`-style buffer (see scripts/lr-sgr-pin-harness.c) and diff
75# every A[k]/B[k] tap against a from-scratch recompute -- the missing
76# half of r6's 9-tap cross-check. No behaviour change (only linkage).
77#
78# Idempotent: re-running is a no-op. Rebuild afterwards with
79# ninja -C ~/.cache/aom-oracle/build aomdec
80set -euo pipefail
81SRC="${AOM_ORACLE_SRC:-$HOME/.cache/aom-oracle/src}"
82F="$SRC/av1/decoder/decodeframe.c"
83[ -f "$F" ] || { echo "no oracle source at $F -- run scripts/build-aom-oracle.sh first" >&2; exit 1; }
84
85python3 - "$F" <<'PY'
86import sys, re
87path = sys.argv[1]
88s = open(path).read()
89if "EC_INSTRUMENTED" in s:
90 print("already instrumented (no-op)")
91 sys.exit(0)
92
93# --- rung 2: partition range ladder -------------------------------------
94old_sig = """static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
95 aom_reader *r, int has_rows, int has_cols,
96 BLOCK_SIZE bsize) {"""
97new_sig = """/* EC_INSTRUMENTED */
98static PARTITION_TYPE ec_read_partition_impl(MACROBLOCKD *xd, int mi_row,
99 int mi_col, aom_reader *r,
100 int has_rows, int has_cols,
101 BLOCK_SIZE bsize);
102
103static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
104 aom_reader *r, int has_rows, int has_cols,
105 BLOCK_SIZE bsize) {
106 const int ec_trace = getenv("EC_TRACE") != NULL;
107 if (ec_trace) {
108 fprintf(stderr,
109 "EC_PART mi_row=%d mi_col=%d bsize=%d ctx=%d tell=%d rng=%u\\n",
110 mi_row, mi_col, (int)bsize,
111 partition_plane_context(xd, mi_row, mi_col, bsize),
112 (int)aom_reader_tell(r), (unsigned)r->ec.rng);
113 }
114 PARTITION_TYPE ec_p =
115 ec_read_partition_impl(xd, mi_row, mi_col, r, has_rows, has_cols, bsize);
116 if (ec_trace) {
117 fprintf(stderr, "EC_PART_VAL mi_row=%d mi_col=%d bsize=%d value=%d\\n",
118 mi_row, mi_col, (int)bsize, (int)ec_p);
119 }
120 return ec_p;
121}
122
123static PARTITION_TYPE ec_read_partition_impl(MACROBLOCKD *xd, int mi_row,
124 int mi_col, aom_reader *r,
125 int has_rows, int has_cols,
126 BLOCK_SIZE bsize) {"""
127assert old_sig in s, "read_partition signature moved"
128s = s.replace(old_sig, new_sig, 1)
129
130# --- rung 1: pre-filter recon dump --------------------------------------
131# DEPTH ASSUMPTION (lane-av1oraclerungdepth): this rung writes 1 byte per
132# sample and has NO YV12_FLAG_HIGHBITDEPTH check. That is deliberate -- it is
133# byte-paired with our own EC_AV1_PREFILT_DUMP, which narrows 10/12-bit to u8
134# on purpose (decode.rs:20048-20054, `p.data.iter().map(|&s| s as u8)` in
135# `dump_stage`).
136# TRAP: on an HBD stream the file is EXACTLY HALF w*h*2 = w*h bytes, which
137# reads like a truncated/short decode, not a decoder bug. For HBD use rung 12
138# EC_AV1_FINAL_DUMP (:730) -- it IS depth-correct (u8 / u16 LE).
139# OBSERVED 2026-09-29 on the HBD oracle build (CONFIG_AV1_HIGHBITDEPTH=1) with
140# the committed `av112bit-key.obu` (160x128 4:2:0 12-bit = 30720 samples):
141# rung 12 wrote 61440 B (w*h*bps) and this rung's 1-byte fwrite SIGSEGVs inside
142# fwrite (exit 139, 0-byte file); the bytes it would have written are 30720 B
143# = exactly half. Either way this is the RUNG's depth assumption, not a decoder
144# defect -- never read a half-length/empty file here as a truncated decode.
145anchor = """ av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync,
146 pbi->num_workers, 1);"""
147dump = """ {
148 const char *ec_dump = getenv("EC_AV1_PREFILT_DUMP");
149 if (ec_dump) {
150 static int ec_prefilt_idx = 0;
151 char ec_path[1024];
152 snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, ec_prefilt_idx++);
153 FILE *ec_f = fopen(ec_path, "wb");
154 if (ec_f) {
155 const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf;
156 for (int ec_r = 0; ec_r < ec_b->y_crop_height; ++ec_r)
157 fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_crop_width,
158 ec_f);
159 if (num_planes > 1) {
160 for (int ec_r = 0; ec_r < ec_b->uv_crop_height; ++ec_r)
161 fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1,
162 ec_b->uv_crop_width, ec_f);
163 for (int ec_r = 0; ec_r < ec_b->uv_crop_height; ++ec_r)
164 fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1,
165 ec_b->uv_crop_width, ec_f);
166 }
167 fclose(ec_f);
168 }
169 }
170 }
171
172"""
173assert anchor in s, "cdef alloc anchor moved"
174s = s.replace(anchor, dump + anchor, 1)
175open(path, "w").write(s)
176print("instrumented")
177PY
178echo "now: ninja -C ${AOM_ORACLE_BUILD:-$HOME/.cache/aom-oracle/build} aomdec"
179
180# --- rung 3: coefficient range ladder (decodetxb.c) ---------------------
181G="$SRC/av1/decoder/decodetxb.c"
182[ -f "$G" ] || { echo "no oracle source at $G" >&2; exit 1; }
183
184python3 - "$G" <<'PYC'
185import sys
186path = sys.argv[1]
187s = open(path).read()
188if "EC_INSTRUMENTED" in s:
189 print("decodetxb already instrumented (no-op)")
190 sys.exit(0)
191
192old = """void av1_read_coeffs_txb(const AV1_COMMON *const cm, DecoderCodingBlock *dcb,
193 aom_reader *const r, const int plane, const int row,
194 const int col, const TX_SIZE tx_size) {"""
195new = """/* EC_INSTRUMENTED */
196static void ec_read_coeffs_txb_impl(const AV1_COMMON *const cm,
197 DecoderCodingBlock *dcb,
198 aom_reader *const r, const int plane,
199 const int row, const int col,
200 const TX_SIZE tx_size);
201
202void av1_read_coeffs_txb(const AV1_COMMON *const cm, DecoderCodingBlock *dcb,
203 aom_reader *const r, const int plane, const int row,
204 const int col, const TX_SIZE tx_size) {
205 const int ec_trace = getenv("EC_TRACE_COEFF") != NULL;
206 if (ec_trace) {
207 fprintf(stderr, "EC_COEFF plane=%d row=%d col=%d tx_size=%d rng=%u\\n",
208 plane, row, col, (int)tx_size, (unsigned)r->ec.rng);
209 }
210 ec_read_coeffs_txb_impl(cm, dcb, r, plane, row, col, tx_size);
211 if (ec_trace) {
212 fprintf(stderr, "EC_COEFF_VAL plane=%d row=%d col=%d rng=%u\\n", plane, row,
213 col, (unsigned)r->ec.rng);
214 }
215}
216
217static void ec_read_coeffs_txb_impl(const AV1_COMMON *const cm,
218 DecoderCodingBlock *dcb,
219 aom_reader *const r, const int plane,
220 const int row, const int col,
221 const TX_SIZE tx_size) {"""
222assert old in s, "av1_read_coeffs_txb signature moved"
223s = s.replace(old, new, 1)
224open(path, "w").write(s)
225print("decodetxb instrumented")
226PYC
227
228# --- rung 4: mode-info range ladder (decodemv.c) ------------------------
229H="$SRC/av1/decoder/decodemv.c"
230[ -f "$H" ] || { echo "no oracle source at $H" >&2; exit 1; }
231
232python3 - "$H" <<'PYM'
233import sys
234path = sys.argv[1]
235s = open(path).read()
236if "EC_INSTRUMENTED" in s:
237 print("decodemv already instrumented (no-op)")
238 sys.exit(0)
239
240old = """static void read_inter_block_mode_info(AV1Decoder *const pbi,
241 DecoderCodingBlock *dcb,
242 MB_MODE_INFO *const mbmi,
243 aom_reader *r) {"""
244new = """/* EC_INSTRUMENTED */
245static void ec_read_inter_block_mode_info_impl(AV1Decoder *const pbi,
246 DecoderCodingBlock *dcb,
247 MB_MODE_INFO *const mbmi,
248 aom_reader *r);
249
250static void read_inter_block_mode_info(AV1Decoder *const pbi,
251 DecoderCodingBlock *dcb,
252 MB_MODE_INFO *const mbmi,
253 aom_reader *r) {
254 const int ec_trace = getenv("EC_TRACE_MODE") != NULL;
255 const MACROBLOCKD *const ec_xd = &dcb->xd;
256 if (ec_trace) {
257 fprintf(stderr, "EC_MODE mi_row=%d mi_col=%d rng=%u\\n", ec_xd->mi_row,
258 ec_xd->mi_col, (unsigned)r->ec.rng);
259 }
260 ec_read_inter_block_mode_info_impl(pbi, dcb, mbmi, r);
261 if (ec_trace) {
262 fprintf(stderr,
263 "EC_MODE_VAL mi_row=%d mi_col=%d mode=%d ref0=%d ref1=%d "
264 "mv0=(%d,%d) rng=%u\\n",
265 ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode,
266 (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1],
267 mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col,
268 (unsigned)r->ec.rng);
269 }
270}
271
272static void ec_read_inter_block_mode_info_impl(AV1Decoder *const pbi,
273 DecoderCodingBlock *dcb,
274 MB_MODE_INFO *const mbmi,
275 aom_reader *r) {"""
276assert old in s, "read_inter_block_mode_info signature moved"
277s = s.replace(old, new, 1)
278open(path, "w").write(s)
279print("decodemv instrumented")
280PYM
281
282# --- rung 5: intra key-frame mode-info ladder (decodemv.c) --------------
283python3 - "$SRC/av1/decoder/decodemv.c" <<'PYI'
284import sys
285path = sys.argv[1]
286s = open(path).read()
287if "EC_INSTRUMENTED_INTRA" in s:
288 print("intra mode-info already instrumented (no-op)")
289 sys.exit(0)
290
291old = """static void read_intra_frame_mode_info(AV1_COMMON *const cm,
292 DecoderCodingBlock *dcb, aom_reader *r) {"""
293new = """/* EC_INSTRUMENTED_INTRA */
294static void ec_read_intra_frame_mode_info_impl(AV1_COMMON *const cm,
295 DecoderCodingBlock *dcb,
296 aom_reader *r);
297
298static void read_intra_frame_mode_info(AV1_COMMON *const cm,
299 DecoderCodingBlock *dcb, aom_reader *r) {
300 const int ec_trace = getenv("EC_TRACE_MODE") != NULL;
301 const MACROBLOCKD *const ec_xd = &dcb->xd;
302 if (ec_trace) {
303 fprintf(stderr, "EC_IMODE mi_row=%d mi_col=%d bsize=%d rng=%u\\n",
304 ec_xd->mi_row, ec_xd->mi_col, (int)ec_xd->mi[0]->bsize,
305 (unsigned)r->ec.rng);
306 }
307 ec_read_intra_frame_mode_info_impl(cm, dcb, r);
308 if (ec_trace) {
309 const MB_MODE_INFO *const ec_mbmi = ec_xd->mi[0];
310 fprintf(stderr,
311 "EC_IMODE_VAL mi_row=%d mi_col=%d mode=%d uv_mode=%d skip=%d "
312 "tx=%d rng=%u\\n",
313 ec_xd->mi_row, ec_xd->mi_col, (int)ec_mbmi->mode,
314 (int)ec_mbmi->uv_mode, (int)ec_mbmi->skip_txfm,
315 (int)ec_mbmi->tx_size, (unsigned)r->ec.rng);
316 }
317}
318
319static void ec_read_intra_frame_mode_info_impl(AV1_COMMON *const cm,
320 DecoderCodingBlock *dcb,
321 aom_reader *r) {"""
322assert old in s, "read_intra_frame_mode_info signature moved"
323s = s.replace(old, new, 1)
324open(path, "w").write(s)
325print("intra mode-info instrumented")
326PYI
327
328# --- rung 6: post-deblock, pre-superres row dump ------------------------
329# DEPTH ASSUMPTION (lane-av1oraclerungdepth): 1 byte per sample, NO
330# YV12_FLAG_HIGHBITDEPTH check. Deliberate -- byte-paired with our
331# EC_AV1_POSTDEBLOCK_DUMP, which narrows to u8 (decode.rs:20048-20054,
332# `dump_stage(..., &y, &u, &v)` over the u16 planes; same closure at :53489).
333# TRAP: on an HBD stream the file is EXACTLY HALF w*h*2, which reads like a
334# truncated/short decode, not a decoder bug. For HBD use rung 12
335# EC_AV1_FINAL_DUMP (:730) -- depth-correct (u8 / u16 LE).
336# OBSERVED 2026-09-29 (HBD build, av112bit-key.obu): the 1-byte fwrite SIGSEGVs
337# (exit 139); where it survives it writes 30720 B where 61440 B is expected --
338# exactly half. That is this rung, not a truncated decode.
339python3 - "$F" <<'PYD'
340import sys
341path = sys.argv[1]
342s = open(path).read()
343if "EC_INSTRUMENTED_POSTDEBLOCK" in s:
344 print("postdeblock dump already instrumented (no-op)")
345 sys.exit(0)
346
347anchor = """ if (cm->lf.filter_level[0] || cm->lf.filter_level[1]) {
348 av1_loop_filter_frame_mt(&cm->cur_frame->buf, cm, &pbi->dcb.xd, 0,
349 num_planes, 0, pbi->tile_workers,
350 pbi->num_workers, &pbi->lf_row_sync, 0);
351 }
352"""
353dump = """
354 /* EC_INSTRUMENTED_POSTDEBLOCK */
355 {
356 const char *ec_dump = getenv("EC_AV1_POSTDEBLOCK_DUMP");
357 if (ec_dump) {
358 static int ec_postdeblock_idx = 0;
359 char ec_path[1024];
360 snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump,
361 ec_postdeblock_idx++);
362 FILE *ec_f = fopen(ec_path, "wb");
363 if (ec_f) {
364 const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf;
365 /* Dump the FULL aligned buffer (y_width/y_height), not the
366 * crop_width/crop_height (== FrameWidth/FrameHeight): the
367 * superres margin (columns [FrameWidth, true mi-aligned width))
368 * only exists in the aligned buffer -- lane-superres r5. */
369 for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r)
370 fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width,
371 ec_f);
372 if (num_planes > 1) {
373 for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r)
374 fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1,
375 ec_b->uv_width, ec_f);
376 for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r)
377 fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1,
378 ec_b->uv_width, ec_f);
379 }
380 fclose(ec_f);
381 }
382 }
383 }
384"""
385assert anchor in s, "loop filter call anchor moved"
386s = s.replace(anchor, anchor + dump, 1)
387open(path, "w").write(s)
388print("postdeblock dump instrumented")
389PYD
390
391# --- rung 7: pre-deblock, FULL aligned-buffer row dump (lane-superres r5) -
392# EC_AV1_PREFILT_DUMP (rung 1) is used by other lanes at its existing
393# y_crop_width/y_crop_height shape -- left untouched. This adds a second,
394# additive env var at the SAME anchor (pre-loop-filter) but dumping the full
395# y_width/y_height aligned buffer, so a margin-region reconstruction bug can
396# be told apart from a margin-region deblock bug.
397# DEPTH ASSUMPTION (lane-av1oraclerungdepth): 1 byte per sample, NO
398# YV12_FLAG_HIGHBITDEPTH check. Deliberate -- byte-paired with our
399# EC_AV1_PREFILT_WIDE_DUMP, which narrows to u8 (decode.rs:20078-20090,
400# `dump_prefilter_wide`; same closure at :53489). TRAP: on an HBD
401# stream the file is EXACTLY HALF w*h*2, which reads like a truncated/short
402# decode, not a decoder bug. For HBD use rung 12 EC_AV1_FINAL_DUMP (:730) --
403# depth-correct (u8 / u16 LE).
404# OBSERVED 2026-09-29 (HBD build, av112bit-key.obu): the 1-byte fwrite SIGSEGVs
405# (exit 139); where it survives it writes 30720 B where 61440 B is expected --
406# exactly half. That is this rung, not a truncated decode.
407python3 - "$F" <<'PYW'
408import sys
409path = sys.argv[1]
410s = open(path).read()
411if "EC_INSTRUMENTED_PREFILT_WIDE" in s:
412 print("prefilt-wide dump already instrumented (no-op)")
413 sys.exit(0)
414
415anchor = """ av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync,
416 pbi->num_workers, 1);"""
417dump = """ /* EC_INSTRUMENTED_PREFILT_WIDE */
418 {
419 const char *ec_dump = getenv("EC_AV1_PREFILT_WIDE_DUMP");
420 if (ec_dump) {
421 static int ec_prefilt_wide_idx = 0;
422 char ec_path[1024];
423 snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump,
424 ec_prefilt_wide_idx++);
425 FILE *ec_f = fopen(ec_path, "wb");
426 if (ec_f) {
427 const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf;
428 for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r)
429 fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width,
430 ec_f);
431 if (num_planes > 1) {
432 for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r)
433 fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1,
434 ec_b->uv_width, ec_f);
435 for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r)
436 fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1,
437 ec_b->uv_width, ec_f);
438 }
439 fclose(ec_f);
440 }
441 }
442 }
443
444"""
445assert anchor in s, "cdef alloc anchor moved"
446s = s.replace(anchor, dump + anchor, 1)
447open(path, "w").write(s)
448print("prefilt-wide dump instrumented")
449PYW
450# --- rung 8: palette colour-index map range ladder (detokenize.c) -------
451# EC_TRACE_PALETTE=1 -> "EC_PAL row=.. col=.. ctx=.. n=.. rng=.." before every
452# colour-index symbol in decode_color_map_tokens's wavefront, "EC_PAL_VAL
453# row=.. col=.. color_idx=.. rng=.." after. lane-palette r4: r3 already
454# cleared every table/context function against this same source line-for-line
455# by hand; this rung is what lets a real per-symbol range compare (class
456# compare-range-not-tell / equal-range-means-unread) replace that by-hand
457# check instead of re-reading the tables again.
458I="$SRC/av1/decoder/detokenize.c"
459[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; }
460
461python3 - "$I" <<'PYP'
462import sys
463path = sys.argv[1]
464s = open(path).read()
465if "EC_INSTRUMENTED_PALETTE" in s:
466 print("palette map already instrumented (no-op)")
467 sys.exit(0)
468
469old = """ const int color_ctx = av1_get_palette_color_index_context(
470 color_map, plane_block_width, (i - j), j, n, color_order, NULL);
471 const int color_idx = aom_read_symbol(
472 r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR);
473 assert(color_idx >= 0 && color_idx < n);
474 color_map[(i - j) * plane_block_width + j] = color_order[color_idx];"""
475new = """/* EC_INSTRUMENTED_PALETTE */
476 const int color_ctx = av1_get_palette_color_index_context(
477 color_map, plane_block_width, (i - j), j, n, color_order, NULL);
478 const int ec_pal_trace = getenv("EC_TRACE_PALETTE") != NULL;
479 if (ec_pal_trace) {
480 fprintf(stderr, "EC_PAL row=%d col=%d ctx=%d n=%d rng=%u\\n", (i - j),
481 j, color_ctx, n, (unsigned)r->ec.rng);
482 }
483 const int color_idx = aom_read_symbol(
484 r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR);
485 assert(color_idx >= 0 && color_idx < n);
486 color_map[(i - j) * plane_block_width + j] = color_order[color_idx];
487 if (ec_pal_trace) {
488 fprintf(stderr, "EC_PAL_VAL row=%d col=%d color_idx=%d rng=%u\\n",
489 (i - j), j, color_idx, (unsigned)r->ec.rng);
490 }"""
491assert old in s, "decode_color_map_tokens loop body moved"
492s = s.replace(old, new, 1)
493s = s.replace(
494 "static void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {",
495 "/* EC_INSTRUMENTED_PALETTE */\nstatic void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {",
496 1,
497)
498open(path, "w").write(s)
499print("palette map instrumented")
500PYP
501
502# --- rung 8b: palette map[0] (av1_read_uniform) range ladder ------------
503python3 - "$I" <<'PYP0'
504import sys
505path = sys.argv[1]
506s = open(path).read()
507if "EC_INSTRUMENTED_PALETTE_UNIFORM" in s:
508 print("palette map[0] already instrumented (no-op)")
509 sys.exit(0)
510
511old = """ // The first color index.
512 color_map[0] = av1_read_uniform(r, n);
513 assert(color_map[0] < n);"""
514new = """ // The first color index.
515 /* EC_INSTRUMENTED_PALETTE_UNIFORM */
516 if (getenv("EC_TRACE_PALETTE") != NULL) {
517 fprintf(stderr, "EC_PAL row=0 col=0 ctx=-1 n=%d rng=%u\\n", n,
518 (unsigned)r->ec.rng);
519 }
520 color_map[0] = av1_read_uniform(r, n);
521 assert(color_map[0] < n);
522 if (getenv("EC_TRACE_PALETTE") != NULL) {
523 fprintf(stderr, "EC_PAL_VAL row=0 col=0 color_idx=%d rng=%u\\n",
524 color_map[0], (unsigned)r->ec.rng);
525 }"""
526assert old in s, "color_map[0] uniform read moved"
527s = s.replace(old, new, 1)
528open(path, "w").write(s)
529print("palette map[0] instrumented")
530PYP0
531
532# --- rung 9: export calculate_intermediate_result for a direct harness call
533I="$SRC/av1/common/restoration.c"
534[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; }
535
536python3 - "$I" <<'PYA'
537import sys
538path = sys.argv[1]
539s = open(path).read()
540if "/* EC_INSTRUMENTED_AB */" in s:
541 print("calculate_intermediate_result already exported (no-op)")
542 sys.exit(0)
543
544old = """static void calculate_intermediate_result(int32_t *dgd, int width, int height,"""
545new = """/* EC_INSTRUMENTED_AB */
546void calculate_intermediate_result(int32_t *dgd, int width, int height,"""
547assert old in s, "calculate_intermediate_result signature moved"
548s = s.replace(old, new, 1)
549open(path, "w").write(s)
550print("calculate_intermediate_result exported")
551PYA
552
553# --- rung 10: per-symbol range ladder inside intra key-frame mode info --
554python3 - "$SRC/av1/decoder/decodemv.c" <<'PYS'
555import sys
556path = sys.argv[1]
557s = open(path).read()
558if "EC_INSTRUMENTED_INTRA_STEP" in s:
559 print("intra mode-info per-symbol ladder already instrumented (no-op)")
560 sys.exit(0)
561
562def step(name, val):
563 return """ {
564 const int ec_trace = getenv("EC_TRACE_MODE_STEP") != NULL;
565 if (ec_trace) {
566 fprintf(stderr, "EC_ISTEP mi_row=%%d mi_col=%%d name=%s val=%%d rng=%%u\\n",
567 xd->mi_row, xd->mi_col, (int)(%s), (unsigned)r->ec.rng);
568 }
569 }
570""" % (name, val)
571
572old = " mbmi->skip_txfm = read_skip_txfm(cm, xd, mbmi->segment_id, r);\n"
573assert old in s, "read_skip_txfm call moved"
574s = s.replace(old, old + step("skip", "mbmi->skip_txfm"), 1)
575
576old = " read_cdef(cm, r, xd);\n"
577assert old in s, "read_cdef call moved"
578s = s.replace(old, old + step("cdef", "0"), 1)
579
580old = " read_delta_q_params(cm, xd, r);\n"
581assert old in s, "read_delta_q_params call moved"
582s = s.replace(old, old + step("dq", "xd->current_base_qindex"), 1)
583
584old = " mbmi->mode = read_intra_mode(r, get_y_mode_cdf(ec_ctx, above_mi, left_mi));\n"
585assert old in s, "y mode read moved"
586s = s.replace(old, old + step("mode", "mbmi->mode"), 1)
587
588old = """ mbmi->angle_delta[PLANE_TYPE_Y] =
589 (use_angle_delta && av1_is_directional_mode(mbmi->mode))
590 ? read_angle_delta(r, ec_ctx->angle_delta_cdf[mbmi->mode - V_PRED])
591 : 0;
592"""
593assert old in s, "angle_delta_y block moved"
594s = s.replace(old, old + step("angle_y", "mbmi->angle_delta[PLANE_TYPE_Y]"), 1)
595
596old = """ mbmi->uv_mode =
597 read_intra_mode_uv(ec_ctx, r, is_cfl_allowed(xd), mbmi->mode);
598"""
599assert old in s, "uv_mode read moved"
600s = s.replace(old, old + step("uv_mode", "mbmi->uv_mode"), 1)
601
602old = """ mbmi->angle_delta[PLANE_TYPE_UV] =
603 (use_angle_delta && av1_is_directional_mode(intra_mode))
604 ? read_angle_delta(r, ec_ctx->angle_delta_cdf[intra_mode - V_PRED])
605 : 0;
606"""
607assert old in s, "angle_delta_uv block moved"
608s = s.replace(old, old + step("angle_uv", "mbmi->angle_delta[PLANE_TYPE_UV]"), 1)
609
610marker_old = "static int read_mv_component(aom_reader *r, nmv_component *mvcomp,"
611assert marker_old in s, "anchor for EC_INSTRUMENTED_INTRA_STEP marker moved"
612s = s.replace(marker_old, "/* EC_INSTRUMENTED_INTRA_STEP */\n" + marker_old, 1)
613
614open(path, "w").write(s)
615print("intra mode-info per-symbol ladder instrumented")
616PYS
617
618# --- rung 11: per-symbol range ladder inside read_coeffs_txb (decodetxb.c) --
619# lane-sbpart r7: rung 3's EC_TRACE_COEFF only bracketed a whole coefficient
620# block (entry/exit rng) -- too coarse to find WHICH symbol inside a Luma64
621# corner-scan block diverges. This adds EC_COEFF_STEP tag=eob/base_eob/
622# after_bases/sign/post_golomb lines, rng after each, under the same
623# EC_TRACE_COEFF flag (no new env var). Localized r7's own bisect to the
624# `base` symbol at scan position (row=1,col=0) inside block2's luma corner:
625# entry rng and eob/base_eob both match ours byte-for-byte, then our `base`
626# read at that position decodes value=3 (triggering an extra `br` read)
627# where the oracle's equivalent position decodes level=1 -- see
628# lanes/sbpart-r7.report.md.
629G="$SRC/av1/decoder/decodetxb.c"
630[ -f "$G" ] || { echo "no oracle source at $G" >&2; exit 1; }
631
632python3 - "$G" <<'PYC11'
633import sys
634path = sys.argv[1]
635s = open(path).read()
636if "EC_COEFF_STEP" in s:
637 print("decodetxb rung 11 already applied (no-op)")
638 sys.exit(0)
639
640old1 = " *eob = rec_eob_pos(eob_pt, eob_extra);\n"
641new1 = old1 + """ {
642 const int ec_trace2 = getenv("EC_TRACE_COEFF") != NULL;
643 if (ec_trace2) {
644 fprintf(stderr, "EC_COEFF_STEP tag=eob eob=%d rng=%u\\n", *eob, (unsigned)r->ec.rng);
645 }
646 }
647"""
648assert old1 in s, "eob assign not found"
649s = s.replace(old1, new1, 1)
650
651old2 = " levels[get_padded_idx(pos, bhl)] = level;\n }\n if (*eob > 1) {"
652new2 = """ levels[get_padded_idx(pos, bhl)] = level;
653 if (getenv("EC_TRACE_COEFF") != NULL) {
654 fprintf(stderr, "EC_COEFF_STEP tag=base_eob level=%d rng=%u\\n", level, (unsigned)r->ec.rng);
655 }
656 }
657 if (*eob > 1) {"""
658assert old2 in s, "base_eob block not found"
659s = s.replace(old2, new2, 1)
660
661old3 = """ read_coeffs_reverse(r, tx_size, tx_class, 0, *eob - 1 - 1, scan, bhl,
662 levels, base_cdf, br_cdf);
663 }
664 }
665"""
666new3 = old3 + """ if (getenv("EC_TRACE_COEFF") != NULL) {
667 fprintf(stderr, "EC_COEFF_STEP tag=after_bases rng=%u\\n", (unsigned)r->ec.rng);
668 }
669"""
670assert old3 in s, "after_bases site not found"
671s = s.replace(old3, new3, 1)
672
673old4 = """ if (level >= MAX_BASE_BR_RANGE) {
674 level += read_golomb(xd, r);
675 }
676
677 if (c == 0) dc_val = sign ? -level : level;"""
678new4 = """ if (getenv("EC_TRACE_COEFF") != NULL) {
679 fprintf(stderr, "EC_COEFF_STEP tag=sign c=%d sign=%d rng=%u\\n", c, sign, (unsigned)r->ec.rng);
680 }
681 if (level >= MAX_BASE_BR_RANGE) {
682 level += read_golomb(xd, r);
683 }
684 if (getenv("EC_TRACE_COEFF") != NULL) {
685 fprintf(stderr, "EC_COEFF_STEP tag=post_golomb c=%d level=%d rng=%u\\n", c, level, (unsigned)r->ec.rng);
686 }
687
688 if (c == 0) dc_val = sign ? -level : level;"""
689assert old4 in s, "sign/golomb site not found"
690s = s.replace(old4, new4, 1)
691
692open(path, "w").write(s)
693print("decodetxb rung 11 (per-symbol coeff ladder) instrumented")
694PYC11
695
696# --- rung 12: FINAL reconstruction dump (lane-hidden r1) ----------------
697# EC_AV1_FINAL_DUMP=<prefix> -> <prefix>.f<N> per DECODED frame (decode order,
698# hidden alt-ref frames included), written after CDEF + superres + loop
699# restoration have all run, i.e. exactly the frame as it is stored into the
700# reference buffer. Y then U then V, crop-sized rows (post-superres
701# y_crop_width), 8-bit as u8 and high bitdepth as u16 LE -- bit-depth
702# correct, unlike the u8-narrowing debug dumps.
703#
704# DEPTH TRAP (lane-av1oraclerungdepth) -- READ BEFORE USING ANY DUMP RUNG:
705# rungs 1 (PREFILT :146), 6 (POSTDEBLOCK :352), 7 (PREFILT_WIDE :416) and
706# 15 (POSTCDEF :934) write 1 byte per sample with NO YV12_FLAG_HIGHBITDEPTH
707# check, because each is byte-paired with a decoder-side dump that narrows to
708# u8 on purpose. On a 10/12-bit stream those four are unusable: measured on the
709# HBD oracle build with `av112bit-key.obu` (160x128 4:2:0 12-bit, 30720
710# samples) their 1-byte fwrite SIGSEGVs (exit 139, 0-byte file), and where it
711# survives it writes 30720 B where w*h*bps = 61440 B is expected -- EXACTLY
712# HALF, which reads like a truncated decode. Check `stat -c%s` against
713# w*h*bps before calling either a decoder defect. This rung (12) is the
714# depth-correct one for HBD. Each of those four rungs carries a
715# `DEPTH ASSUMPTION` block naming its decoder-side pair and line.
716#
717# Rungs 1/6 (pre-filter / post-deblock) stop before CDEF+LR+superres, and
718# every ffmpeg/aomdec pixel gate in this repo compares SHOWN frames only
719# (class gate-blind-to-hidden-frames), so before this rung no instrument in
720# the repo could compare a hidden frame's final pixels at all.
721python3 - "$F" <<'PYF'
722import sys
723path = sys.argv[1]
724s = open(path).read()
725if "EC_INSTRUMENTED_FINAL" in s:
726 print("final dump already instrumented (no-op)")
727 sys.exit(0)
728
729anchor = """ if (!pbi->dcb.corrupted) {
730 if (cm->features.refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {"""
731dump = """ /* EC_INSTRUMENTED_FINAL */
732 {
733 const char *ec_dump = getenv("EC_AV1_FINAL_DUMP");
734 if (ec_dump) {
735 static int ec_final_idx = 0;
736 char ec_path[1024];
737 snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump, ec_final_idx++);
738 FILE *ec_f = fopen(ec_path, "wb");
739 if (ec_f) {
740 const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf;
741 const int ec_hbd = (ec_b->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
742 const uint8_t *const ec_p8[3] = { ec_b->y_buffer, ec_b->u_buffer,
743 ec_b->v_buffer };
744 const int ec_st[3] = { ec_b->y_stride, ec_b->uv_stride,
745 ec_b->uv_stride };
746 const int ec_w[3] = { ec_b->y_crop_width, ec_b->uv_crop_width,
747 ec_b->uv_crop_width };
748 const int ec_h[3] = { ec_b->y_crop_height, ec_b->uv_crop_height,
749 ec_b->uv_crop_height };
750 for (int ec_pl = 0; ec_pl < (num_planes > 1 ? 3 : 1); ++ec_pl) {
751 for (int ec_r = 0; ec_r < ec_h[ec_pl]; ++ec_r) {
752 if (ec_hbd) {
753 const uint16_t *ec_s = CONVERT_TO_SHORTPTR(ec_p8[ec_pl]);
754 fwrite(ec_s + (size_t)ec_r * ec_st[ec_pl], 2, ec_w[ec_pl], ec_f);
755 } else {
756 fwrite(ec_p8[ec_pl] + (size_t)ec_r * ec_st[ec_pl], 1,
757 ec_w[ec_pl], ec_f);
758 }
759 }
760 }
761 fclose(ec_f);
762 }
763 }
764 }
765
766"""
767assert anchor in s, "final dump anchor moved"
768s = s.replace(anchor, dump + anchor, 1)
769open(path, "w").write(s)
770print("final dump instrumented")
771PYF
772
773# --- rung 13: MV ground truth inside the inter mode ladder (lane-inter8 r3) --
774# lane-inter8 r3 patched the live oracle tree BY HAND and rebuilt aomdec, so
775# these two probes existed only in ~/.cache/aom-oracle/src and any rebuild
776# from this script would have silently dropped them (class: instrument that
777# lives only in a build tree). Both extend rung 4 and are gated by the same
778# EC_TRACE_MODE:
779# * EC_MODE_MV .. mode=.. mv0=(..,..) rng=.. -- printed immediately after
780# assign_mv, i.e. the MV as decoded, BEFORE interintra/motion-mode/
781# interp-filter syntax moves the range further; lets a lane separate an
782# MV defect from a later-symbol defect on the same block.
783# * stack=<ref_mv_count[ref_frame_type]> added to rung 4's EC_MODE_VAL --
784# the reference's own mv-stack depth for the block's reference pair.
785H="$SRC/av1/decoder/decodemv.c"
786[ -f "$H" ] || { echo "no oracle source at $H" >&2; exit 1; }
787
788python3 - "$H" <<'PYMV'
789import sys
790path = sys.argv[1]
791s = open(path).read()
792if "EC_MODE_MV" in s:
793 print("decodemv rung 13 already applied (no-op)")
794 sys.exit(0)
795assert "EC_INSTRUMENTED" in s, "rung 13 needs rung 4 (run this script top to bottom)"
796
797# (a) stack= on rung 4's EC_MODE_VAL
798old_val = """ "mv0=(%d,%d) rng=%u\\n",
799 ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode,
800 (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1],
801 mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col,
802 (unsigned)r->ec.rng);"""
803new_val = """ "mv0=(%d,%d) stack=%d rng=%u\\n",
804 ec_xd->mi_row, ec_xd->mi_col, (int)mbmi->mode,
805 (int)mbmi->ref_frame[0], (int)mbmi->ref_frame[1],
806 mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col,
807 /* EC_STACK */ (int)dcb->ref_mv_count[av1_ref_frame_type(mbmi->ref_frame)],
808 (unsigned)r->ec.rng);"""
809assert old_val in s, "rung 4's EC_MODE_VAL body moved"
810s = s.replace(old_val, new_val, 1)
811
812# (b) EC_MODE_MV right after assign_mv's corrupted-flag merge
813anchor = " aom_merge_corrupted_flag(&dcb->corrupted, mv_corrupted_flag);\n"
814assert s.count(anchor) == 1, "assign_mv corrupted-flag merge is no longer unique"
815probe = """ if (getenv("EC_TRACE_MODE") != NULL) {
816 fprintf(stderr,
817 "EC_MODE_MV mi_row=%d mi_col=%d mode=%d mv0=(%d,%d) rng=%u\\n",
818 xd->mi_row, xd->mi_col, (int)mbmi->mode, mbmi->mv[0].as_mv.row,
819 mbmi->mv[0].as_mv.col, (unsigned)r->ec.rng);
820 }
821"""
822s = s.replace(anchor, anchor + probe, 1)
823open(path, "w").write(s)
824print("decodemv rung 13 (EC_MODE_MV + EC_MODE_VAL stack=) instrumented")
825PYMV
826
827# --- rung 14: temporal-MV (MFMV) ground truth (lane-interbis, scripted by ----
828# --- lane-refstamp r1) -----------------------------------------------------
829# lane-interbis patched the live oracle tree BY HAND for its motion-field hunt,
830# so these two probes lived only in ~/.cache/aom-oracle/src and a rebuild from
831# this script would have dropped them (class: instrument that lives only in a
832# build tree -- same reason rung 13 exists).
833# * EC_TRACE_TPL=1 -> "EC_TPL mi_row=.. mi_col=.. blk=(..,..) mfmv0=(..,..)
834# rfo=.." (or ".. INVALID") for every temporal candidate `add_tpl_ref_mv`
835# probes -- the reference's own projected motion field, cell by cell, to
836# compare against ours (EC_TRACE_TPL on our side).
837# * the resolved MV STACK itself, one "EC_STACK mi_row=.. mi_col=.. ref=..
838# i=.. this=(..,..) comp=(..,..) w=.." line per entry, printed under rung
839# 4's EC_TRACE_MODE right after EC_MODE_VAL (rung 13 only prints the
840# stack DEPTH).
841python3 - "$SRC/av1/common/mvref_common.c" <<'PYT'
842import sys
843path = sys.argv[1]
844s = open(path).read()
845if "EC_TRACE_TPL" in s:
846 print("mvref_common rung 14 already applied (no-op)")
847 sys.exit(0)
848old = " if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) return 0;\n"
849assert old in s, "add_tpl_ref_mv's INVALID_MV early return moved"
850new = """ if (prev_frame_mvs->mfmv0.as_int == INVALID_MV) {
851 if (getenv("EC_TRACE_TPL"))
852 fprintf(stderr, "EC_TPL mi_row=%d mi_col=%d blk=(%d,%d) INVALID\\n",
853 mi_row, mi_col, blk_row, blk_col);
854 return 0;
855 }
856 if (getenv("EC_TRACE_TPL"))
857 fprintf(stderr,
858 "EC_TPL mi_row=%d mi_col=%d blk=(%d,%d) mfmv0=(%d,%d) rfo=%d\\n",
859 mi_row, mi_col, blk_row, blk_col, prev_frame_mvs->mfmv0.as_mv.row,
860 prev_frame_mvs->mfmv0.as_mv.col, prev_frame_mvs->ref_frame_offset);
861"""
862s = s.replace(old, new, 1)
863open(path, "w").write(s)
864print("mvref_common rung 14 (EC_TPL) instrumented")
865PYT
866
867python3 - "$SRC/av1/decoder/decodemv.c" <<'PYST'
868import sys
869path = sys.argv[1]
870s = open(path).read()
871if "EC_STACK mi_row" in s:
872 print("decodemv rung 14 already applied (no-op)")
873 sys.exit(0)
874assert "EC_MODE_MV" in s, "rung 14 needs rung 13 (run this script top to bottom)"
875anchor = """ /* EC_STACK */ (int)dcb->ref_mv_count[av1_ref_frame_type(mbmi->ref_frame)],
876 (unsigned)r->ec.rng);
877"""
878assert s.count(anchor) == 1, "rung 13's EC_MODE_VAL body moved"
879dump = """ /* EC_INSTRUMENTED lane-interbis: the resolved mv stack itself */
880 const MV_REFERENCE_FRAME ec_rt = av1_ref_frame_type(mbmi->ref_frame);
881 for (int ec_i = 0; ec_i < dcb->ref_mv_count[ec_rt]; ec_i++) {
882 fprintf(stderr,
883 "EC_STACK mi_row=%d mi_col=%d ref=%d i=%d this=(%d,%d) "
884 "comp=(%d,%d) w=%d\\n",
885 ec_xd->mi_row, ec_xd->mi_col, (int)ec_rt, ec_i,
886 ec_xd->ref_mv_stack[ec_rt][ec_i].this_mv.as_mv.row,
887 ec_xd->ref_mv_stack[ec_rt][ec_i].this_mv.as_mv.col,
888 ec_xd->ref_mv_stack[ec_rt][ec_i].comp_mv.as_mv.row,
889 ec_xd->ref_mv_stack[ec_rt][ec_i].comp_mv.as_mv.col,
890 ec_xd->weight[ec_rt][ec_i]);
891 }
892"""
893s = s.replace(anchor, anchor + dump, 1)
894open(path, "w").write(s)
895print("decodemv rung 14 (per-entry EC_STACK) instrumented")
896PYST
897
898# --- rung 15: post-CDEF, pre-superres 8-bit row dump (lane-av1422filter) ---
899# The 8-bit mirror of rung 6 one stage later: written right after the CDEF
900# pass (the `if (do_cdef) {...}` block) and before superres/LR, so a final
901# chroma/luma mismatch splits into "already in CDEF" vs "introduced by
902# loop restoration". The *_DUMP16 family covers this stage only in 16-bit
903# builds (its 8-bit run SEGFAULTS); this rung is the 8-bit one. lane-
904# av1422filter added it to the live oracle tree by hand first, then it was
905# transcribed here (class: instrument that lives only in a build tree).
906# DEPTH ASSUMPTION (lane-av1oraclerungdepth): 1 byte per sample, NO
907# YV12_FLAG_HIGHBITDEPTH check. Deliberate -- byte-paired with our
908# EC_AV1_POSTCDEF_DUMP, which narrows to u8 (decode.rs:20048-20054; same
909# closure at :53489). TRAP: on an HBD stream the file is EXACTLY HALF w*h*2,
910# which reads like a truncated/short decode, not a decoder bug. For HBD use rung 12
911# EC_AV1_FINAL_DUMP (:730) -- depth-correct (u8 / u16 LE).
912# OBSERVED 2026-09-29 (HBD build, av112bit-key.obu): the 1-byte fwrite SIGSEGVs
913# (exit 139); where it survives it writes 30720 B where 61440 B is expected --
914# exactly half. That is this rung, not a truncated decode.
915python3 - "$F" <<'PYC'
916import sys
917path = sys.argv[1]
918s = open(path).read()
919if "EC_INSTRUMENTED_POSTCDEF" in s:
920 print("postcdef dump already instrumented (no-op)")
921 sys.exit(0)
922
923anchor = """ if (do_cdef) {
924 if (pbi->num_workers > 1) {
925 av1_cdef_frame_mt(cm, &pbi->dcb.xd, pbi->cdef_worker,
926 pbi->tile_workers, &pbi->cdef_sync,
927 pbi->num_workers, av1_cdef_init_fb_row_mt,
928 do_extend_border_mt);
929 } else {
930 av1_cdef_frame(&pbi->common.cur_frame->buf, cm, &pbi->dcb.xd,
931 av1_cdef_init_fb_row);
932 }
933 }
934"""
935dump = """
936 /* EC_INSTRUMENTED_POSTCDEF (8-bit twin of the POSTDEBLOCK rung:
937 * full aligned buffer, post-CDEF pre-superres/LR) */
938 {
939 const char *ec_dump = getenv("EC_AV1_POSTCDEF_DUMP");
940 if (ec_dump) {
941 static int ec_postcdef_idx = 0;
942 char ec_path[1024];
943 snprintf(ec_path, sizeof(ec_path), "%s.f%d", ec_dump,
944 ec_postcdef_idx++);
945 FILE *ec_f = fopen(ec_path, "wb");
946 if (ec_f) {
947 const YV12_BUFFER_CONFIG *ec_b = &cm->cur_frame->buf;
948 for (int ec_r = 0; ec_r < ec_b->y_height; ++ec_r)
949 fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_width,
950 ec_f);
951 if (num_planes > 1) {
952 for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r)
953 fwrite(ec_b->u_buffer + ec_r * ec_b->uv_stride, 1,
954 ec_b->uv_width, ec_f);
955 for (int ec_r = 0; ec_r < ec_b->uv_height; ++ec_r)
956 fwrite(ec_b->v_buffer + ec_r * ec_b->uv_stride, 1,
957 ec_b->uv_width, ec_f);
958 }
959 fclose(ec_f);
960 }
961 }
962 }
963"""
964assert anchor in s, "do_cdef block anchor moved"
965s = s.replace(anchor, anchor + dump, 1)
966open(path, "w").write(s)
967print("postcdef dump instrumented")
968PYC
969
970# --- depth contract for the four u8-narrowing dump rungs ------------------
971# PREFILT (rung 1), POSTDEBLOCK (rung 3), PREFILT_WIDE (rung 7) and POSTCDEF
972# are paired with ec-av1 decoder rungs that narrow every sample with `as u8`,
973# so the oracle side owes ONE BYTE PER SAMPLE at every depth. As instrumented
974# above they wrote `fwrite(plane + r*stride, 1, w, f)`, which is wrong twice
975# over on a high-bit-depth stream:
976# 1. YV12_BUFFER_CONFIG stores plane pointers in HALVED form -- aom_ports/mem.h
977# defines CONVERT_TO_BYTEPTR(x) = x >> 1 -- so the real address is
978# CONVERT_TO_SHORTPTR(p) (p << 1). Pointer arithmetic on the raw uint8_t*
979# therefore yields an unrelated half-address, and fwrite faults inside
980# memmove: SIGSEGV (exit 139) with a 0-byte file, on EVERY HBD stream, for
981# all four rungs, while rung 12 (which does convert) works. A lane hitting
982# it sees a crashed aomdec and cannot tell it from a decoder defect.
983# 2. y_stride/uv_stride count SAMPLES, so `+ r*stride` in bytes also picks the
984# wrong row even where the address happens to be readable.
985# At 8 bit neither applies: buf is the real pointer and flags is 0, so the
986# bytes emitted are bit-for-bit what these rungs always wrote. This block owns
987# the contract for all four, runs last, and is a REPAIR pass: it rewrites the
988# loops an earlier (or pre-fix) instrumentation left behind, so re-running this
989# script on an already-instrumented tree fixes it in place.
990python3 - "$F" <<'PYN'
991import re
992import sys
993
994path = sys.argv[1]
995s = open(path).read()
996
997helper = '''/* EC_INSTRUMENTED_NARROW_ROW: emit one plane row as ONE BYTE PER SAMPLE, the
998 * shape the ec-av1 decoder's own EC_AV1_*_DUMP rungs write (they narrow every
999 * sample with `as u8`).
1000 *
1001 * Two HBD traps this replaces, both fatal until fixed:
1002 * 1. YV12_BUFFER_CONFIG stores plane pointers in HALVED form: the real
1003 * address is `CONVERT_TO_SHORTPTR(p)` (aom_ports/mem.h defines
1004 * `CONVERT_TO_BYTEPTR(x) = x >> 1`), so `p + r*stride` computed on the raw
1005 * uint8_t* is an unrelated address. `fwrite(y_buffer + r*y_stride, 1, w,
1006 * f)` on a 10/12-bit stream therefore hands fwrite a half-address that
1007 * faults inside memmove -- SIGSEGV with a 0-byte file, which reads as a
1008 * decoder crash rather than a broken rung.
1009 * 2. y_stride/uv_stride count SAMPLES, so a byte-wise `+ r*stride` addresses
1010 * the wrong row as well.
1011 * At 8 bit neither applies: the pointer is the real one and the bytes written
1012 * are exactly what the rung always emitted. */
1013static void ec_dump_narrow_row(FILE *f, const YV12_BUFFER_CONFIG *b,
1014 const uint8_t *plane8, int stride, int row,
1015 int w) {
1016 if (!(b->flags & YV12_FLAG_HIGHBITDEPTH)) {
1017 fwrite(plane8 + (size_t)row * stride, 1, (size_t)w, f);
1018 return;
1019 }
1020 const uint16_t *p = CONVERT_TO_SHORTPTR(plane8) + (size_t)row * stride;
1021 uint8_t *narrow = (uint8_t *)aom_malloc((size_t)w);
1022 if (!narrow) return;
1023 for (int c = 0; c < w; ++c) narrow[c] = (uint8_t)(p[c] & 0xFF);
1024 fwrite(narrow, 1, (size_t)w, f);
1025 aom_free(narrow);
1026}
1027
1028/* EC_INSTRUMENTED_DUMP_CHECK: the harm the depth bug above caused is not a
1029 * wrong number, it is a SILENT 0-byte dump -- downstream that reads as "the
1030 * oracle has no data for this stage" and becomes a phantom stage diff. So
1031 * every narrowing rung checks the byte count it just produced against the
1032 * shape it claims to write and aborts IN THE ORACLE, naming itself, instead
1033 * of handing the decoder an empty file. `expect` is Y + U + V at ONE BYTE PER
1034 * SAMPLE: the crop extent when `aligned` is 0 (PREFILT), the mi-aligned
1035 * extent when 1 (PREFILT_WIDE / POSTDEBLOCK / POSTCDEF). No configuration
1036 * writes 0 bytes: a frame's crop extent is non-zero by construction, and a
1037 * failed fopen skips the block entirely (so a bad path is not an abort). */
1038static void ec_dump_finish(FILE *f, const char *rung,
1039 const YV12_BUFFER_CONFIG *b, int num_planes,
1040 int aligned) {
1041 const size_t y = aligned ? (size_t)b->y_width * b->y_height
1042 : (size_t)b->y_crop_width * b->y_crop_height;
1043 const size_t uv = aligned ? (size_t)b->uv_width * b->uv_height
1044 : (size_t)b->uv_crop_width * b->uv_crop_height;
1045 const size_t expect = y + (num_planes > 1 ? 2 * uv : 0);
1046 const long wrote = ftell(f);
1047 if (wrote < 0 || (size_t)wrote != expect || fflush(f) != 0) {
1048 fprintf(stderr,
1049 "EC_DUMP_ABORT rung=%s bit_depth=%u hbd=%d expect=%zu wrote=%ld "
1050 "(one byte per sample, Y+U+V)\\n",
1051 rung, b->bit_depth,
1052 (b->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0, expect, wrote);
1053 abort();
1054 }
1055 fclose(f);
1056}
1057
1058'''
1059
1060MARKER_ROW = "EC_INSTRUMENTED_NARROW_ROW"
1061MARKER_CHECK = "EC_INSTRUMENTED_DUMP_CHECK"
1062missing = ""
1063if MARKER_ROW not in s:
1064 missing = helper
1065elif MARKER_CHECK not in s:
1066 # The tree already carries the row helper from an earlier run of this
1067 # script: add the byte-count checker on its own so a repaired tree
1068 # converges instead of erroring.
1069 missing = helper[helper.index("/* " + MARKER_CHECK):]
1070if missing:
1071 # Both helpers must precede every user: the POSTCDEF rung was refactored
1072 # into a static helper that sits ABOVE av1_decode_tg_tiles_and_wrapup, so
1073 # anchor there when it exists and at the function itself otherwise.
1074 for anchor in ("static void ec_dump_postcdef(const AV1_COMMON *cm, int num_planes) {",
1075 "void av1_decode_tg_tiles_and_wrapup(AV1Decoder *pbi, const uint8_t *data,"):
1076 if anchor in s:
1077 s = s.replace(anchor, missing + anchor, 1)
1078 break
1079 else:
1080 raise SystemExit("dump helpers: no anchor before the dump rungs")
1081 print("dump helpers inserted: %s"
1082 % ("narrow-row + byte-count check" if len(missing) == len(helper)
1083 else "byte-count check only"))
1084
1085row_loop = re.compile(
1086 r"for \(int ec_r = 0; ec_r < ec_b->(\w+); \+\+ec_r\)\n"
1087 r"(\s*)fwrite\(ec_b->(\w+)_buffer \+ ec_r \* ec_b->(\w+), 1,\s*\n?\s*ec_b->(\w+),\s*\n?\s*ec_f\);")
1088
1089
1090def narrow(match):
1091 rows, indent, plane, stride, width = match.groups()
1092 return ("for (int ec_r = 0; ec_r < ec_b->%s; ++ec_r)\n%s"
1093 "ec_dump_narrow_row(ec_f, ec_b, ec_b->%s_buffer, ec_b->%s, ec_r,\n"
1094 "%s%s ec_b->%s);" % (rows, indent, plane, stride, indent, indent, width))
1095
1096
1097s, rewritten = row_loop.subn(narrow, s)
1098if rewritten:
1099 print("narrow-row depth fix: rewrote %d plane row loops" % rewritten)
1100else:
1101 print("narrow-row depth fix: no legacy row loop left (already depth-correct)")
1102
1103# Close each narrowing rung through the checker. Keyed on the presence of a
1104# rewritten row loop, so rung 12 (EC_AV1_FINAL_DUMP, 2 bytes per sample and
1105# already depth-correct) is never reached: its block has no ec_dump_narrow_row.
1106# The terminator alternation keeps each block matched to ITS OWN close, so a
1107# re-run cannot run a block's body forward into a later rung's fclose.
1108dump_block = re.compile(
1109 r'(FILE \*ec_f = fopen\(ec_path, "wb"\);)(.*?)'
1110 r'((?:fclose\(ec_f\);)|(?:ec_dump_finish\([^;]*\);))',
1111 re.S)
1112
1113WIRED = []
1114
1115def finish(match):
1116 opened, body, closed = match.groups()
1117 if "ec_dump_narrow_row" not in body:
1118 return match.group(0)
1119 # The rung name can sit ABOVE the fopen (the POSTCDEF rung was refactored
1120 # into a helper that does getenv -> fopen at the top), so take the nearest
1121 # preceding EC_AV1_* env lookup rather than searching the block body.
1122 preceding = re.findall(r'getenv\("(EC_AV1_[A-Z_]+)"\)', s[:match.start()])
1123 if not preceding:
1124 raise SystemExit("dump check: no rung env var above a narrowing block")
1125 aligned = 0 if "y_crop_height" in body else 1
1126 if closed.startswith("fclose"):
1127 WIRED.append(preceding[-1])
1128 return "%s%s%s" % (
1129 opened, body,
1130 'ec_dump_finish(ec_f, "%s", ec_b, num_planes, %d);' % (preceding[-1], aligned))
1131
1132
1133s, _ = dump_block.subn(finish, s)
1134if WIRED:
1135 print("dump byte-count check: wired into %d narrowing rung(s): %s"
1136 % (len(WIRED), ", ".join(WIRED)))
1137else:
1138 print("dump byte-count check: every narrowing rung already checks its bytes")
1139open(path, "w").write(s)
1140PYN
1141
1142# --- rung 16: EC_PREDOUT8, the 8-bit predicted block (lane-av1cmpaudit) ----
1143# This rung lived ONLY in the hand-patched oracle tree -- `instrument-aom-
1144# oracle.sh` never transcribed it -- so a rebuild from this script silently
1145# dropped it (class: instrument that lives only in a build tree, the same
1146# reason rung 13 exists). It is transcribed here at BOTH 8-bit prediction
1147# sites in reconintra.c: the non-directional early-return path (DC, SMOOTH*,
1148# PAETH) and the directional / filter-intra tail. lane-av1cmpaudit also grew
1149# `mode=` on both: without it, an agreeing-top / disagreeing-bottom pattern
1150# on a non-directional unit could not be attributed to a mode at all.
1151# `mode=` sits after `txh=`, matching EC_PREDND's own field order; every
1152# pre-existing field keeps its position.
1153#
1154# Idempotent, and an UPGRADE as well as an install: the oracle tree's git HEAD
1155# already carries the rung WITHOUT `mode=`, so the script has to rewrite that
1156# form too, not just insert the block into a pristine upstream file.
1157I="$SRC/av1/common/reconintra.c"
1158[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; }
1159
1160python3 - "$I" <<'PYRI'
1161import sys
1162path = sys.argv[1]
1163s = open(path).read()
1164
1165if 'EC_PREDOUT8' not in s:
1166 # Pristine upstream: insert the rung at both 8-bit prediction sites.
1167 nd_old = """ build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride,
1168 mode, tx_size, n_top_px, n_left_px);
1169 return;
1170 }"""
1171 nd_new = """ build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride,
1172 mode, tx_size, n_top_px, n_left_px);
1173 /* EC_INSTRUMENTED_PREDOUT8 (non-directional, 8-bit) */
1174 if (getenv("EC_PRED")) {
1175 long ec_sum = 0;
1176 for (int r = 0; r < txhpx; ++r)
1177 for (int c = 0; c < txwpx; ++c) ec_sum += dst[r * dst_stride + c];
1178 fprintf(stderr, "EC_PREDOUT8 mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d txw=%d txh=%d mode=%d sum=%ld row0=", xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx, mode, ec_sum);
1179 for (int c = 0; c < txwpx && c < 8; ++c) fprintf(stderr, "%d,", dst[c]);
1180 fprintf(stderr, " col0=");
1181 for (int r = 0; r < txhpx && r < 8; ++r) fprintf(stderr, "%d,", dst[r * dst_stride]);
1182 fprintf(stderr, "\\n");
1183 }
1184 return;
1185 }"""
1186 assert nd_old in s, "non-directional intra predictor tail moved"
1187 s = s.replace(nd_old, nd_new, 1)
1188
1189 dir_old = """ build_directional_and_filter_intra_predictors(
1190 ref, ref_stride, dst, dst_stride, mode, p_angle, filter_intra_mode,
1191 tx_size, disable_edge_filter, n_top_px, n_topright_px, n_left_px,
1192 n_bottomleft_px, intra_edge_filter_type);
1193}"""
1194 dir_new = """ build_directional_and_filter_intra_predictors(
1195 ref, ref_stride, dst, dst_stride, mode, p_angle, filter_intra_mode,
1196 tx_size, disable_edge_filter, n_top_px, n_topright_px, n_left_px,
1197 n_bottomleft_px, intra_edge_filter_type);
1198 /* EC_INSTRUMENTED_PREDOUT8 (directional / filter-intra, 8-bit) */
1199 if (getenv("EC_PRED")) {
1200 long ec_sum = 0;
1201 for (int r = 0; r < txhpx; ++r)
1202 for (int c = 0; c < txwpx; ++c) ec_sum += dst[r * dst_stride + c];
1203 fprintf(stderr, "EC_PREDOUT8 mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d txw=%d txh=%d mode=%d sum=%ld row0=", mi_row, mi_col, plane, row_off, col_off, txwpx, txhpx, mode, ec_sum);
1204 for (int c = 0; c < txwpx && c < 8; ++c) fprintf(stderr, "%d,", dst[c]);
1205 fprintf(stderr, " col0=");
1206 for (int r = 0; r < txhpx && r < 8; ++r) fprintf(stderr, "%d,", dst[r * dst_stride]);
1207 fprintf(stderr, "\\n");
1208 }
1209}"""
1210 assert dir_old in s, "directional intra predictor tail moved"
1211 s = s.replace(dir_old, dir_new, 1)
1212 open(path, "w").write(s)
1213 print("EC_PREDOUT8 installed (both 8-bit paths, with mode=)")
1214 sys.exit(0)
1215
1216# Already present: upgrade the rung to carry `mode=` if it does not yet.
1217nd_fmt_old = 'txw=%d txh=%d sum=%ld row0=", xd->mi_row'
1218nd_fmt_new = 'txw=%d txh=%d mode=%d sum=%ld row0=", xd->mi_row'
1219dir_fmt_old = 'txw=%d txh=%d sum=%ld row0=", mi_row'
1220dir_fmt_new = 'txw=%d txh=%d mode=%d sum=%ld row0=", mi_row'
1221upgraded = 0
1222arg_old = "col_off, txwpx, txhpx, ec_sum);"
1223arg_new = "col_off, txwpx, txhpx, mode, ec_sum);"
1224if nd_fmt_old in s:
1225 s = s.replace(nd_fmt_old, nd_fmt_new, 1)
1226 assert arg_old in s, "EC_PREDOUT8 non-directional argument list moved"
1227 s = s.replace(arg_old, arg_new, 1)
1228 upgraded += 1
1229if dir_fmt_old in s:
1230 s = s.replace(dir_fmt_old, dir_fmt_new, 1)
1231 assert arg_old in s, "EC_PREDOUT8 directional argument list moved"
1232 s = s.replace(arg_old, arg_new, 1)
1233 upgraded += 1
1234if upgraded:
1235 open(path, "w").write(s)
1236 print("EC_PREDOUT8 upgraded to mode= (%d site(s))" % upgraded)
1237else:
1238 print("EC_PREDOUT8 already carries mode= (no-op)")
1239PYRI
1240
1241# --- rung 17: EC_PREDND, the hbd twin of EC_PREDOUT8 (lane-av1cmpaudit) ----
1242# The 10/12-bit non-directional twin of rung 16, and like it this rung lived
1243# ONLY in the hand-patched oracle tree. Without it a rebuild drops the only
1244# prediction probe that fires on a high-bitdepth stream -- rung 16 and the
1245# pre-existing EC_PREDOUT both sit after the `is_hbd` early return and print
1246# nothing there. EC_PREDND already carried `mode=`, so unlike rung 16 this one
1247# is an INSTALL-ONLY rung: it is inserted into a pristine upstream file and is
1248# a no-op on the already-instrumented tree.
1249I="$SRC/av1/common/reconintra.c"
1250[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; }
1251
1252python3 - "$I" <<'PYND'
1253import sys
1254path = sys.argv[1]
1255s = open(path).read()
1256if "EC_PREDND" in s:
1257 print("EC_PREDND already instrumented (no-op)")
1258 sys.exit(0)
1259
1260old = """ highbd_build_non_directional_intra_predictors(
1261 ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px,
1262 xd->bd);
1263 return;
1264 }"""
1265new = """ highbd_build_non_directional_intra_predictors(
1266 ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px,
1267 xd->bd);
1268 /* EC_INSTRUMENTED_PREDND (non-directional, high bitdepth) */
1269 if (getenv("EC_PRED")) {
1270 const int ec_mi_row = -xd->mb_to_top_edge >> (3 + MI_SIZE_LOG2);
1271 const int ec_mi_col = -xd->mb_to_left_edge >> (3 + MI_SIZE_LOG2);
1272 const uint16_t *d16 = CONVERT_TO_SHORTPTR(dst);
1273 long sum = 0;
1274 for (int r = 0; r < txhpx; ++r)
1275 for (int c = 0; c < txwpx; ++c) sum += d16[r * dst_stride + c];
1276 fprintf(stderr,
1277 "EC_PREDND mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d "
1278 "txw=%d txh=%d mode=%d n_top=%d n_left=%d sum=%ld row0=",
1279 ec_mi_row, ec_mi_col, plane, row_off, col_off, txwpx, txhpx,
1280 mode, n_top_px, n_left_px, sum);
1281 for (int c = 0; c < txwpx && c < 8; ++c) fprintf(stderr, "%d,", d16[c]);
1282 fprintf(stderr, " col0=");
1283 for (int r = 0; r < txhpx && r < 8; ++r)
1284 fprintf(stderr, "%d,", d16[r * dst_stride]);
1285 fprintf(stderr, "\\n");
1286 }
1287 return;
1288 }"""
1289assert old in s, "highbd non-directional intra predictor tail moved"
1290s = s.replace(old, new, 1)
1291open(path, "w").write(s)
1292print("EC_PREDND instrumented (non-directional, high bitdepth)")
1293PYND
1294
1295# --- rung 18: var-tx partition CONTEXT OPERANDS (lane-av1oddheightfork3) ----
1296# `EC_VARTX` itself was hand-added to the oracle tree and was NOT in this
1297# generator, so a rebuild from the script dropped it (the rung-loss class:
1298# every rung must be derived here or the next lane loses it). This block
1299# installs BOTH, from a pristine upstream file, idempotently, and is the only
1300# place either print may be edited.
1301#
1302# Why the operands: `txfm_partition_context` (av1_common_int.h:1747-1769) is
1303# `category * 3 + (*above_ctx < txw) + (*left_ctx < txh)`, so a ctx
1304# disagreement with our decoder names WHICH `TXFM_CONTEXT` neighbour band
1305# differs only if both operands are printed -- `EC_VARTX` alone gives the sum
1306# (ctx) and nothing under it. `above` is read at `+ blk_col` of the row band,
1307# `left` at `+ blk_row` of the column band; those indices are in the print so
1308# a reader can tell a band-offset bug from a value bug. Env-gated on
1309# EC_VARTXCTX (a separate flag from EC_VARTX so an existing EC_VARTX ladder
1310# log stays byte-identical to before this rung).
1311python3 - "$F" <<'PYVX'
1312import re, sys
1313path = sys.argv[1]
1314s = open(path).read()
1315if "EC_VARTXCTX" in s:
1316 print("EC_VARTXCTX already instrumented (no-op)")
1317 sys.exit(0)
1318
1319anchor = " is_split = aom_read_symbol(r, ec_ctx->txfm_partition_cdf[ctx], 2, ACCT_STR);\n"
1320assert anchor in s, "read_tx_size_vartx symbol read moved"
1321
1322# Drop a hand-added EC_VARTX print (the tree this block first ran against
1323# carried one that this script never derived), so the derived text is the
1324# only definition and a re-run is a no-op rather than a duplicate print.
1325legacy = re.search(
1326 r' if \(getenv\("EC_VARTX"\) != NULL\)\n'
1327 r' fprintf\(stderr,\n'
1328 r' "EC_VARTX mi=\(%d,%d\).*?\(int\)aom_reader_tell\(r\)\);\n',
1329 s, re.S)
1330if legacy:
1331 s = s[:legacy.start()] + s[legacy.end():]
1332
1333new = anchor + """ if (getenv("EC_VARTX") != NULL)
1334 fprintf(stderr,
1335 "EC_VARTX mi=(%d,%d) row=%d col=%d ctx=%d n=2 s=%d bitpos=%d\\n",
1336 xd->mi_row, xd->mi_col, blk_row, blk_col, ctx, is_split,
1337 (int)aom_reader_tell(r));
1338 /* EC_INSTRUMENTED_VARTXCTX: the two TXFM_CONTEXT operands of `ctx`. */
1339 if (getenv("EC_VARTXCTX") != NULL)
1340 fprintf(stderr,
1341 "EC_VARTXCTX mi=(%d,%d) row=%d col=%d above=%d left=%d txw=%d "
1342 "txh=%d ctx=%d\\n",
1343 xd->mi_row, xd->mi_col, blk_row, blk_col,
1344 (int)xd->above_txfm_context[blk_col],
1345 (int)xd->left_txfm_context[blk_row], (int)tx_size_wide[tx_size],
1346 (int)tx_size_high[tx_size], ctx);
1347"""
1348s = s.replace(anchor, new, 1)
1349open(path, "w").write(s)
1350print("EC_VARTX/EC_VARTXCTX instrumented (read_tx_size_vartx)")
1351PYVX
1352
1353# --- rung 19: EC_PIB, EVERY av1_predict_intra_block call (lane-av1422ctattr) ---
1354# WHY. Three lanes of 4:2:2 chroma archaeology stalled on ONE blind spot:
1355# `av1_predict_intra_block` has an early `if (use_palette) { ...; return; }`
1356# and TWO early `return`s after it (the 8-bit non-directional site and the
1357# hbd one), so EC_PREDOUT8 / EC_PREDND only print on SOME of the paths that
1358# write a block. A chroma region where no rung fires is therefore
1359# un-attributable: "libaom used dc_top" was an inference from the predicted
1360# VALUE, not a printed flag, and the whole ladder looked like it had no block
1361# there at all. EC_PIB prints the CALL IDENTITY -- before any early return --
1362# so the question "which call wrote this pixel, and did it return early" is
1363# answerable from the trace instead of from arithmetic.
1364#
1365# Field order is deliberately identical to EC_PREDOUT8/EC_PRED for the fields
1366# they share, so a rung 16 line and a rung 19 line for the same block read as
1367# one line. `use_palette` is the early-return bit: use_palette=1 with no
1368# EC_PREDOUT8/EC_PRED twin line IS a palette write.
1369#
1370# Env: EC_PIB=1. Optional EC_PIBWIN="mi_row_lo:mi_row_hi:mi_col_lo:mi_col_hi"
1371# (any field < 0 means "any") so a seed's own block can be isolated without
1372# dumping a whole frame.
1373python3 - "$I" <<'PYPIB'
1374import sys
1375path = sys.argv[1]
1376s = open(path).read()
1377if "EC_PIB " in s:
1378 print("EC_PIB already instrumented (no-op)")
1379 sys.exit(0)
1380
1381anchor = """ const int is_hbd = is_cur_buf_hbd(xd);
1382
1383 assert(mode < INTRA_MODES);"""
1384new = """ const int is_hbd = is_cur_buf_hbd(xd);
1385
1386 /* EC_INSTRUMENTED_PIB: the call IDENTITY, printed BEFORE the palette
1387 early return so every call is visible. */
1388 if (getenv("EC_PIB")) {
1389 const char *ec_w = getenv("EC_PIBWIN");
1390 int ec_r0 = -1, ec_r1 = -1, ec_c0 = -1, ec_c1 = -1;
1391 if (ec_w) sscanf(ec_w, "%d:%d:%d:%d", &ec_r0, &ec_r1, &ec_c0, &ec_c1);
1392 if ((ec_r0 < 0 || (xd->mi_row >= ec_r0 && xd->mi_row <= ec_r1)) &&
1393 (ec_c0 < 0 || (xd->mi_col >= ec_c0 && xd->mi_col <= ec_c1))) {
1394 fprintf(stderr,
1395 "EC_PIB mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d "
1396 "txw=%d txh=%d mode=%d use_palette=%d filter_intra=%d bsize=%d "
1397 "px=%d py=%d hbd=%d\\n",
1398 xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx,
1399 mode, use_palette, (int)filter_intra_mode, (int)mbmi->bsize,
1400 col_off << MI_SIZE_LOG2, row_off << MI_SIZE_LOG2, (int)is_hbd);
1401 }
1402 }
1403
1404 assert(mode < INTRA_MODES);"""
1405assert anchor in s, "av1_predict_intra_block prologue moved"
1406s = s.replace(anchor, new, 1)
1407
1408# --- rung 20: EC_DCIN, the DC path's availability INPUTS (lane-av1422ctattr) --
1409# `dc_predictor`'s four variants are selected by (have_top, have_left) and
1410# scaled by (n_top_px, n_left_px); EC_PREDOUT8 prints none of them, only the
1411# RESULT and the mode. So a predicted value that "looks like dc_top" is an
1412# inference. EC_DCIN prints the four operands, the two edge SUMS they are
1413# taken from, the availability BITS themselves (including the per-plane
1414# chroma_* narrowing in set_mi_row_col), and the variant id the four-way
1415# select picked -- so the variant is a printed field, not an inference.
1416#
1417# Variant id: 0 = dc (both edges), 1 = dc_top, 2 = dc_left, 3 = dc_128.
1418#
1419# Installed at BOTH 8-bit and high-bitdepth non-directional sites, before the
1420# predictor call. Env: EC_DCIN=1 (EC_PIBWIN filters it too).
1421nd_anchor = """ build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride,
1422 mode, tx_size, n_top_px, n_left_px);"""
1423nd_new = """ /* EC_INSTRUMENTED_DCIN (8-bit non-directional): the availability INPUTS
1424 and the DC variant they select. */
1425 if (getenv("EC_DCIN")) {
1426 long ec_atop = 0, ec_aleft = 0;
1427 int ec_i;
1428 for (ec_i = 0; ec_i < n_top_px; ++ec_i) ec_atop += ref[ec_i];
1429 for (ec_i = 0; ec_i < n_left_px; ++ec_i) ec_aleft += ref[ec_i * ref_stride];
1430 fprintf(stderr,
1431 "EC_DCIN mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d "
1432 "txw=%d txh=%d mode=%d have_top=%d have_left=%d n_top=%d "
1433 "n_left=%d atop=%ld aleft=%ld dcv=%d up=%d left=%d cup=%d "
1434 "cleft=%d ss_x=%d ss_y=%d bsize=%d\\n",
1435 xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx,
1436 mode, have_top, have_left, n_top_px, n_left_px, ec_atop,
1437 ec_aleft,
1438 (n_top_px > 0 ? (n_left_px > 0 ? 0 : 1)
1439 : (n_left_px > 0 ? 2 : 3)),
1440 xd->up_available, xd->left_available, xd->chroma_up_available,
1441 xd->chroma_left_available, ss_x, ss_y, (int)mbmi->bsize);
1442 }
1443 build_non_directional_intra_predictors(ref, ref_stride, dst, dst_stride,
1444 mode, tx_size, n_top_px, n_left_px);"""
1445assert nd_anchor in s, "8-bit non-directional predictor call moved"
1446s = s.replace(nd_anchor, nd_new, 1)
1447
1448hbd_anchor = """ highbd_build_non_directional_intra_predictors(
1449 ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px,
1450 xd->bd);"""
1451hbd_new = """ /* EC_INSTRUMENTED_DCIN (high bitdepth non-directional): the hbd twin. */
1452 if (getenv("EC_DCIN")) {
1453 const uint16_t *ec_r16 = CONVERT_TO_SHORTPTR(ref);
1454 long ec_atop = 0, ec_aleft = 0;
1455 int ec_i;
1456 for (ec_i = 0; ec_i < n_top_px; ++ec_i) ec_atop += ec_r16[ec_i];
1457 for (ec_i = 0; ec_i < n_left_px; ++ec_i)
1458 ec_aleft += ec_r16[ec_i * ref_stride];
1459 fprintf(stderr,
1460 "EC_DCIN mi_row=%d mi_col=%d plane=%d row_off=%d col_off=%d "
1461 "txw=%d txh=%d mode=%d have_top=%d have_left=%d n_top=%d "
1462 "n_left=%d atop=%ld aleft=%ld dcv=%d up=%d left=%d cup=%d "
1463 "cleft=%d ss_x=%d ss_y=%d bsize=%d\\n",
1464 xd->mi_row, xd->mi_col, plane, row_off, col_off, txwpx, txhpx,
1465 mode, have_top, have_left, n_top_px, n_left_px, ec_atop,
1466 ec_aleft,
1467 (n_top_px > 0 ? (n_left_px > 0 ? 0 : 1)
1468 : (n_left_px > 0 ? 2 : 3)),
1469 xd->up_available, xd->left_available, xd->chroma_up_available,
1470 xd->chroma_left_available, ss_x, ss_y, (int)mbmi->bsize);
1471 }
1472 highbd_build_non_directional_intra_predictors(
1473 ref, ref_stride, dst, dst_stride, mode, tx_size, n_top_px, n_left_px,
1474 xd->bd);"""
1475if hbd_anchor in s:
1476 s = s.replace(hbd_anchor, hbd_new, 1)
1477else:
1478 print("WARN: hbd non-directional call anchor not found; EC_DCIN is 8-bit only")
1479
1480open(path, "w").write(s)
1481print("EC_PIB/EC_DCIN instrumented (av1_predict_intra_block)")
1482PYPIB
1483
1484# --- rung 21: EC_DP, the per-block branch taken in decode_token_recon_block ---
1485# WHY. `decode_token_recon_block` has two arms -- intra (the only one whose
1486# prediction prints a rung) and inter (`predict_inter_block_visit`, no
1487# intra rung at all) -- AND, inside the intra arm, `if (plane && !xd-
1488# >is_chroma_ref) break;`, so a chroma plane can be skipped entirely. A
1489# region where NO prediction rung fires is consistent with all three, and the
1490# rung ladder alone cannot tell them apart. EC_DP prints the branch decision
1491# for every block: which arm, whether chroma is reconstructed at all, and the
1492# max_unit geometry the loop walks. Env: EC_DP=1.
1493python3 - "$F" <<'PYDP'
1494import sys
1495path = sys.argv[1]
1496s = open(path).read()
1497if "EC_DP mi_row=" in s:
1498 print("EC_DP already instrumented (no-op)")
1499 sys.exit(0)
1500
1501anchor = """ MB_MODE_INFO *mbmi = xd->mi[0];
1502
1503 if (!is_inter_block(mbmi)) {"""
1504new = """ MB_MODE_INFO *mbmi = xd->mi[0];
1505
1506 /* EC_INSTRUMENTED_DP: the branch decode_token_recon_block takes for this
1507 block -- intra vs inter, and whether the chroma planes are reconstructed
1508 at all (`plane && !xd->is_chroma_ref`). Anchored on the `mbmi` +
1509 `if (!is_inter_block)` pair, not on the function signature, because the
1510 signature's parameter wrapping is not stable across libaom revisions
1511 (v3.13.3 wraps `ThreadData *const td, aom_reader *r,` onto one line). */
1512 if (getenv("EC_DP")) {
1513 fprintf(stderr,
1514 "EC_DP mi_row=%d mi_col=%d bsize=%d inter=%d chroma_ref=%d "
1515 "skip_txfm=%d bw=%d bh=%d planes=%d is_intrabc=%d\\n",
1516 xd->mi_row, xd->mi_col, (int)bsize, (int)is_inter_block(mbmi),
1517 (int)xd->is_chroma_ref, (int)mbmi->skip_txfm,
1518 (int)max_block_wide(xd, bsize, 0),
1519 (int)max_block_high(xd, bsize, 0), num_planes,
1520 (int)is_intrabc_block(mbmi));
1521 }
1522
1523 if (!is_inter_block(mbmi)) {"""
1524assert anchor in s, "decode_token_recon_block prologue moved"
1525s = s.replace(anchor, new, 1)
1526open(path, "w").write(s)
1527print("EC_DP instrumented (decode_token_recon_block)")
1528PYDP