cue2discid: Fix possibly undefined variables
[abcde.git] / examples / cue2discid
1 #!/usr/bin/python
2
3 """Outputs a long-form cddb discid given a cue file as input"""
4
5 import fileinput
6 import re
7
8 FRAMES_PER_SECOND = 75
9 SAMPLES_PER_SECOND = 44100
10 SAMPLES_PER_FRAME = SAMPLES_PER_SECOND // FRAMES_PER_SECOND
11
12 pregap = 0
13 currentTrackFrame = 0
14 pregapRegex = re.compile(r'PREGAP (?P<min>\d+):(?P<sec>\d\d):(?P<frame>\d\d)')
15 startTrackRegex = re.compile(r'INDEX 01 (?P<min>\d+):(?P<sec>\d\d):(?P<frame>\d\d)')
16 leadInRegex = re.compile(r'REM FLAC__lead-in (?P<sample>\d+)')
17 leadOutRegex = re.compile(r'REM FLAC__lead-out 170 (?P<sample>\d+)')
18 raw_framelist = list()
19 leadInFrame = 0
20 leadOutFrame_raw = 0
21 numTracks = 0
22
23 def cddb_sum(trackseconds):
24     def digits(number):
25         tmp = number
26         while tmp:
27             yield tmp % 10
28             tmp = tmp // 10
29
30     return sum(digits(trackseconds))
31
32 for line in fileinput.input():
33     pregapMatch = pregapRegex.search(line)
34     if pregapMatch:
35         pregap = (int((pregapMatch.group('min')) * 60) + int(pregapMatch.group('sec'))) * FRAMES_PER_SECOND + int(pregapMatch.group('frame'))
36         continue
37
38     startTrackMatch = startTrackRegex.search(line)
39     if startTrackMatch:
40         numTracks += 1
41         currentTrackFrame = ((int(startTrackMatch.group('min')) * 60) + int(startTrackMatch.group('sec'))) * FRAMES_PER_SECOND + int(startTrackMatch.group('frame'))
42         raw_framelist.append(currentTrackFrame)
43         continue
44
45     leadInMatch = leadInRegex.search(line)
46     if leadInMatch:
47         leadInFrame = long(leadInMatch.group('sample')) // SAMPLES_PER_FRAME
48         continue
49
50     leadOutMatch = leadOutRegex.search(line)
51     if leadOutMatch:
52         leadOutFrame_raw = long(leadOutMatch.group('sample')) // SAMPLES_PER_FRAME
53         continue
54
55 leadOutFrame = leadOutFrame_raw + leadInFrame
56
57 framelist = [i + leadInFrame + pregap for i in raw_framelist]
58
59 secondslist = [i//FRAMES_PER_SECOND for i in framelist]
60
61 n = long(sum(map(cddb_sum, secondslist)))
62 t = leadOutFrame/FRAMES_PER_SECOND - framelist[0]/FRAMES_PER_SECOND
63 print "%08x" % (((n % 0xff) << 24) | (t << 8) | numTracks), numTracks, 
64 print " ".join([str(i) for i in framelist]), leadOutFrame/FRAMES_PER_SECOND