1 #! /usr/bin/env python2.4
6 B<flac2mp3> - transcode FLAC file to MP3 files
10 B<flac2mp3> [B<--lame-options> I<lame-options>] [B<-j> I<jobs>] [B<-q>] [B<-v>] I<file> [...]
14 B<flac2mp3> transcodes the FLAC files I<file> to MP3 files. I<file>
15 may be the kind of FLAC file B<fa-flacd> generates. That is, it
16 contains a cue sheet, one TITLE tag per track listed therein, and
17 ARTIST, ALBUM, and DATE tags.
23 =item B<--lame-options> I<lame-options>
25 Pass I<lame-options> to B<lame>. This ends up being passed to the
26 shell, so feel free to take advantage of that. You'll almost
27 certainly have to put I<lame-options> in single quotes.
29 =item B<-j> [B<--jobs>] I<jobs>
31 Run up to I<jobs> jobs instead of the default 1.
33 =item B<-q> [B<--quiet>]
35 Suppress status information. This option is passed along to B<flac>
38 =item B<-v> [B<--verbose>]
40 Print diagnostic information. This option is passed along to B<flac>
47 Written by Eric Gillespie <epg@pretzelnet.org>.
51 ''' #' # python-mode is sucks
53 import re, sys, traceback
54 from optparse import OptionParser
55 from subprocess import Popen, PIPE
57 import org.diplodocus.jobs
58 from org.diplodocus.util import run_or_die
60 ################################################################################
63 def flac2mp3(fn, title, artist, album, date, track, skip_until):
64 (title, artist, album, date) = [(x == None and 'unknown') or x
65 for x in (title, artist, album, date)]
67 (skip_arg, until_arg) = skip_until
69 skip_arg = until_arg = ''
72 flac_options = '--silent'
78 if lame_options != None:
79 tmp.append(lame_options)
81 tmp.append('--preset standard');
82 quiet and tmp.append('--quiet')
83 verbose and tmp.append('--verbose')
84 lame_options = ' '.join(tmp)
86 # Escape any single quotes ' so we can quote this.
88 album, date) = [x.replace("'", r"'\''")
89 for x in (fn, title, artist, album, date)]
91 outfile = ('%s (%s) %02d %s.mp3' % (artist, album,
92 track, title)).replace('/', '_')
94 run_or_die(3, "flac %s -cd %s %s '%s' | lame %s --tt '%s' --ta '%s' --tl '%s' --ty '%s' --tn %d - '%s'"
95 % (flac_options, skip_arg or '', until_arg or '', fn,
96 lame_options, title, artist, album, date, track, outfile))
100 ################################################################################
103 def tformat(m, s, c):
104 return '%02d:%02d.%02d' % (m, s, c)
106 def get_decode_args(fn):
109 p = Popen(['metaflac', '--export-cuesheet-to=-', fn], stdout=PIPE)
110 for line in (x.rstrip() for x in p.stdout):
111 m = re.search(r'INDEX 01 (\d\d):(\d\d):(\d\d)$', line)
113 l.append(map(int, m.groups()))
115 # XXX dataloss! check status
118 for i in xrange(len(l)):
119 arg = ['--skip=' + tformat(*l[i])]
127 arg.append('--until=' + tformat(next[0] - 1, 59, 74))
129 arg.append('--until=' + tformat(next[0], next[1] - 1,
132 arg.append('--until=' + tformat(next[0], next[1],
137 # If no cue sheet, stick a dummy in here.
143 # XXX other things should usue this; flac files, for example, should
144 # get PART as part of the filelname, same as mp3s.
149 return len(self._tags)
150 def get(self, key, track=None):
154 return self._tags[None][key]
156 return self._tags[track][key]
158 return self._tags[None][key]
161 def gets(self, key, track=None):
162 value = self.get(key, track)
165 return '\n'.join(value)
166 def set(self, key, value, track=None):
167 if track not in self._tags:
168 self._tags[track] = {}
169 if key not in self._tags[track]:
170 self._tags[track][key] = []
171 self._tags[track][key].append(value)
174 '''Return the ARTIST, ALBUM, and DATE tags followed by the TITLE tags
179 p = Popen(['metaflac', '--export-vc-to=-', fn], stdout=PIPE)
180 for line in (x.rstrip() for x in p.stdout):
181 (tag, value) = line.split('=', 1)
183 m = re.search(r'\[([0-9]+)]$', tag)
185 tag = tag[:m.start()]
186 track = int(m.group(1))
190 tags.set(tag, value, track)
191 # XXX dataloss! check status
197 # Control the exit code for any uncaught exceptions.
199 parser = OptionParser()
200 parser.disable_interspersed_args()
201 parser.add_option('-X', '--debug', action='store_true', default=False)
202 parser.add_option('-j', '--jobs', type='int', default=1)
203 parser.add_option('--lame-options')
204 parser.add_option('-q', '--quiet', action='store_true', default=False)
205 parser.add_option('-v', '--verbose', action='store_true', default=False)
207 traceback.print_exc()
211 # Raises SystemExit on invalid options in argv.
212 (options, args) = parser.parse_args(argv[1:])
213 except Exception, error:
214 if isinstance(error, SystemExit):
216 traceback.print_exc()
220 global debug, flac_options, lame_options, quiet, verbose
221 debug = options.debug
222 lame_options = options.lame_options
223 quiet = options.quiet
224 verbose = options.verbose
229 args = get_decode_args(fn)
232 album = tags.gets('ALBUM')
233 discnum = tags.gets('DISCNUMBER')
234 track = tags.gets('TRACKNUMBER')
236 # lame doesn't seem to support disc number.
238 album = '%s (disc %s)' % (album, discnum)
240 # Stupid hack: only a single-track file should have the
241 # TRACKNUMBER tag, so use it if set for the first pass through
242 # the loop. At the end of the loop, we'll set $track for the
243 # next run, so this continues to work for multi-track files.
249 for i in range(len(tags)):
250 title = tags.gets('TITLE', track)
251 part = tags.gets('PART', track)
253 title = '%s - %s' % (title, part)
254 jobs.append([fn, title,
255 tags.gets('ARTIST', track),
257 tags.gets('DATE', track),
260 except Exception, error:
261 sys.stderr.write(getattr(error, 'msg', ''))
262 traceback.print_exc()
263 sys.stderr.write('Continuing...\n')
270 return lambda: flac2mp3(*job)
271 org.diplodocus.jobs.run(maxjobs=options.jobs, debug=debug, get_job=getjob)
272 except Exception, error:
273 if isinstance(error, SystemExit):
275 # check all print_exc and format_exc in fa-flacd.py; i think
276 # for some i don't do this msg print check
277 sys.stderr.write(getattr(error, 'msg', ''))
278 traceback.print_exc()
283 if __name__ == '__main__':
284 sys.exit(main(sys.argv))