diff --git a/lanes/av1422seed.report.md b/lanes/av1422seed.report.md new file mode 100644 index 00000000..ccfa0de3 --- /dev/null +++ b/lanes/av1422seed.report.md @@ -0,0 +1,379 @@ +# lane-av1422seed — the frame-0 chroma-only 4:2:2 family: LOCALISED, not closed + +**Outcome in one line: the seed is `decode_rect4_16_intrabc`'s 4:2:0 pair geometry +applied verbatim at ss (1,0) — proved by an unwritten-sample census, not inferred — +and the write-side half of the fix is not sufficient on its own: moving the chroma +write alone regresses luma, so the entropy-side half of the same arm must move with +it. This branch therefore lands NO decoder change.** + +Tip: `main` = `affe70dc`. Worktree `/home/user/.cache/wt/av1422seed`, branch +`lane/av1422seed`. `crates/ec-av1/src/decode.rs` and `src/stream.rs` are at +`main`'s content — the `if false &&` 4:2:2 bypass used for probing is **not** +committed and the sequence-header refusal is intact. + +--- + +## 0. What is delivered + +1. §2 — the ffmpeg comparator, its decode→display mapping rule, and the control + cells it reports byte-exact. +2. §3 — all five slice cells reproduced against ffmpeg, with the first divergence + and the per-frame counts. +3. §4 — the localisation: the exact arm, the exact constants, and a census that + names the unwritten samples. +4. §5 — the attempted fix, why it is **not** landed, and what the remaining half is. +5. §6 — what is NOT measured (stated, not hidden). + +--- + +## 1. The instrument, and what it does NOT inherit from the census + +`scripts/cmp422-ffmpeg.py` + `scripts/run422-ffmpeg.py` (committed). The census's +`cmp422.py` compares against the **instrumented aomdec**; this lane's brief makes +**ffmpeg 8.1.3** the pixel oracle, so the comparator is new and its disciplines are +stated here rather than inherited. + +1. **Geometry is an explicit argument read from the SEQUENCE HEADER.** `ffprobe + -show_entries stream=coded_width,coded_height,pix_fmt` on the `.obu`; the + chroma tag and depth come from `pix_fmt` (`yuv422p`, `yuv422p10le`, …), and the + comparator refuses a `pix_fmt` that disagrees with the ss/depth it derived + (`cmp422-ffmpeg.py:24`). A raw frame whose length is not a whole multiple of + the geometry's frame size is a hard error (`split`, `:80`). **Never** a file + size, and never the u8-narrowing dump for a 10-bit cell. +2. **Plane attribution is per frame**, from that frame's own plane lengths + (`sizes = (w*h, cw*ch, cw*ch)`, `cw = ceil(w/2^ss_x)`, `ch = ceil(h/2^ss_y)`), + with a monotone cursor inside the frame (`compare`, `:145`). +3. **A wrong SAMPLE is one `bps`-wide unit.** At 10 bit the comparator walks + 16-bit LE samples, so a `0x0C00`-vs-`0x0BFF` defect cannot hide behind a byte + compare. +4. **A count over zero frames is a hard error** (`:120`, `:140`): an empty dump + set raises rather than reporting a vacuous `0/0/0`. +5. **Decode-order → display-order is derived, not assumed.** Ours is + `EC_AV1_FINAL_DUMP` (decode order, hidden alt-refs included); ffmpeg's + `-f rawvideo` is **display order and has no hidden frames** — 16 shown frames + against our 17. `map_decode_to_display` (`:80`) identifies each decode frame by + its **luma plane** and enumerates *every* assignment that covers the display + side; if the assignments disagree on the counts it raises rather than picking + one. This is load-bearing: a real altref stream **reorders display against + decode** (measured on all five control cells: decode f1 is the hidden picture + and decode f2..f8 map to display 7, 3, 1, 2, 5, 4, 6), so the tempting + "decode order = display order" prior is wrong and a monotonicity prior is + wrong too — both are rejected in the code with the measurement that rejects + them. + +### 1.1 Comparator controls + +Five control cells, same pipeline, same binary, **before any change**: + +| cell | geometry | decode / shown | hidden | verdict | Y/U/V | +|---|---|---|---|---|---| +| `s420_320x240` | 320x240 ss 1,1 d8 | 17 / 16 | `[1]` | BYTE-EXACT | 0/0/0 | +| `s420_320x246` | 320x246 ss 1,1 d8 | 17 / 16 | `[16]` (2 assignments, counts agree) | BYTE-EXACT | 0/0/0 | +| `s420_352x242_10b` | 352x242 ss 1,1 d10 | 17 / 16 | `[16]` (2 assignments) | BYTE-EXACT | 0/0/0 | +| `s444_320x240` | 320x240 ss 0,0 d8 | 17 / 16 | `[1]` | BYTE-EXACT | 0/0/0 | +| `s444_320x242_10b` | 320x242 ss 0,0 d10 | 17 / 16 | `[1]` | BYTE-EXACT | 0/0/0 | + +Two of them are the 10-bit class and two are the **2-solution** mapping class, so +the mapping rule is exercised, not assumed. The 4:2:2 cells are re-measured +against the same pipeline in §3, where a non-zero baseline is reported — the +instrument is shown reading a plane that is already wrong by thousands. + +**NOT DONE — the flip control.** The intended next control (flip one ffmpeg sample +per plane and require exactly `+1` in that plane, `0` everywhere else, on a +non-zero baseline) is scripted as `flipctl.py` in the census scratch but was **not +executed**; §6 repeats this. What stands in its place is weaker and is named as +such: the instrument reports per-plane counts that move by thousands on the +diverging cells while the two formats it must not touch (4:2:0, 4:4:4) read +`0/0/0` on five cells, and the unwritten-sample census of §4 is a completely +independent witness to the same region. + +--- + +## 2. The five slice cells, reproduced + +`/home/user/.cache/census422b/sweep/.obu`, ffmpeg 8.1.3, our side +`EC_AV1_FINAL_DUMP`. Counts are wrong **samples**, summed over the 16 **shown** +frames (the hidden picture is not in ffmpeg's output and is reported separately). + +| cell | geometry | depth | decode / shown | hidden | pre Y/U/V | first divergence | +|---|---|---|---|---|---|---| +| `s422_322x240` | 322x240 | 8 | 17 / 16 | `[1]` | 0 / **22003** / **21625** | disp f0 (decode f0) **U (r62, c149)** ours 160 ffmpeg 166 | +| `s422_320x246` | 320x246 | 8 | 17 / 16 | `[1]` | 0 / **7810** / **5531** | disp f0 (decode f0) **U (r62, c144)** ours 161 ffmpeg 166 | +| `s422_322x246` | 322x246 | 8 | 17 / 16 | `[1]` | 0 / **3437** / **2222** | disp f0 (decode f0) **U (r62, c144)** ours 169 ffmpeg 166 | +| `s422_352x242_10b` | 352x242 | 10 | 17 / 16 | `[1]` | 0 / **4653** / **3777** | disp f0 (decode f0) **U (r62, c160)** ours 667 ffmpeg 664 | +| `s422_416x242_10b` | 416x242 | 10 | 17 / 16 | `[1]` | 0 / **5740** / **4348** | disp f0 (decode f0) **U (r62, c192)** ours 640 ffmpeg 664 | + +All five: **chroma only, luma exact on every shown frame**, first divergence in +decode frame 0, wrong region reaching every frame. + +**Answer to the brief's question 4 — do the 10-bit members fail for the same +reason?** *Mechanically yes, numerically no.* All five first-diverge in decode +frame 0, plane U, and in every case the first wrong **row is 62**; the first wrong +**column** is `chroma_width - 16` in chroma-sample units for four of the five +(320→144, 322x246→144 of 161, 352→160 of 176, 416→192 of 208) and +`chroma_width - 12` for `s422_322x240` (149 of 161, the first *scanning* column of +that row, not the region's left edge). The seed block is the **same shape and the +same relative position** in all five (8.4 §4.2), and the per-frame counts differ +only because the 10-bit cells are wider. So: one defect, five geometries — not a +depth-specific one. (This is also the census's own conclusion, reached +independently: "bit depth does not separate them".) + +Counts are lower than the census's `0/8339/5903`-style figures by exactly the +hidden picture's contribution (e.g. `s422_320x246`: 8339 − 7810 = 529 U, +5903 − 5531 = 372 V), which is the expected difference between a 17-decode-frame +and a 16-shown-frame basis and confirms both measurements agree. + +--- + +## 3. The seed: an unwritten-sample census, not a diff pattern + +A wrong-sample diff says *where the output is wrong*; it cannot say *whether the +block was written at all*. The crate already carries the instrument for that +question: `fresh_plane` (`decode.rs:21123`) leaves the plane backing store +**uninitialised** and fills it with `PLANE_SENTINEL = 0xDEAD` under +`EC_AV1_PLANE_SENTINEL=1`. Every sample reconstruction writes is overwritten; +every sample it does not write still reads `0xDEAD`. A scan of the three planes at +the frame's pre-deblock point is then an exact census of unwritten samples. + +Run on `s422_320x246.obu`, **decode frame 0**: + +``` +SEEDUNWRITTEN plane=0 320x256 runs=0 +SEEDUNWRITTEN plane=1 160x256 runs=4 + plane=1 row=128 cols=144..151 + plane=1 row=129 cols=144..151 + plane=1 row=130 cols=144..151 + plane=1 row=131 cols=144..151 +SEEDUNWRITTEN plane=2 160x256 runs=4 + plane=2 row=128 cols=144..151 + plane=2 row=129 cols=144..151 + plane=2 row=130 cols=144..151 + plane=2 row=131 cols=144..151 +``` + +**Luma: nothing unwritten. U and V: one 4×8 block each, chroma rows 128..131, +cols 144..151, and nothing else in the frame.** So the 16×16 luma region at luma +(288, 128) is fully reconstructed while its chroma half — 8×4 per plane — is +**never written at all**. (The census scan is a temporary local edit and is not +committed; it is four lines at the `dump_stage16` call in `decode_frame`.) + +A lowest-level write trace (the three `PlaneBuf` sinks — `reconstruct`, +`reconstruct_rect`, `reconstruct_mc_rect` — are the only writers of a plane in this +tree) then names the block, and frame 0 contains exactly **three** MC writes: + +``` +SEEDWR3 reconstruct_mc_rect x=288 y=128 plane=0 w=16 h=4 +SEEDWR3 reconstruct_mc_rect x=144 y=62 plane=1 w=8 h=4 +SEEDWR3 reconstruct_mc_rect x=144 y=62 plane=2 w=8 h=4 +``` + +One 16×4 **luma** write at (288, 128) — the strip's own footprint, and it is +exact — and one 8×4 **chroma** write per plane, at **(144, 62)** instead of +(144, 128). The 8×4 shape is right; the **row is 66 too high**, and the strip's +own chroma is the block the census found unwritten. That is the whole defect: +one write, landing in the wrong row. + +### 3.1 The owning arm + +`decode.rs:18162 fn decode_rect4_16_intrabc` — reconstruction of one **intrabc +16×4 / 4×16 strip** (a 1:4 partition strip; `is_inter_block` counts intrabc, so +its luma is a frame copy through the MC path, which is why the luma write is an +MC write and not `reconstruct_rect`). + +The function's own doc comment states the 4:2:0 pair rule: *"A 1:4 strip is a +PAIR. Both children share one chroma block, and only the odd-mi member codes it +(`is_chroma_reference`, `av1_common_int.h:1454`) … `setup_pred_plane`'s +`mi_row -= 1` when the block is one mi tall on an odd row."* That rule is applied +at every `ss` except 4:4:4, which got its own `own444` arm (lane-av1444rect r2). +**4:2:2 is the second `ss` where the rule does not hold, and it was never given +an arm.** The three constants that carry it, at `main`: + +| site | `main` | what 4:2:2 needs | value on the seed strip (`lmi = (32, 72)`, HORZ) | +|---|---|---|---| +| `decode.rs:18244` `cw, ch` | `(pw/2, ph/2)` = `(8, 4)` | `ss_size_lookup[BLOCK_16X4][1][0]` | `(8, 4)` — **accidentally already right** | +| `decode.rs:18246` `pair_mi` | `(lmi.0 - 1, lmi.1)` = `(31, 72)` | no pair: `lmi` | `(32, 72)` | +| `decode.rs:18256` `cpx, cpy` | `(pair_mi.1*MI/2, pair_mi.0*MI/2)` = `(144, 62)` | `(px>>ss_x, py>>ss_y)` | **`(144, 128)`** | + +and the two chroma coefficient-context gathers that must move **with** them, +`decode.rs:18574` and `decode.rs:18635`: + +```rust +let around = neighbours.around_mi_rect(pair_mi, pw, ph); +``` + +The libaom clause that decides it, `av1_common_int.h:1454`'s `is_chroma_reference`, +ends in + +```c + ... || (g->subsampling_x == 1 && g->subsampling_y == 0) || (mi_col & 1) || (mi_row & 1); +``` + +so at ss (1, 0) it answers **true for every block**: no pair, every strip codes +its own chroma, at its own origin, with its context gathered over its own extent +(and through `around_mi_422_chroma`, the every-second-column 4:2:2 gather every +other 4:2:2 chroma context read in this tree already uses). + +**The census's `first divergence U(62,144)` is this write.** The block at chroma +(144, 62) is the block the census's first-divergence coordinates name; the block +at (144, 128) is the one the census's "shrunk region, origin unmoved" table could +not see, because nothing was ever written there. + +### 3.2 The same shape in all five cells + +The unwritten census was run on `s422_320x246` only; the *diff* geometry is +reported for the other four by `scripts/shape422-diff.py`. In every cell the +frame-0 wrong region is a single 8-wide chroma column band, **16 chroma columns +from the right edge** (320→144 of 160, 322→144 of 161, 352→160 of 176, 416→192 of +208) at chroma rows 62..65 and 128..131 — the two rows of §3 and of §4.1. Same +strip family, same two-row-pair displacement, five geometries. + +--- + +## 4. The attempted fix, and why it is not landed + +The write-side half of the fix, applied and measured (this is the change that is +**not** in the tree): + +```rust +let own422 = ss_x(fctx) == 1 && ss_y(fctx) == 0 && horz; +if own422 && has_chroma { hit!(INTRABC_RECT4_OWN_CHROMA422_HITS); } +let (cw, ch) = if own444 || own422 { (bw >> ss_x(fctx), bh >> ss_y(fctx)) } else { (pw/2, ph/2) }; +let pair_mi = if has_chroma { if own444 || own422 { lmi } else if horz { (lmi.0-1, lmi.1) } else { (lmi.0, lmi.1-1) } } else { lmi }; +let (cpx, cpy) = if has_chroma { if own444 || own422 { (px >> ss_x(fctx), py >> ss_y(fctx)) } else { (pair_mi.1*MI/2, pair_mi.0*MI/2) } } else { (0, 0) }; +``` + +plus a new gate counter `INTRABC_RECT4_OWN_CHROMA422_HITS` / +`intrabc_rect4_own_chroma422_hits()` (the ss (1,0) twin of the existing +`INTRABC_RECT4_OWN_CHROMA444_HITS`). + +VERT_4 is deliberately **not** claimed: `ss_size_lookup[BLOCK_4X16][1][0]` is +`BLOCK_INVALID` at ss (1,0), so only the pair shape is codable for a 4×16 strip — +the same statement `decode_block_rect4` already carries. + +**Measured result: it regresses luma.** + +| build | `s422_320x246` frame-0 luma wrong samples | five cells | +|---|---|---| +| `main` (`affe70dc`) | **0** | 0/7810/5531, 0/22003/21625, 0/3437/2222, 0/4653/3777, 0/5740/4348 (chroma only) | +| + write-side fix, gathers untouched | **5958** | all five fail luma identity | +| + write-side fix + `around_mi_rect(pair_mi, pw, ph)` → `(gmi, gw, gh)` = `(lmi, bw, bh)` and routed through `around_mi_422_chroma` | **5958** | all five still fail luma identity | + +The control is exact and cheap: `git stash push crates/ec-av1/src/decode.rs`, +rebuild, re-run → the `main` numbers above reproduce to the sample +(0/7810/5531 etc.), so the pipeline is not drifting and the regression is the +change's. The decode is deterministic (two runs of the same binary, frames 0..3, +`SAME` sha256 on all four), so this is not a flake. + +**Reading.** The write-side constants and the entropy-side gather are the *same* +misapplication, and moving the write alone turns a reconstruction defect into an +**entropy desync** that corrupts luma for the rest of the frame — the classic +`reconstruction-only vs parse` split. My second attempt moved the gather too, by +the same `own422` predicate, and did not restore luma, which says the remaining +half is **not** in `around_mi_rect`'s extent alone. The untested candidates, in +order: + +1. **`has_chroma` itself.** The caller decides whether a strip codes chroma by + mi parity. At ss (1,0) *every* strip does (`is_chroma_reference`'s clause), so + an even-row HORZ strip that our tree currently passes `has_chroma = false` must + become `true` — which adds a chroma coefficient read and changes the parse. If + the caller already passes `true` for all HORZ strips at 4:2:2, this is not it. +2. **`rect_inter_chroma_set(cw, ch)`** and the `TxbSet` chosen for an 8×4 chroma + unit at ss (1,0) — the entropy class, not the extent. +3. The **coefficient context row/offset** for a chroma unit whose plane block is + 8×4 at ss (1,0) (`around_mi_422_chroma`'s every-second-column sampling plus the + offset-7/offset-10 rows). + +Agent07-4 (`lane-av1422luma`, cell `s422_416x250_10b`) independently localised a +**luma** desync in this same function, to the same `own444` pair-geometry block +and the `around_mi_rect(pair_mi, pw, ph)` gather. Two lanes converging on one +function is the strongest signal in this report: **the 4:2:2 arm of +`decode_rect4_16_intrabc` does not exist and has to be written whole** — origin, +extent, `has_chroma`, entropy set and context gather together — not patched in +pieces. Ownership was split by message: Agent07-4 takes the entropy side, this +lane's write-side hunk is described above and is not landed. + +--- + +## 5. Per-plane, per-frame numbers + +Pre-fix (this lane's instrument, ffmpeg oracle, 16 shown frames): + +| cell | Y | U | V | +|---|---|---|---| +| `s422_322x240` | 0 | 22003 | 21625 | +| `s422_320x246` | 0 | 7810 | 5531 | +| `s422_322x246` | 0 | 3437 | 2222 | +| `s422_352x242_10b` | 0 | 4653 | 3777 | +| `s422_416x242_10b` | 0 | 5740 | 4348 | + +Per-frame U counts, `s422_320x246` (display order, 16 frames): +`58 269 308 371 410 348 580 608 620 634 621 655 640 575 584 529` — wrong in +**every** frame, growing with the altref's reference use, which is what a +frame-0 seed that later frames predict from looks like. + +Post-fix: **none** — the change is not landed. + +**4:2:0 and 4:4:4 controls after the change attempt:** unchanged, `0/0/0` on all +five control cells (§1.1 re-run with the change in the tree: 5/5 BYTE-EXACT). The +attempt is 4:2:2-specific in blast radius — it breaks 4:2:2 luma and touches +nothing else. + +--- + +## 6. Family sweep (the class, repo-wide in this corpus) + +All 18 `s422_*` sweep cells, same instrument, with the change **not** applied +(`main`), which is the honest baseline for whoever takes the arm next: + +| verdict | cells | +|---|---| +| BYTE-EXACT | 12 — `320x240`, `320x242`, `320x242_10b`, `320x250_10b`, `322x242`, `326x240`, `326x242`, `326x246`, `352x250_10b`, `384x242`, `384x246` (+ the 5 targets' siblings) | +| DIVERGES, chroma only | `s422_384x240` — **0 / 1780 / 1871**; first bad frame 1 per the census, i.e. a **different, later** seed | +| instrument error (luma identity does not cover the display side) | `s422_320x246`, `s422_322x240`, `s422_322x246`, `s422_352x242_10b`, `s422_416x242_10b`, `s422_416x250_10b` — the five slice cells plus `416x250_10b`, measured **with the change in the tree**; each is a luma-corrupting desync, not a count | + +Run against `main` instead, the five slice cells read the §2 numbers and +`s422_416x250_10b` reads the census's luma-wrong row. The sweep is here so the +next lane does not have to re-derive it: **`s422_384x240` is not this defect** +(its first bad frame is 1, and its region is not the 16-columns-from-the-right +band), so closing this arm should leave exactly one 4:2:2 cell diverging in the +sweep. + +## 7. What is NOT measured + +* **The flip control was not run.** §1.1's controls are the five byte-exact cells, + not the sample-flip arms. Nothing here should be read as "the comparator was + proven to bite by a flip". +* **No permanent gate was added.** The brief asked for a gate in the crate's test + binary naming a cell; with the fix unlanded a gate would have to assert a + *failure*, and a gate that asserts a known defect is not a gate. The + `INTRABC_RECT4_OWN_CHROMA422_HITS` counter is the hook such a gate will need; + the non-vacuity argument for it will be "this cell moves 5958 luma samples when + the arm is wrong", not a count. +* **`s422_384x240` and the 4:4:4 `s444_352x242_10b` residual are untouched** and + are not this arm. +* The 4:2:2 sequence-header refusal is **untouched** — `stream.rs:1803` reads + `if seq.subsampling_x != seq.subsampling_y` on this branch, verified by + `git status` clean for that file. +* `s422_416x250_10b`'s luma desync is Agent07-4's slice; this report only records + that it is in the same function. + +## 8. Reproducing this lane's numbers + +```sh +# 1. the bypass (LOCAL ONLY, never commit) +# crates/ec-av1/src/stream.rs:1803 -> if false && seq.subsampling_x != seq.subsampling_y { +CARGO_TARGET_DIR=/tmp/tgt cargo build -p ec-av1 --example decode_probe --features gate-counters + +# 2. the five cells + the five controls, against ffmpeg 8.1.3 +python3 scripts/run422-ffmpeg.py + +# 3. the frame-0 unwritten-sample census (temporary four-line scan, see §3) +EC_AV1_PLANE_SENTINEL=1 sweep/s422_320x246.obu + +# 4. the wrong-region geometry, per cell +python3 scripts/shape422-diff.py s422_320x246 sweep/s422_320x246.obu +``` + +`cells.json` entries are `{"name": ..., "path": ...}`. The comparator derives +geometry from the sequence header itself and needs no other argument; it raises +rather than reporting a count it cannot justify. diff --git a/scripts/cmp422-ffmpeg.py b/scripts/cmp422-ffmpeg.py new file mode 100755 index 00000000..fb522806 --- /dev/null +++ b/scripts/cmp422-ffmpeg.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""ffmpeg pixel-oracle comparator for ec-av1 4:2:2 (and 4:2:0 / 4:4:4 controls). + +Discipline (oracle-comparator-liveness-control): + +1. Geometry is an EXPLICIT argument read from the SEQUENCE HEADER via ffprobe + (coded_width / coded_height / pix_fmt of the AV1 stream), never derived + from a file size. A raw frame whose byte length disagrees with the geometry + is a hard error. +2. Plane attribution is per FRAME, from that frame's own plane lengths, with a + monotone cursor -- never absolute thresholds from frame 0. +3. A wrong SAMPLE is one bps-wide unit. At 10 bit the comparator walks + 16-bit LE samples, so the top bits cannot hide. +4. A count over zero frames is a hard error (vacuous 0/0/0). +5. Decode-order (ours, EC_AV1_FINAL_DUMP) -> display-order (ffmpeg rawvideo) + mapping is derived by LUMA-IDENTITY content match under a strictly + increasing assignment, then re-verified per frame. Exactly one decode frame + must have no display partner: the hidden alt-ref picture. +""" +import json +import os +import re +import subprocess +import sys + +SS = {"420": (1, 1), "422": (1, 0), "444": (0, 0), "440": (0, 1)} +DEPTH_RE = re.compile(r"^yuv(\d{3})p(\d*)(?:le)?$") + + +def probe_geometry(obu): + """ffprobe reads the AV1 SEQUENCE HEADER: coded_width/coded_height and the + chroma format/depth it implies. Never the raw output's byte length.""" + r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v", + "-show_entries", "stream=coded_width,coded_height,pix_fmt", + "-of", "csv=p=0", obu], capture_output=True, check=True) + parts = r.stdout.decode().strip().split(",") + mw, h, pix = parts[0], parts[1], parts[2] + m = DEPTH_RE.match(pix) + if not m: + raise SystemExit(f"{obu}: unsupported pix_fmt {pix!r} (need a planar yuv*p[le])") + ss = SS.get(m.group(1)) + if ss is None: + raise SystemExit(f"{obu}: unknown chroma tag C{m.group(1)} in pix_fmt {pix!r}") + depth = int(m.group(2)) if m.group(2) else 8 + return int(mw), int(h), ss[0], ss[1], depth, pix + + +def plane_spans(w, h, ss_x, ss_y, bps): + cw = -(-w // (1 << ss_x)) + ch = -(-h // (1 << ss_y)) + sizes = (w * h, cw * ch, cw * ch) + return sizes, sum(sizes) * bps + + +def frame_files(prefix): + out, i = [], 0 + while os.path.isfile(f"{prefix}.f{i}"): + out.append(f"{prefix}.f{i}") + i += 1 + return out + + +def ffmpeg_frames(obu, pix): + r = subprocess.run(["ffmpeg", "-v", "error", "-i", obu, "-f", "rawvideo", + "-pix_fmt", pix, "-"], capture_output=True) + if r.returncode != 0: + raise SystemExit(f"{obu}: ffmpeg refused: {r.stderr.decode()[-300:]}") + return r.stdout + + +def split(raw, sizes, fsz, cell): + if not raw: + raise SystemExit(f"{cell}: ffmpeg produced ZERO bytes -- a 0/0/0 here is vacuous") + if len(raw) % fsz: + raise SystemExit(f"{cell}: ffmpeg rawvideo is {len(raw)} B, not a whole " + f"multiple of the {fsz} B frame the geometry implies") + return [raw[i * fsz:(i + 1) * fsz] for i in range(len(raw) // fsz)] + + +def _matchings(cands, disp_n, cap=64): + """Every way to assign each decode frame either a distinct display partner + or the hidden role, covering the display side exactly. Enumerated, not + guessed: a duplicated picture can make the assignment genuinely ambiguous, + and the caller then has to show the ambiguity does not change the answer.""" + sols = [] + + def dfs(i, used, acc, hid): + if len(sols) >= cap: + return + if i == len(cands): + if len(used) == disp_n: + sols.append((dict(acc), list(hid))) + return + for di in cands[i]: + if di not in used: + used.add(di) + acc[i] = di + dfs(i + 1, used, acc, hid) + del acc[i] + used.discard(di) + hid.append(i) + dfs(i + 1, used, acc, hid) + hid.pop() + + dfs(0, set(), {}, []) + return sols + + +def map_decode_to_display(ours, disp, sizes, bps, cell): + """Identity of each decode-order frame is carried by its LUMA plane; full-frame + identity is preferred when it exists. Every assignment that covers the + display side is enumerated, so a duplicated picture shows up as an + explicit solution COUNT rather than a silent pick. Real altref streams + REORDER display against decode (measured: decode f2..f8 -> display + 7,3,1,2,5,4,6), so no monotonicity prior is applied -- an unjustified one + is exactly the class of silent mismatch this instrument exists to catch.""" + luma = sizes[0] * bps + for use_full in (True, False): + cands = [[di for di, d in enumerate(disp) + if o[:luma] == d[:luma] and (o == d or not use_full)] for o in ours] + sols = _matchings(cands, len(disp)) + if sols: + if min(len(h) for _, h in sols) > 4: + raise SystemExit(f"{cell}: {min(len(h) for _, h in sols)} decode frames have " + f"no luma-identical display partner -- LUMA itself " + f"diverges, so this is not a hidden-alt-ref count " + f"(class av1-frame-count-vs-pixel-divergence)") + return sols + raise SystemExit(f"{cell}: luma identity never covers the display side " + f"({len(ours)} decode frames, {len(disp)} display frames) " + f"-- the frame-count or per-frame identity claim is wrong") + + + +def compare(cell, ours_prefix, disp, w, h, ss_x, ss_y, depth, want_hidden=None): + bps = 1 if depth <= 8 else 2 + sizes, fsz = plane_spans(w, h, ss_x, ss_y, bps) + ours = [open(p, "rb").read() for p in frame_files(ours_prefix)] + if not ours: + raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames from us -- vacuous 0/0/0") + for i, o in enumerate(ours): + if len(o) != fsz: + raise SystemExit(f"{cell}: our decode frame {i} is {len(o)} B, geometry " + f"{w}x{h} ss={ss_x}{ss_y} depth={depth} implies {fsz} B") + sols = map_decode_to_display(ours, disp, sizes, bps, cell) + + def measure(mapping, hidden): + tot = [0, 0, 0] + per_disp = [[0, 0, 0] for _ in disp] + per_dec, first = [], None + bb_all = [[None, None, None, None] for _ in range(3)] + for oi, a in enumerate(ours): + if oi in hidden: + per_dec.append(None) + continue + b = disp[mapping[oi]] + fcount, off = [0, 0, 0], 0 + for pi, sz in enumerate(sizes): + pw = w if pi == 0 else -(-w // (1 << ss_x)) + for i in range(sz): + s = i * bps + if a[off + s:off + s + bps] != b[off + s:off + s + bps]: + fcount[pi] += 1 + tot[pi] += 1 + per_disp[mapping[oi]][pi] += 1 + r, c = divmod(i, pw) + bb = bb_all[pi] + if bb[0] is None or r < bb[0]: + bb[0] = r + if bb[1] is None or r > bb[1]: + bb[1] = r + if bb[2] is None or c < bb[2]: + bb[2] = c + if bb[3] is None or c > bb[3]: + bb[3] = c + if first is None: + first = (mapping[oi], oi, "YUV"[pi], r, c, + int.from_bytes(a[off + s:off + s + bps], "little"), + int.from_bytes(b[off + s:off + s + bps], "little")) + off += sz * bps + per_dec.append(fcount) + return tot, per_disp, per_dec, first, bb_all + + measured = [measure(m, h) for m, h in sols] + totals = {tuple(t[0]) for t in measured} + if len(totals) > 1: + raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS " + f"({len(sols)} solutions) and they DISAGREE on the counts " + f"{sorted(totals)} -- pick the identity source explicitly, " + f"this instrument will not choose for you") + tot, per_disp, per_dec, first, bbox = measured[0] + mapping, hidden = sols[0] + if want_hidden is not None and len(hidden) != want_hidden: + raise SystemExit(f"{cell}: {len(hidden)} hidden decode frame(s) {hidden}, " + f"expected {want_hidden} -- the frame-count claim changed") + return {"cell": cell, "status": "BYTE-EXACT" if tot == [0, 0, 0] else "DIVERGES", + "w": w, "h": h, "ss": f"{ss_x}{ss_y}", "depth": depth, "pix": pix_of(ss_x, ss_y, depth), + "decode_frames": len(ours), "display_frames": len(disp), + "hidden_decode": hidden, "mapping_solutions": len(sols), + "Y": tot[0], "U": tot[1], "V": tot[2], + "first": first, "bbox": bbox, + "per_decode_frame": per_dec, "per_display_frame": per_disp} + + +def pix_of(ss_x, ss_y, depth): + tag = next(k for k, v in SS.items() if v == (ss_x, ss_y)) + return f"yuv{tag}p" + ("" if depth <= 8 else f"{depth}le") + + +def flip(disp, sizes, bps, disp_index, plane, sample_index): + """Flip bit 0 of one oracle SAMPLE's low byte: exactly +1 wrong sample in + both depths (2**bitdepth < 2**16, so nothing carries out of the container). + Returns a new list; the caller drops it to restore.""" + new = list(disp) + buf = bytearray(new[disp_index]) + buf[sum(sizes[:plane]) * bps + sample_index * bps] ^= 1 + new[disp_index] = bytes(buf) + return new + + +def run(cell, obu, ours_prefix, want_hidden=None, json_out=False): + w, h, ssx, ssy, depth, pix = probe_geometry(obu) + bps = 1 if depth <= 8 else 2 + sizes, fsz = plane_spans(w, h, ssx, ssy, bps) + disp = split(ffmpeg_frames(obu, pix), sizes, fsz, cell) + res = compare(cell, ours_prefix, disp, w, h, ssx, ssy, depth, want_hidden) + if json_out: + print(json.dumps(res)) + else: + f = res["first"] + fs = "none" if f is None else \ + f"disp f{f[0]} (decode f{f[1]}) {f[2]} (r{f[3]},c{f[4]}) ours={f[5]} ffmpeg={f[6]}" + print(f"{cell}: {res['status']} {res['decode_frames']}df/" + f"{res['display_frames']}shown hidden={res['hidden_decode']} " + f"Y={res['Y']} U={res['U']} V={res['V']} first: {fs}") + return res, disp, sizes, fsz, bps + + +if __name__ == "__main__": + cell, obu, prefix = sys.argv[1:4] + wh = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4].isdigit() else None + run(cell, obu, prefix, wh, "--json" in sys.argv) diff --git a/scripts/run422-ffmpeg.py b/scripts/run422-ffmpeg.py new file mode 100755 index 00000000..f637668c --- /dev/null +++ b/scripts/run422-ffmpeg.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Driver: decode a cell with our decode_probe (EC_AV1_FINAL_DUMP) and compare +against ffmpeg, per plane, per frame. Geometry from the sequence header.""" +import json +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import cmpff # noqa: E402 + +PROBE = "/home/user/.cache/tgt/av1422seed/debug/examples/decode_probe" +WORK = "/home/user/.cache/seed422" + + +def decode_ours(name, path, extra_env=None): + d = os.path.join(WORK, name) + os.makedirs(d, exist_ok=True) + for f in os.listdir(d): + os.remove(os.path.join(d, f)) + prefix = os.path.join(d, "ours") + env = dict(os.environ, EC_AV1_FINAL_DUMP=prefix) + env.update(extra_env or {}) + r = subprocess.run([PROBE, path], stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, timeout=3600, env=env) + out = r.stdout.decode("utf-8", "replace") + if "REFUSED:" in out: + return None, out.split("REFUSED:", 1)[1].strip().splitlines()[0] + return prefix, out + + +def one(name, path, want_hidden=None, keep=True): + prefix, out = decode_ours(name, path) + if prefix is None: + print(f"{name}: REFUSES: {out}") + return {"cell": name, "status": "REFUSES", "msg": out} + res, *_ = cmpff.run(name, path, prefix, want_hidden, json_out=False) + res["probe"] = out.strip().splitlines()[-1] if out.strip() else "" + return res + + +if __name__ == "__main__": + cells = json.load(open(sys.argv[1])) + out = [] + for c in cells: + try: + res = one(c["name"], c["path"], c.get("hidden")) + except SystemExit as e: + res = {"cell": c["name"], "status": "COMPARATOR-ERROR", "msg": str(e)} + print(json.dumps({k: v for k, v in res.items() + if k not in ("per_decode_frame", "per_display_frame", "bbox")}), + flush=True) + out.append(res) + json.dump(out, open(sys.argv[2], "w"), indent=1) diff --git a/scripts/shape422-diff.py b/scripts/shape422-diff.py new file mode 100644 index 00000000..ad98dc86 --- /dev/null +++ b/scripts/shape422-diff.py @@ -0,0 +1,28 @@ +import sys +import cmpff +def shape(cell, obu, frame_d=0, frame_s=0, planes=(1,2)): + w,h,ssx,ssy,depth,pix=cmpff.probe_geometry(obu) + bps=1 if depth<=8 else 2 + sizes,fsz=cmpff.plane_spans(w,h,ssx,ssy,bps) + disp=cmpff.split(cmpff.ffmpeg_frames(obu,pix),sizes,fsz,cell) + a=open(f"/home/user/.cache/seed422/{cell}/ours.f{frame_d}",'rb').read() + b=disp[frame_s] + cw=-(-w>>ssx); ch=-(-h>>ssy) + print(f"== {cell} {w}x{h} d{depth} chroma {cw}x{ch} decode f{frame_d} vs display f{frame_s}") + for pi in planes: + name="YUV"[pi] + off=sum(sizes[:pi])*bps + blocks={} + for r in range(ch): + base=off+(r*cw)*bps + for c in range(cw): + if a[base+c*bps:base+(c+1)*bps]!=b[base+c*bps:base+(c+1)*bps]: + blocks.setdefault((r//8,c//8),[]).append((r%8,c%8)) + print(f" {name}: {len(blocks)} 8x8 blocks wrong") + for k in sorted(blocks): + v=blocks[k] + rows=sorted({p[0] for p in v}); cols=sorted({p[1] for p in v}) + print(f" blk(r{k[0]},c{k[1]}) abs rows {k[0]*8}..{k[0]*8+7} cols {k[1]*8}..{k[1]*8+7}" + f": {len(v)}/64 wrong, subrows {rows[0]}..{rows[-1]} subcols {cols[0]}..{cols[-1]}") +if __name__=="__main__": + shape(sys.argv[1], sys.argv[2], int(sys.argv[3]) if len(sys.argv)>3 else 0)