forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB0a60b22Tahinli3 months ago150 commits

sbrpatchmap.py382 lines, 18.9 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-30): the bin-per-band placement math is now fixed -- a source
40QMF band is 1024/32 == 32 core-MDCT bins wide, not 16, so `stream_one_band`
41places its probe tone at `k = active_p * 32 + 16` (the band CENTER, which
42also lands exactly on a 4-bin group boundary, so no fractional-offset trick
43is needed; `D` is 0.5, not 0.25). That fix, however, could NOT be calibrated
44against the header-A anchor `(13, 42, 1)`, because a DEEPER, BLOCKING defect
45was found first: the reference decoder is not actually engaging its SBR
46upsampling path for ANY of these synthetic ADTS probe streams at all, for
47either `tone_core` or `broadband_core_bits` content, regardless of header
48shape (A's kx=14/k2=43 and the round-19 DEFAULT shape both affected
49identically) --
50
51 - `ffprobe` on a probe stream built by `stream_one_band`/`stream` reports
52 `codec_name=aac`, NO `profile=HE-AAC`, `sample_rate=22050` (the bare
53 core/ADTS-declared rate) -- vs. the real `~/Music/reeln.mp4`
54 fixture (round-19's working baseline), which reports
55 `profile=HE-AAC sample_rate=44100`. Decoded PCM length for a 26-frame
56 probe is exactly `26 * 1024` samples, i.e. literally core-rate output,
57 never doubled -- this is not just a metadata-reporting quirk, the actual
58 decoded sample count proves SBR upsampling never ran.
59 - This is NOT visible from the `"No quantized data read for sbr_dequant."`
60 warning's raw occurrence count alone: it fires only ONCE across a
61 26-frame stream (24 of them real SBR frames with `header=1` every
62 frame) -- by the charter's own "once-or-twice = benign" heuristic this
63 reads as a clean, engaged run. It is NOT: an envelope-value sweep
64 (`env0` raw 3..63, `amp_res=1`) shows the power *inside* the
65 `[kx*BAND_HZ, k2*BAND_HZ)` window our own table math predicts is
66 completely FLAT (no order-of-magnitude movement -- fails the charter's
67 own engagement test outright), while a huge, smoothly env0-scaling
68 power increase (orders of magnitude, from ~18 to ~6e9) shows up OUTSIDE
69 that window, concentrated roughly 9-15 kHz and tailing out past 20 kHz
70 -- i.e. real envelope-driven energy exists, but not where our table
71 math says the SBR target band should be, AND it never causes the
72 decoder to report itself as HE-AAC/44100 the way the real file does.
73 The likely explanation: without an out-of-band MPEG-4 `AudioSpecificConfig`
74 (which the real `.mp4` fixture's container carries and our bare `.aac`
75 ADTS files do not), the reference decoder's *implicit* SBR detection
76 from frame 1's fill element is deciding "no SBR" once, on the very
77 first payload frame, and locks the whole stream's output rate to
78 core-only from then on even though later frames carry ostensibly valid
79 bits -- consistent with, and a generalization of, round-27's dead-end
80 (`tone_core` "does not round-trip" against the real header/grid shape),
81 now shown to affect `broadband_core_bits` identically, so it is a
82 property of the shared frame/extension-payload construction in
83 `stream()`/`stream_one_band()`, not of either core-spectrum writer.
84
85Sanity gate: DO NOT trust `measured(ref)` output below -- it is not reading
86genuine SBR-patched content at all, in either the old or new placement math.
87Task 2/3/4 (reading and acting on the reference's map) remain BLOCKED, now
88on getting the synthetic ADTS fixture writer to genuinely engage the
89reference's implicit SBR/HE-AAC upsampling path (matching the real file's
90`profile=HE-AAC sample_rate=44100`), not on the placement-math bug this
91round set out to fix.
92"""
93import os
94import subprocess
95import sys
96
97import numpy as np
98
99HERE = os.path.dirname(os.path.abspath(__file__))
100sys.path.insert(0, HERE)
101
102import sbrchirp as C # noqa: E402
103import sbrpayload_fixtures as F # noqa: E402
104import sbrprobe as P # noqa: E402
105import sbrtables as T # noqa: E402
106
107SF_INDEX = 7
108RATE = 44100
109OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm")
110# Round-32: field-by-field bisection (scripts/aac-tables/sbrbisect.py) proved
111# stream_one_band's bit construction ALREADY engages the reference's SBR
112# dequant once wrapped in an explicit-SBR ASC (env0 sweep moves in-band power
113# ~1e12x, warning fires once at stream head only, PCM length doubles) --
114# every flip tried (header, core content, delta words) engaged identically.
115# The round-30/31 "flat" reading was this module still calling `P.decode`
116# (bare ADTS, implicit per-frame detection) on the reference side while
117# `wrap_sbr` (round-31) sat unused; `ref_decode` below is the fix.
118WRAP_SBR = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/wrap_sbr")
119
120
121def ref_decode(frames, tag):
122 assert os.path.exists(WRAP_SBR), f"build first: cargo build -p ec-aac --example wrap_sbr ({WRAP_SBR})"
123 raw = f"/tmp/sbrpatchmap-ref-{tag}.aac"
124 mp4 = f"/tmp/sbrpatchmap-ref-{tag}.mp4"
125 with open(raw, "wb") as f:
126 f.write(b"".join(frames))
127 r = subprocess.run([WRAP_SBR, raw, "22050", "44100", "1", mp4], capture_output=True)
128 assert r.returncode == 0, f"wrap_sbr failed: {r.stderr.decode()}"
129 dec = subprocess.run(
130 ["ffmpeg", "-v", "error", "-i", mp4, "-f", "f32le", "-ac", "1", "-"],
131 capture_output=True,
132 )
133 os.remove(raw)
134 os.remove(mp4)
135 return np.frombuffer(dec.stdout, dtype="<f4").astype(np.float64), dec.stderr.decode(errors="replace")
136BAND_HZ = RATE / 128 # QMF band width, both source and target index units
137# Round-30 fix: a source (low) QMF band is 32 core-MDCT bins wide (1024-bin
138# core MDCT / 32 core bands), not 16 -- every prior round's k = p*16 + offset
139# was reading the wrong bin for band p entirely, not just the wrong in-band
140# offset. Placed at the BAND CENTER (bin 16 of the 32), which lands exactly
141# on a 4-bin group boundary (16 % 4 == 0) so tone_core's grouping needs no
142# fractional-offset trick. A center tone's fractional position within its
143# 32-bin source band is 0.5; patches translate by whole band widths, so the
144# translated line keeps frac == 0.5 in its target band too (or 1-0.5 == 0.5
145# under mirroring -- indistinguishable at the center, which is fine, this
146# probe only needs the TARGET BAND INDEX, not direct/mirror discrimination).
147D = 0.5 # fractional offset (of one band width) the probe tone is placed at
148NO_QUANT_WARNING = "No quantized data read for sbr_dequant."
149
150
151def build_patches_predicted(kx, k2, f_high):
152 """Python port of `build_patches` (crates/ec-aac/src/sbr_hf.rs), for
153 comparing the reference's measured map against our own prediction."""
154 patches = []
155 if kx == 0 or k2 <= kx:
156 return patches
157 msb, sb = kx, kx
158 while sb < k2:
159 width, probe = 0, sb
160 while True:
161 border = next((b for b in f_high if b > probe), None)
162 if border is None:
163 break
164 iv = border - probe
165 if width + iv > msb or border > k2:
166 break
167 width += iv
168 probe = border
169 if width == 0:
170 width = min(k2 - sb, max(msb, 1))
171 source_start = msb - min(width, msb)
172 patches.append((source_start, sb, width))
173 sb += width
174 msb = kx if source_start == 0 else source_start
175 return patches
176
177
178def predicted_targets(patches, p):
179 out = []
180 for source_start, target_start, width in patches:
181 if source_start <= p < source_start + width:
182 out.append(target_start + (p - source_start))
183 return out
184
185
186def bin_to_sfb_group(k, swb):
187 for i in range(len(swb) - 1):
188 if swb[i] <= k < swb[i + 1]:
189 return i, (k - swb[i]) // 4
190 return None
191
192
193def make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
194 cfg = dict(T.DEFAULT, sf_index=SF_INDEX, start_freq=start_freq, stop_freq=stop_freq,
195 freq_scale=freq_scale, alter_scale=alter_scale, noise_bands=noise_bands,
196 xover_band=xover_band)
197 t = T.freq_tables(RATE, cfg)
198 return cfg, t
199
200
201def stream_one_band(cfg, tables, active_p, n_frames=24, invf_mode=0):
202 """`n_frames` FIXFIX/2-env amp_res=1 frames (sbrchirp.py's `stream()`
203 engaging shape, byte-for-byte -- FIXFIX, num_env=2, amp_res=1, env0 at a
204 healthy mid value, noise0 at the quiet end so noise floor cannot bury the
205 line), core = one isolated tone at low QMF band `active_p`'s SECOND 4-bin
206 group (offset `D` of a band width into the band, not the ambiguous
207 boundary bin), held fixed; invf NONE, no harmonics."""
208 swb = P.SWB_LONG[SF_INDEX]
209 k = active_p * 32 + 16
210 found = bin_to_sfb_group(k, swb)
211 assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]"
212 sfb_idx, group_active = found
213 grid = dict(frame_class=0, num_env=2, freq_res=0)
214 frames = [P.silent(SF_INDEX)]
215 # sbrtables.py's `slot()` falls back to `T.FILL` (24 raw zero bits) for
216 # any delta slot the caller doesn't supply explicit bits for -- fine for
217 # the bootstrap probes that don't yet know a codebook's length, but for
218 # amp_res=1/coupling=0/df_env=df_noise=0 (this probe's exact config) the
219 # book is known: ENV30_F and NOISE_F (crates/ec-aac/src/sbr_tables.rs)
220 # both give delta=0 its SHORTEST codeword, (len=1, code=0). 24 zero bits
221 # where only 1 is consumed leaves 23 unconsumed zero bits per slot that
222 # bleed into every field transmitted after it (env1's raw start value,
223 # noise0/1, ...), silently corrupting it to whatever a run of stray zero
224 # bits happens to decode as -- this is round-29's "readout is wrong"
225 # candidate B made concrete, and the fix.
226 zero_delta = [0]
227 n_slots = 2 * (tables["n_low"] - 1) + 2 * (tables["n_q"] - 1)
228 for _ in range(n_frames):
229 c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0,
230 df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2])
231 w = P.BitW()
232 C.tone_core(w, sfb_idx, group_active)
233 body = F.sbr_bits_full(c, tables, grid, [zero_delta] * n_slots)
234 w.w(6, 3)
235 cnt = (len(body.bits) + 4 + 7) // 8
236 if cnt >= 15:
237 w.w(15, 4)
238 w.w(cnt - 15 + 1, 8)
239 else:
240 w.w(cnt, 4)
241 start = len(w)
242 w.w(13, 4)
243 w.wbits(body.bits)
244 while len(w) - start < cnt * 8:
245 w.w(0, 1)
246 w.w(7, 3)
247 frames.append(P.adts(w.pack(pad=0), SF_INDEX))
248 frames.append(P.silent(SF_INDEX))
249 return frames
250
251
252def our_decode(frames, tag):
253 src = f"/tmp/sbrpatchmap-our-{tag}.aac"
254 with open(src, "wb") as f:
255 f.write(b"".join(frames))
256 env = dict(os.environ, EC_AAC_SBR_SAME_RATE="1", EC_AAC_SBR_CHANNELS="1")
257 r = subprocess.run([OUR_DECODER, src], capture_output=True, env=env)
258 os.remove(src)
259 return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode(errors="replace")
260
261
262def averaged_spectrum(pcm, n_fft=4096, hop=2048, skip_samples=5120):
263 """Power spectrum averaged over several overlapping steady-state windows
264 (Welch-style) for a cleaner noise floor than a single FFT window."""
265 win = np.hanning(n_fft)
266 specs = []
267 start = skip_samples
268 while start + n_fft <= len(pcm):
269 seg = pcm[start : start + n_fft] * win
270 specs.append(np.abs(np.fft.rfft(seg)) ** 2)
271 start += hop
272 assert specs, "not enough samples past skip_samples for even one FFT window"
273 spec = np.mean(specs, axis=0)
274 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
275 return freqs, spec
276
277
278def find_lines(freqs, spec, lo_hz, hi_hz, floor_mult=8.0):
279 """Local-maximum bins within [lo_hz, hi_hz) whose power clearly exceeds
280 the local noise floor (median of the in-range spectrum) -- power GATES
281 detection only, never decides the mapping. Sub-bin frequency via
282 parabolic interpolation around each peak."""
283 idx = np.where((freqs >= lo_hz) & (freqs < hi_hz))[0]
284 if len(idx) < 3:
285 return []
286 floor = np.median(spec[idx])
287 if floor <= 0:
288 floor = np.finfo(float).tiny
289 df = freqs[1] - freqs[0]
290 lines = []
291 for j in range(1, len(idx) - 1):
292 i = idx[j]
293 if spec[i] > spec[i - 1] and spec[i] >= spec[i + 1] and spec[i] > floor_mult * floor:
294 a, b, c = spec[i - 1], spec[i], spec[i + 1]
295 denom = a - 2 * b + c
296 delta = 0.5 * (a - c) / denom if denom != 0 else 0.0
297 delta = max(-0.5, min(0.5, delta))
298 lines.append((freqs[i] + delta * df, float(b)))
299 return lines
300
301
302def measured_targets(freqs, spec, kx, k2, d=D, tol=0.06):
303 """Patch map read directly from fractional frequency offset: a detected
304 HF line in target band `q` counts as "source -> q" iff its offset within
305 the band matches `d` (direct) or `1 - d` (mirrored, per the charter's
306 filterbank-parity note -- logged, not discarded). Returns
307 (direct_targets, mirrored_targets, all_lines_for_debug)."""
308 lines = find_lines(freqs, spec, kx * BAND_HZ, k2 * BAND_HZ)
309 direct, mirrored, debug = [], [], []
310 for f, power in lines:
311 q = int(f // BAND_HZ)
312 frac = f / BAND_HZ - q
313 debug.append((q, round(frac, 3), power))
314 if abs(frac - d) <= tol:
315 direct.append(q)
316 elif abs(frac - (1 - d)) <= tol:
317 mirrored.append(q)
318 return sorted(set(direct)), sorted(set(mirrored)), debug
319
320
321def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
322 cfg, tables = make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band)
323 assert tables is not None, f"{label}: header does not produce valid tables"
324 kx, k2 = tables["kx"], tables["k2"]
325 print(f"\n== {label}: start={start_freq} stop={stop_freq} scale={freq_scale} alter={alter_scale}"
326 f" noise={noise_bands} xover={xover_band} -> kx={kx} k2={k2} n_q={tables['n_q']} ==")
327 patches = build_patches_predicted(kx, k2, tables["f_high"])
328 print(f" predicted patches (src_start, tgt_start, width): {patches}")
329
330 ref_map, our_map, warnings_seen = {}, {}, []
331 our_sane = True
332 for p in range(kx):
333 frames = stream_one_band(cfg, tables, p)
334 pcm_ref, err_ref = ref_decode(frames, f"{label}-p{p}")
335 pcm_our, err_our = our_decode(frames, f"{label}-p{p}")
336 if NO_QUANT_WARNING in err_ref:
337 warnings_seen.append(p)
338 freqs_ref, spec_ref = averaged_spectrum(pcm_ref)
339 freqs_our, spec_our = averaged_spectrum(pcm_our)
340 d_ref, m_ref, dbg_ref = measured_targets(freqs_ref, spec_ref, kx, k2)
341 d_our, m_our, dbg_our = measured_targets(freqs_our, spec_our, kx, k2)
342 pred = predicted_targets(patches, p)
343 ref_map[p] = d_ref
344 our_map[p] = d_our
345 if d_our != pred:
346 our_sane = False
347 flag = "" if d_ref == pred else " <<< DIFFERS FROM PREDICTION"
348 our_flag = "" if d_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches"
349 mir = f" mirrored(ref)={m_ref}" if m_ref else ""
350 print(f" p={p:2d} predicted={pred} measured(ref)={d_ref}{flag}{mir} measured(ours)={d_our}{our_flag}"
351 f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]")
352
353 if warnings_seen:
354 print(f" !! {NO_QUANT_WARNING!r} present on p={warnings_seen} -- run NOT trustworthy, fix shape first")
355 else:
356 print(f" {NO_QUANT_WARNING!r} absent on every probe -- reference decode confirmed engaged")
357
358 if not our_sane:
359 print(" !! SANITY GATE FAILED: our decoder's measured map != build_patches prediction -- "
360 "do not trust the reference read below until this is resolved")
361 else:
362 print(" sanity gate passed: our decoder's measured map == build_patches prediction on every band")
363
364 return kx, k2, patches, ref_map, our_map, our_sane, warnings_seen
365
366
367if __name__ == "__main__":
368 assert os.path.exists(OUR_DECODER), f"build first: cargo build -p ec-aac --example adts_to_pcm ({OUR_DECODER})"
369 # Header A: the real file's ACTUAL SBR header, read straight off
370 # reeln's own bitstream via `EC_AAC_SBR_DEBUG=1` on our own decoder
371 # (start_freq=5 stop_freq=8 xover_band=0 freq_scale=2 alter_scale=1
372 # noise_bands=2 -> kx=14 k2=43 n_q=3) -- NOT the `sbr_hf.rs` unit test's
373 # `real_file_tables()`, whose stop_freq/xover_band guess (3/2) was wrong
374 # and gives a different, smaller kx=16 k2=29 header.
375 run_header("A-reeln", start_freq=5, stop_freq=8, freq_scale=2, alter_scale=1,
376 noise_bands=2, xover_band=0)
377 # Headers B and C: different start/stop/xover -> differently-shaped
378 # kx/k2, to pin the algorithm's shape rather than one lucky header.
379 run_header("B-alt", start_freq=8, stop_freq=10, freq_scale=2, alter_scale=1,
380 noise_bands=2, xover_band=1)
381 run_header("C-alt", start_freq=3, stop_freq=5, freq_scale=2, alter_scale=1,
382 noise_bands=2, xover_band=0)