forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2602aecTahinli6 days ago3958 commits

measure.py118 lines, 4.5 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Measures the Layer II bit-allocation tables (ISO 11172-3 Table 3-B.2a..d and the
3ISO 13818-3 LSF table) out of an oracle decoder instead of copying them from anyone.
4
5Method: a mono frame whose only non-zero bits are the allocation code `c` of subband
6`s` decodes (all sample bits zero) to a constant -(L-1)/L * scalefactor in that subband,
7L being the number of quantiser levels the code selects. Layer I's allocation is known
8from the standard (nb = a+1 bits, L = 2^nb - 1), so a Layer I frame with allocation 14
9in the same subband calibrates the oracle's gain for that subband. The ratio of the two
10steady-state energies gives L. The per-subband bit widths (nbal) were found by setting one allocation bit at a
11time and watching where the oracle stops reacting (a constant subband input only
12excites lines at multiples of fs/32, so adjacent subbands pair up in frequency, and the
13run lengths of the pairs give the widths).
14
15Usage: measure.py > table.txt (needs ffmpeg with the mp2 decoder)
16"""
17import math, os, struct, subprocess, sys, tempfile
18
19SF = 12 # 2^(1-12/3) = 0.125, keeps the output clear of clipping
20TMP = os.environ.get("TMPDIR", "/tmp")
21
22def nbal_for(table):
23 return {
24 0: [4]*11 + [3]*12 + [2]*4,
25 1: [4]*11 + [3]*12 + [2]*7,
26 2: [4]*2 + [3]*6,
27 3: [4]*2 + [3]*10,
28 4: [4]*4 + [3]*7 + [2]*19,
29 }[table]
30
31# (version byte1, rate idx, bitrate idx, rate Hz) giving each table in a mono stream
32CFG = {
33 0: (0xFD, 1, 4, 48000), # 48k 64k mono -> table 0
34 1: (0xFD, 0, 8, 44100), # 44.1k 128k mono -> table 1
35 2: (0xFD, 0, 1, 44100), # 44.1k 32k mono -> table 2
36 3: (0xFD, 2, 1, 32000), # 32k 32k mono -> table 3
37 4: (0xF5, 0, 8, 22050), # MPEG-2 22.05k 64k mono -> LSF table
38}
39
40def frame_len(table):
41 b1, r, br, hz = CFG[table]
42 kbps = {4: 64, 0: 64, 1: 128, 2: 32, 3: 32}[table]
43 return 144 * kbps * 1000 // hz
44
45class Bits:
46 def __init__(self, n): self.b = bytearray(n); self.p = 0
47 def put(self, v, n):
48 for i in range(n - 1, -1, -1):
49 if (v >> i) & 1: self.b[self.p >> 3] |= 0x80 >> (self.p & 7)
50 self.p += 1
51
52def l2_frame(table, sb, code):
53 b1, r, br, hz = CFG[table]
54 n = frame_len(table)
55 f = Bits(n)
56 f.put(0xFF, 8); f.put(b1, 8); f.put((br << 4) | (r << 2), 8); f.put(0xC0, 8)
57 for i, nb in enumerate(nbal_for(table)):
58 f.put(code if i == sb else 0, nb)
59 if code:
60 f.put(0, 2) # scfsi 0: three scalefactors
61 for _ in range(3): f.put(SF, 6)
62 return bytes(f.b)
63
64def l1_frame(sb):
65 f = Bits(192)
66 f.put(0xFF, 8); f.put(0xFF, 8); f.put((6 << 4) | (1 << 2), 8); f.put(0xC0, 8)
67 for i in range(32):
68 f.put(14 if i == sb else 0, 4)
69 f.put(SF, 6)
70 return bytes(f.b)
71
72def decode(frames, n):
73 path = os.path.join(TMP, "mp2probe.mp2")
74 with open(path, "wb") as fh: fh.write(frames * n)
75 out = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-"],
76 capture_output=True, check=True).stdout
77 return struct.unpack("<%df" % (len(out) // 4), out)
78
79def window(x):
80 return x[4 * 1152:5 * 1152]
81
82def energy(w): return sum(v * v for v in w)
83
84def goertzel_frac(w, hz, sb):
85 f = (sb + 0.5) / 64.0 # cycles per sample, for a stream sampled at hz
86 re = sum(v * math.cos(2 * math.pi * f * i) for i, v in enumerate(w))
87 im = sum(v * math.sin(2 * math.pi * f * i) for i, v in enumerate(w))
88 return (re * re + im * im) * 2 / len(w) / max(energy(w), 1e-30)
89
90K = {}
91def gain(sb):
92 if sb not in K:
93 w = window(decode(l1_frame(sb), 36))
94 K[sb] = math.sqrt(energy(w)) / (1 - 1 / 32767.0) # per unit of |v|, scalefactor included
95 return K[sb]
96
97LEVELS = [3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535]
98
99for table in range(5):
100 nbal = nbal_for(table)
101 print("table", table, "sblimit", len(nbal))
102 for sb in range(len(nbal)):
103 row = []
104 for code in range(1 << nbal[sb]):
105 if code == 0:
106 row.append(0); continue
107 w = window(decode(l2_frame(table, sb, code), 8))
108 e = energy(w)
109 if e == 0:
110 row.append(-1); continue
111 frac = goertzel_frac(w, CFG[table][3], sb)
112 v = math.sqrt(e) / gain(sb)
113 lv = 1.0 / (1.0 - v) if 0 < v < 1 else 1e-9
114 near = min(LEVELS, key=lambda L: abs(math.log(L / lv)))
115 ok = abs(math.log(near / lv)) < 0.3
116 row.append(near if ok else -(int(lv)))
117 print(" sb", sb, nbal[sb], row)
118 sys.stdout.flush()