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
|
from cchardet import detect as encoding_detect
import codecs
import sys
import re
def sort_iter(d):
def over(d):
for k in sorted(d.keys()):
yield k, d[k]
return iter(over(d))
class Track:
def __init__(self, number, datatype):
try:
self.number = int(number)
except ValueError:
raise InvalidCommand("invalid number \"%s\"" % number)
self.type = datatype
self._indexes = {}
self._attrs = {}
def attrs(self):
return sort_iter(self._attrs)
def indexes(self):
return sort_iter(self._indexes)
def get(self, attr):
return self._attrs.get(attr,
None if attr in ("pregap", "postgap") else ""
)
def isaudio(self):
return self.type == "AUDIO" and self.begin is not None
class File:
def __init__(self, name, filetype):
self.name = name
self.type = filetype
self._tracks = []
def tracks(self, audio_only = False):
return filter(Track.isaudio if audio_only else None, self._tracks)
def add_track(self, track):
self._tracks.append(track)
def isaudio(self):
return self.type == "WAVE"
def has_audio_tracks(self):
return len(self.tracks(Track)) > 0
def split_points(self, info):
rate = info.sample_rate * info.bits_per_sample * info.channels / 8
for track in self.tracks(True)[1:]:
yield rate * track.begin / 75
def __repr__(self):
return self.name
class Cue:
def __init__(self):
self._attrs = {}
self._files = []
def attrs(self):
return sort_iter(self._attrs)
def files(self, audio_only = False):
return filter(File.isaudio if audio_only else None, self._files)
def get(self, attr):
return self._attrs.get(attr, "")
def add_file(self, file):
self._files.append(file)
class CueParserError(Exception):
pass
class UnknownCommand(CueParserError):
pass
class InvalidCommand(CueParserError):
pass
class InvalidContext(CueParserError):
pass
class Context:
(
GENERAL,
TRACK,
FILE
) = range(3)
def check(count = None, context = None):
def deco(func):
def method(cls, *lst):
if count is not None:
n = len(lst)
if n != count:
raise InvalidCommand(
"%d arg%s expected, got %d" %
(count, "s" if count > 1 else "", n)
)
if context is not None:
if type(context) in (list, tuple):
if cls.context not in context:
raise InvalidContext
elif cls.context != context:
raise InvalidContext
func(cls, *lst)
return method
return deco
class CueParser:
re_timestamp = re.compile("^[\d]{1,3}:[\d]{1,2}:[\d]{1,2}$")
rem_commands = ('genre', 'date', 'comment')
def __init__(self):
def do_set_attr(name, cue = False, track = False, convert = None):
def func(*args):
n = len(args)
if n != 1:
raise InvalidCommand("1 arg expected, got %d" % n)
opt = {}
if cue:
opt[Context.GENERAL] = self.cue
if track:
opt[Context.TRACK] = self.track
arg = convert(args[0]) if convert else args[0]
self.set_attr(name, arg, opt)
return func
self.cue = Cue()
self.context = Context.GENERAL
self.track = None
self.file = None
self.commands = {
"file": self.parse_file,
"flags": self.parse_flags,
"index": self.parse_index,
"pregap": self.parse_pregap,
"rem": self.parse_rem,
"track": self.parse_track,
"catalog": do_set_attr("catalog", cue = True),
"performer": do_set_attr("performer", cue = True, track = True),
"postgap": do_set_attr("postgap", track = True, convert = self.parse_timestamp),
"songwriter": do_set_attr("songwriter", cue = True, track = True),
"title": do_set_attr("title", cue = True, track = True),
"cdtextfile": self.parse_skip,
"isrc": self.parse_skip,
}
@staticmethod
def split_args(args):
lst = []
quote = None
cur = []
def push():
lst.append("".join(cur))
cur[:] = []
for ch in args:
if quote:
if ch != quote:
cur.append(ch)
else:
quote = None
elif ch.isspace():
if cur:
push()
elif ch in ("\"", "'"):
quote = ch
else:
cur.append(ch)
if quote:
raise CueParserError("unclosed quote '%s'" % quote)
if cur:
push()
return lst
@staticmethod
def parse_timestamp(time):
if not CueParser.re_timestamp.match(time):
raise InvalidCommand("invalid timestamp \"%s\"" % time)
m, s, f = map(int, time.split(":"))
return (m * 60 + s) * 75 + f
def get_cue(self):
return self.cue
@check(2)
def parse_file(self, *args):
self.file = File(*args)
self.cue.add_file(self.file)
self.context = Context.FILE
@check(2, (Context.FILE, Context.TRACK))
def parse_track(self, *args):
self.track = Track(*args)
self.file.add_track(self.track)
self.context = Context.TRACK
@check(2, Context.TRACK)
def parse_index(self, number, time):
if "postgap" in self.track._attrs:
raise InvalidCommand("after POSTGAP")
try:
number = int(number)
except ValueError:
raise InvalidCommand("invalid number \"%s\"" % number)
if number is 0 and "pregap" in self.track._attrs:
raise InvalidCommand("conflict with previous PREGAP")
if number in self.track._indexes:
raise InvalidCommand("duplicate index number %d" % number)
self.track._indexes[number] = self.parse_timestamp(time)
@check(1, Context.TRACK)
def parse_pregap(self, time):
if self.track._indexes:
raise InvalidCommand("must appear before any INDEX commands for the current track")
self.set_attr("pregap", self.parse_timestamp(time), obj = self.track)
def set_attr(self, attr, value, opt = None, obj = None):
if opt is not None:
obj = opt.get(self.context)
if obj is None:
raise InvalidContext
elif obj is None:
raise CueParserError("CueParserError.set_attr: invalid usage")
if attr in obj._attrs:
raise InvalidCommand("duplicate")
obj._attrs[attr] = value
@check(context = Context.TRACK)
def parse_flags(self, *flags):
if self.track._indexes:
raise InvalidCommand("must appear before any INDEX commands")
def parse_rem(self, opt, value = None, *args):
cmd = opt.lower()
if value and cmd in self.rem_commands:
if len(args):
raise InvalidCommand("extra arguments for \"%s\"" % opt)
self.set_attr(cmd, value, obj = self.cue)
def parse_skip(self, *args):
pass
def parse_default(self, *args):
raise UnknownCommand
def parse(self, cmd, arg):
self.commands.get(cmd.lower(), self.parse_default)(*self.split_args(arg))
def calc_offsets(self):
for file in self.cue._files:
previous = None
for track in file._tracks:
track.begin = None
track.end = None
pregap = track.get("pregap")
if pregap is None and 0 in track._indexes:
pregap = track._indexes[0]
if pregap is not None and previous and previous.end is None:
previous.end = pregap
try:
track.begin = min([v for k, v in track._indexes.items() if k != 0])
except:
continue
if previous and previous.end is None:
previous.end = track.begin if pregap is None else pregap
postgap = track.get("postgap")
if postgap is not None:
track.end = postgap
previous = track
def __read_file(filename):
f = open(filename, "rb")
data = f.read()
f.close()
encoded = None
try:
encoded = data.decode("utf-8-sig")
except UnicodeDecodeError:
pass
if encoded is None:
enc = encoding_detect(data)
if enc is None:
raise Exception("autodetect failed")
encoding = enc["encoding"]
try:
encoded = data.decode(encoding)
except UnicodeDecodeError:
raise Exception("autodetect failed: invalid encoding %s" % encoding)
return encoded
def read_cue(filename, on_error = None):
if on_error:
def msg(fmt, *args):
err = CueParserError(fmt % args)
err.line = nline
on_error(err)
else:
msg = lambda *args: None
cuefile = __read_file(filename)
parser = CueParser()
nline = 0
for line in cuefile.split("\n"):
nline = nline + 1
s = line.strip()
if not len(s):
continue
data = s.split(None, 1)
if len(data) is 1:
msg("invalid command \"%s\": arg missed", data[0])
continue
try:
parser.parse(*data)
except UnknownCommand:
msg("unknown command \"%s\"", data[0])
except InvalidContext:
msg("invalid context for command \"%s\"", data[0])
except InvalidCommand as err:
msg("invalid command \"%s\": %s", data[0], err)
except CueParserError as err:
msg("%s", err)
parser.calc_offsets()
return parser.get_cue()
|