forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB58b009bTahinli2 months ago2045 commits

sbrchirp.py228 lines, 9.6 KiBHistoryRawDownload
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
4smoothing rule.
5
6Method: a pure single-bin AAC-LC core spectrum (one isolated MDCT line, all
7other lines silent via ZERO_HCB) puts an exact, noiseless sinusoid into one
8low 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
10method, so the SBR "inverse filter" recursion `y = residual + g*a1*y[-1] -
11g^2*y[-2]` (residual ~= 0 once the source is a pure tone the predictor
12already explains) collapses to an undriven damped oscillator whose envelope
13decays 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
15our own decoder involved.
16
17STATUS (round-19): the round-18 non-engagement was `stream()`'s own recipe
18shape, not a framing bug -- bisected field-by-field against a known-working
19CPE probe (see project ledger) and isolated to TWO independent culprits,
20either one sufficient alone to make the reference decoder's SBR gain stage
21not engage (envelope amplitude and `bs_invf_mode` both become powerless,
22`"No quantized data read for sbr_dequant."` fires either way -- that
23message is a red herring, printed on this SCE probe shape regardless of
24engagement, not diagnostic of it):
25
26 1. `bs_amp_res=0` (coarse, 7-bit raw envelope resolution). Sweeping the
27 full raw range (0..127) still gives <0.03% output-power change; fine
28 resolution (`bs_amp_res=1`, 6-bit raw) with the same header gives
29 three-to-four-orders-of-magnitude power swings for a mid-range raw
30 sweep (3 -> 60). Pure probe-construction quirk, not implicating our
31 parser/writer: real encoders emit both resolutions routinely and nothing
32 here says our AAC parser mishandles coarse-resolution streams -- it is
33 specifically *this reference build's* dequant path refusing these raw
34 values under `amp_res=0`, for a reason not chased further (plausibly an
35 offset/table-range mismatch in how this probe's raw codewords map,
36 unrelated to any of our own code).
37 2. `bs_num_env=1` (FIXFIX single envelope). Independent of amp_res: even
38 requesting `amp_res=1` explicitly, a single-envelope frame still fails
39 to engage here.
40
41`stream()` below now uses the repaired shape: SCE, FIXFIX with `num_env=2`,
42`amp_res=1`, envelope held constant across `bs_invf_mode` sweeps. Task 2 (a
43four-level `bs_invf_mode` sweep plus a HIGH->NONE transition, `n_q=1`
44narrow HF target) on this repaired instrument found only a ~0.1% output
45power drift across all four levels and no resolvable flatness difference,
46against a `BW_TABLE` that nominally spans `bw=0.0..0.98` -- STOP RULE
47applies: fingerprints are indistinguishable on the working instrument, so
48the bw-per-level hypothesis is refuted for this measurement and `sbr_hf.rs`
49was left unchanged. (The HIGH->NONE transition run showed a >200x power
50spike two frames from the stream's end; that coincides with the trailing
51silence frame and reads as a decoder-side reset artifact of this probe's
52framing, not a chirp-smoothing signal -- not chased further.)
53"""
54import os
55import sys
56
57import numpy as np
58
59HERE = os.path.dirname(os.path.abspath(__file__))
60sys.path.insert(0, HERE)
61
62import sbrpayload_fixtures as F
63import sbrprobe as P
64import sbrtables as T
65
66SF_INDEX = 7
67RATE = 44100
68
69
70def tone_core(w, sfb_idx, group_active, gain=200):
71 """SCE with one isolated MDCT line: `sfb_idx`'s `group_active`'th 4-tuple
72 group carries value 2 in its first line, everything else (all other
73 sfbs, and the other groups of `sfb_idx`) silent."""
74 swb = P.SWB_LONG[SF_INDEX]
75 max_sfb = sfb_idx + 1
76 w.w(0, 3).w(0, 4) # SCE, instance tag
77 w.w(gain, 8)
78 w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1)
79 # section 1: ZERO_HCB over the leading silent sfbs
80 w.w(0, 4)
81 left = sfb_idx
82 while left >= 31:
83 w.w(31, 5)
84 left -= 31
85 w.w(left, 5)
86 # section 2: codebook 3 over the one active sfb
87 w.w(3, 4)
88 w.w(1, 5)
89 w.w(P.HCB_SF[60][1], P.HCB_SF[60][0]) # scalefactor delta 0
90 w.w(0, 3) # pulse/tns/gain-control absent -- MUST precede spectral_data()
91 # (round-28 fix: this write sat AFTER the spectral loop below, shifting
92 # every bit that followed and desyncing the reference decoder on every
93 # probed band -- byte-accounted against sce_core's proven field order.)
94 ngroups = (swb[sfb_idx + 1] - swb[sfb_idx]) // 4
95 for i in range(ngroups):
96 quad = (2, 0, 0, 0) if i == group_active else (0, 0, 0, 0)
97 length, code = P.HCB3[P.tuple_index_u(quad, 2, 4)]
98 signs = [1 for v in quad if v != 0]
99 w.w(code, length)
100 for _ in signs:
101 w.w(0, 1)
102 return w
103
104
105SFB = 29 # SWB_LONG[7][29:31] = [240, 260]: bins 240..260, QMF band 15
106GROUP = 0 # bin 240, QMF band [15*344.5, 16*344.5) Hz
107MAX_SFB = 30 # bins 0..260: covers source QMF band 15 (bins 240..256) broadband
108
109
110def core_frame_bits(w):
111 tone_core(w, SFB, GROUP)
112
113
114def broadband_core_bits(w, gain=200):
115 """The already-verified codebook-3 comb pattern (`sce_core`, proven clean
116 at `max_sfb=30` above) -- strongly, stationarily correlated but not a
117 literal single MDCT bin, used as the resonant-content probe once the
118 isolated-tone encoding above turned out not to round-trip (HCB3 table
119 entries away from the exact tuple that earlier probes exercised are
120 unverified; not chased further here, broadband suffices for a fingerprint
121 test)."""
122 P.sce_core(w, SF_INDEX, MAX_SFB, gain=gain)
123
124
125def stream(cfg, tables, n_frames, invf_seq):
126 """`n_frames` FIXFIX/2-env, `amp_res=1` frames (the repaired, engaging
127 shape -- see module docstring), header on the first, `bs_invf_mode`
128 taken from `invf_seq[i]` (repeats last if shorter), envelope held fixed
129 across the sweep."""
130 grid = dict(frame_class=0, num_env=2, freq_res=0)
131 frames = [P.silent(SF_INDEX)]
132 for i in range(n_frames):
133 mode = invf_seq[min(i, len(invf_seq) - 1)]
134 c = dict(cfg, invf=mode, header=1, amp_res=1, element="sce", coupling=0,
135 df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2])
136 w = P.BitW()
137 broadband_core_bits(w)
138 body = F.sbr_bits_full(c, tables, grid, [])
139 w.w(6, 3)
140 cnt = (len(body.bits) + 4 + 7) // 8
141 if cnt >= 15:
142 w.w(15, 4)
143 w.w(cnt - 15 + 1, 8)
144 else:
145 w.w(cnt, 4)
146 start = len(w)
147 w.w(13, 4)
148 w.wbits(body.bits)
149 while len(w) - start < cnt * 8:
150 w.w(0, 1)
151 w.w(7, 3)
152 frames.append(P.adts(w.pack(pad=0), SF_INDEX))
153 frames.append(P.silent(SF_INDEX))
154 return frames
155
156
157def decode(frames, tag):
158 return P.decode(frames, SF_INDEX, tag)
159
160
161def target_band_envelope(pcm, band_lo_hz, band_hi_hz, sr=RATE):
162 """Per-QMF-slot (32 samples at full SBR rate here since no dual-rate)
163 envelope of the isolated band via a Goertzel-style single-bin DFT swept
164 along the signal -- narrowband enough that only the target tone
165 contributes, since nothing else in the stream carries energy there."""
166 n = len(pcm)
167 hop = 32
168 center = (band_lo_hz + band_hi_hz) / 2
169 w0 = 2 * np.pi * center / sr
170 win = hop
171 kernel_cos = np.cos(w0 * np.arange(win))
172 kernel_sin = np.sin(w0 * np.arange(win))
173 env = []
174 for start in range(0, n - win, hop):
175 seg = pcm[start : start + win]
176 re = np.dot(seg, kernel_cos)
177 im = np.dot(seg, kernel_sin)
178 env.append(np.hypot(re, im))
179 return np.array(env)
180
181
182def spectral_flatness(pcm, lo_hz, hi_hz, n_fft=8192, skip=3):
183 """Geometric/arithmetic mean ratio of the power spectrum inside
184 `[lo_hz,hi_hz)`, in a steady-state window (`skip` frames of 1024 samples
185 dropped for transient). Near 1 = white/flat (bw~0, whitened residual);
186 near 0 = tonal/peaky (bw~1, resonance preserved)."""
187 start = skip * 1024
188 seg = pcm[start : start + n_fft]
189 if len(seg) < n_fft:
190 seg = np.pad(seg, (0, n_fft - len(seg)))
191 spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg))))
192 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
193 mask = (freqs >= lo_hz) & (freqs < hi_hz)
194 power = spec[mask] ** 2 + 1e-24
195 gm = np.exp(np.mean(np.log(power)))
196 am = np.mean(power)
197 return gm / am, np.mean(power)
198
199
200if __name__ == "__main__":
201 cfg0, tables0 = F.one_band_header()
202 print("cfg0 amp_res", cfg0["amp_res"], "tables0", tables0)
203
204 # kx=19, k2=23: target HF region is QMF bands [19,23) = [6546, 7924) Hz.
205 lo, hi = 19 * RATE / 128, 23 * RATE / 128
206 src_lo, src_hi = 15 * RATE / 128, 16 * RATE / 128
207 print(f"target region {lo:.1f}-{hi:.1f} Hz, source band {src_lo:.1f}-{src_hi:.1f} Hz")
208
209 cfg = dict(cfg0)
210 print("\n== Task 1: four invf levels, flat/identical envelopes ==")
211 results = {}
212 for mode, name in [(0, "NONE"), (1, "LOW"), (2, "MID"), (3, "HIGH")]:
213 frames = stream(cfg, tables0, 20, [mode])
214 pcm, err = decode(frames, f"invf{mode}")
215 print(f"invf={name} err={err.strip()[:100]!r} samples={len(pcm)}")
216 for i in range(2, 18):
217 flat, pwr = spectral_flatness(pcm, lo, hi, skip=i)
218 print(f" frame {i}: flatness={flat:.4f} pwr={pwr:.3e}")
219 results[name] = pcm
220
221 print("\n== Task 1: transition HIGH -> NONE, per-frame flatness decay ==")
222 frames = stream(cfg, tables0, 16, [3, 3, 3, 3, 0])
223 pcm, err = decode(frames, "transition")
224 for i in range(2, 14):
225 flat, pwr = spectral_flatness(pcm, lo, hi, skip=i)
226 print(f"frame {i}: flatness={flat:.4f} pwr={pwr:.3e}")
227 if err.strip():
228 print("transition err:", err.strip()[:200])