forked from tuffy/python-audio-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracksplit
executable file
·411 lines (353 loc) · 14.8 KB
/
tracksplit
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
#!/usr/bin/python
#Audio Tools, a module and set of tools for manipulating audio data
#Copyright (C) 2007-2012 Brian Langenberger
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import audiotools
import audiotools.cue
import audiotools.ui
import sys
import os
import os.path
import gettext
gettext.install("audiotools", unicode=True)
def has_embedded_cuesheet(audiofile):
return audiofile.get_cuesheet() is not None
if (__name__ == '__main__'):
parser = audiotools.OptionParser(
_(u'%prog [options] [-d directory] <track>'),
version="Python Audio Tools %s" % (audiotools.VERSION))
parser.add_option(
'-V', '--verbose',
action='store',
dest='verbosity',
choices=audiotools.VERBOSITY_LEVELS,
default=audiotools.DEFAULT_VERBOSITY,
help=_(u'the verbosity level to execute at'))
parser.add_option(
'--cue',
action='store',
type='string',
dest='cuesheet',
metavar='FILENAME',
help=_(u'the cuesheet to use for splitting track'))
conversion = audiotools.OptionGroup(parser, _(u"Encoding Options"))
conversion.add_option(
'-t', '--type',
action='store',
dest='type',
choices=audiotools.TYPE_MAP.keys(),
help=_(u'the type of audio track to convert to'))
conversion.add_option(
'-q', '--quality',
action='store',
type='string',
dest='quality',
help=_(u'the quality to store audio tracks at'))
conversion.add_option(
'-d', '--dir',
action='store',
type='string',
dest='dir',
default='.',
help=_(u'the directory to store converted audio tracks'))
conversion.add_option(
'--format',
action='store',
type='string',
default=None,
dest='format',
help=_(u'the format string for new filenames'))
parser.add_option_group(conversion)
lookup = audiotools.OptionGroup(parser, _(u"CD Lookup Options"))
lookup.add_option(
'--musicbrainz-server', action='store',
type='string', dest='musicbrainz_server',
default=audiotools.MUSICBRAINZ_SERVER,
metavar='HOSTNAME')
lookup.add_option(
'--musicbrainz-port', action='store',
type='int', dest='musicbrainz_port',
default=audiotools.MUSICBRAINZ_PORT,
metavar='PORT')
lookup.add_option(
'--no-musicbrainz', action='store_false',
dest='use_musicbrainz',
default=audiotools.MUSICBRAINZ_SERVICE,
help='do not query MusicBrainz for metadata')
lookup.add_option(
'--freedb-server', action='store',
type='string', dest='freedb_server',
default=audiotools.FREEDB_SERVER,
metavar='HOSTNAME')
lookup.add_option(
'--freedb-port', action='store',
type='int', dest='freedb_port',
default=audiotools.FREEDB_PORT,
metavar='PORT')
lookup.add_option(
'--no-freedb', action='store_false',
dest='use_freedb',
default=audiotools.FREEDB_SERVICE,
help='do not query FreeDB for metadata')
lookup.add_option(
'-I', '--interactive',
action='store_true',
default=False,
dest='interactive',
help=_(u'edit metadata in interactive mode'))
lookup.add_option(
'-D', '--default',
dest='use_default', action='store_true', default=False,
help=_(u'when multiple choices are available, ' +
u'select the first one automatically'))
parser.add_option_group(lookup)
metadata = audiotools.OptionGroup(parser, _(u"Metadata Options"))
metadata.add_option(
'--album-number',
dest='album_number',
action='store',
type='int',
default=0,
help=_(u'the album number of this CD, ' +
u'if it is one of a series of albums'))
metadata.add_option(
'--album-total',
dest='album_total',
action='store',
type='int',
default=0,
help=_(u'the total albums of this CD\'s set, ' +
u'if it is one of a series of albums'))
#if adding ReplayGain is a lossless process
#(i.e. added as tags rather than modifying track data)
#add_replay_gain should default to True
#if not, add_replay_gain should default to False
#which is which depends on the track type
metadata.add_option(
'--replay-gain',
action='store_true',
dest='add_replay_gain',
help=_(u'add ReplayGain metadata to newly created tracks'))
metadata.add_option(
'--no-replay-gain',
action='store_false',
dest='add_replay_gain',
help=_(u'do not add ReplayGain metadata to newly extracted tracks'))
parser.add_option_group(metadata)
(options, args) = parser.parse_args()
msg = audiotools.Messenger("tracksplit", options)
#ensure interactive mode is available, if selected
if (options.interactive and (not audiotools.ui.AVAILABLE)):
audiotools.ui.not_available_message(msg)
sys.exit(1)
#get the AudioFile class we are converted to
if (options.type is not None):
AudioType = audiotools.TYPE_MAP[options.type]
else:
AudioType = audiotools.TYPE_MAP[audiotools.DEFAULT_TYPE]
#ensure the selected compression is compatible with that class
if (options.quality == 'help'):
if (len(AudioType.COMPRESSION_MODES) > 1):
msg.info(_(u"Available compression types for %s:") % \
(AudioType.NAME))
for mode in AudioType.COMPRESSION_MODES:
msg.new_row()
if (mode == audiotools.__default_quality__(AudioType.NAME)):
msg.output_column(msg.ansi(mode.decode('ascii'),
[msg.BOLD,
msg.UNDERLINE]), True)
else:
msg.output_column(mode.decode('ascii'), True)
if (mode in AudioType.COMPRESSION_DESCRIPTIONS):
msg.output_column(u" : ")
else:
msg.output_column(u" ")
msg.output_column(
AudioType.COMPRESSION_DESCRIPTIONS.get(mode, u""))
msg.info_rows()
else:
msg.error(_(u"Audio type %s has no compression modes") % \
(AudioType.NAME))
sys.exit(0)
elif (options.quality is None):
options.quality = audiotools.__default_quality__(AudioType.NAME)
elif (options.quality not in AudioType.COMPRESSION_MODES):
msg.error(_(u"\"%(quality)s\" is not a supported " +
u"compression mode for type \"%(type)s\"") %
{"quality": options.quality,
"type": AudioType.NAME})
sys.exit(1)
if (len(args) != 1):
msg.error(_(u"You must specify exactly 1 supported audio file"))
sys.exit(1)
try:
audiofile = audiotools.open(args[0])
except audiotools.UnsupportedFile:
msg.error(_(u"You must specify exactly 1 supported audio file"))
sys.exit(1)
except IOError:
msg.error(_(u"Unable to open \"%s\"") % (msg.filename(args[0])))
sys.exit(1)
if (options.add_replay_gain is None):
options.add_replay_gain = (
audiotools.ADD_REPLAYGAIN and
AudioType.lossless_replay_gain() and
audiotools.applicable_replay_gain([audiofile]))
if ((options.cuesheet is None) and (not has_embedded_cuesheet(audiofile))):
msg.error(_(u"You must specify a cuesheet to split audio file"))
sys.exit(1)
base_directory = options.dir
encoded_filenames = []
if (options.cuesheet is not None):
#grab the cuesheet we're using to split tracks
#(this overrides an embedded cuesheet)
try:
cuesheet = audiotools.read_sheet(options.cuesheet)
except audiotools.SheetException, err:
msg.error(unicode(err))
sys.exit(1)
else:
cuesheet = audiofile.get_cuesheet()
if (list(cuesheet.pcm_lengths(audiofile.total_frames()))[-1] <= 0):
msg.error(_(u"Cuesheet too long for track being split"))
sys.exit(1)
#use cuesheet to query metadata services for metadata choices
metadata_choices = audiotools.metadata_lookup(
first_track_number=1,
last_track_number=len(list(cuesheet.indexes())),
offsets=[i[-1] + 150 for i in cuesheet.indexes()],
lead_out_offset=audiofile.cd_frames() + 150,
total_length=audiofile.cd_frames(),
musicbrainz_server=options.musicbrainz_server,
musicbrainz_port=options.musicbrainz_port,
freedb_server=options.freedb_server,
freedb_port=options.freedb_port,
use_musicbrainz=options.use_musicbrainz,
use_freedb=options.use_freedb)
#populate any empty Album-level metadata fields
#with those from original file
album_metadata = audiofile.get_metadata()
if (album_metadata is not None):
album_fields = dict([(attr, field) for (attr, field) in
album_metadata.filled_fields()
if (attr in set(["album_name",
"artist_name",
"performer_name",
"composer_name",
"conductor_name",
"media",
"catalog",
"copyright",
"publisher",
"year",
"date",
"album_number",
"album_total",
"comment"]))])
for c in metadata_choices:
for m in c:
for (attr, field) in m.empty_fields():
if (attr in album_fields):
setattr(m, attr, album_fields[attr])
#update MetaData with command-line album-number/total, if given
if (options.album_number != 0):
for c in metadata_choices:
for m in c:
m.album_number = options.album_number
if (options.album_total != 0):
for c in metadata_choices:
for m in c:
m.album_total = options.album_total
#decide which metadata to use to tag split tracks
if (options.interactive):
#pick choice using interactive widget
metadata_widget = audiotools.ui.MetaDataFiller(metadata_choices)
loop = audiotools.ui.urwid.MainLoop(
metadata_widget,
[('key', 'white', 'dark blue')],
unhandled_input=metadata_widget.handle_text)
loop.run()
track_metadatas = dict([(m.track_number, m) for m in
metadata_widget.populated_metadata()])
else:
if ((len(metadata_choices) == 1) or options.use_default):
#use default choice
track_metadatas = dict([(m.track_number, m) for m in
metadata_choices[0]])
else:
#pick choice using raw stdin/stdout
track_metadatas = \
dict([(m.track_number, m) for m in
audiotools.ui.select_metadata(metadata_choices, msg)])
#pull ISRC metadata from the cuesheet, if any
cuesheet_ISRCs = cuesheet.ISRCs()
for metadata in track_metadatas.values():
if ((len(metadata.ISRC) == 0) and
(metadata.track_number in cuesheet_ISRCs.keys())):
metadata.ISRC = \
cuesheet_ISRCs[metadata.track_number].decode('ascii',
'replace')
#perform actual track splitting and tagging
encoded_files = []
total_pcm = audiotools.BufferedPCMReader(audiofile.to_pcm())
try:
for (i, pcm_frames) in enumerate(
cuesheet.pcm_lengths(audiofile.total_frames())):
track_number = i + 1
track_metadata = track_metadatas.get(track_number, None)
filename = os.path.join(
base_directory,
AudioType.track_name(
file_path=audiofile.filename,
track_metadata=track_metadata,
format=options.format))
audiotools.make_dirs(filename)
progress = audiotools.SingleProgressDisplay(
msg, msg.filename(filename))
#FIXME - catch from_pcm errors here
encoded_files.append(
AudioType.from_pcm(
filename,
audiotools.PCMReaderProgress(
audiotools.LimitedPCMReader(total_pcm, pcm_frames),
pcm_frames,
progress.update),
options.quality))
encoded_files[-1].set_metadata(track_metadata)
progress.clear()
msg.info(u"%s -> %s" %
(msg.filename(audiofile.filename),
msg.filename(filename)))
except audiotools.UnsupportedTracknameField, err:
err.error_msg(msg)
sys.exit(1)
except audiotools.EncodingError, err:
msg.error(unicode(err))
sys.exit(1)
#apply ReplayGain to split tracks, if requested
if (options.add_replay_gain and AudioType.can_add_replay_gain()):
rg_progress = audiotools.ReplayGainProgressDisplay(
msg, AudioType.lossless_replay_gain())
rg_progress.initial_message()
try:
#separate encoded files by album_name and album_number
for album in audiotools.group_tracks(encoded_files):
#add ReplayGain to groups of files
#belonging to the same album
AudioType.add_replay_gain([a.filename for a in album],
rg_progress.update)
except ValueError, err:
rg_progress.clear()
msg.error(unicode(err))
sys.exit(1)
rg_progress.final_message()