forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1feddfcTahinli2 months ago3786 commits

cmp422-ffmpeg.py242 lines, 10.5 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""ffmpeg pixel-oracle comparator for ec-av1 4:2:2 (and 4:2:0 / 4:4:4 controls).
3
4Discipline (oracle-comparator-liveness-control):
5
61. Geometry is an EXPLICIT argument read from the SEQUENCE HEADER via ffprobe
7 (coded_width / coded_height / pix_fmt of the AV1 stream), never derived
8 from a file size. A raw frame whose byte length disagrees with the geometry
9 is a hard error.
102. Plane attribution is per FRAME, from that frame's own plane lengths, with a
11 monotone cursor -- never absolute thresholds from frame 0.
123. A wrong SAMPLE is one bps-wide unit. At 10 bit the comparator walks
13 16-bit LE samples, so the top bits cannot hide.
144. A count over zero frames is a hard error (vacuous 0/0/0).
155. Decode-order (ours, EC_AV1_FINAL_DUMP) -> display-order (ffmpeg rawvideo)
16 mapping is derived by LUMA-IDENTITY content match under a strictly
17 increasing assignment, then re-verified per frame. Exactly one decode frame
18 must have no display partner: the hidden alt-ref picture.
19"""
20import json
21import os
22import re
23import subprocess
24import sys
25
26SS = {"420": (1, 1), "422": (1, 0), "444": (0, 0), "440": (0, 1)}
27DEPTH_RE = re.compile(r"^yuv(\d{3})p(\d*)(?:le)?$")
28
29
30def probe_geometry(obu):
31 """ffprobe reads the AV1 SEQUENCE HEADER: coded_width/coded_height and the
32 chroma format/depth it implies. Never the raw output's byte length."""
33 r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v",
34 "-show_entries", "stream=coded_width,coded_height,pix_fmt",
35 "-of", "csv=p=0", obu], capture_output=True, check=True)
36 parts = r.stdout.decode().strip().split(",")
37 mw, h, pix = parts[0], parts[1], parts[2]
38 m = DEPTH_RE.match(pix)
39 if not m:
40 raise SystemExit(f"{obu}: unsupported pix_fmt {pix!r} (need a planar yuv*p[le])")
41 ss = SS.get(m.group(1))
42 if ss is None:
43 raise SystemExit(f"{obu}: unknown chroma tag C{m.group(1)} in pix_fmt {pix!r}")
44 depth = int(m.group(2)) if m.group(2) else 8
45 return int(mw), int(h), ss[0], ss[1], depth, pix
46
47
48def plane_spans(w, h, ss_x, ss_y, bps):
49 cw = -(-w // (1 << ss_x))
50 ch = -(-h // (1 << ss_y))
51 sizes = (w * h, cw * ch, cw * ch)
52 return sizes, sum(sizes) * bps
53
54
55def frame_files(prefix):
56 out, i = [], 0
57 while os.path.isfile(f"{prefix}.f{i}"):
58 out.append(f"{prefix}.f{i}")
59 i += 1
60 return out
61
62
63def ffmpeg_frames(obu, pix):
64 r = subprocess.run(["ffmpeg", "-v", "error", "-i", obu, "-f", "rawvideo",
65 "-pix_fmt", pix, "-"], capture_output=True)
66 if r.returncode != 0:
67 raise SystemExit(f"{obu}: ffmpeg refused: {r.stderr.decode()[-300:]}")
68 return r.stdout
69
70
71def split(raw, sizes, fsz, cell):
72 if not raw:
73 raise SystemExit(f"{cell}: ffmpeg produced ZERO bytes -- a 0/0/0 here is vacuous")
74 if len(raw) % fsz:
75 raise SystemExit(f"{cell}: ffmpeg rawvideo is {len(raw)} B, not a whole "
76 f"multiple of the {fsz} B frame the geometry implies")
77 return [raw[i * fsz:(i + 1) * fsz] for i in range(len(raw) // fsz)]
78
79
80def _matchings(cands, disp_n, cap=64):
81 """Every way to assign each decode frame either a distinct display partner
82 or the hidden role, covering the display side exactly. Enumerated, not
83 guessed: a duplicated picture can make the assignment genuinely ambiguous,
84 and the caller then has to show the ambiguity does not change the answer."""
85 sols = []
86
87 def dfs(i, used, acc, hid):
88 if len(sols) >= cap:
89 return
90 if i == len(cands):
91 if len(used) == disp_n:
92 sols.append((dict(acc), list(hid)))
93 return
94 for di in cands[i]:
95 if di not in used:
96 used.add(di)
97 acc[i] = di
98 dfs(i + 1, used, acc, hid)
99 del acc[i]
100 used.discard(di)
101 hid.append(i)
102 dfs(i + 1, used, acc, hid)
103 hid.pop()
104
105 dfs(0, set(), {}, [])
106 return sols
107
108
109def map_decode_to_display(ours, disp, sizes, bps, cell):
110 """Identity of each decode-order frame is carried by its LUMA plane; full-frame
111 identity is preferred when it exists. Every assignment that covers the
112 display side is enumerated, so a duplicated picture shows up as an
113 explicit solution COUNT rather than a silent pick. Real altref streams
114 REORDER display against decode (measured: decode f2..f8 -> display
115 7,3,1,2,5,4,6), so no monotonicity prior is applied -- an unjustified one
116 is exactly the class of silent mismatch this instrument exists to catch."""
117 luma = sizes[0] * bps
118 for use_full in (True, False):
119 cands = [[di for di, d in enumerate(disp)
120 if o[:luma] == d[:luma] and (o == d or not use_full)] for o in ours]
121 sols = _matchings(cands, len(disp))
122 if sols:
123 if min(len(h) for _, h in sols) > 4:
124 raise SystemExit(f"{cell}: {min(len(h) for _, h in sols)} decode frames have "
125 f"no luma-identical display partner -- LUMA itself "
126 f"diverges, so this is not a hidden-alt-ref count "
127 f"(class av1-frame-count-vs-pixel-divergence)")
128 return sols
129 raise SystemExit(f"{cell}: luma identity never covers the display side "
130 f"({len(ours)} decode frames, {len(disp)} display frames) "
131 f"-- the frame-count or per-frame identity claim is wrong")
132
133
134
135def compare(cell, ours_prefix, disp, w, h, ss_x, ss_y, depth, want_hidden=None):
136 bps = 1 if depth <= 8 else 2
137 sizes, fsz = plane_spans(w, h, ss_x, ss_y, bps)
138 ours = [open(p, "rb").read() for p in frame_files(ours_prefix)]
139 if not ours:
140 raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames from us -- vacuous 0/0/0")
141 for i, o in enumerate(ours):
142 if len(o) != fsz:
143 raise SystemExit(f"{cell}: our decode frame {i} is {len(o)} B, geometry "
144 f"{w}x{h} ss={ss_x}{ss_y} depth={depth} implies {fsz} B")
145 sols = map_decode_to_display(ours, disp, sizes, bps, cell)
146
147 def measure(mapping, hidden):
148 tot = [0, 0, 0]
149 per_disp = [[0, 0, 0] for _ in disp]
150 per_dec, first = [], None
151 bb_all = [[None, None, None, None] for _ in range(3)]
152 for oi, a in enumerate(ours):
153 if oi in hidden:
154 per_dec.append(None)
155 continue
156 b = disp[mapping[oi]]
157 fcount, off = [0, 0, 0], 0
158 for pi, sz in enumerate(sizes):
159 pw = w if pi == 0 else -(-w // (1 << ss_x))
160 for i in range(sz):
161 s = i * bps
162 if a[off + s:off + s + bps] != b[off + s:off + s + bps]:
163 fcount[pi] += 1
164 tot[pi] += 1
165 per_disp[mapping[oi]][pi] += 1
166 r, c = divmod(i, pw)
167 bb = bb_all[pi]
168 if bb[0] is None or r < bb[0]:
169 bb[0] = r
170 if bb[1] is None or r > bb[1]:
171 bb[1] = r
172 if bb[2] is None or c < bb[2]:
173 bb[2] = c
174 if bb[3] is None or c > bb[3]:
175 bb[3] = c
176 if first is None:
177 first = (mapping[oi], oi, "YUV"[pi], r, c,
178 int.from_bytes(a[off + s:off + s + bps], "little"),
179 int.from_bytes(b[off + s:off + s + bps], "little"))
180 off += sz * bps
181 per_dec.append(fcount)
182 return tot, per_disp, per_dec, first, bb_all
183
184 measured = [measure(m, h) for m, h in sols]
185 totals = {tuple(t[0]) for t in measured}
186 if len(totals) > 1:
187 raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS "
188 f"({len(sols)} solutions) and they DISAGREE on the counts "
189 f"{sorted(totals)} -- pick the identity source explicitly, "
190 f"this instrument will not choose for you")
191 tot, per_disp, per_dec, first, bbox = measured[0]
192 mapping, hidden = sols[0]
193 if want_hidden is not None and len(hidden) != want_hidden:
194 raise SystemExit(f"{cell}: {len(hidden)} hidden decode frame(s) {hidden}, "
195 f"expected {want_hidden} -- the frame-count claim changed")
196 return {"cell": cell, "status": "BYTE-EXACT" if tot == [0, 0, 0] else "DIVERGES",
197 "w": w, "h": h, "ss": f"{ss_x}{ss_y}", "depth": depth, "pix": pix_of(ss_x, ss_y, depth),
198 "decode_frames": len(ours), "display_frames": len(disp),
199 "hidden_decode": hidden, "mapping_solutions": len(sols),
200 "Y": tot[0], "U": tot[1], "V": tot[2],
201 "first": first, "bbox": bbox,
202 "per_decode_frame": per_dec, "per_display_frame": per_disp}
203
204
205def pix_of(ss_x, ss_y, depth):
206 tag = next(k for k, v in SS.items() if v == (ss_x, ss_y))
207 return f"yuv{tag}p" + ("" if depth <= 8 else f"{depth}le")
208
209
210def flip(disp, sizes, bps, disp_index, plane, sample_index):
211 """Flip bit 0 of one oracle SAMPLE's low byte: exactly +1 wrong sample in
212 both depths (2**bitdepth < 2**16, so nothing carries out of the container).
213 Returns a new list; the caller drops it to restore."""
214 new = list(disp)
215 buf = bytearray(new[disp_index])
216 buf[sum(sizes[:plane]) * bps + sample_index * bps] ^= 1
217 new[disp_index] = bytes(buf)
218 return new
219
220
221def run(cell, obu, ours_prefix, want_hidden=None, json_out=False):
222 w, h, ssx, ssy, depth, pix = probe_geometry(obu)
223 bps = 1 if depth <= 8 else 2
224 sizes, fsz = plane_spans(w, h, ssx, ssy, bps)
225 disp = split(ffmpeg_frames(obu, pix), sizes, fsz, cell)
226 res = compare(cell, ours_prefix, disp, w, h, ssx, ssy, depth, want_hidden)
227 if json_out:
228 print(json.dumps(res))
229 else:
230 f = res["first"]
231 fs = "none" if f is None else \
232 f"disp f{f[0]} (decode f{f[1]}) {f[2]} (r{f[3]},c{f[4]}) ours={f[5]} ffmpeg={f[6]}"
233 print(f"{cell}: {res['status']} {res['decode_frames']}df/"
234 f"{res['display_frames']}shown hidden={res['hidden_decode']} "
235 f"Y={res['Y']} U={res['U']} V={res['V']} first: {fs}")
236 return res, disp, sizes, fsz, bps
237
238
239if __name__ == "__main__":
240 cell, obu, prefix = sys.argv[1:4]
241 wh = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4].isdigit() else None
242 run(cell, obu, prefix, wh, "--json" in sys.argv)