forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1a0aad1Tahinli2 months ago3768 commits

lsf_probe.py71 lines, 2.4 KiBHistoryRawDownload
1"""Short-block reorder probes for the low sampling frequencies: one non-zero
2coefficient per granule, so the spectral position it lands in reveals the
3scalefactor band widths."""
4import numpy as np
5from mp3probe import BitWriter, Granule
6from learn_window import TABLE1, GLOBAL_GAIN
7
8RATES = {8000: (0, 2), 11025: (0, 0), 12000: (0, 1), 16000: (2, 2), 22050: (2, 0), 24000: (2, 1)}
9BITRATES_V2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]
10
11
12def lsf_frame(granule, main_bits, rate, bitrate_idx=14):
13 version_id, rate_idx = RATES[rate]
14 frame_len = 72 * BITRATES_V2[bitrate_idx] * 1000 // rate
15 bw = BitWriter()
16 bw.w(0x7FF, 11); bw.w(version_id, 2); bw.w(0b01, 2); bw.w(1, 1)
17 bw.w(bitrate_idx, 4); bw.w(rate_idx, 2); bw.w(0, 1); bw.w(0, 1)
18 bw.w(0b11, 2); bw.w(0, 2); bw.w(0, 1); bw.w(1, 1); bw.w(0, 2)
19 bw.w(0, 8) # main_data_begin
20 bw.w(0, 1) # private
21 g = granule
22 bw.w(g.part2_3_length, 12); bw.w(g.big_values, 9); bw.w(g.global_gain, 8)
23 bw.w(g.scalefac_compress, 9)
24 bw.w(1 if g.block_type else 0, 1)
25 if g.block_type:
26 bw.w(g.block_type, 2); bw.w(g.mixed_block, 1)
27 for t in g.table_select[:2]:
28 bw.w(t, 5)
29 for s in g.subblock_gain:
30 bw.w(s, 3)
31 else:
32 for t in g.table_select:
33 bw.w(t, 5)
34 bw.w(g.region0_count, 4); bw.w(g.region1_count, 3)
35 bw.w(g.scalefac_scale, 1); bw.w(g.count1table_select, 1)
36 assert len(bw) == 32 + 9 * 8, len(bw)
37 bw.bits.extend(main_bits)
38 assert len(bw) <= frame_len * 8, (len(bw), frame_len * 8)
39 return bw.bytes(pad_to=frame_len)
40
41
42def pair_bits(x, y):
43 bw = BitWriter()
44 ln, code = TABLE1[x * 2 + y]
45 bw.w(code, ln)
46 if x:
47 bw.w(0, 1)
48 if y:
49 bw.w(0, 1)
50 return bw.bits
51
52
53def build(rate, positions):
54 stream = b""
55 for pos in positions:
56 bits = []
57 for i in range(288):
58 bits += pair_bits(1 if 2 * i == pos else 0, 1 if 2 * i + 1 == pos else 0)
59 g = Granule(part2_3_length=len(bits), big_values=288, global_gain=GLOBAL_GAIN,
60 table_select=(1, 1, 1), block_type=2, mixed_block=0)
61 stream += lsf_frame(g, bits, rate)
62 stream += lsf_frame(Granule(), [], rate)
63 return stream
64
65
66if __name__ == "__main__":
67 import sys
68 rate = int(sys.argv[1])
69 positions = list(range(576))
70 open(f"/tmp/lsf{rate}.mp3", "wb").write(build(rate, positions))
71 print("wrote", rate, len(positions))