forge
Explore
Log in

Don't you dare go Hollow

scripts(sbr): black-box chirp/bw probe -- dead end, harness never engaged SBR envelope

Browse files at this commit

054aa957a32203d39c3326f3d6410225f468743fAhmet Kaan GümüşParent: 2cccf17
Attempted to measure the reference decoder's per-invf-mode bandwidth-
expansion factor by black box (round 18, Task 1). Two dead ends recorded
in the script's own docstring for a successor:

* An isolated single-MDCT-line core (for an exact-AR2 pure-tone source,
  whose LPC coefficients are analytically known) desyncs the bitstream --
  most HCB3 codewords beyond the one tuple earlier probes exercised are
  unverified.
* Falling back to the already-proven-clean broadband comb core, every
  real SBR decode attempt makes the reference print "No quantized data
  read for sbr_dequant." and then produce PCM that is value-independent
  of both bs_invf_mode (all four levels byte-identical) and the envelope
  amplitude itself -- the envelope/gain stage never engages, for a reason
  the byte-count oracle (which only checks framing) cannot see.

No bw fingerprint extracted; sbr_hf.rs is unchanged -- no measurement to
base a fix on, and the task's own stop rule forbids fitting constants to
noise.
scripts/aac-tables/sbrchirp.pyadded+204 -0
@@ -0,0 +1,204 @@
1+#!/usr/bin/env python3
2+"""Black-box measurement of the reference decoder's HF-generator chirp
3+(bandwidth-expansion) factor per `bs_invf_mode`, and its frame-to-frame
4+smoothing rule.
5+
6+Method: a pure single-bin AAC-LC core spectrum (one isolated MDCT line, all
7+other lines silent via ZERO_HCB) puts an exact, noiseless sinusoid into one
8+low QMF subband. A single-tone AR(2) source has *exact* LPC coefficients
9+`a1 = 2*cos(w0), a2 = -1` (unit-radius poles) independent of estimation
10+method, so the SBR "inverse filter" recursion `y = residual + g*a1*y[-1] -
11+g^2*y[-2]` (residual ~= 0 once the source is a pure tone the predictor
12+already explains) collapses to an undriven damped oscillator whose envelope
13+decays geometrically as `g^n` per QMF slot -- `g` *is* the chirp factor
14+(pole radius), directly recoverable from the decay rate with no analysis of
15+our own decoder involved.
16+
17+STATUS (dead end, not chased further): the isolated-single-MDCT-line core
18+(`tone_core`) does not round-trip -- most HCB3 codewords beyond the one
19+tuple earlier probes happened to exercise are unverified and desync the
20+bitstream ("Input buffer exhausted before END element found"); see the
21+`(2,0,0,0)`/`(2,0,2,2)`/`(0,0,0,0)` isolation test in the project ledger.
22+Falling back to the already-proven-clean broadband `sce_core` comb content
23+(`broadband_core_bits`) decodes without framing errors, but every real SBR
24+sweep built on top of it (`stream()`, any `n_low`/`n_high`/`n_q` combination
25+tried, any `env0`/`noise0` magnitude) makes the reference decoder print
26+"No quantized data read for sbr_dequant." and then produce PCM that is
27+*value-independent* of both `bs_invf_mode` (all four levels byte-identical)
28+and the envelope amplitude itself (`env0=0` vs `env0=100`: power differs by
29+<0.02%, when a real amp_res=0 dequant law would differ by orders of
30+magnitude) -- i.e. the reference's SBR envelope/gain stage is not engaging
31+with this harness's `sbr_data` payload at all, for a reason not yet
32+isolated (framing/byte-count is provably correct per `oracle_check`, so the
33+fault is in a field *value* or ordering `oracle_check`'s byte-count-only
34+check cannot see). No bw fingerprint could be extracted; Task 1 could not be
35+completed this round. Do not reuse `stream()`'s SCE/FIXFIX(num_env=1) recipe
36+believing it produces a working real decode -- it does not, despite passing
37+the byte-count oracle.
38+"""
39+import os
40+import sys
41+
42+import numpy as np
43+
44+HERE = os.path.dirname(os.path.abspath(__file__))
45+sys.path.insert(0, HERE)
46+
47+import sbrpayload_fixtures as F
48+import sbrprobe as P
49+import sbrtables as T
50+
51+SF_INDEX = 7
52+RATE = 44100
53+
54+
55+def tone_core(w, sfb_idx, group_active, gain=200):
56+ """SCE with one isolated MDCT line: `sfb_idx`'s `group_active`'th 4-tuple
57+ group carries value 2 in its first line, everything else (all other
58+ sfbs, and the other groups of `sfb_idx`) silent."""
59+ swb = P.SWB_LONG[SF_INDEX]
60+ max_sfb = sfb_idx + 1
61+ w.w(0, 3).w(0, 4) # SCE, instance tag
62+ w.w(gain, 8)
63+ w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1)
64+ # section 1: ZERO_HCB over the leading silent sfbs
65+ w.w(0, 4)
66+ left = sfb_idx
67+ while left >= 31:
68+ w.w(31, 5)
69+ left -= 31
70+ w.w(left, 5)
71+ # section 2: codebook 3 over the one active sfb
72+ w.w(3, 4)
73+ w.w(1, 5)
74+ w.w(P.HCB_SF[60][1], P.HCB_SF[60][0]) # scalefactor delta 0
75+ ngroups = (swb[sfb_idx + 1] - swb[sfb_idx]) // 4
76+ for i in range(ngroups):
77+ quad = (2, 0, 0, 0) if i == group_active else (0, 0, 0, 0)
78+ length, code = P.HCB3[P.tuple_index_u(quad, 2, 4)]
79+ signs = [1 for v in quad if v != 0]
80+ w.w(code, length)
81+ for _ in signs:
82+ w.w(0, 1)
83+ w.w(0, 3) # pulse/tns/gain-control absent
84+ return w
85+
86+
87+SFB = 29 # SWB_LONG[7][29:31] = [240, 260]: bins 240..260, QMF band 15
88+GROUP = 0 # bin 240, QMF band [15*344.5, 16*344.5) Hz
89+MAX_SFB = 30 # bins 0..260: covers source QMF band 15 (bins 240..256) broadband
90+
91+
92+def core_frame_bits(w):
93+ tone_core(w, SFB, GROUP)
94+
95+
96+def broadband_core_bits(w, gain=200):
97+ """The already-verified codebook-3 comb pattern (`sce_core`, proven clean
98+ at `max_sfb=30` above) -- strongly, stationarily correlated but not a
99+ literal single MDCT bin, used as the resonant-content probe once the
100+ isolated-tone encoding above turned out not to round-trip (HCB3 table
101+ entries away from the exact tuple that earlier probes exercised are
102+ unverified; not chased further here, broadband suffices for a fingerprint
103+ test)."""
104+ P.sce_core(w, SF_INDEX, MAX_SFB, gain=gain)
105+
106+
107+def stream(cfg, tables, n_frames, invf_seq):
108+ """`n_frames` FIXFIX/1-env frames, header on the first, `bs_invf_mode`
109+ taken from `invf_seq[i]` (repeats last if shorter)."""
110+ grid = dict(frame_class=0, num_env=1, freq_res=0)
111+ frames = [P.silent(SF_INDEX)]
112+ for i in range(n_frames):
113+ mode = invf_seq[min(i, len(invf_seq) - 1)]
114+ c = dict(cfg, invf=mode, header=1)
115+ w = P.BitW()
116+ broadband_core_bits(w)
117+ body = F.sbr_bits_full(c, tables, grid, [])
118+ w.w(6, 3)
119+ cnt = (len(body.bits) + 4 + 7) // 8
120+ if cnt >= 15:
121+ w.w(15, 4)
122+ w.w(cnt - 15 + 1, 8)
123+ else:
124+ w.w(cnt, 4)
125+ w.w(13, 4)
126+ w.wbits(body.bits)
127+ w.w(7, 3)
128+ frames.append(P.adts(w.pack(pad=0), SF_INDEX))
129+ frames.append(P.silent(SF_INDEX))
130+ return frames
131+
132+
133+def decode(frames, tag):
134+ return P.decode(frames, SF_INDEX, tag)
135+
136+
137+def target_band_envelope(pcm, band_lo_hz, band_hi_hz, sr=RATE):
138+ """Per-QMF-slot (32 samples at full SBR rate here since no dual-rate)
139+ envelope of the isolated band via a Goertzel-style single-bin DFT swept
140+ along the signal -- narrowband enough that only the target tone
141+ contributes, since nothing else in the stream carries energy there."""
142+ n = len(pcm)
143+ hop = 32
144+ center = (band_lo_hz + band_hi_hz) / 2
145+ w0 = 2 * np.pi * center / sr
146+ win = hop
147+ kernel_cos = np.cos(w0 * np.arange(win))
148+ kernel_sin = np.sin(w0 * np.arange(win))
149+ env = []
150+ for start in range(0, n - win, hop):
151+ seg = pcm[start : start + win]
152+ re = np.dot(seg, kernel_cos)
153+ im = np.dot(seg, kernel_sin)
154+ env.append(np.hypot(re, im))
155+ return np.array(env)
156+
157+
158+def spectral_flatness(pcm, lo_hz, hi_hz, n_fft=8192, skip=3):
159+ """Geometric/arithmetic mean ratio of the power spectrum inside
160+ `[lo_hz,hi_hz)`, in a steady-state window (`skip` frames of 1024 samples
161+ dropped for transient). Near 1 = white/flat (bw~0, whitened residual);
162+ near 0 = tonal/peaky (bw~1, resonance preserved)."""
163+ start = skip * 1024
164+ seg = pcm[start : start + n_fft]
165+ if len(seg) < n_fft:
166+ seg = np.pad(seg, (0, n_fft - len(seg)))
167+ spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg))))
168+ freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
169+ mask = (freqs >= lo_hz) & (freqs < hi_hz)
170+ power = spec[mask] ** 2 + 1e-24
171+ gm = np.exp(np.mean(np.log(power)))
172+ am = np.mean(power)
173+ return gm / am, np.mean(power)
174+
175+
176+if __name__ == "__main__":
177+ cfg0, tables0 = F.one_band_header()
178+ print("cfg0 amp_res", cfg0["amp_res"], "tables0", tables0)
179+
180+ # kx=19, k2=23: target HF region is QMF bands [19,23) = [6546, 7924) Hz.
181+ lo, hi = 19 * RATE / 128, 23 * RATE / 128
182+ src_lo, src_hi = 15 * RATE / 128, 16 * RATE / 128
183+ print(f"target region {lo:.1f}-{hi:.1f} Hz, source band {src_lo:.1f}-{src_hi:.1f} Hz")
184+
185+ cfg = dict(cfg0)
186+ print("\n== Task 1: four invf levels, flat/identical envelopes ==")
187+ results = {}
188+ for mode, name in [(0, "NONE"), (1, "LOW"), (2, "MID"), (3, "HIGH")]:
189+ frames = stream(cfg, tables0, 20, [mode])
190+ pcm, err = decode(frames, f"invf{mode}")
191+ print(f"invf={name} err={err.strip()[:100]!r} samples={len(pcm)}")
192+ for i in range(2, 18):
193+ flat, pwr = spectral_flatness(pcm, lo, hi, skip=i)
194+ print(f" frame {i}: flatness={flat:.4f} pwr={pwr:.3e}")
195+ results[name] = pcm
196+
197+ print("\n== Task 1: transition HIGH -> NONE, per-frame flatness decay ==")
198+ frames = stream(cfg, tables0, 16, [3, 3, 3, 3, 0])
199+ pcm, err = decode(frames, "transition")
200+ for i in range(2, 14):
201+ flat, pwr = spectral_flatness(pcm, lo, hi, skip=i)
202+ print(f"frame {i}: flatness={flat:.4f} pwr={pwr:.3e}")
203+ if err.strip():
204+ print("transition err:", err.strip()[:200])