forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB854ea37Tahinli3 months ago149 commits

learn_window.py83 lines, 3.0 KiBHistoryRawDownload
1"""Measure the Layer III synthesis window D[512] from the ffmpeg decoder.
2
3Probes carry only +-1 spectral values, written with Huffman table 1 (four
4codewords), so nothing but the header/side-info syntax is assumed. The decode
5chain up to the synthesis window is modelled exactly, leaving a linear system
6pcm = A @ D that a least-squares solve inverts.
7"""
8
9import numpy as np
10import sys
11from mp3probe import (BitWriter, Granule, frame_bytes, ffmpeg_decode,
12 granules_to_subband, synthesis_basis)
13
14# table 1: (x,y) -> (length, code), index = x*2 + y
15TABLE1 = [(1, 0b1), (3, 0b001), (2, 0b01), (3, 0b000)]
16
17GLOBAL_GAIN = 170 # 2^((gg-210)/4) = 2^-10 spectral scale, far from clipping
18
19
20def write_pairs(pairs):
21 bw = BitWriter()
22 for (x, sx), (y, sy) in pairs:
23 ln, code = TABLE1[x * 2 + y]
24 bw.w(code, ln)
25 if x:
26 bw.w(sx, 1)
27 if y:
28 bw.w(sy, 1)
29 return bw.bits
30
31
32def probe_frames(rng, nframes=6, npairs=288):
33 """Random +-1 spectra; returns (mp3 bytes, list of granule spectra)."""
34 stream = b""
35 spectra = []
36 for _ in range(nframes):
37 grans, mains = [], []
38 for _g in range(2):
39 vals = rng.integers(0, 2, size=(npairs, 2))
40 signs = rng.integers(0, 2, size=(npairs, 2))
41 pairs = [((int(vals[i, 0]), int(signs[i, 0])),
42 (int(vals[i, 1]), int(signs[i, 1]))) for i in range(npairs)]
43 bits = write_pairs(pairs)
44 grans.append(Granule(part2_3_length=len(bits), big_values=npairs,
45 global_gain=GLOBAL_GAIN, table_select=(1, 1, 1)))
46 mains.append(bits)
47 xr = np.zeros(576)
48 scale = 2.0 ** ((GLOBAL_GAIN - 210) / 4.0)
49 for i in range(npairs):
50 for j in range(2):
51 v = float(vals[i, j])
52 if signs[i, j]:
53 v = -v
54 xr[2 * i + j] = v * scale
55 spectra.append(xr)
56 stream += frame_bytes(grans, mains)
57 return stream, spectra
58
59
60def main():
61 rng = np.random.default_rng(0xC0DE)
62 mp3, spectra = probe_frames(rng)
63 pcm, err = ffmpeg_decode(mp3)
64 print(f"ffmpeg: {len(pcm)} samples, stderr={err.strip()!r}, peak={np.abs(pcm).max():.6g}")
65 slots = granules_to_subband(spectra)
66 A = synthesis_basis(slots)
67 print(f"model: {A.shape[0]} samples from {len(slots)} slots")
68 n = min(len(pcm), A.shape[0])
69 # frame-granularity alignment search
70 best = None
71 for off in range(0, len(pcm) - n + 1, 1152 // 2):
72 D, res, rank, _ = np.linalg.lstsq(A[:n], pcm[off:off + n], rcond=None)
73 resid = np.linalg.norm(A[:n] @ D - pcm[off:off + n]) / max(np.linalg.norm(pcm[off:off + n]), 1e-30)
74 if best is None or resid < best[0]:
75 best = (resid, off, D, rank)
76 resid, off, D, rank = best
77 print(f"offset={off} rank={rank} relative residual={resid:.3e}")
78 print(f"D peak={np.abs(D).max():.6g} D[0..4]={D[:5]}")
79 np.save("D.npy", D)
80
81
82if __name__ == "__main__":
83 sys.exit(main())