forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gen_h263_tables.py515 lines, 22.3 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Generate crates/ec-mpeg4/src/h263data.rs from the text of ITU-T Rec. H.263 (01/2005).
3
4Usage:
5 pdftotext -layout T-REC-H.263-200501-I!!PDF-E.pdf h263.txt
6 python3 -I tools/gen_h263_tables.py h263.txt crates/ec-mpeg4/src/h263data.rs
7 rustfmt --edition 2021 crates/ec-mpeg4/src/h263data.rs
8
9The PDF is freely downloadable from https://www.itu.int/rec/T-REC-H.263 and is the
10only input; every table below is read from the tables/figures of that document.
11"""
12import re
13import sys
14
15src = open(sys.argv[1], encoding="utf-8").read().replace("−", "-").replace("–", "-")
16lines = src.split("\n")
17
18
19def section(start, end):
20 """Lines from the first line containing `start` up to the next line containing `end`."""
21 i = next(k for k, l in enumerate(lines) if start in l)
22 j = next(k for k in range(i + 1, len(lines)) if end in lines[k])
23 return lines[i:j]
24
25
26def bits(code):
27 return code.replace(" ", "")
28
29
30# ---- Tables 7 and 8: MCBPC ------------------------------------------------------
31def mcbpc(sec, kinds):
32 rows = {}
33 for l in sec:
34 m = re.match(r"^\s*(\d+)\s+(\S+)\s+(?:(-|\d\d)\s+)?(\d+)\s+((?:[01]+ ?)+)\s*$", l)
35 if m:
36 rows[int(m.group(1))] = (m.group(2), m.group(3), int(m.group(4)), bits(m.group(5)))
37 return rows
38
39
40t7 = mcbpc(section("Table 7/H.263", "Table 8/H.263"), None)
41t8 = mcbpc(section("Table 8/H.263 – VLC table for MCBPC (for P-pictures)".replace("–", "-"), "An extra codeword"), None)
42assert sorted(t7) == list(range(9)) and sorted(t8) == list(range(25)), (sorted(t7), sorted(t8))
43for rows in (t7, t8):
44 for k, (_, _, n, c) in rows.items():
45 assert len(c) == n
46intra_code, intra_bits = [], []
47for i in range(9):
48 intra_code.append(int(t7[i][3], 2))
49 intra_bits.append(t7[i][2])
50# Layout of the P-picture table: slot = 4 * group + CBPC, where the group is a flag
51# combination of the MB type: bit 0 = INTRA, bit 1 = "+Q" (DQUANT present), bit 2 = four
52# vectors (spec types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, 4 INTRA+Q, 5 INTER4V+Q give
53# groups 0, 2, 4, 1, 3, 6). Group 5 holds the stuffing code in its first slot only, so
54# slots 21-23 are unused.
55GROUP = {0: 0, 1: 2, 2: 4, 3: 1, 4: 3, 5: 6}
56inter_code, inter_bits = [0] * 28, [0] * 28
57for i in range(25):
58 if t8[i][0] == "Stuffing":
59 slot = 4 * 5
60 else:
61 assert t8[i][1] == format(i % 4 if i < 20 else i - 21, "02b")
62 slot = 4 * GROUP[int(t8[i][0])] + int(t8[i][1], 2)
63 assert inter_bits[slot] == 0
64 inter_code[slot], inter_bits[slot] = int(t8[i][3], 2), t8[i][2]
65mcbpc_spec = {"I": [(t7[i][0], t7[i][1], t7[i][3]) for i in range(9)],
66 "P": [(t8[i][0], t8[i][1], t8[i][3]) for i in range(25)]}
67
68# ---- Table 12: CBPY ---------------------------------------------------------------
69sec = section("Table 12/H.263", "5.3.6")
70cbpy_rows = {}
71cur = None
72for l in sec:
73 m = re.match(r"^\s*(\d+)\s+(\d\d)\s+(\d\d)\s+(\d+)\s+((?:[01]+ ?)+)\s*$", l)
74 if m:
75 cur = (int(m.group(1)), m.group(2), m.group(3), int(m.group(4)), bits(m.group(5)))
76 continue
77 m = re.match(r"^\s*(\d\d)\s+(\d\d)\s*$", l)
78 if m and cur:
79 idx, a12, b12, n, c = cur
80 intra = int(a12 + m.group(1), 2)
81 inter = int(b12 + m.group(2), 2)
82 assert inter == 15 - intra and intra == idx and len(c) == n
83 cbpy_rows[intra] = (c, n)
84 cur = None
85assert sorted(cbpy_rows) == list(range(16))
86cbpy = [[int(cbpy_rows[i][0], 2), cbpy_rows[i][1]] for i in range(16)]
87cbpy_spec = [cbpy_rows[i][0] for i in range(16)]
88
89# ---- Table 14: MVD ---------------------------------------------------------------
90sec = section("Table 14/H.263", "5.3.8")
91mvd = {}
92for l in sec:
93 m = re.match(r"^\s*(\d+)\s+(-?[\d.]+)\s+(?:(-?[\d.]+)\s+)?(\d+)\s+((?:[01]+ ?)+)\s*$", l)
94 if m:
95 c = bits(m.group(5))
96 assert len(c) == int(m.group(4))
97 mvd[int(m.group(1))] = (float(m.group(2)), c)
98assert sorted(mvd) == list(range(64))
99by_vec = {v: c for v, c in mvd.values()}
100mvtab = [] # index = |vector| in half samples; the code without its trailing sign bit
101mvd_spec = []
102for k in range(33):
103 v = k / 2
104 if k == 0:
105 c = by_vec[0.0]
106 assert c == "1"
107 mvtab.append([1, 1])
108 mvd_spec.append("1")
109 continue
110 if k == 32: # +-16 share one codeword (-16 is listed; +16 == -16 modulo 32)
111 c = by_vec[-16.0]
112 assert c.endswith("1")
113 c = c[:-1]
114 else:
115 cp, cn = by_vec[v], by_vec[-v]
116 assert cp[:-1] == cn[:-1] and cp[-1] == "0" and cn[-1] == "1"
117 c = cp[:-1]
118 mvtab.append([int(c, 2), len(c)])
119 mvd_spec.append(c)
120
121# ---- Tables 16 and I.2: TCOEF ----------------------------------------------------
122def tcoef(start, end):
123 sec = section(start, end)
124 rows = {}
125 esc = None
126 for l in sec:
127 m = re.match(r"^\s*(\d+)\s+([01])\s+(\d+)\s+(\d+)\s+(\d+)\s+((?:[01]+ ?)+)s\s*$", l)
128 if m:
129 c = bits(m.group(6))
130 assert len(c) + 1 == int(m.group(5))
131 rows[int(m.group(1))] = (int(m.group(2)), int(m.group(3)), int(m.group(4)), c)
132 continue
133 m = re.match(r"^\s*(\d+)\s+ESCAPE\s+(\d+)\s+((?:[01]+ ?)+)\s*$", l)
134 if m:
135 esc = (int(m.group(1)), bits(m.group(3)))
136 assert len(esc[1]) == int(m.group(2))
137 assert sorted(rows) == list(range(102)) and esc[0] == 102
138 return [rows[i] for i in range(102)], esc[1]
139
140
141def rl_arrays(entries, esc):
142 """Entries sorted by (LAST, RUN, |LEVEL|); vlc excludes the sign bit; the escape
143 code is the final entry. Returns vlc, run, level, count of LAST = 0 entries."""
144 ent = sorted(entries, key=lambda e: (e[0], e[1], e[2]))
145 vlc = [[int(e[3], 2), len(e[3])] for e in ent] + [[int(esc, 2), len(esc)]]
146 return ent, vlc, [e[1] for e in ent], [e[2] for e in ent], sum(1 for e in ent if e[0] == 0)
147
148
149t16, t16esc = tcoef("Table 16/H.263", "Table 17/H.263")
150t12i, t12iesc = tcoef("Table I.2/H.263", "Depending on the value of INTRA_MODE")
151inter_ent, inter_vlc, inter_run, inter_level, inter_last = rl_arrays(t16, t16esc)
152aic_ent, aic_vlc, aic_run, aic_level, aic_last = rl_arrays(t12i, t12iesc)
153# Table 16 is printed in this order already
154assert [e for e in t16] == inter_ent
155assert {e[3] for e in t16} == {e[3] for e in t12i} and t16esc == t12iesc # I.2 re-uses the codewords
156
157# ---- Table O.4: CBPC for B/EP pictures ------------------------------------------
158sec = section("Table O.4/H.263", "O.4.4")
159cbpc_b = {}
160for l in sec:
161 m = re.match(r"^\s*(\d)\s+(\d\d)\s+([01]+)\s+(\d)\s*$", l)
162 if m:
163 assert len(m.group(3)) == int(m.group(4))
164 cbpc_b[int(m.group(2), 2)] = (m.group(3), int(m.group(1)))
165assert sorted(cbpc_b) == [0, 1, 2, 3]
166cbpc_b_tab = [[int(cbpc_b[i][0], 2), len(cbpc_b[i][0])] for i in range(4)]
167
168# ---- Tables T.1 and T.2: Modified Quantization ---------------------------------
169sec = section("Table T.1/H.263", "T.2.2")
170t1 = {}
171for l in sec:
172 m = re.match(r"^\s*(\d+)(?:-(\d+))?\s+([+-]?\d)\s+([+-]?\d)\s*$", l)
173 if m:
174 lo = int(m.group(1))
175 hi = int(m.group(2) or lo)
176 for q in range(lo, hi + 1):
177 t1[q] = (int(m.group(3)), int(m.group(4)))
178assert sorted(t1) == list(range(1, 32))
179# Slot 0 (QUANT = 0 does not occur) is 0. Row 0: DQUANT = 10, row 1: DQUANT = 11.
180modq = [[0] + [q + t1[q][r] for q in range(1, 32)] for r in range(2)]
181sec = section("Table T.2/H.263", "T.4")
182t2 = {}
183for l in sec:
184 m = re.match(r"^\s*(\d+)-(\d+)\s+(?:QUANT_C = QUANT(?: - (\d))?|(\d+))\s*$", l)
185 if m:
186 for q in range(int(m.group(1)), int(m.group(2)) + 1):
187 if m.group(4):
188 t2[q] = int(m.group(4))
189 else:
190 t2[q] = q - int(m.group(3) or 0)
191assert sorted(t2) == list(range(1, 32))
192chroma_q = [0] + [t2[q] for q in range(1, 32)]
193
194# ---- Table K.2: MBA field width ------------------------------------------------
195sec = section("Table K.2/H.263", "K.2.6")
196mba_max, mba_len = [], []
197for l in sec:
198 m = re.match(r"^\s*(sub-QCIF|QCIF|CIF|4CIF|16CIF|2048 .* 1152)\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s*$", l)
199 if m:
200 mba_max.append(int(m.group(2)))
201 mba_len.append(int(m.group(3)))
202assert len(mba_max) == 6
203# Pictures larger than the last row also use 14 bits (final padding slot).
204mba_len.append(mba_len[-1])
205
206# ---- Figure 14 and Figure I.2: scans -------------------------------------------
207def grid_rows(sec, n):
208 rows = []
209 for l in sec:
210 nums = re.findall(r"\d+", l)
211 if len(nums) == n and re.match(r"^[\s\d]+$", l):
212 rows.append([int(x) for x in nums])
213 return rows
214
215
216start14 = next(k for k, l in enumerate(lines) if l.lstrip("\x0c").startswith("6.2.3") and "Zigzag" in l and "...." not in l)
217rows = grid_rows(lines[start14:start14 + 20], 8)[:8]
218assert len(rows) == 8
219
220
221def scan_from_grid(g):
222 """g[row][col] = 1-based scan position -> table of raster positions per scan index."""
223 out = [None] * 64
224 for r in range(8):
225 for c in range(8):
226 out[g[r][c] - 1] = r * 8 + c
227 assert None not in out
228 return out
229
230
231zigzag = scan_from_grid(rows)
232startI2 = next(k for k, l in enumerate(lines) if l.lstrip("\x0c").rstrip() == "I.3 Decoding process")
233rows2 = grid_rows(lines[startI2:startI2 + 20], 16)[:8]
234assert len(rows2) == 8
235alt_h = scan_from_grid([r[:8] for r in rows2])
236alt_v = scan_from_grid([r[8:] for r in rows2])
237
238# ---- Table 2 + PTYPE source format codes, Table 5 + Table 3: formats and PAR ----
239fmt = {}
240for l in section("Table 2/H.263", "For all picture formats, colour"):
241 m = re.match(r"^\s*(sub-QCIF|QCIF|CIF|4CIF|16CIF)\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s*$", l)
242 if m:
243 fmt[m.group(1)] = (int(m.group(2)), int(m.group(3)))
244# PTYPE bits 6-8 (5.1.3): 001 sub-QCIF, 010 QCIF, 011 CIF, 100 4CIF, 101 16CIF.
245flat = re.sub(r"\s+", " ", " ".join(lines))
246assert '"001" sub-QCIF, "010" QCIF, "011" CIF, "100" 4CIF, "101" 16CIF' in flat
247names = ["sub-QCIF", "QCIF", "CIF", "4CIF", "16CIF"]
248h263_format = [[0, 0]] + [list(fmt[n]) for n in names] + [[0, 0], [0, 0]]
249par = {}
250for l in section("Table 5/H.263", "5.1.6"):
251 m = re.match(r"^\s*([01]{4})\s+(\d+):(\d+)\b", l)
252 if m:
253 par[int(m.group(1), 2)] = (int(m.group(2)), int(m.group(3)))
254assert sorted(par) == [1, 2, 3, 4, 5] and par[1] == (1, 1) and par[5] == (40, 33)
255# Codes 0 (forbidden), 6-14 (reserved) and 15 (extended PAR, carried in EPAR) are (0, 1).
256h263_par = [[0, 1]] + [list(par[i]) for i in range(1, 6)] + [[0, 1]] * 10
257
258# ---- Annex I.3: INTRA dequantisation RecC = 2 * QUANT * LEVEL (also for DC) -----
259assert "RecC(u,v) = 2 * QUANT * LEVEL(u,v)" in src
260aic_dc_scale = [2 * q for q in range(32)]
261
262# ---------------------------------------------------------------------------------
263out = []
264w = out.append
265
266
267def arr2(name, ty, a, doc):
268 w(f"/// {doc}")
269 w(f"pub const {name}: [[{ty}; 2]; {len(a)}] = [")
270 for x in a:
271 w(f" [{x[0]}, {x[1]}],")
272 w("];\n")
273
274
275def arr1(name, ty, a, doc):
276 w(f"/// {doc}")
277 w(f"pub const {name}: [{ty}; {len(a)}] = [" + ", ".join(str(x) for x in a) + "];\n")
278
279
280w("""// Generated by tools/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005)
281// (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand.
282//
283// Every table in this file is transcribed from the Recommendation; the clause or table
284// number is given in each doc comment. A `[code, bits]` pair holds a variable length
285// code as its integer value and its length in bits (the sign bit of TCOEF / MVD
286// codes is not included).
287""")
288arr1("H263_INTRA_MCBPC_CODE", "u8", intra_code, "MCBPC for I pictures, code value by spec index (Table 7/H.263; index 8 is stuffing).")
289arr1("H263_INTRA_MCBPC_BITS", "u8", intra_bits, "MCBPC for I pictures, code length (Table 7/H.263).")
290arr1("H263_INTER_MCBPC_CODE", "u8", inter_code, "MCBPC for P pictures, code value. Slot = 4 * group + CBPC with group = INTRA + 2 * Q + 4 * four-vectors flags of the MB type (types 0, 3, 1, 4, 2 -> groups 0..4, type 5 -> group 6), slot 20 = stuffing, slots 21-23 unused (Table 8/H.263).")
291arr1("H263_INTER_MCBPC_BITS", "u8", inter_bits, "MCBPC for P pictures, code length (Table 8/H.263); 0 marks an unused slot.")
292arr2("CBPC_B_TAB", "u8", cbpc_b_tab, "CBPC for B- and EP-pictures, indexed by the coded block pattern (Table O.4/H.263).")
293arr2("H263_CBPY_TAB", "u8", cbpy, "CBPY, indexed by the INTRA pattern value (12,34) read as four bits (Table 12/H.263); the INTER code is that of the complemented pattern.")
294arr2("MVTAB", "u8", mvtab, "MVD, indexed by the absolute vector difference in half samples 0..32 (Table 14/H.263); the sign bit follows the code, +-16 share one code.")
295arr2("INTER_VLC", "u16", inter_vlc, "TCOEF VLC without the sign bit, 102 (LAST, RUN, |LEVEL|) codes sorted by LAST, RUN, |LEVEL| followed by ESCAPE (Table 16/H.263).")
296arr1("INTER_LEVEL", "i8", inter_level, "|LEVEL| of the entries of INTER_VLC (Table 16/H.263).")
297arr1("INTER_RUN", "i8", inter_run, "RUN of the entries of INTER_VLC (Table 16/H.263).")
298arr2("INTRA_VLC_AIC", "u16", aic_vlc, "INTRA TCOEF VLC for Advanced INTRA Coding, entries sorted by LAST, RUN, |LEVEL|, then ESCAPE (Table I.2/H.263).")
299arr1("INTRA_RUN_AIC", "i8", aic_run, "RUN of the entries of INTRA_VLC_AIC (Table I.2/H.263).")
300arr1("INTRA_LEVEL_AIC", "i8", aic_level, "|LEVEL| of the entries of INTRA_VLC_AIC (Table I.2/H.263).")
301arr1("AIC_DC_SCALE_TABLE", "u8", aic_dc_scale, "Advanced INTRA Coding reconstruction scale 2 * QUANT (Annex I.3: RecC = 2 * QUANT * LEVEL, applied to INTRADC too).")
302w("/// Modified Quantization: new QUANT for DQUANT = 10 (row 0) and 11 (row 1) by prior QUANT (Table T.1/H.263); slot 0 is unused.")
303w(f"pub const MODIFIED_QUANT_TAB: [[u8; 32]; 2] = [")
304for r in modq:
305 w(" [" + ", ".join(map(str, r)) + "],")
306w("];\n")
307arr1("H263_CHROMA_QSCALE_TABLE", "u8", chroma_q, "QUANT_C for chrominance in Modified Quantization mode (Table T.2/H.263); slot 0 is unused.")
308arr1("MBA_MAX", "u16", mba_max, "Largest macroblock address per standard picture format, sub-QCIF to 2048x1152 (Table K.2/H.263).")
309arr1("MBA_LENGTH", "u8", mba_len, "MBA field width in bits for the same formats (Table K.2/H.263); the last slot repeats the 14 bits of the largest format.")
310arr1("ZIGZAG_DIRECT", "u8", zigzag, "Zigzag scan: raster position (row * 8 + column) of each scan index (Figure 14/H.263).")
311arr1("ALTERNATE_HORIZONTAL_SCAN", "u8", alt_h, "Alternate-Horizontal scan (Figure I.2-a/H.263).")
312arr1("ALTERNATE_VERTICAL_SCAN", "u8", alt_v, "Alternate-Vertical scan (Figure I.2-b/H.263, as in H.262).")
313w("/// Source format dimensions by PTYPE source-format code 0-7 (width, height; Table 2/H.263 and 5.1.3); 0, 6 and 7 are not standard formats.")
314w(f"pub const H263_FORMAT: [[u16; 2]; 8] = [")
315for x in h263_format:
316 w(f" [{x[0]}, {x[1]}],")
317w("];\n")
318arr2("H263_PIXEL_ASPECT", "u8", h263_par, "Pixel aspect ratio (width, height) by PAR code (Table 5/H.263); forbidden, reserved and extended codes give (0, 1).")
319w("// Number of entries (without ESCAPE) and number of LAST = 0 entries of the TCOEF tables.")
320w(f"pub const H263_RL_INTER_N: usize = {len(inter_ent)};")
321w(f"pub const H263_RL_INTER_LAST: usize = {inter_last};")
322w(f"pub const RL_INTRA_AIC_N: usize = {len(aic_ent)};")
323w(f"pub const RL_INTRA_AIC_LAST: usize = {aic_last};")
324
325# --- test module with the spec's own text
326w("""
327#[cfg(test)]
328mod spec_tests {
329 //! The rows below are the printed codes of the Recommendation; the tests rebuild
330 //! the packed tables from them and compare.
331 use super::*;
332
333 fn val(c: &str) -> (u32, u32) {
334 (u32::from_str_radix(c, 2).unwrap(), c.len() as u32)
335 }
336""")
337w(" /// (MB type, CBPC, code) of Table 7/H.263, indices 0-8.")
338w(" const T7: [(&str, &str, &str); 9] = [")
339for r in mcbpc_spec["I"]:
340 w(f' ("{r[0]}", "{r[1]}", "{r[2]}"),')
341w(" ];")
342w(" /// (MB type, CBPC, code) of Table 8/H.263, indices 0-24.")
343w(" const T8: [(&str, &str, &str); 25] = [")
344for r in mcbpc_spec["P"]:
345 w(f' ("{r[0]}", "{r[1]}", "{r[2]}"),')
346w(" ];")
347w(" /// Table 12/H.263 codes in index order (index = INTRA pattern).")
348w(" const T12: [&str; 16] = [" + ", ".join(f'"{c}"' for c in cbpy_spec) + "];")
349w(" /// Table 14/H.263 codes for positive vectors 0, 0.5, ... 15.5 without sign bit, and -16 last.")
350w(" const T14: [&str; 33] = [" + ", ".join(f'"{c}"' for c in mvd_spec) + "];")
351w(" /// Table 16/H.263 rows: (LAST, RUN, |LEVEL|, code without sign) by index; ESCAPE code below.")
352w(f" const T16: [(u8, i8, i8, &str); 102] = [")
353for e in t16:
354 w(f' ({e[0]}, {e[1]}, {e[2]}, "{e[3]}"),')
355w(" ];")
356w(f' const T16_ESC: &str = "{t16esc}";')
357w(" /// Table I.2/H.263 rows in index order.")
358w(f" const TI2: [(u8, i8, i8, &str); 102] = [")
359for e in t12i:
360 w(f' ({e[0]}, {e[1]}, {e[2]}, "{e[3]}"),')
361w(" ];")
362w("""
363 #[test]
364 fn mcbpc_matches_tables_7_and_8() {
365 for (i, r) in T7.iter().enumerate() {
366 let (c, n) = val(r.2);
367 assert_eq!((H263_INTRA_MCBPC_CODE[i] as u32, H263_INTRA_MCBPC_BITS[i] as u32), (c, n));
368 }
369 for r in T8.iter() {
370 // group = flags of the MB type (INTRA 1, +Q 2, 4V 4); stuffing is group 5.
371 let group = match r.0 {
372 "Stuffing" => 5,
373 t => [0, 2, 4, 1, 3, 6][t.parse::<usize>().unwrap()],
374 };
375 let slot = 4 * group + if r.0 == "Stuffing" { 0 } else { usize::from_str_radix(r.1, 2).unwrap() };
376 let (c, n) = val(r.2);
377 assert_eq!(
378 (H263_INTER_MCBPC_CODE[slot] as u32, H263_INTER_MCBPC_BITS[slot] as u32),
379 (c, n)
380 );
381 }
382 for slot in 21..24 {
383 assert_eq!(H263_INTER_MCBPC_BITS[slot], 0);
384 }
385 }
386
387 #[test]
388 fn cbpy_and_mvd_match_tables_12_and_14() {
389 for (i, c) in T12.iter().enumerate() {
390 let (v, n) = val(c);
391 assert_eq!((H263_CBPY_TAB[i][0] as u32, H263_CBPY_TAB[i][1] as u32), (v, n));
392 }
393 for (i, c) in T14.iter().enumerate() {
394 let (v, n) = val(c);
395 assert_eq!((MVTAB[i][0] as u32, MVTAB[i][1] as u32), (v, n));
396 }
397 }
398
399 fn check_rl(rows: &[(u8, i8, i8, &str); 102], vlc: &[[u16; 2]], run: &[i8], level: &[i8], last: usize) {
400 let mut sorted: Vec<_> = rows.to_vec();
401 sorted.sort_by_key(|r| (r.0, r.1, r.2));
402 assert_eq!(sorted.iter().filter(|r| r.0 == 0).count(), last);
403 for (i, r) in sorted.iter().enumerate() {
404 let (v, n) = val(r.3);
405 assert_eq!((vlc[i][0] as u32, vlc[i][1] as u32), (v, n), "entry {i}");
406 assert_eq!((run[i], level[i]), (r.1, r.2), "entry {i}");
407 }
408 let (v, n) = val(T16_ESC);
409 assert_eq!((vlc[102][0] as u32, vlc[102][1] as u32), (v, n));
410 }
411
412 #[test]
413 fn tcoef_matches_tables_16_and_i2() {
414 check_rl(&T16, &INTER_VLC, &INTER_RUN, &INTER_LEVEL, H263_RL_INTER_LAST);
415 check_rl(&TI2, &INTRA_VLC_AIC, &INTRA_RUN_AIC, &INTRA_LEVEL_AIC, RL_INTRA_AIC_LAST);
416 // Table I.2 re-uses the codewords of Table 16 (I.3).
417 let mut a: Vec<_> = T16.iter().map(|r| r.3).collect();
418 let mut b: Vec<_> = TI2.iter().map(|r| r.3).collect();
419 a.sort();
420 b.sort();
421 assert_eq!(a, b);
422 }
423
424 #[test]
425 fn small_tables_match_the_text() {
426 // Table O.4: 0, 10, 111, 110 for CBPC pattern 00, 01, 10, 11.
427 assert_eq!(CBPC_B_TAB, [[0, 1], [2, 2], [7, 3], [6, 3]]);
428 // Annex I.3: RecC = 2 * QUANT * LEVEL.
429 for q in 0..32 {
430 assert_eq!(AIC_DC_SCALE_TABLE[q] as usize, 2 * q);
431 }
432 // Table T.2.
433 for q in 1..32usize {
434 let c = match q {
435 1..=6 => q,
436 7..=9 => q - 1,
437 10..=11 => 9,
438 12..=13 => 10,
439 14..=15 => 11,
440 16..=18 => 12,
441 19..=21 => 13,
442 22..=26 => 14,
443 _ => 15,
444 };
445 assert_eq!(H263_CHROMA_QSCALE_TABLE[q] as usize, c, "QUANT {q}");
446 }
447 // Table T.1: change of QUANT for DQUANT = 10 / 11.
448 for q in 1..32i32 {
449 let (d10, d11) = match q {
450 1 => (2, 1),
451 2..=10 => (-1, 1),
452 11..=20 => (-2, 2),
453 21..=28 => (-3, 3),
454 29 => (-3, 2),
455 30 => (-3, 1),
456 _ => (-3, -5),
457 };
458 assert_eq!(MODIFIED_QUANT_TAB[0][q as usize] as i32, q + d10);
459 assert_eq!(MODIFIED_QUANT_TAB[1][q as usize] as i32, q + d11);
460 }
461 // Table K.2.
462 assert_eq!(MBA_MAX, [47, 98, 395, 1583, 6335, 9215]);
463 assert_eq!(MBA_LENGTH, [6, 7, 9, 11, 13, 14, 14]);
464 // Table 2 (formats) and Table 5 (PAR).
465 assert_eq!(H263_FORMAT[1], [128, 96]);
466 assert_eq!(H263_FORMAT[5], [1408, 1152]);
467 assert_eq!(&H263_PIXEL_ASPECT[1..6], &[[1, 1], [12, 11], [10, 11], [16, 11], [40, 33]]);
468 }
469
470 #[test]
471 fn scans_match_figures() {
472 // Figure 14: first rows of the printed grid (scan positions, 1-based).
473 let fig14: [[u8; 8]; 8] = [
474 [1, 2, 6, 7, 15, 16, 28, 29],
475 [3, 5, 8, 14, 17, 27, 30, 43],
476 [4, 9, 13, 18, 26, 31, 42, 44],
477 [10, 12, 19, 25, 32, 41, 45, 54],
478 [11, 20, 24, 33, 40, 46, 53, 55],
479 [21, 23, 34, 39, 47, 52, 56, 61],
480 [22, 35, 38, 48, 51, 57, 60, 62],
481 [36, 37, 49, 50, 58, 59, 63, 64],
482 ];
483 for (i, &p) in ZIGZAG_DIRECT.iter().enumerate() {
484 assert_eq!(fig14[p as usize / 8][p as usize % 8] as usize, i + 1);
485 }
486 // Figure I.2-a and I.2-b.
487 let a: [[u8; 8]; 8] = [
488 [1, 2, 3, 4, 11, 12, 13, 14],
489 [5, 6, 9, 10, 18, 17, 16, 15],
490 [7, 8, 20, 19, 27, 28, 29, 30],
491 [21, 22, 25, 26, 31, 32, 33, 34],
492 [23, 24, 35, 36, 43, 44, 45, 46],
493 [37, 38, 41, 42, 47, 48, 49, 50],
494 [39, 40, 51, 52, 57, 58, 59, 60],
495 [53, 54, 55, 56, 61, 62, 63, 64],
496 ];
497 let b: [[u8; 8]; 8] = [
498 [1, 5, 7, 21, 23, 37, 39, 53],
499 [2, 6, 8, 22, 24, 38, 40, 54],
500 [3, 9, 20, 25, 35, 41, 51, 55],
501 [4, 10, 19, 26, 36, 42, 52, 56],
502 [11, 18, 27, 31, 43, 47, 57, 61],
503 [12, 17, 28, 32, 44, 48, 58, 62],
504 [13, 16, 29, 33, 45, 49, 59, 63],
505 [14, 15, 30, 34, 46, 50, 60, 64],
506 ];
507 for (i, &p) in ALTERNATE_HORIZONTAL_SCAN.iter().enumerate() {
508 assert_eq!(a[p as usize / 8][p as usize % 8] as usize, i + 1);
509 }
510 for (i, &p) in ALTERNATE_VERTICAL_SCAN.iter().enumerate() {
511 assert_eq!(b[p as usize / 8][p as usize % 8] as usize, i + 1);
512 }
513 }
514}""")
515open(sys.argv[2], "w").write("\n".join(out) + "\n")