80 columns, spacing and line continuations.
[pyTivo/wgw.git] / plugins / video / transcode.py
blob944da5cdf6e9e79939af7d53b5e5be8cda947156
1 import subprocess, shutil, os, re, sys, tempfile, ConfigParser, time, lrucache, math
2 import config
3 import logging
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']
13 def ffmpeg_path():
14 return config.get('Server', 'ffmpeg')
16 # XXX BIG HACK
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")
27 if mswindows:
28 patchSubprocess()
30 def output_video(inFile, outFile, tsn=''):
31 if tivo_compatable(inFile, tsn)[0]:
32 logger.debug('%s is tivo compatible' % inFile)
33 f = file(inFile, 'rb')
34 shutil.copyfileobj(f, outFile)
35 f.close()
36 else:
37 logger.debug('%s is not tivo compatible' % inFile)
38 transcode(False, inFile, outFile, tsn)
40 def transcode(isQuery, inFile, outFile, tsn=''):
42 settings = {}
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(tsn)
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(isQuery, inFile, tsn)
53 settings['audio_lang'] = select_audiolang(inFile, tsn)
54 settings['ffmpeg_pram'] = select_ffmpegprams(tsn)
55 settings['format'] = select_format(tsn)
57 if isQuery:
58 return settings
60 cmd_string = config.getFFmpegTemplate(tsn) % settings
62 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
63 logging.debug('transcoding to tivo model '+tsn[:3]+' using ffmpeg command:')
64 logging.debug(' '.join(cmd))
65 ffmpeg = subprocess.Popen(cmd, bufsize=512*1024, stdout=subprocess.PIPE)
67 try:
68 shutil.copyfileobj(ffmpeg.stdout, outFile)
69 except:
70 kill(ffmpeg.pid)
72 def select_audiocodec(isQuery, inFile, tsn = ''):
73 # Default, compatible with all TiVo's
74 codec = 'ac3'
75 vInfo = video_info(inFile)
76 codectype = vInfo['vCodec']
77 if config.getAudioCodec(tsn) == None:
78 if vInfo['aCodec'] in ('ac3', 'liba52', 'mp2'):
79 if vInfo['aKbps'] == None:
80 if not isQuery:
81 cmd_string = '-y -vcodec mpeg2video -r 29.97 ' + \
82 '-b 1000k -acodec copy ' + \
83 select_audiolang(inFile, tsn) + \
84 ' -t 00:00:01 -f vob -'
85 if video_check(inFile, cmd_string):
86 vInfo = video_info(videotest)
87 else:
88 codec = 'TBD'
89 if (not vInfo['aKbps'] == None and
90 int(vInfo['aKbps']) <= config.getMaxAudioBR(tsn)):
91 # compatible codec and bitrate, do not reencode audio
92 codec = 'copy'
93 else:
94 codec = config.getAudioCodec(tsn)
95 copyts = ' -copyts'
96 if ((codec == 'copy' and config.getCopyTS(tsn).lower() == 'none'
97 and codectype == 'mpeg2video') or
98 config.getCopyTS(tsn).lower() == 'false'):
99 copyts = ''
100 return '-acodec ' + codec + copyts
102 def select_audiofr(inFile, tsn):
103 freq = '48000' #default
104 vInfo = video_info(inFile)
105 if not vInfo['aFreq'] == None and vInfo['aFreq'] in ('44100', '48000'):
106 # compatible frequency
107 freq = vInfo['aFreq']
108 if config.getAudioFR(tsn) != None:
109 freq = config.getAudioFR(tsn)
110 return '-ar '+freq
112 def select_audioch(tsn):
113 if config.getAudioCH(tsn) != None:
114 return '-ac '+config.getAudioCH(tsn)
115 return ''
117 def select_audiolang(inFile, tsn):
118 vInfo = video_info(inFile)
119 if config.getAudioLang(tsn) != None and vInfo['mapVideo'] != None:
120 stream = vInfo['mapAudio'][0][0]
121 langmatch = []
122 for lang in config.getAudioLang(tsn).replace(' ','').lower().split(','):
123 for s, l in vInfo['mapAudio']:
124 if lang in s+l.replace(' ','').lower():
125 langmatch.append(s)
126 stream = s
127 break
128 if langmatch: break
129 if stream is not '':
130 return '-map '+vInfo['mapVideo']+' -map '+stream
131 return ''
133 def select_videofps(inFile, tsn):
134 vInfo = video_info(inFile)
135 fps = '-r 29.97' #default
136 if config.isHDtivo(tsn) and vInfo['vFps'] not in BAD_MPEG_FPS:
137 fps = ' '
138 if config.getVideoFPS(tsn) != None:
139 fps = '-r '+config.getVideoFPS(tsn)
140 return fps
142 def select_videocodec(tsn):
143 codec = 'mpeg2video' #default
144 if config.getVideoCodec(tsn) != None:
145 codec = config.getVideoCodec(tsn)
146 return '-vcodec '+codec
148 def select_videobr(inFile, tsn):
149 return '-b ' + str(select_videostr(inFile, tsn) / 1000) + 'k'
151 def select_videostr(inFile, tsn):
152 video_str = config.strtod(config.getVideoBR(tsn))
153 if config.isHDtivo(tsn):
154 vInfo = video_info(inFile)
155 if vInfo['kbps'] != None and config.getVideoPCT() > 0:
156 video_percent = int(vInfo['kbps']) * 10 * config.getVideoPCT()
157 video_str = max(video_str, video_percent)
158 video_str = int(min(config.strtod(config.getMaxVideoBR()) * 0.95,
159 video_str))
160 return video_str
162 def select_audiobr(tsn):
163 return '-ab '+config.getAudioBR(tsn)
165 def select_maxvideobr():
166 return '-maxrate '+config.getMaxVideoBR()
168 def select_buffsize(tsn):
169 return '-bufsize '+config.getBuffSize(tsn)
171 def select_ffmpegprams(tsn):
172 if config.getFFmpegPrams(tsn) != None:
173 return config.getFFmpegPrams(tsn)
174 return ''
176 def select_format(tsn):
177 fmt = 'vob'
178 if config.getFormat(tsn) != None:
179 fmt = config.getFormat(tsn)
180 return '-f '+fmt+' -'
182 def select_aspect(inFile, tsn = ''):
183 TIVO_WIDTH = config.getTivoWidth(tsn)
184 TIVO_HEIGHT = config.getTivoHeight(tsn)
186 vInfo = video_info(inFile)
188 logging.debug('tsn: %s' % tsn)
190 aspect169 = config.get169Setting(tsn)
192 logging.debug('aspect169:%s' % aspect169)
194 optres = config.getOptres(tsn)
196 logging.debug('optres:%s' % optres)
198 if optres:
199 optHeight = config.nearestTivoHeight(vInfo['vHeight'])
200 optWidth = config.nearestTivoWidth(vInfo['vWidth'])
201 if optHeight < TIVO_HEIGHT:
202 TIVO_HEIGHT = optHeight
203 if optWidth < TIVO_WIDTH:
204 TIVO_WIDTH = optWidth
206 d = gcd(vInfo['vHeight'], vInfo['vWidth'])
207 ratio = (vInfo['vWidth'] * 100) / vInfo['vHeight']
208 rheight, rwidth = vInfo['vHeight'] / d, vInfo['vWidth'] / d
210 logger.debug('File=%s vCodec=%s vWidth=%s vHeight=%s vFps=%s ' +
211 'millisecs=%s ratio=%s rheight=%s rwidth=%s ' +
212 'TIVO_HEIGHT=%s TIVO_WIDTH=%s' % (inFile,
213 vInfo['vCodec'], vInfo['vWidth'], vInfo['vHeight'],
214 vInfo['vFps'], vInfo['millisecs'], ratio, rheight,
215 rwidth, TIVO_HEIGHT, TIVO_WIDTH))
217 multiplier16by9 = (16.0 * TIVO_HEIGHT) / (9.0 * TIVO_WIDTH)
218 multiplier4by3 = (4.0 * TIVO_HEIGHT) / (3.0 * TIVO_WIDTH)
220 if config.isHDtivo(tsn) and not optres:
221 if config.getPixelAR(0):
222 if vInfo['par2'] == None:
223 npar = config.getPixelAR(1)
224 else:
225 npar = vInfo['par2']
227 # adjust for pixel aspect ratio, if set, because TiVo
228 # expects square pixels
230 if npar < 1.0:
231 return ['-s', str(vInfo['vWidth']) + 'x' +
232 str(int(math.ceil(vInfo['vHeight'] / npar)))]
233 elif npar > 1.0:
234 # FFMPEG expects width to be a multiple of two
236 return ['-s', str(int(math.ceil(vInfo['vWidth'] * npar /
237 2.0) * 2)) + 'x' + str(vInfo['vHeight'])]
239 if vInfo['vHeight'] <= TIVO_HEIGHT:
240 # pass all resolutions to S3, except heights greater than
241 # conf height
242 return []
243 # else, resize video.
245 if (rwidth, rheight) in [(1, 1)] and vInfo['par1'] == '8:9':
246 logger.debug('File + PAR is within 4:3.')
247 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' +
248 str(TIVO_HEIGHT)]
250 elif (rwidth, rheight) in [(4, 3), (10, 11), (15, 11), (59, 54),
251 (59, 72), (59, 36), (59, 54)] or
252 vInfo['dar1'] == '4:3':
253 logger.debug('File is within 4:3 list.')
254 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' +
255 str(TIVO_HEIGHT)]
257 elif (((rwidth, rheight) in [(16, 9), (20, 11), (40, 33), (118, 81),
258 (59, 27)] or vInfo['dar1'] == '16:9')
259 and (aspect169 or config.get169Letterbox(tsn))):
260 logger.debug('File is within 16:9 list and 16:9 allowed.')
262 if config.get169Blacklist(tsn) or (aspect169 and
263 config.get169Letterbox(tsn)):
264 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' +
265 str(TIVO_HEIGHT)]
266 else:
267 return ['-aspect', '16:9', '-s', str(TIVO_WIDTH) + 'x' +
268 str(TIVO_HEIGHT)]
269 else:
270 settings = []
272 # If video is wider than 4:3 add top and bottom padding
274 if (ratio > 133): # Might be 16:9 file, or just need padding on
275 # top and bottom
277 if aspect169 and (ratio > 135): # If file would fall in 4:3
278 # assume it is supposed to be 4:3
280 if (ratio > 177): # too short needs padding top and bottom
281 endHeight = int(((TIVO_WIDTH * vInfo['vHeight']) /
282 vInfo['vWidth']) * multiplier16by9)
283 settings.append('-aspect')
284 if (config.get169Blacklist(tsn) or
285 config.get169Letterbox(tsn)):
286 settings.append('4:3')
287 else:
288 settings.append('16:9')
289 if endHeight % 2:
290 endHeight -= 1
291 if endHeight < TIVO_HEIGHT * 0.99:
292 settings.append('-s')
293 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
295 topPadding = ((TIVO_HEIGHT - endHeight) / 2)
296 if topPadding % 2:
297 topPadding -= 1
299 settings.append('-padtop')
300 settings.append(str(topPadding))
301 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
302 settings.append('-padbottom')
303 settings.append(str(bottomPadding))
304 else: # if only very small amount of padding
305 # needed, then just stretch it
306 settings.append('-s')
307 settings.append(str(TIVO_WIDTH) + 'x' +
308 str(TIVO_HEIGHT))
310 logger.debug('16:9 aspect allowed, file is wider ' +
311 'than 16:9 padding top and bottom\n%s' %
312 ' '.join(settings))
314 else: # too skinny needs padding on left and right.
315 endWidth = int((TIVO_HEIGHT * vInfo['vWidth']) /
316 (vInfo['vHeight'] * multiplier16by9))
317 settings.append('-aspect')
318 if (config.get169Blacklist(tsn) or
319 config.get169Letterbox(tsn)):
320 settings.append('4:3')
321 else:
322 settings.append('16:9')
323 if endWidth % 2:
324 endWidth -= 1
325 if endWidth < (TIVO_WIDTH - 10):
326 settings.append('-s')
327 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
329 leftPadding = ((TIVO_WIDTH - endWidth) / 2)
330 if leftPadding % 2:
331 leftPadding -= 1
333 settings.append('-padleft')
334 settings.append(str(leftPadding))
335 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
336 settings.append('-padright')
337 settings.append(str(rightPadding))
338 else: # if only very small amount of padding needed,
339 # then just stretch it
340 settings.append('-s')
341 settings.append(str(TIVO_WIDTH) + 'x' +
342 str(TIVO_HEIGHT))
343 logger.debug('16:9 aspect allowed, file is narrower ' +
344 'than 16:9 padding left and right\n%s' %
345 ' '.join(settings))
346 else: # this is a 4:3 file or 16:9 output not allowed
347 multiplier = multiplier4by3
348 settings.append('-aspect')
349 if ratio > 135 and config.get169Letterbox(tsn):
350 settings.append('16:9')
351 multiplier = multiplier16by9
352 else:
353 settings.append('4:3')
354 endHeight = int(((TIVO_WIDTH * vInfo['vHeight']) /
355 vInfo['vWidth']) * multiplier)
356 if endHeight % 2:
357 endHeight -= 1
358 if endHeight < TIVO_HEIGHT * 0.99:
359 settings.append('-s')
360 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
362 topPadding = ((TIVO_HEIGHT - endHeight)/2)
363 if topPadding % 2:
364 topPadding -= 1
366 settings.append('-padtop')
367 settings.append(str(topPadding))
368 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
369 settings.append('-padbottom')
370 settings.append(str(bottomPadding))
371 else: # if only very small amount of padding needed,
372 # then just stretch it
373 settings.append('-s')
374 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
375 logging.debug('File is wider than 4:3 padding ' +
376 'top and bottom\n%s' % ' '.join(settings))
378 return settings
380 # If video is taller than 4:3 add left and right padding, this
381 # is rare. All of these files will always be sent in an aspect
382 # ratio of 4:3 since they are so narrow.
384 else:
385 endWidth = int((TIVO_HEIGHT * vInfo['vWidth']) /
386 (vInfo['vHeight'] * multiplier4by3))
387 settings.append('-aspect')
388 settings.append('4:3')
389 if endWidth % 2:
390 endWidth -= 1
391 if endWidth < (TIVO_WIDTH * 0.99):
392 settings.append('-s')
393 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
395 leftPadding = ((TIVO_WIDTH - endWidth) / 2)
396 if leftPadding % 2:
397 leftPadding -= 1
399 settings.append('-padleft')
400 settings.append(str(leftPadding))
401 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
402 settings.append('-padright')
403 settings.append(str(rightPadding))
404 else: # if only very small amount of padding needed, then
405 # just stretch it
406 settings.append('-s')
407 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
409 logger.debug('File is taller than 4:3 padding left and right\n%s'
410 % ' '.join(settings))
412 return settings
414 def tivo_compatable(inFile, tsn = ''):
415 supportedModes = [[720, 480], [704, 480], [544, 480], [528, 480],
416 [480, 480], [352, 480]]
417 vInfo = video_info(inFile)
419 while True:
420 if (inFile[-5:]).lower() == '.tivo':
421 message = (True, 'TRANSCODE=NO, ends with .tivo.')
422 break
424 if not vInfo['vCodec'] == 'mpeg2video':
425 #print 'Not Tivo Codec'
426 message = (False, 'TRANSCODE=YES, vCodec %s not compatible.' %
427 vInfo['vCodec'])
428 break
430 if os.path.splitext(inFile)[-1].lower() in ('.ts', '.mpv',
431 '.tp', '.dvr-ms'):
432 message = (False, 'TRANSCODE=YES, ext %s not compatible.' %
433 os.path.splitext(inFile)[-1])
434 break
436 if vInfo['aCodec'] == 'dca':
437 message = (False, 'TRANSCODE=YES, aCodec %s not compatible.' %
438 vInfo['aCodec'])
439 break
441 if vInfo['aCodec'] != None:
442 if (not vInfo['aKbps'] or
443 int(vInfo['aKbps']) > config.getMaxAudioBR(tsn)):
444 message = (False, 'TRANSCODE=YES, %s kbps exceeds max ' +
445 'audio bitrate.' % vInfo['aKbps'])
446 break
448 if vInfo['kbps'] != None:
449 abit = max('0', vInfo['aKbps'])
450 if (int(vInfo['kbps']) - int(abit) >
451 config.strtod(config.getMaxVideoBR()) / 1000):
452 message = (False, 'TRANSCODE=YES, %s kbps exceeds max ' +
453 'video bitrate.' % vInfo['kbps']
454 break
455 else:
456 message = (False, 'TRANSCODE=YES, %s kbps not supported.' %
457 vInfo['kbps'])
458 break
460 if config.getAudioLang(tsn) is not None:
461 if vInfo['mapAudio'][0][0] != select_audiolang(inFile, tsn)[-3:]:
462 message = (False, 'TRANSCODE=YES, %s preferred audio ' +
463 'track exists.' % config.getAudioLang(tsn))
464 break
466 if config.isHDtivo(tsn):
467 if vInfo['par2'] != 1.0:
468 if config.getPixelAR(0):
469 if vInfo['par2'] != None or config.getPixelAR(1) != 1.0:
470 message = (False, 'TRANSCODE=YES, %s not correct PAR.'
471 % vInfo['par2'])
472 break
473 message = (True, 'TRANSCODE=NO, HD Tivo detected, skipping ' +
474 'remaining tests.')
475 break
477 if not vInfo['vFps'] == '29.97':
478 #print 'Not Tivo fps'
479 message = (False, 'TRANSCODE=YES, %s vFps, should be 29.97.' %
480 vInfo['vFps'])
481 break
483 if ((config.get169Blacklist(tsn) and not config.get169Setting(tsn))
484 or (config.get169Letterbox(tsn) and config.get169Setting(tsn))):
485 if vInfo['dar1'] == None or not vInfo['dar1'] in ('4:3', '8:9'):
486 message = (False, 'TRANSCODE=YES, DAR %s not supported ' +
487 'by BLACKLIST_169 tivos.' % vInfo['dar1'])
488 break
490 for mode in supportedModes:
491 if (mode[0], mode[1]) == (vInfo['vWidth'], vInfo['vHeight']):
492 message = (True, 'TRANSCODE=NO, %s x %s is valid.' %
493 (vInfo['vWidth'], vInfo['vHeight']))
494 break
495 #print 'Not Tivo dimensions'
496 message = (False, 'TRANSCODE=YES, %s x %s not in supported modes.'
497 % (vInfo['vWidth'], vInfo['vHeight']))
498 break
500 logger.debug('%s, %s' % (message, inFile))
501 return message
504 def video_info(inFile):
505 vInfo = dict()
506 mtime = os.stat(inFile).st_mtime
507 if inFile != videotest:
508 if inFile in info_cache and info_cache[inFile][0] == mtime:
509 logging.debug('CACHE HIT! %s' % inFile)
510 return info_cache[inFile][1]
512 vInfo['Supported'] = True
514 if (inFile[-5:]).lower() == '.tivo':
515 vInfo['millisecs'] = 0
516 info_cache[inFile] = (mtime, vInfo)
517 logger.debug('VALID, ends in .tivo. %s' % inFile)
518 return vInfo
520 cmd = [ffmpeg_path(), '-i', inFile ]
521 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
522 err_tmp = tempfile.TemporaryFile()
523 ffmpeg = subprocess.Popen(cmd, stderr=err_tmp, stdout=subprocess.PIPE,
524 stdin=subprocess.PIPE)
526 # wait 10 sec if ffmpeg is not back give up
527 for i in xrange(200):
528 time.sleep(.05)
529 if not ffmpeg.poll() == None:
530 break
532 if ffmpeg.poll() == None:
533 kill(ffmpeg.pid)
534 vInfo['Supported'] = False
535 info_cache[inFile] = (mtime, vInfo)
536 return vInfo
538 err_tmp.seek(0)
539 output = err_tmp.read()
540 err_tmp.close()
541 logging.debug('ffmpeg output=%s' % output)
543 rezre = re.compile(r'.*Video: ([^,]+),.*')
544 x = rezre.search(output)
545 if x:
546 vInfo['vCodec'] = x.group(1)
547 else:
548 vInfo['vCodec'] = ''
549 vInfo['Supported'] = False
550 logger.debug('failed at vCodec')
552 rezre = re.compile(r'.*Video: .+, (\d+)x(\d+)[, ].*')
553 x = rezre.search(output)
554 if x:
555 vInfo['vWidth'] = int(x.group(1))
556 vInfo['vHeight'] = int(x.group(2))
557 else:
558 vInfo['vWidth'] = ''
559 vInfo['vHeight'] = ''
560 vInfo['Supported'] = False
561 logger.debug('failed at vWidth/vHeight')
563 rezre = re.compile(r'.*Video: .+, (.+) (?:fps|tb).*')
564 x = rezre.search(output)
565 if x:
566 vInfo['vFps'] = x.group(1)
568 # Allow override only if it is mpeg2 and frame rate was doubled
569 # to 59.94
571 if (not vInfo['vFps'] == '29.97') and (vInfo['vCodec'] == 'mpeg2video'):
572 # First look for the build 7215 version
573 rezre = re.compile(r'.*film source: 29.97.*')
574 x = rezre.search(output.lower() )
575 if x:
576 logger.debug('film source: 29.97 setting vFps to 29.97')
577 vInfo['vFps'] = '29.97'
578 else:
579 # for build 8047:
580 rezre = re.compile(r'.*frame rate differs from container ' +
581 r'frame rate: 29.97.*')
582 logger.debug('Bug in VideoReDo')
583 x = rezre.search(output.lower() )
584 if x:
585 vInfo['vFps'] = '29.97'
586 else:
587 vInfo['vFps'] = ''
588 vInfo['Supported'] = False
589 logger.debug('failed at vFps')
591 durre = re.compile(r'.*Duration: ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+),')
592 d = durre.search(output)
594 if d:
595 vInfo['millisecs'] = ((int(d.group(1)) * 3600 +
596 int(d.group(2)) * 60 +
597 int(d.group(3))) * 1000 +
598 int(d.group(4)) * (10 ** (3 - len(d.group(4)))))
599 else:
600 vInfo['millisecs'] = 0
602 #get bitrate of source for tivo compatibility test.
603 rezre = re.compile(r'.*bitrate: (.+) (?:kb/s).*')
604 x = rezre.search(output)
605 if x:
606 vInfo['kbps'] = x.group(1)
607 else:
608 vInfo['kbps'] = None
609 logger.debug('failed at kbps')
611 #get audio bitrate of source for tivo compatibility test.
612 rezre = re.compile(r'.*Audio: .+, (.+) (?:kb/s).*')
613 x = rezre.search(output)
614 if x:
615 vInfo['aKbps'] = x.group(1)
616 else:
617 vInfo['aKbps'] = None
618 logger.debug('failed at aKbps')
620 #get audio codec of source for tivo compatibility test.
621 rezre = re.compile(r'.*Audio: ([^,]+),.*')
622 x = rezre.search(output)
623 if x:
624 vInfo['aCodec'] = x.group(1)
625 else:
626 vInfo['aCodec'] = None
627 logger.debug('failed at aCodec')
629 #get audio frequency of source for tivo compatibility test.
630 rezre = re.compile(r'.*Audio: .+, (.+) (?:Hz).*')
631 x = rezre.search(output)
632 if x:
633 vInfo['aFreq'] = x.group(1)
634 else:
635 vInfo['aFreq'] = None
636 logger.debug('failed at aFreq')
638 #get par.
639 rezre = re.compile(r'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
640 x = rezre.search(output)
641 if x and x.group(1) != "0" and x.group(2) != "0":
642 vInfo['par1'] = x.group(1) + ':' + x.group(2)
643 vInfo['par2'] = float(x.group(1)) / float(x.group(2))
644 else:
645 vInfo['par1'], vInfo['par2'] = None, None
647 #get dar.
648 rezre = re.compile(r'.*Video: .+DAR ([0-9]+):([0-9]+).*')
649 x = rezre.search(output)
650 if x and x.group(1) != "0" and x.group(2) != "0":
651 vInfo['dar1'] = x.group(1) + ':' + x.group(2)
652 vInfo['dar2'] = float(x.group(1)) / float(x.group(2))
653 else:
654 vInfo['dar1'], vInfo['dar2'] = None, None
656 #get Video Stream mapping.
657 rezre = re.compile(r'([0-9]+\.[0-9]+).*: Video:.*')
658 x = rezre.search(output)
659 if x:
660 vInfo['mapVideo'] = x.group(1)
661 else:
662 vInfo['mapVideo'] = None
663 logger.debug('failed at mapVideo')
666 #get Audio Stream mapping.
667 rezre = re.compile(r'([0-9]+\.[0-9]+)(.*): Audio:.*')
668 x = rezre.search(output)
669 amap = []
670 if x:
671 for x in rezre.finditer(output):
672 amap.append(x.groups())
673 else:
674 amap.append(('', ''))
675 logger.debug('failed at mapAudio')
676 vInfo['mapAudio'] = amap
679 videoPlugin = GetPlugin('video')
680 metadata = videoPlugin.getMetadataFromTxt(inFile)
682 for key in metadata:
683 if key.startswith('Override_'):
684 vInfo['Supported'] = True
685 if key.startswith('Override_mapAudio'):
686 audiomap = dict(vInfo['mapAudio'])
687 stream = key.replace('Override_mapAudio','').strip()
688 if audiomap.has_key(stream):
689 newaudiomap = (stream, metadata[key])
690 audiomap.update([newaudiomap])
691 vInfo['mapAudio'] = sorted(audiomap.items(),
692 key=lambda (k,v): (k,v))
693 elif key.startswith('Override_millisecs'):
694 vInfo[key.replace('Override_','')] = int(metadata[key])
695 else:
696 vInfo[key.replace('Override_','')] = metadata[key]
698 info_cache[inFile] = (mtime, vInfo)
699 logger.debug("; ".join(["%s=%s" % (k, v) for k, v in vInfo.items()]))
700 return vInfo
702 def video_check(inFile, cmd_string):
703 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
704 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
705 try:
706 shutil.copyfileobj(ffmpeg.stdout, open(videotest, 'wb'))
707 return True
708 except:
709 kill(ffmpeg.pid)
710 return False
712 def supported_format(inFile):
713 if video_info(inFile)['Supported']:
714 return True
715 else:
716 logger.debug('FALSE, file not supported %s' % inFile)
717 return False
719 def kill(pid):
720 logger.debug('killing pid=%s' % str(pid))
721 if mswindows:
722 win32kill(pid)
723 else:
724 import os, signal
725 os.kill(pid, signal.SIGTERM)
727 def win32kill(pid):
728 import ctypes
729 handle = ctypes.windll.kernel32.OpenProcess(1, False, pid)
730 ctypes.windll.kernel32.TerminateProcess(handle, -1)
731 ctypes.windll.kernel32.CloseHandle(handle)
733 def gcd(a,b):
734 while b:
735 a, b = b, a % b
736 return a