dts not tivo compatible
[pyTivo.git] / plugins / video / transcode.py
blob72052944d55c392e8063f798c4d13a00c726e5d9
1 import subprocess, shutil, os, re, sys, ConfigParser, time, lrucache
2 import config
3 from debug import debug_write, fn_attr
5 info_cache = lrucache.LRUCache(1000)
6 videotest = os.path.join(os.path.dirname(__file__), 'videotest.mpg')
8 def ffmpeg_path():
9 return config.get('Server', 'ffmpeg')
11 # XXX BIG HACK
12 # subprocess is broken for me on windows so super hack
13 def patchSubprocess():
14 o = subprocess.Popen._make_inheritable
16 def _make_inheritable(self, handle):
17 if not handle: return subprocess.GetCurrentProcess()
18 return o(self, handle)
20 subprocess.Popen._make_inheritable = _make_inheritable
21 mswindows = (sys.platform == "win32")
22 if mswindows:
23 patchSubprocess()
25 def output_video(inFile, outFile, tsn=''):
26 if tivo_compatable(inFile, tsn):
27 debug_write(__name__, fn_attr(), [inFile, ' is tivo compatible'])
28 f = file(inFile, 'rb')
29 shutil.copyfileobj(f, outFile)
30 f.close()
31 else:
32 debug_write(__name__, fn_attr(), [inFile, ' is not tivo compatible'])
33 transcode(inFile, outFile, tsn)
35 def transcode(inFile, outFile, tsn=''):
37 settings = {}
38 settings['video_codec'] = select_videocodec(tsn)
39 settings['video_br'] = select_videobr(tsn)
40 settings['video_fps'] = select_videofps(tsn)
41 settings['max_video_br'] = select_maxvideobr()
42 settings['buff_size'] = select_buffsize()
43 settings['aspect_ratio'] = ' '.join(select_aspect(inFile, tsn))
44 settings['audio_br'] = select_audiobr(tsn)
45 settings['audio_fr'] = select_audiofr(inFile, tsn)
46 settings['audio_ch'] = select_audioch(tsn)
47 settings['audio_codec'] = select_audiocodec(inFile, tsn)
48 settings['ffmpeg_pram'] = select_ffmpegprams(tsn)
49 settings['format'] = select_format(tsn)
51 cmd_string = config.getFFmpegTemplate(tsn) % settings
53 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
54 print 'transcoding to tivo model '+tsn[:3]+' using ffmpeg command:'
55 print ' '.join(cmd)
56 debug_write(__name__, fn_attr(), ['ffmpeg command is ', ' '.join(cmd)])
57 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
58 try:
59 shutil.copyfileobj(ffmpeg.stdout, outFile)
60 except:
61 kill(ffmpeg.pid)
63 def select_audiocodec(inFile, tsn = ''):
64 # Default, compatible with all TiVo's
65 codec = 'ac3'
66 if config.getAudioCodec(tsn) == None:
67 type, width, height, fps, millisecs, kbps, akbps, acodec, afreq = video_info(inFile)
68 if acodec in ('ac3', 'liba52', 'mp2'):
69 if akbps == None:
70 cmd_string = '-y -vcodec mpeg2video -r 29.97 -b 1000k -acodec copy -t 00:00:01 -f vob -'
71 if video_check(inFile, cmd_string):
72 type, width, height, fps, millisecs, kbps, akbps, acodec, afreq = video_info(videotest)
73 if not akbps == None and int(akbps) <= config.getMaxAudioBR(tsn):
74 # compatible codec and bitrate, do not reencode audio
75 codec = 'copy'
76 else:
77 codec = config.getAudioCodec(tsn)
78 return '-acodec '+codec
80 def select_audiofr(inFile, tsn):
81 freq = '48000' #default
82 type, width, height, fps, millisecs, kbps, akbps, acodec, afreq = video_info(inFile)
83 if not afreq == None and afreq in ('44100', '48000'):
84 # compatible frequency
85 freq = afreq
86 if config.getAudioFR(tsn) != None:
87 freq = config.getAudioFR(tsn)
88 return '-ar '+freq
90 def select_audioch(tsn):
91 if config.getAudioCH(tsn) != None:
92 return '-ac '+config.getAudioCH(tsn)
93 return ''
95 def select_videofps(tsn):
96 vfps = '-r 29.97' #default
97 if config.isHDtivo(tsn):
98 vfps = ' '
99 if config.getVideoFPS(tsn) != None:
100 vfps = '-r '+config.getVideoFPS(tsn)
101 return vfps
103 def select_videocodec(tsn):
104 vcodec = 'mpeg2video' #default
105 if config.getVideoCodec(tsn) != None:
106 vcodec = config.getVideoCodec(tsn)
107 return '-vcodec '+vcodec
109 def select_videobr(tsn):
110 return '-b '+config.getVideoBR(tsn)
112 def select_audiobr(tsn):
113 return '-ab '+config.getAudioBR(tsn)
115 def select_maxvideobr():
116 return '-maxrate '+config.getMaxVideoBR()
118 def select_buffsize():
119 return '-bufsize '+config.getBuffSize()
121 def select_ffmpegprams(tsn):
122 if config.getFFmpegPrams(tsn) != None:
123 return config.getFFmpegPrams(tsn)
124 return ''
126 def select_format(tsn):
127 fmt = 'vob'
128 if config.getFormat(tsn) != None:
129 fmt = config.getFormat(tsn)
130 return '-f '+fmt+' -'
132 def select_aspect(inFile, tsn = ''):
133 TIVO_WIDTH = config.getTivoWidth(tsn)
134 TIVO_HEIGHT = config.getTivoHeight(tsn)
136 type, width, height, fps, millisecs, kbps, akbps, acodec, afreq = video_info(inFile)
138 debug_write(__name__, fn_attr(), ['tsn:', tsn])
140 aspect169 = config.get169Setting(tsn)
142 debug_write(__name__, fn_attr(), ['aspect169:', aspect169])
144 optres = config.getOptres(tsn)
146 debug_write(__name__, fn_attr(), ['optres:', optres])
148 if optres:
149 optHeight = config.nearestTivoHeight(height)
150 optWidth = config.nearestTivoWidth(width)
151 if optHeight < TIVO_HEIGHT:
152 TIVO_HEIGHT = optHeight
153 if optWidth < TIVO_WIDTH:
154 TIVO_WIDTH = optWidth
156 d = gcd(height,width)
157 ratio = (width*100)/height
158 rheight, rwidth = height/d, width/d
160 debug_write(__name__, fn_attr(), ['File=', inFile, ' Type=', type, ' width=', width, ' height=', height, ' fps=', fps, ' millisecs=', millisecs, ' ratio=', ratio, ' rheight=', rheight, ' rwidth=', rwidth, ' TIVO_HEIGHT=', TIVO_HEIGHT, 'TIVO_WIDTH=', TIVO_WIDTH])
162 multiplier16by9 = (16.0 * TIVO_HEIGHT) / (9.0 * TIVO_WIDTH)
163 multiplier4by3 = (4.0 * TIVO_HEIGHT) / (3.0 * TIVO_WIDTH)
165 if config.isHDtivo(tsn) and height <= TIVO_HEIGHT and not optres:
166 return [] #pass all resolutions to S3/HD, except heights greater than conf height
167 # else, optres is enabled and resizes SD video to the "S2" standard on S3/HD.
168 elif (rwidth, rheight) in [(4, 3), (10, 11), (15, 11), (59, 54), (59, 72), (59, 36), (59, 54)]:
169 debug_write(__name__, fn_attr(), ['File is within 4:3 list.'])
170 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
171 elif ((rwidth, rheight) in [(16, 9), (20, 11), (40, 33), (118, 81), (59, 27)]) and aspect169:
172 debug_write(__name__, fn_attr(), ['File is within 16:9 list and 16:9 allowed.'])
173 return ['-aspect', '16:9', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
174 else:
175 settings = []
176 #If video is wider than 4:3 add top and bottom padding
177 if (ratio > 133): #Might be 16:9 file, or just need padding on top and bottom
178 if aspect169 and (ratio > 135): #If file would fall in 4:3 assume it is supposed to be 4:3
179 if (ratio > 177):#too short needs padding top and bottom
180 endHeight = int(((TIVO_WIDTH*height)/width) * multiplier16by9)
181 settings.append('-aspect')
182 settings.append('16:9')
183 if endHeight % 2:
184 endHeight -= 1
185 if endHeight < TIVO_HEIGHT * 0.99:
186 settings.append('-s')
187 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
189 topPadding = ((TIVO_HEIGHT - endHeight)/2)
190 if topPadding % 2:
191 topPadding -= 1
193 settings.append('-padtop')
194 settings.append(str(topPadding))
195 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
196 settings.append('-padbottom')
197 settings.append(str(bottomPadding))
198 else: #if only very small amount of padding needed, then just stretch it
199 settings.append('-s')
200 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
201 debug_write(__name__, fn_attr(), ['16:9 aspect allowed, file is wider than 16:9 padding top and bottom', ' '.join(settings)])
202 else: #too skinny needs padding on left and right.
203 endWidth = int((TIVO_HEIGHT*width)/(height*multiplier16by9))
204 settings.append('-aspect')
205 settings.append('16:9')
206 if endWidth % 2:
207 endWidth -= 1
208 if endWidth < (TIVO_WIDTH-10):
209 settings.append('-s')
210 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
212 leftPadding = ((TIVO_WIDTH - endWidth)/2)
213 if leftPadding % 2:
214 leftPadding -= 1
216 settings.append('-padleft')
217 settings.append(str(leftPadding))
218 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
219 settings.append('-padright')
220 settings.append(str(rightPadding))
221 else: #if only very small amount of padding needed, then just stretch it
222 settings.append('-s')
223 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
224 debug_write(__name__, fn_attr(), ['16:9 aspect allowed, file is narrower than 16:9 padding left and right\n', ' '.join(settings)])
225 else: #this is a 4:3 file or 16:9 output not allowed
226 settings.append('-aspect')
227 settings.append('4:3')
228 endHeight = int(((TIVO_WIDTH*height)/width) * multiplier4by3)
229 if endHeight % 2:
230 endHeight -= 1
231 if endHeight < TIVO_HEIGHT * 0.99:
232 settings.append('-s')
233 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
235 topPadding = ((TIVO_HEIGHT - endHeight)/2)
236 if topPadding % 2:
237 topPadding -= 1
239 settings.append('-padtop')
240 settings.append(str(topPadding))
241 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
242 settings.append('-padbottom')
243 settings.append(str(bottomPadding))
244 else: #if only very small amount of padding needed, then just stretch it
245 settings.append('-s')
246 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
247 debug_write(__name__, fn_attr(), ['File is wider than 4:3 padding top and bottom\n', ' '.join(settings)])
249 return settings
250 #If video is taller than 4:3 add left and right padding, this is rare. All of these files will always be sent in
251 #an aspect ratio of 4:3 since they are so narrow.
252 else:
253 endWidth = int((TIVO_HEIGHT*width)/(height*multiplier4by3))
254 settings.append('-aspect')
255 settings.append('4:3')
256 if endWidth % 2:
257 endWidth -= 1
258 if endWidth < (TIVO_WIDTH * 0.99):
259 settings.append('-s')
260 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
262 leftPadding = ((TIVO_WIDTH - endWidth)/2)
263 if leftPadding % 2:
264 leftPadding -= 1
266 settings.append('-padleft')
267 settings.append(str(leftPadding))
268 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
269 settings.append('-padright')
270 settings.append(str(rightPadding))
271 else: #if only very small amount of padding needed, then just stretch it
272 settings.append('-s')
273 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
275 debug_write(__name__, fn_attr(), ['File is taller than 4:3 padding left and right\n', ' '.join(settings)])
277 return settings
279 def tivo_compatable(inFile, tsn = ''):
280 supportedModes = [[720, 480], [704, 480], [544, 480], [480, 480], [352, 480]]
281 type, width, height, fps, millisecs, kbps, akbps, acodec, afreq = video_info(inFile)
282 #print type, width, height, fps, millisecs, kbps, akbps, acodec
284 if (inFile[-5:]).lower() == '.tivo':
285 debug_write(__name__, fn_attr(), ['TRUE, ends with .tivo.', inFile])
286 return True
288 if not type == 'mpeg2video':
289 #print 'Not Tivo Codec'
290 debug_write(__name__, fn_attr(), ['FALSE, type', type, 'not mpeg2video.', inFile])
291 return False
293 if (inFile[-3:]).lower() == '.ts':
294 debug_write(__name__, fn_attr(), ['FALSE, transport stream not supported.', inFile])
295 return False
297 if acodec == 'dca':
298 debug_write(__name__, fn_attr(), ['FALSE, acodec', acodec, ', not supported.', inFile])
299 return False
301 if not akbps or int(akbps) > config.getMaxAudioBR(tsn):
302 debug_write(__name__, fn_attr(), ['FALSE,', akbps, 'kbps exceeds max audio bitrate.', inFile])
303 return False
305 if not kbps or int(kbps)-int(akbps) > config.strtod(config.getMaxVideoBR())/1000:
306 debug_write(__name__, fn_attr(), ['FALSE,', kbps, 'kbps exceeds max video bitrate.', inFile])
307 return False
309 if config.isHDtivo(tsn):
310 debug_write(__name__, fn_attr(), ['TRUE, HD Tivo detected, skipping remaining tests', inFile])
311 return True
313 if not fps == '29.97':
314 #print 'Not Tivo fps'
315 debug_write(__name__, fn_attr(), ['FALSE,', fps, 'fps, should be 29.97.', inFile])
316 return False
318 for mode in supportedModes:
319 if (mode[0], mode[1]) == (width, height):
320 #print 'Is TiVo!'
321 debug_write(__name__, fn_attr(), ['TRUE,', width, 'x', height, 'is valid.', inFile])
322 return True
323 #print 'Not Tivo dimensions'
324 debug_write(__name__, fn_attr(), ['FALSE,', width, 'x', height, 'not in supported modes.', inFile])
325 return False
327 def video_info(inFile):
328 mtime = os.stat(inFile).st_mtime
329 if inFile != videotest:
330 if inFile in info_cache and info_cache[inFile][0] == mtime:
331 debug_write(__name__, fn_attr(), ['CACHE HIT!', inFile])
332 return info_cache[inFile][1]
334 if (inFile[-5:]).lower() == '.tivo':
335 info_cache[inFile] = (mtime, (True, True, True, True, True, True, True, True, True))
336 debug_write(__name__, fn_attr(), ['VALID, ends in .tivo.', inFile])
337 return True, True, True, True, True, True, True, True, True
339 cmd = [ffmpeg_path(), '-i', inFile ]
340 ffmpeg = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
342 # wait 10 sec if ffmpeg is not back give up
343 for i in xrange(200):
344 time.sleep(.05)
345 if not ffmpeg.poll() == None:
346 break
348 if ffmpeg.poll() == None:
349 kill(ffmpeg.pid)
350 info_cache[inFile] = (mtime, (None, None, None, None, None, None, None, None, None))
351 return None, None, None, None, None, None, None, None, None
353 output = ffmpeg.stderr.read()
354 debug_write(__name__, fn_attr(), ['ffmpeg output=', output])
356 rezre = re.compile(r'.*Video: ([^,]+),.*')
357 x = rezre.search(output)
358 if x:
359 codec = x.group(1)
360 else:
361 info_cache[inFile] = (mtime, (None, None, None, None, None, None, None, None, None))
362 debug_write(__name__, fn_attr(), ['failed at video codec'])
363 return None, None, None, None, None, None, None, None, None
365 rezre = re.compile(r'.*Video: .+, (\d+)x(\d+)[, ].*')
366 x = rezre.search(output)
367 if x:
368 width = int(x.group(1))
369 height = int(x.group(2))
370 else:
371 info_cache[inFile] = (mtime, (None, None, None, None, None, None, None, None, None))
372 debug_write(__name__, fn_attr(), ['failed at width/height'])
373 return None, None, None, None, None, None, None, None, None
375 rezre = re.compile(r'.*Video: .+, (.+) (?:fps|tb).*')
376 x = rezre.search(output)
377 if x:
378 fps = x.group(1)
379 else:
380 info_cache[inFile] = (mtime, (None, None, None, None, None, None, None, None, None))
381 debug_write(__name__, fn_attr(), ['failed at fps'])
382 return None, None, None, None, None, None, None, None, None
384 # Allow override only if it is mpeg2 and frame rate was doubled to 59.94
385 if (not fps == '29.97') and (codec == 'mpeg2video'):
386 # First look for the build 7215 version
387 rezre = re.compile(r'.*film source: 29.97.*')
388 x = rezre.search(output.lower() )
389 if x:
390 debug_write(__name__, fn_attr(), ['film source: 29.97 setting fps to 29.97'])
391 fps = '29.97'
392 else:
393 # for build 8047:
394 rezre = re.compile(r'.*frame rate differs from container frame rate: 29.97.*')
395 debug_write(__name__, fn_attr(), ['Bug in VideoReDo'])
396 x = rezre.search(output.lower() )
397 if x:
398 fps = '29.97'
400 durre = re.compile(r'.*Duration: (.{2}):(.{2}):(.{2})\.(.),')
401 d = durre.search(output)
402 if d:
403 millisecs = ((int(d.group(1))*3600) + (int(d.group(2))*60) + int(d.group(3)))*1000 + (int(d.group(4))*100)
404 else:
405 millisecs = 0
407 #get bitrate of source for tivo compatibility test.
408 rezre = re.compile(r'.*bitrate: (.+) (?:kb/s).*')
409 x = rezre.search(output)
410 if x:
411 kbps = x.group(1)
412 else:
413 kbps = None
414 debug_write(__name__, fn_attr(), ['failed at kbps'])
416 #get audio bitrate of source for tivo compatibility test.
417 rezre = re.compile(r'.*Audio: .+, (.+) (?:kb/s).*')
418 x = rezre.search(output)
419 if x:
420 akbps = x.group(1)
421 else:
422 akbps = None
423 debug_write(__name__, fn_attr(), ['failed at akbps'])
425 #get audio codec of source for tivo compatibility test.
426 rezre = re.compile(r'.*Audio: ([^,]+),.*')
427 x = rezre.search(output)
428 if x:
429 acodec = x.group(1)
430 else:
431 acodec = None
432 debug_write(__name__, fn_attr(), ['failed at acodec'])
434 #get audio frequency of source for tivo compatibility test.
435 rezre = re.compile(r'.*Audio: .+, (.+) (?:Hz).*')
436 x = rezre.search(output)
437 if x:
438 afreq = x.group(1)
439 else:
440 afreq = None
441 debug_write(__name__, fn_attr(), ['failed at afreq'])
443 info_cache[inFile] = (mtime, (codec, width, height, fps, millisecs, kbps, akbps, acodec, afreq))
444 debug_write(__name__, fn_attr(), ['Codec=', codec, ' width=', width, ' height=', height, ' fps=', fps, ' millisecs=', millisecs, ' kbps=', kbps, ' akbps=', akbps, ' acodec=', acodec, ' afreq=', afreq])
445 return codec, width, height, fps, millisecs, kbps, akbps, acodec, afreq
447 def video_check(inFile, cmd_string):
448 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
449 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
450 try:
451 shutil.copyfileobj(ffmpeg.stdout, open(videotest, 'wb'))
452 return True
453 except:
454 kill(ffmpeg.pid)
455 return False
457 def supported_format(inFile):
458 if video_info(inFile)[0]:
459 return True
460 else:
461 debug_write(__name__, fn_attr(), ['FALSE, file not supported', inFile])
462 return False
464 def kill(pid):
465 debug_write(__name__, fn_attr(), ['killing pid=', str(pid)])
466 if mswindows:
467 win32kill(pid)
468 else:
469 import os, signal
470 os.kill(pid, signal.SIGTERM)
472 def win32kill(pid):
473 import ctypes
474 handle = ctypes.windll.kernel32.OpenProcess(1, False, pid)
475 ctypes.windll.kernel32.TerminateProcess(handle, -1)
476 ctypes.windll.kernel32.CloseHandle(handle)
478 def gcd(a,b):
479 while b:
480 a, b = b, a % b
481 return a