forked from rraval/pied-piper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.py
173 lines (132 loc) · 4.52 KB
/
decode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from __future__ import print_function
import sys
import wave
from io import StringIO
import alsaaudio
import colorama
import numpy as np
from reedsolo import RSCodec, ReedSolomonError
from termcolor import cprint
from pyfiglet import figlet_format
HANDSHAKE_START_HZ = 8192
HANDSHAKE_END_HZ = 8192 + 512
START_HZ = 1024
STEP_HZ = 256
BITS = 4
FEC_BYTES = 4
def stereo_to_mono(input_file, output_file):
inp = wave.open(input_file, 'r')
params = list(inp.getparams())
params[0] = 1 # nchannels
params[3] = 0 # nframes
out = wave.open(output_file, 'w')
out.setparams(tuple(params))
frame_rate = inp.getframerate()
frames = inp.readframes(inp.getnframes())
data = np.fromstring(frames, dtype=np.int16)
left = data[0::2]
out.writeframes(left.tostring())
inp.close()
out.close()
def yield_chunks(input_file, interval):
wav = wave.open(input_file)
frame_rate = wav.getframerate()
chunk_size = int(round(frame_rate * interval))
total_size = wav.getnframes()
while True:
chunk = wav.readframes(chunk_size)
if len(chunk) == 0:
return
yield frame_rate, np.fromstring(chunk, dtype=np.int16)
def dominant(frame_rate, chunk):
w = np.fft.fft(chunk)
freqs = np.fft.fftfreq(len(chunk))
peak_coeff = np.argmax(np.abs(w))
peak_freq = freqs[peak_coeff]
return abs(peak_freq * frame_rate) # in Hz
def match(freq1, freq2):
return abs(freq1 - freq2) < 20
def decode_bitchunks(chunk_bits, chunks):
out_bytes = []
next_read_chunk = 0
next_read_bit = 0
byte = 0
bits_left = 8
while next_read_chunk < len(chunks):
can_fill = chunk_bits - next_read_bit
to_fill = min(bits_left, can_fill)
offset = chunk_bits - next_read_bit - to_fill
byte <<= to_fill
shifted = chunks[next_read_chunk] & (((1 << to_fill) - 1) << offset)
byte |= shifted >> offset;
bits_left -= to_fill
next_read_bit += to_fill
if bits_left <= 0:
out_bytes.append(byte)
byte = 0
bits_left = 8
if next_read_bit >= chunk_bits:
next_read_chunk += 1
next_read_bit -= chunk_bits
return out_bytes
def decode_file(input_file, speed):
wav = wave.open(input_file)
if wav.getnchannels() == 2:
mono = StringIO()
stereo_to_mono(input_file, mono)
mono.seek(0)
input_file = mono
wav.close()
offset = 0
for frame_rate, chunk in yield_chunks(input_file, speed / 2):
dom = dominant(frame_rate, chunk)
print("{} => {}".format(offset, dom))
offset += 1
def extract_packet(freqs):
freqs = freqs[::2]
bit_chunks = [int(round((f - START_HZ) / STEP_HZ)) for f in freqs]
bit_chunks = [c for c in bit_chunks if 0 <= c < (2 ** BITS)]
return bytearray(decode_bitchunks(BITS, bit_chunks))
def display(s):
cprint(figlet_format(s.replace(' ', ' '), font='doom'), 'yellow')
def listen_linux(frame_rate=44100, interval=0.1):
num_frames = int(round((interval / 2) * frame_rate))
mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, channels=1, rate=44100, format=alsaaudio.PCM_FORMAT_S16_LE, periodsize=num_frames)
# mic.setchannels(1)
# mic.setrate(44100)
# mic.setformat(alsaaudio.PCM_FORMAT_S16_LE)
# mic.setperiodsize(num_frames)
in_packet = False
packet = []
while True:
l, data = mic.read()
if not l:
continue
chunk = np.frombuffer(data, dtype=np.int16)
dom = dominant(frame_rate, chunk)
if in_packet and match(dom, HANDSHAKE_END_HZ):
byte_stream = extract_packet(packet)
try:
byte_stream = RSCodec(FEC_BYTES).decode(byte_stream)
print(type(byte_stream))
for s in byte_stream:
print(type(s))
try:
display(s.decode())
except:
print("Unable to decode string")
print(str(s))
# print(byte_stream.decode())
display("")
except ReedSolomonError as e:
print("{}: {}".format(e, byte_stream))
packet = []
in_packet = False
elif in_packet:
packet.append(dom)
elif match(dom, HANDSHAKE_START_HZ):
in_packet = True
if __name__ == '__main__':
colorama.init(strip=not sys.stdout.isatty())
#decode_file(sys.argv[1], float(sys.argv[2]))
listen_linux()