/
lossless.py
450 lines (313 loc) · 11.7 KB
/
lossless.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
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
import os
import subprocess
import glob
from mutagen.apev2 import APEv2
from mutagen.flac import FLAC
from cuesheet.cueyacc import parsecuedata
from util import check_command_available, MyException, \
infomsg, warnmsg, parsecuefile, conv2unicode
from util import normalize_filename, NoCuedataError
class ShntoolError(MyException):
pass
class ReplayGainError(MyException):
pass
def shnconv(filename, format="flac"):
command = [ 'shntool', 'conv', '-o', format, filename ]
exitcode = subprocess.call( command, shell=False)
if exitcode != 0:
raise ShntoolError("shntool failed to convert %s into %s format"
% (filename, format) )
def shnsplit ( filename, breakpoints, format="flac" ):
pipe = subprocess.Popen( ['shnsplit', '-O', 'never', '-o', format, filename ],
shell=False, stdin=subprocess.PIPE)
pipe.stdin.write(breakpoints)
pipe.stdin.close()
exitcode = pipe.wait()
if exitcode != 0 :
raise ShntoolError("shntool failed to split %s into %s pieces"
%(filename, format) )
pieces_pattern = "split-track*.%s" % format
pieces = glob.glob(pieces_pattern)
return sorted(pieces)
def eval_scheme(scheme, taginfo):
scheme = scheme.replace("%a" , taginfo.get("artist" , "") )
scheme = scheme.replace("%A" , taginfo.get("album" , "") )
scheme = scheme.replace("%g" , taginfo.get("genre" , "") )
scheme = scheme.replace("%t" , taginfo.get("title" , "") )
scheme = scheme.replace("%y" , taginfo.get("date" , "") )
scheme = scheme.replace("%n" , "%02d" % int(taginfo.get("tracknumber" , "") ))
return scheme
default_scheme = "%n. %t"
class LossLessAudio(object):
# A proxy class for accessing taginfo
TagProxy = None
extension = ""
format = ""
encoder = ""
decoder = ""
gainer = ""
reminder = ""
@classmethod
def check_encodable(cls):
check_command_available(cls.encoder, cls.reminder)
@classmethod
def check_decodable(cls):
check_command_available(cls.decoder, cls.reminder)
@classmethod
def calcReplayGain(cls, pieces):
pass
@staticmethod
def tag_pieces(pieces, cuesheet):
number = 1
for piece in pieces:
track = cuesheet.track(number)
target = getLossLessAudio(piece)
target.update_taginfo_from_cueinfo(track)
number += 1
@staticmethod
def rename_pieces(pieces, scheme=default_scheme):
infomsg( "renaming pieces...")
for piece in pieces:
target = getLossLessAudio(piece)
target.rename_by_taginfo(scheme)
def __init__(self, filename):
self.filename = filename
self.basename = os.path.splitext(filename)[0]
# dummy method
def extract_taginfo(self):
pass
def update_taginfo(self, **kwargs):
try :
tagproxy = self.TagProxy(self.filename)
except ValueError as e:
# previous line may fail when the file does not contain tag yet.
# this line implies overwriting.
tagproxy = self.TagProxy()
for key in kwargs.keys():
tagproxy[key] = kwargs[key]
tagproxy.save(self.filename)
def embeded_cuedata(self):
taginfo = self.extract_taginfo()
return taginfo.get("cuesheet", "")
def embeded_image(self):
pass
def split (self, cuefile, cmd_args ):
format = cmd_args.format if cmd_args.format else "flac"
scheme = cmd_args.scheme if cmd_args.scheme else default_scheme
target = getLossLessAudio("xyz." + format)
self.check_decodable()
target.check_encodable()
try :
cuesheet = parsecuefile( cuefile)
except NoCuedataError as e:
# when no cuefile is not available
infomsg( e.message)
infomsg("trying embeded cuesheet...")
cuedata = self.embeded_cuedata()
if not cuedata :
raise NoCuedataError("%s does not contain embeded cuedata."
% self.filename )
cuesheet = parsecuedata( conv2unicode(cuedata) )
infomsg( "splitting audio chunk: %s..." % self.filename)
pieces = shnsplit(self.filename, cuesheet.breakpoints(), format)
target.tag_pieces(pieces, cuesheet)
target.calcReplayGain(pieces)
target.rename_pieces(pieces, scheme)
def convert(self, format="flac"):
target = getLossLessAudio(self.basename + "." + format)
# avoid un-necessary work
if self.format == target.format :
warnmsg("%s is already in %s format." % (self.filename, self.format) )
return
self.check_decodable()
target.check_encodable()
shnconv(self.filename, format)
self._copy_taginfo(target)
def update_taginfo_from_cueinfo(self, track):
taginfo = { }
#taginfo["title"] = track.title()
#taginfo["artist"] = track.artist()
#taginfo["album"] = track.album()
#taginfo["date"] = track.date()
#taginfo["genre"] = track.genre()
#taginfo["tracknumber"] = track.tracknumber()
#taginfo["tracktotal"] = str(track.tracktotal())
#taginfo["comment"] = track.comment()
taginfo["title"] = track.title
taginfo["artist"] = track.artist
taginfo["album"] = track.album
taginfo["date"] = track.date
taginfo["genre"] = track.genre
taginfo["tracknumber"] = track.tracknumber
taginfo["tracktotal"] = str(track.tracktotal)
taginfo["comment"] = track.comment
self.update_taginfo(**taginfo)
def rename_by_taginfo(self, scheme=default_scheme):
taginfo = self.extract_taginfo()
filename = "%s%s" % ( eval_scheme(scheme, taginfo),
self.extension,
)
filename_good = normalize_filename(filename)
infomsg ("filename_good: %s => %s" % (self.filename, filename_good))
os.rename(self.filename, filename_good)
self.filename = filename_good
self.basename = os.path.splitext(filename_good)[0]
def _copy_taginfo(self, target):
taginfo = self.extract_taginfo()
target.update_taginfo(**taginfo)
def convert2flac(self):
self.convert("flac")
def convert2ape(self):
self.convert("ape")
def convert2tta(self):
self.convert("tta")
def convert2wv(self):
self.convert("wv")
def convert2wav(self):
self.convert("wav")
def debug_repr(self):
pass
class FLACAudio(LossLessAudio):
TagProxy = FLAC
extension = ".flac"
format = "FLAC"
encoder = "flac"
decoder = "flac"
gainer = "metaflac"
reminder = "please install package 'flac'. "
@classmethod
def calcReplayGain(cls, pieces):
command = ['metaflac', '--add-replay-gain' ]
command.extend(pieces)
return
infomsg( "calculating replaygain info for flac files...")
exitcode = subprocess.call( command,
shell=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
if exitcode != 0:
raise ReplayGainError( "fail to calulate replaygain for flac files. ")
def __init__(self, filename):
super(FLACAudio, self).__init__(filename)
def extract_taginfo(self):
taginfo = { }
try :
tagproxy = FLAC(self.filename)
except ValueError :
return { }
for key in tagproxy.keys():
taginfo[key.lower()] = tagproxy[key][0]
return taginfo
def convert2flac(self):
warnmsg("%s is already in %s format." % (self.filename, self.format) )
class APEAudio(LossLessAudio):
TagProxy = APEv2
extension = ".ape"
format = "APE"
encoder = "mac"
decoder = "mac"
reminder = "please install package 'mac'. "
def __init__(self, filename):
super(APEAudio, self).__init__(filename)
def extract_taginfo(self):
try :
tagproxy = APEv2( self.filename)
except ValueError :
return { }
taginfo = { }
for key in tagproxy.keys():
taginfo[key.lower()] = unicode(tagproxy[key])
return taginfo
def convert2ape(self):
warnmsg("%s is already in %s format." % (self.filename, self.format) )
class TTAAudio(LossLessAudio):
TagProxy = APEv2
extension = ".tta"
format = "TTA"
encoder = "ttaenc"
decoder = "ttaenc"
reminder = "please install package 'ttaenc'. "
def __init__(self, filename):
super(TTAAudio, self).__init__(filename)
def extract_taginfo(self):
try :
tagproxy = APEv2( self.filename)
except ValueError as e:
return { }
taginfo = { }
for key in tagproxy.keys():
taginfo[key.lower()] = unicode(tagproxy[key])
return taginfo
def convert2tta(self):
warnmsg("%s is already in %s format." % (self.filename, self.format) )
class WVAudio(LossLessAudio):
TagProxy = APEv2
extension = ".wv"
format = "WavPack"
encoder = "wavpack"
decoder = "wvunpack"
gainer = "wvgain"
reminder = "please install package 'wavpack'. "
@classmethod
def calcReplayGain(cls, pieces):
command = ['wvgain', '-a' ]
command.extend(pieces)
infomsg( "calculating replaygain info for wavpack files...")
exitcode = subprocess.call( command,
shell=False,
stdout=subprocess.PIPE,
)
if exitcode != 0:
raise ReplayGainError( "fail to calulate replaygain for wavpack files. ")
def __init__(self, filename):
super(WVAudio, self).__init__(filename)
def extract_taginfo(self):
try :
tagproxy = APEv2( self.filename)
except ValueError:
return { }
taginfo = { }
for key in tagproxy.keys():
taginfo[key.lower()] = unicode(tagproxy[key])
return taginfo
def convert2wv(self):
warnmsg("%s is already in %s format." % (self.filename, self.format) )
class WAVAudio(LossLessAudio):
extension = ".wav"
format = "Wave"
encoder = "ls"
decoder = "ls"
reminder = "command ls not founded. Are you really using *nix ?"
def __init__(self, filename):
super(WAVAudio, self).__init__(filename)
def extract_taginfo(self):
# .wav format does support taginfo
return { }
def update_taginfo(self, **kwargs):
return
def rename_by_taginfo(self, scheme=default_scheme):
# .wav format dose not support taginfo
return
def convert2wav(self):
warnmsg("%s is already in %s format." % (self.filename, self.format) )
lossless_formats = {
".flac": FLACAudio,
".ape" : APEAudio,
".tta" : TTAAudio,
".wv" : WVAudio,
".wav" : WAVAudio,
}
lossless_extensions = [ '.ape', '.flac', '.tta', '.wv', '.wav', ]
class FormatError(MyException):
pass
def getLossLessAudio(filename):
_, ext = os.path.splitext(filename)
ext = ext.lower()
try:
format = lossless_formats[ext]
return format(filename)
except KeyError :
raise FormatError("format %s is not supported." % ext)