forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb8ca533Tahinli2 months ago3110 commits

extract_vp8_tables.py102 lines, 3.9 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Extract the fixed probability/quant tables from the local RFC 6386 text
3into a Rust module (crates/ec-vp8/src/tables.rs).
4
5The tables are transcribed VERBATIM from the RFC text; the script asserts
6each table's element count so a parsing slip cannot produce a silently
7wrong table. Run from the worktree root:
8
9 python3 scripts/extract_vp8_tables.py [rfc.txt] [out.rs]
10"""
11
12import re
13import sys
14
15RFC = sys.argv[1] if len(sys.argv) > 1 else "/home/user/.cache/vp8/rfc6386.txt"
16OUT = sys.argv[2] if len(sys.argv) > 2 else "crates/ec-vp8/src/tables.rs"
17
18text = open(RFC, encoding="utf-8").read()
19# Strip RFC page furniture (running headers/footers land mid-table).
20text = "\n".join(
21 l for l in text.splitlines()
22 if not re.search(r"RFC 6386\s+VP8 Data Format.*2011$", l)
23 and not re.search(r"Bankoski, et al\..*\[Page \d+\]$", l)
24)
25text = text.replace("\f", "")
26
27INT_RE = re.compile(r"-?\d+")
28
29
30def collect(name: str, expect: int) -> list[int]:
31 """Find `name`'s C array DEFINITION -- '=' reachable from the name
32 through nothing but brackets, identifiers, spaces and hyphens (the
33 section-13.4 pseudocode mentions `coeff_update_probs [i] [j] [k] [t]))`
34 and must not match) -- and collect every integer between '=' and the
35 terminating '};'."""
36 for m in re.finditer(rf"\b{re.escape(name)}\b[\[\]\w\s-]*?=", text):
37 body = text[m.end() : m.end() + 60000]
38 end = body.find("};")
39 assert end != -1, f"{name}: no terminator"
40 vals = [int(v) for v in INT_RE.findall(body[:end])]
41 if len(vals) != expect:
42 raise SystemExit(
43 f"{name}: expected {expect} ints, got {len(vals)}: {vals[:10]}..."
44 )
45 return vals
46 raise SystemExit(f"{name}: definition not found")
47
48
49# (rust name, RFC name, expected ints incl. Pcat sentinels, dims, type)
50TABLES = [
51 ("COEFF_UPDATE_PROBS", "coeff_update_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"),
52 ("DEFAULT_COEFF_PROBS", "default_coeff_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"),
53 ("KF_BMODE_PROB", "kf_bmode_prob", 10 * 10 * 9, (10, 10, 9), "u8"),
54 ("COEFF_BANDS", "coeff_bands", 16, (16,), "u8"),
55 ("DC_QLOOKUP", "dc_qlookup", 128, (128,), "i16"),
56 ("AC_QLOOKUP", "ac_qlookup", 128, (128,), "i16"),
57 ("PCAT1", "Pcat1", 2, (2,), "u8"),
58 ("PCAT2", "Pcat2", 3, (3,), "u8"),
59 ("PCAT3", "Pcat3", 4, (4,), "u8"),
60 ("PCAT4", "Pcat4", 5, (5,), "u8"),
61 ("PCAT5", "Pcat5", 6, (6,), "u8"),
62 ("PCAT6", "Pcat6", 12, (12,), "u8"),
63 ("DEFAULT_MV_PROBS", "k_default_mv_probs", 2 * 19, (2, 19), "u8"),
64 ("MV_UPDATE_PROBS", "k_mv_entropy_update_probs", 2 * 19, (2, 19), "u8"),
65]
66
67
68def rust_ty(ty: str, dims: tuple[int, ...]) -> str:
69 t = ty
70 for d in reversed(dims):
71 t = f"[{t}; {d}]"
72 return t
73
74
75def nest(vals: list[int], dims: tuple[int, ...]) -> str:
76 if len(dims) == 1:
77 return "[" + ", ".join(str(v) for v in vals) + "]"
78 step = len(vals) // dims[0]
79 parts = [
80 nest(vals[i * step : (i + 1) * step], dims[1:]) for i in range(dims[0])
81 ]
82 if len(dims) == 2:
83 return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]"
84 return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]"
85
86
87out = [
88 "//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and",
89 "//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from",
90 "//! the RFC text; do not edit by hand. The extractor asserts every",
91 "//! table's element count, so a slip cannot drop or add values.",
92 "#![allow(clippy::all)]",
93 "",
94]
95for rust_name, rfc_name, expect, dims, ty in TABLES:
96 vals = collect(rfc_name, expect)
97 note = " (trailing 0 is the DCTextra sentinel)" if rfc_name.startswith("Pcat") else ""
98 out.append(f"/// RFC 6386 `{rfc_name}`{note}.")
99 out.append(f"pub const {rust_name}: {rust_ty(ty, dims)} = {nest(vals, dims)};\n")
100
101open(OUT, "w", encoding="utf-8").write("\n".join(out))
102print(f"wrote {OUT}")