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