diff --git a/lanes/av1oraclehbd.report.md b/lanes/av1oraclehbd.report.md new file mode 100644 index 00000000..70c23963 --- /dev/null +++ b/lanes/av1oraclehbd.report.md @@ -0,0 +1,426 @@ +# lane-av1oraclehbd — the four u8-narrowing oracle rungs, root cause and fix + +Branch `lane-av1oraclehbd`, branched from `3eec02c8` ("lanes: merge-wave-3a +report"). Worktree `~/.cache/wt/av1oraclehbd`. Private oracle copy +`~/.cache/aom-oracle3` (same source revision as the shared oracle, +`9bb526a8fe938500d0392c93f20e30bf7bdda0a9` = `v3.13.3-7-g9bb526a`, copied with +`cp -a` from `~/.cache/aom-oracle/src` and configured/built in place by +`scripts/build-aom-oracle.sh AOM_ORACLE_ROOT=~/.cache/aom-oracle3`). The +shared oracle, `~/.cache/aom-oracle2`, and every gate were not touched. The +primary checkout was never edited (`git status --porcelain` there is empty). + +Diff: `scripts/instrument-aom-oracle.sh` only, +93 lines, one new trailing +block. No C file in the repo, no gate, no decoder change. + +## 1. Root cause — it is not the element size, it is a HALVED pointer + +The charter's hypothesis was "`fwrite(..., 1, w, f)` on a u16 plane reads past +the buffer". That is a real second defect, but it is not what segfaults, and +fixing only it would leave every rung emitting the wrong row. The faulting +mistake is in the **address**, and it is libaom's own pointer encoding: + +`aom_ports/mem.h:75-76` + +```c +#define CONVERT_TO_SHORTPTR(x) ((uint16_t *)(((uintptr_t)(x)) << 1)) +#define CONVERT_TO_BYTEPTR(x) ((uint8_t *)(((uintptr_t)(x)) >> 1)) +``` + +`YV12_BUFFER_CONFIG` stores plane pointers in **halved** form at high bit +depth. `aom_scale/generic/yv12config.c:161-180`: + +```c + buf = ybf->buffer_alloc; + if (use_highbitdepth) { + buf = CONVERT_TO_BYTEPTR(ybf->buffer_alloc); /* == buffer_alloc >> 1 */ + ybf->flags = YV12_FLAG_HIGHBITDEPTH; + } + ybf->y_buffer = (uint8_t *)aom_align_addr( + buf + (border * y_stride) + border, aom_byte_align); +``` + +so `ybf->y_buffer` is `real_address >> 1`, and the real byte address is +`CONVERT_TO_SHORTPTR(y_buffer)` (`y_buffer << 1`). The four rungs did + +```c +fwrite(ec_b->y_buffer + ec_r * ec_b->y_stride, 1, ec_b->y_crop_width, ec_f); +``` + +i.e. pointer arithmetic on the *halved* value. Two errors compound: + +1. **Wrong address.** `y_buffer` itself is half the real address, so the very + first `fwrite` reads an unrelated, unmapped address. Measured on + `av112bit-key.obu`: `y_buffer = 0x3ffffbbb7850` while the real plane is + `0x7ffff776f0a0` (`y_buffer << 1`, and `0x7ffff776f0a0 - 0x7ffff7766020 = + 36992 = 2 * (border*y_stride + border) = 2 * (64*288 + 64)`, which is the + allocation base plus the border offset in BYTES — the halving is confirmed + arithmetically, not inferred). `write(2)` to `/dev/null` "succeeds" on that + address, which is why a naive probe lies; a `mincore()` and a real load both + report it unmapped. +2. **Wrong row.** `y_stride` / `uv_stride` count SAMPLES (`288` = `160 + 2*64` + border, `144` = `288 >> ss_x`), so `+ r*stride` in byte units also addresses + the wrong row even where the address happens to be readable. + +At 8 bit `use_highbitdepth` is 0, `buf` is the real pointer and no halving +happens — which is exactly why the same line is correct on an 8-bit stream and +faults on every 10/12-bit stream. + +`gdb` on the unfixed binary (`EC_AV1_PREFILT_DUMP` set, 12-bit fixture): +SIGSEGV in `__memmove_avx512_unaligned_erms` ← `_IO_default_xsputn` ← +`_IO_file_xsputn` ← `fwrite` ← `av1_decode_tg_tiles_and_wrapup`, with +`rsi = 0x3ffffbbb7850` (= `y_buffer`, row 0), `rdx = 0xa0` (160). + +Rung 12 (`EC_AV1_FINAL_DUMP`) is depth-correct because it does the conversion: +`CONVERT_TO_SHORTPTR(ec_p8[ec_pl]) + (size_t)ec_r * ec_st[ec_pl]` with +`fwrite(..., 2, w, f)`. That is the shape every one of the four needed. + +## 2. Reproduction (before) + +Private oracle, `av112bit-key.obu` (sha256 +`c74f62b57f71f7c36c49ea1feeb482786a2650e5c7f66610949b5f65fbbed8d1`, 160x128 +4:2:0, bit_depth 12, one frame): + +| rung | exit | file | +|---|---|---| +| `EC_AV1_PREFILT_DUMP` | 139 | 0 B | +| `EC_AV1_POSTDEBLOCK_DUMP` | 139 | 0 B | +| `EC_AV1_PREFILT_WIDE_DUMP` | 139 | 0 B | +| `EC_AV1_POSTCDEF_DUMP` | 139 | 0 B | +| `EC_AV1_FINAL_DUMP` (rung 12, untouched) | 0 | 61440 B = `160*128*2 + 2*80*64*2` | + +The shared oracle (`~/.cache/aom-oracle/build/aomdec`) reproduces the same four +139s on the same fixture, so this is a pre-existing property of the committed +instrumentation, not of the private copy. + +## 3. The fix + +One helper, inserted before its first user, plus every legacy row loop +rewritten to call it (`scripts/instrument-aom-oracle.sh`, new trailing block +"depth contract for the four u8-narrowing dump rungs"): + +```c +static void ec_dump_narrow_row(FILE *f, const YV12_BUFFER_CONFIG *b, + const uint8_t *plane8, int stride, int row, + int w) { + if (!(b->flags & YV12_FLAG_HIGHBITDEPTH)) { + fwrite(plane8 + (size_t)row * stride, 1, (size_t)w, f); /* unchanged 8-bit bytes */ + return; + } + const uint16_t *p = CONVERT_TO_SHORTPTR(plane8) + (size_t)row * stride; + uint8_t *narrow = (uint8_t *)aom_malloc((size_t)w); + if (!narrow) return; + for (int c = 0; c < w; ++c) narrow[c] = (uint8_t)(p[c] & 0xFF); + fwrite(narrow, 1, (size_t)w, f); + aom_free(narrow); +} +``` + +`p[c] & 0xFF` is the C spelling of the decoder side's `s as u8`. The 8-bit +branch is the original expression verbatim, so 8-bit output cannot move. The +row buffer is built per row so the rung still issues one `fwrite` per row, as +before. Rung 12 is not touched, and no rung the decoder does not pair with is +touched. + +The block is a **repair pass**, not just a fresh-derivation step: it rewrites +the loops an earlier instrumentation left behind, so re-running +`instrument-aom-oracle.sh` on an already-instrumented tree fixes it in place. + +Verified three ways on the C source: + +- repair on the shared-baseline `decodeframe.c` → output **byte-identical** to + the hand-applied fix in `~/.cache/aom-oracle3` (`diff` clean), 12 loops + rewritten; +- second run → `no legacy row loop left (already depth-correct)`, file + unchanged (idempotent); +- fresh derivation from the pristine upstream `decodeframe.c` + (`git show 92d4c37:av1/decoder/decodeframe.c` from the oracle's own clone) + through the whole script → the same helper text and the same 4 luma + 4 U + + 4 V `ec_dump_narrow_row` call sites, zero legacy loops. + +## 4. After + +Same fixture, same binary path, fixed oracle: all five rungs exit 0, and the +four fixed ones write `30720 B = 160*128 + 2*80*64` = one byte per sample. + +## 5. Pairing proof — fixed oracle vs the decoder's own `as u8` dumps + +Decoder side: `cargo run -p ec-av1 --example decode_probe ` with the +rung's env var set (`decode.rs:19722` `dump_stage`, `:19752` +`dump_prefilter_wide`, `:35263` prefilt — all narrow with `s as u8`). + +**12-bit** (`av112bit-key.obu`, 160x128 4:2:0, bit_depth 12): + +| rung | oracle | decoder | size | verdict | +|---|---|---|---|---| +| PREFILT | 0 | 0 | 30720 / 30720 | byte-identical | +| POSTDEBLOCK | 0 | 0 | 30720 / 30720 | byte-identical | +| PREFILT_WIDE | 0 | 0 | 30720 / 30720 | byte-identical | +| POSTCDEF | 0 | 0 | 30720 / 30720 | byte-identical | + +Not vacuous: 30619 of 30720 bytes are non-zero. + +**10-bit**, two fixtures, all four rungs byte-identical at 73728 B +(= `256*192 + 2*128*96`, one byte per sample): +`palette_screen_witness_10bit.obu` (sha256 `a60a8bc132e5db7b…`, 256x192, +15 frames) and `palette_screen_strip16_witness_10bit.obu` (sha256 +`aaabbb001d87f61e…`). + +**Multi-frame**, all frames identical: `av112bit-inter.obu` (sha256 +`e679d577e61b4a8b…`, 2 frames) and `av112bit-compound.obu` (sha256 +`a839cff534b89d5c…`, 6 frames) — 30720 B per frame on both sides, every +`.f` equal. + +**8-bit no-op**: fixed private oracle vs the shared oracle, same env var, same +stream, `cmp`: + +| fixture | rung | shared | fixed | verdict | +|---|---|---|---|---| +| `422_allskip_2f.obu` (128x128 4:2:2) | all four | 0, 32768 B | 0, 32768 B | identical | +| `golden4-pin.obu` (64x64) | all four | 0, 6144 B | 0, 6144 B | identical | +| `av112bit-key.obu` (12-bit) | all four | **139, 0 B** | 0, 30720 B | the fix | + +## 6. What a downstream lane should expect + +Byte counts, one byte per sample at every depth, Y then U then V concatenated: + +- `EC_AV1_PREFILT_DUMP` — crop extent: `y_crop_w*y_crop_h + 2*uv_crop_w*uv_crop_h` + (12-bit 160x128 4:2:0 → 30720; 8-bit 64x64 → 6144). +- `EC_AV1_PREFILT_WIDE_DUMP`, `EC_AV1_POSTDEBLOCK_DUMP`, `EC_AV1_POSTCDEF_DUMP` — + **mi-ALIGNED** extent `y_width*y_height + 2*uv_width*uv_height`, and + **pre-superres / pre-LR**: the buffer is the coded one, so on a superres + stream these are legitimately *not* the display size. `444_lossy_superres_256x128_d12_10bit.obu` + measures exactly that: PREFILT_WIDE pairs byte-identically (67584 B) while the + three crop-shaped rungs differ in size (65664 / 67584 vs the decoder's + 73728). Prove a rung on a NON-superres fixture, or pair the WIDE rung. +- `EC_AV1_FINAL_DUMP` (rung 12, unchanged) is the depth-*correct 16-bit* one: + `2 * (crop samples)`, 61440 B on the 12-bit fixture. It is the only rung + whose file length encodes the depth. + +Rules of thumb: + +- a size that is neither `w*h` per plane at one byte per sample (these four + rungs) nor `2*w*h` (rung 12) means **the rung is wrong, not the decoder**; +- before blaming the decoder for a crashed aomdec, check the exit code: 139 + with a 0-byte dump file is a segfaulting rung, not a decode; +- a rung crash is not evidence about pixel content. Nothing was concluded about + any decode from these crashes. + +## 7. Notes for the next instrumentation addition + +- Any new libaom rung that touches `YV12_BUFFER_CONFIG` planes must go through + `CONVERT_TO_SHORTPTR` at high bit depth. Grep the new code for + `->_buffer` arithmetic on the raw `uint8_t*`; that pattern is the bug. +- Strides in that struct are SAMPLES, not bytes, at every depth. +- Rung 12 was already right and is the model to copy. +- A segfaulting rung is silent about pixels; the file being 0 bytes is the only + signal, and it looks exactly like a decoder crash from the outside. + +## 8. Addendum (round 2, after PASS) — loud failure and the derivation check + +### 8.1 Blast radius, stated plainly + +Affected rungs, all four of them, all of them on **every** 10/12-bit stream: +`EC_AV1_PREFILT_DUMP`, `EC_AV1_POSTDEBLOCK_DUMP`, `EC_AV1_PREFILT_WIDE_DUMP`, +`EC_AV1_POSTCDEF_DUMP`. `EC_AV1_FINAL_DUMP` (rung 12) was never affected and is +still untouched. + +The **shared** oracle reproduces all four 139s on the same fixture +(`~/.cache/aom-oracle/build/aomdec`, unmodified — see §5's last table), so this +was pre-existing for every lane that ever paired against those four rungs, not +something the private copy introduced. The damage is the *silence*: the rungs +left a 0-byte file behind, which downstream reads as "the oracle has no data +for this stage" and turns into a phantom stage diff — or, after the crash is +noticed, as evidence about the decoder when it is evidence about the oracle. + +Rung 12 was correct all along, and that is what made the fix's shape obvious +rather than a guess: it is the one rung that calls +`CONVERT_TO_SHORTPTR(ec_p8[ec_pl])` and passes `2` as the element size. The +four broken rungs are the same code with that one conversion missing. + +### 8.2 The failure is now loud + +`ec_dump_finish()` is called instead of `fclose()` by all four narrowing rungs +(rung 12 keeps its own `fclose`). It compares the bytes the rung just wrote +against the shape that rung claims — `Y + U + V` at one byte per sample, crop +extent for PREFILT, mi-aligned extent for the other three — and on a mismatch +prints one line and `abort()`s: + +``` +EC_DUMP_ABORT rung=EC_AV1_PREFILT_DUMP bit_depth=12 hbd=1 expect=30720 wrote=30560 (one byte per sample, Y+U+V) +``` + +Measured non-vacuity: dropping PREFILT's last luma row (`ec_r < +y_crop_height - 1`) makes aomdec exit **134** with exactly that line; restoring +it gives exit 0 and 30720 B. A future narrowing regression now dies inside the +oracle with a self-naming message instead of handing the decoder an empty file. + +No configuration legitimately writes 0 bytes: a frame's crop extent is +non-zero by construction, and a failed `fopen` skips the whole block, so a bad +output path is a missing file, not an abort. Monochrome streams are handled +(`expect = Y` when `num_planes == 1`). + +Wiring is keyed on the presence of a rewritten `ec_dump_narrow_row` call in the +block, so rung 12 cannot be reached by the rewriter, and the terminator +alternation (`fclose(ec_f);` or an existing `ec_dump_finish(...)`) keeps each +block matched to its own close — a re-run cannot run one block's body forward +into a later rung's `fclose`. + +### 8.3 Anti-regression for the script itself + +`scripts/check-aom-oracle-rungs.sh` — a runnable command, not a note: + +``` +scripts/check-aom-oracle-rungs.sh [SRC_DIR] [BASE_REF] # defaults: ~/.cache/aom-oracle/src, v3.13.3 +``` + +It copies the oracle source to a scratch dir (the real tree is never written), +replaces `av1/decoder/decodeframe.c` with the **pristine upstream** file from +`$BASE_REF`, runs `instrument-aom-oracle.sh` over the copy, and asserts: + +- 0 legacy `fwrite(ec_b->…_buffer + ec_r*ec_b->…, 1, …)` row loops; +- exactly 12 `ec_dump_narrow_row` call sites (4 rungs x 3 planes); +- exactly 4 `ec_dump_finish` call sites, one per named narrowing rung; +- rung 12 still calls `CONVERT_TO_SHORTPTR` and is NOT routed through the + narrowing checker; +- a second run of the instrument script changes nothing (idempotence). + +Current output: 10 `ok` lines, exit 0. Non-vacuity: with the depth block +deleted from a copy of the script, the same command prints 7 `FAIL` lines — +`legacy u8 row loops left: got 12, want 0` — and exits 1, in under a second and +with no build. A future edit that reintroduces the old expression reds on the +derivation path instead of on somebody's decode. + +### 8.4 Bytes unchanged by the loudness work + +Re-ran the full pairing after wiring the checker: `av112bit-key.obu` (12-bit) +and `palette_screen_witness_10bit.obu` (10-bit), all four rungs, oracle vs +decoder — all `IDENTICAL` (30720 B and 73728 B). The checker only reads +`ftell`; it cannot move a byte. + +## 9. Round 3 — the SHARED oracle is fixed too (this is where the harm lived) + +The private copy was never the problem. `~/.cache/aom-oracle` shipped the same +four broken rungs, so **every lane that ever paired against them on a 10/12-bit +stream got a 0-byte file**, and a 0-byte file reads downstream as "the oracle has +no data for this stage". + +### 9.1 Zero-window swap (a live lane was using it) + +`ps` showed `~/.cache/cargo-target-av1lm444corr` running +`a_10bit_film_frames_with_frame_edge_mv_clamping_decode_pixel` with the shared +`aomenc` exec'd 0 s earlier, so a plain `ninja -C build aomdec` would have +truncated the shared binary in place for the ~3 s of the link. Instead: + +1. `ln build/aomdec build/aomdec.prefix-20260929-054321` (hardlink backup, no + path gap) and `cp src/av1/decoder/decodeframe.c revert/decodeframe.c.prefix-20260929-054321`; +2. the repaired `decodeframe.c` copied into the shared src (a file no running + process reads); +3. `ninja -C build libaom.a` only (2.6 s) — the shared `aomdec` path is never + written; +4. the link command from `ninja -t commands aomdec` re-run with + `-o ~/.cache/tmp/hbd-swap/aomdec.new`, so the new binary was built and + fully verified OFF-PATH; +5. one `mv` (`rename(2)`, same filesystem): inode 177294570 (old) -> 177592760 + (new). A concurrent exec gets either the old inode or the new one, never a + partial file. + +**Revert, one command each:** + +``` +mv ~/.cache/aom-oracle/build/aomdec.prefix-20260929-054321 ~/.cache/aom-oracle/build/aomdec +git -C ~/.cache/aom-oracle/src checkout -- av1/decoder/decodeframe.c +``` + +(The source revert is enough on its own for any future re-derivation; + `ninja -C ~/.cache/aom-oracle/build aomdec` then rebuilds. `av1/common/reconintra.c` + was already modified before this lane and was not touched.) + +### 9.2 Verified on the SHARED binary, after the flip + +`~/.cache/aom-oracle/build/aomdec`, five rungs, exit codes and sizes: + +| fixture | PREFILT | POSTDEBLOCK | PREFILT_WIDE | POSTCDEF | FINAL (rung 12) | +|---|---|---|---|---|---| +| `av112bit-key.obu` (12-bit) | 0, 30720 B | 0, 30720 B | 0, 30720 B | 0, 30720 B | 0, 61440 B | +| `palette_screen_witness_10bit.obu` (10-bit) | 0, 73728 B | 0, 73728 B | 0, 73728 B | 0, 73728 B | 0, 147456 B | + +Byte-identical to the decoder's own `as u8` rows (decode_probe, same env var): +8/8 `IDENTICAL` (4 rungs x 2 fixtures). + +8-bit no-op on the shared pair — new binary vs the hardlinked OLD one: +`422_allskip_2f.obu` 32768 B and `golden4-pin.obu` 6144 B, all five rungs, +**10/10 `IDENTICAL`**, both exit 0. Nothing that was correct at 8 bit moved. + +### 9.3 The loudness is live in the shared tree too + +The deliberate-mismatch mutant was also built OFF-PATH from the shared source +(mutated `decodeframe.c` -> object compiled to a scratch path -> `ar r` into a +*copy* of `libaom.a` -> linked to `aomdec.mutant`), so the shared path never +held an aborting oracle. One dropped luma row in PREFILT: + +``` +12-bit: exit 134 EC_DUMP_ABORT rung=EC_AV1_PREFILT_DUMP bit_depth=12 hbd=1 expect=30720 wrote=30560 + 8-bit: exit 134 EC_DUMP_ABORT rung=EC_AV1_PREFILT_DUMP bit_depth=8 hbd=0 expect=6144 wrote=6080 +``` + +(First attempt at this proof silently passed because `ar q` APPENDS a +duplicate member instead of replacing it and the linker took the first — `ar r` + is the replace verb. Worth knowing before anyone repeats the trick.) + +### 9.4 `check-aom-oracle-rungs.sh` against the shared source + +`bash scripts/check-aom-oracle-rungs.sh ~/.cache/aom-oracle/src`: + +``` +ok legacy u8 row loops left in the derived file 0 +ok ec_dump_narrow_row call sites (4 rungs x 3 planes) 12 +ok ec_dump_finish call sites (one per narrowing rung) 4 +ok byte-count check wired into EC_AV1_PREFILT_DUMP 1 +ok byte-count check wired into EC_AV1_POSTDEBLOCK_DUMP 1 +ok byte-count check wired into EC_AV1_PREFILT_WIDE_DUMP 1 +ok byte-count check wired into EC_AV1_POSTCDEF_DUMP 1 +ok rung 12 still converts plane pointers 1 +ok rung 12 not routed through the narrowing checker 0 +ok instrument-aom-oracle.sh derives the depth-correct, byte-checked rungs (base v3.13.3) +``` + +### 9.5 Who could have been misled — the naming + +**Waves merged today: nobody.** Wave 3a (`3eec02c8`: av1cmpaudit, av1leftwit, +av1lossy128x96, av1pinslive, av1txsearch) and wave 3b (`c6112723`: +av1rawhelper, av1oracleskip r1+r2+r3) — of those seven lanes: + +- `lane-av1cmpaudit` NAMES `EC_AV1_PREFILT_DUMP` once, to record that the + decode-order dump rungs "have no in-repo consumer" and that the stale-dump + hazard there is manual-only. It paired against none of them. +- `lane-av1rawhelper` names `EC_AV1_PREFILT_DUMP` twice, only as the contract + `examples/dump_yuv.rs` documents itself against. Its gate is + `assert_rawvideo_matches` — `aomdec --rawvideo` plus rung 12 — which is + depth-correct and unaffected. +- `lane-av1oracleskip` is the aomenc-**SKIP** class (`have_aomenc()` returning + empty and a gate calling that green). No dump-rung pairing. +- the other four wave-3a reports do not mention the four rungs at all. + +**No automated gate ever paired them**: `grep` over `crates/` and `tools/` finds +the four names only in doc comments and in the decoder-side definitions in +`decode.rs` — no test sets those env vars. The exposure was always a manual +ladder procedure, which is also why it survived so long. + +**Historical users, and why their conclusions stand**: the rungs were used by +earlier 8-bit lanes (av1444edge, av1444, av1444sb, av1422filter, av1422kf, +av1422kf2, av1422stripwrite, av1lrflush, av1intrapred, av1wavefront, +av1seglvl, hgkf-r2, tiny-r4, sub8-r5, mergefix-r4, sb128c-r4/r5, band63-r1, +golomb-r9, mc64-r1, inter4-r4, txselect-r2, sqchroma-r1, superres-r6). At +8 bit the old rungs were correct, and §9.2's 10/10 byte-identity against the +backed-up old binary is the direct proof that their output did not change. +The one report that both sweeps HBD cells and uses the rungs is +`av1formatsweep`; its two `EC_AV1_PREFILT_DUMP` pairing claims (lines 238, 290) +are on 8-bit 4:4:4 `testsrc2` streams, not on its 10/12-bit cells, and its +HBD cells pair through rung 12. + +**The honest limit of that sweep**: it is name-based over `lanes/*.md` plus a +targeted read of every report that mentions both a rung and an HBD marker. It +is not a line-by-line audit of every historical report. What it does establish +mechanically is the thing that matters: a 0-byte dump only ever occurred on a +10/12-bit stream, and any lane that paired on one would have seen a rung that +exited 139 — a value no report in `lanes/` quotes as a result. diff --git a/scripts/check-aom-oracle-rungs.sh b/scripts/check-aom-oracle-rungs.sh new file mode 100755 index 00000000..7cc67ac6 --- /dev/null +++ b/scripts/check-aom-oracle-rungs.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Anti-regression check for the aomdec dump rungs that +# scripts/instrument-aom-oracle.sh derives. +# +# Why this exists: the four u8-narrowing rungs (PREFILT, POSTDEBLOCK, +# PREFILT_WIDE, POSTCDEF) shipped with `fwrite(plane + r*stride, 1, w, f)`, +# which on a 10/12-bit stream reads a HALVED plane pointer +# (CONVERT_TO_BYTEPTR in aom_ports/mem.h) and SIGSEGVs with a 0-byte file +# (lanes/av1oraclehbd.report.md). A rung defect that only shows up as an +# aomdec crash during a decode is found late; this reds on the DERIVATION +# instead, in seconds, without a build. +# +# What it does: copies the oracle source tree to a scratch dir, replaces +# av1/decoder/decodeframe.c with the PRISTINE upstream file, runs the +# instrument script over the copy, and asserts the derived file's shape. The +# real oracle tree is never written to. +# +# Usage: +# scripts/check-aom-oracle-rungs.sh [SRC_DIR] [BASE_REF] +# Defaults: $AOM_ORACLE_SRC or ~/.cache/aom-oracle/src, and base ref v3.13.3 +# (override with AOM_ORACLE_BASE_REF). Exit 0 = all assertions hold. +set -euo pipefail + +SRC="${1:-${AOM_ORACLE_SRC:-$HOME/.cache/aom-oracle/src}}" +BASE="${2:-${AOM_ORACLE_BASE_REF:-v3.13.3}}" +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DERIVED="$SRC/av1/decoder/decodeframe.c" + +[ -f "$DERIVED" ] || { echo "no oracle source at $DERIVED" >&2; exit 1; } +git -C "$SRC" rev-parse --verify "$BASE^{commit}" >/dev/null 2>&1 || { + echo "base ref '$BASE' is not a commit in $SRC" >&2 + exit 1 +} + +WORK="$(mktemp -d "${TMPDIR:-$HOME/.cache/tmp}/aom-rung-check.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT +cp -a "$SRC" "$WORK/src" +git -C "$SRC" show "$BASE:av1/decoder/decodeframe.c" > "$WORK/src/av1/decoder/decodeframe.c" + +AOM_ORACLE_SRC="$WORK/src" bash "$HERE/instrument-aom-oracle.sh" > "$WORK/derive.log" 2>&1 || { + echo "FAIL: instrument-aom-oracle.sh errored on a pristine tree:" >&2 + tail -20 "$WORK/derive.log" >&2 + exit 1 +} +cp "$WORK/src/av1/decoder/decodeframe.c" "$WORK/derived.c" + +# Re-running must be a no-op, or the repair pass is not idempotent and a +# second run would rewrite a tree under someone's feet. +AOM_ORACLE_SRC="$WORK/src" bash "$HERE/instrument-aom-oracle.sh" > "$WORK/rerun.log" 2>&1 +cmp -s "$WORK/derived.c" "$WORK/src/av1/decoder/decodeframe.c" || { + echo "FAIL: a second instrument-aom-oracle.sh run changed the derived file" >&2 + exit 1 +} + +fail=0 +check() { # description, actual, expected + if [ "$2" = "$3" ]; then + printf 'ok %-58s %s\n' "$1" "$2" + else + printf 'FAIL %-58s got %s, want %s\n' "$1" "$2" "$3" >&2 + fail=1 + fi +} + +legacy=$(grep -c 'fwrite(ec_b->[yuv]_buffer + ec_r \* ec_b->' "$WORK/derived.c" || true) +check "legacy u8 row loops left in the derived file" "$legacy" "0" + +rows=$(grep -c 'ec_dump_narrow_row(ec_f, ec_b, ec_b->[yuv]_buffer' "$WORK/derived.c" || true) +check "ec_dump_narrow_row call sites (4 rungs x 3 planes)" "$rows" "12" + +fin=$(grep -c 'ec_dump_finish(ec_f, "EC_AV1_' "$WORK/derived.c" || true) +check "ec_dump_finish call sites (one per narrowing rung)" "$fin" "4" + +for rung in EC_AV1_PREFILT_DUMP EC_AV1_POSTDEBLOCK_DUMP EC_AV1_PREFILT_WIDE_DUMP \ + EC_AV1_POSTCDEF_DUMP; do + n=$(grep -c "ec_dump_finish(ec_f, \"$rung\"" "$WORK/derived.c" || true) + check "byte-count check wired into $rung" "$n" "1" +done + +# Rung 12 (EC_AV1_FINAL_DUMP) is the depth-correct one and must stay that way: +# it converts, it writes 2 bytes per sample, and it is not routed through the +# narrowing checker. +conv=$(grep -c 'CONVERT_TO_SHORTPTR(ec_p8\[ec_pl\])' "$WORK/derived.c" || true) +check "rung 12 still converts plane pointers" "$conv" "1" +r12=$(grep -c 'ec_dump_finish(ec_f, "EC_AV1_FINAL_DUMP"' "$WORK/derived.c" || true) +check "rung 12 not routed through the narrowing checker" "$r12" "0" + +if [ "$fail" -ne 0 ]; then + echo "FAIL: derived decodeframe.c violates the rung contract (base $BASE)" >&2 + exit 1 +fi +echo "ok instrument-aom-oracle.sh derives the depth-correct, byte-checked rungs (base $BASE)" diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh index fddc2b7a..c016b23b 100755 --- a/scripts/instrument-aom-oracle.sh +++ b/scripts/instrument-aom-oracle.sh @@ -902,3 +902,175 @@ s = s.replace(anchor, anchor + dump, 1) open(path, "w").write(s) print("postcdef dump instrumented") PYC + +# --- depth contract for the four u8-narrowing dump rungs ------------------ +# PREFILT (rung 1), POSTDEBLOCK (rung 3), PREFILT_WIDE (rung 7) and POSTCDEF +# are paired with ec-av1 decoder rungs that narrow every sample with `as u8`, +# so the oracle side owes ONE BYTE PER SAMPLE at every depth. As instrumented +# above they wrote `fwrite(plane + r*stride, 1, w, f)`, which is wrong twice +# over on a high-bit-depth stream: +# 1. YV12_BUFFER_CONFIG stores plane pointers in HALVED form -- aom_ports/mem.h +# defines CONVERT_TO_BYTEPTR(x) = x >> 1 -- so the real address is +# CONVERT_TO_SHORTPTR(p) (p << 1). Pointer arithmetic on the raw uint8_t* +# therefore yields an unrelated half-address, and fwrite faults inside +# memmove: SIGSEGV (exit 139) with a 0-byte file, on EVERY HBD stream, for +# all four rungs, while rung 12 (which does convert) works. A lane hitting +# it sees a crashed aomdec and cannot tell it from a decoder defect. +# 2. y_stride/uv_stride count SAMPLES, so `+ r*stride` in bytes also picks the +# wrong row even where the address happens to be readable. +# At 8 bit neither applies: buf is the real pointer and flags is 0, so the +# bytes emitted are bit-for-bit what these rungs always wrote. This block owns +# the contract for all four, runs last, and is a REPAIR pass: it rewrites the +# loops an earlier (or pre-fix) instrumentation left behind, so re-running this +# script on an already-instrumented tree fixes it in place. +python3 - "$F" <<'PYN' +import re +import sys + +path = sys.argv[1] +s = open(path).read() + +helper = '''/* EC_INSTRUMENTED_NARROW_ROW: emit one plane row as ONE BYTE PER SAMPLE, the + * shape the ec-av1 decoder's own EC_AV1_*_DUMP rungs write (they narrow every + * sample with `as u8`). + * + * Two HBD traps this replaces, both fatal until fixed: + * 1. YV12_BUFFER_CONFIG stores plane pointers in HALVED form: the real + * address is `CONVERT_TO_SHORTPTR(p)` (aom_ports/mem.h defines + * `CONVERT_TO_BYTEPTR(x) = x >> 1`), so `p + r*stride` computed on the raw + * uint8_t* is an unrelated address. `fwrite(y_buffer + r*y_stride, 1, w, + * f)` on a 10/12-bit stream therefore hands fwrite a half-address that + * faults inside memmove -- SIGSEGV with a 0-byte file, which reads as a + * decoder crash rather than a broken rung. + * 2. y_stride/uv_stride count SAMPLES, so a byte-wise `+ r*stride` addresses + * the wrong row as well. + * At 8 bit neither applies: the pointer is the real one and the bytes written + * are exactly what the rung always emitted. */ +static void ec_dump_narrow_row(FILE *f, const YV12_BUFFER_CONFIG *b, + const uint8_t *plane8, int stride, int row, + int w) { + if (!(b->flags & YV12_FLAG_HIGHBITDEPTH)) { + fwrite(plane8 + (size_t)row * stride, 1, (size_t)w, f); + return; + } + const uint16_t *p = CONVERT_TO_SHORTPTR(plane8) + (size_t)row * stride; + uint8_t *narrow = (uint8_t *)aom_malloc((size_t)w); + if (!narrow) return; + for (int c = 0; c < w; ++c) narrow[c] = (uint8_t)(p[c] & 0xFF); + fwrite(narrow, 1, (size_t)w, f); + aom_free(narrow); +} + +/* EC_INSTRUMENTED_DUMP_CHECK: the harm the depth bug above caused is not a + * wrong number, it is a SILENT 0-byte dump -- downstream that reads as "the + * oracle has no data for this stage" and becomes a phantom stage diff. So + * every narrowing rung checks the byte count it just produced against the + * shape it claims to write and aborts IN THE ORACLE, naming itself, instead + * of handing the decoder an empty file. `expect` is Y + U + V at ONE BYTE PER + * SAMPLE: the crop extent when `aligned` is 0 (PREFILT), the mi-aligned + * extent when 1 (PREFILT_WIDE / POSTDEBLOCK / POSTCDEF). No configuration + * writes 0 bytes: a frame's crop extent is non-zero by construction, and a + * failed fopen skips the block entirely (so a bad path is not an abort). */ +static void ec_dump_finish(FILE *f, const char *rung, + const YV12_BUFFER_CONFIG *b, int num_planes, + int aligned) { + const size_t y = aligned ? (size_t)b->y_width * b->y_height + : (size_t)b->y_crop_width * b->y_crop_height; + const size_t uv = aligned ? (size_t)b->uv_width * b->uv_height + : (size_t)b->uv_crop_width * b->uv_crop_height; + const size_t expect = y + (num_planes > 1 ? 2 * uv : 0); + const long wrote = ftell(f); + if (wrote < 0 || (size_t)wrote != expect || fflush(f) != 0) { + fprintf(stderr, + "EC_DUMP_ABORT rung=%s bit_depth=%u hbd=%d expect=%zu wrote=%ld " + "(one byte per sample, Y+U+V)\\n", + rung, b->bit_depth, + (b->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0, expect, wrote); + abort(); + } + fclose(f); +} + +''' + +MARKER_ROW = "EC_INSTRUMENTED_NARROW_ROW" +MARKER_CHECK = "EC_INSTRUMENTED_DUMP_CHECK" +missing = "" +if MARKER_ROW not in s: + missing = helper +elif MARKER_CHECK not in s: + # The tree already carries the row helper from an earlier run of this + # script: add the byte-count checker on its own so a repaired tree + # converges instead of erroring. + missing = helper[helper.index("/* " + MARKER_CHECK):] +if missing: + # Both helpers must precede every user: the POSTCDEF rung was refactored + # into a static helper that sits ABOVE av1_decode_tg_tiles_and_wrapup, so + # anchor there when it exists and at the function itself otherwise. + for anchor in ("static void ec_dump_postcdef(const AV1_COMMON *cm, int num_planes) {", + "void av1_decode_tg_tiles_and_wrapup(AV1Decoder *pbi, const uint8_t *data,"): + if anchor in s: + s = s.replace(anchor, missing + anchor, 1) + break + else: + raise SystemExit("dump helpers: no anchor before the dump rungs") + print("dump helpers inserted: %s" + % ("narrow-row + byte-count check" if len(missing) == len(helper) + else "byte-count check only")) + +row_loop = re.compile( + r"for \(int ec_r = 0; ec_r < ec_b->(\w+); \+\+ec_r\)\n" + r"(\s*)fwrite\(ec_b->(\w+)_buffer \+ ec_r \* ec_b->(\w+), 1,\s*\n?\s*ec_b->(\w+),\s*\n?\s*ec_f\);") + + +def narrow(match): + rows, indent, plane, stride, width = match.groups() + return ("for (int ec_r = 0; ec_r < ec_b->%s; ++ec_r)\n%s" + "ec_dump_narrow_row(ec_f, ec_b, ec_b->%s_buffer, ec_b->%s, ec_r,\n" + "%s%s ec_b->%s);" % (rows, indent, plane, stride, indent, indent, width)) + + +s, rewritten = row_loop.subn(narrow, s) +if rewritten: + print("narrow-row depth fix: rewrote %d plane row loops" % rewritten) +else: + print("narrow-row depth fix: no legacy row loop left (already depth-correct)") + +# Close each narrowing rung through the checker. Keyed on the presence of a +# rewritten row loop, so rung 12 (EC_AV1_FINAL_DUMP, 2 bytes per sample and +# already depth-correct) is never reached: its block has no ec_dump_narrow_row. +# The terminator alternation keeps each block matched to ITS OWN close, so a +# re-run cannot run a block's body forward into a later rung's fclose. +dump_block = re.compile( + r'(FILE \*ec_f = fopen\(ec_path, "wb"\);)(.*?)' + r'((?:fclose\(ec_f\);)|(?:ec_dump_finish\([^;]*\);))', + re.S) + +WIRED = [] + +def finish(match): + opened, body, closed = match.groups() + if "ec_dump_narrow_row" not in body: + return match.group(0) + # The rung name can sit ABOVE the fopen (the POSTCDEF rung was refactored + # into a helper that does getenv -> fopen at the top), so take the nearest + # preceding EC_AV1_* env lookup rather than searching the block body. + preceding = re.findall(r'getenv\("(EC_AV1_[A-Z_]+)"\)', s[:match.start()]) + if not preceding: + raise SystemExit("dump check: no rung env var above a narrowing block") + aligned = 0 if "y_crop_height" in body else 1 + if closed.startswith("fclose"): + WIRED.append(preceding[-1]) + return "%s%s%s" % ( + opened, body, + 'ec_dump_finish(ec_f, "%s", ec_b, num_planes, %d);' % (preceding[-1], aligned)) + + +s, _ = dump_block.subn(finish, s) +if WIRED: + print("dump byte-count check: wired into %d narrowing rung(s): %s" + % (len(WIRED), ", ".join(WIRED))) +else: + print("dump byte-count check: every narrowing rung already checks its bytes") +open(path, "w").write(s) +PYN