forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBca58ed5Tahinli3 months ago1597 commits

mp3op.py85 lines, 2.7 KiBHistoryRawDownload
1"""The linear map (requantised spectrum -> PCM) for one probe frame, and its
2pseudo-inverse: what turns an ffmpeg decode back into the integers a probe's
3Huffman bits decoded to."""
4
5import math
6import numpy as np
7from mp3probe import ALIAS_CS, ALIAS_CA, WIN_NORMAL
8
9NSLOTS = 72 # probe frame (36 slots) + trailing silent frame
10NSAMPLES = NSLOTS * 32
11
12
13def imdct_matrix():
14 n = 36
15 return np.array([[math.cos(math.pi / (2 * n) * (2 * i + 1 + n // 2) * (2 * k + 1))
16 for k in range(18)] for i in range(n)]) * WIN_NORMAL[:, None]
17
18
19def alias_matrix():
20 ar = np.eye(576)
21 for sb in range(1, 32):
22 for i in range(8):
23 lo, hi = sb * 18 - 1 - i, sb * 18 + i
24 a, b = ar[lo].copy(), ar[hi].copy()
25 ar[lo] = a * ALIAS_CS[i] - b * ALIAS_CA[i]
26 ar[hi] = b * ALIAS_CS[i] + a * ALIAS_CA[i]
27 return ar
28
29
30def spectrum_to_slots():
31 """(2 granules x 576) -> (72 slots x 32 subbands), flattened columns."""
32 imw = imdct_matrix()
33 ar = alias_matrix()
34 L = np.zeros((1152, NSLOTS * 32))
35 for g in range(2):
36 for sb in range(32):
37 for k in range(18):
38 col = np.zeros(NSLOTS * 32)
39 for i in range(18):
40 t0 = 18 * g + i
41 sign = -1.0 if (sb % 2 == 1 and i % 2 == 1) else 1.0
42 col[t0 * 32 + sb] += imw[i, k] * sign
43 t1 = 18 * (g + 1) + i
44 sign = -1.0 if (sb % 2 == 1 and i % 2 == 1) else 1.0
45 col[t1 * 32 + sb] += imw[18 + i, k] * sign
46 # the alias butterflies mix coefficients before the imdct
47 L[g * 576:(g + 1) * 576] += np.outer(ar[sb * 18 + k, :], col)
48 return L
49
50
51def slots_to_pcm(D):
52 N = np.array([[math.cos((16 + i) * (2 * k + 1) * math.pi / 64) for k in range(32)]
53 for i in range(64)])
54 S = np.zeros((NSLOTS * 32, NSAMPLES))
55 for i in range(16):
56 Ci = np.zeros((32, 32))
57 for j in range(32):
58 b = j if i % 2 == 0 else j + 32
59 Ci[j] = D[j + 32 * i] * N[b]
60 for t in range(NSLOTS):
61 s = t - i
62 if s < 0:
63 continue
64 S[s * 32:(s + 1) * 32, t * 32:(t + 1) * 32] += Ci.T
65 return S
66
67
68def build(D):
69 M = spectrum_to_slots() @ slots_to_pcm(D)
70 return M, np.linalg.pinv(M)
71
72
73if __name__ == "__main__":
74 D = np.load("D.npy")
75 M, Minv = build(D)
76 np.save("M.npy", M)
77 np.save("Minv.npy", Minv)
78 print("M", M.shape, "cond ok")
79
80 # self-check: round-trip a random spectrum through the model
81 rng = np.random.default_rng(7)
82 c = rng.normal(size=1152) * 1e-3
83 pcm = c @ M
84 back = pcm @ Minv
85 print("model round-trip max err", np.abs(back - c).max())