forge
Explore
Log in

Don't you dare go Hollow

Stop sbrpatchmap's delta-huffman filler desyncing envelope1/noise1

Browse files at this commit

a913c8463d4bd520ab43837841cd80ec10d4d172Ahmet Kaan GümüşParent: 23f057e
  • fix
    • stop sbrpatchmap's delta-huffman filler desyncing envelope1/noise1
Show full message
fix(sbr-tables): stop sbrpatchmap's delta-huffman filler desyncing envelope1/noise1

sbr_bits_full's slot() defaulted every un-supplied delta band to T.FILL (24
raw zero bits); ENV30_F/NOISE_F's shortest codeword (delta=0) is only 1 bit,
so 23 leftover zero bits per slot bled into every field transmitted after
the first multi-band delta run, silently corrupting envelope1/noise1's raw
values to 0 regardless of what stream_one_band asked for (confirmed via
EC_AAC_SBR_DEBUG before/after). Also switched the readout from power buckets
to fractional-frequency-offset line detection per round-29's charter, and
moved the tone off the ambiguous band-boundary bin.

Sanity gate (ours vs build_patches) still fails: localized to the tone's
bin-placement assumption (k = p*16), not build_patches or the runtime
(patches dumped via EC_AAC_SBR_DEBUG match build_patches exactly). Left
documented as open in the module docstring; reference maps not read this
round since Task 1's own gate blocks it.
scripts/aac-tables/sbrpatchmap.pymodified+167 -59
@@ -1,24 +1,65 @@
1 #!/usr/bin/env python31 #!/usr/bin/env python3
2-"""Round-27: measures the reference decoder's ACTUAL SBR HF patch map (which2+"""Round-29: measures the reference decoder's ACTUAL SBR HF patch map (which
3 low QMF source band feeds which high target band), by isolating one source3 low QMF source band feeds which high target band), by isolating one source
4-band at a time and reading off which target bands carry power in the output.4+band at a time and reading off the FRACTIONAL FREQUENCY OFFSET of the
5-5+resulting HF line(s), not their power.
6-Method (one-band-at-a-time, simpler than a multi-line comb and avoids any6+
7-ambiguity from overlapping lines): the core spectrum for a probe frame is a7+Round-28 found that a power-bucket readout cannot work: the envelope adjuster
8-single isolated MDCT bin -- `tone_core()` in `sbrchirp.py`, already proven to8+renormalizes every target band's POWER to the transmitted envelope regardless
9-place value 2 in one 4-bin group and ZERO_HCB everywhere else -- at the first9+of patch content, so every source band lit the SAME target range at similar
10-bin of low QMF band `p` (`k = p*16`, always a group boundary since a QMF band10+power (expected physics, not a bug). Gains rescale amplitude, never a line's
11-is 16 MDCT bins wide and a group is 4). Patching copies that source band's11+frequency position within its band, so the fix is to read frequency instead.
12-complex QMF series verbatim (mixed by LPC/chirp, which round-19 already12+
13-measured as a <0.1% power effect regardless of `bs_invf_mode`) into every13+Method: the core spectrum for a probe frame is a single isolated MDCT bin --
14-target band any patch maps it to, so an FFT of the decoded output that finds14+`tone_core()` in `sbrchirp.py` -- placed not at low QMF band `p`'s first bin
15-elevated power in target band `q` means "patch measured: source `p` -> target15+(a group/band boundary, ambiguous under FFT leakage and coincident with the
16-`q`" directly, no fractional-offset bookkeeping needed.16+target band edge too) but at its SECOND 4-bin group (`k = p*16 + 4`), i.e. a
17+known, non-zero fractional offset `D = 0.25` of a QMF band's width inside
18+band `p` (0.25 is the finest offset `tone_core`'s group granularity allows;
19+any of 0.25/0.5/0.75 is equally "distinctive", 0.25 chosen arbitrarily).
20+Patching copies that source band's complex QMF series verbatim into every
21+target band any patch maps it to, translating the tone in frequency by an
22+integer number of band widths -- so the offset is preserved (or, per the
23+charter's note on filterbank parity, possibly mirrored to `1 - D`) in
24+whichever target band(s) the patch actually lit up. An averaged FFT of the
25+decoded 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)`
27+and `frac = f/bw - q` are computed, and a line is read as "source `p` ->
28+target `q`" iff `frac` is within a few percent of `D` (direct) or `1 - D`
29+(mirrored, logged separately as data, not discarded).
17 30
18 Runs the same probes through our own decoder via the `adts_to_pcm` example31 Runs the same probes through our own decoder via the `adts_to_pcm` example
19 (`cargo build -p ec-aac --example adts_to_pcm`) for the sanity cross-check the32 (`cargo build -p ec-aac --example adts_to_pcm`) for the sanity cross-check the
20 charter requires: our measured map must equal `build_patches`' prediction, or33 charter requires: our measured map must equal `build_patches`' prediction, or
21-the fingerprint method itself is the thing that's broken.34+the fingerprint method itself is the thing that's broken. Also checks the
35+reference's stderr for "No quantized data read for sbr_dequant." -- if
36+present the run used a shape that leaves the SBR gain stage unengaged and the
37+decode is not trustworthy.
38+
39+STATUS (round-29): the sanity gate still FAILS after two real fixes landed
40+this round (see the ledger's round-29 facts): (1) `sbr_bits_full`'s `slot()`
41+default (`T.FILL`, 24 raw zero bits) desyncs the bitstream whenever a
42+multi-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
44+leak into every field transmitted after it; `stream_one_band` now supplies
45+exactly 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,
47+were 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,
50+inherited unchanged here) does not track the true source-band placement --
51+calibration by sweeping raw bin `k` and reading which target band lights up
52+shows a clean *32*-bin-per-band slope (not 16) locally, but with an offset
53+that is NOT a fixed constant across headers (k=64 lands on `target == kx`
54+for headers A and C, whose `patches[0]` happens to have `source_start == 0`,
55+but for header B -- `xover_band=1`, whose `patches[0]` has `source_start ==
56+2` -- k=64 *also* lands on `target == kx`, meaning it tracked `source_start`
57+itself, 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
59+tables' own low-band structure rather than assumed, which this round did not
60+reach. Sanity gate: DO NOT trust `measured(ref)` output below until this is
61+resolved -- Task 2/3 (reading and acting on the reference's map) are blocked
62+on it.
22 """63 """
23 import os64 import os
24 import subprocess65 import subprocess
@@ -37,6 +78,10 @@ import sbrtables as T # noqa: E402
37 SF_INDEX = 778 SF_INDEX = 7
38 RATE = 4410079 RATE = 44100
39 OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm")80 OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm")
81+BAND_HZ = RATE / 128 # QMF band width, both source and target index units
82+D = 0.25 # fractional offset (of one band width) the probe tone is placed at
83+GROUP_OFFSET = 4 # bins: 4/16 == D, the finest offset tone_core's grouping allows
84+NO_QUANT_WARNING = "No quantized data read for sbr_dequant."
40 85
41 86
42 def build_patches_predicted(kx, k2, f_high):87 def build_patches_predicted(kx, k2, f_high):
@@ -89,23 +134,39 @@ def make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xov
89 return cfg, t134 return cfg, t
90 135
91 136
92-def stream_one_band(cfg, tables, active_p, n_frames=16, invf_mode=0):137+def stream_one_band(cfg, tables, active_p, n_frames=24, invf_mode=0):
93- """`n_frames` FIXFIX/2-env amp_res=1 frames (round-19's engaging shape),138+ """`n_frames` FIXFIX/2-env amp_res=1 frames (sbrchirp.py's `stream()`
94- core = one isolated tone at low QMF band `active_p`'s first bin, held139+ engaging shape, byte-for-byte -- FIXFIX, num_env=2, amp_res=1, env0 at a
95- fixed; envelope flat/loud, noise floor minimal, invf NONE, no harmonics."""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."""
96 swb = P.SWB_LONG[SF_INDEX]144 swb = P.SWB_LONG[SF_INDEX]
97- k = active_p * 16145+ k = active_p * 16 + GROUP_OFFSET
98 found = bin_to_sfb_group(k, swb)146 found = bin_to_sfb_group(k, swb)
99 assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]"147 assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]"
100 sfb_idx, group_active = found148 sfb_idx, group_active = found
101 grid = dict(frame_class=0, num_env=2, freq_res=0)149 grid = dict(frame_class=0, num_env=2, freq_res=0)
102 frames = [P.silent(SF_INDEX)]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)
103 for _ in range(n_frames):164 for _ in range(n_frames):
104 c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0,165 c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0,
105 df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2])166 df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2])
106 w = P.BitW()167 w = P.BitW()
107 C.tone_core(w, sfb_idx, group_active)168 C.tone_core(w, sfb_idx, group_active)
108- body = F.sbr_bits_full(c, tables, grid, [])169+ body = F.sbr_bits_full(c, tables, grid, [zero_delta] * n_slots)
109 w.w(6, 3)170 w.w(6, 3)
110 cnt = (len(body.bits) + 4 + 7) // 8171 cnt = (len(body.bits) + 4 + 7) // 8
111 if cnt >= 15:172 if cnt >= 15:
@@ -134,34 +195,63 @@ def our_decode(frames, tag):
134 return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode(errors="replace")195 return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode(errors="replace")
135 196
136 197
137-def band_powers(pcm, kx, k2, n_fft=8192, skip_samples=5120):198+def averaged_spectrum(pcm, n_fft=4096, hop=2048, skip_samples=5120):
138- """Power in each target band `q in [kx, k2)`, from a steady-state FFT199+ """Power spectrum averaged over several overlapping steady-state windows
139- window (RATE/128 Hz per band, `n_fft=8192` gives ~5.4 Hz/bin -- fine200+ (Welch-style) for a cleaner noise floor than a single FFT window."""
140- enough that a single active source band's line falls cleanly in one201+ win = np.hanning(n_fft)
141- band's bin range even without knowing its exact intra-band position)."""202+ specs = []
142- seg = pcm[skip_samples : skip_samples + n_fft]203+ start = skip_samples
143- if len(seg) < n_fft:204+ while start + n_fft <= len(pcm):
144- seg = np.pad(seg, (0, n_fft - len(seg)))205+ seg = pcm[start : start + n_fft] * win
145- spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2206+ 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)
146 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)210 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
147- powers = {}211+ return freqs, spec
148- for q in range(kx, k2):212+
149- lo, hi = q * RATE / 128, (q + 1) * RATE / 128213+
150- mask = (freqs >= lo) & (freqs < hi)214+def find_lines(freqs, spec, lo_hz, hi_hz, floor_mult=8.0):
151- powers[q] = float(spec[mask].sum())215+ """Local-maximum bins within [lo_hz, hi_hz) whose power clearly exceeds
152- return powers216+ the local noise floor (median of the in-range spectrum) -- power GATES
153-217+ detection only, never decides the mapping. Sub-bin frequency via
154-218+ parabolic interpolation around each peak."""
155-def measured_targets(powers, rel_threshold=0.05):219+ idx = np.where((freqs >= lo_hz) & (freqs < hi_hz))[0]
156- """Bands whose power is at least `rel_threshold` of the loudest band's --220+ if len(idx) < 3:
157- the loudest is always the patch that actually fired, background/leakage
158- bands sit orders of magnitude lower."""
159- if not powers:
160- return []
161- top = max(powers.values())
162- if top <= 0:
163 return []221 return []
164- return sorted(q for q, p in powers.items() if p >= rel_threshold * top)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+
238+def 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
165 255
166 256
167 def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):257 def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band):
@@ -173,23 +263,41 @@ def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_band
173 patches = build_patches_predicted(kx, k2, tables["f_high"])263 patches = build_patches_predicted(kx, k2, tables["f_high"])
174 print(f" predicted patches (src_start, tgt_start, width): {patches}")264 print(f" predicted patches (src_start, tgt_start, width): {patches}")
175 265
176- ref_map, our_map = {}, {}266+ ref_map, our_map, warnings_seen = {}, {}, []
267+ our_sane = True
177 for p in range(kx):268 for p in range(kx):
178- frames = stream_one_band(cfg, tables, p, n_frames=16)269+ frames = stream_one_band(cfg, tables, p)
179 pcm_ref, err_ref = P.decode(frames, SF_INDEX, f"{label}-p{p}")270 pcm_ref, err_ref = P.decode(frames, SF_INDEX, f"{label}-p{p}")
180 pcm_our, err_our = our_decode(frames, f"{label}-p{p}")271 pcm_our, err_our = our_decode(frames, f"{label}-p{p}")
181- pw_ref = band_powers(pcm_ref, kx, k2)272+ if NO_QUANT_WARNING in err_ref:
182- pw_our = band_powers(pcm_our, kx, k2)273+ warnings_seen.append(p)
183- tgt_ref = measured_targets(pw_ref)274+ freqs_ref, spec_ref = averaged_spectrum(pcm_ref)
184- tgt_our = measured_targets(pw_our)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)
185 pred = predicted_targets(patches, p)278 pred = predicted_targets(patches, p)
186- ref_map[p] = tgt_ref279+ ref_map[p] = d_ref
187- our_map[p] = tgt_our280+ our_map[p] = d_our
188- flag = "" if tgt_ref == pred else " <<< DIFFERS FROM PREDICTION"281+ if d_our != pred:
189- our_flag = "" if tgt_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches"282+ our_sane = False
190- print(f" p={p:2d} predicted={pred} measured(ref)={tgt_ref}{flag} measured(ours)={tgt_our}{our_flag}"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}"
191 f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]")287 f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]")
192- return kx, k2, patches, ref_map, our_map288+
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
193 301
194 302
195 if __name__ == "__main__":303 if __name__ == "__main__":