forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB48a7da3Tahinli2 months ago2367 commits

derive-aac-tables.py64 lines, 2.6 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Derive the normative AAC-LC tables by black-box probing of a reference decoder.
3
4Clean room: no AAC implementation source is read. The only oracle is ffmpeg's
5`aac` decoder, driven as a black box. Synthetic access units carry a spectral
6payload we choose; decoding them and inverting the MDCT recovers the quantised
7values, and a binary-tree walk over bit prefixes enumerates each codebook.
8
9A bit string `b` is a complete codeword exactly when the first decoded tuple does
10not change if a `0` is appended -- prefix codes are injective, and the filler
11after the codeword is identical in both probes. That makes the walk about `2M`
12probes for `M` codewords, and every codebook it produces is checked against a
13Kraft sum of exactly 1 and the entry count ISO/IEC 14496-3 prescribes, which is
14what makes the derivation self-checking.
15
16The band tables come out the same way: with `max_sfb = k` the highest non-zero
17coefficient is `swb_offset[k] - 1`, and the TNS band limits show up as the
18`max_sfb` at which a filter stops being applied.
19
20Usage: python3 scripts/derive-aac-tables.py [work-dir]
21Writes cb1..cb11.json, sfb.json, swb.json and swb_short.json into the work
22directory, then regenerates crates/ec-aac/src/tables.rs. Needs numpy and ffmpeg.
23"""
24
25import json
26import os
27import subprocess
28import sys
29
30HERE = os.path.dirname(os.path.abspath(__file__))
31MODULES = os.path.join(HERE, "aac-tables")
32CODEBOOKS = [
33 (1, 4, "s"), (2, 4, "s"), (3, 4, "u"), (4, 4, "u"), (5, 2, "s"), (6, 2, "s"),
34 (7, 2, "u"), (8, 2, "u"), (9, 2, "u"), (10, 2, "u"),
35]
36
37
38def run(args, cwd):
39 print("+", " ".join(args), flush=True)
40 subprocess.run([sys.executable, *args], cwd=cwd, check=True)
41
42
43def main():
44 work = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "aac-tables-work")
45 os.makedirs(work, exist_ok=True)
46 for name in os.listdir(MODULES):
47 if name.endswith(".py"):
48 with open(os.path.join(MODULES, name)) as src, \
49 open(os.path.join(work, name), "w") as dst:
50 dst.write(src.read())
51 for cb, dim, signed in CODEBOOKS:
52 run(["learn.py", str(cb), str(dim), signed], work)
53 run(["learn11.py", "11"], work)
54 run(["learn11.py", "sf"], work)
55 run(["swblong.py"], work) if os.path.exists(os.path.join(work, "swblong.py")) else None
56 run(["swbshort.py"], work)
57 out = os.path.join(HERE, "..", "crates", "ec-aac", "src", "tables.rs")
58 run(["gen_tables.py", os.path.abspath(out)], work)
59 with open(os.path.join(work, "cb11.json")) as f:
60 print("cb11 entries:", len(json.load(f)))
61
62
63if __name__ == "__main__":
64 main()