-
Notifications
You must be signed in to change notification settings - Fork 1
/
circuit_samples.py
464 lines (380 loc) · 15.1 KB
/
circuit_samples.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#!/usr/bin/python
#
# Script decode/encode manipulate Circuit's sample SysEx files
# (c) Simon Wood, 03 Dec 2020. GPLv2 or higher
#
from binascii import crc32
#--------------------------------------------------
# Define Sound data format using Construct (v2.9)
# requires:
# https://github.com/construct/construct
from construct import *
CircuitSample = Struct(
"channels" / Byte,
"bits" / Byte,
"rate" / Int32ul,
"length" / Int32ul, # in bytes
"data" / Bytes(this.length),
)
CircuitSamples = Struct(
"count" / Default(Byte, 0),
"samples" / Default(Array(this.count, CircuitSample),[]),
)
#--------------------------------------------------
class circuit_samples(object):
circuitHeader = (0x00, 0x20, 0x29, 0x00)
maxLength = 0x0057F000
offset = 0x0023B000
length = 0
unpackedData = None
checksum = 0
def pack(self, data):
# Pack 8bit data into 7bit
# MSB's in first byte, followed by 7 bytes (bits 6..0).
packet = bytearray(b"")
encode = bytearray(b"\x00")
for byte in data:
encode[0] |= (byte & 0x80) >> (8 - len(encode))
encode.append(byte & 0x7f)
if len(encode) > 7:
packet = packet + encode
encode = bytearray(b"\x00")
# don't forget the last few bytes
if len(encode) > 1:
packet = packet + encode
return(packet)
def unpack(self, packet):
# Unpack data 7bit to 8bit
# MSB's in first byte, followed by 7 bytes (bits 6..0).
data = bytearray(b"")
loop = 7
hibits = 0
for byte in packet:
if loop < 7:
if (hibits & (1 << loop)):
data.append(128 + byte)
else:
data.append(byte)
loop += 1
else:
hibits = byte
loop = 0
return(data)
def packNyble(self, value):
# Pack 32bit value into 8 bytes
data = bytearray(b"")
for nyble in reversed(range(8)):
data.append((value >> (4 * nyble)) & 0x0f)
return(data)
def unpackNyble(self, data):
# Unpack 8 bytes into 32bit value
value = 0
for nyble in range(8):
value = value << 4
value |= data[nyble] & 0x0f
return(value)
def readSysEx(self, filename):
self.unpackedData = b""
messages = mido.read_syx_file(filename)
for msg in messages:
if msg.type == 'sysex':
header = msg.data[0:4]
cmd = msg.data[4]
if header == self.circuitHeader:
if cmd == 0x77:
self.offset = self.unpackNyble(msg.data[5:13])
self.length = self.unpackNyble(msg.data[13:21])
if cmd == 0x79:
self.unpackedData += self.unpack(bytes(msg.data[5:]))
if cmd == 0x7a:
self.checksum = self.unpackNyble(msg.data[5:13])
return(self.unpackedData)
def writeSysEx(self, filename, unpackedData):
messages = []
# need to figure out whether we must pad the bytes
self.length = len(unpackedData)
self.unpackedData = unpackedData
self.checksum = crc32(unpackedData)
data = bytes(self.circuitHeader) + b"\x77" + \
self.packNyble(self.offset) + \
self.packNyble(self.length)
messages.append(mido.Message('sysex', data=data))
while unpackedData:
# chunk into 256 bytes
data = bytes(self.circuitHeader) + b"\x79" + \
self.pack(unpackedData[0:256])
unpackedData = unpackedData[256:]
messages.append(mido.Message('sysex', data=data))
data = bytes(self.circuitHeader) + b"\x7a" + \
self.packNyble(self.checksum)
messages.append(mido.Message('sysex', data=data))
'''
for msg in messages:
if msg.type == 'sysex':
print(msg)
'''
mido.write_syx_file(filename, messages, plaintext=False)
def endianSwap(self, data, width):
raw = bytearray()
if width == 4:
for i in range(0, len(data), width):
a = data[i:i+width]
raw.append(a[3])
raw.append(a[2])
raw.append(a[1])
raw.append(a[0])
elif width == 3:
for i in range(0, len(data), width):
a = data[i:i+width]
raw.append(a[2])
raw.append(a[1])
raw.append(a[0])
elif width == 2:
for i in range(0, len(data), width):
a = data[i:i+width]
raw.append(a[1])
raw.append(a[0])
else:
return(data)
return(bytes(raw))
#--------------------------------------------------
if __name__ == "__main__":
import sys
import os
import wave
import struct
from optparse import OptionParser
try:
import mido
_hasMido = True
if sys.platform == 'win32':
mido.set_backend('mido.backends.rtmidi_python')
except ImportError:
_hasMido = False
'''
_hasMido = False
'''
usage = "usage: %prog [options] FILENAME"
parser = OptionParser(usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-i", "--info",
help="summarize Samples/SysEx in human readable form",
action="store_true", dest="info")
parser.add_option("-o", "--outfile",
help="store SysEx into OUTFILE",
dest="outfile")
parser.add_option("-O", "--samefile",
help="store SysEx into same file as input",
action="store_true", dest="samefile")
parser.add_option("-n", "--nopad",
help="do not pad resultant SysEx upto max size (experimental)",
action="store_true", dest="nopad")
parser.add_option("-u", "--unpack",
help="unpack Samples/SysEx to UNPACK directory",
dest="unpack")
parser.add_option("-p", "--pack",
help="pack PACK directory of samples to SysEx (overwrites contents)",
dest="pack")
'''
parser.add_option("-d", "--del",
help="delete sample number DEL (changes numbering of others)",
dest="del")
'''
parser.add_option("-a", "--add",
help="add file 'ADD.wav' (at end, or replacing SAMPLE number)",
dest="add")
parser.add_option("-s", "--sample", type="int",
help="export/replace SAMPLE number",
dest="sample", default=64)
parser.add_option("-x", "--export",
help="export SAMPLE number as file 'EXPORT.wav'",
dest="export")
parser.add_option("-R", "--raw",
help="use '.raw' sample files (rather than '.wav')",
action="store_true", dest="raw")
parser.add_option("-F", "--force",
help="force rate/ch/bit when importing '.wav'",
action="store_true", dest="force")
parser.add_option("-r", "--rate", type="int",
help="set RATE when importing '.raw' files",
dest="rate", default=48000)
parser.add_option("-c", "--ch", type="int",
help="set CH(annels) when importing '.raw' files",
dest="ch", default=1)
parser.add_option("-b", "--bits", type="int",
help="set BITS when importing '.raw' files",
dest="bits", default=16)
(options, args) = parser.parse_args()
# print(options)
circuit = circuit_samples()
samples = None
if len(args) == 1:
sampleData = circuit.readSysEx(args[0])
if sampleData:
samples = CircuitSamples.parse(sampleData)
if options.samefile:
options.outfile = args[0]
if options.unpack and samples:
path = os.path.join(os.getcwd(), options.unpack)
if os.path.exists(path):
sys.exit("Directory %s already exists" % path)
os.mkdir(path)
count = 1
for sample in samples['samples']:
if options.verbose:
print("Unpacking sample %d : %s" % (count, path))
if options.raw:
name = os.path.join(path, "sample_{0:0=2d}.raw".format(count))
outfile = open(name, "wb")
outfile.write(sample['data'])
outfile.close()
# playback: aplay -c 1 -f S16_BE -r 48000 test/sample_01.raw
else:
name = os.path.join(path, "sample_{0:0=2d}.wav".format(count))
outfile = wave.open(name, "wb")
width = int(sample['bits'] / 8)
outfile.setsampwidth(width)
outfile.setnchannels(sample['channels'])
outfile.setframerate(sample['rate'])
# problem... sample data is BigEndian :-(
if width > 1:
outfile.writeframesraw(circuit.endianSwap(
sample['data'], width))
else:
outfile.writeframesraw(sample['data'])
outfile.close()
count += 1
if options.export and samples:
if options.sample > len(samples['samples']):
sys.exit("Sample %d does not exist" % options.sample)
if options.verbose:
print("Unpacking Sample %d to %s" % (options.sample, options.export))
sample = samples['samples'][options.sample - 1]
if options.raw:
# subsitute suffix if needed
if options.export[-4:] == '.wav':
options.export = options.export[:-4] + '.raw'
name = os.path.join(os.getcwd(), "%s" % options.export)
outfile = open(name, "wb")
outfile.write(sample['data'])
outfile.close()
# playback: aplay -c 1 -f S16_BE -r 48000 test/sample_01.raw
else:
name = os.path.join(os.getcwd(), "%s" % options.export)
outfile = wave.open(name, "wb")
width = int(sample['bits'] / 8)
outfile.setsampwidth(width)
outfile.setnchannels(sample['channels'])
outfile.setframerate(sample['rate'])
# problem... sample data is BigEndian :-(
if width > 1:
outfile.writeframesraw(circuit.endianSwap(
sample['data'], width))
else:
outfile.writeframesraw(sample['data'])
outfile.close()
# need to create an empty SysEx if it doesn't exist
if not samples:
temp = CircuitSamples.build({})
samples = CircuitSamples.parse(temp)
if options.pack and samples:
path = os.path.join(os.getcwd(), options.pack)
for count in range(1,65):
if options.verbose:
print("Packing sample %d : %s" % (count, path))
if options.raw:
name = os.path.join(path, "sample_{0:0=2d}.raw".format(count))
else:
name = os.path.join(path, "sample_{0:0=2d}.wav".format(count))
infile = None
if os.path.isfile(name):
infile = wave.open(name, "rb")
if infile:
if infile.getsampwidth() > 1:
raw = circuit.endianSwap(infile.readframes(
infile.getnframes()), infile.getsampwidth())
else:
raw = infile.readframes(infile.getnframes())
if options.force or options.raw:
samples['samples'].append({
"channels": options.ch,
"bits": options.bits,
"rate": options.rate,
"length": len(raw),
"data": raw })
else:
samples['samples'].append({
"channels": infile.getnchannels(),
"bits": 8 * infile.getsampwidth(),
"rate": infile.getframerate(),
"length": len(raw),
"data": raw })
samples['count'] = count
else:
break
if options.add and samples:
if options.sample < 1:
options.sample = 64
if options.sample > samples['count']:
# add at end
count = samples['count']
else:
# replace sample
count = options.sample - 1
if True:
if options.raw:
# subsitute suffix if needed
if options.add[-4:] == '.wav':
options.add = options.add[:-4] + '.raw'
name = os.path.join(os.getcwd(), options.add)
if not os.path.isfile(name):
sys.exit("Unable to open file %s for reading", name)
if options.verbose:
print("Adding sample %d : %s" % (count + 1, name))
if options.raw:
infile = open(name, "rb")
if infile:
raw = infile.read()
else:
infile = wave.open(name, "rb")
if infile:
if infile.getsampwidth() > 1:
raw = circuit.endianSwap(infile.readframes(
infile.getnframes()), infile.getsampwidth())
else:
raw = infile.readframes(infile.getnframes())
if options.force or options.raw:
samples['samples'].append({
"channels": options.ch,
"bits": options.bits,
"rate": options.rate,
"length": len(raw),
"data": raw })
else:
samples['samples'].append({
"channels": infile.getnchannels(),
"bits": 8 * infile.getsampwidth(),
"rate": infile.getframerate(),
"length": len(raw),
"data": raw })
samples['count'] = samples['count']+1
if options.info and samples:
count = 1
print("Number of samples:", samples['count'])
for sample in samples['samples']:
print("Sample %d: %d bytes (%f seconds, %d ch %d bits @ %d)" %
(count, sample['length'],
sample['length'] * 8 / (sample['bits'] * sample['rate']),
sample['channels'], sample['bits'], sample['rate']))
count += 1
if options.outfile and samples:
sampleData = CircuitSamples.build(samples)
# by default we pad the file upto the maximum size
if not options.nopad and len(sampleData) < circuit.maxLength:
sampleData += b"\x00" * (circuit.maxLength - len(sampleData))
if len(sampleData) > circuit.maxLength:
sys.exit("Resultant SysEx too large for Circuit")
if options.verbose:
print("Creating SysEx file %s" % options.outfile)
circuit.writeSysEx(options.outfile, sampleData)