1 import subprocess
, shutil
, os
, re
, sys
, tempfile
, ConfigParser
, time
, lrucache
, math
4 from plugin
import GetPlugin
6 logger
= logging
.getLogger('pyTivo.video.transcode')
8 info_cache
= lrucache
.LRUCache(1000)
9 videotest
= os
.path
.join(os
.path
.dirname(__file__
), 'videotest.mpg')
11 BAD_MPEG_FPS
= ['15.00']
14 return config
.get('Server', 'ffmpeg')
17 # subprocess is broken for me on windows so super hack
18 def patchSubprocess():
19 o
= subprocess
.Popen
._make
_inheritable
21 def _make_inheritable(self
, handle
):
22 if not handle
: return subprocess
.GetCurrentProcess()
23 return o(self
, handle
)
25 subprocess
.Popen
._make
_inheritable
= _make_inheritable
26 mswindows
= (sys
.platform
== "win32")
30 def output_video(inFile
, outFile
, tsn
=''):
31 if tivo_compatable(inFile
, tsn
):
32 logger
.debug('%s is tivo compatible' % inFile
)
33 f
= file(inFile
, 'rb')
34 shutil
.copyfileobj(f
, outFile
)
37 logger
.debug('%s is not tivo compatible' % inFile
)
38 transcode(inFile
, outFile
, tsn
)
40 def transcode(inFile
, outFile
, tsn
=''):
43 settings
['video_codec'] = select_videocodec(tsn
)
44 settings
['video_br'] = select_videobr(inFile
, tsn
)
45 settings
['video_fps'] = select_videofps(inFile
, tsn
)
46 settings
['max_video_br'] = select_maxvideobr()
47 settings
['buff_size'] = select_buffsize()
48 settings
['aspect_ratio'] = ' '.join(select_aspect(inFile
, tsn
))
49 settings
['audio_br'] = select_audiobr(tsn
)
50 settings
['audio_fr'] = select_audiofr(inFile
, tsn
)
51 settings
['audio_ch'] = select_audioch(tsn
)
52 settings
['audio_codec'] = select_audiocodec(inFile
, tsn
)
53 settings
['ffmpeg_pram'] = select_ffmpegprams(tsn
)
54 settings
['format'] = select_format(tsn
)
56 cmd_string
= config
.getFFmpegTemplate(tsn
) % settings
58 cmd
= [ffmpeg_path(), '-i', inFile
] + cmd_string
.split()
59 logging
.debug('transcoding to tivo model '+tsn
[:3]+' using ffmpeg command:')
60 logging
.debug(' '.join(cmd
))
61 ffmpeg
= subprocess
.Popen(cmd
, bufsize
=512*1024, stdout
=subprocess
.PIPE
)
64 shutil
.copyfileobj(ffmpeg
.stdout
, outFile
)
68 def select_audiocodec(inFile
, tsn
= ''):
69 # Default, compatible with all TiVo's
71 vInfo
= video_info(inFile
)
72 if config
.getAudioCodec(tsn
) == None:
73 if vInfo
['acodec'] in ('ac3', 'liba52', 'mp2'):
74 if vInfo
['akbps'] == None:
75 cmd_string
= '-y -vcodec mpeg2video -r 29.97 -b 1000k -acodec copy -t 00:00:01 -f vob -'
76 if video_check(inFile
, cmd_string
):
77 vInfo
= video_info(videotest
)
78 if not vInfo
['akbps'] == None and int(vInfo
['akbps']) <= config
.getMaxAudioBR(tsn
):
79 # compatible codec and bitrate, do not reencode audio
82 codec
= config
.getAudioCodec(tsn
)
84 if (codec
== 'copy' and config
.getCopyTS(tsn
).lower() == 'none' \
85 and type == 'mpeg2video') or config
.getCopyTS(tsn
).lower() == 'false':
87 return '-acodec '+codec
+copyts
89 def select_audiofr(inFile
, tsn
):
90 freq
= '48000' #default
91 vInfo
= video_info(inFile
)
92 if not vInfo
['afreq'] == None and vInfo
['afreq'] in ('44100', '48000'):
93 # compatible frequency
95 if config
.getAudioFR(tsn
) != None:
96 freq
= config
.getAudioFR(tsn
)
99 def select_audioch(tsn
):
100 if config
.getAudioCH(tsn
) != None:
101 return '-ac '+config
.getAudioCH(tsn
)
104 def select_videofps(inFile
, tsn
):
105 vInfo
= video_info(inFile
)
106 vfps
= '-r 29.97' #default
107 if config
.isHDtivo(tsn
) and vInfo
['fps'] not in BAD_MPEG_FPS
:
109 if config
.getVideoFPS(tsn
) != None:
110 vfps
= '-r '+config
.getVideoFPS(tsn
)
113 def select_videocodec(tsn
):
114 vcodec
= 'mpeg2video' #default
115 if config
.getVideoCodec(tsn
) != None:
116 vcodec
= config
.getVideoCodec(tsn
)
117 return '-vcodec '+vcodec
119 def select_videobr(inFile
, tsn
):
120 return '-b '+select_videostr(inFile
, tsn
)
122 def select_videostr(inFile
, tsn
):
123 video_str
= config
.getVideoBR(tsn
)
124 if config
.isHDtivo(tsn
):
125 vInfo
= video_info(inFile
)
126 if vInfo
['kbps'] != None and config
.getVideoPCT() > 0:
127 video_percent
= int(vInfo
['kbps'])*10*config
.getVideoPCT()
128 video_bitrate
= max(config
.strtod(video_str
), video_percent
)
129 video_str
= str(int(min(config
.strtod(config
.getMaxVideoBR())*0.95, video_bitrate
)))
132 def select_audiobr(tsn
):
133 return '-ab '+config
.getAudioBR(tsn
)
135 def select_maxvideobr():
136 return '-maxrate '+config
.getMaxVideoBR()
138 def select_buffsize():
139 return '-bufsize '+config
.getBuffSize()
141 def select_ffmpegprams(tsn
):
142 if config
.getFFmpegPrams(tsn
) != None:
143 return config
.getFFmpegPrams(tsn
)
146 def select_format(tsn
):
148 if config
.getFormat(tsn
) != None:
149 fmt
= config
.getFormat(tsn
)
150 return '-f '+fmt
+' -'
152 def select_aspect(inFile
, tsn
= ''):
153 TIVO_WIDTH
= config
.getTivoWidth(tsn
)
154 TIVO_HEIGHT
= config
.getTivoHeight(tsn
)
156 vInfo
= video_info(inFile
)
158 logging
.debug('tsn: %s' % tsn
)
160 aspect169
= config
.get169Setting(tsn
)
162 logging
.debug('aspect169:%s' % aspect169
)
164 optres
= config
.getOptres(tsn
)
166 logging
.debug('optres:%s' % optres
)
169 optHeight
= config
.nearestTivoHeight(vInfo
['height'])
170 optWidth
= config
.nearestTivoWidth(vInfo
['width'])
171 if optHeight
< TIVO_HEIGHT
:
172 TIVO_HEIGHT
= optHeight
173 if optWidth
< TIVO_WIDTH
:
174 TIVO_WIDTH
= optWidth
176 d
= gcd(vInfo
['height'],vInfo
['width'])
177 ratio
= (width
*100)/vInfo
['height']
178 rheight
, rwidth
= vInfo
['height']/d
, vInfo
['width']/d
180 logger
.debug('File=%s Type=%s width=%s height=%s fps=%s millisecs=%s ratio=%s rheight=%s rwidth=%s TIVO_HEIGHT=%sTIVO_WIDTH=%s' % (inFile
, vInfo
['codec'], vInfo
['width'], vInfo
['height'], vInfo
['fps'], vInfo
['millisecs'], ratio
, rheight
, rwidth
, TIVO_HEIGHT
, TIVO_WIDTH
))
182 multiplier16by9
= (16.0 * TIVO_HEIGHT
) / (9.0 * TIVO_WIDTH
)
183 multiplier4by3
= (4.0 * TIVO_HEIGHT
) / (3.0 * TIVO_WIDTH
)
185 if config
.isHDtivo(tsn
) and not optres
:
186 if config
.getPixelAR(0):
188 npar
= config
.getPixelAR(1)
191 # adjust for pixel aspect ratio, if set, because TiVo expects square pixels
193 return ['-s', str(width
) + 'x' + str(int(math
.ceil(height
/npar
)))]
195 # FFMPEG expects width to be a multiple of two
196 return ['-s', str(int(math
.ceil(width
*npar
/2.0)*2)) + 'x' + str(height
)]
197 if height
<= TIVO_HEIGHT
:
198 # pass all resolutions to S3, except heights greater than conf height
200 # else, resize video.
201 if (rwidth
, rheight
) in [(1, 1)] and par1
== '8:9':
202 logger
.debug('File + PAR is within 4:3.')
203 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
)]
204 elif (rwidth
, rheight
) in [(4, 3), (10, 11), (15, 11), (59, 54), (59, 72), (59, 36), (59, 54)] or dar1
== '4:3':
205 logger
.debug('File is within 4:3 list.')
206 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
)]
207 elif ((rwidth
, rheight
) in [(16, 9), (20, 11), (40, 33), (118, 81), (59, 27)] or dar1
== '16:9')\
208 and (aspect169
or config
.get169Letterbox(tsn
)):
209 logger
.debug('File is within 16:9 list and 16:9 allowed.')
210 if config
.get169Blacklist(tsn
) or (aspect169
and config
.get169Letterbox(tsn
)):
211 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
)]
213 return ['-aspect', '16:9', '-s', str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
)]
216 #If video is wider than 4:3 add top and bottom padding
217 if (ratio
> 133): #Might be 16:9 file, or just need padding on top and bottom
218 if aspect169
and (ratio
> 135): #If file would fall in 4:3 assume it is supposed to be 4:3
219 if (ratio
> 177):#too short needs padding top and bottom
220 endHeight
= int(((TIVO_WIDTH
*height
)/width
) * multiplier16by9
)
221 settings
.append('-aspect')
222 if config
.get169Blacklist(tsn
) or config
.get169Letterbox(tsn
):
223 settings
.append('4:3')
225 settings
.append('16:9')
228 if endHeight
< TIVO_HEIGHT
* 0.99:
229 settings
.append('-s')
230 settings
.append(str(TIVO_WIDTH
) + 'x' + str(endHeight
))
232 topPadding
= ((TIVO_HEIGHT
- endHeight
)/2)
236 settings
.append('-padtop')
237 settings
.append(str(topPadding
))
238 bottomPadding
= (TIVO_HEIGHT
- endHeight
) - topPadding
239 settings
.append('-padbottom')
240 settings
.append(str(bottomPadding
))
241 else: #if only very small amount of padding needed, then just stretch it
242 settings
.append('-s')
243 settings
.append(str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
))
244 logger
.debug('16:9 aspect allowed, file is wider than 16:9 padding top and bottom\n%s' % ' '.join(settings
))
245 else: #too skinny needs padding on left and right.
246 endWidth
= int((TIVO_HEIGHT
*width
)/(height
*multiplier16by9
))
247 settings
.append('-aspect')
248 if config
.get169Blacklist(tsn
) or config
.get169Letterbox(tsn
):
249 settings
.append('4:3')
251 settings
.append('16:9')
254 if endWidth
< (TIVO_WIDTH
-10):
255 settings
.append('-s')
256 settings
.append(str(endWidth
) + 'x' + str(TIVO_HEIGHT
))
258 leftPadding
= ((TIVO_WIDTH
- endWidth
)/2)
262 settings
.append('-padleft')
263 settings
.append(str(leftPadding
))
264 rightPadding
= (TIVO_WIDTH
- endWidth
) - leftPadding
265 settings
.append('-padright')
266 settings
.append(str(rightPadding
))
267 else: #if only very small amount of padding needed, then just stretch it
268 settings
.append('-s')
269 settings
.append(str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
))
270 logger
.debug('16:9 aspect allowed, file is narrower than 16:9 padding left and right\n%s' % ' '.join(settings
))
271 else: #this is a 4:3 file or 16:9 output not allowed
272 multiplier
= multiplier4by3
273 settings
.append('-aspect')
274 if ratio
> 135 and config
.get169Letterbox(tsn
):
275 settings
.append('16:9')
276 multiplier
= multiplier16by9
278 settings
.append('4:3')
279 endHeight
= int(((TIVO_WIDTH
*height
)/width
) * multiplier
)
282 if endHeight
< TIVO_HEIGHT
* 0.99:
283 settings
.append('-s')
284 settings
.append(str(TIVO_WIDTH
) + 'x' + str(endHeight
))
286 topPadding
= ((TIVO_HEIGHT
- endHeight
)/2)
290 settings
.append('-padtop')
291 settings
.append(str(topPadding
))
292 bottomPadding
= (TIVO_HEIGHT
- endHeight
) - topPadding
293 settings
.append('-padbottom')
294 settings
.append(str(bottomPadding
))
295 else: #if only very small amount of padding needed, then just stretch it
296 settings
.append('-s')
297 settings
.append(str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
))
298 logging
.debug('File is wider than 4:3 padding top and bottom\n%s' % ' '.join(settings
))
301 #If video is taller than 4:3 add left and right padding, this is rare. All of these files will always be sent in
302 #an aspect ratio of 4:3 since they are so narrow.
304 endWidth
= int((TIVO_HEIGHT
*width
)/(height
*multiplier4by3
))
305 settings
.append('-aspect')
306 settings
.append('4:3')
309 if endWidth
< (TIVO_WIDTH
* 0.99):
310 settings
.append('-s')
311 settings
.append(str(endWidth
) + 'x' + str(TIVO_HEIGHT
))
313 leftPadding
= ((TIVO_WIDTH
- endWidth
)/2)
317 settings
.append('-padleft')
318 settings
.append(str(leftPadding
))
319 rightPadding
= (TIVO_WIDTH
- endWidth
) - leftPadding
320 settings
.append('-padright')
321 settings
.append(str(rightPadding
))
322 else: #if only very small amount of padding needed, then just stretch it
323 settings
.append('-s')
324 settings
.append(str(TIVO_WIDTH
) + 'x' + str(TIVO_HEIGHT
))
326 logger
.debug('File is taller than 4:3 padding left and right\n%s' % ' '.join(settings
))
330 def tivo_compatable(inFile
, tsn
= ''):
331 supportedModes
= [[720, 480], [704, 480], [544, 480], [528, 480], [480, 480], [352, 480]]
332 vInfo
= video_info(inFile
)
333 #print type, width, height, fps, millisecs, kbps, akbps, acodec
335 if (inFile
[-5:]).lower() == '.tivo':
336 logger
.debug('TRUE, ends with .tivo. %s' % inFile
)
339 if not vInfo
['codec'] == 'mpeg2video':
340 #print 'Not Tivo Codec'
341 logger
.debug('FALSE, type %s not mpeg2video. %s' % (vInfo
['codec'], inFile
))
344 if os
.path
.splitext(inFile
)[-1].lower() in ('.ts', '.mpv', '.tp'):
345 logger
.debug('FALSE, ext %s not tivo compatible. %s' % (os
.path
.splitext(inFile
)[-1], inFile
))
348 if vInfo
['acodec'] == 'dca':
349 logger
.debug('FALSE, acodec %s not supported. %s' % (vInfo
['acodec'], inFile
))
352 if vInfo
['acodec'] != None:
353 if not vInfo
['akbps'] or int(vInfo
['akbps']) > config
.getMaxAudioBR(tsn
):
354 logger
.debug('FALSE, %s kbps exceeds max audio bitrate. %s' % (vInfo
['akbps'], inFile
))
357 if vInfo
['kbps'] != None:
358 abit
= max('0', vInfo
['akbps'])
359 if int(vInfo
['kbps'])-int(abit
) > config
.strtod(config
.getMaxVideoBR())/1000:
360 logger
.debug('FALSE, %s kbps exceeds max video bitrate. %s' % (vInfo
['kbps'], inFile
))
363 logger
.debug('FALSE, %s kbps not supported. %s' % (vInfo
['kbps'], inFile
))
366 if config
.isHDtivo(tsn
):
367 if vInfo
['par2'] != 1.0:
368 if config
.getPixelAR(0):
369 if vInfo
['par2'] != None or config
.getPixelAR(1) != 1.0:
370 logger
.debug('FALSE, %s not correct PAR, %s' % (vInfo
['par2'], inFile
))
372 logger
.debug('TRUE, HD Tivo detected, skipping remaining tests %s' % inFile
)
375 if not vInfo
['fps'] == '29.97':
376 #print 'Not Tivo fps'
377 logger
.debug('FALSE, %s fps, should be 29.97. %s' % (vInfo
['fps'], inFile
))
380 if (config
.get169Blacklist(tsn
) and not config
.get169Setting(tsn
))\
381 or (config
.get169Letterbox(tsn
) and config
.get169Setting(tsn
)):
382 if vInfo
['dar1'] == None or not vInfo
['dar1'] in ('4:3', '8:9'):
383 debug_write(__name__
, fn_attr(), ['FALSE, DAR', vInfo
['dar1'], 'not supported by BLACKLIST_169 tivos.', inFile
])
386 for mode
in supportedModes
:
387 if (mode
[0], mode
[1]) == (vInfo
['width'], vInfo
['height']):
388 logger
.debug('TRUE, %s x %s is valid. %s' % (vInfo
['width'], vInfo
['height'], inFile
))
390 #print 'Not Tivo dimensions'
391 logger
.debug('FALSE, %s x %s not in supported modes. %s' % (vInfo
['width'], vInfo
['height'], inFile
))
394 def video_info(inFile
):
396 mtime
= os
.stat(inFile
).st_mtime
397 if inFile
!= videotest
:
398 if inFile
in info_cache
and info_cache
[inFile
][0] == mtime
:
399 logging
.debug('CACHE HIT! %s' % inFile
)
400 return info_cache
[inFile
][1]
402 vInfo
['Supported'] = True
404 if (inFile
[-5:]).lower() == '.tivo':
405 vInfo
['millisecs'] = 0
406 info_cache
[inFile
] = (mtime
, vInfo
)
407 logger
.debug('VALID, ends in .tivo. %s' % inFile
)
410 cmd
= [ffmpeg_path(), '-i', inFile
]
411 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
412 err_tmp
= tempfile
.TemporaryFile()
413 ffmpeg
= subprocess
.Popen(cmd
, stderr
=err_tmp
, stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
415 # wait 10 sec if ffmpeg is not back give up
416 for i
in xrange(200):
418 if not ffmpeg
.poll() == None:
421 if ffmpeg
.poll() == None:
423 vInfo
['Supported'] = False
424 info_cache
[inFile
] = (mtime
, vInfo
)
428 output
= err_tmp
.read()
430 logging
.debug('ffmpeg output=%s' % output
)
432 rezre
= re
.compile(r
'.*Video: ([^,]+),.*')
433 x
= rezre
.search(output
)
435 vInfo
['codec'] = x
.group(1)
438 vInfo
['Supported'] = False
439 logger
.debug('failed at codec')
441 rezre
= re
.compile(r
'.*Video: .+, (\d+)x(\d+)[, ].*')
442 x
= rezre
.search(output
)
444 vInfo
['width'] = int(x
.group(1))
445 vInfo
['height'] = int(x
.group(2))
449 vInfo
['Supported'] = False
450 logger
.debug('failed at width/height')
452 rezre
= re
.compile(r
'.*Video: .+, (.+) (?:fps|tb).*')
453 x
= rezre
.search(output
)
455 vInfo
['fps'] = x
.group(1)
456 # Allow override only if it is mpeg2 and frame rate was doubled to 59.94
457 if (not vInfo
['fps'] == '29.97') and (vInfo
['codec'] == 'mpeg2video'):
458 # First look for the build 7215 version
459 rezre
= re
.compile(r
'.*film source: 29.97.*')
460 x
= rezre
.search(output
.lower() )
462 logger
.debug('film source: 29.97 setting fps to 29.97')
463 vInfo
['fps'] = '29.97'
466 rezre
= re
.compile(r
'.*frame rate differs from container frame rate: 29.97.*')
467 logger
.debug('Bug in VideoReDo')
468 x
= rezre
.search(output
.lower() )
470 vInfo
['fps'] = '29.97'
473 vInfo
['Supported'] = False
474 logger
.debug('failed at fps')
476 durre
= re
.compile(r
'.*Duration: (.{2}):(.{2}):(.{2})\.(.),')
477 d
= durre
.search(output
)
479 vInfo
['millisecs'] = ((int(d
.group(1))*3600) + (int(d
.group(2))*60) + int(d
.group(3)))*1000 + (int(d
.group(4))*100)
481 vInfo
['millisecs'] = 0
483 #get bitrate of source for tivo compatibility test.
484 rezre
= re
.compile(r
'.*bitrate: (.+) (?:kb/s).*')
485 x
= rezre
.search(output
)
487 vInfo
['kbps'] = x
.group(1)
490 logger
.debug('failed at kbps')
492 #get audio bitrate of source for tivo compatibility test.
493 rezre
= re
.compile(r
'.*Audio: .+, (.+) (?:kb/s).*')
494 x
= rezre
.search(output
)
496 vInfo
['akbps'] = x
.group(1)
498 vInfo
['akbps'] = None
499 logger
.debug('failed at akbps')
501 #get audio codec of source for tivo compatibility test.
502 rezre
= re
.compile(r
'.*Audio: ([^,]+),.*')
503 x
= rezre
.search(output
)
505 vInfo
['acodec'] = x
.group(1)
507 vInfo
['acodec'] = None
508 logger
.debug('failed at acodec')
510 #get audio frequency of source for tivo compatibility test.
511 rezre
= re
.compile(r
'.*Audio: .+, (.+) (?:Hz).*')
512 x
= rezre
.search(output
)
514 vInfo
['afreq'] = x
.group(1)
516 vInfo
['afreq'] = None
517 logger
.debug('failed at afreq')
520 rezre
= re
.compile(r
'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
521 x
= rezre
.search(output
)
522 if x
and x
.group(1)!="0" and x
.group(2)!="0":
523 vInfo
['par1'], vInfo
['par2'] = x
.group(1)+':'+x
.group(2), float(x
.group(1))/float(x
.group(2))
525 vInfo
['par1'], vInfo
['par2'] = None, None
528 rezre
= re
.compile(r
'.*Video: .+DAR ([0-9]+):([0-9]+).*')
529 x
= rezre
.search(output
)
530 if x
and x
.group(1)!="0" and x
.group(2)!="0":
531 vInfo
['dar1'], vInfo
['dar2'] = x
.group(1)+':'+x
.group(2), float(x
.group(1))/float(x
.group(2))
533 vInfo
['dar1'], vInfo
['dar2'] = None, None
535 videoPlugin
= GetPlugin('video')
536 metadata
= videoPlugin
.getMetadataFromTxt(inFile
)
539 if key
.startswith('Override_'):
540 vInfo
['Supported'] = True
541 vInfo
[key
.replace('Override_','')] = metadata
[key
]
543 info_cache
[inFile
] = (mtime
, vInfo
)
544 logger
.debug("; ".join(["%s=%s" % (k
, v
) for k
, v
in vInfo
.items()]))
547 def video_check(inFile
, cmd_string
):
548 cmd
= [ffmpeg_path(), '-i', inFile
] + cmd_string
.split()
549 ffmpeg
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
551 shutil
.copyfileobj(ffmpeg
.stdout
, open(videotest
, 'wb'))
557 def supported_format(inFile
):
558 if video_info(inFile
)['Supported']:
561 logger
.debug('FALSE, file not supported %s' % inFile
)
565 logger
.debug('killing pid=%s' % str(pid
))
570 os
.kill(pid
, signal
.SIGTERM
)
574 handle
= ctypes
.windll
.kernel32
.OpenProcess(1, False, pid
)
575 ctypes
.windll
.kernel32
.TerminateProcess(handle
, -1)
576 ctypes
.windll
.kernel32
.CloseHandle(handle
)