forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB10ef9beTahinli2 months ago2951 commits

vp8ref_model.py291 lines, 9.3 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Dixie-faithful full key-frame VP8 decode model (modes + tokens, no
3pixels) with per-decision tracing, interleaved per MB row exactly like
4the reference decoder. Diff its `B` lines against the Rust decoder's
5EC_VP8_TRACE output.
6
7Usage: python3 vp8ref.py frame.ivf
8"""
9import re
10import sys
11
12TABLES_RS = "crates/ec-vp8/src/tables.rs"
13
14
15class BD:
16 def __init__(self, data):
17 self.data = data
18 self.pos = 2 if len(data) >= 2 else len(data)
19 v = 0
20 if len(data) >= 1:
21 v = data[0] << 8
22 if len(data) >= 2:
23 v |= data[1]
24 self.value = v
25 self.range = 255
26 self.bit_count = 0
27
28 def bool(self, prob):
29 split = 1 + (((self.range - 1) * prob) >> 8)
30 big = split << 8
31 if self.value >= big:
32 self.range -= split
33 self.value -= big
34 bit = 1
35 else:
36 self.range = split
37 bit = 0
38 while self.range < 128:
39 self.value <<= 1
40 self.range <<= 1
41 self.bit_count += 1
42 if self.bit_count == 8:
43 self.bit_count = 0
44 if self.pos < len(self.data):
45 self.value |= self.data[self.pos]
46 self.pos += 1
47 print(f"B {self.pos} {self.bit_count} {prob} {bit}")
48 return bit
49
50 def lit(self, n):
51 v = 0
52 for _ in range(n):
53 v = (v << 1) + self.bool(128)
54 return v
55
56 def maybe_int(self, n):
57 if not self.bool(128):
58 return 0
59 v = self.lit(n)
60 return -v if self.bool(128) else v
61
62 def tree(self, tree, probs):
63 i = 0
64 while True:
65 b = self.bool(probs[i >> 1])
66 i = tree[i + b]
67 if i <= 0:
68 return -i
69
70
71def table(name):
72 src = open(TABLES_RS).read()
73 m = re.search(rf"pub const {name}: [^=]+= ", src)
74 body = src[m.end(): src.index("];", m.end())]
75 return [int(x) for x in re.findall(r"-?\d+", body)]
76
77
78
79
80def main():
81 CUP = table("COEFF_UPDATE_PROBS")
82 KF_BMODE = table("KF_BMODE_PROB")
83 BANDS = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]
84 ZIGZAG = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]
85 CAT_EXTRA = [
86 [173, 148, 140],
87 [176, 155, 140, 135],
88 [180, 157, 141, 134, 130],
89 [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129],
90 ]
91 KF_YMODE_TREE = [-4, 2, 4, 6, 0, -1, -2, -3]
92 BMODE_TREE = [0, 2, -1, 4, -2, 6, 8, 12, -3, 10, -5, -6, -4, 14, -7, 16, -8, -9]
93 UV_MODE_TREE = [0, 2, -1, 4, -2, -3]
94 YMODE_MAP = {0: 0, 1: 2, 2: 3, 3: 1} # 16x16 mode -> bmode context
95 LEFT = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8]
96 ABOVE = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8]
97
98 raw = open(sys.argv[1], "rb").read()
99 sz = int.from_bytes(raw[32:36], "little")
100 frame = raw[44 : 44 + sz]
101 tag = int.from_bytes(frame[0:3], "little")
102 part0_sz = tag >> 5
103 w = int.from_bytes(frame[6:8], "little") & 0x3FFF
104 h = int.from_bytes(frame[8:10], "little") & 0x3FFF
105 cols, rows = (w + 15) // 16, (h + 15) // 16
106
107 d = BD(frame[10 : 10 + part0_sz])
108 d.lit(2) # colour space + clamping
109 # segmentation
110 if d.bool(128):
111 d.bool(128)
112 if d.bool(128):
113 d.bool(128)
114 for _ in range(4):
115 d.maybe_int(7)
116 for _ in range(4):
117 d.maybe_int(6)
118 # loop filter header
119 d.lit(1)
120 d.lit(6)
121 d.lit(3)
122 if d.bool(128):
123 if d.bool(128):
124 for _ in range(4):
125 d.maybe_int(6)
126 for _ in range(4):
127 d.maybe_int(6)
128 # token partitions
129 log2 = d.lit(2)
130 nparts = 1 << log2
131 off = 10 + part0_sz
132 sizes = []
133 for i in range(nparts):
134 if i < nparts - 1:
135 sizes.append(int.from_bytes(frame[off : off + 3], "little"))
136 off += 3
137 else:
138 sizes.append(len(frame) - off)
139 parts = []
140 po = off
141 for i in range(nparts):
142 parts.append(frame[po : po + sizes[i]])
143 po += sizes[i]
144 # quant
145 d.lit(7)
146 for _ in range(5):
147 d.maybe_int(4)
148 # reference header: refresh_entropy is read on key frames too
149 d.bool(128)
150 # coefficient probability updates
151 probs = table("DEFAULT_COEFF_PROBS")
152 idx = 0
153 for _i in range(4):
154 for _j in range(8):
155 for _k in range(3):
156 for _l in range(11):
157 if d.bool(CUP[idx]):
158 probs[idx] = d.lit(8)
159 idx += 1
160 # mb_no_skip_coeff
161 skip_enabled = d.bool(128)
162 prob_skip = d.lit(8) if skip_enabled else 128
163
164 # per-MB state; row 0 / col W are the DC_PRED border
165 mbmode = [[0] * (cols + 1) for _ in range(rows + 1)]
166 bmode = [[[0] * 16 for _ in range(cols + 1)] for _ in range(rows + 1)]
167 skips = [[False] * (cols + 1) for _ in range(rows + 1)]
168 above_ctx = [[0] * 9 for _ in range(cols)]
169
170 def get_coeffs(ptype, n0, ctx0, out):
171 base = ptype * 264
172 n = n0
173 band = BANDS[n0]
174 c = ctx0
175 p = base + band * 33 + c * 11
176
177 def g(prob_):
178 bit = d2.bool(prob_)
179 print(f"G n={n} band={band} ctx={c} prob={prob_} bit={1 if bit else 0}")
180 return bit
181
182 if not g(probs[p]):
183 return 0
184 while True:
185 n += 1
186 if not g(probs[p + 1]):
187 c = 0
188 band = BANDS[n]
189 p = base + band * 33
190 else:
191 if not g(probs[p + 2]):
192 c = 1
193 band = BANDS[n]
194 p = base + band * 33 + 11
195 v = 1
196 else:
197 if not g(probs[p + 3]):
198 if not g(probs[p + 4]):
199 v = 2
200 else:
201 v = 3 + (1 if g(probs[p + 5]) else 0)
202 else:
203 if not g(probs[p + 6]):
204 if not g(probs[p + 7]):
205 v = 5 + (1 if g(159) else 0)
206 else:
207 v = 7 + 2 * (1 if g(165) else 0)
208 v += 1 if g(145) else 0
209 else:
210 bit1 = 1 if g(probs[p + 8]) else 0
211 bit0 = 1 if g(probs[p + 9 + bit1]) else 0
212 cat = 2 * bit1 + bit0
213 v = 0
214 for prob in CAT_EXTRA[cat]:
215 v += v + (1 if g(prob) else 0)
216 v += 3 + (8 << cat)
217 c = 2
218 band = BANDS[n]
219 p = base + band * 33 + 22
220 out[ZIGZAG[n - 1]] = -v if g(128) else v
221 if n < 16 and not g(probs[p]):
222 return n
223 if n == 16:
224 return 16
225
226 # One PERSISTENT bool decoder per token partition: rows that share a
227 # partition continue its stream (dixie/libvpx behaviour).
228 d2s = [None] * nparts
229 for r in range(1, rows + 1):
230 pi = (r - 1) % nparts
231 if d2s[pi] is None:
232 d2s[pi] = BD(parts[pi])
233 d2 = d2s[pi]
234 left_ctx = [0] * 9
235 # phase 1: every mode record of the row (partition 0)
236 for c in range(1, cols + 1):
237 print(f"M {r-1} {c-1}")
238 if skip_enabled:
239 skips[r][c] = bool(d.bool(prob_skip))
240 ym = d.tree(KF_YMODE_TREE, [145, 156, 163, 128])
241 mbmode[r][c] = ym
242 if ym == 4:
243 for j in range(16):
244 if j < 4:
245 am = mbmode[r - 1][c]
246 a = bmode[r - 1][c][j + 12] if am == 4 else YMODE_MAP[am]
247 else:
248 a = bmode[r][c][j - 4]
249 if j % 4 == 0:
250 lm = mbmode[r][c - 1]
251 l = bmode[r][c - 1][j + 3] if lm == 4 else YMODE_MAP[lm]
252 else:
253 l = bmode[r][c][j - 1]
254 bmode[r][c][j] = d.tree(BMODE_TREE, KF_BMODE[(a * 10 + l) * 9 : (a * 10 + l) * 9 + 9])
255 d.tree(UV_MODE_TREE, [142, 114, 183])
256 # phase 2: tokens of the row (partition r-1 % n)
257 for c in range(1, cols + 1):
258 ac = above_ctx[c - 1]
259 hy2 = mbmode[r][c] != 4
260 if skips[r][c]:
261 for i in range(8):
262 ac[i] = 0
263 left_ctx[i] = 0
264 if hy2:
265 ac[8] = 0
266 left_ctx[8] = 0
267 continue
268
269 def one(blkidx, ptype, n0):
270 o = [0] * 16
271 ctxv = min(2, left_ctx[LEFT[blkidx]] + ac[ABOVE[blkidx]])
272 print(f"T {r-1} {c-1} {blkidx} {ptype} {ctxv}")
273 eob = get_coeffs(ptype, n0, ctxv, o)
274 t = 1 if eob > 0 else 0
275 left_ctx[LEFT[blkidx]] = t
276 ac[ABOVE[blkidx]] = t
277
278 if hy2:
279 one(24, 1, 0)
280 for b in range(16):
281 one(b, 0, 1)
282 else:
283 for b in range(16):
284 one(b, 3, 0)
285 for b in range(4):
286 one(16 + b, 2, 0)
287 for b in range(4):
288 one(20 + b, 2, 0)
289
290
291main()