forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe548d52Tahinli2 months ago2204 commits

aacprobe.py132 lines, 4.4 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Black-box derivation of the ISO/IEC 14496-3 AAC-LC Huffman codebooks.
3
4Clean-room: no AAC implementation source is read. The only oracle is ffmpeg's
5`aac` decoder driven as a black box. We synthesise ADTS frames whose spectral
6payload is a bit string we choose, decode them, invert the (windowed) MDCT to
7recover the quantised spectrum, and learn the prefix code from bits -> tuple.
8
9Frame shape (mono, 48 kHz, ONLY_LONG, sine window):
10 SCE(3)=0 tag(4)=0 global_gain(8) ics_info section_data sf_data flags spectral
11max_sfb=2 gives one section of 8 coefficients, so the spectral field always
12outlives the probe prefix and the trailing all-ones run lands on an END element
13(id 7 = 0b111). The ones run is bounded -- a long 0xFF tail makes ffmpeg's ADTS
14parser resync on a false 0xFFF sync word.
15"""
16
17import numpy as np
18import subprocess
19import os
20
21SR = 48000
22N = 1024
23ONES_RUN = 96 # bits of `1` filler after the probe, then zero padding
24
25
26class BitW:
27 def __init__(self):
28 self.bits = []
29
30 def w(self, val, n):
31 for i in range(n - 1, -1, -1):
32 self.bits.append((val >> i) & 1)
33 return self
34
35 def wbits(self, seq):
36 self.bits.extend(seq)
37 return self
38
39 def __len__(self):
40 return len(self.bits)
41
42 def pack(self, total_bytes=None, pad=0):
43 if total_bytes is None:
44 total_bytes = (len(self.bits) + 7) // 8
45 b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8]
46 out = bytearray()
47 for i in range(0, len(b), 8):
48 v = 0
49 for bit in b[i : i + 8]:
50 v = (v << 1) | bit
51 out.append(v)
52 return bytes(out)
53
54
55def adts(payload: bytes, sf_index=3, chan_cfg=1) -> bytes:
56 h = BitW()
57 h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1) # sync, MPEG-4, layer, no CRC
58 h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3) # AAC-LC
59 h.w(0, 1).w(0, 1).w(0, 1).w(0, 1) # original, home, copyright id/start
60 h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2)
61 return h.pack(7) + payload
62
63
64def probe_frame(cb, sf_bits, probe_bits, gg=200, max_sfb=2):
65 w = BitW()
66 w.w(0, 3).w(0, 4) # SCE, instance tag
67 w.w(gg, 8)
68 w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine window
69 w.w(cb, 4).w(max_sfb, 5) # one section covering every band
70 w.wbits(sf_bits)
71 w.w(0, 3) # pulse / tns / gain-control absent
72 w.wbits(probe_bits).wbits([1] * ONES_RUN)
73 return adts(w.pack(pad=0))
74
75
76def silent_frame():
77 w = BitW()
78 w.w(0, 3).w(0, 4).w(128, 8)
79 w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1) # max_sfb = 0: nothing coded
80 w.w(0, 3).w(7, 3) # flags, END
81 return adts(w.pack(4))
82
83
84# --- MDCT read-back ---------------------------------------------------------
85
86_PINV = None
87
88
89def recover(block, ncoef=12):
90 """Quantised-spectrum-proportional coefficients from 2048 output samples."""
91 global _PINV
92 if _PINV is None:
93 cache = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pinv.npy")
94 if os.path.exists(cache):
95 _PINV = np.load(cache)
96 else:
97 n = np.arange(2 * N)
98 k = np.arange(N)
99 m = np.cos(2 * np.pi / N * np.outer(n + 0.5 + N / 2, k + 0.5))
100 win = np.sin(np.pi / (2 * N) * (n + 0.5))
101 _PINV = np.linalg.pinv(m * win[:, None])[:32].astype(np.float64)
102 np.save(cache, _PINV)
103 return _PINV[:ncoef] @ block
104
105
106def decode_probes(frames, tag="p"):
107 """One 2048-sample block per probe frame, or None when ffmpeg refused it."""
108 d = os.path.dirname(os.path.abspath(__file__))
109 src = os.path.join(d, f"probe-{tag}.aac")
110 sil = silent_frame()
111 with open(src, "wb") as f:
112 f.write(sil + b"".join(fr + sil + sil for fr in frames))
113 raw = subprocess.run(
114 ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"],
115 capture_output=True,
116 )
117 pcm = np.frombuffer(raw.stdout, dtype="<f4")
118 nblk = len(pcm) // N
119 pcm = pcm[: nblk * N].reshape(nblk, N).astype(np.float64)
120 os.remove(src)
121 if nblk != 3 * len(frames) + 1:
122 return None, raw.stderr.decode()
123 return [np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]) for i in range(len(frames))], ""
124
125
126if __name__ == "__main__":
127 frs = [probe_frame(3, [0] * 2, [1] * 40)]
128 blocks, err = decode_probes(frs, "smoke")
129 if blocks is None:
130 print("MISALIGNED", err[:400])
131 else:
132 print("coefs", np.round(recover(blocks[0], 12), 6))