More fiddly bits that probably no one else cares about.
[pyTivo/wgw.git] / plugins / video / transcode.py
blobec75225ba578e7ad7ee99d58f28debc2c9a8d4fc
1 import ConfigParser
2 import logging
3 import math
4 import os
5 import re
6 import shutil
7 import subprocess
8 import sys
9 import tempfile
10 import time
12 import lrucache
13 import config
14 from plugin import GetPlugin
16 logger = logging.getLogger('pyTivo.video.transcode')
18 info_cache = lrucache.LRUCache(1000)
19 videotest = os.path.join(os.path.dirname(__file__), 'videotest.mpg')
21 BAD_MPEG_FPS = ['15.00']
23 def ffmpeg_path():
24 return config.get('Server', 'ffmpeg')
26 # XXX BIG HACK
27 # subprocess is broken for me on windows so super hack
28 def patchSubprocess():
29 o = subprocess.Popen._make_inheritable
31 def _make_inheritable(self, handle):
32 if not handle: return subprocess.GetCurrentProcess()
33 return o(self, handle)
35 subprocess.Popen._make_inheritable = _make_inheritable
36 mswindows = (sys.platform == "win32")
37 if mswindows:
38 patchSubprocess()
40 def output_video(inFile, outFile, tsn=''):
41 if tivo_compatible(inFile, tsn)[0]:
42 logger.debug('%s is tivo compatible' % inFile)
43 f = file(inFile, 'rb')
44 shutil.copyfileobj(f, outFile)
45 f.close()
46 else:
47 logger.debug('%s is not tivo compatible' % inFile)
48 transcode(False, inFile, outFile, tsn)
50 def transcode(isQuery, inFile, outFile, tsn=''):
51 settings = {'video_codec': select_videocodec(tsn),
52 'video_br': select_videobr(inFile, tsn),
53 'video_fps': select_videofps(inFile, tsn),
54 'max_video_br': select_maxvideobr(),
55 'buff_size': select_buffsize(tsn),
56 'aspect_ratio': ' '.join(select_aspect(inFile, tsn)),
57 'audio_br': select_audiobr(tsn),
58 'audio_fr': select_audiofr(inFile, tsn),
59 'audio_ch': select_audioch(tsn),
60 'audio_codec': select_audiocodec(isQuery, inFile, tsn),
61 'audio_lang': select_audiolang(inFile, tsn),
62 'ffmpeg_pram': select_ffmpegprams(tsn),
63 'format': select_format(tsn)}
65 if isQuery:
66 return settings
68 cmd_string = config.getFFmpegTemplate(tsn) % settings
70 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
71 logging.debug('transcoding to tivo model ' + tsn[:3] +
72 ' using ffmpeg command:')
73 logging.debug(' '.join(cmd))
74 ffmpeg = subprocess.Popen(cmd, bufsize=(512 * 1024),
75 stdout=subprocess.PIPE)
76 try:
77 shutil.copyfileobj(ffmpeg.stdout, outFile)
78 except:
79 kill(ffmpeg.pid)
81 def select_audiocodec(isQuery, inFile, tsn=''):
82 # Default, compatible with all TiVo's
83 codec = 'ac3'
84 vInfo = video_info(inFile)
85 codectype = vInfo['vCodec']
86 if config.getAudioCodec(tsn) == None:
87 if vInfo['aCodec'] in ('ac3', 'liba52', 'mp2'):
88 if vInfo['aKbps'] == None:
89 if not isQuery:
90 cmd_string = ('-y -vcodec mpeg2video -r 29.97 ' +
91 '-b 1000k -acodec copy ' +
92 select_audiolang(inFile, tsn) +
93 ' -t 00:00:01 -f vob -')
94 if video_check(inFile, cmd_string):
95 vInfo = video_info(videotest)
96 else:
97 codec = 'TBD'
98 if (not vInfo['aKbps'] == None and
99 int(vInfo['aKbps']) <= config.getMaxAudioBR(tsn)):
100 # compatible codec and bitrate, do not reencode audio
101 codec = 'copy'
102 else:
103 codec = config.getAudioCodec(tsn)
104 copyts = ' -copyts'
105 if ((codec == 'copy' and config.getCopyTS(tsn).lower() == 'none'
106 and codectype == 'mpeg2video') or
107 config.getCopyTS(tsn).lower() == 'false'):
108 copyts = ''
109 return '-acodec ' + codec + copyts
111 def select_audiofr(inFile, tsn):
112 freq = '48000' #default
113 vInfo = video_info(inFile)
114 if not vInfo['aFreq'] == None and vInfo['aFreq'] in ('44100', '48000'):
115 # compatible frequency
116 freq = vInfo['aFreq']
117 if config.getAudioFR(tsn) != None:
118 freq = config.getAudioFR(tsn)
119 return '-ar ' + freq
121 def select_audioch(tsn):
122 ch = config.getAudioCH(tsn)
123 if ch:
124 return '-ac ' + ch
125 return ''
127 def select_audiolang(inFile, tsn):
128 vInfo = video_info(inFile)
129 if config.getAudioLang(tsn) != None and vInfo['mapVideo'] != None:
130 stream = vInfo['mapAudio'][0][0]
131 langmatch = []
132 for lang in config.getAudioLang(tsn).replace(' ','').lower().split(','):
133 for s, l in vInfo['mapAudio']:
134 if lang in s + l.replace(' ','').lower():
135 langmatch.append(s)
136 stream = s
137 break
138 if langmatch: break
139 if stream is not '':
140 return '-map ' + vInfo['mapVideo'] + ' -map ' + stream
141 return ''
143 def select_videofps(inFile, tsn):
144 vInfo = video_info(inFile)
145 fps = '-r 29.97' # default
146 if config.isHDtivo(tsn) and vInfo['vFps'] not in BAD_MPEG_FPS:
147 fps = ' '
148 if config.getVideoFPS(tsn) != None:
149 fps = '-r ' + config.getVideoFPS(tsn)
150 return fps
152 def select_videocodec(tsn):
153 codec = config.getVideoCodec(tsn)
154 if not codec:
155 codec = 'mpeg2video' # default
156 return '-vcodec ' + codec
158 def select_videobr(inFile, tsn):
159 return '-b ' + str(select_videostr(inFile, tsn) / 1000) + 'k'
161 def select_videostr(inFile, tsn):
162 video_str = config.strtod(config.getVideoBR(tsn))
163 if config.isHDtivo(tsn):
164 vInfo = video_info(inFile)
165 if vInfo['kbps'] != None and config.getVideoPCT() > 0:
166 video_percent = int(vInfo['kbps']) * 10 * config.getVideoPCT()
167 video_str = max(video_str, video_percent)
168 video_str = int(min(config.strtod(config.getMaxVideoBR()) * 0.95,
169 video_str))
170 return video_str
172 def select_audiobr(tsn):
173 return '-ab ' + config.getAudioBR(tsn)
175 def select_maxvideobr():
176 return '-maxrate ' + config.getMaxVideoBR()
178 def select_buffsize(tsn):
179 return '-bufsize ' + config.getBuffSize(tsn)
181 def select_ffmpegprams(tsn):
182 params = config.getFFmpegPrams(tsn)
183 if not params:
184 params = ''
185 return params
187 def select_format(tsn):
188 fmt = config.getFormat(tsn)
189 if not fmt:
190 fmt = 'vob'
191 return '-f %s -' % fmt
193 def select_aspect(inFile, tsn = ''):
194 TIVO_WIDTH = config.getTivoWidth(tsn)
195 TIVO_HEIGHT = config.getTivoHeight(tsn)
197 vInfo = video_info(inFile)
199 logging.debug('tsn: %s' % tsn)
201 aspect169 = config.get169Setting(tsn)
203 logging.debug('aspect169: %s' % aspect169)
205 optres = config.getOptres(tsn)
207 logging.debug('optres: %s' % optres)
209 if optres:
210 optHeight = config.nearestTivoHeight(vInfo['vHeight'])
211 optWidth = config.nearestTivoWidth(vInfo['vWidth'])
212 if optHeight < TIVO_HEIGHT:
213 TIVO_HEIGHT = optHeight
214 if optWidth < TIVO_WIDTH:
215 TIVO_WIDTH = optWidth
217 d = gcd(vInfo['vHeight'], vInfo['vWidth'])
218 ratio = vInfo['vWidth'] * 100 / vInfo['vHeight']
219 rheight, rwidth = vInfo['vHeight'] / d, vInfo['vWidth'] / d
221 logger.debug(('File=%s vCodec=%s vWidth=%s vHeight=%s vFps=%s ' +
222 'millisecs=%s ratio=%s rheight=%s rwidth=%s ' +
223 'TIVO_HEIGHT=%s TIVO_WIDTH=%s') % (inFile,
224 vInfo['vCodec'], vInfo['vWidth'], vInfo['vHeight'],
225 vInfo['vFps'], vInfo['millisecs'], ratio, rheight,
226 rwidth, TIVO_HEIGHT, TIVO_WIDTH))
228 multiplier16by9 = (16.0 * TIVO_HEIGHT) / (9.0 * TIVO_WIDTH)
229 multiplier4by3 = (4.0 * TIVO_HEIGHT) / (3.0 * TIVO_WIDTH)
231 if config.isHDtivo(tsn) and not optres:
232 if config.getPixelAR(0):
233 if vInfo['par2'] == None:
234 npar = config.getPixelAR(1)
235 else:
236 npar = vInfo['par2']
238 # adjust for pixel aspect ratio, if set, because TiVo
239 # expects square pixels
241 if npar < 1.0:
242 return ['-s', str(vInfo['vWidth']) + 'x' +
243 str(int(math.ceil(vInfo['vHeight'] / npar)))]
244 elif npar > 1.0:
245 # FFMPEG expects width to be a multiple of two
247 return ['-s', str(int(math.ceil(vInfo['vWidth'] * npar /
248 2.0) * 2)) + 'x' + str(vInfo['vHeight'])]
250 if vInfo['vHeight'] <= TIVO_HEIGHT:
251 # pass all resolutions to S3, except heights greater than
252 # conf height
253 return []
254 # else, resize video.
256 if (rwidth, rheight) in [(1, 1)] and vInfo['par1'] == '8:9':
257 logger.debug('File + PAR is within 4:3.')
258 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
260 elif ((rwidth, rheight) in [(4, 3), (10, 11), (15, 11), (59, 54),
261 (59, 72), (59, 36), (59, 54)] or
262 vInfo['dar1'] == '4:3'):
263 logger.debug('File is within 4:3 list.')
264 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
266 elif (((rwidth, rheight) in [(16, 9), (20, 11), (40, 33), (118, 81),
267 (59, 27)] or vInfo['dar1'] == '16:9')
268 and (aspect169 or config.get169Letterbox(tsn))):
269 logger.debug('File is within 16:9 list and 16:9 allowed.')
271 if config.get169Blacklist(tsn) or (aspect169 and
272 config.get169Letterbox(tsn)):
273 return ['-aspect', '4:3', '-s', '%sx%s' %
274 (TIVO_WIDTH, TIVO_HEIGHT)]
275 else:
276 return ['-aspect', '16:9', '-s', '%sx%s' %
277 (TIVO_WIDTH, TIVO_HEIGHT)]
278 else:
279 settings = []
281 # If video is wider than 4:3 add top and bottom padding
283 if ratio > 133: # Might be 16:9 file, or just need padding on
284 # top and bottom
286 if aspect169 and ratio > 135: # If file would fall in 4:3
287 # assume it is supposed to be 4:3
289 if ratio > 177: # too short needs padding top and bottom
290 endHeight = int(((TIVO_WIDTH * vInfo['vHeight']) /
291 vInfo['vWidth']) * multiplier16by9)
292 settings.append('-aspect')
293 if (config.get169Blacklist(tsn) or
294 config.get169Letterbox(tsn)):
295 settings.append('4:3')
296 else:
297 settings.append('16:9')
298 if endHeight % 2:
299 endHeight -= 1
300 if endHeight < TIVO_HEIGHT * 0.99:
301 settings.append('-s')
302 settings.append('%sx%s' % (TIVO_WIDTH, endHeight))
304 topPadding = ((TIVO_HEIGHT - endHeight) / 2)
305 if topPadding % 2:
306 topPadding -= 1
308 settings.append('-padtop')
309 settings.append(str(topPadding))
310 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
311 settings.append('-padbottom')
312 settings.append(str(bottomPadding))
313 else: # if only very small amount of padding
314 # needed, then just stretch it
315 settings.append('-s')
316 settings.append('%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT))
318 logger.debug(('16:9 aspect allowed, file is wider ' +
319 'than 16:9 padding top and bottom\n%s') %
320 ' '.join(settings))
322 else: # too skinny needs padding on left and right.
323 endWidth = int((TIVO_HEIGHT * vInfo['vWidth']) /
324 (vInfo['vHeight'] * multiplier16by9))
325 settings.append('-aspect')
326 if (config.get169Blacklist(tsn) or
327 config.get169Letterbox(tsn)):
328 settings.append('4:3')
329 else:
330 settings.append('16:9')
331 if endWidth % 2:
332 endWidth -= 1
333 if endWidth < (TIVO_WIDTH - 10):
334 settings.append('-s')
335 settings.append('%sx%s' % (endWidth, TIVO_HEIGHT))
337 leftPadding = ((TIVO_WIDTH - endWidth) / 2)
338 if leftPadding % 2:
339 leftPadding -= 1
341 settings.append('-padleft')
342 settings.append(str(leftPadding))
343 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
344 settings.append('-padright')
345 settings.append(str(rightPadding))
346 else: # if only very small amount of padding needed,
347 # then just stretch it
348 settings.append('-s')
349 settings.append('%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT))
350 logger.debug(('16:9 aspect allowed, file is narrower ' +
351 'than 16:9 padding left and right\n%s') %
352 ' '.join(settings))
353 else: # this is a 4:3 file or 16:9 output not allowed
354 multiplier = multiplier4by3
355 settings.append('-aspect')
356 if ratio > 135 and config.get169Letterbox(tsn):
357 settings.append('16:9')
358 multiplier = multiplier16by9
359 else:
360 settings.append('4:3')
361 endHeight = int(((TIVO_WIDTH * vInfo['vHeight']) /
362 vInfo['vWidth']) * multiplier)
363 if endHeight % 2:
364 endHeight -= 1
365 if endHeight < TIVO_HEIGHT * 0.99:
366 settings.append('-s')
367 settings.append('%sx%s' % (TIVO_WIDTH, endHeight))
369 topPadding = ((TIVO_HEIGHT - endHeight)/2)
370 if topPadding % 2:
371 topPadding -= 1
373 settings.append('-padtop')
374 settings.append(str(topPadding))
375 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
376 settings.append('-padbottom')
377 settings.append(str(bottomPadding))
378 else: # if only very small amount of padding needed,
379 # then just stretch it
380 settings.append('-s')
381 settings.append('%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT))
382 logging.debug(('File is wider than 4:3 padding ' +
383 'top and bottom\n%s') % ' '.join(settings))
385 return settings
387 # If video is taller than 4:3 add left and right padding, this
388 # is rare. All of these files will always be sent in an aspect
389 # ratio of 4:3 since they are so narrow.
391 else:
392 endWidth = int((TIVO_HEIGHT * vInfo['vWidth']) /
393 (vInfo['vHeight'] * multiplier4by3))
394 settings.append('-aspect')
395 settings.append('4:3')
396 if endWidth % 2:
397 endWidth -= 1
398 if endWidth < (TIVO_WIDTH * 0.99):
399 settings.append('-s')
400 settings.append('%sx%s' % (endWidth, TIVO_HEIGHT))
402 leftPadding = ((TIVO_WIDTH - endWidth) / 2)
403 if leftPadding % 2:
404 leftPadding -= 1
406 settings.append('-padleft')
407 settings.append(str(leftPadding))
408 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
409 settings.append('-padright')
410 settings.append(str(rightPadding))
411 else: # if only very small amount of padding needed, then
412 # just stretch it
413 settings.append('-s')
414 settings.append('%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT))
416 logger.debug('File is taller than 4:3 padding left and right\n%s'
417 % ' '.join(settings))
419 return settings
421 def tivo_compatible(inFile, tsn=''):
422 supportedModes = [(720, 480), (704, 480), (544, 480),
423 (528, 480), (480, 480), (352, 480)]
424 vInfo = video_info(inFile)
426 while True:
427 if (inFile[-5:]).lower() == '.tivo':
428 message = (True, 'TRANSCODE=NO, ends with .tivo.')
429 break
431 if not vInfo['vCodec'] == 'mpeg2video':
432 #print 'Not Tivo Codec'
433 message = (False, 'TRANSCODE=YES, vCodec %s not compatible.' %
434 vInfo['vCodec'])
435 break
437 if os.path.splitext(inFile)[-1].lower() in ('.ts', '.mpv',
438 '.tp', '.dvr-ms'):
439 message = (False, 'TRANSCODE=YES, ext %s not compatible.' %
440 os.path.splitext(inFile)[-1])
441 break
443 if vInfo['aCodec'] == 'dca':
444 message = (False, 'TRANSCODE=YES, aCodec %s not compatible.' %
445 vInfo['aCodec'])
446 break
448 if vInfo['aCodec'] != None:
449 if (not vInfo['aKbps'] or
450 int(vInfo['aKbps']) > config.getMaxAudioBR(tsn)):
451 message = (False, ('TRANSCODE=YES, %s kbps exceeds max ' +
452 'audio bitrate.') % vInfo['aKbps'])
453 break
455 if vInfo['kbps'] != None:
456 abit = max('0', vInfo['aKbps'])
457 if (int(vInfo['kbps']) - int(abit) >
458 config.strtod(config.getMaxVideoBR()) / 1000):
459 message = (False, ('TRANSCODE=YES, %s kbps exceeds max ' +
460 'video bitrate.') % vInfo['kbps'])
461 break
462 else:
463 message = (False, 'TRANSCODE=YES, %s kbps not supported.' %
464 vInfo['kbps'])
465 break
467 if config.getAudioLang(tsn):
468 if vInfo['mapAudio'][0][0] != select_audiolang(inFile, tsn)[-3:]:
469 message = (False, ('TRANSCODE=YES, %s preferred audio ' +
470 'track exists.') % config.getAudioLang(tsn))
471 break
473 if config.isHDtivo(tsn):
474 if vInfo['par2'] != 1.0:
475 if config.getPixelAR(0):
476 if vInfo['par2'] != None or config.getPixelAR(1) != 1.0:
477 message = (False, 'TRANSCODE=YES, %s not correct PAR.'
478 % vInfo['par2'])
479 break
480 message = (True, 'TRANSCODE=NO, HD Tivo detected, skipping ' +
481 'remaining tests.')
482 break
484 if not vInfo['vFps'] == '29.97':
485 #print 'Not Tivo fps'
486 message = (False, 'TRANSCODE=YES, %s vFps, should be 29.97.' %
487 vInfo['vFps'])
488 break
490 if ((config.get169Blacklist(tsn) and not config.get169Setting(tsn))
491 or (config.get169Letterbox(tsn) and config.get169Setting(tsn))):
492 if vInfo['dar1'] == None or not vInfo['dar1'] in ('4:3', '8:9'):
493 message = (False, ('TRANSCODE=YES, DAR %s not supported ' +
494 'by BLACKLIST_169 tivos.') % vInfo['dar1'])
495 break
497 for mode in supportedModes:
498 if mode == (vInfo['vWidth'], vInfo['vHeight']):
499 message = (True, 'TRANSCODE=NO, %s x %s is valid.' %
500 (vInfo['vWidth'], vInfo['vHeight']))
501 break
502 #print 'Not Tivo dimensions'
503 message = (False, 'TRANSCODE=YES, %s x %s not in supported modes.'
504 % (vInfo['vWidth'], vInfo['vHeight']))
505 break
507 logger.debug('%s, %s' % (message, inFile))
508 return message
511 def video_info(inFile):
512 vInfo = dict()
513 mtime = os.stat(inFile).st_mtime
514 if inFile != videotest:
515 if inFile in info_cache and info_cache[inFile][0] == mtime:
516 logging.debug('CACHE HIT! %s' % inFile)
517 return info_cache[inFile][1]
519 vInfo['Supported'] = True
521 if (inFile[-5:]).lower() == '.tivo':
522 vInfo['millisecs'] = 0
523 info_cache[inFile] = (mtime, vInfo)
524 logger.debug('VALID, ends in .tivo. %s' % inFile)
525 return vInfo
527 cmd = [ffmpeg_path(), '-i', inFile]
528 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
529 err_tmp = tempfile.TemporaryFile()
530 ffmpeg = subprocess.Popen(cmd, stderr=err_tmp, stdout=subprocess.PIPE,
531 stdin=subprocess.PIPE)
533 # wait 10 sec if ffmpeg is not back give up
534 for i in xrange(200):
535 time.sleep(.05)
536 if not ffmpeg.poll() == None:
537 break
539 if ffmpeg.poll() == None:
540 kill(ffmpeg.pid)
541 vInfo['Supported'] = False
542 info_cache[inFile] = (mtime, vInfo)
543 return vInfo
545 err_tmp.seek(0)
546 output = err_tmp.read()
547 err_tmp.close()
548 logging.debug('ffmpeg output=%s' % output)
550 rezre = re.compile(r'.*Video: ([^,]+),.*')
551 x = rezre.search(output)
552 if x:
553 vInfo['vCodec'] = x.group(1)
554 else:
555 vInfo['vCodec'] = ''
556 vInfo['Supported'] = False
557 logger.debug('failed at vCodec')
559 rezre = re.compile(r'.*Video: .+, (\d+)x(\d+)[, ].*')
560 x = rezre.search(output)
561 if x:
562 vInfo['vWidth'] = int(x.group(1))
563 vInfo['vHeight'] = int(x.group(2))
564 else:
565 vInfo['vWidth'] = ''
566 vInfo['vHeight'] = ''
567 vInfo['Supported'] = False
568 logger.debug('failed at vWidth/vHeight')
570 rezre = re.compile(r'.*Video: .+, (.+) (?:fps|tb).*')
571 x = rezre.search(output)
572 if x:
573 vInfo['vFps'] = x.group(1)
575 # Allow override only if it is mpeg2 and frame rate was doubled
576 # to 59.94
578 if vInfo['vCodec'] == 'mpeg2video' and vInfo['vFps'] != '29.97':
579 # First look for the build 7215 version
580 rezre = re.compile(r'.*film source: 29.97.*')
581 x = rezre.search(output.lower())
582 if x:
583 logger.debug('film source: 29.97 setting vFps to 29.97')
584 vInfo['vFps'] = '29.97'
585 else:
586 # for build 8047:
587 rezre = re.compile(r'.*frame rate differs from container ' +
588 r'frame rate: 29.97.*')
589 logger.debug('Bug in VideoReDo')
590 x = rezre.search(output.lower())
591 if x:
592 vInfo['vFps'] = '29.97'
593 else:
594 vInfo['vFps'] = ''
595 vInfo['Supported'] = False
596 logger.debug('failed at vFps')
598 durre = re.compile(r'.*Duration: ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+),')
599 d = durre.search(output)
601 if d:
602 vInfo['millisecs'] = ((int(d.group(1)) * 3600 +
603 int(d.group(2)) * 60 +
604 int(d.group(3))) * 1000 +
605 int(d.group(4)) * (10 ** (3 - len(d.group(4)))))
606 else:
607 vInfo['millisecs'] = 0
609 # get bitrate of source for tivo compatibility test.
610 rezre = re.compile(r'.*bitrate: (.+) (?:kb/s).*')
611 x = rezre.search(output)
612 if x:
613 vInfo['kbps'] = x.group(1)
614 else:
615 vInfo['kbps'] = None
616 logger.debug('failed at kbps')
618 # get audio bitrate of source for tivo compatibility test.
619 rezre = re.compile(r'.*Audio: .+, (.+) (?:kb/s).*')
620 x = rezre.search(output)
621 if x:
622 vInfo['aKbps'] = x.group(1)
623 else:
624 vInfo['aKbps'] = None
625 logger.debug('failed at aKbps')
627 # get audio codec of source for tivo compatibility test.
628 rezre = re.compile(r'.*Audio: ([^,]+),.*')
629 x = rezre.search(output)
630 if x:
631 vInfo['aCodec'] = x.group(1)
632 else:
633 vInfo['aCodec'] = None
634 logger.debug('failed at aCodec')
636 # get audio frequency of source for tivo compatibility test.
637 rezre = re.compile(r'.*Audio: .+, (.+) (?:Hz).*')
638 x = rezre.search(output)
639 if x:
640 vInfo['aFreq'] = x.group(1)
641 else:
642 vInfo['aFreq'] = None
643 logger.debug('failed at aFreq')
645 # get par.
646 rezre = re.compile(r'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
647 x = rezre.search(output)
648 if x and x.group(1) != "0" and x.group(2) != "0":
649 vInfo['par1'] = x.group(1) + ':' + x.group(2)
650 vInfo['par2'] = float(x.group(1)) / float(x.group(2))
651 else:
652 vInfo['par1'], vInfo['par2'] = None, None
654 # get dar.
655 rezre = re.compile(r'.*Video: .+DAR ([0-9]+):([0-9]+).*')
656 x = rezre.search(output)
657 if x and x.group(1) != "0" and x.group(2) != "0":
658 vInfo['dar1'] = x.group(1) + ':' + x.group(2)
659 vInfo['dar2'] = float(x.group(1)) / float(x.group(2))
660 else:
661 vInfo['dar1'], vInfo['dar2'] = None, None
663 # get Video Stream mapping.
664 rezre = re.compile(r'([0-9]+\.[0-9]+).*: Video:.*')
665 x = rezre.search(output)
666 if x:
667 vInfo['mapVideo'] = x.group(1)
668 else:
669 vInfo['mapVideo'] = None
670 logger.debug('failed at mapVideo')
672 # get Audio Stream mapping.
673 rezre = re.compile(r'([0-9]+\.[0-9]+)(.*): Audio:.*')
674 x = rezre.search(output)
675 amap = []
676 if x:
677 for x in rezre.finditer(output):
678 amap.append(x.groups())
679 else:
680 amap.append(('', ''))
681 logger.debug('failed at mapAudio')
682 vInfo['mapAudio'] = amap
684 videoPlugin = GetPlugin('video')
685 metadata = videoPlugin.getMetadataFromTxt(inFile)
687 for key in metadata:
688 if key.startswith('Override_'):
689 vInfo['Supported'] = True
690 if key.startswith('Override_mapAudio'):
691 audiomap = dict(vInfo['mapAudio'])
692 stream = key.replace('Override_mapAudio', '').strip()
693 if stream in audiomap:
694 newaudiomap = (stream, metadata[key])
695 audiomap.update([newaudiomap])
696 vInfo['mapAudio'] = sorted(audiomap.items(),
697 key=lambda (k,v): (k,v))
698 elif key.startswith('Override_millisecs'):
699 vInfo[key.replace('Override_', '')] = int(metadata[key])
700 else:
701 vInfo[key.replace('Override_', '')] = metadata[key]
703 info_cache[inFile] = (mtime, vInfo)
704 logger.debug("; ".join(["%s=%s" % (k, v) for k, v in vInfo.items()]))
705 return vInfo
707 def video_check(inFile, cmd_string):
708 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
709 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
710 try:
711 shutil.copyfileobj(ffmpeg.stdout, open(videotest, 'wb'))
712 return True
713 except:
714 kill(ffmpeg.pid)
715 return False
717 def supported_format(inFile):
718 if video_info(inFile)['Supported']:
719 return True
720 else:
721 logger.debug('FALSE, file not supported %s' % inFile)
722 return False
724 def kill(pid):
725 logger.debug('killing pid=%s' % str(pid))
726 if mswindows:
727 win32kill(pid)
728 else:
729 import os, signal
730 os.kill(pid, signal.SIGTERM)
732 def win32kill(pid):
733 import ctypes
734 handle = ctypes.windll.kernel32.OpenProcess(1, False, pid)
735 ctypes.windll.kernel32.TerminateProcess(handle, -1)
736 ctypes.windll.kernel32.CloseHandle(handle)
738 def gcd(a, b):
739 while b:
740 a, b = b, a % b
741 return a