forge
Explore
Log in

Don't you dare go Hollow

SBR probing rig, and what it has established so far

Browse files at this commit

838fa63131208fd6ff1daf5b1cad98429f222f73Ahmet Kaan GümüşParent: 43c8097
  • chore
    • SBR probing rig, and what it has established so far
Show full message
chore(aac): SBR probing rig, and what it has established so far

Not an implementation of SBR: a bench for one. The core AAC-LC writer and
the FIL framing are correct and the reference decoder parses the sbr_header
this builds -- it answers a deliberately invalid start_freq with a
complaint about n_master. sbr_data is not accepted yet; the decoder
consumes sixteen bits more than the writer emits, which is where the
envelope codebooks would be read.

What that decoder reports is the useful part: the exact byte count its
parser consumed. That is the same kind of cheap, exact observable the AAC
codebooks were derived through, so the ten SBR codebooks have an
instrument waiting for them.

The measurements that scope the work are in the module docstring rather
than in anyone's memory.
scripts/aac-tables/sbrprobe.pyadded+231 -0
@@ -0,0 +1,231 @@
1+#!/usr/bin/env python3
2+"""Black-box probing rig for the SBR (HE-AAC v1) tool. WORK IN PROGRESS.
3+
4+Same method as the AAC tables: the vehicle is an ADTS access unit whose core is
5+an AAC-LC frame of exactly known bit length -- so the FIL element carrying the
6+SBR payload starts at a position we control -- followed by a FIL element holding
7+an sbr_extension_data built field by field. A reference decoder is the only
8+oracle.
9+
10+State, so a successor does not repeat the ground already covered:
11+
12+* The core writer is correct: `sce_core` frames decode clean at every max_sfb,
13+ and the FIL length accounting is right (the reference decoder reads the
14+ element without complaint about its framing).
15+* `sbr_header` is parsed by the reference decoder -- `start_freq=14` comes back
16+ as "Invalid n_master: 0", which is a semantic complaint about a field it read,
17+ not a framing one.
18+* `sbr_data` is NOT yet accepted: the decoder consumes 16 bits more than this
19+ writer emits ("Expected to read 7 SBR bytes actually read 9"), constant across
20+ start_freq, stop_freq and freq_res. The gap is most likely the envelope
21+ Huffman reads for bands beyond the first, whose codebooks are still unknown --
22+ which is the bootstrap problem: only the first envelope value of a
23+ frequency-delta frame is raw (6 or 7 bits), every later one is coded.
24+* The decoder reports the exact byte count its parser consumed, which is a
25+ precise, cheap observable: that is the instrument to bootstrap the ten SBR
26+ codebooks by the same prefix walk the AAC tables came from.
27+"""
28+
29+import os
30+import re
31+import subprocess
32+import sys
33+
34+import numpy as np
35+
36+TABLES = "/home/user/Documents/Code/Rust/edith_codecs/crates/ec-aac/src/tables.rs"
37+SR_TABLE = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]
38+
39+
40+def load_table(name):
41+ src = open(TABLES).read()
42+ body = re.search(rf"static {name}: \[\(u8, u32\); \d+\] = \[(.*?)\n\];", src, re.S).group(1)
43+ return [tuple(int(x) for x in m) for m in re.findall(r"\((\d+),\s*(\d+)\)", body)]
44+
45+
46+def load_swb(kind):
47+ src = open(TABLES).read()
48+ body = re.search(rf"pub static SWB_{kind}: \[&\[u16\]; 12\] = \[(.*?)\n\];", src, re.S).group(1)
49+ return [[int(x) for x in re.findall(r"\d+", row)] for row in re.findall(r"&\[([^\]]*?)\]", body, re.S)]
50+
51+
52+HCB3 = load_table("HCB3")
53+HCB_SF = load_table("HCB_SF")
54+SWB_LONG = load_swb("LONG")
55+
56+
57+class BitW:
58+ def __init__(self):
59+ self.bits = []
60+
61+ def w(self, val, n):
62+ for i in range(n - 1, -1, -1):
63+ self.bits.append((val >> i) & 1)
64+ return self
65+
66+ def wbits(self, seq):
67+ self.bits.extend(seq)
68+ return self
69+
70+ def __len__(self):
71+ return len(self.bits)
72+
73+ def pack(self, total_bytes=None, pad=0):
74+ if total_bytes is None:
75+ total_bytes = (len(self.bits) + 7) // 8
76+ b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8]
77+ out = bytearray()
78+ for i in range(0, len(b), 8):
79+ v = 0
80+ for bit in b[i : i + 8]:
81+ v = (v << 1) | bit
82+ out.append(v)
83+ return bytes(out)
84+
85+
86+def adts(payload, sf_index, chan_cfg=1):
87+ h = BitW()
88+ h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1)
89+ h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3)
90+ h.w(0, 1).w(0, 1).w(0, 1).w(0, 1)
91+ h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2)
92+ return h.pack(7) + payload
93+
94+
95+def tuple_index_u(vals, lav, dim):
96+ span = lav + 1
97+ idx = 0
98+ for i in range(dim):
99+ idx = idx * span + min(abs(vals[i]), lav)
100+ return idx
101+
102+
103+def sce_core(w, sf_index, max_sfb, gain=200, quad=(2, 0, 2, 2)):
104+ """A single_channel_element of exactly known length: codebook 3 throughout,
105+ the same tuple in every position, so the bit cost is arithmetic."""
106+ swb = SWB_LONG[sf_index]
107+ max_sfb = min(max_sfb, len(swb) - 1)
108+ w.w(0, 3).w(0, 4) # SCE, instance tag
109+ w.w(gain, 8)
110+ w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine
111+ w.w(3, 4) # one section, codebook 3
112+ left = max_sfb
113+ while left >= 31:
114+ w.w(31, 5)
115+ left -= 31
116+ w.w(left, 5)
117+ for _ in range(max_sfb):
118+ w.w(HCB_SF[60][1], HCB_SF[60][0]) # delta 0
119+ w.w(0, 3) # pulse / tns / gain-control absent
120+ length, code = HCB3[tuple_index_u(quad, 2, 4)]
121+ signs = [1 for v in quad if v != 0]
122+ for _ in range(swb[max_sfb] // 4):
123+ w.w(code, length)
124+ for _ in signs:
125+ w.w(0, 1) # positive
126+ return w
127+
128+
129+def sbr_payload(cfg):
130+ """sbr_extension_data for one single channel element, from `cfg`."""
131+ s = BitW()
132+ s.w(1, 1) # bs_header_flag
133+ s.w(cfg["amp_res"], 1)
134+ s.w(cfg["start_freq"], 4)
135+ s.w(cfg["stop_freq"], 4)
136+ s.w(cfg["xover_band"], 3)
137+ s.w(0, 2) # bs_reserved
138+ s.w(1, 1) # bs_header_extra_1
139+ s.w(1, 1) # bs_header_extra_2
140+ s.w(cfg["freq_scale"], 2)
141+ s.w(cfg["alter_scale"], 1)
142+ s.w(cfg["noise_bands"], 2)
143+ s.w(cfg["limiter_bands"], 2)
144+ s.w(cfg["limiter_gains"], 2)
145+ s.w(cfg["interpol_freq"], 1)
146+ s.w(cfg["smoothing_mode"], 1)
147+ # sbr_single_channel_element
148+ s.w(0, 1) # bs_data_extra
149+ # sbr_grid: FIXFIX with one envelope
150+ s.w(0, 2) # bs_frame_class = FIXFIX
151+ s.w(0, 2) # bs_num_env_raw -> num_env = 1
152+ s.w(cfg["freq_res"], 1)
153+ # sbr_dtdf
154+ s.w(0, 1) # bs_df_env[0] = frequency direction
155+ s.w(0, 1) # bs_df_noise[0]
156+ # sbr_invf: one mode per noise band
157+ for _ in range(cfg["n_q"]):
158+ s.w(cfg["invf"], 2)
159+ # sbr_envelope: first value raw, the rest would need Huffman
160+ s.w(cfg["env0"], 6 if cfg["amp_res"] else 7)
161+ for value, (length, code) in cfg.get("env_deltas", []):
162+ s.w(code, length)
163+ # sbr_noise: first value raw, the rest Huffman
164+ s.w(cfg["noise0"], 5)
165+ for value, (length, code) in cfg.get("noise_deltas", []):
166+ s.w(code, length)
167+ # bs_add_harmonic_flag
168+ if cfg.get("harmonics") is None:
169+ s.w(0, 1)
170+ else:
171+ s.w(1, 1)
172+ for bit in cfg["harmonics"]:
173+ s.w(bit, 1)
174+ s.w(0, 1) # bs_extended_data
175+ return s
176+
177+
178+def frame(cfg, sf_index=7, max_sfb=20):
179+ w = BitW()
180+ sce_core(w, sf_index, max_sfb, gain=cfg.get("gain", 200))
181+ body = sbr_payload(cfg)
182+ # extension_type nibble plus the payload, padded to whole bytes
183+ payload_bits = 4 + len(body)
184+ count = (payload_bits + 7) // 8
185+ w.w(6, 3) # FIL
186+ if count >= 15:
187+ w.w(15, 4)
188+ w.w(count - 15 + 1, 8)
189+ else:
190+ w.w(count, 4)
191+ start = len(w)
192+ w.w(13, 4) # EXT_SBR_DATA
193+ w.wbits(body.bits)
194+ while len(w) - start < count * 8:
195+ w.w(0, 1)
196+ w.w(7, 3) # END
197+ return adts(w.pack(pad=0), sf_index)
198+
199+
200+def silent(sf_index):
201+ w = BitW()
202+ w.w(0, 3).w(0, 4).w(128, 8)
203+ w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1)
204+ w.w(0, 3).w(7, 3)
205+ return adts(w.pack(4), sf_index)
206+
207+
208+def decode(frames, sf_index, tag=None):
209+ """(samples, stderr) from ffmpeg for a stream of frames."""
210+ src = f"/tmp/sbrprobe-{tag or os.getpid()}.aac"
211+ with open(src, "wb") as f:
212+ f.write(b"".join(frames))
213+ r = subprocess.run(
214+ ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"],
215+ capture_output=True,
216+ )
217+ os.remove(src)
218+ return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode()
219+
220+
221+DEFAULT = dict(
222+ amp_res=1, start_freq=5, stop_freq=3, xover_band=0, freq_scale=0, alter_scale=0,
223+ noise_bands=0, limiter_bands=0, limiter_gains=2, interpol_freq=1, smoothing_mode=1,
224+ freq_res=1, invf=1, env0=40, noise0=15, n_q=1,
225+)
226+
227+if __name__ == "__main__":
228+ cfg = dict(DEFAULT)
229+ frames = [silent(7)] + [frame(cfg) for _ in range(6)] + [silent(7)]
230+ pcm, err = decode(frames, 7, "smoke")
231+ print("samples", len(pcm), "err", err.strip()[:300])