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