From a913c8463d4bd520ab43837841cd80ec10d4d172 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 03:57:14 +0300 Subject: [PATCH] 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.py | 226 ++++++++++++++++++++++-------- 1 file changed, 167 insertions(+), 59 deletions(-) diff --git a/scripts/aac-tables/sbrpatchmap.py b/scripts/aac-tables/sbrpatchmap.py index deb2ee0e..226d780b 100644 --- a/scripts/aac-tables/sbrpatchmap.py +++ b/scripts/aac-tables/sbrpatchmap.py @@ -1,24 +1,65 @@ #!/usr/bin/env python3 -"""Round-27: measures the reference decoder's ACTUAL SBR HF patch map (which +"""Round-29: measures the reference decoder's ACTUAL SBR HF patch map (which low QMF source band feeds which high target band), by isolating one source -band at a time and reading off which target bands carry power in the output. - -Method (one-band-at-a-time, simpler than a multi-line comb and avoids any -ambiguity from overlapping lines): the core spectrum for a probe frame is a -single isolated MDCT bin -- `tone_core()` in `sbrchirp.py`, already proven to -place value 2 in one 4-bin group and ZERO_HCB everywhere else -- at the first -bin of low QMF band `p` (`k = p*16`, always a group boundary since a QMF band -is 16 MDCT bins wide and a group is 4). Patching copies that source band's -complex QMF series verbatim (mixed by LPC/chirp, which round-19 already -measured as a <0.1% power effect regardless of `bs_invf_mode`) into every -target band any patch maps it to, so an FFT of the decoded output that finds -elevated power in target band `q` means "patch measured: source `p` -> target -`q`" directly, no fractional-offset bookkeeping needed. +band at a time and reading off the FRACTIONAL FREQUENCY OFFSET of the +resulting HF line(s), not their power. + +Round-28 found that a power-bucket readout cannot work: the envelope adjuster +renormalizes every target band's POWER to the transmitted envelope regardless +of patch content, so every source band lit the SAME target range at similar +power (expected physics, not a bug). Gains rescale amplitude, never a line's +frequency position within its band, so the fix is to read frequency instead. + +Method: the core spectrum for a probe frame is a single isolated MDCT bin -- +`tone_core()` in `sbrchirp.py` -- placed not at low QMF band `p`'s first bin +(a group/band boundary, ambiguous under FFT leakage and coincident with the +target band edge too) but at its SECOND 4-bin group (`k = p*16 + 4`), i.e. a +known, non-zero fractional offset `D = 0.25` of a QMF band's width inside +band `p` (0.25 is the finest offset `tone_core`'s group granularity allows; +any of 0.25/0.5/0.75 is equally "distinctive", 0.25 chosen arbitrarily). +Patching copies that source band's complex QMF series verbatim into every +target band any patch maps it to, translating the tone in frequency by an +integer number of band widths -- so the offset is preserved (or, per the +charter's note on filterbank parity, possibly mirrored to `1 - D`) in +whichever target band(s) the patch actually lit up. An averaged FFT of the +decoded output finds every HF line clearly above the local noise floor +(power only GATES detection); for each line, `target band q = floor(f/bw)` +and `frac = f/bw - q` are computed, and a line is read as "source `p` -> +target `q`" iff `frac` is within a few percent of `D` (direct) or `1 - D` +(mirrored, logged separately as data, not discarded). Runs the same probes through our own decoder via the `adts_to_pcm` example (`cargo build -p ec-aac --example adts_to_pcm`) for the sanity cross-check the charter requires: our measured map must equal `build_patches`' prediction, or -the fingerprint method itself is the thing that's broken. +the fingerprint method itself is the thing that's broken. Also checks the +reference's stderr for "No quantized data read for sbr_dequant." -- if +present the run used a shape that leaves the SBR gain stage unengaged and the +decode is not trustworthy. + +STATUS (round-29): the sanity gate still FAILS after two real fixes landed +this round (see the ledger's round-29 facts): (1) `sbr_bits_full`'s `slot()` +default (`T.FILL`, 24 raw zero bits) desyncs the bitstream whenever a +multi-band delta run is used -- ENV30_F/NOISE_F's shortest codeword (the one +"0" bits actually decode as) is only 1 bit, so 23 excess zero bits per slot +leak into every field transmitted after it; `stream_one_band` now supplies +exactly enough real 1-bit zero-delta codewords instead (fixed, confirmed via +`EC_AAC_SBR_DEBUG`: `e_q[1]`/`q_q[1]` now read back the intended raw values, +were silently zeroed before). (2) The tone's fractional-offset placement +(`GROUP_OFFSET`) is unaffected by that fix. What remains OPEN: `k = active_p +* 16` (the MDCT-bin-per-QMF-band assumption every prior round's readout used, +inherited unchanged here) does not track the true source-band placement -- +calibration by sweeping raw bin `k` and reading which target band lights up +shows a clean *32*-bin-per-band slope (not 16) locally, but with an offset +that is NOT a fixed constant across headers (k=64 lands on `target == kx` +for headers A and C, whose `patches[0]` happens to have `source_start == 0`, +but for header B -- `xover_band=1`, whose `patches[0]` has `source_start == +2` -- k=64 *also* lands on `target == kx`, meaning it tracked `source_start` +itself, not a fixed `p`). The low/source band index space is not a simple +`p*N + offset` function of MDCT bin position; it needs deriving from the +tables' own low-band structure rather than assumed, which this round did not +reach. Sanity gate: DO NOT trust `measured(ref)` output below until this is +resolved -- Task 2/3 (reading and acting on the reference's map) are blocked +on it. """ import os import subprocess @@ -37,6 +78,10 @@ import sbrtables as T # noqa: E402 SF_INDEX = 7 RATE = 44100 OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm") +BAND_HZ = RATE / 128 # QMF band width, both source and target index units +D = 0.25 # fractional offset (of one band width) the probe tone is placed at +GROUP_OFFSET = 4 # bins: 4/16 == D, the finest offset tone_core's grouping allows +NO_QUANT_WARNING = "No quantized data read for sbr_dequant." 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 return cfg, t -def stream_one_band(cfg, tables, active_p, n_frames=16, invf_mode=0): - """`n_frames` FIXFIX/2-env amp_res=1 frames (round-19's engaging shape), - core = one isolated tone at low QMF band `active_p`'s first bin, held - fixed; envelope flat/loud, noise floor minimal, invf NONE, no harmonics.""" +def stream_one_band(cfg, tables, active_p, n_frames=24, invf_mode=0): + """`n_frames` FIXFIX/2-env amp_res=1 frames (sbrchirp.py's `stream()` + engaging shape, byte-for-byte -- FIXFIX, num_env=2, amp_res=1, env0 at a + healthy mid value, noise0 at the quiet end so noise floor cannot bury the + line), core = one isolated tone at low QMF band `active_p`'s SECOND 4-bin + group (offset `D` of a band width into the band, not the ambiguous + boundary bin), held fixed; invf NONE, no harmonics.""" swb = P.SWB_LONG[SF_INDEX] - k = active_p * 16 + k = active_p * 16 + GROUP_OFFSET found = bin_to_sfb_group(k, swb) assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]" sfb_idx, group_active = found grid = dict(frame_class=0, num_env=2, freq_res=0) frames = [P.silent(SF_INDEX)] + # sbrtables.py's `slot()` falls back to `T.FILL` (24 raw zero bits) for + # any delta slot the caller doesn't supply explicit bits for -- fine for + # the bootstrap probes that don't yet know a codebook's length, but for + # amp_res=1/coupling=0/df_env=df_noise=0 (this probe's exact config) the + # book is known: ENV30_F and NOISE_F (crates/ec-aac/src/sbr_tables.rs) + # both give delta=0 its SHORTEST codeword, (len=1, code=0). 24 zero bits + # where only 1 is consumed leaves 23 unconsumed zero bits per slot that + # bleed into every field transmitted after it (env1's raw start value, + # noise0/1, ...), silently corrupting it to whatever a run of stray zero + # bits happens to decode as -- this is round-29's "readout is wrong" + # candidate B made concrete, and the fix. + zero_delta = [0] + n_slots = 2 * (tables["n_low"] - 1) + 2 * (tables["n_q"] - 1) for _ in range(n_frames): c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0, df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2]) w = P.BitW() C.tone_core(w, sfb_idx, group_active) - body = F.sbr_bits_full(c, tables, grid, []) + body = F.sbr_bits_full(c, tables, grid, [zero_delta] * n_slots) w.w(6, 3) cnt = (len(body.bits) + 4 + 7) // 8 if cnt >= 15: @@ -134,34 +195,63 @@ def our_decode(frames, tag): return np.frombuffer(r.stdout, dtype="= lo) & (freqs < hi) - powers[q] = float(spec[mask].sum()) - return powers - - -def measured_targets(powers, rel_threshold=0.05): - """Bands whose power is at least `rel_threshold` of the loudest band's -- - the loudest is always the patch that actually fired, background/leakage - bands sit orders of magnitude lower.""" - if not powers: - return [] - top = max(powers.values()) - if top <= 0: + return freqs, spec + + +def find_lines(freqs, spec, lo_hz, hi_hz, floor_mult=8.0): + """Local-maximum bins within [lo_hz, hi_hz) whose power clearly exceeds + the local noise floor (median of the in-range spectrum) -- power GATES + detection only, never decides the mapping. Sub-bin frequency via + parabolic interpolation around each peak.""" + idx = np.where((freqs >= lo_hz) & (freqs < hi_hz))[0] + if len(idx) < 3: return [] - return sorted(q for q, p in powers.items() if p >= rel_threshold * top) + floor = np.median(spec[idx]) + if floor <= 0: + floor = np.finfo(float).tiny + df = freqs[1] - freqs[0] + lines = [] + for j in range(1, len(idx) - 1): + i = idx[j] + if spec[i] > spec[i - 1] and spec[i] >= spec[i + 1] and spec[i] > floor_mult * floor: + a, b, c = spec[i - 1], spec[i], spec[i + 1] + denom = a - 2 * b + c + delta = 0.5 * (a - c) / denom if denom != 0 else 0.0 + delta = max(-0.5, min(0.5, delta)) + lines.append((freqs[i] + delta * df, float(b))) + return lines + + +def measured_targets(freqs, spec, kx, k2, d=D, tol=0.06): + """Patch map read directly from fractional frequency offset: a detected + HF line in target band `q` counts as "source -> q" iff its offset within + the band matches `d` (direct) or `1 - d` (mirrored, per the charter's + filterbank-parity note -- logged, not discarded). Returns + (direct_targets, mirrored_targets, all_lines_for_debug).""" + lines = find_lines(freqs, spec, kx * BAND_HZ, k2 * BAND_HZ) + direct, mirrored, debug = [], [], [] + for f, power in lines: + q = int(f // BAND_HZ) + frac = f / BAND_HZ - q + debug.append((q, round(frac, 3), power)) + if abs(frac - d) <= tol: + direct.append(q) + elif abs(frac - (1 - d)) <= tol: + mirrored.append(q) + return sorted(set(direct)), sorted(set(mirrored)), debug 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 patches = build_patches_predicted(kx, k2, tables["f_high"]) print(f" predicted patches (src_start, tgt_start, width): {patches}") - ref_map, our_map = {}, {} + ref_map, our_map, warnings_seen = {}, {}, [] + our_sane = True for p in range(kx): - frames = stream_one_band(cfg, tables, p, n_frames=16) + frames = stream_one_band(cfg, tables, p) pcm_ref, err_ref = P.decode(frames, SF_INDEX, f"{label}-p{p}") pcm_our, err_our = our_decode(frames, f"{label}-p{p}") - pw_ref = band_powers(pcm_ref, kx, k2) - pw_our = band_powers(pcm_our, kx, k2) - tgt_ref = measured_targets(pw_ref) - tgt_our = measured_targets(pw_our) + if NO_QUANT_WARNING in err_ref: + warnings_seen.append(p) + freqs_ref, spec_ref = averaged_spectrum(pcm_ref) + freqs_our, spec_our = averaged_spectrum(pcm_our) + d_ref, m_ref, dbg_ref = measured_targets(freqs_ref, spec_ref, kx, k2) + d_our, m_our, dbg_our = measured_targets(freqs_our, spec_our, kx, k2) pred = predicted_targets(patches, p) - ref_map[p] = tgt_ref - our_map[p] = tgt_our - flag = "" if tgt_ref == pred else " <<< DIFFERS FROM PREDICTION" - our_flag = "" if tgt_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches" - print(f" p={p:2d} predicted={pred} measured(ref)={tgt_ref}{flag} measured(ours)={tgt_our}{our_flag}" + ref_map[p] = d_ref + our_map[p] = d_our + if d_our != pred: + our_sane = False + flag = "" if d_ref == pred else " <<< DIFFERS FROM PREDICTION" + our_flag = "" if d_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches" + mir = f" mirrored(ref)={m_ref}" if m_ref else "" + print(f" p={p:2d} predicted={pred} measured(ref)={d_ref}{flag}{mir} measured(ours)={d_our}{our_flag}" f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]") - return kx, k2, patches, ref_map, our_map + + if warnings_seen: + print(f" !! {NO_QUANT_WARNING!r} present on p={warnings_seen} -- run NOT trustworthy, fix shape first") + else: + print(f" {NO_QUANT_WARNING!r} absent on every probe -- reference decode confirmed engaged") + + if not our_sane: + print(" !! SANITY GATE FAILED: our decoder's measured map != build_patches prediction -- " + "do not trust the reference read below until this is resolved") + else: + print(" sanity gate passed: our decoder's measured map == build_patches prediction on every band") + + return kx, k2, patches, ref_map, our_map, our_sane, warnings_seen if __name__ == "__main__":