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