-
Notifications
You must be signed in to change notification settings - Fork 1
/
flac2ogg.py
executable file
·449 lines (340 loc) · 12.4 KB
/
flac2ogg.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
#!/usr/bin/env python
"""
Audio file converter.
"""
import argparse
import multiprocessing as mp
import os
import re
import subprocess as sp
import sys
import mutagen
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3, EasyID3KeyError
VERSION = '1.0'
def match_file(path):
"""Get all wav files from provided location"""
matched_files = []
re_ = re.compile(r"^.*_\d+.wav$")
for filename in os.listdir(os.path.abspath(path)):
if re_.match(filename):
matched_files.append(os.path.join(path, filename))
return sorted(matched_files)
def get_filepaths_recursively(pattern=None):
"""Gather and return files"""
if pattern and len(pattern) == 1 and pattern[0].startswith("*"):
pat = "." + pattern[0]
else:
print("Recursive option only works with simple pattern for files"
" match")
sys.exit(1)
files_ = []
for root, _, files in os.walk("."):
for filename in files:
if re.match(pat, filename):
files_.append(os.path.join(root, filename))
return files_
def encode(obj):
"""Encode files with specified command"""
obj.encode()
class CueTrack(object):
def __init__(self):
"""Init"""
self.performer = None
self.title = None
class CueObjectParser(object):
def __init__(self, cuefile):
"""Init"""
self.cuefile = cuefile
self.album_artist = None
self.album = None
self.tracks = []
self._parse_cue()
def get_track_data(self, index):
return self.tracks[index].title, self.tracks[index].performer
def _parse_cue(self):
"""Read and parse cuefile"""
with open(self.cuefile) as fobj:
content = fobj.read()
in_track = False
track = None
for line in content.split('\n'):
if not in_track:
if line.strip().upper().startswith('REM'):
continue
if line.strip().upper().startswith('PERFORMER'):
self.album_artist = line.split('"')[1]
continue
if line.strip().upper().startswith('TITLE'):
self.album = line.split('"')[1]
continue
if 'TRACK' in line.strip().upper():
in_track = True
track = CueTrack()
self.tracks.append(track)
continue
if in_track:
if line.strip().upper().startswith('PERFORMER'):
track.performer = line.split('"')[1]
continue
if line.strip().upper().startswith('TITLE'):
track.title = line.split('"')[1]
continue
class Encoder(object):
"""Encoder base class"""
EXT = ".undefined"
def __init__(self, quality=None):
self.quality = quality
self.ext = self.EXT
def encode(self, input_fname, output_fname):
"""Encode file"""
raise NotImplementedError()
class OggEncoder(Encoder):
"""Vorbis encoder"""
EXT = ".ogg"
def __init__(self, quality=None):
"""Init"""
super(OggEncoder, self).__init__(quality)
if self.quality is None:
self.quality = 8
def encode(self, input_fname, output_fname):
sp.check_call(["oggenc", "-q%s" % self.quality, input_fname,
'-o', output_fname])
class Mp3Encoder(Encoder):
"""Mp3 encoder"""
EXT = ".mp3"
def __init__(self, quality=None):
"""Init"""
super(Mp3Encoder, self).__init__(quality)
if self.quality is None:
self.quality = 6
def encode(self, input_fname, output_fname):
sp.check_call(["lame", "-V%s" % self.quality, input_fname,
output_fname])
class FileType(object):
"""Base class for file objects"""
extensions = {'ogg': '.ogg',
'mp3': '.mp3'}
def __init__(self, filename, encoder):
self.filename = filename
self.encoder = encoder
self.out_fname = None
self.base, self.ext = os.path.splitext(filename)
self.ext = self.ext.lower()
self.wav = self.base + ".wav"
self.tmp_wav_remove = True
self.album = None
self.album_artist = None
self.title = None
self.performer = None
def extract_wav(self):
"""Dummy function for wav files"""
raise NotImplementedError()
def encode(self):
"""Encode and tag file"""
self.out_fname = self._get_output_fn()
self.extract_wav()
self.encoder.encode(self.wav, self.out_fname)
self._tag_file()
self.cleanup()
def cleanup(self):
"""Remove intermediate wav file"""
if not self.tmp_wav_remove:
return
os.unlink(self.wav)
def _get_output_fn(self):
"""Get unique name for the output file"""
out = self.base
while os.path.exists(out + self.encoder.ext):
out = out + "_encoded_"
return out + self.encoder.ext
def _tag_file(self):
"""Transfer tags from source files, or from cue"""
if self.ext == '.mp3':
tag = MP3(self.filename, ID3=EasyID3)
else:
tag = mutagen.File(self.filename)
if isinstance(self.encoder, Mp3Encoder):
self._mp3_tag(tag)
return
out_tag = mutagen.File(self.out_fname)
if self.album:
out_tag['album'] = self.album
if self.album_artist:
out_tag['albumartist'] = self.album_artist
if self.performer:
out_tag['artist'] = self.performer
if self.title:
out_tag['title'] = self.title
out_tag.save()
try:
out_tag.update(tag)
out_tag.save()
except:
pass
def _mp3_tag(self, tag):
"""Special case of tagging mp3 output file"""
mp3_tag = MP3(self.out_fname, ID3=EasyID3)
mp3_tag.add_tags(ID3=EasyID3)
if self.album:
mp3_tag['album'] = self.album
if self.performer:
mp3_tag['artist'] = self.performer
if self.title:
mp3_tag['title'] = self.title
mp3_tag.save()
for key, val in tag.items():
try:
if isinstance(val, list):
mp3_tag[key] = ", ".join(val)
else:
mp3_tag[key] = val
except EasyID3KeyError:
pass # ignore unknown keys
mp3_tag.save()
class FlacType(FileType):
"""Flac filetype"""
def extract_wav(self):
"""Call flac to extract flac file to wav"""
sp.check_call(["flac", "-d", self.filename])
class ApeType(FileType):
"""Ape filetype"""
def extract_wav(self):
"""Extract ape file to wav"""
sp.check_call(["mac", self.filename, self.wav, "-d"])
class WvType(FileType):
"""Wv filetype"""
def extract_wav(self):
"""Extract wavepack file to wav"""
sp.check_call(["wvunpack", self.filename, "-o", self.wav])
class M4aType(FileType):
"""M4a filetype"""
def __init__(self, filename, encoder):
super(M4aType, self).__init__(filename, encoder)
def extract_wav(self):
"""Extract m4a file to wav"""
wav = self.wav
if "," in wav:
wav = wav.replace(",", "\\,")
sp.check_call(["mplayer", "-vo", "none", self.filename, "-ao",
"pcm:file=%s" % wav])
class WavType(FileType):
"""Uncompressed wav filetype"""
def __init__(self, filename, encoder):
super(WavType, self).__init__(filename, encoder)
self.wav = filename
self.tmp_wav_remove = False
def extract_wav(self):
"""Do nothing, we already unpacked here"""
return
class Mp3Type(FileType):
"""Mp3 filetype"""
def extract_wav(self):
"""Extract mp3 file to wav"""
sp.check_call(["lame", "--decode", self.filename, self.wav])
class OggType(FileType):
"""Ogg Vorbis filetype"""
def extract_wav(self):
"""Extract mp3 file to wav"""
sp.check_call(["oggdec", self.filename])
class Converter(object):
"""Main class for converting files"""
extract_map = {'.ape': ApeType,
'.flac': FlacType,
'.m4a': M4aType,
'.mp3': Mp3Type,
'.ogg': OggType,
'.wav': WavType,
'.wv': WvType}
def __init__(self, split=False, files=tuple()):
"""Init"""
self.files = files
self._file_objs = []
self.split = split
def run(self, encoder):
"""Do the conversion"""
self._prepare_files(encoder)
self._encode()
def _prepare_files(self, encoder):
"""Determine file types, and create corresponding objects"""
for filename in self.files:
base, ext = os.path.splitext(filename)
if self.split:
self._split_file(filename, base, ext, encoder)
else:
klass = Converter.extract_map.get(ext.lower())
if not klass:
continue
obj = klass(filename, encoder)
self._file_objs.append(obj)
def _split_file(self, filename, base, ext, encoder):
"""Split file using cue file information"""
wav = base + ".wav"
cuefile = None
for tmp in (base + ".cue", base + ".wav.cue", base + ".flac.cue",
base + ".wv.cue", base + ".ape.cue"):
if os.path.exists(tmp):
cuefile = tmp
print("*** cuefile: %s" % cuefile)
break
if cuefile is None:
print("*** No cuefile found for `%s'" % filename)
return
cue = CueObjectParser(cuefile)
# Extract file to the wav. Note, that object will not be added to the
# list of wavs to encode
klass = Converter.extract_map.get(ext.lower())
if not klass:
print("*** Cannot find right converter for `%s'" % ext)
return
fobj = klass(filename, encoder)
fobj.extract_wav()
pipe = sp.Popen(["cuebreakpoints", cuefile], stdout=sp.PIPE)
sp.check_call(["shnsplit", "-a", base + "_", "-o", "wav", wav],
stdin=pipe.stdout, stdout=sp.PIPE)
filepath = os.path.dirname(filename)
for index, filename in enumerate(match_file(filepath)):
obj = WavType(filename, encoder)
obj.tmp_wav_remove = True
obj.album = cue.album
obj.album_artist = cue.album_artist
obj.album = cue.album
obj.title, obj.performer = cue.get_track_data(index)
self._file_objs.append(obj)
fobj.cleanup()
def _encode(self):
"""Encode files"""
pool = mp.Pool()
# NOTE: map_async and get with timeout 999 are simply a hack for being
# able to interrupt the process with ctrl+c
pool.map_async(encode, tuple(self._file_objs)).get(999)
ENCODERS = {'ogg': OggEncoder,
'mp3': Mp3Encoder}
def main():
"""Main"""
arg = argparse.ArgumentParser(description='Convert between different '
'audio file format.')
arg.add_argument('-s', '--split', action='store_true',
help='Split output file with provided *.cue file')
arg.add_argument('-r', '--recursive', action='store_true',
help='Do the files searching recursive')
arg.add_argument('-e', '--encoder', default='ogg', type=str,
choices=('ogg', 'mp3'), help='Encoder to use. Defaults '
'to "ogg"')
arg.add_argument('-q', '--quality', help='Quality of the encoded file. '
'Consult "lame" and "oggenc" for details. Defaults are '
'6 for lame and 8 for oggenc.')
arg.add_argument('-v', '--version', action='version',
version='%(prog)s v' + VERSION,
help='Display version and exit.')
arg.add_argument('files', nargs='+', help='File(s) to encode')
args = arg.parse_args()
if args.recursive:
files = get_filepaths_recursively(args.files)
else:
files = args.files
conv = Converter(args.split, files)
encoder = ENCODERS[args.encoder](args.quality)
conv.run(encoder)
if __name__ == "__main__":
main()