SBR codebook derivation, staged sweep/lengths/values over the byte-accounting oracle
Browse files at this commit17d3de1425c16a816a6e6d15d1b2469a6eaae8d8Parent: 3c2d14b- chore
- SBR codebook derivation, staged sweep/lengths/values over the byte-accounting oracle
1 changed file +1136 -0
- scripts/aac-tables/sbrtables.py +1136 -0
scripts/aac-tables/sbrtables.pyadded+1136 -0
| @@ -0,0 +1,1136 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""Derives the ten SBR Huffman codebooks, black box, from a reference decoder. | ||
| 3 | + | ||
| 4 | +The instrument is the reference decoder's own bit accounting. An SBR payload | ||
| 5 | +rides in a FIL element whose declared byte count `cnt` we choose; the decoder | ||
| 6 | +parses the payload with its own syntax knowledge and complains | ||
| 7 | + | ||
| 8 | + Expected to read <cnt> SBR bytes actually read <n> | ||
| 9 | + | ||
| 10 | +whenever `n > cnt`. Declaring `cnt = 1` therefore turns every probe into a | ||
| 11 | +readout of `n = ceil((4 + bits_the_parser_consumed) / 8)`. | ||
| 12 | + | ||
| 13 | +That 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 | + | ||
| 24 | +Values come from a second observable in the same probe: the decoder range-checks | ||
| 25 | +the accumulated envelope and noise scalefactors and says so on stderr. Bisecting | ||
| 26 | +the raw start value for the point where that complaint appears gives the delta a | ||
| 27 | +codeword carries, with no audio analysis at all. | ||
| 28 | + | ||
| 29 | +Run `--stage sweep` to check the band tables, `--stage lengths` for the prefix | ||
| 30 | +walk, `--stage values` for the assignment, `--stage all` for the lot; the result | ||
| 31 | +is written as Rust to crates/ec-aac/src/sbr_tables.rs. | ||
| 32 | +""" | ||
| 33 | + | ||
| 34 | +import argparse | ||
| 35 | +import json | ||
| 36 | +import math | ||
| 37 | +import os | ||
| 38 | +import re | ||
| 39 | +import subprocess | ||
| 40 | +import sys | ||
| 41 | +from concurrent.futures import ThreadPoolExecutor | ||
| 42 | + | ||
| 43 | +HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 44 | +ROOT = os.path.abspath(os.path.join(HERE, "..", "..")) | ||
| 45 | +sys.path.insert(0, HERE) | ||
| 46 | + | ||
| 47 | +from sbrprobe import BitW, adts, sce_core # noqa: E402 | ||
| 48 | + | ||
| 49 | +CACHE = os.path.join(HERE, "sbr-cache.json") | ||
| 50 | + | ||
| 51 | +# ---------------------------------------------------------------- band tables | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def 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`. | ||
| 75 | +K0_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 | + | ||
| 88 | +def 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 | + | ||
| 94 | +def 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 | + | ||
| 101 | +def 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 | + | ||
| 180 | +def 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. | ||
| 219 | +FILL = [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. | ||
| 222 | +RAW_ENV = {(0, 0): 7, (0, 1): 6, (1, 0): 6, (1, 1): 5} | ||
| 223 | +RAW_NOISE = 5 | ||
| 224 | + | ||
| 225 | + | ||
| 226 | +def 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 | + | ||
| 231 | +def 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 | + | ||
| 236 | +def noise_kind(balance, direction): | ||
| 237 | + return f"NOISE{'B' if balance else ''}_{direction}" | ||
| 238 | + | ||
| 239 | + | ||
| 240 | +def 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 | + | ||
| 261 | +def 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 | + | ||
| 295 | +def known_bits(cfg, tables): | ||
| 296 | + return plan(cfg, tables)[1] | ||
| 297 | + | ||
| 298 | + | ||
| 299 | +def 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 | + | ||
| 382 | +DEFAULT = 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 | + | ||
| 392 | +def 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 | + | ||
| 405 | +def 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 | + | ||
| 427 | +READ = re.compile(r"Expected to read (\d+) SBR bytes actually read (\d+)") | ||
| 428 | + | ||
| 429 | + | ||
| 430 | +class 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 | + | ||
| 483 | +def 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 | + | ||
| 489 | +def 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 | + | ||
| 503 | +def 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 | + | ||
| 514 | +def 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 | + | ||
| 521 | +def 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 | + | ||
| 528 | +KINDS = [ | ||
| 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. | ||
| 537 | +EXTRA1_DEFAULTS = dict(freq_scale=2, alter_scale=1, noise_bands=2) | ||
| 538 | + | ||
| 539 | + | ||
| 540 | +def 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. | ||
| 580 | +RECIPES = { | ||
| 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 | + | ||
| 613 | +def 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 | + | ||
| 629 | +def 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. | ||
| 660 | +BAD_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 | +RAW_TRIES = [(0, 16), (30, 16), (0, 0), (30, 30)] | ||
| 667 | + | ||
| 668 | + | ||
| 669 | +def as_bits(length, code): | ||
| 670 | + return [(code >> (length - 1 - i)) & 1 for i in range(length)] | ||
| 671 | + | ||
| 672 | + | ||
| 673 | +def filler(books, kind, extra=0): | ||
| 674 | + """A derived codeword of this book, `extra` bits longer than its shortest. | ||
| 675 | + | ||
| 676 | + Swapping one filler for a longer one shifts the payload by a known number of | ||
| 677 | + bits, which is the knob a coupled probe would otherwise lack. | ||
| 678 | + """ | ||
| 679 | + if kind not in books: | ||
| 680 | + return None | ||
| 681 | + lengths = sorted({l for l, _ in books[kind]}) | ||
| 682 | + want = lengths[0] + extra | ||
| 683 | + for length, code in sorted(books[kind]): | ||
| 684 | + if length == want: | ||
| 685 | + return as_bits(length, code) | ||
| 686 | + return None | ||
| 687 | + | ||
| 688 | + | ||
| 689 | +def fill_words(cfg, tables, kind, word, books, extra=0): | ||
| 690 | + """Slot words: `word` in the last slot of `kind`, derived codewords before.""" | ||
| 691 | + kinds, _ = plan(cfg, tables) | ||
| 692 | + last = max(i for i, k in enumerate(kinds) if k == kind) | ||
| 693 | + # An envelope value has room for any delta its table holds, so swapping an | ||
| 694 | + # envelope filler is safe; a noise floor's does not, so it is a last resort. | ||
| 695 | + order = [i for i, k in enumerate(kinds) if i != last and k.startswith("ENV")] | ||
| 696 | + order += [i for i, k in enumerate(kinds) if i != last and not k.startswith("ENV")] | ||
| 697 | + swap_at = None | ||
| 698 | + for i in order: | ||
| 699 | + if filler(books, kinds[i], extra) is not None: | ||
| 700 | + swap_at = i | ||
| 701 | + break | ||
| 702 | + words = [] | ||
| 703 | + shifted = not extra | ||
| 704 | + for i, k in enumerate(kinds): | ||
| 705 | + if i == last: | ||
| 706 | + words.append(list(word)) | ||
| 707 | + continue | ||
| 708 | + if not shifted and i == swap_at: | ||
| 709 | + got = filler(books, k, extra) | ||
| 710 | + if got is not None: | ||
| 711 | + words.append(got) | ||
| 712 | + shifted = True | ||
| 713 | + continue | ||
| 714 | + got = filler(books, k, 0) | ||
| 715 | + if got is None: | ||
| 716 | + return None | ||
| 717 | + words.append(got) | ||
| 718 | + return words if shifted else None | ||
| 719 | + | ||
| 720 | + | ||
| 721 | +def exact_bits(oracle, cfg, tables, kind, word, books): | ||
| 722 | + """The length of the codeword `word` starts with, exactly. | ||
| 723 | + | ||
| 724 | + A byte count pins the bits the parser read to within a byte. Shifting the | ||
| 725 | + payload ahead of the slot -- by dropping a header group, by adding the | ||
| 726 | + reserved data-extra field, or by swapping one already-derived filler | ||
| 727 | + codeword for a longer one -- and reading the count again pins it exactly. | ||
| 728 | + """ | ||
| 729 | + knobs = knob_variants(cfg, tables) | ||
| 730 | + cases = [] | ||
| 731 | + residues = set() | ||
| 732 | + for extra in range(0, 8): | ||
| 733 | + words = fill_words(cfg, tables, kind, word, books, extra) | ||
| 734 | + if words is None: | ||
| 735 | + continue | ||
| 736 | + for v, _delta in knobs: | ||
| 737 | + base = known_bits(v, tables) + sum(len(w) for w in words[:-1]) | ||
| 738 | + cases.append((v, words, base)) | ||
| 739 | + residues.add(base % 8) | ||
| 740 | + if len(residues) == 8: | ||
| 741 | + break | ||
| 742 | + if len(residues) < 8: | ||
| 743 | + return None | ||
| 744 | + # Refusing a value stops the parse right after the codeword that carried | ||
| 745 | + # it, so the fields the payload spends after the slot go unread: that is a | ||
| 746 | + # measurement too, of the same codeword, with a known amount less around it. | ||
| 747 | + trailing = 1 + (2 if cfg.get("element") == "cpe" else 1) | ||
| 748 | + for noise0, noise0b in RAW_TRIES: | ||
| 749 | + tries = [(dict(v, noise0=[noise0] * 2, noise0b=[noise0b] * 2), w, b) | ||
| 750 | + for v, w, b in cases] | ||
| 751 | + got = measure(oracle, [(v, tables, w) for v, w, _ in tries]) | ||
| 752 | + lo, hi, bad = -10 ** 6, 10 ** 6, False | ||
| 753 | + for (_v, _w, base), (n, err) in zip(tries, got): | ||
| 754 | + if n is None: | ||
| 755 | + bad = True | ||
| 756 | + break | ||
| 757 | + top = 8 * n - 4 - base + (trailing if BAD_VALUE.search(err) else 0) | ||
| 758 | + lo, hi = max(lo, top - 7), min(hi, top) | ||
| 759 | + if not bad and lo == hi: | ||
| 760 | + return lo | ||
| 761 | + return None | ||
| 762 | + | ||
| 763 | + | ||
| 764 | +def walk(oracle, kind, cfg, tables, books, verbose=True): | ||
| 765 | + """Enumerates a complete prefix code by walking its intervals. | ||
| 766 | + | ||
| 767 | + A complete code tiles the unit interval: the codeword at `cur` is the first | ||
| 768 | + `L` bits of `cur`, and the next one starts at `cur + 2^-L`. One length | ||
| 769 | + measurement per codeword enumerates the whole book, and the walk landing | ||
| 770 | + exactly on 1 is the completeness check. | ||
| 771 | + """ | ||
| 772 | + codes = [] | ||
| 773 | + cur, depth, kraft = 0, 0, 0.0 | ||
| 774 | + while True: | ||
| 775 | + bits = [(cur >> (depth - 1 - i)) & 1 for i in range(depth)] | ||
| 776 | + length = exact_bits(oracle, cfg, tables, kind, bits + [0] * 32, books) | ||
| 777 | + if length is None and kraft < 1.0: | ||
| 778 | + # A complete code ends on a single interval, and its width is the | ||
| 779 | + # last codeword's length: that one needs no probe. | ||
| 780 | + rest = 1.0 - kraft | ||
| 781 | + exact = int(round(math.log2(1.0 / rest))) | ||
| 782 | + if abs(rest - 2.0 ** -exact) < 1e-12 and 1 <= exact <= 32: | ||
| 783 | + length = exact | ||
| 784 | + if verbose: | ||
| 785 | + print(f" {kind}: last codeword closed by completeness at {exact} bits") | ||
| 786 | + if length is None or not 1 <= length <= 32: | ||
| 787 | + print(f" {kind}: no length after {len(codes)} at " | ||
| 788 | + f"{''.join(map(str, bits)) or '(empty)'}: {length}") | ||
| 789 | + return None | ||
| 790 | + while depth < length: | ||
| 791 | + cur <<= 1 | ||
| 792 | + depth += 1 | ||
| 793 | + codes.append((length, cur >> (depth - length))) | ||
| 794 | + kraft += 2.0 ** -length | ||
| 795 | + cur += 1 << (depth - length) | ||
| 796 | + while depth and cur % 2 == 0: | ||
| 797 | + cur >>= 1 | ||
| 798 | + depth -= 1 | ||
| 799 | + if depth == 0 and cur >= 1: | ||
| 800 | + break | ||
| 801 | + if len(codes) > 200: | ||
| 802 | + print(f" {kind}: walk did not close") | ||
| 803 | + return None | ||
| 804 | + if verbose: | ||
| 805 | + print(f" {kind}: {len(codes)} codewords, Kraft {kraft:.9f}, lengths " | ||
| 806 | + f"{min(l for l, _ in codes)}..{max(l for l, _ in codes)}") | ||
| 807 | + return codes | ||
| 808 | + | ||
| 809 | + | ||
| 810 | +def bootstrap(oracle, kind, cfg, tables, books, span=(1, 33)): | ||
| 811 | + """The first codeword of a book, when there is no filler for it yet. | ||
| 812 | + | ||
| 813 | + Every slot of the kind carries the same candidate word, so the length that | ||
| 814 | + explains the bit count is the one the parser actually read. | ||
| 815 | + """ | ||
| 816 | + kinds, _ = plan(cfg, tables) | ||
| 817 | + if kinds.count(kind) == 1: | ||
| 818 | + books[kind] = [(1, 0)] | ||
| 819 | + return True | ||
| 820 | + for length in range(span[0], span[1]): | ||
| 821 | + books[kind] = [(length, 0)] | ||
| 822 | + if exact_bits(oracle, cfg, tables, kind, [0] * 33, books) == length: | ||
| 823 | + return True | ||
| 824 | + books.pop(kind, None) | ||
| 825 | + return False | ||
| 826 | + | ||
| 827 | + | ||
| 828 | +def stage_books(oracle, sf_index=7, only=None, books=None): | ||
| 829 | + """Derives every codebook, each with the ones it leans on already in hand.""" | ||
| 830 | + books = books if books is not None else {} | ||
| 831 | + out = {} | ||
| 832 | + for kind in KINDS: | ||
| 833 | + if only and kind not in only: | ||
| 834 | + continue | ||
| 835 | + made = recipe_config(kind, sf_index) | ||
| 836 | + if made is None: | ||
| 837 | + print(f" {kind}: no configuration") | ||
| 838 | + continue | ||
| 839 | + cfg, tables = made | ||
| 840 | + kinds, _ = plan(cfg, tables) | ||
| 841 | + missing = {k for k in kinds if k != kind and k not in books} | ||
| 842 | + if missing: | ||
| 843 | + print(f" {kind}: needs {sorted(missing)} first") | ||
| 844 | + continue | ||
| 845 | + if not bootstrap(oracle, kind, cfg, tables, books): | ||
| 846 | + print(f" {kind}: no bootstrap codeword") | ||
| 847 | + continue | ||
| 848 | + codes = walk(oracle, kind, cfg, tables, books) | ||
| 849 | + if codes is None: | ||
| 850 | + books.pop(kind, None) | ||
| 851 | + continue | ||
| 852 | + out[kind] = books[kind] = codes | ||
| 853 | + return out | ||
| 854 | + | ||
| 855 | + | ||
| 856 | + | ||
| 857 | +# ---------------------------------------------------------------- raw widths | ||
| 858 | + | ||
| 859 | +WIDTH_VARS = ["E00", "E01", "E10", "E11", "N0", "N1"] | ||
| 860 | + | ||
| 861 | + | ||
| 862 | +def width_cases(sf_index=7): | ||
| 863 | + """Configurations with no Huffman slot at all, and what they spend on raw | ||
| 864 | + start values -- the widths are the only thing in them this script guesses.""" | ||
| 865 | + out = [] | ||
| 866 | + combos = [ | ||
| 867 | + # Four envelopes still carry two noise floors, which is what separates | ||
| 868 | + # an envelope's raw width from a noise floor's. Eight is refused: the | ||
| 869 | + # tool caps a FIXFIX frame's envelope count below that. | ||
| 870 | + ("sce", 4, 0, {"E00": 4, "N0": 2}), | ||
| 871 | + ("sce", 4, 1, {"E01": 4, "N0": 2}), | ||
| 872 | + ("cpe", 4, 0, {"E00": 4, "N0": 2, "E10": 4, "N1": 2}), | ||
| 873 | + ("cpe", 4, 1, {"E01": 4, "N0": 2, "E11": 4, "N1": 2}), | ||
| 874 | + ("sce", 1, 0, {"E00": 1, "N0": 1}), | ||
| 875 | + ("sce", 2, 0, {"E00": 2, "N0": 2}), | ||
| 876 | + ("sce", 2, 1, {"E01": 2, "N0": 2}), | ||
| 877 | + ("cpe", 1, 0, {"E00": 1, "N0": 1, "E10": 1, "N1": 1}), | ||
| 878 | + ("cpe", 2, 0, {"E00": 2, "N0": 2, "E10": 2, "N1": 2}), | ||
| 879 | + ("cpe", 2, 1, {"E01": 2, "N0": 2, "E11": 2, "N1": 2}), | ||
| 880 | + ] | ||
| 881 | + for element, num_env, amp_res, coeff in combos: | ||
| 882 | + over = dict(element=element, coupling=1, num_env=num_env, amp_res=amp_res, | ||
| 883 | + df_env=[0] * 8, df_noise=[0, 0], freq_res=0) | ||
| 884 | + found = find_config(sf_index, over, n_high=2, n_low=1, n_q=1) | ||
| 885 | + if found is None: | ||
| 886 | + continue | ||
| 887 | + cfg, tables = found | ||
| 888 | + assert not plan(cfg, tables)[0], "width probe must have no Huffman slot" | ||
| 889 | + for knob in ({}, {"add_harmonic": [1, 0]}, {"add_harmonic": [1, 1]}, | ||
| 890 | + {"extended": 1}, {"extended": 1, "add_harmonic": [1, 0]}, | ||
| 891 | + {"data_extra": 1}, {"header": 0}): | ||
| 892 | + v = dict(cfg, **knob) | ||
| 893 | + out.append((v, tables, coeff)) | ||
| 894 | + return out | ||
| 895 | + | ||
| 896 | + | ||
| 897 | +def stage_widths(oracle, sf_index=7): | ||
| 898 | + """Solves the raw start value widths against the byte counts.""" | ||
| 899 | + global RAW_ENV, RAW_NOISE | ||
| 900 | + cases = width_cases(sf_index) | ||
| 901 | + # The widths themselves are what the probe is measuring, so they must not | ||
| 902 | + # enter the prediction: zero them while the equations are built. | ||
| 903 | + guess = dict(E00=RAW_ENV[(0, 0)], E01=RAW_ENV[(0, 1)], E10=RAW_ENV[(1, 0)], | ||
| 904 | + E11=RAW_ENV[(1, 1)], N0=RAW_NOISE, N1=RAW_NOISE) | ||
| 905 | + got = measure(oracle, [(c, t, []) for c, t, _ in cases]) | ||
| 906 | + eqs = [] | ||
| 907 | + for (cfg, tables, coeff), (n, err) in zip(cases, got): | ||
| 908 | + if n is None: | ||
| 909 | + continue | ||
| 910 | + # The written payload keeps the guessed widths -- what it holds cannot | ||
| 911 | + # change what the parser reads -- so only the prediction drops them. | ||
| 912 | + base = known_bits(cfg, tables) - sum(c * guess[k] for k, c in coeff.items()) | ||
| 913 | + eqs.append((coeff, 8 * n - 4 - base - 7, 8 * n - 4 - base)) | ||
| 914 | + best = [] | ||
| 915 | + ranges = range(3, 10) | ||
| 916 | + for e00 in ranges: | ||
| 917 | + for e01 in ranges: | ||
| 918 | + for e10 in ranges: | ||
| 919 | + for e11 in ranges: | ||
| 920 | + for n0 in ranges: | ||
| 921 | + for n1 in ranges: | ||
| 922 | + v = dict(E00=e00, E01=e01, E10=e10, E11=e11, N0=n0, N1=n1) | ||
| 923 | + if all(lo <= sum(c * v[k] for k, c in coeff.items()) <= hi | ||
| 924 | + for coeff, lo, hi in eqs): | ||
| 925 | + best.append(v) | ||
| 926 | + print(f"widths: {len(eqs)} equations, {len(best)} solutions: {best[:4]}") | ||
| 927 | + if len(best) == 1: | ||
| 928 | + v = best[0] | ||
| 929 | + RAW_ENV = {(0, 0): v["E00"], (0, 1): v["E01"], (1, 0): v["E10"], (1, 1): v["E11"]} | ||
| 930 | + RAW_NOISE = v["N0"] | ||
| 931 | + if v["N1"] != v["N0"]: | ||
| 932 | + print(f" balance noise raw width differs: {v['N1']} vs {v['N0']}") | ||
| 933 | + return best | ||
| 934 | + | ||
| 935 | + | ||
| 936 | +# ---------------------------------------------------------------- stage sweep | ||
| 937 | + | ||
| 938 | + | ||
| 939 | +def one_band_cfg(rate, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, sf_index): | ||
| 940 | + """A configuration whose payload holds no Huffman codeword at all. | ||
| 941 | + | ||
| 942 | + `bs_xover_band` is chosen so `n_high` is 2, which with `bs_freq_res = 0` | ||
| 943 | + leaves a single envelope band: the raw start value and nothing else. | ||
| 944 | + """ | ||
| 945 | + cfg = dict(DEFAULT) | ||
| 946 | + cfg.update( | ||
| 947 | + start_freq=start_freq, stop_freq=stop_freq, freq_scale=freq_scale, | ||
| 948 | + alter_scale=alter_scale, noise_bands=noise_bands, sf_index=sf_index, | ||
| 949 | + ) | ||
| 950 | + probe = dict(cfg, xover_band=0) | ||
| 951 | + t = freq_tables(rate, probe) | ||
| 952 | + if t is None or t["n_master"] < 2: | ||
| 953 | + return None | ||
| 954 | + xover = t["n_master"] - 2 | ||
| 955 | + if xover > 7: | ||
| 956 | + return None | ||
| 957 | + cfg["xover_band"] = xover | ||
| 958 | + t = freq_tables(rate, cfg) | ||
| 959 | + if t is None or t["n_high"] != 2 or t["n_low"] != 1 or t["n_q"] != 1: | ||
| 960 | + return None | ||
| 961 | + # The core is analysed with 32 QMF bands, so a crossover above band 32 is | ||
| 962 | + # refused: measured, and the reason several sweep cells used to disagree. | ||
| 963 | + if t["kx"] > 32: | ||
| 964 | + return None | ||
| 965 | + return cfg, t | ||
| 966 | + | ||
| 967 | + | ||
| 968 | +def stage_sweep(oracle, verbose=True): | ||
| 969 | + """Checks the band derivation against the decoder, over many headers.""" | ||
| 970 | + cases = [] | ||
| 971 | + for sf_index, rate in sorted(SBR_RATE_FOR_SF.items()): | ||
| 972 | + for start_freq in range(0, 16): | ||
| 973 | + for stop_freq in (0, 2, 4, 6, 8, 10, 12, 13, 14, 15): | ||
| 974 | + for freq_scale in (0, 1, 2, 3): | ||
| 975 | + for alter_scale in (0, 1): | ||
| 976 | + for noise_bands in (0, 1, 2, 3): | ||
| 977 | + made = one_band_cfg( | ||
| 978 | + rate, start_freq, stop_freq, freq_scale, | ||
| 979 | + alter_scale, noise_bands, sf_index, | ||
| 980 | + ) | ||
| 981 | + if made: | ||
| 982 | + cases.append(made) | ||
| 983 | + if verbose: | ||
| 984 | + print(f"sweep: {len(cases)} single-band configurations") | ||
| 985 | + got = measure(oracle, [(c, t, []) for c, t in cases]) | ||
| 986 | + bad = 0 | ||
| 987 | + for (cfg, t), (n, err) in zip(cases, got): | ||
| 988 | + want = predicted(cfg, t, []) | ||
| 989 | + if n != want: | ||
| 990 | + bad += 1 | ||
| 991 | + if bad < 15 and verbose: | ||
| 992 | + print( | ||
| 993 | + f" MISMATCH rate_sf={cfg['sf_index']} start={cfg['start_freq']} " | ||
| 994 | + f"stop={cfg['stop_freq']} scale={cfg['freq_scale']} alter={cfg['alter_scale']} " | ||
| 995 | + f"nb={cfg['noise_bands']} xover={cfg['xover_band']}: want {want} got {n} " | ||
| 996 | + f"n_master={t['n_master']} :: {err.strip()[:120]}" | ||
| 997 | + ) | ||
| 998 | + print(f"sweep: {len(cases) - bad}/{len(cases)} configurations agree with the reference parser") | ||
| 999 | + return bad == 0 | ||
| 1000 | + | ||
| 1001 | + | ||
| 1002 | +SBR_RATE_FOR_SF = {11: 16000, 10: 22050, 9: 24000, 8: 32000, 7: 44100, 6: 48000, 5: 64000, 4: 88200, 3: 96000} | ||
| 1003 | + | ||
| 1004 | + | ||
| 1005 | +def stop_table(rate): | ||
| 1006 | + """`k2` for each `bs_stop_freq` below 14 (4.6.18.3.2.1).""" | ||
| 1007 | + stop_min = start_stop_min(rate)[1] | ||
| 1008 | + widths = sorted(make_bands(stop_min, 64, 13)) | ||
| 1009 | + out = [stop_min] | ||
| 1010 | + for w in widths: | ||
| 1011 | + out.append(out[-1] + w) | ||
| 1012 | + return out | ||
| 1013 | + | ||
| 1014 | + | ||
| 1015 | +def stage_k0(oracle): | ||
| 1016 | + """Measures `k0` for every rate and `bs_start_freq`, from the decoder. | ||
| 1017 | + | ||
| 1018 | + A header whose reconstruction span `k2 - k0` exceeds what the tool allows is | ||
| 1019 | + refused with the span itself in the message, and `k2` follows from | ||
| 1020 | + `bs_stop_freq` alone: one refusal per configuration therefore reads `k0` | ||
| 1021 | + straight out, and the several `bs_stop_freq` values that all refuse have to | ||
| 1022 | + agree on it, which is the check that the stop table is right too. | ||
| 1023 | + """ | ||
| 1024 | + span = re.compile(r"too many QMF subbands: (\d+)") | ||
| 1025 | + cases = [] | ||
| 1026 | + for sf_index, rate in sorted(SBR_RATE_FOR_SF.items()): | ||
| 1027 | + for start_freq in range(16): | ||
| 1028 | + for stop_freq in (10, 11, 12, 13): | ||
| 1029 | + cfg = dict(DEFAULT) | ||
| 1030 | + cfg.update(sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq) | ||
| 1031 | + cases.append((cfg, dict(n_q=1, n_high=2, n_low=1), [])) | ||
| 1032 | + got = measure(oracle, cases) | ||
| 1033 | + found = {} | ||
| 1034 | + for (cfg, _t, _e), (_n_bytes, err) in zip(cases, got): | ||
| 1035 | + m = span.search(err) | ||
| 1036 | + if not m: | ||
| 1037 | + continue | ||
| 1038 | + rate = SBR_RATE_FOR_SF[cfg["sf_index"]] | ||
| 1039 | + k2 = stop_table(rate)[cfg["stop_freq"]] | ||
| 1040 | + k0 = k2 - int(m.group(1)) | ||
| 1041 | + found.setdefault((rate, cfg["start_freq"]), set()).add(k0) | ||
| 1042 | + print("measured k0 (SBR rate, bs_start_freq):") | ||
| 1043 | + table = {} | ||
| 1044 | + for rate in sorted(set(SBR_RATE_FOR_SF.values())): | ||
| 1045 | + row = [] | ||
| 1046 | + for start_freq in range(16): | ||
| 1047 | + v = found.get((rate, start_freq)) | ||
| 1048 | + row.append(sorted(v) if v else None) | ||
| 1049 | + table[rate] = row | ||
| 1050 | + flat = [(r[0] if r and len(r) == 1 else r) for r in row] | ||
| 1051 | + temp = 3000 if rate < 32000 else (4000 if rate < 64000 else 5000) | ||
| 1052 | + start_min = ((temp << 7) + (rate >> 1)) // rate | ||
| 1053 | + offs = [(v - start_min) if isinstance(v, int) else v for v in flat] | ||
| 1054 | + print(f" {rate:6d} start_min={start_min:3d} k0={flat}") | ||
| 1055 | + print(f" offsets={offs}") | ||
| 1056 | + return table | ||
| 1057 | + | ||
| 1058 | + | ||
| 1059 | +def stage_diag(oracle): | ||
| 1060 | + """Measures the decoder's own `n_master` and compares it with ours. | ||
| 1061 | + | ||
| 1062 | + `bs_xover_band > n_master` is refused with a message of its own, so the | ||
| 1063 | + largest accepted crossover *is* `n_master` whenever it fits in the field. | ||
| 1064 | + """ | ||
| 1065 | + grid = [] | ||
| 1066 | + for sf_index, rate in ((7, 44100), (6, 48000), (8, 32000)): | ||
| 1067 | + for start_freq in range(0, 14): | ||
| 1068 | + for stop_freq in range(0, 16): | ||
| 1069 | + for freq_scale in (0, 1, 2, 3): | ||
| 1070 | + for alter_scale in (0, 1): | ||
| 1071 | + cfg = dict(DEFAULT) | ||
| 1072 | + cfg.update( | ||
| 1073 | + sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq, | ||
| 1074 | + freq_scale=freq_scale, alter_scale=alter_scale, | ||
| 1075 | + ) | ||
| 1076 | + grid.append((rate, cfg)) | ||
| 1077 | + cases = [] | ||
| 1078 | + for rate, cfg in grid: | ||
| 1079 | + for xover in range(8): | ||
| 1080 | + c = dict(cfg, xover_band=xover) | ||
| 1081 | + t = freq_tables(rate, dict(c, xover_band=0)) or dict(n_q=1, n_high=2, n_low=1) | ||
| 1082 | + cases.append((c, t, [])) | ||
| 1083 | + got = measure(oracle, cases) | ||
| 1084 | + rows = {} | ||
| 1085 | + for (cfg, _t, _e), (n, err) in zip(cases, got): | ||
| 1086 | + key = (cfg["sf_index"], cfg["start_freq"], cfg["stop_freq"], cfg["freq_scale"], cfg["alter_scale"]) | ||
| 1087 | + ok = "crossover band index" not in err | ||
| 1088 | + rows.setdefault(key, {})[cfg["xover_band"]] = (ok, err) | ||
| 1089 | + disagree = 0 | ||
| 1090 | + total = 0 | ||
| 1091 | + shown = 0 | ||
| 1092 | + for (sf_index, start_freq, stop_freq, freq_scale, alter_scale), by_x in sorted(rows.items()): | ||
| 1093 | + rate = {7: 44100, 6: 48000, 8: 32000}[sf_index] | ||
| 1094 | + cfg = dict(DEFAULT) | ||
| 1095 | + cfg.update(sf_index=sf_index, start_freq=start_freq, stop_freq=stop_freq, | ||
| 1096 | + freq_scale=freq_scale, alter_scale=alter_scale, xover_band=0) | ||
| 1097 | + mine = freq_tables(rate, cfg) | ||
| 1098 | + accepted = [x for x in range(8) if by_x[x][0]] | ||
| 1099 | + theirs = max(accepted) if accepted else -1 | ||
| 1100 | + # An out-of-range header is refused for every crossover, ours says None. | ||
| 1101 | + if mine is None: | ||
| 1102 | + valid_here = theirs < 0 or all("Invalid" in by_x[x][1] or "invalid" in by_x[x][1] for x in range(8)) | ||
| 1103 | + total += 1 | ||
| 1104 | + if not valid_here: | ||
| 1105 | + disagree += 1 | ||
| 1106 | + if shown < 20: | ||
| 1107 | + shown += 1 | ||
| 1108 | + print(f" we refuse, they take: rate={rate} start={start_freq} stop={stop_freq} " | ||
| 1109 | + f"scale={freq_scale} alter={alter_scale} maxx={theirs}") | ||
| 1110 | + continue | ||
| 1111 | + total += 1 | ||
| 1112 | + if theirs == 7 and mine["n_master"] >= 7: | ||
| 1113 | + continue # the field caps at 7: no information above it | ||
| 1114 | + if theirs != mine["n_master"]: | ||
| 1115 | + disagree += 1 | ||
| 1116 | + if shown < 20: | ||
| 1117 | + shown += 1 | ||
| 1118 | + print(f" n_master rate={rate} start={start_freq} stop={stop_freq} scale={freq_scale} " | ||
| 1119 | + f"alter={alter_scale}: ours {mine['n_master']} theirs {theirs}") | ||
| 1120 | + print(f"diag: {total - disagree}/{total} headers agree on n_master") | ||
| 1121 | + | ||
| 1122 | + | ||
| 1123 | +if __name__ == "__main__": | ||
| 1124 | + ap = argparse.ArgumentParser() | ||
| 1125 | + ap.add_argument("--stage", default="sweep") | ||
| 1126 | + ap.add_argument("--workers", type=int, default=12) | ||
| 1127 | + args = ap.parse_args() | ||
| 1128 | + oracle = Oracle(args.workers) | ||
| 1129 | + try: | ||
| 1130 | + if args.stage in ("sweep", "all"): | ||
| 1131 | + stage_sweep(oracle) | ||
| 1132 | + if args.stage == "diag": | ||
| 1133 | + stage_diag(oracle) | ||
| 1134 | + finally: | ||
| 1135 | + oracle.save() | ||
| 1136 | + print(f"oracle: {oracle.runs} decoder runs, {oracle.hits} cache hits") | ||