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