- pyTivo
[pyTivo/krkeegan.git] / plugins / video / transcode.py
blobba5e7c0bd3b28ac02d4caea4114f236e4313138d
1 import subprocess, shutil, os, re, sys, ConfigParser, time, lrucache
2 import Config
4 info_cache = lrucache.LRUCache(1000)
7 debug = Config.getDebug()
8 TIVO_WIDTH = Config.getTivoWidth()
9 TIVO_HEIGHT = Config.getTivoHeight()
10 AUDIO_BR = Config.getAudioBR()
11 VIDEO_BR = Config.getVideoBR()
12 FFMPEG = Config.get('Server', 'ffmpeg')
14 def debug_write(data):
15 if debug:
16 debug_out = []
17 for x in data:
18 debug_out.append(str(x))
19 fdebug = open('debug.txt', 'a')
20 fdebug.write(' '.join(debug_out))
21 fdebug.close()
23 # XXX BIG HACK
24 # subprocess is broken for me on windows so super hack
25 def patchSubprocess():
26 o = subprocess.Popen._make_inheritable
28 def _make_inheritable(self, handle):
29 if not handle: return subprocess.GetCurrentProcess()
30 return o(self, handle)
32 subprocess.Popen._make_inheritable = _make_inheritable
33 mswindows = (sys.platform == "win32")
34 if mswindows:
35 patchSubprocess()
37 def output_video(inFile, outFile, tsn=''):
38 if tivo_compatable(inFile):
39 debug_write(['output_video: ', inFile, ' is tivo compatible\n'])
40 f = file(inFile, 'rb')
41 shutil.copyfileobj(f, outFile)
42 f.close()
43 else:
44 debug_write(['output_video: ', inFile, ' is not tivo compatible\n'])
45 transcode(inFile, outFile, tsn)
47 def transcode(inFile, outFile, tsn=''):
48 cmd = [FFMPEG, '-i', inFile, '-vcodec', 'mpeg2video', '-r', '29.97', '-b', VIDEO_BR] + select_aspect(inFile, tsn) + ['-comment', 'pyTivo.py', '-ac', '2', '-ab', AUDIO_BR,'-ar', '44100', '-f', 'vob', '-' ]
49 debug_write(['transcode: ffmpeg command is ', ''.join(cmd), '\n'])
50 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
51 try:
52 shutil.copyfileobj(ffmpeg.stdout, outFile)
53 except:
54 kill(ffmpeg.pid)
56 def select_aspect(inFile, tsn = ''):
57 type, width, height, fps, millisecs = video_info(inFile)
59 debug_write(['tsn:', tsn, '\n'])
61 aspect169 = Config.get169Setting(tsn)
63 debug_write(['aspect169:', aspect169, '\n'])
65 d = gcd(height,width)
66 ratio = (width*100)/height
67 rheight, rwidth = height/d, width/d
69 debug_write(['select_aspect: File=', inFile, ' Type=', type, ' width=', width, ' height=', height, ' fps=', fps, ' millisecs=', millisecs, ' ratio=', ratio, ' rheight=', rheight, ' rwidth=', rwidth, '\n'])
71 multiplier16by9 = (16.0 * TIVO_HEIGHT) / (9.0 * TIVO_WIDTH)
72 multiplier4by3 = (4.0 * TIVO_HEIGHT) / (3.0 * TIVO_WIDTH)
74 if (rwidth, rheight) in [(4, 3), (10, 11), (15, 11), (59, 54), (59, 72), (59, 36), (59, 54)]:
75 debug_write(['select_aspect: File is within 4:3 list.\n'])
76 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
77 elif ((rwidth, rheight) in [(16, 9), (20, 11), (40, 33), (118, 81), (59, 27)]) and aspect169:
78 debug_write(['select_aspect: File is within 16:9 list and 16:9 allowed.\n'])
79 return ['-aspect', '16:9', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
80 else:
81 settings = []
82 #If video is wider than 4:3 add top and bottom padding
83 if (ratio > 133): #Might be 16:9 file, or just need padding on top and bottom
84 if aspect169 and (ratio > 135): #If file would fall in 4:3 assume it is supposed to be 4:3
85 if (ratio > 177):#too short needs padding top and bottom
86 endHeight = int(((TIVO_WIDTH*height)/width) * multiplier16by9)
87 settings.append('-aspect')
88 settings.append('16:9')
89 if endHeight % 2:
90 endHeight -= 1
91 if endHeight < TIVO_HEIGHT * 0.99:
92 settings.append('-s')
93 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
95 topPadding = ((TIVO_HEIGHT - endHeight)/2)
96 if topPadding % 2:
97 topPadding -= 1
99 settings.append('-padtop')
100 settings.append(str(topPadding))
101 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
102 settings.append('-padbottom')
103 settings.append(str(bottomPadding))
104 else: #if only very small amount of padding needed, then just stretch it
105 settings.append('-s')
106 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
107 debug_write(['select_aspect: 16:9 aspect allowed, file is wider than 16:9 padding top and bottom\n', ' '.join(settings), '\n'])
108 else: #too skinny needs padding on left and right.
109 endWidth = int((TIVO_HEIGHT*width)/(height*multiplier16by9))
110 settings.append('-aspect')
111 settings.append('16:9')
112 if endWidth % 2:
113 endWidth -= 1
114 if endWidth < (TIVO_WIDTH-10):
115 settings.append('-s')
116 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
118 leftPadding = ((TIVO_WIDTH - endWidth)/2)
119 if leftPadding % 2:
120 leftPadding -= 1
122 settings.append('-padleft')
123 settings.append(str(leftPadding))
124 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
125 settings.append('-padright')
126 settings.append(str(rightPadding))
127 else: #if only very small amount of padding needed, then just stretch it
128 settings.append('-s')
129 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
130 debug_write(['select_aspect: 16:9 aspect allowed, file is narrower than 16:9 padding left and right\n', ' '.join(settings), '\n'])
131 else: #this is a 4:3 file or 16:9 output not allowed
132 settings.append('-aspect')
133 settings.append('4:3')
134 endHeight = int(((TIVO_WIDTH*height)/width) * multiplier4by3)
135 if endHeight % 2:
136 endHeight -= 1
137 if endHeight < TIVO_HEIGHT * 0.99:
138 settings.append('-s')
139 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
141 topPadding = ((TIVO_HEIGHT - endHeight)/2)
142 if topPadding % 2:
143 topPadding -= 1
145 settings.append('-padtop')
146 settings.append(str(topPadding))
147 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
148 settings.append('-padbottom')
149 settings.append(str(bottomPadding))
150 else: #if only very small amount of padding needed, then just stretch it
151 settings.append('-s')
152 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
153 debug_write(['select_aspect: File is wider than 4:3 padding top and bottom\n', ' '.join(settings), '\n'])
155 return settings
156 #If video is taller than 4:3 add left and right padding, this is rare. All of these files will always be sent in
157 #an aspect ratio of 4:3 since they are so narrow.
158 else:
159 endWidth = int((TIVO_HEIGHT*width)/(height*multiplier4by3))
160 settings.append('-aspect')
161 settings.append('4:3')
162 if endWidth % 2:
163 endWidth -= 1
164 if endWidth < (TIVO_WIDTH * 0.99):
165 settings.append('-s')
166 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
168 leftPadding = ((TIVO_WIDTH - endWidth)/2)
169 if leftPadding % 2:
170 leftPadding -= 1
172 settings.append('-padleft')
173 settings.append(str(leftPadding))
174 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
175 settings.append('-padright')
176 settings.append(str(rightPadding))
177 else: #if only very small amount of padding needed, then just stretch it
178 settings.append('-s')
179 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
181 debug_write(['select_aspect: File is taller than 4:3 padding left and right\n', ' '.join(settings), '\n'])
183 return settings
185 def tivo_compatable(inFile):
186 suportedModes = [[720, 480], [704, 480], [544, 480], [480, 480], [352, 480]]
187 type, width, height, fps, millisecs = video_info(inFile)
188 #print type, width, height, fps, millisecs
190 if (inFile[-5:]).lower() == '.tivo':
191 debug_write(['tivo_compatible: ', inFile, ' ends with .tivo\n'])
192 return True
194 if not type == 'mpeg2video':
195 #print 'Not Tivo Codec'
196 debug_write(['tivo_compatible: ', inFile, ' is not mpeg2video it is ', type, '\n'])
197 return False
199 if not fps == '29.97':
200 #print 'Not Tivo fps'
201 debug_write(['tivo_compatible: ', inFile, ' is not correct fps it is ', fps, '\n'])
202 return False
204 for mode in suportedModes:
205 if (mode[0], mode[1]) == (width, height):
206 #print 'Is TiVo!'
207 debug_write(['tivo_compatible: ', inFile, ' has correct width of ', width, ' and height of ', height, '\n'])
208 return True
209 #print 'Not Tivo dimensions'
210 return False
212 def video_info(inFile):
213 mtime = os.stat(inFile).st_mtime
214 if inFile in info_cache and info_cache[inFile][0] == mtime:
215 debug_write(['video_info: ', inFile, ' cache hit!', '\n'])
216 return info_cache[inFile][1]
218 if (inFile[-5:]).lower() == '.tivo':
219 info_cache[inFile] = (mtime, (True, True, True, True, True))
220 debug_write(['video_info: ', inFile, ' ends in .tivo.\n'])
221 return True, True, True, True, True
223 cmd = [FFMPEG, '-i', inFile ]
224 ffmpeg = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
226 # wait 4 sec if ffmpeg is not back give up
227 for i in range(80):
228 time.sleep(.05)
229 if not ffmpeg.poll() == None:
230 break
232 if ffmpeg.poll() == None:
233 kill(ffmpeg.pid)
234 info_cache[inFile] = (mtime, (None, None, None, None, None))
235 return None, None, None, None, None
237 output = ffmpeg.stderr.read()
238 debug_write(['video_info: ffmpeg output=', output, '\n'])
240 durre = re.compile(r'.*Duration: (.{2}):(.{2}):(.{2})\.(.),')
241 d = durre.search(output)
243 rezre = re.compile(r'.*Video: ([^,]+),.*')
244 x = rezre.search(output)
245 if x:
246 codec = x.group(1)
247 else:
248 info_cache[inFile] = (mtime, (None, None, None, None, None))
249 debug_write(['video_info: failed at codec\n'])
250 return None, None, None, None, None
252 rezre = re.compile(r'.*Video: .+, (\d+)x(\d+),.*')
253 x = rezre.search(output)
254 if x:
255 width = int(x.group(1))
256 height = int(x.group(2))
257 else:
258 info_cache[inFile] = (mtime, (None, None, None, None, None))
259 debug_write(['video_info: failed at width/height\n'])
260 return None, None, None, None, None
262 rezre = re.compile(r'.*Video: .+, (.+) fps.*')
263 x = rezre.search(output)
264 if x:
265 fps = x.group(1)
266 else:
267 info_cache[inFile] = (mtime, (None, None, None, None, None))
268 debug_write(['video_info: failed at fps\n'])
269 return None, None, None, None, None
271 # Allow override only if it is mpeg2 and frame rate was doubled to 59.94
272 if (not fps == '29.97') and (codec == 'mpeg2video'):
273 # First look for the build 7215 version
274 rezre = re.compile(r'.*film source: 29.97.*')
275 x = rezre.search(output.lower() )
276 if x:
277 debug_write(['video_info: film source: 29.97 setting fps to 29.97\n'])
278 fps = '29.97'
279 else:
280 # for build 8047:
281 rezre = re.compile(r'.*frame rate differs from container frame rate: 29.97.*')
282 debug_write(['video_info: Bug in VideoReDo\n'])
283 x = rezre.search(output.lower() )
284 if x:
285 fps = '29.97'
287 millisecs = ((int(d.group(1))*3600) + (int(d.group(2))*60) + int(d.group(3)))*1000 + (int(d.group(4))*100)
288 info_cache[inFile] = (mtime, (codec, width, height, fps, millisecs))
289 debug_write(['video_info: Codec=', codec, ' width=', width, ' height=', height, ' fps=', fps, ' millisecs=', millisecs, '\n'])
290 return codec, width, height, fps, millisecs
292 def suported_format(inFile):
293 if video_info(inFile)[0]:
294 return True
295 else:
296 debug_write(['supported_format: ', inFile, ' is not supported\n'])
297 return False
299 def kill(pid):
300 debug_write(['kill: killing pid=', str(pid), '\n'])
301 if mswindows:
302 win32kill(pid)
303 else:
304 import os, signal
305 os.kill(pid, signal.SIGKILL)
307 def win32kill(pid):
308 import ctypes
309 handle = ctypes.windll.kernel32.OpenProcess(1, False, pid)
310 ctypes.windll.kernel32.TerminateProcess(handle, -1)
311 ctypes.windll.kernel32.CloseHandle(handle)
313 def gcd(a,b):
314 while b:
315 a, b = b, a % b
316 return a