forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB237a87fTahinli7 days ago3928 commits

sbrvalues.py182 lines, 6.8 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Reads the delta every 3.0 dB envelope codeword carries off the reference
3decoder's `env_facs_q V is invalid` range check, by ACCUMULATION.
4
5`sbrtables.py --stage values` applies a codeword once to a raw start value and
6reads the delta from the out-of-range complaint. The 3.0 dB books ride a 6-bit
7(5-bit balance) raw field but are checked against a 7-bit ceiling, so a single
8positive 3.0 dB delta never trips it and every one was emitted as 0
9(ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros).
10
11The check sees the ACCUMULATED value, and delta-time coding accumulates across
12envelopes and frames: a `_T` codeword repeated for enough envelopes walks any
13non-zero delta out of range, and a `_F` codeword is walked out by trusted
14negative `_T` steps riding after it. The complaint reports the first value out
15of range (mod 256); a tiny simulator predicts that value for every candidate
16delta and the one candidate that reproduces every probe is the answer. Trusted
17negative entries go through the same readout and must come back unchanged.
18
19Writes the values in place into crates/ec-aac/src/sbr_tables.rs.
20
21 python3 scripts/aac-tables/sbrvalues.py
22"""
23
24import os
25import re
26import sys
27
28HERE = os.path.dirname(os.path.abspath(__file__))
29sys.path.insert(0, HERE)
30import sbrtables as T # noqa: E402
31from sbrprobe import silent # noqa: E402
32
33RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs")
34KINDS = ["ENV30_T", "ENVB30_T", "ENV30_F", "ENVB30_F"]
35INVALID = re.compile(r"env_facs_q (-?\d+) is invalid")
36RUNS = 40
37
38
39def load_books():
40 src = open(RS).read()
41 books = {}
42 for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S):
43 books[m.group(1)] = {
44 (int(a), int(b)): int(c)
45 for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2))
46 }
47 return books
48
49
50def by_value(book, v):
51 return T.as_bits(*next(lc for lc, d in book.items() if d == v))
52
53
54def first_invalid(err):
55 m = INVALID.search(err)
56 return int(m.group(1)) if m else None
57
58
59def simulate(steps, scale, raw):
60 """First out-of-range `scale * value` (mod 256) along `raw + cumsum(steps)`."""
61 acc = raw
62 for s in steps:
63 acc += s
64 v = scale * acc
65 if v < 0 or v > 127:
66 return v % 256
67 return None
68
69
70def probe_t(kind, book, cfg, tables, word, raw, balance):
71 """env0 F-coded from `raw` (no F slots: one band), env1 T-coded with `word`,
72 then RUNS frames with both envelopes T-coded with `word`. ch0 of a coupled
73 pair rides trusted zero words."""
74 key = "env0b" if balance else "env0"
75 start = dict(cfg, **{key: [raw] * 8})
76 run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8})
77 z = by_value(T_BOOK, 0)
78 ch0 = [z] if balance else []
79 frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word])]
80 frames += [T.frame(run, tables, ch0 * 2 + [word, word])] * RUNS
81 return b"".join(frames), [None] + [None] * (2 * RUNS) # steps = word each
82
83
84def probe_f(kind, book, cfg, tables, word, raw, balance, step_book, step):
85 """env0 F-coded from `raw` with `word` in band 1, env1 T-coded with band 0
86 zero and band 1 `step`, then RUNS frames of the same T pair."""
87 key = "env0b" if balance else "env0"
88 start = dict(cfg, df_env=[0, 1] + [0] * 6, **{key: [raw] * 8})
89 run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8})
90 zf, zt = by_value(F_BOOK, 0), by_value(T_BOOK, 0)
91 s = by_value(step_book, step)
92 zs = by_value(T_BOOK if balance else step_book, 0)
93 ch0 = [zf, zt, zt] if balance else []
94 ch0r = [zt, zt, zt, zt] if balance else []
95 frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word, zs, s])]
96 frames += [T.frame(run, tables, ch0r + [zs, s, zs, s])] * 6
97 return b"".join(frames), [None] + [step] * 13
98
99
100def read_book(oracle, kind, books):
101 book = books[kind]
102 balance = kind.startswith("ENVB")
103 scale = 2 if balance else 1
104 span = 12 if balance else 31
105 cands = range(-span, span + 1)
106 cfg, tables = T.recipe_config(kind)
107 raw_max = 31 if balance else 63
108 out = {}
109 for lc in sorted(book):
110 word = T.as_bits(*lc)
111 obs = [] # (steps template, raw, observed)
112 alive = set(cands)
113 # Probe until exactly one candidate reproduces every observation.
114 if kind.endswith("_T"):
115 plan = [("t", raw, None) for raw in range(raw_max, -1, -1)]
116 else:
117 sb = books["ENVB30_T" if balance else "ENV30_T"]
118 neg = sorted({d for d in sb.values() if d < 0})
119 plan = [("f", raw_max, s) for s in neg[:4]] + [("f", 0, s) for s in neg[:4]]
120 for mode, raw, s in plan:
121 if mode == "t":
122 data, steps = probe_t(kind, book, cfg, tables, word, raw, balance)
123 else:
124 data, steps = probe_f(kind, book, cfg, tables, word, raw, balance, sb, s)
125 err = oracle.one(f"acc:{kind}:{lc}:{mode}:{raw}:{s}", data)
126 got = first_invalid(err)
127 alive = {
128 d for d in alive
129 if simulate([d if x is None else x for x in steps], scale, raw) == got
130 }
131 if len(alive) <= 1:
132 break
133 if len(alive) != 1:
134 print(f" {kind} {lc}: UNRESOLVED, candidates {sorted(alive)}")
135 continue
136 d = next(iter(alive))
137 old = book[lc]
138 flag = "" if old == d else (" (was 0)" if old == 0 else f" <-- DISAGREES with {old}")
139 print(f" {kind} {lc}: {d:>4}{flag}")
140 out[lc] = d
141 vals = sorted(out.values())
142 complete = vals == list(cands) and len(out) == len(book)
143 print(f"{kind}: {len(out)}/{len(book)} read, values {'complete -%d..%d once each' % (span, span) if complete else 'NOT a permutation: ' + str(vals)}")
144 return out, complete
145
146
147def main():
148 books = load_books()
149 global F_BOOK, T_BOOK
150 F_BOOK, T_BOOK = books["ENV30_F"], books["ENV30_T"]
151 oracle = T.Oracle(12)
152 out = {}
153 try:
154 for kind in KINDS:
155 vals, complete = read_book(oracle, kind, books)
156 if complete:
157 out[kind] = vals
158 books[kind] = vals # later books ride on these
159 if kind == "ENV30_T":
160 T_BOOK = vals
161 finally:
162 oracle.save()
163 src = open(RS).read()
164
165 def patch_block(m):
166 name, body = m.group(1), m.group(2)
167 if name not in out:
168 return m.group(0)
169 new = re.sub(
170 r"\((\d+), (\d+), (-?\d+)\)",
171 lambda t: f"({t.group(1)}, {t.group(2)}, {out[name][(int(t.group(1)), int(t.group(2)))]})",
172 body,
173 )
174 return m.group(0).replace(body, new)
175
176 src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S)
177 open(RS, "w").write(src)
178 print(f"wrote {RS}: {sorted(out)}")
179
180
181if __name__ == "__main__":
182 main()