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