-
Notifications
You must be signed in to change notification settings - Fork 15
/
riff.py
271 lines (244 loc) · 10.5 KB
/
riff.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
#!/usr/bin/env python
# coding: utf-8
#
# Utility to create ATRAC3 RIFF files from EA3 files
# Parsing of EA3 is incomplete and assumes that the file
# was generated by atracdenc --encode=atrac3
#
# See https://github.com/GrapheneCt/ElevenMPV-A/blob/master/ElevenMPV-A/source/audio/at3.cpp for more complete parsing of EA3 files.
#
import argparse
import os
import struct
def copy_riff(src, dst, max_duration_ms=0):
r = parse_riff(src)
if not r:
return
if r['fmt ']['compression_code'] != 1:
print('Not an uncompressed WAV file.')
return
with open(src, 'rb') as i:
buf = i.read()
buf = buf[12:]
with open(dst, 'wb') as o:
o.write(b'RIFF\x00\x00\x00\x00WAVE')
while buf:
_len = struct.unpack_from('<I', buf, 4)[0]
_l = _len
_c = buf[:4].decode()
if _c == 'data' and max_duration_ms:
_sp = round(1000000000 / r['fmt ']['sample_rate'])
if len(buf) > int(max_duration_ms * 1000000 / _sp) * 4:
print('Clamping file to', max_duration_ms, 'ms')
_l = int(max_duration_ms * 1000000 / _sp) * 4
_b = bytearray(buf[:8 + _l])
struct.pack_into('<I', _b, 4, _l)
o.write(_b)
_len = (_len + 1) & ~1 # chunks are 16 bit aligned
buf = buf[8 + _len:]
x = o.tell() - 8
_b = bytearray(4)
struct.pack_into('<I', _b, 0, x)
o.seek(4)
o.write(_b)
def parse_riff(riff):
with open(riff, 'rb') as f:
buf = f.read()
if buf[:4] != b'RIFF':
print('Not a RIFF File.')
return None
_len = struct.unpack_from('<I', buf, 4)[0]
if _len + 8 != os.stat(riff).st_size:
print('RIFF Header length invalid. Was', _len, 'but expected', os.stat(riff).st_size - 8)
return None
if buf[8:12] != b'WAVE':
print('Not a RIFF/WAVE File.')
return None
result = {}
buf = buf[12:]
while buf:
_len = struct.unpack_from('<I', buf, 4)[0]
_c = buf[:4].decode()
_b = buf[8:8 + _len]
result[_c] = {'data': _b}
if _c == 'fmt ':
result[_c]['compression_code'] = struct.unpack_from('<H', _b, 0)[0]
result[_c]['number_of_channel'] = struct.unpack_from('<H', _b, 2)[0]
result[_c]['sample_rate'] = struct.unpack_from('<I', _b, 4)[0]
result[_c]['average_bytes_per_second'] = struct.unpack_from('<I', _b, 8)[0]
result[_c]['block_align'] = struct.unpack_from('<H', _b, 12)[0]
result[_c]['significant_bits_per_sample'] = struct.unpack_from('<H', _b, 14)[0]
if len(_b[16:]) > 2:
result[_c]['extra_bytes'] = _b[18:]
elif _c == 'data':
True
elif _c == 'fact':
if _len == 4:
result[_c]['number_of_samples'] = [struct.unpack_from('<I', _b, 0)[0]]
elif _len == 8:
result[_c]['number_of_samples'] = [struct.unpack_from('<I', _b, 0)[0], struct.unpack_from('<I', _b, 4)[0]]
elif _c == 'smpl':
result[_c]['manufacturer'] = struct.unpack_from('<I', _b, 0)[0]
result[_c]['product'] = struct.unpack_from('<I', _b, 4)[0]
result[_c]['sample_period'] = struct.unpack_from('<I', _b, 8)[0]
result[_c]['midi_unity_note'] = struct.unpack_from('<I', _b, 12)[0]
result[_c]['midi_pitch_fraction'] = struct.unpack_from('<I', _b, 16)[0]
result[_c]['smpte_format'] = struct.unpack_from('<I', _b, 20)[0]
result[_c]['smpte_offset'] = struct.unpack_from('<I', _b, 24)[0]
result[_c]['num_sample_loops'] = struct.unpack_from('<I', _b, 28)[0]
result[_c]['sampler_data'] = struct.unpack_from('<I', _b, 32)[0]
_b = _b[36:36 + result[_c]['sampler_data']]
if result[_c]['num_sample_loops']:
result[_c]['loops'] = []
for i in range(result[_c]['num_sample_loops']):
r = {}
r['cue_point_id'] = struct.unpack_from('<I', _b, 0)[0]
r['type'] = struct.unpack_from('<I', _b, 4)[0]
r['start'] = struct.unpack_from('<I', _b, 8)[0]
r['end'] = struct.unpack_from('<I', _b, 12)[0]
r['fraction'] = struct.unpack_from('<I', _b, 16)[0]
r['play_count'] = struct.unpack_from('<I', _b, 20)[0]
result[_c]['loops'].append(r)
_b = _b[24:]
elif _c == 'LIST':
True
else:
print('Unknown chunk type', buf[:4])
_len = (_len + 1) & ~1 # chunks are 16 bit aligned
buf = buf[8 + _len:]
return result
def dump_riff(riff):
print('Dumping', riff)
res = parse_riff(riff)
if not res:
print('Not a RIFF/WAVE File.')
exit()
for k in res:
print(k, ': Size 0x%08x (%d) bytes' % (len(res[k]['data']), len(res[k]['data'])))
if k != 'data':
for l in res[k]:
print('\t', l + ':', res[k][l])
def create_riff(ea3, riff, number_of_samples=0, max_data_size=0, loop=False):
print('Create', riff, 'from', ea3)
with open(riff, 'wb') as f:
buf = bytearray(12)
buf[:4] = b'RIFF'
buf[8:12] = b'WAVE'
f.write(buf)
# fmt
_b = bytearray(24)
_b[:4] = b'fmt '
struct.pack_into('<H', _b, 8, 0x270) # compression code
struct.pack_into('<H', _b, 10, 2) # number of channels
struct.pack_into('<I', _b, 12, 44100) # sample rate
struct.pack_into('<I', _b, 16, 16537) # avg bytes per sec
struct.pack_into('<H', _b, 20, 384) # block align
struct.pack_into('<H', _b, 22, 0) # significant bits per sample
_b = _b + b'\x0e\x00'
_b = _b + b'\x01\x00\x00\x10\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00'
struct.pack_into('<I', _b, 4, len(_b) - 8)
f.write(_b)
with open(ea3, 'rb') as d:
buf = d.read()
if buf[:4] != b'EA3\x01':
print('Not a valid EA3 file', ea3, 'aborting.')
exit()
buf = buf[96:]
if max_data_size and len(buf) > max_data_size:
buf = buf[:max_data_size & ~0x3f]
print('Clamping max size to', max_data_size + ~0x3f)
# Clamped the file so number_of_samples are no longer valid
number_of_samples = 0
data_size = len(buf)
if not number_of_samples:
# guesstimate number of samples
number_of_samples = int(data_size / 0xc0 * 0x201)
if loop:
_b = bytearray(16)
_b[:4] = b'fact'
struct.pack_into('<I', _b, 4, len(_b) - 8)
struct.pack_into('<I', _b, 8, (number_of_samples & ~0xfff) - 0x2000)
struct.pack_into('<I', _b, 12, 0x800)
f.write(_b)
# loop(s)
_l = bytearray(24)
struct.pack_into('<I', _l, 0, 0) # cue point id
struct.pack_into('<I', _l, 4, 0) # type
struct.pack_into('<I', _l, 8, 0x800) # start
struct.pack_into('<I', _l, 12, (number_of_samples & ~0xfff) - 0x2000 - 0x2801) # end
struct.pack_into('<I', _l, 16, 0) # fraction
struct.pack_into('<I', _l, 20, 0) # play count
_s = bytearray(36)
struct.pack_into('<I', _s, 0, 0) # manufacturer
struct.pack_into('<I', _s, 4, 0) # product
struct.pack_into('<I', _s, 8, 22676) # sample period
struct.pack_into('<I', _s, 12, 60) # midi unity node
struct.pack_into('<I', _s, 16, 0) # midi pitch fraction
struct.pack_into('<I', _s, 20, 0) # smpte format
struct.pack_into('<I', _s, 24, 0) # smpte offset
struct.pack_into('<I', _s, 28, int(len(_l)/24)) # num sample loops
struct.pack_into('<I', _s, 32, len(_l)) # sampler data
_b = bytearray(8)
_b[:4] = b'smpl'
struct.pack_into('<I', _b, 4, len(_s) + len(_l))
f.write(_b + _s + _l)
#data
_b = bytearray(8)
_b[:4] = b'data'
struct.pack_into('<I', _b, 4, data_size)
buf = _b + buf
if len(buf) & 1:
buf = buf + b'\0'
f.write(buf)
if not loop:
# fact
_b = bytearray(12)
_b[:4] = b'fact'
struct.pack_into('<I', _b, 4, len(_b) - 8)
struct.pack_into('<I', _b, 8, number_of_samples)
f.write(_b)
# LIST
buf = b'ATRACDENC\0'
_b = bytearray(4)
struct.pack_into('<I', _b, 0, len(buf))
buf = b'INFOISFT' + _b + buf
_b = bytearray(4)
struct.pack_into('<I', _b, 0, len(buf))
buf = b'LIST' + _b + buf
if len(buf) & 1:
buf = buf + b'\0'
f.write(buf)
# update the RIFF length
f.seek(0, 2)
x = f.tell() - 8
_b = bytearray(4)
struct.pack_into('<I', _b, 0, x)
f.seek(4)
f.write(_b)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('command', nargs=1,
help='create|dump|copy')
parser.add_argument('--max-data-size', nargs='?', const=0, type=int,
help='Clamp the data chunk to this size')
parser.add_argument('--max-duration-ms', nargs='?', const=0, type=int,
help='Clamp the data chunk to this length in ms')
parser.add_argument('--number-of-samples', nargs='?', const=0, type=int,
help='Number of samples for the \'fact\' chunk')
parser.add_argument('--loop', action='store_true', help='Create a loop')
parser.add_argument('files', nargs='*', help='RIFF/WAVE file')
args = parser.parse_args()
if args.command[0] == 'dump':
dump_riff(args.files[0])
elif args.command[0] == 'create':
if len(args.files) != 2:
print('Usage: riff.py create FILE.EA3 FILE.AT3')
exit()
create_riff(args.files[0], args.files[1], number_of_samples=args.number_of_samples, max_data_size=args.max_data_size, loop=args.loop)
elif args.command[0] == 'copy':
if len(args.files) != 2:
print('Usage: riff.py copy SRC.WAV DST.WAV')
exit()
copy_riff(args.files[0], args.files[1], max_duration_ms=args.max_duration_ms)
else:
print('No command given. Aborting')