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
|
#!/usr/bin/env python
from cutter import formats, cue
from cutter.coding import to_unicode, to_bytes
from cutter.splitter import Splitter, StreamInfo
from cutter.tools import *
from optparse import OptionParser, OptionGroup, IndentedHelpFormatter
import signal
import sys
import os
import re
re_range = re.compile("^(\d+)-(\d+)$")
try:
from cutter import config
except Exception as err:
printerr("import config failed: %s", err)
sys.exit(0)
def print_cue(cue):
for k, v in cue.attrs():
printf("%s: %s\n", k.upper(), quote(v))
for file in cue.files():
name = cue.dir + file.name
printf("FILE %s", quote(file.name))
if not os.path.exists(name):
printf(": not exists\n")
else:
info = StreamInfo.get(name)
if not info:
printf(": unknown type\n")
else:
printf(" [%s] (%d/%d, %d ch)\n",
info.type,
info.bits_per_sample,
info.sample_rate,
info.channels)
for track in file.tracks():
printf("\tTRACK %02d", track.number)
title = track.get("title")
if title != "":
printf(" %s", quote(title))
printf(": %s -", msf(track.begin))
if track.end is not None:
printf(" %s", msf(track.end))
printf("\n")
for k, v in track.attrs():
if k not in ("pregap", "postgap", "title"):
printf("\t\t%s: %s\n", k.upper(), quote(v))
def parse_args():
parser = OptionParser(usage = u"Usage: %prog [options] cuefile",
formatter=IndentedHelpFormatter(max_help_position=40))
parser.add_option("--ignore",
action="store_true", default=False, dest="ignore",
help="ignore cue parsing errors")
parser.add_option("--dump",
dest="dump", choices=["cue", "tags", "tracks"],
metavar="cue|tags|tracks",
help="print cue data, file tags or track names")
parser.add_option("-n", "--dry-run",
action="store_true", default=False, dest="dry_run")
parser.add_option("-v", "--verbose",
dest="verbose", action="store_true", default=False)
general = OptionGroup(parser, "General options")
general.add_option("--tag",
dest="tag", action="store_true", default=False,
help="tag existing files, do not split")
general.add_option("--coding", dest="coding",
help="encoding of original text")
general.add_option("-d", "--dir",
dest="dir", default=config.DIR, help="output directory")
general.add_option("--use-tempdir",
dest="use_tempdir", action="store_true",
help="use temporary directory for files")
general.add_option("--no-tempdir",
dest="use_tempdir", action="store_false",
help="do not use temporary directory")
general.add_option("--no-progress",
dest="show_progress", action="store_false")
general.add_option("--tracks", dest="tracks", help="select tracks")
parser.add_option_group(general)
enc = OptionGroup(parser, "Encoding options")
enc.add_option("-t", "--type", dest="type",
choices = formats.supported() + ["help"],
help="output file format")
enc.add_option("-C", "--compression", type="int",
dest="compression", metavar="FACTOR",
help="compression factor for output format (used for flac, ogg)")
enc.add_option("--bitrate", type="int",
dest="bitrate", default=config.MP3_BITRATE,
help="audio bitrate (used for mp3)")
parser.add_option_group(enc)
fname = OptionGroup(parser, "Filename options")
fname.add_option("--format",
dest="fmt", default=config.FILENAME_FORMAT,
help="the format string for new filenames")
fname.add_option("--convert-chars",
dest="convert_chars", action="store_true",
help="replace illegal characters in filename")
fname.add_option("--no-convert-chars",
dest="convert_chars", action="store_false",
help="do not replace characters in filename")
parser.add_option_group(fname)
format = OptionGroup(parser, "Output format")
format.add_option("-r", "--sample-rate", type="int",
dest="sample_rate", default=config.SAMPLE_RATE, metavar="RATE")
format.add_option("-c", "--channels", type="int",
dest="channels", default=config.CHANNELS)
format.add_option("-b", "--bits-per-sample", type="int",
dest="bits_per_sample", default=config.BITS_PER_SAMPLE, metavar="BITS")
parser.add_option_group(format)
tag = OptionGroup(parser, "Tag options")
tag_options = ["album", "artist", ("date", "year"), "genre",
"comment", "composer", "albumartist"]
for opt in tag_options:
if type(opt) in (list, tuple):
tag.add_option(*["--" + s for s in opt], dest=opt[0], default="")
else:
tag.add_option("--" + opt, dest=opt, default="")
tag.add_option("--track-total", type="int", dest="tracktotal", metavar="TOTAL")
tag.add_option("--track-start", type="int", dest="trackstart", metavar="START")
parser.add_option_group(tag)
return parser.parse_args()
def option_check_range(option, value, min, max):
if value is not None and (value < min or value > max):
printerr("invalid %s value %d, must be in range %d .. %d", option, value, min, max)
return False
return True
def parse_tracks(string):
tracks = set()
for item in string.split(","):
try:
value = int(item)
tracks.add(value)
except ValueError:
m = re_range.match(item)
if not m:
return None
start, end = int(m.group(1)), int(m.group(2))
if start <= 0 or end <= 0 or start == end:
return None
if start > end:
start, end = end, start
tracks.update(range(start, end + 1))
return None if len(tracks) == 0 else tracks
def process_options(opt):
def choose(a, b):
return a if a is not None else b
if opt.type == "help":
printerr("supported formats: " + " ".join(formats.supported()))
return False
if opt.type is None and config.TYPE:
if not formats.issupported(config.TYPE):
printerr("invalid configuration: type '%s' is not supported", config.TYPE)
return False
opt.type = config.TYPE
if not opt.dump and opt.type is None:
printerr("--type option is missed")
return False
if opt.type == "flac":
opt.compression = choose(opt.compression, config.FLAC_COMPRESSION)
if not option_check_range("compression", opt.compression, 0, 8):
return False
elif opt.type == "ogg":
opt.compression = choose(opt.compression, config.OGG_COMPRESSION)
if not option_check_range("compression", opt.compression, -1, 10):
return False
elif opt.type == "mp3":
if not option_check_range("bitrate", opt.bitrate, 32, 320):
return False
if not opt.dir:
opt.dir = u"."
else:
opt.dir = to_unicode(os.path.normpath(opt.dir))
opt.fmt = to_unicode(opt.fmt)
if not os.path.basename(opt.fmt):
printerr("invalid format option \"%s\"", opt.fmt)
return False
else:
opt.fmt = os.path.normpath(opt.fmt)
if opt.fmt.startswith("/"):
opt.fmt = opt.fmt[1:]
if opt.convert_chars is None:
opt.convert_chars = config.CONVERT_CHARS
if opt.use_tempdir is None:
opt.use_tempdir = config.USE_TEMPDIR
if opt.tracks is not None:
tracks = parse_tracks(opt.tracks)
if not tracks:
printerr("invalid tracks option \"%s\"", opt.tracks)
return False
opt.tracks = tracks
if not os.isatty(sys.stdout.fileno()):
opt.show_progress = False
elif opt.show_progress is None:
opt.show_progress = config.PROGRESS
return True
def find_cuefile(path):
for file in os.listdir(path):
fullname = os.path.join(path, file)
if os.path.isfile(fullname) and file.endswith(".cue"):
return fullname
printerr("no cue file")
sys.exit(1)
def switch(value, opts):
opts.get(value, lambda: None)()
def sigint_handler(sig, frame):
printf("\n")
sys.exit(1)
def main():
signal.signal(signal.SIGINT, sigint_handler)
options, args = parse_args()
if not process_options(options):
sys.exit(1)
if len(args) != 1:
printf("Usage: %s [options] cuefile\n", progname)
return 1
def on_error(err):
printerr("%d: %s\n" % (err.line, err))
if not options.ignore:
raise StopIteration
cuepath = to_unicode(args[0])
if os.path.isdir(cuepath):
cuepath = find_cuefile(cuepath)
if options.dry_run:
debug("use cue file %s", quote(cuepath))
try:
cuesheet = cue.read(cuepath, options.coding, on_error=on_error)
except StopIteration:
return 1
except IOError as err:
printerr("open %s: %s", err.filename, err.strerror)
return 1
except Exception as err:
msg = "%s (%s)" % (err, err.__class__.__name__)
if hasattr(err, "filename"):
printerr("%s: %s: %s\n", err.filename, msg)
else:
printerr("%s\n", msg)
return 1
cuesheet.dir = os.path.dirname(cuepath)
if cuesheet.dir:
cuesheet.dir += "/"
switch(options.dump, {
"cue": lambda: print_cue(cuesheet),
"tags": lambda: Splitter(cuesheet, options).dump_tags(),
"tracks": lambda: Splitter(cuesheet, options).dump_tracks(),
None: lambda: Splitter(cuesheet, options).split()
})
return 0
if __name__ == '__main__':
sys.exit(main())
|