forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBbede77eTahinli2 months ago3534 commits

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