forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5111c5aTahinli1 month ago3851 commits

cmp422-ffmpeg.py313 lines, 13.8 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, node_cap=4_000_000):
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
86 Two bounds, both learned the hard way: without the feasibility prune, an
87 instance whose candidate lists cannot cover the display side explores the
88 whole 2**frames tree before returning empty (that is what made three
89 43-frame cells burn a 300 s cap with 15 minutes of user CPU and never
90 finish), and without a node cap a pathological instance would hang the
91 comparator instead of reporting."""
92 sols = []
93 nodes = 0
94
95 def dfs(i, used, acc, hid):
96 nonlocal nodes
97 nodes += 1
98 if nodes > node_cap:
99 raise SystemExit(f"the decode->display assignment search exceeded {node_cap} nodes "
100 f"at frame {i} of {len(cands)} ({disp_n} display frames) -- this "
101 f"instance is not enumerable; report it rather than hang")
102 if len(sols) >= cap:
103 return
104 if disp_n - len(used) > len(cands) - i:
105 return # not enough decode frames left to cover the display side
106 if i == len(cands):
107 if len(used) == disp_n:
108 sols.append((dict(acc), list(hid)))
109 return
110 for di in cands[i]:
111 if di not in used:
112 used.add(di)
113 acc[i] = di
114 dfs(i + 1, used, acc, hid)
115 del acc[i]
116 used.discard(di)
117 hid.append(i)
118 dfs(i + 1, used, acc, hid)
119 hid.pop()
120
121 dfs(0, set(), {}, [])
122 return sols
123
124
125def map_decode_to_display(ours, disp, sizes, bps, cell):
126 """Identity of each decode-order frame is carried by its LUMA plane; full-frame
127 identity is preferred when it exists. Every assignment that covers the
128 display side is enumerated, so a duplicated picture shows up as an
129 explicit solution COUNT rather than a silent pick. Real altref streams
130 REORDER display against decode (measured: decode f2..f8 -> display
131 7,3,1,2,5,4,6), so no monotonicity prior is applied -- an unjustified one
132 is exactly the class of silent mismatch this instrument exists to catch."""
133 luma = sizes[0] * bps
134 for use_full in (True, False):
135 cands = [[di for di, d in enumerate(disp)
136 if o[:luma] == d[:luma] and (o == d or not use_full)] for o in ours]
137 sols = _matchings(cands, len(disp))
138 if sols:
139 if min(len(h) for _, h in sols) > 4:
140 raise SystemExit(f"{cell}: {min(len(h) for _, h in sols)} decode frames have "
141 f"no luma-identical display partner -- LUMA itself "
142 f"diverges, so this is not a hidden-alt-ref count "
143 f"(class av1-frame-count-vs-pixel-divergence)")
144 return sols
145 raise SystemExit(f"{cell}: luma identity never covers the display side "
146 f"({len(ours)} decode frames, {len(disp)} display frames) "
147 f"-- the frame-count or per-frame identity claim is wrong")
148
149
150
151def compare(cell, ours_prefix, disp, w, h, ss_x, ss_y, depth, want_hidden=None):
152 bps = 1 if depth <= 8 else 2
153 sizes, fsz = plane_spans(w, h, ss_x, ss_y, bps)
154 ours = [open(p, "rb").read() for p in frame_files(ours_prefix)]
155 if not ours:
156 raise SystemExit(f"{cell}: no EC_AV1_FINAL_DUMP frames from us -- vacuous 0/0/0")
157 for i, o in enumerate(ours):
158 if len(o) != fsz:
159 raise SystemExit(f"{cell}: our decode frame {i} is {len(o)} B, geometry "
160 f"{w}x{h} ss={ss_x}{ss_y} depth={depth} implies {fsz} B")
161 sols = map_decode_to_display(ours, disp, sizes, bps, cell)
162
163 def measure(mapping, hidden):
164 tot = [0, 0, 0]
165 per_disp = [[0, 0, 0] for _ in disp]
166 per_dec, first = [], None
167 bb_all = [[None, None, None, None] for _ in range(3)]
168 for oi, a in enumerate(ours):
169 if oi in hidden:
170 per_dec.append(None)
171 continue
172 b = disp[mapping[oi]]
173 fcount, off = [0, 0, 0], 0
174 for pi, sz in enumerate(sizes):
175 pw = w if pi == 0 else -(-w // (1 << ss_x))
176 for i in range(sz):
177 s = i * bps
178 if a[off + s:off + s + bps] != b[off + s:off + s + bps]:
179 fcount[pi] += 1
180 tot[pi] += 1
181 per_disp[mapping[oi]][pi] += 1
182 r, c = divmod(i, pw)
183 bb = bb_all[pi]
184 if bb[0] is None or r < bb[0]:
185 bb[0] = r
186 if bb[1] is None or r > bb[1]:
187 bb[1] = r
188 if bb[2] is None or c < bb[2]:
189 bb[2] = c
190 if bb[3] is None or c > bb[3]:
191 bb[3] = c
192 if first is None:
193 first = (mapping[oi], oi, "YUV"[pi], r, c,
194 int.from_bytes(a[off + s:off + s + bps], "little"),
195 int.from_bytes(b[off + s:off + s + bps], "little"))
196 off += sz * bps
197 per_dec.append(fcount)
198 return tot, per_disp, per_dec, first, bb_all
199
200 def xor_plane_counts(a, b):
201 """Per-plane differing-SAMPLE counts at 8-bit, at C speed: XOR the two
202 planes as big ints, then count non-zero bytes per plane. Equivalent to
203 the per-sample loop above, and the only reason a 43-frame cell with 64
204 candidate assignments used to cost half an hour."""
205 z = int.from_bytes(a, "big") ^ int.from_bytes(b, "big")
206 zb = z.to_bytes(len(a), "big")
207 out, off = [], 0
208 for sz in sizes:
209 seg = zb[off:off + sz]
210 off += sz
211 out.append(len(seg) - seg.count(0))
212 return out
213
214 if bps == 1:
215 pair_cache = {}
216
217 def pair_total(oi, di):
218 v = pair_cache.get((oi, di))
219 if v is None:
220 v = xor_plane_counts(ours[oi], disp[di])
221 pair_cache[(oi, di)] = v
222 return v
223
224 sol_totals = []
225 for m, _h in sols:
226 t = [0, 0, 0]
227 for oi, di in m.items():
228 p = pair_total(oi, di)
229 t[0] += p[0]
230 t[1] += p[1]
231 t[2] += p[2]
232 sol_totals.append(tuple(t))
233 if len(set(sol_totals)) > 1:
234 raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS "
235 f"({len(sols)} solutions) and they DISAGREE on the counts "
236 f"{sorted(set(sol_totals))} -- pick the identity source explicitly, "
237 f"this instrument will not choose for you")
238 tot = list(sol_totals[0])
239 mapping, hidden = sols[0]
240 if tot == [0, 0, 0]:
241 per_disp = [[0, 0, 0] for _ in disp]
242 per_dec = [None if oi in hidden else [0, 0, 0] for oi in range(len(ours))]
243 first, bbox = None, [[None, None, None, None] for _ in range(3)]
244 else:
245 tot, per_disp, per_dec, first, bbox = measure(mapping, hidden)
246 else:
247 # 16-bit planes: the sample loop below is the only path today.
248 if all(all(ours[oi] == disp[di] for oi, di in m.items()) for m, h in sols):
249 hidden0 = sols[0][1]
250 measured = [([0, 0, 0], [[0, 0, 0] for _ in disp],
251 [None if oi in hidden0 else [0, 0, 0] for oi in range(len(ours))],
252 None, [[None, None, None, None] for _ in range(3)])]
253 measured *= len(sols)
254 else:
255 measured = [measure(m, h) for m, h in sols]
256 totals = {tuple(t[0]) for t in measured}
257 if len(totals) > 1:
258 raise SystemExit(f"{cell}: the decode->display assignment is AMBIGUOUS "
259 f"({len(sols)} solutions) and they DISAGREE on the counts "
260 f"{sorted(totals)} -- pick the identity source explicitly, "
261 f"this instrument will not choose for you")
262 tot, per_disp, per_dec, first, bbox = measured[0]
263 mapping, hidden = sols[0]
264 if want_hidden is not None and len(hidden) != want_hidden:
265 raise SystemExit(f"{cell}: {len(hidden)} hidden decode frame(s) {hidden}, "
266 f"expected {want_hidden} -- the frame-count claim changed")
267 return {"cell": cell, "status": "BYTE-EXACT" if tot == [0, 0, 0] else "DIVERGES",
268 "w": w, "h": h, "ss": f"{ss_x}{ss_y}", "depth": depth, "pix": pix_of(ss_x, ss_y, depth),
269 "decode_frames": len(ours), "display_frames": len(disp),
270 "hidden_decode": hidden, "mapping_solutions": len(sols),
271 "Y": tot[0], "U": tot[1], "V": tot[2],
272 "first": first, "bbox": bbox,
273 "per_decode_frame": per_dec, "per_display_frame": per_disp}
274
275
276def pix_of(ss_x, ss_y, depth):
277 tag = next(k for k, v in SS.items() if v == (ss_x, ss_y))
278 return f"yuv{tag}p" + ("" if depth <= 8 else f"{depth}le")
279
280
281def flip(disp, sizes, bps, disp_index, plane, sample_index):
282 """Flip bit 0 of one oracle SAMPLE's low byte: exactly +1 wrong sample in
283 both depths (2**bitdepth < 2**16, so nothing carries out of the container).
284 Returns a new list; the caller drops it to restore."""
285 new = list(disp)
286 buf = bytearray(new[disp_index])
287 buf[sum(sizes[:plane]) * bps + sample_index * bps] ^= 1
288 new[disp_index] = bytes(buf)
289 return new
290
291
292def run(cell, obu, ours_prefix, want_hidden=None, json_out=False):
293 w, h, ssx, ssy, depth, pix = probe_geometry(obu)
294 bps = 1 if depth <= 8 else 2
295 sizes, fsz = plane_spans(w, h, ssx, ssy, bps)
296 disp = split(ffmpeg_frames(obu, pix), sizes, fsz, cell)
297 res = compare(cell, ours_prefix, disp, w, h, ssx, ssy, depth, want_hidden)
298 if json_out:
299 print(json.dumps(res))
300 else:
301 f = res["first"]
302 fs = "none" if f is None else \
303 f"disp f{f[0]} (decode f{f[1]}) {f[2]} (r{f[3]},c{f[4]}) ours={f[5]} ffmpeg={f[6]}"
304 print(f"{cell}: {res['status']} {res['decode_frames']}df/"
305 f"{res['display_frames']}shown hidden={res['hidden_decode']} "
306 f"Y={res['Y']} U={res['U']} V={res['V']} first: {fs}")
307 return res, disp, sizes, fsz, bps
308
309
310if __name__ == "__main__":
311 cell, obu, prefix = sys.argv[1:4]
312 wh = int(sys.argv[4]) if len(sys.argv) > 4 and sys.argv[4].isdigit() else None
313 run(cell, obu, prefix, wh, "--json" in sys.argv)