forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

sbrtables.py1399 lines, 55.8 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Derives the ten SBR Huffman codebooks, black box, from a reference decoder.
3
4The instrument is the reference decoder's own bit accounting. An SBR payload
5rides in a FIL element whose declared byte count `cnt` we choose; the decoder
6parses the payload with its own syntax knowledge and complains
7
8 Expected to read <cnt> SBR bytes actually read <n>
9
10whenever `n > cnt`. Declaring `cnt = 1` therefore turns every probe into a
11readout of `n = ceil((4 + bits_the_parser_consumed) / 8)`.
12
13That is byte-granular, and codeword lengths are bits. Two devices sharpen it:
14
15* A configuration with exactly one envelope band (`bs_freq_res = 0` and an
16 `bs_xover_band` chosen so `n_high = 2`) has a payload with *no* Huffman
17 codewords at all -- every bit is one this script wrote. Sweeping such
18 configurations validates the frequency-band derivation (`n_master`, `n_high`,
19 `n_low`, `n_q`) against the decoder without any codebook being known.
20* With the band tables trusted, the same pattern repeated in `m` of the `N - 1`
21 Huffman-coded bands makes the consumed length `K + m * L`; the byte count is a
22 staircase in `m` whose slope pins `L` exactly.
23
24Values come from a second observable in the same probe: the decoder range-checks
25the accumulated envelope and noise scalefactors and says so on stderr. Bisecting
26the raw start value for the point where that complaint appears gives the delta a
27codeword carries, with no audio analysis at all.
28
29Run `--stage sweep` to check the band tables, `--stage lengths` for the prefix
30walk, `--stage values` for the assignment, `--stage all` for the lot; the result
31is written as Rust to crates/ec-aac/src/sbr_tables.rs.
32"""
33
34import argparse
35import json
36import math
37import os
38import re
39import subprocess
40import sys
41from concurrent.futures import ThreadPoolExecutor
42
43HERE = os.path.dirname(os.path.abspath(__file__))
44ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
45sys.path.insert(0, HERE)
46
47from sbrprobe import BitW, adts, sce_core # noqa: E402
48
49CACHE = os.path.join(HERE, "sbr-cache.json")
50
51# ---------------------------------------------------------------- band tables
52
53
54def make_bands(start, stop, num):
55 """`num` band widths geometrically spaced from `start` to `stop`."""
56 base = (stop / start) ** (1.0 / num)
57 prod = float(start)
58 previous = start
59 out = []
60 for _ in range(num - 1):
61 prod *= base
62 present = int(math.floor(prod + 0.5))
63 out.append(present - previous)
64 previous = present
65 out.append(stop - previous)
66 return out
67
68
69# `k0` by SBR sample rate and `bs_start_freq`, measured with `--stage k0`: a
70# header whose reconstruction span exceeds the tool's limit is refused with the
71# span in the message, and `k2` is known from `bs_stop_freq`, so each refusal
72# reads `k0` straight out. The tail every row shares (0, 1, 2 ... 7, 9, 11, 13,
73# 16, 20, 24) continues past the last cell any refusal could reach; those cells
74# are the fitted ones, checked by `--stage fill`.
75K0_OFFSET = {
76 16000: [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7],
77 22050: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13],
78 24000: [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16],
79 32000: [-6, -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16],
80 44100: [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
81 48000: [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
82 64000: [-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20],
83 88200: [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24],
84 96000: [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24],
85}
86
87
88def start_stop_min(rate):
89 """`(start_min, stop_min)`: the QMF band a 3, 4 or 5 kHz border falls in."""
90 temp = 3000 if rate < 32000 else (4000 if rate < 64000 else 5000)
91 return ((temp << 7) + (rate >> 1)) // rate, ((temp << 8) + (rate >> 1)) // rate
92
93
94def span_limit(rate):
95 """The widest `k2 - k0` the tool will reconstruct, measured the same way."""
96 if rate < 32000:
97 return 48
98 return 35 if rate < 64000 else 32
99
100
101def f_master(rate, start_freq, stop_freq, freq_scale, alter_scale):
102 """The master frequency band table (ISO/IEC 14496-3 4.6.18.3.2.1).
103
104 `rate` is the SBR rate: twice the core's. The two band-count rules and the
105 `k0` table are the reference parser's, read off it by `--stage k0` and
106 `--stage sweep`; the shapes are the standard's.
107 """
108 offsets = K0_OFFSET.get(rate)
109 if offsets is None:
110 return None
111 start_min, stop_min = start_stop_min(rate)
112 k0 = start_min + offsets[start_freq]
113 if stop_freq < 14:
114 k2 = stop_min + sum(sorted(make_bands(stop_min, 64, 13))[:stop_freq])
115 elif stop_freq == 14:
116 k2 = 2 * k0
117 else:
118 k2 = 3 * k0
119 k2 = min(k2, 64)
120 if k2 <= k0 or k2 - k0 > span_limit(rate):
121 return None
122
123 if freq_scale == 0:
124 # Bands of a constant width, an even number of them: the count is the
125 # span in whole double-width steps, biased by one step when the width
126 # is doubled. Both edges of that rule are measured, not assumed.
127 dk = 2 if alter_scale else 1
128 num_bands = 2 * ((k2 - k0 + 2 * (dk - 1)) // (2 * dk))
129 if num_bands <= 0:
130 return None
131 vk = [dk] * num_bands
132 k2diff = k2 - k0 - num_bands * dk
133 if k2diff < 0:
134 at, incr = 0, 1
135 else:
136 at, incr = num_bands - 1, -1
137 while k2diff and 0 <= at < num_bands:
138 vk[at] -= incr
139 at += incr
140 k2diff += incr
141 table = [k0]
142 for d in vk:
143 if d <= 0:
144 return None
145 table.append(table[-1] + d)
146 return table
147
148 half_bands = 7 - freq_scale
149 two_regions = 49 * k2 > 110 * k0
150 k1 = 2 * k0 if two_regions else k2
151 num_bands_0 = 2 * int(math.floor(half_bands * math.log2(k1 / k0) + 0.5))
152 if num_bands_0 <= 0:
153 return None
154 vk0 = sorted(make_bands(k0, k1, num_bands_0))
155 vdk0_max = vk0[-1]
156 table = [k0]
157 for d in vk0:
158 if d <= 0:
159 return None
160 table.append(table[-1] + d)
161 if not two_regions:
162 return table
163 invwarp = 1.0 / 1.3 if alter_scale else 1.0
164 num_bands_1 = 2 * int(math.floor(half_bands * invwarp * math.log2(k2 / k1) + 0.5))
165 if num_bands_1 <= 0:
166 return None
167 vk1 = sorted(make_bands(k1, k2, num_bands_1))
168 if vdk0_max > vk1[0]:
169 change = min(vdk0_max - vk1[0], (vk1[-1] - vk1[0]) >> 1)
170 vk1[0] += change
171 vk1[-1] -= change
172 vk1.sort()
173 for d in vk1:
174 if d <= 0:
175 return None
176 table.append(table[-1] + d)
177 return table
178
179
180def freq_tables(rate, cfg):
181 """`(n_master, n_high, n_low, n_q, f_high, f_low, f_noise)` or None."""
182 master = f_master(rate, cfg["start_freq"], cfg["stop_freq"], cfg["freq_scale"], cfg["alter_scale"])
183 if master is None:
184 return None
185 n_master = len(master) - 1
186 xover = cfg["xover_band"]
187 if xover > n_master:
188 return None
189 n_high = n_master - xover
190 if n_high < 1:
191 return None
192 n_low = (n_high + 1) >> 1
193 f_high = master[xover:]
194 f_low = [f_high[0]]
195 if n_high & 1:
196 f_low += [f_high[2 * k - 1] for k in range(1, n_low + 1)]
197 else:
198 f_low += [f_high[2 * k] for k in range(1, n_low + 1)]
199 kx = f_high[0]
200 k2 = master[-1]
201 n_q = max(1, int(math.floor(cfg["noise_bands"] * math.log2(k2 / kx) + 0.5)))
202 if n_q > 5:
203 return None
204 f_noise = [f_low[0]]
205 temp = 0
206 for k in range(1, n_q + 1):
207 temp += (n_low - temp) // (n_q + 1 - k)
208 f_noise.append(f_low[temp])
209 return dict(
210 n_master=n_master, n_high=n_high, n_low=n_low, n_q=n_q,
211 f_high=f_high, f_low=f_low, f_noise=f_noise, kx=kx, k2=k2,
212 )
213
214
215# ------------------------------------------------------------- payload writer
216
217# Stand-in bits for a Huffman position whose codeword this probe does not care
218# about; the parser reads as many as its own syntax says, not as many as these.
219FILL = [0] * 24
220# Raw start value widths: `(balance, amp_res)` for an envelope, and the noise
221# floor's. Measured by `--stage widths`, which reads them off the byte count.
222RAW_ENV = {(0, 0): 7, (0, 1): 6, (1, 0): 6, (1, 1): 5}
223RAW_NOISE = 5
224
225
226def amp_res_of(cfg):
227 """FIXFIX with a single envelope forces the 1.5 dB resolution."""
228 return 0 if cfg["num_env"] == 1 else cfg["amp_res"]
229
230
231def env_kind(cfg, balance, direction):
232 res = "30" if amp_res_of(cfg) else "15"
233 return f"ENV{'B' if balance else ''}{res}_{direction}"
234
235
236def noise_kind(balance, direction):
237 return f"NOISE{'B' if balance else ''}_{direction}"
238
239
240def channel_slots(cfg, tables, balance):
241 """The Huffman slots one channel spends, as `(kind, raw_bits)` steps."""
242 kinds = []
243 raw = 0
244 bands = tables["n_high"] if cfg["freq_res"] else tables["n_low"]
245 for i in range(cfg["num_env"]):
246 if cfg["df_env"][i] == 0:
247 raw += RAW_ENV[(balance, amp_res_of(cfg))]
248 kinds += [env_kind(cfg, balance, "F")] * (bands - 1)
249 else:
250 kinds += [env_kind(cfg, balance, "T")] * bands
251 num_noise = 1 if cfg["num_env"] == 1 else 2
252 for i in range(num_noise):
253 if cfg["df_noise"][i] == 0:
254 raw += RAW_NOISE
255 kinds += [noise_kind(balance, "F")] * (tables["n_q"] - 1)
256 else:
257 kinds += [noise_kind(balance, "T")] * tables["n_q"]
258 return kinds, raw
259
260
261def plan(cfg, tables):
262 """`(kinds, known_bits)`: the codebook of every Huffman slot, in order, and
263 the bits the payload spends outside them."""
264 n = 0
265 if cfg.get("header", 1):
266 n += 1 + 1 + 4 + 4 + 3 + 2 + 1 + 1
267 n += 5 if cfg.get("extra1", 1) else 0
268 n += 6 if cfg.get("extra2", 1) else 0
269 else:
270 n += 1
271 cpe = cfg.get("element", "sce") == "cpe"
272 n += 1 + ((8 if cpe else 4) if cfg.get("data_extra") else 0)
273 channels = [0]
274 if cpe:
275 n += 1 # bs_coupling
276 channels = [0, 1] if cfg.get("coupling", 1) else [0, 1]
277 n += 2 + 2 + 1 # sbr_grid, FIXFIX
278 num_noise = 1 if cfg["num_env"] == 1 else 2
279 n += (cfg["num_env"] + num_noise) * len(channels) # sbr_dtdf per channel
280 n += 2 * tables["n_q"] # sbr_invf, sent once under coupling
281 kinds = []
282 for ch in channels:
283 balance = 1 if (cpe and cfg.get("coupling", 1) and ch == 1) else 0
284 k, raw = channel_slots(cfg, tables, balance)
285 kinds += k
286 n += raw
287 for ch in channels:
288 n += 1 + (tables["n_high"] if cfg.get("add_harmonic", [0, 0])[ch] else 0)
289 n += 1
290 if cfg.get("extended"):
291 n += 4 + 8 * cfg["extended"]
292 return kinds, n
293
294
295def known_bits(cfg, tables):
296 return plan(cfg, tables)[1]
297
298
299def sbr_bits(cfg, tables, words):
300 """The SBR payload as a bit list; `words` fills the Huffman slots in order."""
301 s = BitW()
302 words = list(words)
303
304 def slot():
305 s.wbits(words.pop(0) if words else FILL)
306
307 if cfg.get("header", 1):
308 s.w(1, 1)
309 s.w(cfg["amp_res"], 1)
310 s.w(cfg["start_freq"], 4)
311 s.w(cfg["stop_freq"], 4)
312 s.w(cfg["xover_band"], 3)
313 s.w(0, 2)
314 s.w(1 if cfg.get("extra1", 1) else 0, 1)
315 s.w(1 if cfg.get("extra2", 1) else 0, 1)
316 if cfg.get("extra1", 1):
317 s.w(cfg["freq_scale"], 2)
318 s.w(cfg["alter_scale"], 1)
319 s.w(cfg["noise_bands"], 2)
320 if cfg.get("extra2", 1):
321 s.w(cfg["limiter_bands"], 2)
322 s.w(cfg["limiter_gains"], 2)
323 s.w(cfg["interpol_freq"], 1)
324 s.w(cfg["smoothing_mode"], 1)
325 else:
326 s.w(0, 1)
327 cpe = cfg.get("element", "sce") == "cpe"
328 extra = 1 if cfg.get("data_extra") else 0
329 s.w(extra, 1)
330 if extra:
331 s.w(0, 8 if cpe else 4)
332 if cpe:
333 s.w(1 if cfg.get("coupling", 1) else 0, 1)
334 num_env = cfg["num_env"]
335 num_noise = 1 if num_env == 1 else 2
336 channels = [0, 1] if cpe else [0]
337 s.w(0, 2) # bs_frame_class = FIXFIX
338 s.w(int(math.log2(num_env)), 2)
339 s.w(cfg["freq_res"], 1)
340 for _ in channels:
341 for i in range(num_env):
342 s.w(cfg["df_env"][i], 1)
343 for i in range(num_noise):
344 s.w(cfg["df_noise"][i], 1)
345 for _ in range(tables["n_q"]):
346 s.w(cfg["invf"], 2)
347 for ch in channels:
348 balance = 1 if (cpe and cfg.get("coupling", 1) and ch == 1) else 0
349 bands = tables["n_high"] if cfg["freq_res"] else tables["n_low"]
350 for i in range(num_env):
351 if cfg["df_env"][i] == 0:
352 key = "env0b" if balance else "env0"
353 s.w(cfg[key][i], RAW_ENV[(balance, amp_res_of(cfg))])
354 for _ in range(bands - 1):
355 slot()
356 else:
357 for _ in range(bands):
358 slot()
359 for i in range(num_noise):
360 if cfg["df_noise"][i] == 0:
361 s.w(cfg["noise0b" if balance else "noise0"][i], RAW_NOISE)
362 for _ in range(tables["n_q"] - 1):
363 slot()
364 else:
365 for _ in range(tables["n_q"]):
366 slot()
367 for ch in channels:
368 on = cfg.get("add_harmonic", [0, 0])[ch]
369 s.w(1 if on else 0, 1)
370 if on:
371 for _ in range(tables["n_high"]):
372 s.w(0, 1)
373 if cfg.get("extended"):
374 s.w(1, 1)
375 s.w(cfg["extended"], 4)
376 s.w(0, 8 * cfg["extended"])
377 else:
378 s.w(0, 1)
379 return s
380
381
382DEFAULT = dict(
383 amp_res=0, start_freq=5, stop_freq=3, xover_band=0, freq_scale=0, alter_scale=0,
384 noise_bands=0, limiter_bands=0, limiter_gains=2, interpol_freq=1, smoothing_mode=1,
385 freq_res=0, invf=1, num_env=1, df_env=[0, 0, 0, 0, 0, 0, 0, 0], df_noise=[0, 0],
386 env0=[60] * 8, noise0=[0, 0], env0b=[32] * 8, noise0b=[16, 16],
387 sf_index=7, element="sce", coupling=1,
388 header=1, extra1=1, extra2=1, data_extra=0, add_harmonic=[0, 0], extended=0,
389)
390
391
392def core_element(w, sf_index, max_sfb, channels):
393 """An AAC-LC core element of exactly known length, one or two channels."""
394 if channels == 1:
395 sce_core(w, sf_index, max_sfb)
396 return
397 body = BitW()
398 sce_core(body, sf_index, max_sfb)
399 ics = body.bits[7:] # everything after the element id and instance tag
400 w.w(1, 3).w(0, 4).w(0, 1) # CPE, tag, common_window = 0
401 w.wbits(ics)
402 w.wbits(ics)
403
404
405def frame(cfg, tables, words=(), cnt=1):
406 """One ADTS access unit: an AAC-LC core plus the SBR FIL element."""
407 w = BitW()
408 core_element(w, cfg["sf_index"], 4, 2 if cfg.get("element") == "cpe" else 1)
409 body = sbr_bits(cfg, tables, words)
410 w.w(6, 3) # FIL
411 if cnt >= 15:
412 w.w(15, 4)
413 w.w(cnt - 15 + 1, 8)
414 else:
415 w.w(cnt, 4)
416 w.w(13, 4) # EXT_SBR_DATA
417 w.wbits(body.bits)
418 w.w(7, 3) # END
419 # Slack, so a parser that reads a few bits more than this writer laid down
420 # still has bits to read: what it consumes is the measurement.
421 w.w(0, 32)
422 return adts(w.pack(pad=0), cfg["sf_index"], 2 if cfg.get("element") == "cpe" else 1)
423
424
425# -------------------------------------------------------------------- oracle
426
427READ = re.compile(r"Expected to read (\d+) SBR bytes actually read (\d+)")
428
429
430class Oracle:
431 """Runs the reference decoder on probe frames, with a disk cache."""
432
433 def __init__(self, workers=8):
434 self.workers = workers
435 self.hits = 0
436 self.runs = 0
437 try:
438 with open(CACHE) as f:
439 self.cache = json.load(f)
440 except (OSError, ValueError):
441 self.cache = {}
442
443 def save(self):
444 tmp = CACHE + ".tmp"
445 with open(tmp, "w") as f:
446 json.dump(self.cache, f)
447 os.replace(tmp, CACHE)
448
449 def _run(self, item):
450 serial, key, data = item
451 src = f"/tmp/sbrtables-{os.getpid()}-{serial}.aac"
452 with open(src, "wb") as f:
453 f.write(data)
454 r = subprocess.run(
455 ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"],
456 capture_output=True,
457 )
458 os.remove(src)
459 return key, r.stderr.decode(errors="replace")
460
461 def many(self, items):
462 """`items` is a list of `(key, frame_bytes)`; returns {key: stderr}."""
463 todo = [(k, d) for k, d in items if k not in self.cache]
464 seen = set()
465 uniq = []
466 for k, d in todo:
467 if k not in seen:
468 seen.add(k)
469 uniq.append((k, d))
470 if uniq:
471 numbered = [(i, k, d) for i, (k, d) in enumerate(uniq)]
472 with ThreadPoolExecutor(max_workers=self.workers) as pool:
473 for key, err in pool.map(self._run, numbered):
474 self.cache[key] = err
475 self.runs += 1
476 self.hits += len(items) - len(uniq)
477 return {k: self.cache[k] for k, _ in items}
478
479 def one(self, key, data):
480 return self.many([(key, data)])[key]
481
482
483def bytes_read(err):
484 """The byte count the parser consumed, from its last complaint."""
485 m = READ.findall(err)
486 return int(m[-1][1]) if m else None
487
488
489def probe_frames(cfg, tables, words, reps=2):
490 """A probe file: silence, a header-bearing frame when the probe carries no
491 header of its own, then the probe frames."""
492 from sbrprobe import silent
493
494 out = [silent(cfg["sf_index"])]
495 if not cfg.get("header", 1):
496 lead = dict(cfg, header=1, words=None)
497 _, known = plan(lead, tables)
498 out += [frame(lead, tables, [], cnt=(known + 4 + 7) // 8)]
499 f = frame(cfg, tables, words)
500 return b"".join(out + [f] * reps)
501
502
503def key_for(cfg, tables, words):
504 return json.dumps(
505 [
506 {k: v for k, v in sorted(cfg.items())},
507 [tables["n_high"], tables["n_low"], tables["n_q"]],
508 ["".join(map(str, w)) for w in words],
509 ],
510 sort_keys=True,
511 )
512
513
514def measure(oracle, cases):
515 """`cases` is a list of `(cfg, tables, words)`; returns `(bytes_read, err)`."""
516 items = [(key_for(c, t, w), probe_frames(c, t, w)) for c, t, w in cases]
517 got = oracle.many(items)
518 return [(bytes_read(got[key]), got[key]) for key, _ in items]
519
520
521def predicted(cfg, tables, words):
522 bits = known_bits(cfg, tables) + sum(len(w) for w in words)
523 return (bits + 4 + 7) // 8
524
525
526# ----------------------------------------------------------------- codebooks
527
528KINDS = [
529 "ENV15_F", "ENV15_T", "ENV30_T", "ENV30_F", "NOISE_T", "NOISE_F",
530 "ENVB15_F", "ENVB15_T", "ENVB30_T", "ENVB30_F", "NOISEB_T", "NOISEB_F",
531]
532
533
534# The values the parser assumes when `bs_header_extra_1` is absent. A probe
535# that carries exactly these can drop the field without changing a single
536# derived table, which is what makes the five-bit shift usable as a knob.
537EXTRA1_DEFAULTS = dict(freq_scale=2, alter_scale=1, noise_bands=2)
538
539
540def find_config(sf_index, over, n_high=None, n_low=None, n_q=None, defaults=True):
541 """A header whose derived band tables have the shape a probe needs."""
542 rate = SBR_RATE_FOR_SF[sf_index]
543 scales = (2,) if defaults else (0, 1, 2, 3)
544 alters = (1,) if defaults else (0, 1)
545 noises = (2,) if defaults else (0, 1, 2, 3)
546 for start_freq in range(16):
547 for stop_freq in range(16):
548 for freq_scale in scales:
549 for alter_scale in alters:
550 for noise_bands in noises:
551 base = dict(DEFAULT)
552 base.update(
553 sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq,
554 freq_scale=freq_scale, alter_scale=alter_scale,
555 noise_bands=noise_bands, xover_band=0,
556 )
557 t0 = freq_tables(rate, base)
558 if t0 is None:
559 continue
560 for xover in range(min(8, t0["n_master"])):
561 cfg = dict(base, xover_band=xover)
562 t = freq_tables(rate, cfg)
563 if t is None or t["kx"] > 32:
564 continue
565 if n_high is not None and t["n_high"] != n_high:
566 continue
567 if n_low is not None and t["n_low"] != n_low:
568 continue
569 if n_q is not None and t["n_q"] != n_q:
570 continue
571 cfg.update(over)
572 return cfg, t
573 return None
574
575
576# One probe per codebook. Each is a payload in which the slots of that
577# codebook come last and everything before them is either a field this script
578# wrote or a codeword already derived: the bits the parser spends past the
579# known part are the codeword under test, and nothing else.
580RECIPES = {
581 "ENV15_F": dict(over=dict(num_env=1, amp_res=0, df_env=[0] * 8, df_noise=[0, 0],
582 freq_res=1, element="sce"), n_high=2, n_q=1),
583 "ENV15_T": dict(over=dict(num_env=2, amp_res=0, df_env=[0, 1] + [0] * 6,
584 df_noise=[0, 0], freq_res=0, element="sce"),
585 n_high=2, n_low=1, n_q=1),
586 "ENV30_T": dict(over=dict(num_env=2, amp_res=1, df_env=[0, 1] + [0] * 6, env0=[32] * 8,
587 env0b=[16] * 8, df_noise=[0, 0], freq_res=0, element="sce"),
588 n_high=2, n_low=1, n_q=1),
589 "ENV30_F": dict(over=dict(num_env=2, amp_res=1, df_env=[0] * 8, df_noise=[0, 0], env0=[32] * 8,
590 env0b=[16] * 8, freq_res=1, element="sce"), n_high=2, n_q=1),
591 "NOISE_T": dict(over=dict(num_env=2, amp_res=0, df_env=[0] * 8, df_noise=[0, 1],
592 freq_res=0, element="sce"), n_high=2, n_low=1, n_q=1),
593 "NOISE_F": dict(over=dict(num_env=2, amp_res=0, df_env=[0] * 8, df_noise=[0, 0],
594 freq_res=0, element="sce"), n_q=2),
595 "ENVB15_F": dict(over=dict(num_env=1, amp_res=0, df_env=[0] * 8, df_noise=[0, 0],
596 freq_res=1, element="cpe", coupling=1), n_high=2, n_q=1),
597 "ENVB15_T": dict(over=dict(num_env=2, amp_res=0, df_env=[0, 1] + [0] * 6,
598 df_noise=[0, 0], freq_res=0, element="cpe", coupling=1),
599 n_high=2, n_low=1, n_q=1),
600 "ENVB30_T": dict(over=dict(num_env=2, amp_res=1, df_env=[0, 1] + [0] * 6, env0=[32] * 8,
601 env0b=[16] * 8, df_noise=[0, 0], freq_res=0, element="cpe", coupling=1),
602 n_high=2, n_low=1, n_q=1),
603 "ENVB30_F": dict(over=dict(num_env=2, amp_res=1, df_env=[0] * 8, df_noise=[0, 0], env0=[32] * 8,
604 env0b=[16] * 8, freq_res=1, element="cpe", coupling=1), n_high=2, n_q=1),
605 "NOISEB_T": dict(over=dict(num_env=2, amp_res=0, df_env=[0] * 8, df_noise=[0, 1],
606 freq_res=0, element="cpe", coupling=1),
607 n_low=2, n_q=1),
608 "NOISEB_F": dict(over=dict(num_env=2, amp_res=0, df_env=[0] * 8, df_noise=[0, 0],
609 freq_res=0, element="cpe", coupling=1), n_q=2),
610}
611
612
613def recipe_config(kind, sf_index=7):
614 r = RECIPES[kind]
615 found = find_config(sf_index, r["over"], n_high=r.get("n_high"),
616 n_low=r.get("n_low"), n_q=r.get("n_q"))
617 if found is None:
618 found = find_config(sf_index, r["over"], n_high=r.get("n_high"),
619 n_low=r.get("n_low"), n_q=r.get("n_q"), defaults=False)
620 if found is None:
621 return None
622 cfg, tables = found
623 kinds, _ = plan(cfg, tables)
624 if not kinds or kinds[-1] != kind:
625 return None
626 return cfg, tables
627
628
629def knob_variants(cfg, tables):
630 """Payloads that differ only in fields of a size this script knows.
631
632 A byte count pins the bits the parser read to within a byte; shifting the
633 payload by 4, 5 and 6 bits and reading the count again pins it exactly.
634 None of these knobs changes the frequency tables or the slots.
635 """
636 out = []
637 base = known_bits(cfg, tables)
638 can_drop_extra1 = all(cfg[k] == v for k, v in EXTRA1_DEFAULTS.items())
639 # Only fields *before* the slot under test can serve as a knob: the parser
640 # stops inside the padded slot word, so everything this script writes after
641 # it sits at an offset the parser never reaches.
642 for data_extra in (0, 1):
643 for extra2 in (1, 0):
644 for extra1 in ((1, 0) if can_drop_extra1 else (1,)):
645 v = dict(cfg, data_extra=data_extra, extra2=extra2, extra1=extra1)
646 delta = known_bits(v, tables) - base
647 out.append((v, delta))
648 seen = set()
649 uniq = []
650 for v, delta in out:
651 if delta % 8 in seen:
652 continue
653 seen.add(delta % 8)
654 uniq.append((v, delta))
655 return uniq
656
657
658# A decoded value the tool refuses is a value it never finished reading, so a
659# probe that says this measured nothing.
660BAD_VALUE = re.compile(r"is invalid|out of range|overflow|SBR reset failed")
661
662# Raw start values to try: a noise floor's accumulated value has no centre that
663# survives both ends of its table (0 and 30 are the limits the tool enforces),
664# so both ends are tried and the probe it does not refuse is the one that
665# measured something.
666# A balance value is checked doubled (a coupled channel's noise floor is the
667# base channel's combined with the ratio the balance value codes), so 16 -- the
668# middle of the raw field -- can already read as 32 and refuse on its own,
669# before the codeword under test ever contributes: the extra, smaller-magnitude
670# pairs are the fallback once that is observed (`exact_bits` requires a sane
671# 1..32 answer, not just an unrefused one).
672RAW_TRIES = [(0, 16), (30, 16), (0, 0), (30, 30), (8, 8), (0, 8), (8, 0)]
673
674
675def as_bits(length, code):
676 return [(code >> (length - 1 - i)) & 1 for i in range(length)]
677
678
679def filler(books, kind, extra=0):
680 """A derived codeword of this book, `extra` bits longer than its shortest.
681
682 Swapping one filler for a longer one shifts the payload by a known number of
683 bits, which is the knob a coupled probe would otherwise lack.
684 """
685 if kind not in books:
686 return None
687 lengths = sorted({l for l, _ in books[kind]})
688 want = lengths[0] + extra
689 for length, code in sorted(books[kind]):
690 if length == want:
691 return as_bits(length, code)
692 return None
693
694
695def fill_words(cfg, tables, kind, word, books, extra=0):
696 """Slot words: `word` in the last slot of `kind`, derived codewords before."""
697 kinds, _ = plan(cfg, tables)
698 last = max(i for i, k in enumerate(kinds) if k == kind)
699 # An envelope value has room for any delta its table holds, so swapping an
700 # envelope filler is safe; a noise floor's does not, so it is a last resort.
701 order = [i for i, k in enumerate(kinds) if i != last and k.startswith("ENV")]
702 order += [i for i, k in enumerate(kinds) if i != last and not k.startswith("ENV")]
703 swap_at = None
704 for i in order:
705 if filler(books, kinds[i], extra) is not None:
706 swap_at = i
707 break
708 words = []
709 shifted = not extra
710 for i, k in enumerate(kinds):
711 if i == last:
712 words.append(list(word))
713 continue
714 if not shifted and i == swap_at:
715 got = filler(books, k, extra)
716 if got is not None:
717 words.append(got)
718 shifted = True
719 continue
720 got = filler(books, k, 0)
721 if got is None:
722 return None
723 words.append(got)
724 return words if shifted else None
725
726
727def exact_bits(oracle, cfg, tables, kind, word, books):
728 """The length of the codeword `word` starts with, exactly.
729
730 A byte count pins the bits the parser read to within a byte. Shifting the
731 payload ahead of the slot -- by dropping a header group, by adding the
732 reserved data-extra field, or by swapping one already-derived filler
733 codeword for a longer one -- and reading the count again pins it exactly.
734 """
735 knobs = knob_variants(cfg, tables)
736 cases = []
737 residues = set()
738 for extra in range(0, 8):
739 words = fill_words(cfg, tables, kind, word, books, extra)
740 if words is None:
741 continue
742 for v, _delta in knobs:
743 base = known_bits(v, tables) + sum(len(w) for w in words[:-1])
744 cases.append((v, words, base))
745 residues.add(base % 8)
746 if len(residues) == 8:
747 break
748 if len(residues) < 8:
749 return None
750 # Refusing a value stops the parse right after the codeword that carried
751 # it, so the fields the payload spends after the slot go unread: that is a
752 # measurement too, of the same codeword, with a known amount less around it.
753 trailing = 1 + (2 if cfg.get("element") == "cpe" else 1)
754 for noise0, noise0b in RAW_TRIES:
755 tries = [(dict(v, noise0=[noise0] * 2, noise0b=[noise0b] * 2), w, b)
756 for v, w, b in cases]
757 got = measure(oracle, [(v, tables, w) for v, w, _ in tries])
758 lo, hi, bad = -10 ** 6, 10 ** 6, False
759 for (_v, _w, base), (n, err) in zip(tries, got):
760 if n is None:
761 bad = True
762 break
763 top = 8 * n - 4 - base + (trailing if BAD_VALUE.search(err) else 0)
764 lo, hi = max(lo, top - 7), min(hi, top)
765 if not bad and lo == hi and 1 <= lo <= 32:
766 return lo
767 return None
768
769
770def walk(oracle, kind, cfg, tables, books, verbose=True):
771 """Enumerates a complete prefix code by walking its intervals.
772
773 A complete code tiles the unit interval: the codeword at `cur` is the first
774 `L` bits of `cur`, and the next one starts at `cur + 2^-L`. One length
775 measurement per codeword enumerates the whole book, and the walk landing
776 exactly on 1 is the completeness check.
777 """
778 codes = []
779 cur, depth, kraft = 0, 0, 0.0
780 while True:
781 bits = [(cur >> (depth - 1 - i)) & 1 for i in range(depth)]
782 length = exact_bits(oracle, cfg, tables, kind, bits + [0] * 32, books)
783 if length is None and kraft < 1.0:
784 # A complete code ends on a single interval, and its width is the
785 # last codeword's length: that one needs no probe.
786 rest = 1.0 - kraft
787 exact = int(round(math.log2(1.0 / rest)))
788 if abs(rest - 2.0 ** -exact) < 1e-12 and 1 <= exact <= 32:
789 length = exact
790 if verbose:
791 print(f" {kind}: last codeword closed by completeness at {exact} bits")
792 if length is None or not 1 <= length <= 32:
793 print(f" {kind}: no length after {len(codes)} at "
794 f"{''.join(map(str, bits)) or '(empty)'}: {length}")
795 return None
796 while depth < length:
797 cur <<= 1
798 depth += 1
799 codes.append((length, cur >> (depth - length)))
800 kraft += 2.0 ** -length
801 cur += 1 << (depth - length)
802 while depth and cur % 2 == 0:
803 cur >>= 1
804 depth -= 1
805 if depth == 0 and cur >= 1:
806 break
807 if len(codes) > 200:
808 print(f" {kind}: walk did not close")
809 return None
810 if verbose:
811 print(f" {kind}: {len(codes)} codewords, Kraft {kraft:.9f}, lengths "
812 f"{min(l for l, _ in codes)}..{max(l for l, _ in codes)}")
813 return codes
814
815
816def bootstrap(oracle, kind, cfg, tables, books, span=(1, 33)):
817 """The first codeword of a book, when there is no filler for it yet.
818
819 Every slot of the kind carries the same candidate word, so the length that
820 explains the bit count is the one the parser actually read.
821 """
822 kinds, _ = plan(cfg, tables)
823 if kinds.count(kind) == 1:
824 books[kind] = [(1, 0)]
825 return True
826 for length in range(span[0], span[1]):
827 books[kind] = [(length, 0)]
828 if exact_bits(oracle, cfg, tables, kind, [0] * 33, books) == length:
829 return True
830 books.pop(kind, None)
831 return False
832
833
834def stage_books(oracle, sf_index=7, only=None, books=None):
835 """Derives every codebook, each with the ones it leans on already in hand."""
836 books = books if books is not None else {}
837 out = {}
838 for kind in KINDS:
839 if only and kind not in only:
840 continue
841 made = recipe_config(kind, sf_index)
842 if made is None:
843 print(f" {kind}: no configuration")
844 continue
845 cfg, tables = made
846 kinds, _ = plan(cfg, tables)
847 missing = {k for k in kinds if k != kind and k not in books}
848 if missing:
849 print(f" {kind}: needs {sorted(missing)} first")
850 continue
851 if not bootstrap(oracle, kind, cfg, tables, books):
852 print(f" {kind}: no bootstrap codeword")
853 continue
854 codes = walk(oracle, kind, cfg, tables, books)
855 if codes is None:
856 books.pop(kind, None)
857 continue
858 out[kind] = books[kind] = codes
859 return out
860
861
862# -------------------------------------------------------------- values stage
863
864# `env_facs_q`/`noise_facs_q` are the reference decoder's own accumulated
865# scalefactor: it prints the value it computed the instant that value leaves
866# the valid range, which is `raw + delta` for a plain codebook or, measured
867# below, `2 * (raw + delta)` for a balance one (the coupled channel's value is
868# reconstructed from double the coded ratio). Placing the codeword under test
869# at `raw = 0` and at the field's own maximum brackets every delta the ten
870# tables carry: a delta that overflows high is read straight off the
871# maximum-raw probe, a delta that overflows low wraps through the decoder's
872# own byte-sized accumulator and is read off the zero-raw probe once
873# unwrapped -- the write-up above is what pins the wrap width at 256 and the
874# scale at 1 or 2, not an assumption.
875VALUE_RE_CACHE = {}
876
877
878def value_re(field):
879 if field not in VALUE_RE_CACHE:
880 VALUE_RE_CACHE[field] = re.compile(rf"{field} (-?\d+) is invalid")
881 return VALUE_RE_CACHE[field]
882
883
884def values_config(kind, sf_index=7):
885 """A config in which `kind` carries exactly one codeword, plus the raw
886 field/width/scale that codeword's delta is read against."""
887 balance = kind.startswith("ENVB") or kind.startswith("NOISEB")
888 is_env = kind.startswith("ENV")
889 amp_res = 1 if "30" in kind else 0
890 scale = 2 if balance else 1
891 element = "cpe" if balance else "sce"
892 if kind.endswith("_F"):
893 if is_env:
894 if amp_res:
895 # `amp_res_of` forces the 1.5 dB resolution whenever there is
896 # only one envelope, so a lone envelope can never carry the
897 # 3 dB book: a second envelope (T-coded, already closed) has
898 # to ride along to keep the resolution at 3 dB.
899 over = dict(element=element, coupling=1, num_env=2, amp_res=1,
900 df_env=[0, 1] + [0] * 6, df_noise=[0, 0], freq_res=1)
901 else:
902 over = dict(element=element, coupling=1, num_env=1, amp_res=amp_res,
903 df_env=[0] * 8, df_noise=[0, 0], freq_res=1)
904 found = find_config(sf_index, over, n_high=2, n_q=1)
905 key, width = ("env0b" if balance else "env0"), RAW_ENV[(1 if balance else 0, amp_res)]
906 else:
907 over = dict(element=element, coupling=1, num_env=1, amp_res=0,
908 df_env=[0] * 8, df_noise=[0, 0], freq_res=0)
909 found = find_config(sf_index, over, n_q=2)
910 key, width = ("noise0b" if balance else "noise0"), RAW_NOISE
911 if found is None:
912 return None
913 cfg, tables = found
914 else:
915 found = recipe_config(kind, sf_index)
916 if found is None:
917 return None
918 cfg, tables = found
919 if is_env:
920 key, width = ("env0b" if balance else "env0"), RAW_ENV[(1 if balance else 0, amp_res_of(cfg))]
921 else:
922 key, width = ("noise0b" if balance else "noise0"), RAW_NOISE
923 kinds, _ = plan(cfg, tables)
924 if kinds.count(kind) != 1:
925 return None
926 return cfg, tables, key, width, scale
927
928
929def book_values(oracle, kind, cfg, tables, key, width, scale, books):
930 """`{(length, code): delta}` for every codeword `stage_books` found."""
931 codes = sorted(books[kind])
932 raw_max = (1 << width) - 1
933 field = "env_facs_q" if kind.startswith("ENV") else "noise_facs_q"
934 pat = value_re(field)
935 cases, meta = [], []
936 for length, code in codes:
937 # The exact codeword, no trailing pad: `stage_books` already closed the
938 # length for every codeword here, so (unlike the length-search bisection,
939 # which pads because the length is what it is looking for) padding would
940 # only shift every field after this slot and desync the frame.
941 word = as_bits(length, code)
942 words = fill_words(cfg, tables, kind, word, books, extra=0)
943 if words is None:
944 continue
945 for raw in (0, raw_max):
946 v = dict(cfg)
947 arr = list(v[key])
948 arr[0] = raw
949 v[key] = arr
950 cases.append((v, tables, words))
951 meta.append((length, code, raw))
952 got = measure(oracle, cases)
953 seen = {}
954 crashed = set()
955 clean = set()
956 for (length, code, raw), (v, t, w), (n, err) in zip(meta, cases, got):
957 m = pat.search(err)
958 if not m:
959 # Not a range-check complaint: either a clean decode (only the
960 # routine byte-count line) or the parser aborting the element for
961 # an unrelated reason -- only the former licenses the "both ends
962 # valid" inference below, so the two are told apart here. The
963 # "channel element 0.1 is not allocated" complaint fires on every
964 # mono probe regardless of whether the codeword itself was in
965 # range (the reference decoder treats HE-AAC mono as implicit
966 # stereo and always misses the second channel element), so it
967 # carries no information; the byte count the parser actually
968 # consumed against the full predicted frame length is the real
969 # discriminator -- an undershoot is a genuine early abort.
970 if n == predicted(v, t, w):
971 clean.add((length, code))
972 else:
973 crashed.add((length, code))
974 continue
975 val = int(m.group(1))
976 if raw == 0:
977 v = val % 256
978 if v > 128:
979 v -= 256
980 if v % scale:
981 continue
982 delta = v // scale
983 else:
984 if val % scale:
985 continue
986 delta = val // scale - raw
987 seen.setdefault((length, code), set()).add(delta)
988 values, gaps = {}, []
989 for length, code in codes:
990 vs = seen.get((length, code))
991 if not vs:
992 if (length, code) in clean and (length, code) not in crashed:
993 # Neither end complained and neither crashed either: the
994 # codeword's delta and the raw value it rides with both
995 # stayed inside `[0, raw_max]`, which only `delta = 0` can do
996 # at *both* ends of the field at once.
997 values[(length, code)] = 0
998 else:
999 gaps.append((length, code, "crashed" if (length, code) in crashed else "no signal"))
1000 continue
1001 if len(vs) > 1:
1002 gaps.append((length, code, vs))
1003 continue
1004 values[(length, code)] = next(iter(vs))
1005 return values, gaps
1006
1007
1008def stage_values(oracle, books, sf_index=7):
1009 """Assigns the delta value every codeword of every closed book carries."""
1010 values = {}
1011 for kind in KINDS:
1012 if kind not in books:
1013 print(f" {kind}: no lengths, skipped")
1014 continue
1015 made = values_config(kind, sf_index)
1016 if made is None:
1017 print(f" {kind}: no single-codeword configuration for values")
1018 continue
1019 cfg, tables, key, width, scale = made
1020 vals, gaps = book_values(oracle, kind, cfg, tables, key, width, scale, books)
1021 if gaps:
1022 print(f" {kind}: {len(gaps)}/{len(books[kind])} codewords unresolved: {gaps[:5]}")
1023 if len(vals) == len(books[kind]):
1024 values[kind] = vals
1025 lo, hi = min(vals.values()), max(vals.values())
1026 print(f" {kind}: {len(vals)} values, range {lo}..{hi}")
1027 else:
1028 print(f" {kind}: incomplete ({len(vals)}/{len(books[kind])}), not emitted")
1029 return values
1030
1031
1032def write_rust(books, values, path=None):
1033 """Emits the closed, fully-valued books as `crates/ec-aac/src/sbr_tables.rs`."""
1034 path = path or os.path.join(ROOT, "crates", "ec-aac", "src", "sbr_tables.rs")
1035 ready = [k for k in KINDS if k in books and k in values and len(values[k]) == len(books[k])]
1036 skipped = [k for k in KINDS if k not in ready]
1037 lines = [
1038 "//! SBR (HE-AAC v1) Huffman codebooks (ISO/IEC 14496-3 §4.6.18.3.6).",
1039 "//!",
1040 "//! Derived black box from a reference decoder's own bit accounting by",
1041 "//! `scripts/aac-tables/sbrtables.py`: no source was consulted. The",
1042 "//! decoder's \"Expected to read N SBR bytes actually read M\" complaint",
1043 "//! reads codeword lengths off a controlled FIL payload, and its",
1044 "//! `env_facs_q`/`noise_facs_q` range check reads the delta value each",
1045 "//! codeword carries off the same payload. Every table here closed with",
1046 "//! a Kraft sum of exactly 1 (asserted below).",
1047 "#![allow(dead_code)]",
1048 "",
1049 ]
1050 if skipped:
1051 lines.append(f"// Not emitted (values incomplete or book did not close): {skipped}")
1052 lines.append("")
1053 for kind in ready:
1054 codes = sorted(books[kind])
1055 vals = values[kind]
1056 lines.append(f"/// SBR Huffman book `{kind}`: (length, code, delta) by codeword.")
1057 lines.append(f"pub(crate) static {kind}: [(u8, u32, i32); {len(codes)}] = [")
1058 for length, code in codes:
1059 lines.append(f" ({length}, {code}, {vals[(length, code)]}),")
1060 lines.append("];")
1061 lines.append("")
1062 lines.append("#[cfg(test)]")
1063 lines.append("mod tests {")
1064 lines.append(" use super::*;")
1065 lines.append("")
1066 lines.append(" fn kraft_is_one(codes: &[(u8, u32, i32)]) {")
1067 lines.append(" let sum: f64 = codes.iter().map(|&(l, _, _)| 2f64.powi(-(l as i32))).sum();")
1068 lines.append(" assert!((sum - 1.0).abs() < 1e-9, \"Kraft sum {sum}\");")
1069 lines.append(" }")
1070 lines.append("")
1071 lines.append(" fn is_prefix_free(codes: &[(u8, u32, i32)]) {")
1072 lines.append(" for (i, &(li, ci, _)) in codes.iter().enumerate() {")
1073 lines.append(" for &(lj, cj, _) in codes.iter().skip(i + 1) {")
1074 lines.append(" let (short, long) = if li <= lj { (li, lj) } else { (lj, li) };")
1075 lines.append(" let (sc, lc) = if li <= lj { (ci, cj) } else { (cj, ci) };")
1076 lines.append(" assert_ne!(sc, lc >> (long - short), \"{ci:?} prefixes {cj:?}\");")
1077 lines.append(" }")
1078 lines.append(" }")
1079 lines.append(" }")
1080 lines.append("")
1081 for kind in ready:
1082 lines.append(" #[test]")
1083 lines.append(f" fn {kind.lower()}_is_a_complete_prefix_code() {{")
1084 lines.append(f" kraft_is_one(&{kind});")
1085 lines.append(f" is_prefix_free(&{kind});")
1086 lines.append(" }")
1087 lines.append("")
1088 lines.append("}")
1089 with open(path, "w") as f:
1090 f.write("\n".join(lines) + "\n")
1091 print(f"wrote {path}: {len(ready)} books, {len(skipped)} skipped")
1092 return ready, skipped
1093
1094
1095# ---------------------------------------------------------------- raw widths
1096
1097WIDTH_VARS = ["E00", "E01", "E10", "E11", "N0", "N1"]
1098
1099
1100def width_cases(sf_index=7):
1101 """Configurations with no Huffman slot at all, and what they spend on raw
1102 start values -- the widths are the only thing in them this script guesses."""
1103 out = []
1104 combos = [
1105 # Four envelopes still carry two noise floors, which is what separates
1106 # an envelope's raw width from a noise floor's. Eight is refused: the
1107 # tool caps a FIXFIX frame's envelope count below that.
1108 ("sce", 4, 0, {"E00": 4, "N0": 2}),
1109 ("sce", 4, 1, {"E01": 4, "N0": 2}),
1110 ("cpe", 4, 0, {"E00": 4, "N0": 2, "E10": 4, "N1": 2}),
1111 ("cpe", 4, 1, {"E01": 4, "N0": 2, "E11": 4, "N1": 2}),
1112 ("sce", 1, 0, {"E00": 1, "N0": 1}),
1113 ("sce", 2, 0, {"E00": 2, "N0": 2}),
1114 ("sce", 2, 1, {"E01": 2, "N0": 2}),
1115 ("cpe", 1, 0, {"E00": 1, "N0": 1, "E10": 1, "N1": 1}),
1116 ("cpe", 2, 0, {"E00": 2, "N0": 2, "E10": 2, "N1": 2}),
1117 ("cpe", 2, 1, {"E01": 2, "N0": 2, "E11": 2, "N1": 2}),
1118 ]
1119 for element, num_env, amp_res, coeff in combos:
1120 over = dict(element=element, coupling=1, num_env=num_env, amp_res=amp_res,
1121 df_env=[0] * 8, df_noise=[0, 0], freq_res=0)
1122 found = find_config(sf_index, over, n_high=2, n_low=1, n_q=1)
1123 if found is None:
1124 continue
1125 cfg, tables = found
1126 assert not plan(cfg, tables)[0], "width probe must have no Huffman slot"
1127 for knob in ({}, {"add_harmonic": [1, 0]}, {"add_harmonic": [1, 1]},
1128 {"extended": 1}, {"extended": 1, "add_harmonic": [1, 0]},
1129 {"data_extra": 1}, {"header": 0}):
1130 v = dict(cfg, **knob)
1131 out.append((v, tables, coeff))
1132 return out
1133
1134
1135def stage_widths(oracle, sf_index=7):
1136 """Solves the raw start value widths against the byte counts."""
1137 global RAW_ENV, RAW_NOISE
1138 cases = width_cases(sf_index)
1139 # The widths themselves are what the probe is measuring, so they must not
1140 # enter the prediction: zero them while the equations are built.
1141 guess = dict(E00=RAW_ENV[(0, 0)], E01=RAW_ENV[(0, 1)], E10=RAW_ENV[(1, 0)],
1142 E11=RAW_ENV[(1, 1)], N0=RAW_NOISE, N1=RAW_NOISE)
1143 got = measure(oracle, [(c, t, []) for c, t, _ in cases])
1144 eqs = []
1145 for (cfg, tables, coeff), (n, err) in zip(cases, got):
1146 if n is None:
1147 continue
1148 # The written payload keeps the guessed widths -- what it holds cannot
1149 # change what the parser reads -- so only the prediction drops them.
1150 base = known_bits(cfg, tables) - sum(c * guess[k] for k, c in coeff.items())
1151 eqs.append((coeff, 8 * n - 4 - base - 7, 8 * n - 4 - base))
1152 best = []
1153 ranges = range(3, 10)
1154 for e00 in ranges:
1155 for e01 in ranges:
1156 for e10 in ranges:
1157 for e11 in ranges:
1158 for n0 in ranges:
1159 for n1 in ranges:
1160 v = dict(E00=e00, E01=e01, E10=e10, E11=e11, N0=n0, N1=n1)
1161 if all(lo <= sum(c * v[k] for k, c in coeff.items()) <= hi
1162 for coeff, lo, hi in eqs):
1163 best.append(v)
1164 print(f"widths: {len(eqs)} equations, {len(best)} solutions: {best[:4]}")
1165 if len(best) == 1:
1166 v = best[0]
1167 RAW_ENV = {(0, 0): v["E00"], (0, 1): v["E01"], (1, 0): v["E10"], (1, 1): v["E11"]}
1168 RAW_NOISE = v["N0"]
1169 if v["N1"] != v["N0"]:
1170 print(f" balance noise raw width differs: {v['N1']} vs {v['N0']}")
1171 return best
1172
1173
1174# ---------------------------------------------------------------- stage sweep
1175
1176
1177def one_band_cfg(rate, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, sf_index):
1178 """A configuration whose payload holds no Huffman codeword at all.
1179
1180 `bs_xover_band` is chosen so `n_high` is 2, which with `bs_freq_res = 0`
1181 leaves a single envelope band: the raw start value and nothing else.
1182 """
1183 cfg = dict(DEFAULT)
1184 cfg.update(
1185 start_freq=start_freq, stop_freq=stop_freq, freq_scale=freq_scale,
1186 alter_scale=alter_scale, noise_bands=noise_bands, sf_index=sf_index,
1187 )
1188 probe = dict(cfg, xover_band=0)
1189 t = freq_tables(rate, probe)
1190 if t is None or t["n_master"] < 2:
1191 return None
1192 xover = t["n_master"] - 2
1193 if xover > 7:
1194 return None
1195 cfg["xover_band"] = xover
1196 t = freq_tables(rate, cfg)
1197 if t is None or t["n_high"] != 2 or t["n_low"] != 1 or t["n_q"] != 1:
1198 return None
1199 # The core is analysed with 32 QMF bands, so a crossover above band 32 is
1200 # refused: measured, and the reason several sweep cells used to disagree.
1201 if t["kx"] > 32:
1202 return None
1203 return cfg, t
1204
1205
1206def stage_sweep(oracle, verbose=True):
1207 """Checks the band derivation against the decoder, over many headers."""
1208 cases = []
1209 for sf_index, rate in sorted(SBR_RATE_FOR_SF.items()):
1210 for start_freq in range(0, 16):
1211 for stop_freq in (0, 2, 4, 6, 8, 10, 12, 13, 14, 15):
1212 for freq_scale in (0, 1, 2, 3):
1213 for alter_scale in (0, 1):
1214 for noise_bands in (0, 1, 2, 3):
1215 made = one_band_cfg(
1216 rate, start_freq, stop_freq, freq_scale,
1217 alter_scale, noise_bands, sf_index,
1218 )
1219 if made:
1220 cases.append(made)
1221 if verbose:
1222 print(f"sweep: {len(cases)} single-band configurations")
1223 got = measure(oracle, [(c, t, []) for c, t in cases])
1224 bad = 0
1225 for (cfg, t), (n, err) in zip(cases, got):
1226 want = predicted(cfg, t, [])
1227 if n != want:
1228 bad += 1
1229 if bad < 15 and verbose:
1230 print(
1231 f" MISMATCH rate_sf={cfg['sf_index']} start={cfg['start_freq']} "
1232 f"stop={cfg['stop_freq']} scale={cfg['freq_scale']} alter={cfg['alter_scale']} "
1233 f"nb={cfg['noise_bands']} xover={cfg['xover_band']}: want {want} got {n} "
1234 f"n_master={t['n_master']} :: {err.strip()[:120]}"
1235 )
1236 print(f"sweep: {len(cases) - bad}/{len(cases)} configurations agree with the reference parser")
1237 return bad == 0
1238
1239
1240SBR_RATE_FOR_SF = {11: 16000, 10: 22050, 9: 24000, 8: 32000, 7: 44100, 6: 48000, 5: 64000, 4: 88200, 3: 96000}
1241
1242
1243def stop_table(rate):
1244 """`k2` for each `bs_stop_freq` below 14 (4.6.18.3.2.1)."""
1245 stop_min = start_stop_min(rate)[1]
1246 widths = sorted(make_bands(stop_min, 64, 13))
1247 out = [stop_min]
1248 for w in widths:
1249 out.append(out[-1] + w)
1250 return out
1251
1252
1253def stage_k0(oracle):
1254 """Measures `k0` for every rate and `bs_start_freq`, from the decoder.
1255
1256 A header whose reconstruction span `k2 - k0` exceeds what the tool allows is
1257 refused with the span itself in the message, and `k2` follows from
1258 `bs_stop_freq` alone: one refusal per configuration therefore reads `k0`
1259 straight out, and the several `bs_stop_freq` values that all refuse have to
1260 agree on it, which is the check that the stop table is right too.
1261 """
1262 span = re.compile(r"too many QMF subbands: (\d+)")
1263 cases = []
1264 for sf_index, rate in sorted(SBR_RATE_FOR_SF.items()):
1265 for start_freq in range(16):
1266 for stop_freq in (10, 11, 12, 13):
1267 cfg = dict(DEFAULT)
1268 cfg.update(sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq)
1269 cases.append((cfg, dict(n_q=1, n_high=2, n_low=1), []))
1270 got = measure(oracle, cases)
1271 found = {}
1272 for (cfg, _t, _e), (_n_bytes, err) in zip(cases, got):
1273 m = span.search(err)
1274 if not m:
1275 continue
1276 rate = SBR_RATE_FOR_SF[cfg["sf_index"]]
1277 k2 = stop_table(rate)[cfg["stop_freq"]]
1278 k0 = k2 - int(m.group(1))
1279 found.setdefault((rate, cfg["start_freq"]), set()).add(k0)
1280 print("measured k0 (SBR rate, bs_start_freq):")
1281 table = {}
1282 for rate in sorted(set(SBR_RATE_FOR_SF.values())):
1283 row = []
1284 for start_freq in range(16):
1285 v = found.get((rate, start_freq))
1286 row.append(sorted(v) if v else None)
1287 table[rate] = row
1288 flat = [(r[0] if r and len(r) == 1 else r) for r in row]
1289 temp = 3000 if rate < 32000 else (4000 if rate < 64000 else 5000)
1290 start_min = ((temp << 7) + (rate >> 1)) // rate
1291 offs = [(v - start_min) if isinstance(v, int) else v for v in flat]
1292 print(f" {rate:6d} start_min={start_min:3d} k0={flat}")
1293 print(f" offsets={offs}")
1294 return table
1295
1296
1297def stage_diag(oracle):
1298 """Measures the decoder's own `n_master` and compares it with ours.
1299
1300 `bs_xover_band > n_master` is refused with a message of its own, so the
1301 largest accepted crossover *is* `n_master` whenever it fits in the field.
1302 """
1303 grid = []
1304 for sf_index, rate in ((7, 44100), (6, 48000), (8, 32000)):
1305 for start_freq in range(0, 14):
1306 for stop_freq in range(0, 16):
1307 for freq_scale in (0, 1, 2, 3):
1308 for alter_scale in (0, 1):
1309 cfg = dict(DEFAULT)
1310 cfg.update(
1311 sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq,
1312 freq_scale=freq_scale, alter_scale=alter_scale,
1313 )
1314 grid.append((rate, cfg))
1315 cases = []
1316 for rate, cfg in grid:
1317 for xover in range(8):
1318 c = dict(cfg, xover_band=xover)
1319 t = freq_tables(rate, dict(c, xover_band=0)) or dict(n_q=1, n_high=2, n_low=1)
1320 cases.append((c, t, []))
1321 got = measure(oracle, cases)
1322 rows = {}
1323 for (cfg, _t, _e), (n, err) in zip(cases, got):
1324 key = (cfg["sf_index"], cfg["start_freq"], cfg["stop_freq"], cfg["freq_scale"], cfg["alter_scale"])
1325 ok = "crossover band index" not in err
1326 rows.setdefault(key, {})[cfg["xover_band"]] = (ok, err)
1327 disagree = 0
1328 total = 0
1329 shown = 0
1330 for (sf_index, start_freq, stop_freq, freq_scale, alter_scale), by_x in sorted(rows.items()):
1331 rate = {7: 44100, 6: 48000, 8: 32000}[sf_index]
1332 cfg = dict(DEFAULT)
1333 cfg.update(sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq,
1334 freq_scale=freq_scale, alter_scale=alter_scale, xover_band=0)
1335 mine = freq_tables(rate, cfg)
1336 accepted = [x for x in range(8) if by_x[x][0]]
1337 theirs = max(accepted) if accepted else -1
1338 # An out-of-range header is refused for every crossover, ours says None.
1339 if mine is None:
1340 valid_here = theirs < 0 or all("Invalid" in by_x[x][1] or "invalid" in by_x[x][1] for x in range(8))
1341 total += 1
1342 if not valid_here:
1343 disagree += 1
1344 if shown < 20:
1345 shown += 1
1346 print(f" we refuse, they take: rate={rate} start={start_freq} stop={stop_freq} "
1347 f"scale={freq_scale} alter={alter_scale} maxx={theirs}")
1348 continue
1349 total += 1
1350 if theirs == 7 and mine["n_master"] >= 7:
1351 continue # the field caps at 7: no information above it
1352 if theirs != mine["n_master"]:
1353 disagree += 1
1354 if shown < 20:
1355 shown += 1
1356 print(f" n_master rate={rate} start={start_freq} stop={stop_freq} scale={freq_scale} "
1357 f"alter={alter_scale}: ours {mine['n_master']} theirs {theirs}")
1358 print(f"diag: {total - disagree}/{total} headers agree on n_master")
1359
1360
1361def run_books_to_fixpoint(oracle, sf_index=7):
1362 """Repeats `stage_books` until no further kind closes, honoring the
1363 dependency order `stage_books` itself discovers via its `missing` check."""
1364 books = {}
1365 remaining = set(KINDS)
1366 while remaining:
1367 made = stage_books(oracle, sf_index, only=remaining, books=books)
1368 if not made:
1369 break
1370 remaining -= set(made)
1371 if remaining:
1372 print(f"books: did not close: {sorted(remaining)}")
1373 return books
1374
1375
1376if __name__ == "__main__":
1377 ap = argparse.ArgumentParser()
1378 ap.add_argument("--stage", default="sweep")
1379 ap.add_argument("--workers", type=int, default=12)
1380 args = ap.parse_args()
1381 oracle = Oracle(args.workers)
1382 try:
1383 if args.stage in ("sweep", "all"):
1384 stage_sweep(oracle)
1385 if args.stage == "diag":
1386 stage_diag(oracle)
1387 if args.stage == "k0":
1388 stage_k0(oracle)
1389 if args.stage in ("widths", "all"):
1390 stage_widths(oracle)
1391 books = None
1392 if args.stage in ("books", "values", "all"):
1393 books = run_books_to_fixpoint(oracle)
1394 if args.stage in ("values", "all"):
1395 values = stage_values(oracle, books)
1396 write_rust(books, values)
1397 finally:
1398 oracle.save()
1399 print(f"oracle: {oracle.runs} decoder runs, {oracle.hits} cache hits")