forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa63d087Tahinli2 months ago2151 commits

emit_tables.py53 lines, 1.8 KiBHistoryRawDownload
1"""Turn the measured Huffman tables into ec-mp3 source."""
2
3import json
4
5HDR = '''//! Layer III Huffman code tables.
6//!
7//! Every entry here was *measured*, not transcribed: `scripts/mp3-tables.py`
8//! writes legal Layer III frames whose main-data bits it chooses, decodes them
9//! with ffmpeg, and walks each code tree by asking whether all continuations of
10//! a bit prefix decode to the same pair. The result is checked for a Kraft sum
11//! of exactly 1, for full coverage of the value grid, and for uniqueness before
12//! it is written out, so a wrong entry cannot reach this file silently.
13//!
14//! `(length, code)` indexed by `x * dim + y`, where `x` and `y` are the two
15//! (or four, for the count1 tables) values the codeword yields, in the order
16//! they are written to the spectrum.
17
18'''
19
20
21def emit_table(name, entries, dim, nvals):
22 idx = {}
23 for code, vals in entries.items():
24 i = 0
25 for v in vals:
26 i = i * dim + v
27 idx[i] = (len(code), int(code, 2) if code else 0)
28 assert len(idx) == dim ** nvals, (name, len(idx))
29 body = ", ".join(f"({idx[i][0]}, {idx[i][1]})" for i in range(dim ** nvals))
30 return f"static {name}: [(u8, u16); {dim ** nvals}] = [{body}];\n"
31
32
33def main():
34 tabs = json.load(open("huffman.json"))
35 out = [HDR]
36 names = {}
37 for key in ("1", "2", "3", "5", "6", "7", "8", "9", "10", "11", "12",
38 "13", "15", "16", "24"):
39 entries = tabs[key]
40 dim = max(max(v) for v in entries.values()) + 1
41 name = f"T{key}"
42 names[key] = name
43 out.append(emit_table(name, entries, dim, 2))
44 for sel in (0, 1):
45 entries = tabs[f"count1_{sel}"]
46 out.append(emit_table(f"C{sel}", entries, 2, 4))
47 with open("huffman_tables.rs", "w") as f:
48 f.write("\n".join(out))
49 print("wrote huffman_tables.rs")
50
51
52if __name__ == "__main__":
53 main()