-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconverter.py
executable file
·432 lines (376 loc) · 12.8 KB
/
converter.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# remove warnings for constants (coming for macOS)
# ruff: noqa: N816
import base64
import pathlib
from string import Template
import struct
from typing import Literal
from iir.filter_iir import Biquad, q2bw, bw2q
from iir.filter_peq import peq_preamp_gain, Peq
SRATE = 48000
# types
IIR = list[dict[str, int | float]]
STATUS = Literal[True] | Literal[False]
# ----------------------------------------------------------------------
# AUPRESET
# ----------------------------------------------------------------------
def guess_format(lines: list[str]) -> str:
has_q = False
has_bw = False
has_width = False
has_filter = False
for line in lines:
if line.find("AU_N-Band_EQ") != -1:
has_width = True
if line.find("Filter ") != -1:
has_filter = True
if line.find(" Q ") != -1:
has_q = True
if line.find(" BW ") != -1:
has_bw = True
if has_width:
# generated by REW for AUNBandEQ
return "AUNBandEQ"
if has_filter and (has_q or has_bw):
# more or less EQ APO format / used by autoEQ too
return "APO"
return "Unknown"
def parse_aunbandeq(lines: list[str]) -> tuple[STATUS, IIR]:
iir = []
for line in lines:
tokens = line.split()
len_tokens = len(tokens)
# print(len_tokens, line)
if len_tokens != 8 or tokens[0] == "Number" or tokens[3] == "None":
# print('DEBUG dropping line {}'.format(line))
continue
iir.append(
{
"type": tokens[3],
"freq": float(tokens[4]),
"gain": float(tokens[5]),
"width": float(tokens[6]),
}
)
return True, iir
def parse_apo(lines: list[str]) -> tuple[STATUS, IIR]:
iir = []
for line in lines:
tokens = line.split()
len_tokens = len(tokens)
# print(len_tokens, line)
if (
len_tokens > 0
and tokens[0] == "Filter"
and tokens[2] == "ON"
and tokens[3] != "None"
):
if len_tokens == 12:
iir.append(
{
"type": tokens[3],
"freq": float(tokens[5]),
"gain": float(tokens[8]),
"q": float(tokens[11]),
"width": q2bw(float(tokens[11])),
}
)
elif len_tokens == 13:
iir.append(
{
"type": tokens[3],
"freq": float(tokens[5]),
"gain": float(tokens[8]),
"q": bw2q(float(tokens[12])),
"width": float(tokens[12]),
}
)
return True, iir
def iir2peq(iir: IIR) -> Peq:
peq = []
for biquad in iir:
biquad_type = {
"PK": Biquad.PEAK,
"LP": Biquad.LOWPASS,
"HP": Biquad.HIGHPASS,
"LS": Biquad.LOWSHELF,
"HS": Biquad.HIGHSHELF,
"BP": Biquad.BANDPASS,
}.get(str(biquad["type"]))
if biquad_type is None:
continue
freq = biquad["freq"]
gain = biquad["gain"]
width = biquad["width"]
q = bw2q(width)
peq.append((1.0, Biquad(biquad_type, freq, SRATE, q, gain)))
return peq
def lines2iir(lines: list[str]) -> tuple[STATUS, IIR]:
option = guess_format(lines)
if option == "AUNBandEQ":
return parse_aunbandeq(lines)
elif option == "APO":
return parse_apo(lines)
return True, []
# ----------------------------------------------------------------------
# AUPRESET
# ----------------------------------------------------------------------
PRESET_DIR = pathlib.PosixPath(
"~/Library/Audio/Presets/Apple/AUNBandEQ"
).expanduser()
# https://developer.apple.com/documentation/audiotoolbox/1389745-aunbandeq_parameters
kAUNBandEQParam_BypassBand = 1000
kAUNBandEQParam_FilterType = 2000
kAUNBandEQParam_Frequency = 3000
kAUNBandEQParam_Gain = 4000
kAUNBandEQParam_Bandwidth = 5000
kAUNBandEQParam_GlobalGain = 0
#
kAUNBandEQProperty_NumberOfBands = 2200
kAUNBandEQProperty_MaxNumberOfBands = 2201
kAUNBandEQProperty_BiquadCoefficients = 2203
#
kAUNBandEQFilterType_Parametric = 0
kAUNBandEQFilterType_2ndOrderButterworthLowPass = 1
kAUNBandEQFilterType_2ndOrderButterworthHighPass = 2
kAUNBandEQFilterType_ResonantLowPass = 3
kAUNBandEQFilterType_ResonantHighPass = 4
kAUNBandEQFilterType_BandPass = 5
kAUNBandEQFilterType_BandStop = 6
kAUNBandEQFilterType_LowShelf = 7
kAUNBandEQFilterType_HighShelf = 8
kAUNBandEQFilterType_ResonantLowShelf = 9
kAUNBandEQFilterType_ResonantHighShelf = 10
kNumAUNBandEQFilterTypes = 11
# plist template, could also use a library
AUPRESET_TEMPLATE = Template(
'\
<?xml version="1.0" encoding="UTF-8"?>\n\
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n\
<plist version="1.0">\n\
<dict>\n\
<key>ParametricType</key>\n\
<integer>11</integer>\n\
<key>data</key>\n\
<data>\n\
$data\n\
</data>\n\
<key>manufacturer</key>\n\
<integer>1634758764</integer>\n\
<key>name</key>\n\
<string>$name</string>\n\
<key>numberOfBands</key>\n\
<integer>$number_of_bands</integer>\n\
<key>subtype</key>\n\
<integer>1851942257</integer>\n\
<key>type</key>\n\
<integer>1635083896</integer>\n\
<key>version</key>\n\
<integer>0</integer>\n\
</dict>\n\
</plist>\n\
'
)
def file2iir(filename: str) -> tuple[STATUS, IIR]:
with open(filename, "r", encoding="utf-8") as fd:
lines = fd.readlines()
return lines2iir(lines)
return False, []
def iir2data(iir: IIR) -> tuple[STATUS, int, str]:
"""Build the data field from an iir"""
def type2value(t: str) -> int:
"""Transform a IIR type into the corresponding value for AUNBandEQ"""
val = {
"PK": kAUNBandEQFilterType_Parametric,
"HS": kAUNBandEQFilterType_HighShelf,
"LS": kAUNBandEQFilterType_LowShelf,
"HP": kAUNBandEQFilterType_ResonantHighPass,
"LP": kAUNBandEQFilterType_ResonantLowPass,
"BP": kAUNBandEQFilterType_BandPass,
}.get(t, -1)
if val == -1:
print(
"error in eq: {} is not supported yet, contact developer please!".format(
t
)
)
return val
len_iir = len(iir)
# print(len_iir)
# print(iir)
peq = iir2peq(iir)
preamp_gain = peq_preamp_gain(peq)
params = {}
for i, current_iir in enumerate(iir):
params["{:d}".format(kAUNBandEQParam_BypassBand + i)] = 0.0 # True
params["{:d}".format(kAUNBandEQParam_FilterType + i)] = type2value(
str(current_iir["type"])
)
params["{:d}".format(kAUNBandEQParam_Frequency + i)] = float(
current_iir["freq"]
)
params["{:d}".format(kAUNBandEQParam_Gain + i)] = float(
current_iir["gain"]
)
params["{:d}".format(kAUNBandEQParam_Bandwidth + i)] = float(
current_iir["width"]
)
# remainings EQ are required and are set to 0
for i in range(len_iir, 16):
params["{:d}".format(kAUNBandEQParam_BypassBand + i)] = 1.0 # False
params["{:d}".format(kAUNBandEQParam_FilterType + i)] = 0
params["{:d}".format(kAUNBandEQParam_Frequency + i)] = 0.0
params["{:d}".format(kAUNBandEQParam_Gain + i)] = 0.0
params["{:d}".format(kAUNBandEQParam_Bandwidth + i)] = 0.0
# some black magic, data is padded, the only important values are
# 3. number of parameters + 1
# 5. db_gain
# need to check if length is variable or not
# ndata = 5
# for current_iir in iir:
# ndata += 2
# if current_iir["type"] == "PK":
# ndata += 3
# elif current_iir["type"] in ("LS", "HS", "BP", "BS", "RLP", "RHP"):
# ndata += 2
# elif current_iir["type"] in ("BLP", "BHP"):
# ndata += 1
ndata = 81
buffer = struct.pack(">llllf", 0, 0, ndata, 0, preamp_gain)
# add pairs of (param_id, value) in big endian
# it looks like Apple now sort them
for param_id, value in sorted(params.items()):
if param_id[0] in ("2"):
# value is unsigned int https://developer.apple.com/documentation/audiotoolbox/audiounitparameterid
# buffer += struct.pack(">ll", int(param_id), value)
buffer += struct.pack(">lf", int(param_id), float(value))
else:
# value is a float
buffer += struct.pack(">lf", int(param_id), value)
# convert the byte buffer to base64
text = base64.standard_b64encode(buffer).decode("ascii")
# add \t and slice in chunks of 68 chars
nchunks = 68
len_text = len(text) // nchunks
slices = [
"\t{}\n".format(text[i * nchunks : (i + 1) * nchunks])
for i in range(len_text)
]
slices += ["\t{}".format(text[len_text * nchunks :])]
return True, len_iir, "".join(slices)
def iir2aupreset(iir: list, name: str) -> tuple[STATUS, str]:
status, nbands, data = iir2data(iir)
if not status:
return status, ""
return True, AUPRESET_TEMPLATE.substitute(
data=data, name=name, number_of_bands=nbands
)
# ----------------------------------------------------------------------
# RME
# ----------------------------------------------------------------------
def type2rme(t: str, pos: int) -> float:
if t == "PK":
return 0.0
elif t == "LP":
if pos == 1:
return 3.0
elif pos == 3:
return 2.0
elif t == "HP":
if pos == 1:
return 2.0
elif pos == 3:
return 3.0
elif t == "LS": # noqa: SIM102
if pos == 3:
return 2.0
return -1.0
def iir2rme_totalmix_channel(iirs: list) -> tuple[STATUS, str]:
lines = []
lines.append("<Preset>")
lines.append(" <Equalizer>")
lines.append(" <Params>")
# for now, default
lines.append(' <val e="LC Grade" v="1.00,"/>')
lines.append(' <val e="LC Freq" v="20.00,"/>')
for i, iir in enumerate(iirs):
q = iir.get("q", 0.0)
if "q" not in iir and "width" in iir:
q = bw2q(iir["width"])
lines.append(
' <val e="Band{} Freq" v="{:7.2f},"/>'.format(
i + 1, iir["freq"]
)
)
lines.append(' <val e="Band{} Q" v="{:4.2f},"/>'.format(i + 1, q))
lines.append(
' <val e="Band{} Gain" v="{:4.2f},"/>'.format(
i + 1, iir["gain"]
)
)
for i, iir in enumerate(iirs):
rme = type2rme(iir["type"], i + 1)
if rme == -1:
print("skip eq {} type is unknown {}".format(i, iir["type"]))
continue
lines.append(
' <val e="Band{} Type" v="{:4.2f},"/>'.format(i + 1, rme)
)
lines.append(" </Params>")
lines.append(" </Equalizer>")
lines.append("</Preset>")
return True, "\n".join(lines)
def iir2rme_totalmix_room(left: list, right: list) -> tuple[STATUS, str]:
lines = []
def process(iirs: list):
for i, iir in enumerate(iirs):
q = iir.get("q", 0.0)
if "q" not in iir and "width" in iir:
q = bw2q(iir["width"])
lines.append(
' <val e="REQ Band{} Freq" v="{:7.2f},"/>'.format(
i + 1, iir["freq"]
)
)
lines.append(
' <val e="REQ Band{} Q" v="{:4.2f},"/>'.format(i + 1, q)
)
lines.append(
' <val e="REQ Band{} Gain" v="{:4.2f},"/>'.format(
i + 1, iir["gain"]
)
)
for i, iir in enumerate(iirs):
rme = type2rme(iir["type"], i + 1)
if rme == -1:
print("skip eq {} type is unknown {}", i, iir["type"])
continue
lines.append(
' <val e="REQ Band{} Type" v="{:4.2f},"/>'.format(
i + 1, rme
)
)
lines.append("<Preset>")
preamp_gain = 0.0
lines.append(" <Room EQ L>")
lines.append(" <Params>")
lines.append(' <val e="REQ Delay" v="0.00,"/>')
process(left)
lines.append(' <val e="REQ Chan Gain" v="{},"/>'.format(preamp_gain))
lines.append(" </Params>")
lines.append(" </Room EQ L>")
preamp_gain = 0.0
lines.append(" <Room EQ R>")
lines.append(" <Params>")
lines.append(' <val e="REQ Delay" v="0.00,"/>')
if len(right) > 0:
process(right)
else:
process(left)
lines.append(' <val e="REQ Chan Gain" v="{},"/>'.format(preamp_gain))
lines.append(" </Params>")
lines.append(" </Room EQ R>")
lines.append("</Preset>")
return True, "\n".join(lines)