forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB287d79cTahinli2 months ago3534 commits

sbrpatchmap.py397 lines, 19.8 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-34 fix: round-30's "32 core-MDCT bins per QMF band" was itself wrong
138# by 2x. Empirically re-derived by dumping our own decoder's QMF analysis
139# stage (EC_AAC_SBR_QMFDUMP=1, crates/ec-aac/src/sbr_chain.rs) for k =
140# active_p*32+16 across several p: the dominant analysis band always read
141# back as 2p or 2p+1, never p -- a source (low) QMF band is 16 core-MDCT
142# bins wide (1024-bin core MDCT / 64, not / 32), confirmed by re-running the
143# same dump with k = active_p*16+8 and seeing the dominant band land exactly
144# on p for every probed value (0, 5, 13). Placed at the BAND CENTER (bin 8
145# of the 16), which lands on a 4-bin group boundary (8 % 4 == 0) so
146# tone_core's grouping needs no fractional-offset trick. A center tone's
147# fractional position within its 16-bin source band is 0.5; patches
148# translate by whole band widths, so the translated line keeps frac == 0.5
149# in its target band too (or 1-0.5 == 0.5 under mirroring -- indistinguishable
150# at the center, which is fine, this probe only needs the TARGET BAND INDEX,
151# not direct/mirror discrimination).
152D = 0.5 # fractional offset (of one band width) the probe tone is placed at
153NO_QUANT_WARNING = "No quantized data read for sbr_dequant."
154
155
156def build_patches_predicted(kx, k2, f_high):
157 """Python port of `build_patches` (crates/ec-aac/src/sbr_hf.rs), for
158 comparing the reference's measured map against our own prediction."""
159 patches = []
160 if kx == 0 or k2 <= kx:
161 return patches
162 msb, sb = kx, kx
163 while sb < k2:
164 width, probe = 0, sb
165 while True:
166 border = next((b for b in f_high if b > probe), None)
167 if border is None:
168 break
169 iv = border - probe
170 if width + iv > msb or border > k2:
171 break
172 width += iv
173 probe = border
174 if width == 0:
175 width = min(k2 - sb, max(msb, 1))
176 source_start = msb - min(width, msb)
177 patches.append((source_start, sb, width))
178 sb += width
179 msb = kx if source_start == 0 else source_start
180 return patches
181
182
183def predicted_targets(patches, p):
184 out = []
185 for source_start, target_start, width in patches:
186 if source_start <= p < source_start + width:
187 out.append(target_start + (p - source_start))
188 return out
189
190
191def bin_to_sfb_group(k, swb):
192 for i in range(len(swb) - 1):
193 if swb[i] <= k < swb[i + 1]:
194 return i, (k - swb[i]) // 4
195 return None
196
197
198def make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
199 cfg = dict(T.DEFAULT, sf_index=SF_INDEX, start_freq=start_freq, stop_freq=stop_freq,
200 freq_scale=freq_scale, alter_scale=alter_scale, noise_bands=noise_bands,
201 xover_band=xover_band)
202 t = T.freq_tables(RATE, cfg)
203 return cfg, t
204
205
206def stream_one_band(cfg, tables, active_p, n_frames=24, invf_mode=0):
207 """`n_frames` FIXFIX/2-env amp_res=1 frames (sbrchirp.py's `stream()`
208 engaging shape, byte-for-byte -- FIXFIX, num_env=2, amp_res=1, env0 at a
209 healthy mid value, noise0 at the quiet end so noise floor cannot bury the
210 line), core = one isolated tone at low QMF band `active_p`'s SECOND 4-bin
211 group (offset `D` of a band width into the band, not the ambiguous
212 boundary bin), held fixed; invf NONE, no harmonics.
213
214 Round-34: noise0's raw index runs the OPPOSITE direction from what this
215 docstring's "quiet end" phrase assumed -- `dequant_noise`
216 (`crates/ec-aac/src/sbr_env.rs`) is `2^(NOISE_FLOOR_OFFSET - q_q)`, so a
217 LOW raw index is the LOUD end (matches the spec's own noise-floor
218 dequantization direction) and `noise0=[2, 2]` was injecting a broadband
219 noise floor loud enough to swamp the QMF-domain energy of the probe's own
220 tone (confirmed via EC_AAC_SBR_QMFDUMP=1: post-adjust energy was flat
221 across every target band, not peaked at the patched ones). `[30, 30]` is
222 the genuinely quiet end."""
223 swb = P.SWB_LONG[SF_INDEX]
224 k = active_p * 16 + 8
225 found = bin_to_sfb_group(k, swb)
226 assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]"
227 sfb_idx, group_active = found
228 grid = dict(frame_class=0, num_env=2, freq_res=0)
229 frames = [P.silent(SF_INDEX)]
230 # sbrtables.py's `slot()` falls back to `T.FILL` (24 raw zero bits) for
231 # any delta slot the caller doesn't supply explicit bits for -- fine for
232 # the bootstrap probes that don't yet know a codebook's length, but for
233 # amp_res=1/coupling=0/df_env=df_noise=0 (this probe's exact config) the
234 # book is known: ENV30_F and NOISE_F (crates/ec-aac/src/sbr_tables.rs)
235 # both give delta=0 its SHORTEST codeword, (len=1, code=0). 24 zero bits
236 # where only 1 is consumed leaves 23 unconsumed zero bits per slot that
237 # bleed into every field transmitted after it (env1's raw start value,
238 # noise0/1, ...), silently corrupting it to whatever a run of stray zero
239 # bits happens to decode as -- this is round-29's "readout is wrong"
240 # candidate B made concrete, and the fix.
241 zero_delta = [0]
242 n_slots = 2 * (tables["n_low"] - 1) + 2 * (tables["n_q"] - 1)
243 for _ in range(n_frames):
244 c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0,
245 df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[30, 30])
246 w = P.BitW()
247 C.tone_core(w, sfb_idx, group_active)
248 body = F.sbr_bits_full(c, tables, grid, [zero_delta] * n_slots)
249 w.w(6, 3)
250 cnt = (len(body.bits) + 4 + 7) // 8
251 if cnt >= 15:
252 w.w(15, 4)
253 w.w(cnt - 15 + 1, 8)
254 else:
255 w.w(cnt, 4)
256 start = len(w)
257 w.w(13, 4)
258 w.wbits(body.bits)
259 while len(w) - start < cnt * 8:
260 w.w(0, 1)
261 w.w(7, 3)
262 frames.append(P.adts(w.pack(pad=0), SF_INDEX))
263 frames.append(P.silent(SF_INDEX))
264 return frames
265
266
267def our_decode(frames, tag):
268 src = f"/tmp/sbrpatchmap-our-{tag}.aac"
269 with open(src, "wb") as f:
270 f.write(b"".join(frames))
271 env = dict(os.environ, EC_AAC_SBR_SAME_RATE="1", EC_AAC_SBR_CHANNELS="1")
272 r = subprocess.run([OUR_DECODER, src], capture_output=True, env=env)
273 os.remove(src)
274 return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode(errors="replace")
275
276
277def averaged_spectrum(pcm, n_fft=4096, hop=2048, skip_samples=5120):
278 """Power spectrum averaged over several overlapping steady-state windows
279 (Welch-style) for a cleaner noise floor than a single FFT window."""
280 win = np.hanning(n_fft)
281 specs = []
282 start = skip_samples
283 while start + n_fft <= len(pcm):
284 seg = pcm[start : start + n_fft] * win
285 specs.append(np.abs(np.fft.rfft(seg)) ** 2)
286 start += hop
287 assert specs, "not enough samples past skip_samples for even one FFT window"
288 spec = np.mean(specs, axis=0)
289 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
290 return freqs, spec
291
292
293def find_lines(freqs, spec, lo_hz, hi_hz, floor_mult=8.0):
294 """Local-maximum bins within [lo_hz, hi_hz) whose power clearly exceeds
295 the local noise floor (median of the in-range spectrum) -- power GATES
296 detection only, never decides the mapping. Sub-bin frequency via
297 parabolic interpolation around each peak."""
298 idx = np.where((freqs >= lo_hz) & (freqs < hi_hz))[0]
299 if len(idx) < 3:
300 return []
301 floor = np.median(spec[idx])
302 if floor <= 0:
303 floor = np.finfo(float).tiny
304 df = freqs[1] - freqs[0]
305 lines = []
306 for j in range(1, len(idx) - 1):
307 i = idx[j]
308 if spec[i] > spec[i - 1] and spec[i] >= spec[i + 1] and spec[i] > floor_mult * floor:
309 a, b, c = spec[i - 1], spec[i], spec[i + 1]
310 denom = a - 2 * b + c
311 delta = 0.5 * (a - c) / denom if denom != 0 else 0.0
312 delta = max(-0.5, min(0.5, delta))
313 lines.append((freqs[i] + delta * df, float(b)))
314 return lines
315
316
317def measured_targets(freqs, spec, kx, k2, d=D, tol=0.06):
318 """Patch map read directly from fractional frequency offset: a detected
319 HF line in target band `q` counts as "source -> q" iff its offset within
320 the band matches `d` (direct) or `1 - d` (mirrored, per the charter's
321 filterbank-parity note -- logged, not discarded). Returns
322 (direct_targets, mirrored_targets, all_lines_for_debug)."""
323 lines = find_lines(freqs, spec, kx * BAND_HZ, k2 * BAND_HZ)
324 direct, mirrored, debug = [], [], []
325 for f, power in lines:
326 q = int(f // BAND_HZ)
327 frac = f / BAND_HZ - q
328 debug.append((q, round(frac, 3), power))
329 if abs(frac - d) <= tol:
330 direct.append(q)
331 elif abs(frac - (1 - d)) <= tol:
332 mirrored.append(q)
333 return sorted(set(direct)), sorted(set(mirrored)), debug
334
335
336def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
337 cfg, tables = make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band)
338 assert tables is not None, f"{label}: header does not produce valid tables"
339 kx, k2 = tables["kx"], tables["k2"]
340 print(f"\n== {label}: start={start_freq} stop={stop_freq} scale={freq_scale} alter={alter_scale}"
341 f" noise={noise_bands} xover={xover_band} -> kx={kx} k2={k2} n_q={tables['n_q']} ==")
342 patches = build_patches_predicted(kx, k2, tables["f_high"])
343 print(f" predicted patches (src_start, tgt_start, width): {patches}")
344
345 ref_map, our_map, warnings_seen = {}, {}, []
346 our_sane = True
347 for p in range(kx):
348 frames = stream_one_band(cfg, tables, p)
349 pcm_ref, err_ref = ref_decode(frames, f"{label}-p{p}")
350 pcm_our, err_our = our_decode(frames, f"{label}-p{p}")
351 if NO_QUANT_WARNING in err_ref:
352 warnings_seen.append(p)
353 freqs_ref, spec_ref = averaged_spectrum(pcm_ref)
354 freqs_our, spec_our = averaged_spectrum(pcm_our)
355 d_ref, m_ref, dbg_ref = measured_targets(freqs_ref, spec_ref, kx, k2)
356 d_our, m_our, dbg_our = measured_targets(freqs_our, spec_our, kx, k2)
357 pred = predicted_targets(patches, p)
358 ref_map[p] = d_ref
359 our_map[p] = d_our
360 if d_our != pred:
361 our_sane = False
362 flag = "" if d_ref == pred else " <<< DIFFERS FROM PREDICTION"
363 our_flag = "" if d_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches"
364 mir = f" mirrored(ref)={m_ref}" if m_ref else ""
365 print(f" p={p:2d} predicted={pred} measured(ref)={d_ref}{flag}{mir} measured(ours)={d_our}{our_flag}"
366 f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]")
367
368 if warnings_seen:
369 print(f" !! {NO_QUANT_WARNING!r} present on p={warnings_seen} -- run NOT trustworthy, fix shape first")
370 else:
371 print(f" {NO_QUANT_WARNING!r} absent on every probe -- reference decode confirmed engaged")
372
373 if not our_sane:
374 print(" !! SANITY GATE FAILED: our decoder's measured map != build_patches prediction -- "
375 "do not trust the reference read below until this is resolved")
376 else:
377 print(" sanity gate passed: our decoder's measured map == build_patches prediction on every band")
378
379 return kx, k2, patches, ref_map, our_map, our_sane, warnings_seen
380
381
382if __name__ == "__main__":
383 assert os.path.exists(OUR_DECODER), f"build first: cargo build -p ec-aac --example adts_to_pcm ({OUR_DECODER})"
384 # Header A: the real file's ACTUAL SBR header, read straight off
385 # reeln's own bitstream via `EC_AAC_SBR_DEBUG=1` on our own decoder
386 # (start_freq=5 stop_freq=8 xover_band=0 freq_scale=2 alter_scale=1
387 # noise_bands=2 -> kx=14 k2=43 n_q=3) -- NOT the `sbr_hf.rs` unit test's
388 # `real_file_tables()`, whose stop_freq/xover_band guess (3/2) was wrong
389 # and gives a different, smaller kx=16 k2=29 header.
390 run_header("A-reeln", start_freq=5, stop_freq=8, freq_scale=2, alter_scale=1,
391 noise_bands=2, xover_band=0)
392 # Headers B and C: different start/stop/xover -> differently-shaped
393 # kx/k2, to pin the algorithm's shape rather than one lucky header.
394 run_header("B-alt", start_freq=8, stop_freq=10, freq_scale=2, alter_scale=1,
395 noise_bands=2, xover_band=1)
396 run_header("C-alt", start_freq=3, stop_freq=5, freq_scale=2, alter_scale=1,
397 noise_bands=2, xover_band=0)