forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa913c84Tahinli3 months ago146 commits

sbrpatchmap.py318 lines, 15.1 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Round-29: measures the reference decoder's ACTUAL SBR HF patch map (which
3low QMF source band feeds which high target band), by isolating one source
4band at a time and reading off the FRACTIONAL FREQUENCY OFFSET of the
5resulting HF line(s), not their power.
6
7Round-28 found that a power-bucket readout cannot work: the envelope adjuster
8renormalizes every target band's POWER to the transmitted envelope regardless
9of patch content, so every source band lit the SAME target range at similar
10power (expected physics, not a bug). Gains rescale amplitude, never a line's
11frequency position within its band, so the fix is to read frequency instead.
12
13Method: the core spectrum for a probe frame is a single isolated MDCT bin --
14`tone_core()` in `sbrchirp.py` -- placed not at low QMF band `p`'s first bin
15(a group/band boundary, ambiguous under FFT leakage and coincident with the
16target band edge too) but at its SECOND 4-bin group (`k = p*16 + 4`), i.e. a
17known, non-zero fractional offset `D = 0.25` of a QMF band's width inside
18band `p` (0.25 is the finest offset `tone_core`'s group granularity allows;
19any of 0.25/0.5/0.75 is equally "distinctive", 0.25 chosen arbitrarily).
20Patching copies that source band's complex QMF series verbatim into every
21target band any patch maps it to, translating the tone in frequency by an
22integer number of band widths -- so the offset is preserved (or, per the
23charter's note on filterbank parity, possibly mirrored to `1 - D`) in
24whichever target band(s) the patch actually lit up. An averaged FFT of the
25decoded output finds every HF line clearly above the local noise floor
26(power only GATES detection); for each line, `target band q = floor(f/bw)`
27and `frac = f/bw - q` are computed, and a line is read as "source `p` ->
28target `q`" iff `frac` is within a few percent of `D` (direct) or `1 - D`
29(mirrored, logged separately as data, not discarded).
30
31Runs the same probes through our own decoder via the `adts_to_pcm` example
32(`cargo build -p ec-aac --example adts_to_pcm`) for the sanity cross-check the
33charter requires: our measured map must equal `build_patches`' prediction, or
34the fingerprint method itself is the thing that's broken. Also checks the
35reference's stderr for "No quantized data read for sbr_dequant." -- if
36present the run used a shape that leaves the SBR gain stage unengaged and the
37decode is not trustworthy.
38
39STATUS (round-29): the sanity gate still FAILS after two real fixes landed
40this round (see the ledger's round-29 facts): (1) `sbr_bits_full`'s `slot()`
41default (`T.FILL`, 24 raw zero bits) desyncs the bitstream whenever a
42multi-band delta run is used -- ENV30_F/NOISE_F's shortest codeword (the one
43"0" bits actually decode as) is only 1 bit, so 23 excess zero bits per slot
44leak into every field transmitted after it; `stream_one_band` now supplies
45exactly enough real 1-bit zero-delta codewords instead (fixed, confirmed via
46`EC_AAC_SBR_DEBUG`: `e_q[1]`/`q_q[1]` now read back the intended raw values,
47were silently zeroed before). (2) The tone's fractional-offset placement
48(`GROUP_OFFSET`) is unaffected by that fix. What remains OPEN: `k = active_p
49* 16` (the MDCT-bin-per-QMF-band assumption every prior round's readout used,
50inherited unchanged here) does not track the true source-band placement --
51calibration by sweeping raw bin `k` and reading which target band lights up
52shows a clean *32*-bin-per-band slope (not 16) locally, but with an offset
53that is NOT a fixed constant across headers (k=64 lands on `target == kx`
54for headers A and C, whose `patches[0]` happens to have `source_start == 0`,
55but for header B -- `xover_band=1`, whose `patches[0]` has `source_start ==
562` -- k=64 *also* lands on `target == kx`, meaning it tracked `source_start`
57itself, not a fixed `p`). The low/source band index space is not a simple
58`p*N + offset` function of MDCT bin position; it needs deriving from the
59tables' own low-band structure rather than assumed, which this round did not
60reach. Sanity gate: DO NOT trust `measured(ref)` output below until this is
61resolved -- Task 2/3 (reading and acting on the reference's map) are blocked
62on it.
63"""
64import os
65import subprocess
66import sys
67
68import numpy as np
69
70HERE = os.path.dirname(os.path.abspath(__file__))
71sys.path.insert(0, HERE)
72
73import sbrchirp as C # noqa: E402
74import sbrpayload_fixtures as F # noqa: E402
75import sbrprobe as P # noqa: E402
76import sbrtables as T # noqa: E402
77
78SF_INDEX = 7
79RATE = 44100
80OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm")
81BAND_HZ = RATE / 128 # QMF band width, both source and target index units
82D = 0.25 # fractional offset (of one band width) the probe tone is placed at
83GROUP_OFFSET = 4 # bins: 4/16 == D, the finest offset tone_core's grouping allows
84NO_QUANT_WARNING = "No quantized data read for sbr_dequant."
85
86
87def build_patches_predicted(kx, k2, f_high):
88 """Python port of `build_patches` (crates/ec-aac/src/sbr_hf.rs), for
89 comparing the reference's measured map against our own prediction."""
90 patches = []
91 if kx == 0 or k2 <= kx:
92 return patches
93 msb, sb = kx, kx
94 while sb < k2:
95 width, probe = 0, sb
96 while True:
97 border = next((b for b in f_high if b > probe), None)
98 if border is None:
99 break
100 iv = border - probe
101 if width + iv > msb or border > k2:
102 break
103 width += iv
104 probe = border
105 if width == 0:
106 width = min(k2 - sb, max(msb, 1))
107 source_start = msb - min(width, msb)
108 patches.append((source_start, sb, width))
109 sb += width
110 msb = kx if source_start == 0 else source_start
111 return patches
112
113
114def predicted_targets(patches, p):
115 out = []
116 for source_start, target_start, width in patches:
117 if source_start <= p < source_start + width:
118 out.append(target_start + (p - source_start))
119 return out
120
121
122def bin_to_sfb_group(k, swb):
123 for i in range(len(swb) - 1):
124 if swb[i] <= k < swb[i + 1]:
125 return i, (k - swb[i]) // 4
126 return None
127
128
129def make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
130 cfg = dict(T.DEFAULT, sf_index=SF_INDEX, start_freq=start_freq, stop_freq=stop_freq,
131 freq_scale=freq_scale, alter_scale=alter_scale, noise_bands=noise_bands,
132 xover_band=xover_band)
133 t = T.freq_tables(RATE, cfg)
134 return cfg, t
135
136
137def stream_one_band(cfg, tables, active_p, n_frames=24, invf_mode=0):
138 """`n_frames` FIXFIX/2-env amp_res=1 frames (sbrchirp.py's `stream()`
139 engaging shape, byte-for-byte -- FIXFIX, num_env=2, amp_res=1, env0 at a
140 healthy mid value, noise0 at the quiet end so noise floor cannot bury the
141 line), core = one isolated tone at low QMF band `active_p`'s SECOND 4-bin
142 group (offset `D` of a band width into the band, not the ambiguous
143 boundary bin), held fixed; invf NONE, no harmonics."""
144 swb = P.SWB_LONG[SF_INDEX]
145 k = active_p * 16 + GROUP_OFFSET
146 found = bin_to_sfb_group(k, swb)
147 assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]"
148 sfb_idx, group_active = found
149 grid = dict(frame_class=0, num_env=2, freq_res=0)
150 frames = [P.silent(SF_INDEX)]
151 # sbrtables.py's `slot()` falls back to `T.FILL` (24 raw zero bits) for
152 # any delta slot the caller doesn't supply explicit bits for -- fine for
153 # the bootstrap probes that don't yet know a codebook's length, but for
154 # amp_res=1/coupling=0/df_env=df_noise=0 (this probe's exact config) the
155 # book is known: ENV30_F and NOISE_F (crates/ec-aac/src/sbr_tables.rs)
156 # both give delta=0 its SHORTEST codeword, (len=1, code=0). 24 zero bits
157 # where only 1 is consumed leaves 23 unconsumed zero bits per slot that
158 # bleed into every field transmitted after it (env1's raw start value,
159 # noise0/1, ...), silently corrupting it to whatever a run of stray zero
160 # bits happens to decode as -- this is round-29's "readout is wrong"
161 # candidate B made concrete, and the fix.
162 zero_delta = [0]
163 n_slots = 2 * (tables["n_low"] - 1) + 2 * (tables["n_q"] - 1)
164 for _ in range(n_frames):
165 c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0,
166 df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2])
167 w = P.BitW()
168 C.tone_core(w, sfb_idx, group_active)
169 body = F.sbr_bits_full(c, tables, grid, [zero_delta] * n_slots)
170 w.w(6, 3)
171 cnt = (len(body.bits) + 4 + 7) // 8
172 if cnt >= 15:
173 w.w(15, 4)
174 w.w(cnt - 15 + 1, 8)
175 else:
176 w.w(cnt, 4)
177 start = len(w)
178 w.w(13, 4)
179 w.wbits(body.bits)
180 while len(w) - start < cnt * 8:
181 w.w(0, 1)
182 w.w(7, 3)
183 frames.append(P.adts(w.pack(pad=0), SF_INDEX))
184 frames.append(P.silent(SF_INDEX))
185 return frames
186
187
188def our_decode(frames, tag):
189 src = f"/tmp/sbrpatchmap-our-{tag}.aac"
190 with open(src, "wb") as f:
191 f.write(b"".join(frames))
192 env = dict(os.environ, EC_AAC_SBR_SAME_RATE="1", EC_AAC_SBR_CHANNELS="1")
193 r = subprocess.run([OUR_DECODER, src], capture_output=True, env=env)
194 os.remove(src)
195 return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode(errors="replace")
196
197
198def averaged_spectrum(pcm, n_fft=4096, hop=2048, skip_samples=5120):
199 """Power spectrum averaged over several overlapping steady-state windows
200 (Welch-style) for a cleaner noise floor than a single FFT window."""
201 win = np.hanning(n_fft)
202 specs = []
203 start = skip_samples
204 while start + n_fft <= len(pcm):
205 seg = pcm[start : start + n_fft] * win
206 specs.append(np.abs(np.fft.rfft(seg)) ** 2)
207 start += hop
208 assert specs, "not enough samples past skip_samples for even one FFT window"
209 spec = np.mean(specs, axis=0)
210 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
211 return freqs, spec
212
213
214def find_lines(freqs, spec, lo_hz, hi_hz, floor_mult=8.0):
215 """Local-maximum bins within [lo_hz, hi_hz) whose power clearly exceeds
216 the local noise floor (median of the in-range spectrum) -- power GATES
217 detection only, never decides the mapping. Sub-bin frequency via
218 parabolic interpolation around each peak."""
219 idx = np.where((freqs >= lo_hz) & (freqs < hi_hz))[0]
220 if len(idx) < 3:
221 return []
222 floor = np.median(spec[idx])
223 if floor <= 0:
224 floor = np.finfo(float).tiny
225 df = freqs[1] - freqs[0]
226 lines = []
227 for j in range(1, len(idx) - 1):
228 i = idx[j]
229 if spec[i] > spec[i - 1] and spec[i] >= spec[i + 1] and spec[i] > floor_mult * floor:
230 a, b, c = spec[i - 1], spec[i], spec[i + 1]
231 denom = a - 2 * b + c
232 delta = 0.5 * (a - c) / denom if denom != 0 else 0.0
233 delta = max(-0.5, min(0.5, delta))
234 lines.append((freqs[i] + delta * df, float(b)))
235 return lines
236
237
238def measured_targets(freqs, spec, kx, k2, d=D, tol=0.06):
239 """Patch map read directly from fractional frequency offset: a detected
240 HF line in target band `q` counts as "source -> q" iff its offset within
241 the band matches `d` (direct) or `1 - d` (mirrored, per the charter's
242 filterbank-parity note -- logged, not discarded). Returns
243 (direct_targets, mirrored_targets, all_lines_for_debug)."""
244 lines = find_lines(freqs, spec, kx * BAND_HZ, k2 * BAND_HZ)
245 direct, mirrored, debug = [], [], []
246 for f, power in lines:
247 q = int(f // BAND_HZ)
248 frac = f / BAND_HZ - q
249 debug.append((q, round(frac, 3), power))
250 if abs(frac - d) <= tol:
251 direct.append(q)
252 elif abs(frac - (1 - d)) <= tol:
253 mirrored.append(q)
254 return sorted(set(direct)), sorted(set(mirrored)), debug
255
256
257def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
258 cfg, tables = make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band)
259 assert tables is not None, f"{label}: header does not produce valid tables"
260 kx, k2 = tables["kx"], tables["k2"]
261 print(f"\n== {label}: start={start_freq} stop={stop_freq} scale={freq_scale} alter={alter_scale}"
262 f" noise={noise_bands} xover={xover_band} -> kx={kx} k2={k2} n_q={tables['n_q']} ==")
263 patches = build_patches_predicted(kx, k2, tables["f_high"])
264 print(f" predicted patches (src_start, tgt_start, width): {patches}")
265
266 ref_map, our_map, warnings_seen = {}, {}, []
267 our_sane = True
268 for p in range(kx):
269 frames = stream_one_band(cfg, tables, p)
270 pcm_ref, err_ref = P.decode(frames, SF_INDEX, f"{label}-p{p}")
271 pcm_our, err_our = our_decode(frames, f"{label}-p{p}")
272 if NO_QUANT_WARNING in err_ref:
273 warnings_seen.append(p)
274 freqs_ref, spec_ref = averaged_spectrum(pcm_ref)
275 freqs_our, spec_our = averaged_spectrum(pcm_our)
276 d_ref, m_ref, dbg_ref = measured_targets(freqs_ref, spec_ref, kx, k2)
277 d_our, m_our, dbg_our = measured_targets(freqs_our, spec_our, kx, k2)
278 pred = predicted_targets(patches, p)
279 ref_map[p] = d_ref
280 our_map[p] = d_our
281 if d_our != pred:
282 our_sane = False
283 flag = "" if d_ref == pred else " <<< DIFFERS FROM PREDICTION"
284 our_flag = "" if d_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches"
285 mir = f" mirrored(ref)={m_ref}" if m_ref else ""
286 print(f" p={p:2d} predicted={pred} measured(ref)={d_ref}{flag}{mir} measured(ours)={d_our}{our_flag}"
287 f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]")
288
289 if warnings_seen:
290 print(f" !! {NO_QUANT_WARNING!r} present on p={warnings_seen} -- run NOT trustworthy, fix shape first")
291 else:
292 print(f" {NO_QUANT_WARNING!r} absent on every probe -- reference decode confirmed engaged")
293
294 if not our_sane:
295 print(" !! SANITY GATE FAILED: our decoder's measured map != build_patches prediction -- "
296 "do not trust the reference read below until this is resolved")
297 else:
298 print(" sanity gate passed: our decoder's measured map == build_patches prediction on every band")
299
300 return kx, k2, patches, ref_map, our_map, our_sane, warnings_seen
301
302
303if __name__ == "__main__":
304 assert os.path.exists(OUR_DECODER), f"build first: cargo build -p ec-aac --example adts_to_pcm ({OUR_DECODER})"
305 # Header A: the real file's ACTUAL SBR header, read straight off
306 # reeln's own bitstream via `EC_AAC_SBR_DEBUG=1` on our own decoder
307 # (start_freq=5 stop_freq=8 xover_band=0 freq_scale=2 alter_scale=1
308 # noise_bands=2 -> kx=14 k2=43 n_q=3) -- NOT the `sbr_hf.rs` unit test's
309 # `real_file_tables()`, whose stop_freq/xover_band guess (3/2) was wrong
310 # and gives a different, smaller kx=16 k2=29 header.
311 run_header("A-reeln", start_freq=5, stop_freq=8, freq_scale=2, alter_scale=1,
312 noise_bands=2, xover_band=0)
313 # Headers B and C: different start/stop/xover -> differently-shaped
314 # kx/k2, to pin the algorithm's shape rather than one lucky header.
315 run_header("B-alt", start_freq=8, stop_freq=10, freq_scale=2, alter_scale=1,
316 noise_bands=2, xover_band=1)
317 run_header("C-alt", start_freq=3, stop_freq=5, freq_scale=2, alter_scale=1,
318 noise_bands=2, xover_band=0)