forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

qmf_check.py389 lines, 14.6 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Numpy prototype of the ISO/IEC 14496-3 4.6.18.4.1 (32-band analysis) and
34.6.18.8.2 (64-band synthesis) QMF banks, run back-to-back as a passthrough
4round-trip (upper 32 synthesis subbands zeroed) to verify the exact carrier
5equations before porting to Rust. See ledger sbr-hunt-resume for context.
6
7Usage: python3 qmf_check.py
8"""
9import numpy as np
10
11TAPS_PATH = "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/041875c4-7950-4e24-950e-7b6e9eb5ba3c/scratchpad/qmf_proto_640.txt"
12c = np.array([float(x) for x in open(TAPS_PATH)])
13assert c.shape == (640,)
14
15
16class Analysis32:
17 """4.6.18.4.1: 32 new real samples in -> 32 complex subbands out per slot."""
18
19 def __init__(self, window):
20 self.c = window
21 self.x = np.zeros(320) # analysis history buffer, x[0]=newest
22
23 def process_slot(self, new32, newest_at_zero=True, tap=None, sign=-1.0):
24 x = self.x
25 # shift: x[n] = x[n-32] for n=319..32 ; new samples into x[31..0]
26 x[32:320] = x[0:288]
27 if newest_at_zero:
28 x[0:32] = new32[::-1] # newest at x[0]
29 else:
30 x[0:32] = new32 # oldest-at-front variant
31 if tap == "c2n":
32 Z = x * self.c[0::2][: len(x)]
33 else:
34 Z = x * self.c[: len(x)]
35 u = np.zeros(64)
36 for n in range(64):
37 u[n] = Z[n] + Z[n + 64] + Z[n + 128] + Z[n + 192] + Z[n + 256]
38 k = np.arange(32)
39 n = np.arange(64)
40 # X[k] = sum_n u[n] * exp(sign * j*pi/64*(k+0.5)*(2n-1))
41 phase = sign * 1j * np.pi / 64.0 * np.outer(2 * n - 1, k + 0.5)
42 X = u @ np.exp(phase)
43 self.x = x
44 return X # shape (32,) complex
45
46
47class Synthesis64:
48 """4.6.18.8.2: 64 complex subbands in -> 64 real samples out per slot."""
49
50 def __init__(self, window, sign=1.0, use_re=True):
51 self.c = window
52 self.v = np.zeros(1280)
53 self.sign = sign
54 self.use_re = use_re
55
56 def process_slot(self, X64):
57 v = self.v
58 v[128:1280] = v[0:1152]
59 k = np.arange(64)
60 n = np.arange(128)
61 phase = self.sign * 1j * np.pi / 128.0 * np.outer(2 * n - 255, k + 0.5)
62 vv = (1.0 / 64.0) * (np.exp(phase) @ X64)
63 v[0:128] = vv.real if self.use_re else (vv.real + vv.imag)
64 self.v = v
65 g = np.zeros(640)
66 for i in range(5):
67 g[128 * i : 128 * i + 64] = v[256 * i : 256 * i + 64]
68 g[128 * i + 64 : 128 * i + 128] = v[256 * i + 192 : 256 * i + 256]
69 w = g * self.c
70 y = np.zeros(64)
71 for k_ in range(10):
72 y += w[64 * k_ : 64 * k_ + 64]
73 return y
74
75
76def run_trial(name, syn_sign=1.0, syn_use_re=True, **kw):
77 rng = np.random.default_rng(0)
78 n_slots = 128 # 8192 samples / 64
79 x_in = rng.standard_normal(8192)
80 ana = Analysis32(c)
81 syn = Synthesis64(c, sign=syn_sign, use_re=syn_use_re)
82 out = np.zeros(8192 * 2)
83 for s in range(n_slots):
84 new32 = x_in[s * 32 : s * 32 + 32]
85 X32 = ana.process_slot(new32, **{k: v for k, v in kw.items() if k in ("newest_at_zero", "tap", "sign")})
86 X64 = np.zeros(64, dtype=complex)
87 X64[0:32] = X32
88 y64 = syn.process_slot(X64)
89 out[s * 64 : s * 64 + 64] = y64
90
91 best_corr = -2.0
92 best_lag = None
93 best_ratio = None
94 for lag in range(0, 800):
95 a = out[lag : lag + 8192]
96 b = x_in[: len(a)]
97 if len(a) < 4000:
98 continue
99 # correlate against decimated-out-at-even-samples vs input directly:
100 oa = out[lag::2][: len(x_in)]
101 n = min(len(oa), len(x_in)) - 10
102 oa = oa[:n]
103 bb = x_in[:n]
104 if np.std(oa) < 1e-12:
105 continue
106 corr = np.corrcoef(oa, bb)[0, 1]
107 if corr > best_corr:
108 best_corr = corr
109 best_lag = lag
110 best_ratio = np.std(oa) / np.std(bb)
111 pass # summarized in table below
112 return best_corr
113
114
115class Analysis64:
116 """4.6.18.4: 64 new real samples in -> 64 complex subbands out per slot
117 (same-rate variant, x of 640, full c[n] tap, folded to 128)."""
118
119 def __init__(self, window):
120 self.c = window
121 self.x = np.zeros(640) # x[0]=newest
122
123 def process_slot(self, new64):
124 x = self.x
125 x[64:640] = x[0:576]
126 x[0:64] = new64[::-1] # newest at x[0]
127 Z = x * self.c
128 u = np.zeros(128)
129 for n in range(128):
130 u[n] = Z[n] + Z[n + 128] + Z[n + 256] + Z[n + 384] + Z[n + 512]
131 k = np.arange(64)
132 n = np.arange(128)
133 phase = 1j * np.pi / 128.0 * np.outer(2 * n - 1, k + 0.5)
134 X = u @ np.exp(phase)
135 self.x = x
136 return X # shape (64,) complex
137
138
139class Synthesis32Downsampled:
140 """4.6.18.8.3: 32 complex subbands in -> 32 real samples out per slot
141 (downsampled, same-rate variant)."""
142
143 def __init__(self, window):
144 self.c = window
145 self.v = np.zeros(640)
146
147 def process_slot(self, X32):
148 v = self.v
149 v[64:640] = v[0:576]
150 k = np.arange(32)
151 n = np.arange(64)
152 phase = 1j * np.pi / 64.0 * np.outer(2 * n - 63, k + 0.5)
153 vv = (1.0 / 32.0) * (np.exp(phase) @ X32)
154 v[0:64] = vv.real
155 self.v = v
156 g = np.zeros(320)
157 for i in range(5):
158 g[64 * i : 64 * i + 32] = v[128 * i : 128 * i + 32]
159 g[64 * i + 32 : 64 * i + 64] = v[128 * i + 96 : 128 * i + 128]
160 w = g * self.c[0::2]
161 y = np.zeros(32)
162 for k_ in range(10):
163 y += w[32 * k_ : 32 * k_ + 32]
164 return y
165
166
167class Analysis64Param:
168 """64-band analysis with the shift-direction (T1) and modulation-index
169 (T2) axes exposed as parameters, for cross-check bisection."""
170
171 def __init__(self, window, shift_mode="reverse_newest_at_0", mod_sign=-1.0):
172 self.c = window
173 self.x = np.zeros(640)
174 self.shift_mode = shift_mode
175 self.mod_sign = mod_sign # -1.0 -> (2n-1), +1.0 -> (2n+1)
176
177 def process_slot(self, new64):
178 x = self.x
179 if self.shift_mode == "reverse_newest_at_0":
180 x[64:640] = x[0:576]
181 x[0:64] = new64[::-1]
182 else: # "forward_newest_at_top": x[n] <- x[n+64], new64 forward into x[576:640]
183 x[0:576] = x[64:640]
184 x[576:640] = new64
185 Z = x * self.c
186 u = np.zeros(128)
187 for n in range(128):
188 u[n] = Z[n] + Z[n + 128] + Z[n + 256] + Z[n + 384] + Z[n + 512]
189 k = np.arange(64)
190 n = np.arange(128)
191 expo = 2 * n + 1 if self.mod_sign > 0 else 2 * n - 1
192 phase = 1j * np.pi / 128.0 * np.outer(expo, k + 0.5)
193 X = u @ np.exp(phase)
194 self.x = x
195 return X
196
197
198class Synthesis64Param:
199 """64-band synthesis with shift-direction (T1), modulation offset (T2:
200 2n-255 vs 2n+1) and the 1/64 scale (T3) exposed as parameters."""
201
202 def __init__(self, window, shift_mode="reverse_newest_at_0", mod_variant="2n-255", scale=True):
203 self.c = window
204 self.v = np.zeros(1280)
205 self.shift_mode = shift_mode
206 self.mod_variant = mod_variant
207 self.scale = scale
208
209 def process_slot(self, X64):
210 v = self.v
211 k = np.arange(64)
212 n = np.arange(128)
213 expo = (2 * n + 1) if self.mod_variant == "2n+1" else (2 * n - 255)
214 phase = 1j * np.pi / 128.0 * np.outer(expo, k + 0.5)
215 scale_factor = (1.0 / 64.0) if self.scale else 1.0
216 vv = scale_factor * (np.exp(phase) @ X64)
217 if self.shift_mode == "reverse_newest_at_0":
218 v[128:1280] = v[0:1152]
219 v[0:128] = vv.real
220 else: # "forward_newest_at_top"
221 v[0:1152] = v[128:1280]
222 v[1152:1280] = vv.real
223 self.v = v
224 g = np.zeros(640)
225 for i in range(5):
226 g[128 * i : 128 * i + 64] = v[256 * i : 256 * i + 64]
227 g[128 * i + 64 : 128 * i + 128] = v[256 * i + 192 : 256 * i + 256]
228 w = g * self.c
229 y = np.zeros(64)
230 for k_ in range(10):
231 y += w[64 * k_ : 64 * k_ + 64]
232 return y
233
234
235def run_same_rate_64_param(shift_mode, mod_sign, mod_variant, scale, n_slots=160, lag_max=1300):
236 rng = np.random.default_rng(0)
237 x_in = rng.standard_normal(64 * n_slots)
238 ana = Analysis64Param(c, shift_mode=shift_mode, mod_sign=mod_sign)
239 syn = Synthesis64Param(c, shift_mode=shift_mode, mod_variant=mod_variant, scale=scale)
240 out = np.zeros(64 * n_slots)
241 for s in range(n_slots):
242 X64 = ana.process_slot(x_in[64 * s : 64 * s + 64])
243 out[64 * s : 64 * s + 64] = syn.process_slot(X64)
244 energy_ratio = np.sum(out**2) / np.sum(x_in**2)
245 corr, lag, ratio = best_lag_corr(out, x_in, lag_max)
246 return corr, lag, ratio, energy_ratio
247
248
249def bisect_t1_t2_t3():
250 print()
251 print("T1/T2/T3 cross-check bisection (64->64, same family):")
252 rows = []
253 for shift_mode in ("reverse_newest_at_0", "forward_newest_at_top"):
254 for mod_sign in (-1.0, 1.0): # analysis (2n-1) vs (2n+1)
255 for mod_variant in ("2n-255", "2n+1"): # synthesis
256 for scale in (True, False):
257 corr, lag, ratio, energy = run_same_rate_64_param(shift_mode, mod_sign, mod_variant, scale)
258 name = f"shift={shift_mode} a_mod={'2n+1' if mod_sign>0 else '2n-1'} s_mod={mod_variant} scale64={scale}"
259 rows.append((name, corr, lag, ratio, energy))
260 rows.sort(key=lambda r: -r[1])
261 for name, corr, lag, ratio, energy in rows:
262 print(f" {name}: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy:.6f}")
263 return rows
264
265
266def best_lag_corr(out, x_in, lag_max):
267 """Same-rate (no decimation) lag search."""
268 best_corr, best_lag, best_ratio = -2.0, None, None
269 for lag in range(0, lag_max):
270 a = out[lag:]
271 n = min(len(a), len(x_in)) - 10
272 if n < 4000:
273 continue
274 a, b = a[:n], x_in[:n]
275 if np.std(a) < 1e-12:
276 continue
277 corr = np.corrcoef(a, b)[0, 1]
278 if corr > best_corr:
279 best_corr, best_lag, best_ratio = corr, lag, np.std(a) / np.std(b)
280 return best_corr, best_lag, best_ratio
281
282
283def run_same_rate_64(n_slots=128):
284 rng = np.random.default_rng(0)
285 x_in = rng.standard_normal(64 * n_slots)
286 ana = Analysis64(c)
287 syn = Synthesis64(c, sign=1.0, use_re=True)
288 out = np.zeros(64 * n_slots)
289 for s in range(n_slots):
290 X64 = ana.process_slot(x_in[64 * s : 64 * s + 64])
291 out[64 * s : 64 * s + 64] = syn.process_slot(X64)
292 energy_ratio = np.sum(out**2) / np.sum(x_in**2)
293 corr, lag, ratio = best_lag_corr(out, x_in, 900)
294 print(f"(1) 64->64 same-family round-trip: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy_ratio:.6f}")
295 return corr
296
297
298def run_same_rate_32(n_slots=256):
299 rng = np.random.default_rng(0)
300 x_in = rng.standard_normal(32 * n_slots)
301 ana = Analysis32(c)
302 syn = Synthesis32Downsampled(c)
303 out = np.zeros(32 * n_slots)
304 for s in range(n_slots):
305 X32 = ana.process_slot(x_in[32 * s : 32 * s + 32], newest_at_zero=True, tap="c2n", sign=1.0)
306 out[32 * s : 32 * s + 32] = syn.process_slot(X32)
307 energy_ratio = np.sum(out**2) / np.sum(x_in**2)
308 corr, lag, ratio = best_lag_corr(out, x_in, 700)
309 print(f"(2) 32->32 same-family round-trip: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy_ratio:.6f}")
310 return corr
311
312
313def run_single_band_impulse_spectrum(k_impulse=10):
314 """(3)-fallback: single-band impulse at slot 0, k=k_impulse into
315 Synthesis64; report where the output spectrum peaks land."""
316 syn = Synthesis64(c, sign=1.0, use_re=True)
317 n_slots = 20
318 out = np.zeros(64 * n_slots)
319 for s in range(n_slots):
320 X64 = np.zeros(64, dtype=complex)
321 if s == 0:
322 X64[k_impulse] = 1.0
323 out[64 * s : 64 * s + 64] = syn.process_slot(X64)
324 spec = np.fft.rfft(out)
325 mags = np.abs(spec)
326 top2 = np.argsort(mags)[-2:]
327 freqs = np.fft.rfftfreq(len(out))
328 print(f"single-band impulse k={k_impulse}: top-2 bins {sorted(top2)} at normalized freq {sorted(freqs[top2])}")
329 print(f" expected bin center (band k of 64, full band 0..0.5): {(k_impulse + 0.5) / 128.0:.5f}")
330
331
332if __name__ == "__main__":
333 results = {}
334 for newest_at_zero in (True, False):
335 for tap in (None, "c2n"):
336 for sign in (-1.0, 1.0):
337 for syn_sign in (-1.0, 1.0):
338 for syn_use_re in (True, False):
339 name = (
340 f"newest0={newest_at_zero} tap={tap} asign={sign:+.0f} "
341 f"ssign={syn_sign:+.0f} re_only={syn_use_re}"
342 )
343 results[name] = run_trial(
344 name,
345 newest_at_zero=newest_at_zero,
346 tap=tap,
347 sign=sign,
348 syn_sign=syn_sign,
349 syn_use_re=syn_use_re,
350 )
351 print()
352 print("Trial table (sorted, 32->64 cross-family):")
353 for k, v in sorted(results.items(), key=lambda kv: -kv[1]):
354 print(f" {k}: corr={v:.6f}")
355
356 print()
357 print("Same-family bisection:")
358 c1 = run_same_rate_64()
359 c2 = run_same_rate_32()
360 if c1 >= 0.999 and c2 >= 0.999:
361 print("Both same-family round-trips pass -> the 32->64 cross-family pairing is the bug (see charter step 3).")
362 if c1 < 0.999:
363 run_single_band_impulse_spectrum(k_impulse=10)
364
365 rows = bisect_t1_t2_t3()
366 best_name, best_corr, best_lag, best_ratio, best_energy = rows[0]
367 print()
368 print(f"Best T1/T2/T3 configuration: {best_name} corr={best_corr:.6f} amp_ratio={best_ratio} energy_ratio={best_energy:.6f}")
369
370 print()
371 print("32-band-analysis -> confirmed-correct-64-band-synthesis cross-family, scale/conjugate probe:")
372 for scale_k in (1.0, 2.0, 0.5, np.sqrt(2)):
373 for conj in (False, True):
374 rng = np.random.default_rng(0)
375 n_slots = 160
376 x_in = rng.standard_normal(32 * n_slots)
377 ana = Analysis32(c)
378 syn = Synthesis64Param(c, shift_mode="reverse_newest_at_0", mod_variant="2n-255", scale=True)
379 out = np.zeros(64 * n_slots)
380 for s in range(n_slots):
381 X32 = ana.process_slot(x_in[32 * s : 32 * s + 32], newest_at_zero=True, tap="c2n", sign=1.0)
382 if conj:
383 X32 = np.conj(X32)
384 X64 = np.zeros(64, dtype=complex)
385 X64[0:32] = X32 * scale_k
386 out[64 * s : 64 * s + 64] = syn.process_slot(X64)
387 energy = np.sum(out**2) / np.sum(x_in**2)
388 corr, lag, ratio = best_lag_corr(out, x_in, 900)
389 print(f" scale_k={scale_k:.4f} conj={conj}: corr={corr:.6f} lag={lag} amp_ratio={ratio} energy_ratio={energy:.6f}")