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