forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf567222Tahinli3 months ago1411 commits

learn.py151 lines, 4.5 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Learn one AAC spectral Huffman codebook by black-box probing of ffmpeg.
3
4A bit string b is a complete codeword iff the first decoded tuple does not
5change when a 0 is appended (prefix codes are injective, and the filler after
6the codeword is identical in both probes). BFS over the binary tree therefore
7enumerates the whole codebook in ~2M probes for M codewords.
8"""
9
10import numpy as np
11import subprocess
12import os
13import sys
14import json
15
16import aacprobe as A
17
18N = 1024
19_M = None
20
21
22def basis():
23 global _M
24 if _M is None:
25 n = np.arange(2 * N)
26 _M = np.cos(np.pi / N * np.outer(n + 512.5, np.arange(16) + 0.5))
27 return _M
28
29
30WIN = np.sin(np.pi / (2 * N) * (np.arange(2 * N) + 0.5))
31
32
33def spectrum(block):
34 return (basis().T @ (block / WIN)) / N
35
36
37def quant(x):
38 """Dequantised coefficient -> signed quantised integer."""
39 a = abs(x)
40 if a < 1e-3:
41 return 0
42 v = int(round(a ** 0.75))
43 return -v if x < 0 else v
44
45
46def _decode(frames, tag=None):
47 d = os.path.dirname(os.path.abspath(__file__))
48 src = os.path.join(d, f"probe-{tag or os.getpid()}.aac")
49 sil = A.silent_frame()
50 with open(src, "wb") as f:
51 f.write(sil + b"".join(fr + sil + sil for fr in frames))
52 raw = subprocess.run(
53 ["ffmpeg", "-v", "quiet", "-i", src, "-f", "f32le", "-ac", "1", "-"],
54 capture_output=True,
55 )
56 pcm = np.frombuffer(raw.stdout, dtype="<f4").astype(np.float64)
57 nblk = len(pcm) // N
58 os.remove(src)
59 if nblk != 3 * len(frames) + 1:
60 return None
61 pcm = pcm[: nblk * N].reshape(nblk, N)
62 out = []
63 for i in range(len(frames)):
64 # the third packet of every triple decodes to silence; if it does not,
65 # the stream lost a packet and every later index is off by one
66 if float(np.abs(pcm[3 * i + 3]).max()) > 1e-9:
67 return None
68 out.append(np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]))
69 return out
70
71
72def _blocks(frames):
73 """One 2048-sample block per frame; None for frames ffmpeg refused.
74
75 A refused frame costs the whole batch its packet alignment, so a failed
76 batch is bisected until the offenders are isolated.
77 """
78 got = _decode(frames)
79 if got is not None:
80 return got
81 if len(frames) == 1:
82 return [None]
83 h = len(frames) // 2
84 return _blocks(frames[:h]) + _blocks(frames[h:])
85
86
87def run_batch(cb, probes, filler, gg=200, tag=None):
88 """Decode one frame per probe; returns a list of 8 quantised values or None."""
89 frames = [A.probe_frame(cb, [0, 0], list(p) + filler, gg=gg) for p in probes]
90 return [
91 None if b is None else tuple(quant(v) for v in spectrum(b)[:8])
92 for b in _blocks(frames)
93 ]
94
95
96def learn(cb, dim, signed, esc=False, filler=None):
97 filler = filler if filler is not None else [1] * 96
98 cache = {}
99
100 def evaluate(nodes):
101 todo = [b for b in nodes if b not in cache]
102 for i in range(0, len(todo), 400):
103 chunk = todo[i : i + 400]
104 res = run_batch(cb, chunk, filler)
105 for b, r in zip(chunk, res):
106 if r is None:
107 cache[b] = None
108 else:
109 t = r[:dim]
110 if not signed:
111 t = tuple(abs(v) for v in t)
112 if esc:
113 t = tuple(min(v, 16) if v >= 0 else max(v, -16) for v in t)
114 cache[b] = t
115
116 codewords = {}
117 frontier = [()]
118 depth = 0
119 while frontier and depth < 22:
120 evaluate(frontier + [b + (0,) for b in frontier])
121 nxt = []
122 for b in frontier:
123 g, g0 = cache[b], cache[b + (0,)]
124 if g is None:
125 continue # frame refused: subtree unreachable, retried below
126 if g == g0:
127 codewords[b] = g
128 else:
129 nxt += [b + (0,), b + (1,)]
130 frontier = nxt
131 depth += 1
132 print(f" cb{cb} depth {depth}: {len(codewords)} codewords, {len(frontier)} open",
133 file=sys.stderr)
134 return codewords
135
136
137def kraft(codewords):
138 return sum(2.0 ** -len(b) for b in codewords)
139
140
141if __name__ == "__main__":
142 cb = int(sys.argv[1])
143 dim = int(sys.argv[2])
144 signed = sys.argv[3] == "s"
145 esc = len(sys.argv) > 4 and sys.argv[4] == "esc"
146 cw = learn(cb, dim, signed, esc)
147 tuples = set(cw.values())
148 print(f"cb{cb}: {len(cw)} codewords, {len(tuples)} distinct tuples, kraft={kraft(cw):.6f}")
149 out = {"".join(map(str, b)): list(t) for b, t in cw.items()}
150 with open(f"cb{cb}.json", "w") as f:
151 json.dump(out, f)