]> code.delx.au - transcoding/blob - encode.py
A few tweaks to options
[transcoding] / encode.py
1 #!/usr/bin/env python
2
3 from functools import partial
4 import optparse
5 import re
6 import subprocess
7 import sys
8 import os
9 import shutil
10 import tempfile
11
12 class FatalException(Exception):
13 pass
14
15 def mkarg(arg):
16 if re.match("^[a-zA-Z0-9\-\\.,/@_:=]*$", arg):
17 return arg
18
19 if "'" not in arg:
20 return "'%s'" % arg
21 out = "\""
22 for c in arg:
23 if c in "\\$\"`":
24 out += "\\"
25 out += c
26 out += "\""
27 return out
28
29 def midentify(source, field):
30 process = subprocess.Popen(
31 [
32 "mplayer", source,
33 "-ao", "null", "-vo", "null",
34 "-frames", "0", "-identify",
35 ],
36 stdout=subprocess.PIPE,
37 stderr=subprocess.PIPE,
38 )
39 for line in process.stdout:
40 try:
41 key, value = line.split("=")
42 except ValueError:
43 continue
44 if key == field:
45 return value.strip()
46
47 def append_cmd(cmd, opt, var):
48 if var is not None:
49 cmd.append(opt)
50 cmd.append(str(var))
51
52 def duplicate_opts(opts):
53 return optparse.Values(opts.__dict__)
54
55 def insert_mplayer_options(cmd, o):
56 do_opt = partial(append_cmd, cmd)
57
58 if o.deinterlace:
59 cmd += ["-vf-pre", "yadif"]
60 if o.noskip:
61 cmd += ["-noskip"]
62 if o.skipkb:
63 cmd += ["-sb", str(o.skipkb * 1024)]
64
65 do_opt("-mc", o.mc)
66 do_opt("-fps", o.ifps)
67 do_opt("-ss", o.startpos)
68 do_opt("-endpos", o.endpos)
69 do_opt("-dvd-device", o.dvd)
70 do_opt("-chapter", o.chapter)
71 do_opt("-aid", o.audioid)
72 do_opt("-sid", o.subtitleid)
73 do_opt("-vf", o.vfilters)
74 do_opt("-af-add", o.afilters)
75
76
77 class Command(object):
78 def __init__(self, profile, opts):
79 self.profile = profile
80 self.opts = opts
81 self.__process = None
82 self.init()
83
84 def init(self):
85 pass
86
87 def check_command(self, cmd):
88 if self.opts.dump:
89 return
90 if subprocess.Popen(["which", cmd], stdout=open("/dev/null", "w")).wait() != 0:
91 raise FatalException("Command '%s' is required" % cmd)
92
93 def check_no_file(self, path):
94 if os.path.exists(path):
95 raise FatalException("Output file '%s' exists." % path)
96
97 def do_exec(self, args, wait=True):
98 if self.opts.dump:
99 print " ".join(map(mkarg, args))
100 else:
101 self.__process = subprocess.Popen(args)
102 self.__args = args
103 if wait:
104 self.wait()
105
106 def wait(self):
107 if self.__process == None:
108 return
109 if self.__process.wait() != 0:
110 raise FatalException("Failure executing command: %s" % self.__args)
111 self.__process = None
112
113
114 class MP4Box(Command):
115 def init(self):
116 self.check_command("MP4Box")
117 self.check_no_file(self.opts.output + ".mp4")
118
119 def run(self):
120 o = self.opts
121 p = self.profile
122
123 if o.dump:
124 fps = "???"
125 else:
126 fps = midentify(p.video_tmp, "ID_VIDEO_FPS")
127
128 self.do_exec([
129 "MP4Box",
130 "-fps", fps,
131 "-add", p.video_tmp,
132 "-add", p.audio_tmp,
133 o.output + ".mp4"
134 ])
135
136
137
138 class MKVMerge(Command):
139 def init(self):
140 self.check_command("mkvmerge")
141 self.check_no_file(self.opts.output + ".mkv")
142
143 def run(self):
144 o = self.opts
145 p = self.profile
146
147 if o.dump:
148 fps = "???"
149 else:
150 fps = midentify(p.video_tmp, "ID_VIDEO_FPS")
151
152 self.do_exec([
153 "mkvmerge",
154 "-o", o.output + ".mkv",
155 "--default-duration", "0:%sfps"%fps,
156 p.video_tmp,
157 p.audio_tmp,
158 ])
159
160
161
162 class MencoderFixRemux(Command):
163 def init(self):
164 self.check_command("mencoder")
165 self.check_no_file("remux.avi")
166
167 orig = self.opts
168 self.opts = duplicate_opts(orig)
169 orig.input = "remux.avi"
170 orig.dvd = orig.chapter = orig.startpos = orig.endpos = None
171
172 def run(self):
173 o = self.opts
174 cmd = [
175 "mencoder",
176 "-o", "remux.avi",
177 "-oac", "copy", "-ovc", "copy",
178 "-mc", "0.1",
179 o.input,
180 ]
181 do_opt = partial(append_cmd, cmd)
182 do_opt("-dvd-device", o.dvd)
183 do_opt("-chapter", o.chapter)
184 do_opt("-ss", o.startpos)
185 do_opt("-endpos", o.endpos)
186 self.do_exec(cmd)
187
188
189
190
191
192 class MPlayer(Command):
193 def init(self):
194 self.check_command("mplayer")
195 self.check_no_file("video.y4m")
196 self.check_no_file("audio.wav")
197
198 def run(self):
199 os.mkfifo("video.y4m")
200 os.mkfifo("audio.wav")
201 cmd = []
202 cmd += ["mplayer", self.opts.input]
203 cmd += ["-benchmark", "-noconsolecontrols", "-noconfig", "all"]
204 cmd += ["-vo", "yuv4mpeg:file=video.y4m"]
205 cmd += ["-ao", "pcm:waveheader:file=audio.wav"]
206 insert_mplayer_options(cmd, self.opts)
207 cmd += self.profile.mplayeropts
208 self.do_exec(cmd, wait=False)
209
210
211 class MencoderCopyAC3(Command):
212 def init(self):
213 self.check_command("mplayer")
214 self.check_no_file("audio.ac3")
215 self.profile.audio_tmp = "audio.ac3"
216
217 def run(self):
218 cmd = []
219 cmd += ["mencoder", self.opts.input]
220 cmd += ["-noconfig", "all"]
221 cmd += ["-ovc", "copy", "-oac", "copy"]
222 cmd += ["-of", "rawaudio", "-o", "audio.ac3"]
223 insert_mplayer_options(cmd, self.opts)
224 self.do_exec(cmd)
225
226
227 class X264(Command):
228 def init(self):
229 self.check_command("x264")
230 self.profile.video_tmp = "video.h264"
231
232 def run(self):
233 p = self.profile
234 cmd = []
235 cmd += ["x264", "--no-progress"]
236 cmd += p.x264opts
237 cmd += ["-o", p.video_tmp]
238 cmd += ["video.y4m"]
239 self.do_exec(cmd, wait=False)
240
241
242 class Lame(Command):
243 def init(self):
244 self.check_command("lame")
245 self.profile.audio_tmp = "audio.mp3"
246
247 def run(self):
248 p = self.profile
249 cmd = []
250 cmd += ["lame", "--quiet"]
251 cmd += p.lameopts
252 cmd += ["audio.wav"]
253 cmd += [p.audio_tmp]
254 self.do_exec(cmd, wait=False)
255
256
257 class Faac(Command):
258 def init(self):
259 self.check_command("faac")
260 self.profile.audio_tmp = "audio.aac"
261
262 def run(self):
263 p = self.profile
264 cmd = []
265 cmd += ["faac"]
266 cmd += ["-o", p.audio_tmp]
267 cmd += p.faacopts
268 cmd += ["audio.wav"]
269 self.do_exec(cmd, wait=False)
270
271
272 class Mencoder(Command):
273 codec2opts = {
274 "xvid": "-xvidencopts",
275 "x264": "-x264encopts",
276 "faac": "-faacopts",
277 "mp3lame": "-lameopts",
278 }
279
280 def init(self):
281 o = self.opts
282 p = self.profile
283
284 self.check_command("mencoder")
285 self.check_no_file(o.output + ".avi")
286
287 p.video_tmp = o.output + ".avi"
288 p.audio_tmp = o.output + ".avi"
289
290 def run(self):
291 o = self.opts
292 p = self.profile
293
294 cmd = []
295 cmd += ["mencoder", o.input]
296 cmd += ["-noconfig", "all"]
297 insert_mplayer_options(cmd, o)
298 cmd += ["-vf-add", "harddup"]
299 cmd += ["-ovc", p.vcodec, self.codec2opts[p.vcodec], p.vopts]
300 cmd += ["-oac", p.acodec]
301 if p.aopts:
302 cmd += [self.codec2opts[p.acodec], p.aopts]
303 cmd += self.profile.mplayeropts
304 cmd += ["-o", self.opts.output + ".avi"]
305
306 self.do_exec(cmd)
307
308
309 class MencoderDemux(Command):
310 codec2exts = {
311 "xvid": "m4v",
312 "x264": "h264",
313 "faac": "aac",
314 "mp3lame": "mp3",
315 "copyac3": "ac3",
316 }
317
318 def init(self):
319 o = self.opts
320 p = self.profile
321
322 self.check_command("mencoder")
323 p.audio_tmp = "audio." + self.codec2exts[p.acodec]
324 p.video_tmp = "video." + self.codec2exts[p.vcodec]
325 self.check_no_file(p.audio_tmp)
326 self.check_no_file(p.video_tmp)
327
328 def run(self):
329 o = self.opts
330 p = self.profile
331
332 cmd = ["mencoder", "-ovc", "copy", "-oac", "copy", o.output + ".avi"]
333 cmd += ["-noconfig", "all", "-noskip", "-mc", "0"]
334 self.do_exec(cmd + ["-of", "rawaudio", "-o", p.audio_tmp])
335 self.do_exec(cmd + ["-of", "rawvideo", "-o", p.video_tmp])
336 self.do_exec(["rm", "-f", o.output + ".avi"])
337
338
339
340 class Profile(object):
341 def __init__(self, commands, **kwargs):
342 self.commands = commands
343 self.__dict__.update(kwargs)
344
345 def __contains__(self, keyname):
346 return hasattr(self, keyname)
347
348 class Wait(object):
349 def __init__(self, commands):
350 self.commands = commands[:]
351
352 def run(self):
353 for command in self.commands:
354 command.wait()
355
356
357
358 profiles = {
359 "x264/lame" :
360 Profile(
361 commands=[MPlayer, X264, Lame, Wait, MKVMerge],
362 mplayeropts=[],
363 x264opts=["--preset", "veryslow", "--crf", "20"],
364 lameopts=["--preset", "medium"],
365 ),
366
367 "x264/copyac3" :
368 Profile(
369 commands=[MPlayer, X264, Wait, MencoderCopyAC3, MKVMerge],
370 mplayeropts=["-nosound"],
371 x264opts=["--preset", "veryslow", "--crf", "20"],
372 lameopts=["--preset", "medium"],
373 ),
374
375 "xvid/lame" :
376 Profile(
377 commands=[Mencoder],
378 mplayeropts=["-ffourcc", "DX50"],
379 vcodec="xvid",
380 vopts="fixed_quant=2:vhq=4:autoaspect",
381 acodec="mp3lame",
382 aopts="cbr:br=128",
383 ),
384
385 "apple-quicktime" :
386 Profile(
387 commands=[MPlayer, X264, Faac, Wait, MP4Box],
388 mplayeropts=[],
389 x264opts=["--crf", "20", "--bframes", "1"],
390 faacopts=["-q", "100", "--mpeg-vers", "4"],
391 ),
392
393 "nokia-n97" :
394 Profile(
395 commands=[Mencoder, MencoderDemux, MP4Box],
396 mplayeropts=["-vf-add", "scale=640:-10"],
397 vcodec="xvid",
398 vopts="bitrate=384:vhq=4:autoaspect:max_bframes=0",
399 acodec="faac",
400 aopts="br=64:mpeg=4:object=2",
401 ),
402 }
403
404 mappings = {
405 "x264": "x264/lame",
406 "xvid": "xvid/lame",
407 }
408 for x, y in mappings.iteritems():
409 profiles[x] = profiles[y]
410
411
412
413
414 def parse_args():
415 for profile_name in profiles.keys():
416 if sys.argv[0].find(profile_name) >= 0:
417 break
418 else:
419 profile_name = "xvid/lame"
420
421 parser = optparse.OptionParser(usage="%prog [options] input [output]")
422 parser.add_option("--dvd", action="store", dest="dvd")
423 parser.add_option("--deinterlace", action="store_true", dest="deinterlace")
424 parser.add_option("--fixmux", action="store_true", dest="fixmux")
425 parser.add_option("--mc", action="store", dest="mc", type="int")
426 parser.add_option("--noskip", action="store_true", dest="noskip")
427 parser.add_option("--vfilters", action="store", dest="vfilters")
428 parser.add_option("--afilters", action="store", dest="afilters")
429 parser.add_option("--chapter", action="store", dest="chapter")
430 parser.add_option("--ifps", action="store", dest="ifps")
431 parser.add_option("--skipkb", action="store", dest="skipkb", type="int")
432 parser.add_option("--startpos", action="store", dest="startpos")
433 parser.add_option("--endpos", action="store", dest="endpos")
434 parser.add_option("--audioid", action="store", dest="audioid")
435 parser.add_option("--subtitleid", action="store", dest="subtitleid")
436 parser.add_option("--profile", action="store", dest="profile_name", default=profile_name)
437 parser.add_option("--dump", action="store_true", dest="dump")
438 try:
439 opts, args = parser.parse_args(sys.argv[1:])
440 if len(args) == 1:
441 input = args[0]
442 output = os.path.splitext(os.path.basename(input))[0]
443 elif len(args) == 2:
444 input, output = args
445 else:
446 raise ValueError
447 except Exception:
448 parser.print_usage()
449 sys.exit(1)
450
451 if "://" not in input:
452 opts.input = os.path.abspath(input)
453 else:
454 if opts.dvd:
455 opts.dvd = os.path.abspath(opts.dvd)
456 opts.input = input
457
458 opts.output = os.path.abspath(output)
459
460 return opts
461
462 def main():
463 os.nice(1)
464
465 opts = parse_args()
466
467 # Find our profile
468 try:
469 profile = profiles[opts.profile_name]
470 except KeyError:
471 print >>sys.stderr, "Profile '%s' not found!" % opts.profile_name
472 sys.exit(1)
473
474 # Run in a temp dir so that multiple instances can be run simultaneously
475 tempdir = tempfile.mkdtemp()
476 try:
477 os.chdir(tempdir)
478
479 try:
480 commands = []
481 if opts.fixmux:
482 profile.commands.insert(0, MencoderFixRemux)
483 for CommandClass in profile.commands:
484 if Command in CommandClass.__bases__:
485 command = CommandClass(profile, opts)
486 else:
487 command = CommandClass(commands)
488 commands.append(command)
489 for command in commands:
490 command.run()
491
492 except FatalException, e:
493 print >>sys.stderr, "Error:", str(e)
494 sys.exit(1)
495
496 finally:
497 os.chdir("/")
498 shutil.rmtree(tempdir)
499
500 if __name__ == "__main__":
501 main()
502