Somewhat simpler and cleaner.
[pyTivo/wgw.git] / plugins / video / transcode.py
blobee5f21f68fccc7537b6c5e3863f3af219b2f7028
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 codec = config.getAudioCodec(tsn)
86 if not codec:
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 copy_flag = config.getCopyTS(tsn)
103 copyts = ' -copyts'
104 if (codec == 'copy' and codectype == 'mpeg2video' and not copy_flag) or
105 (copy_flag and copy_flag.lower() == 'false'):
106 copyts = ''
107 return '-acodec ' + codec + copyts
109 def select_audiofr(inFile, tsn):
110 freq = '48000' #default
111 vInfo = video_info(inFile)
112 if not vInfo['aFreq'] == None and vInfo['aFreq'] in ('44100', '48000'):
113 # compatible frequency
114 freq = vInfo['aFreq']
115 if config.getAudioFR(tsn) != None:
116 freq = config.getAudioFR(tsn)
117 return '-ar ' + freq
119 def select_audioch(tsn):
120 ch = config.getAudioCH(tsn)
121 if ch:
122 return '-ac ' + ch
123 return ''
125 def select_audiolang(inFile, tsn):
126 vInfo = video_info(inFile)
127 if config.getAudioLang(tsn) != None and vInfo['mapVideo'] != None:
128 stream = vInfo['mapAudio'][0][0]
129 langmatch = []
130 for lang in config.getAudioLang(tsn).replace(' ','').lower().split(','):
131 for s, l in vInfo['mapAudio']:
132 if lang in s + l.replace(' ','').lower():
133 langmatch.append(s)
134 stream = s
135 break
136 if langmatch: break
137 if stream is not '':
138 return '-map ' + vInfo['mapVideo'] + ' -map ' + stream
139 return ''
141 def select_videofps(inFile, tsn):
142 vInfo = video_info(inFile)
143 fps = '-r 29.97' # default
144 if config.isHDtivo(tsn) and vInfo['vFps'] not in BAD_MPEG_FPS:
145 fps = ' '
146 if config.getVideoFPS(tsn) != None:
147 fps = '-r ' + config.getVideoFPS(tsn)
148 return fps
150 def select_videocodec(tsn):
151 codec = config.getVideoCodec(tsn)
152 if not codec:
153 codec = 'mpeg2video' # default
154 return '-vcodec ' + codec
156 def select_videobr(inFile, tsn):
157 return '-b ' + str(select_videostr(inFile, tsn) / 1000) + 'k'
159 def select_videostr(inFile, tsn):
160 video_str = config.strtod(config.getVideoBR(tsn))
161 if config.isHDtivo(tsn):
162 vInfo = video_info(inFile)
163 if vInfo['kbps'] != None and config.getVideoPCT() > 0:
164 video_percent = int(vInfo['kbps']) * 10 * config.getVideoPCT()
165 video_str = max(video_str, video_percent)
166 video_str = int(min(config.strtod(config.getMaxVideoBR()) * 0.95,
167 video_str))
168 return video_str
170 def select_audiobr(tsn):
171 return '-ab ' + config.getAudioBR(tsn)
173 def select_maxvideobr():
174 return '-maxrate ' + config.getMaxVideoBR()
176 def select_buffsize(tsn):
177 return '-bufsize ' + config.getBuffSize(tsn)
179 def select_ffmpegprams(tsn):
180 params = config.getFFmpegPrams(tsn)
181 if not params:
182 params = ''
183 return params
185 def select_format(tsn):
186 fmt = config.getFormat(tsn)
187 if not fmt:
188 fmt = 'vob'
189 return '-f %s -' % fmt
191 def select_aspect(inFile, tsn = ''):
192 TIVO_WIDTH = config.getTivoWidth(tsn)
193 TIVO_HEIGHT = config.getTivoHeight(tsn)
195 vInfo = video_info(inFile)
197 logging.debug('tsn: %s' % tsn)
199 aspect169 = config.get169Setting(tsn)
201 logging.debug('aspect169: %s' % aspect169)
203 optres = config.getOptres(tsn)
205 logging.debug('optres: %s' % optres)
207 if optres:
208 optHeight = config.nearestTivoHeight(vInfo['vHeight'])
209 optWidth = config.nearestTivoWidth(vInfo['vWidth'])
210 if optHeight < TIVO_HEIGHT:
211 TIVO_HEIGHT = optHeight
212 if optWidth < TIVO_WIDTH:
213 TIVO_WIDTH = optWidth
215 d = gcd(vInfo['vHeight'], vInfo['vWidth'])
216 ratio = vInfo['vWidth'] * 100 / vInfo['vHeight']
217 rheight, rwidth = vInfo['vHeight'] / d, vInfo['vWidth'] / d
219 logger.debug(('File=%s vCodec=%s vWidth=%s vHeight=%s vFps=%s ' +
220 'millisecs=%s ratio=%s rheight=%s rwidth=%s ' +
221 'TIVO_HEIGHT=%s TIVO_WIDTH=%s') % (inFile,
222 vInfo['vCodec'], vInfo['vWidth'], vInfo['vHeight'],
223 vInfo['vFps'], vInfo['millisecs'], ratio, rheight,
224 rwidth, TIVO_HEIGHT, TIVO_WIDTH))
226 multiplier16by9 = (16.0 * TIVO_HEIGHT) / (9.0 * TIVO_WIDTH)
227 multiplier4by3 = (4.0 * TIVO_HEIGHT) / (3.0 * TIVO_WIDTH)
229 if config.isHDtivo(tsn) and not optres:
230 if config.getPixelAR(0):
231 if vInfo['par2'] == None:
232 npar = config.getPixelAR(1)
233 else:
234 npar = vInfo['par2']
236 # adjust for pixel aspect ratio, if set, because TiVo
237 # expects square pixels
239 if npar < 1.0:
240 return ['-s', str(vInfo['vWidth']) + 'x' +
241 str(int(math.ceil(vInfo['vHeight'] / npar)))]
242 elif npar > 1.0:
243 # FFMPEG expects width to be a multiple of two
245 return ['-s', str(int(math.ceil(vInfo['vWidth'] * npar /
246 2.0) * 2)) + 'x' + str(vInfo['vHeight'])]
248 if vInfo['vHeight'] <= TIVO_HEIGHT:
249 # pass all resolutions to S3, except heights greater than
250 # conf height
251 return []
252 # else, resize video.
254 if (rwidth, rheight) in [(1, 1)] and vInfo['par1'] == '8:9':
255 logger.debug('File + PAR is within 4:3.')
256 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
258 elif ((rwidth, rheight) in [(4, 3), (10, 11), (15, 11), (59, 54),
259 (59, 72), (59, 36), (59, 54)] or
260 vInfo['dar1'] == '4:3'):
261 logger.debug('File is within 4:3 list.')
262 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
264 elif (((rwidth, rheight) in [(16, 9), (20, 11), (40, 33), (118, 81),
265 (59, 27)] or vInfo['dar1'] == '16:9')
266 and (aspect169 or config.get169Letterbox(tsn))):
267 logger.debug('File is within 16:9 list and 16:9 allowed.')
269 if config.get169Blacklist(tsn) or (aspect169 and
270 config.get169Letterbox(tsn)):
271 return ['-aspect', '4:3', '-s', '%sx%s' %
272 (TIVO_WIDTH, TIVO_HEIGHT)]
273 else:
274 return ['-aspect', '16:9', '-s', '%sx%s' %
275 (TIVO_WIDTH, TIVO_HEIGHT)]
276 else:
277 settings = []
279 # If video is wider than 4:3 add top and bottom padding
281 if ratio > 133: # Might be 16:9 file, or just need padding on
282 # top and bottom
284 if aspect169 and ratio > 135: # If file would fall in 4:3
285 # assume it is supposed to be 4:3
287 if ratio > 177: # too short needs padding top and bottom
288 endHeight = int(((TIVO_WIDTH * vInfo['vHeight']) /
289 vInfo['vWidth']) * multiplier16by9)
290 settings.append('-aspect')
291 if (config.get169Blacklist(tsn) or
292 config.get169Letterbox(tsn)):
293 settings.append('4:3')
294 else:
295 settings.append('16:9')
296 if endHeight % 2:
297 endHeight -= 1
298 if endHeight < TIVO_HEIGHT * 0.99:
299 topPadding = (TIVO_HEIGHT - endHeight) / 2
300 if topPadding % 2:
301 topPadding -= 1
302 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
303 settings += ['-s', '%sx%s' % (TIVO_WIDTH, endHeight),
304 '-padtop', str(topPadding),
305 '-padbottom', str(bottomPadding)]
306 else: # if only very small amount of padding
307 # needed, then just stretch it
308 settings += ['-s', '%sx%s' % (TIVO_WIDTH, 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 leftPadding = (TIVO_WIDTH - endWidth) / 2
327 if leftPadding % 2:
328 leftPadding -= 1
329 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
330 settings += ['-s', '%sx%s' % (endWidth, TIVO_HEIGHT),
331 '-padleft', str(leftPadding),
332 '-padright', str(rightPadding)]
333 else: # if only very small amount of padding needed,
334 # then just stretch it
335 settings += ['-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
336 logger.debug(('16:9 aspect allowed, file is narrower ' +
337 'than 16:9 padding left and right\n%s') %
338 ' '.join(settings))
339 else: # this is a 4:3 file or 16:9 output not allowed
340 multiplier = multiplier4by3
341 settings.append('-aspect')
342 if ratio > 135 and config.get169Letterbox(tsn):
343 settings.append('16:9')
344 multiplier = multiplier16by9
345 else:
346 settings.append('4:3')
347 endHeight = int(((TIVO_WIDTH * vInfo['vHeight']) /
348 vInfo['vWidth']) * multiplier)
349 if endHeight % 2:
350 endHeight -= 1
351 if endHeight < TIVO_HEIGHT * 0.99:
352 topPadding = (TIVO_HEIGHT - endHeight) / 2
353 if topPadding % 2:
354 topPadding -= 1
355 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
356 settings += ['-s', '%sx%s' % (TIVO_WIDTH, endHeight),
357 '-padtop', str(topPadding),
358 '-padbottom', str(bottomPadding)]
359 else: # if only very small amount of padding needed,
360 # then just stretch it
361 settings += ['-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
362 logging.debug(('File is wider than 4:3 padding ' +
363 'top and bottom\n%s') % ' '.join(settings))
365 return settings
367 # If video is taller than 4:3 add left and right padding, this
368 # is rare. All of these files will always be sent in an aspect
369 # ratio of 4:3 since they are so narrow.
371 else:
372 endWidth = int((TIVO_HEIGHT * vInfo['vWidth']) /
373 (vInfo['vHeight'] * multiplier4by3))
374 settings += ['-aspect', '4:3']
375 if endWidth % 2:
376 endWidth -= 1
377 if endWidth < (TIVO_WIDTH * 0.99):
378 leftPadding = (TIVO_WIDTH - endWidth) / 2
379 if leftPadding % 2:
380 leftPadding -= 1
381 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
382 settings += ['-s', '%sx%s' % (endWidth, TIVO_HEIGHT),
383 '-padleft', str(leftPadding),
384 '-padright', str(rightPadding)]
385 else: # if only very small amount of padding needed, then
386 # just stretch it
387 settings += ['-s', '%sx%s' % (TIVO_WIDTH, TIVO_HEIGHT)]
389 logger.debug('File is taller than 4:3 padding left and right\n%s'
390 % ' '.join(settings))
392 return settings
394 def tivo_compatible(inFile, tsn=''):
395 supportedModes = [(720, 480), (704, 480), (544, 480),
396 (528, 480), (480, 480), (352, 480)]
397 vInfo = video_info(inFile)
399 while True:
400 if (inFile[-5:]).lower() == '.tivo':
401 message = (True, 'TRANSCODE=NO, ends with .tivo.')
402 break
404 if not vInfo['vCodec'] == 'mpeg2video':
405 #print 'Not Tivo Codec'
406 message = (False, 'TRANSCODE=YES, vCodec %s not compatible.' %
407 vInfo['vCodec'])
408 break
410 if os.path.splitext(inFile)[-1].lower() in ('.ts', '.mpv',
411 '.tp', '.dvr-ms'):
412 message = (False, 'TRANSCODE=YES, ext %s not compatible.' %
413 os.path.splitext(inFile)[-1])
414 break
416 if vInfo['aCodec'] == 'dca':
417 message = (False, 'TRANSCODE=YES, aCodec %s not compatible.' %
418 vInfo['aCodec'])
419 break
421 if vInfo['aCodec'] != None:
422 if (not vInfo['aKbps'] or
423 int(vInfo['aKbps']) > config.getMaxAudioBR(tsn)):
424 message = (False, ('TRANSCODE=YES, %s kbps exceeds max ' +
425 'audio bitrate.') % vInfo['aKbps'])
426 break
428 if vInfo['kbps'] != None:
429 abit = max('0', vInfo['aKbps'])
430 if (int(vInfo['kbps']) - int(abit) >
431 config.strtod(config.getMaxVideoBR()) / 1000):
432 message = (False, ('TRANSCODE=YES, %s kbps exceeds max ' +
433 'video bitrate.') % vInfo['kbps'])
434 break
435 else:
436 message = (False, 'TRANSCODE=YES, %s kbps not supported.' %
437 vInfo['kbps'])
438 break
440 if config.getAudioLang(tsn):
441 if vInfo['mapAudio'][0][0] != select_audiolang(inFile, tsn)[-3:]:
442 message = (False, ('TRANSCODE=YES, %s preferred audio ' +
443 'track exists.') % config.getAudioLang(tsn))
444 break
446 if config.isHDtivo(tsn):
447 if vInfo['par2'] != 1.0:
448 if config.getPixelAR(0):
449 if vInfo['par2'] != None or config.getPixelAR(1) != 1.0:
450 message = (False, 'TRANSCODE=YES, %s not correct PAR.'
451 % vInfo['par2'])
452 break
453 message = (True, 'TRANSCODE=NO, HD Tivo detected, skipping ' +
454 'remaining tests.')
455 break
457 if not vInfo['vFps'] == '29.97':
458 #print 'Not Tivo fps'
459 message = (False, 'TRANSCODE=YES, %s vFps, should be 29.97.' %
460 vInfo['vFps'])
461 break
463 if ((config.get169Blacklist(tsn) and not config.get169Setting(tsn))
464 or (config.get169Letterbox(tsn) and config.get169Setting(tsn))):
465 if vInfo['dar1'] == None or not vInfo['dar1'] in ('4:3', '8:9'):
466 message = (False, ('TRANSCODE=YES, DAR %s not supported ' +
467 'by BLACKLIST_169 tivos.') % vInfo['dar1'])
468 break
470 for mode in supportedModes:
471 if mode == (vInfo['vWidth'], vInfo['vHeight']):
472 message = (True, 'TRANSCODE=NO, %s x %s is valid.' %
473 (vInfo['vWidth'], vInfo['vHeight']))
474 break
475 #print 'Not Tivo dimensions'
476 message = (False, 'TRANSCODE=YES, %s x %s not in supported modes.'
477 % (vInfo['vWidth'], vInfo['vHeight']))
478 break
480 logger.debug('%s, %s' % (message, inFile))
481 return message
484 def video_info(inFile):
485 vInfo = dict()
486 mtime = os.stat(inFile).st_mtime
487 if inFile != videotest:
488 if inFile in info_cache and info_cache[inFile][0] == mtime:
489 logging.debug('CACHE HIT! %s' % inFile)
490 return info_cache[inFile][1]
492 vInfo['Supported'] = True
494 if (inFile[-5:]).lower() == '.tivo':
495 vInfo['millisecs'] = 0
496 info_cache[inFile] = (mtime, vInfo)
497 logger.debug('VALID, ends in .tivo. %s' % inFile)
498 return vInfo
500 cmd = [ffmpeg_path(), '-i', inFile]
501 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
502 err_tmp = tempfile.TemporaryFile()
503 ffmpeg = subprocess.Popen(cmd, stderr=err_tmp, stdout=subprocess.PIPE,
504 stdin=subprocess.PIPE)
506 # wait 10 sec if ffmpeg is not back give up
507 for i in xrange(200):
508 time.sleep(.05)
509 if not ffmpeg.poll() == None:
510 break
512 if ffmpeg.poll() == None:
513 kill(ffmpeg.pid)
514 vInfo['Supported'] = False
515 info_cache[inFile] = (mtime, vInfo)
516 return vInfo
518 err_tmp.seek(0)
519 output = err_tmp.read()
520 err_tmp.close()
521 logging.debug('ffmpeg output=%s' % output)
523 rezre = re.compile(r'.*Video: ([^,]+),.*')
524 x = rezre.search(output)
525 if x:
526 vInfo['vCodec'] = x.group(1)
527 else:
528 vInfo['vCodec'] = ''
529 vInfo['Supported'] = False
530 logger.debug('failed at vCodec')
532 rezre = re.compile(r'.*Video: .+, (\d+)x(\d+)[, ].*')
533 x = rezre.search(output)
534 if x:
535 vInfo['vWidth'] = int(x.group(1))
536 vInfo['vHeight'] = int(x.group(2))
537 else:
538 vInfo['vWidth'] = ''
539 vInfo['vHeight'] = ''
540 vInfo['Supported'] = False
541 logger.debug('failed at vWidth/vHeight')
543 rezre = re.compile(r'.*Video: .+, (.+) (?:fps|tb).*')
544 x = rezre.search(output)
545 if x:
546 vInfo['vFps'] = x.group(1)
548 # Allow override only if it is mpeg2 and frame rate was doubled
549 # to 59.94
551 if vInfo['vCodec'] == 'mpeg2video' and vInfo['vFps'] != '29.97':
552 # First look for the build 7215 version
553 rezre = re.compile(r'.*film source: 29.97.*')
554 x = rezre.search(output.lower())
555 if x:
556 logger.debug('film source: 29.97 setting vFps to 29.97')
557 vInfo['vFps'] = '29.97'
558 else:
559 # for build 8047:
560 rezre = re.compile(r'.*frame rate differs from container ' +
561 r'frame rate: 29.97.*')
562 logger.debug('Bug in VideoReDo')
563 x = rezre.search(output.lower())
564 if x:
565 vInfo['vFps'] = '29.97'
566 else:
567 vInfo['vFps'] = ''
568 vInfo['Supported'] = False
569 logger.debug('failed at vFps')
571 durre = re.compile(r'.*Duration: ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+),')
572 d = durre.search(output)
574 if d:
575 vInfo['millisecs'] = ((int(d.group(1)) * 3600 +
576 int(d.group(2)) * 60 +
577 int(d.group(3))) * 1000 +
578 int(d.group(4)) * (10 ** (3 - len(d.group(4)))))
579 else:
580 vInfo['millisecs'] = 0
582 # get bitrate of source for tivo compatibility test.
583 rezre = re.compile(r'.*bitrate: (.+) (?:kb/s).*')
584 x = rezre.search(output)
585 if x:
586 vInfo['kbps'] = x.group(1)
587 else:
588 vInfo['kbps'] = None
589 logger.debug('failed at kbps')
591 # get audio bitrate of source for tivo compatibility test.
592 rezre = re.compile(r'.*Audio: .+, (.+) (?:kb/s).*')
593 x = rezre.search(output)
594 if x:
595 vInfo['aKbps'] = x.group(1)
596 else:
597 vInfo['aKbps'] = None
598 logger.debug('failed at aKbps')
600 # get audio codec of source for tivo compatibility test.
601 rezre = re.compile(r'.*Audio: ([^,]+),.*')
602 x = rezre.search(output)
603 if x:
604 vInfo['aCodec'] = x.group(1)
605 else:
606 vInfo['aCodec'] = None
607 logger.debug('failed at aCodec')
609 # get audio frequency of source for tivo compatibility test.
610 rezre = re.compile(r'.*Audio: .+, (.+) (?:Hz).*')
611 x = rezre.search(output)
612 if x:
613 vInfo['aFreq'] = x.group(1)
614 else:
615 vInfo['aFreq'] = None
616 logger.debug('failed at aFreq')
618 # get par.
619 rezre = re.compile(r'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
620 x = rezre.search(output)
621 if x and x.group(1) != "0" and x.group(2) != "0":
622 vInfo['par1'] = x.group(1) + ':' + x.group(2)
623 vInfo['par2'] = float(x.group(1)) / float(x.group(2))
624 else:
625 vInfo['par1'], vInfo['par2'] = None, None
627 # get dar.
628 rezre = re.compile(r'.*Video: .+DAR ([0-9]+):([0-9]+).*')
629 x = rezre.search(output)
630 if x and x.group(1) != "0" and x.group(2) != "0":
631 vInfo['dar1'] = x.group(1) + ':' + x.group(2)
632 vInfo['dar2'] = float(x.group(1)) / float(x.group(2))
633 else:
634 vInfo['dar1'], vInfo['dar2'] = None, None
636 # get Video Stream mapping.
637 rezre = re.compile(r'([0-9]+\.[0-9]+).*: Video:.*')
638 x = rezre.search(output)
639 if x:
640 vInfo['mapVideo'] = x.group(1)
641 else:
642 vInfo['mapVideo'] = None
643 logger.debug('failed at mapVideo')
645 # get Audio Stream mapping.
646 rezre = re.compile(r'([0-9]+\.[0-9]+)(.*): Audio:.*')
647 x = rezre.search(output)
648 amap = []
649 if x:
650 for x in rezre.finditer(output):
651 amap.append(x.groups())
652 else:
653 amap.append(('', ''))
654 logger.debug('failed at mapAudio')
655 vInfo['mapAudio'] = amap
657 videoPlugin = GetPlugin('video')
658 metadata = videoPlugin.getMetadataFromTxt(inFile)
660 for key in metadata:
661 if key.startswith('Override_'):
662 vInfo['Supported'] = True
663 if key.startswith('Override_mapAudio'):
664 audiomap = dict(vInfo['mapAudio'])
665 stream = key.replace('Override_mapAudio', '').strip()
666 if stream in audiomap:
667 newaudiomap = (stream, metadata[key])
668 audiomap.update([newaudiomap])
669 vInfo['mapAudio'] = sorted(audiomap.items(),
670 key=lambda (k,v): (k,v))
671 elif key.startswith('Override_millisecs'):
672 vInfo[key.replace('Override_', '')] = int(metadata[key])
673 else:
674 vInfo[key.replace('Override_', '')] = metadata[key]
676 info_cache[inFile] = (mtime, vInfo)
677 logger.debug("; ".join(["%s=%s" % (k, v) for k, v in vInfo.items()]))
678 return vInfo
680 def video_check(inFile, cmd_string):
681 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
682 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
683 try:
684 shutil.copyfileobj(ffmpeg.stdout, open(videotest, 'wb'))
685 return True
686 except:
687 kill(ffmpeg.pid)
688 return False
690 def supported_format(inFile):
691 if video_info(inFile)['Supported']:
692 return True
693 else:
694 logger.debug('FALSE, file not supported %s' % inFile)
695 return False
697 def kill(pid):
698 logger.debug('killing pid=%s' % str(pid))
699 if mswindows:
700 win32kill(pid)
701 else:
702 import os, signal
703 os.kill(pid, signal.SIGTERM)
705 def win32kill(pid):
706 import ctypes
707 handle = ctypes.windll.kernel32.OpenProcess(1, False, pid)
708 ctypes.windll.kernel32.TerminateProcess(handle, -1)
709 ctypes.windll.kernel32.CloseHandle(handle)
711 def gcd(a, b):
712 while b:
713 a, b = b, a % b
714 return a