force transcode and/or disable mapping if Override_mapAud is used
[pyTivo/wgw.git] / plugins / video / transcode.py
blob7862b81dbffac7c772a0a4dcbef8563e5e7968fe
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()
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 -b 1000k -acodec copy '+\
82 select_audiolang(inFile, tsn)+' -t 00:00:01 -f vob -'
83 if video_check(inFile, cmd_string):
84 vInfo = video_info(videotest)
85 else:
86 codec = 'TBD'
87 if not vInfo['aKbps'] == None and int(vInfo['aKbps']) <= config.getMaxAudioBR(tsn):
88 # compatible codec and bitrate, do not reencode audio
89 codec = 'copy'
90 else:
91 codec = config.getAudioCodec(tsn)
92 copyts = ' -copyts'
93 if (codec == 'copy' and config.getCopyTS(tsn).lower() == 'none' \
94 and codectype == 'mpeg2video') or config.getCopyTS(tsn).lower() == 'false':
95 copyts = ''
96 return '-acodec '+codec+copyts
98 def select_audiofr(inFile, tsn):
99 freq = '48000' #default
100 vInfo = video_info(inFile)
101 if not vInfo['aFreq'] == None and vInfo['aFreq'] in ('44100', '48000'):
102 # compatible frequency
103 freq = vInfo['aFreq']
104 if config.getAudioFR(tsn) != None:
105 freq = config.getAudioFR(tsn)
106 return '-ar '+freq
108 def select_audioch(tsn):
109 if config.getAudioCH(tsn) != None:
110 return '-ac '+config.getAudioCH(tsn)
111 return ''
113 def select_audiolang(inFile, tsn):
114 vInfo = video_info(inFile)
115 if config.getAudioLang(tsn) != None and vInfo['mapVid'] != None:
116 stream, l = vInfo['mapAud'][0]
117 for s, l in vInfo['mapAud']:
118 if config.getAudioLang(tsn) in s+l:
119 stream = s
120 break
121 if not stream == '':
122 return '-map '+vInfo['mapVid']+' -map '+stream
123 return ''
125 def select_videofps(inFile, tsn):
126 vInfo = video_info(inFile)
127 fps = '-r 29.97' #default
128 if config.isHDtivo(tsn) and vInfo['vFps'] not in BAD_MPEG_FPS:
129 fps = ' '
130 if config.getVideoFPS(tsn) != None:
131 fps = '-r '+config.getVideoFPS(tsn)
132 return fps
134 def select_videocodec(tsn):
135 codec = 'mpeg2video' #default
136 if config.getVideoCodec(tsn) != None:
137 codec = config.getVideoCodec(tsn)
138 return '-vcodec '+codec
140 def select_videobr(inFile, tsn):
141 return '-b '+select_videostr(inFile, tsn)
143 def select_videostr(inFile, tsn):
144 video_str = config.getVideoBR(tsn)
145 if config.isHDtivo(tsn):
146 vInfo = video_info(inFile)
147 if vInfo['kbps'] != None and config.getVideoPCT() > 0:
148 video_percent = int(vInfo['kbps'])*10*config.getVideoPCT()
149 video_bitrate = max(config.strtod(video_str), video_percent)
150 video_str = str(int(min(config.strtod(config.getMaxVideoBR())*0.95, video_bitrate)))
151 return video_str
153 def select_audiobr(tsn):
154 return '-ab '+config.getAudioBR(tsn)
156 def select_maxvideobr():
157 return '-maxrate '+config.getMaxVideoBR()
159 def select_buffsize():
160 return '-bufsize '+config.getBuffSize()
162 def select_ffmpegprams(tsn):
163 if config.getFFmpegPrams(tsn) != None:
164 return config.getFFmpegPrams(tsn)
165 return ''
167 def select_format(tsn):
168 fmt = 'vob'
169 if config.getFormat(tsn) != None:
170 fmt = config.getFormat(tsn)
171 return '-f '+fmt+' -'
173 def select_aspect(inFile, tsn = ''):
174 TIVO_WIDTH = config.getTivoWidth(tsn)
175 TIVO_HEIGHT = config.getTivoHeight(tsn)
177 vInfo = video_info(inFile)
179 logging.debug('tsn: %s' % tsn)
181 aspect169 = config.get169Setting(tsn)
183 logging.debug('aspect169:%s' % aspect169)
185 optres = config.getOptres(tsn)
187 logging.debug('optres:%s' % optres)
189 if optres:
190 optHeight = config.nearestTivoHeight(vInfo['vHeight'])
191 optWidth = config.nearestTivoWidth(vInfo['vWidth'])
192 if optHeight < TIVO_HEIGHT:
193 TIVO_HEIGHT = optHeight
194 if optWidth < TIVO_WIDTH:
195 TIVO_WIDTH = optWidth
197 d = gcd(vInfo['vHeight'],vInfo['vWidth'])
198 ratio = (vInfo['vWidth']*100)/vInfo['vHeight']
199 rheight, rwidth = vInfo['vHeight']/d, vInfo['vWidth']/d
201 logger.debug('File=%s vCodec=%s vWidth=%s vHeight=%s vFps=%s millisecs=%s ratio=%s rheight=%s rwidth=%s TIVO_HEIGHT=%sTIVO_WIDTH=%s' % (inFile, vInfo['vCodec'], vInfo['vWidth'], vInfo['vHeight'], vInfo['vFps'], vInfo['millisecs'], ratio, rheight, rwidth, TIVO_HEIGHT, TIVO_WIDTH))
203 multiplier16by9 = (16.0 * TIVO_HEIGHT) / (9.0 * TIVO_WIDTH)
204 multiplier4by3 = (4.0 * TIVO_HEIGHT) / (3.0 * TIVO_WIDTH)
206 if config.isHDtivo(tsn) and not optres:
207 if config.getPixelAR(0):
208 if vInfo['par2'] == None:
209 npar = config.getPixelAR(1)
210 else:
211 npar = vInfo['par2']
212 # adjust for pixel aspect ratio, if set, because TiVo expects square pixels
213 if npar<1.0:
214 return ['-s', str(vInfo['vWidth']) + 'x' + str(int(math.ceil(vInfo['vHeight']/npar)))]
215 elif npar>1.0:
216 # FFMPEG expects width to be a multiple of two
217 return ['-s', str(int(math.ceil(vInfo['vWidth']*npar/2.0)*2)) + 'x' + str(vInfo['vHeight'])]
218 if vInfo['vHeight'] <= TIVO_HEIGHT:
219 # pass all resolutions to S3, except heights greater than conf height
220 return []
221 # else, resize video.
222 if (rwidth, rheight) in [(1, 1)] and vInfo['par1'] == '8:9':
223 logger.debug('File + PAR is within 4:3.')
224 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
225 elif (rwidth, rheight) in [(4, 3), (10, 11), (15, 11), (59, 54), (59, 72), (59, 36), (59, 54)] or vInfo['dar1'] == '4:3':
226 logger.debug('File is within 4:3 list.')
227 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
228 elif ((rwidth, rheight) in [(16, 9), (20, 11), (40, 33), (118, 81), (59, 27)] or vInfo['dar1'] == '16:9')\
229 and (aspect169 or config.get169Letterbox(tsn)):
230 logger.debug('File is within 16:9 list and 16:9 allowed.')
231 if config.get169Blacklist(tsn) or (aspect169 and config.get169Letterbox(tsn)):
232 return ['-aspect', '4:3', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
233 else:
234 return ['-aspect', '16:9', '-s', str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT)]
235 else:
236 settings = []
237 #If video is wider than 4:3 add top and bottom padding
238 if (ratio > 133): #Might be 16:9 file, or just need padding on top and bottom
239 if aspect169 and (ratio > 135): #If file would fall in 4:3 assume it is supposed to be 4:3
240 if (ratio > 177):#too short needs padding top and bottom
241 endHeight = int(((TIVO_WIDTH*vInfo['vHeight'])/vInfo['vWidth']) * multiplier16by9)
242 settings.append('-aspect')
243 if config.get169Blacklist(tsn) or config.get169Letterbox(tsn):
244 settings.append('4:3')
245 else:
246 settings.append('16:9')
247 if endHeight % 2:
248 endHeight -= 1
249 if endHeight < TIVO_HEIGHT * 0.99:
250 settings.append('-s')
251 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
253 topPadding = ((TIVO_HEIGHT - endHeight)/2)
254 if topPadding % 2:
255 topPadding -= 1
257 settings.append('-padtop')
258 settings.append(str(topPadding))
259 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
260 settings.append('-padbottom')
261 settings.append(str(bottomPadding))
262 else: #if only very small amount of padding needed, then just stretch it
263 settings.append('-s')
264 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
265 logger.debug('16:9 aspect allowed, file is wider than 16:9 padding top and bottom\n%s' % ' '.join(settings))
266 else: #too skinny needs padding on left and right.
267 endWidth = int((TIVO_HEIGHT*vInfo['vWidth'])/(vInfo['vHeight']*multiplier16by9))
268 settings.append('-aspect')
269 if config.get169Blacklist(tsn) or config.get169Letterbox(tsn):
270 settings.append('4:3')
271 else:
272 settings.append('16:9')
273 if endWidth % 2:
274 endWidth -= 1
275 if endWidth < (TIVO_WIDTH-10):
276 settings.append('-s')
277 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
279 leftPadding = ((TIVO_WIDTH - endWidth)/2)
280 if leftPadding % 2:
281 leftPadding -= 1
283 settings.append('-padleft')
284 settings.append(str(leftPadding))
285 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
286 settings.append('-padright')
287 settings.append(str(rightPadding))
288 else: #if only very small amount of padding needed, then just stretch it
289 settings.append('-s')
290 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
291 logger.debug('16:9 aspect allowed, file is narrower than 16:9 padding left and right\n%s' % ' '.join(settings))
292 else: #this is a 4:3 file or 16:9 output not allowed
293 multiplier = multiplier4by3
294 settings.append('-aspect')
295 if ratio > 135 and config.get169Letterbox(tsn):
296 settings.append('16:9')
297 multiplier = multiplier16by9
298 else:
299 settings.append('4:3')
300 endHeight = int(((TIVO_WIDTH*vInfo['vHeight'])/vInfo['vWidth']) * multiplier)
301 if endHeight % 2:
302 endHeight -= 1
303 if endHeight < TIVO_HEIGHT * 0.99:
304 settings.append('-s')
305 settings.append(str(TIVO_WIDTH) + 'x' + str(endHeight))
307 topPadding = ((TIVO_HEIGHT - endHeight)/2)
308 if topPadding % 2:
309 topPadding -= 1
311 settings.append('-padtop')
312 settings.append(str(topPadding))
313 bottomPadding = (TIVO_HEIGHT - endHeight) - topPadding
314 settings.append('-padbottom')
315 settings.append(str(bottomPadding))
316 else: #if only very small amount of padding needed, then just stretch it
317 settings.append('-s')
318 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
319 logging.debug('File is wider than 4:3 padding top and bottom\n%s' % ' '.join(settings))
321 return settings
322 #If video is taller than 4:3 add left and right padding, this is rare. All of these files will always be sent in
323 #an aspect ratio of 4:3 since they are so narrow.
324 else:
325 endWidth = int((TIVO_HEIGHT*vInfo['vWidth'])/(vInfo['vHeight']*multiplier4by3))
326 settings.append('-aspect')
327 settings.append('4:3')
328 if endWidth % 2:
329 endWidth -= 1
330 if endWidth < (TIVO_WIDTH * 0.99):
331 settings.append('-s')
332 settings.append(str(endWidth) + 'x' + str(TIVO_HEIGHT))
334 leftPadding = ((TIVO_WIDTH - endWidth)/2)
335 if leftPadding % 2:
336 leftPadding -= 1
338 settings.append('-padleft')
339 settings.append(str(leftPadding))
340 rightPadding = (TIVO_WIDTH - endWidth) - leftPadding
341 settings.append('-padright')
342 settings.append(str(rightPadding))
343 else: #if only very small amount of padding needed, then just stretch it
344 settings.append('-s')
345 settings.append(str(TIVO_WIDTH) + 'x' + str(TIVO_HEIGHT))
347 logger.debug('File is taller than 4:3 padding left and right\n%s' % ' '.join(settings))
349 return settings
351 def tivo_compatable(inFile, tsn = ''):
352 supportedModes = [[720, 480], [704, 480], [544, 480], [528, 480], [480, 480], [352, 480]]
353 vInfo = video_info(inFile)
355 while True:
357 if (inFile[-5:]).lower() == '.tivo':
358 message = True, 'TRANSCODE=NO, ends with .tivo.'
359 break
361 if not vInfo['vCodec'] == 'mpeg2video':
362 #print 'Not Tivo Codec'
363 message = False, 'TRANSCODE=YES, vCodec %s not compatible.' % vInfo['vCodec']
364 break
366 if os.path.splitext(inFile)[-1].lower() in ('.ts', '.mpv', '.tp', '.dvr-ms'):
367 message = False, 'TRANSCODE=YES, ext %s not compatible.' % os.path.splitext(inFile)[-1]
368 break
370 if vInfo['aCodec'] == 'dca':
371 message = False, 'TRANSCODE=YES, aCodec %s not compatible.' % vInfo['aCodec']
372 break
374 if vInfo['aCodec'] != None:
375 if not vInfo['aKbps'] or int(vInfo['aKbps']) > config.getMaxAudioBR(tsn):
376 message = False, 'TRANSCODE=YES, %s kbps exceeds max audio bitrate.' % vInfo['aKbps']
377 break
379 if vInfo['kbps'] != None:
380 abit = max('0', vInfo['aKbps'])
381 if int(vInfo['kbps'])-int(abit) > config.strtod(config.getMaxVideoBR())/1000:
382 message = False, 'TRANSCODE=YES, %s kbps exceeds max video bitrate.' % vInfo['kbps']
383 break
384 else:
385 message = False, 'TRANSCODE=YES, %s kbps not supported.' % vInfo['kbps']
386 break
388 stream, l = vInfo['mapAud'][0]
389 if stream != select_audiolang(inFile, tsn)[-3:]:
390 message = False, 'TRANSCODE=YES, %s preferred audio track exists.' % config.getAudioLang(tsn)
391 break
393 if config.isHDtivo(tsn):
394 if vInfo['par2'] != 1.0:
395 if config.getPixelAR(0):
396 if vInfo['par2'] != None or config.getPixelAR(1) != 1.0:
397 message = False, 'TRANSCODE=YES, %s not correct PAR.' % vInfo['par2']
398 break
399 message = True, 'TRANSCODE=NO, HD Tivo detected, skipping remaining tests.'
400 break
402 if not vInfo['vFps'] == '29.97':
403 #print 'Not Tivo fps'
404 message = False, 'TRANSCODE=YES, %s vFps, should be 29.97.' % vInfo['vFps']
405 break
407 if (config.get169Blacklist(tsn) and not config.get169Setting(tsn))\
408 or (config.get169Letterbox(tsn) and config.get169Setting(tsn)):
409 if vInfo['dar1'] == None or not vInfo['dar1'] in ('4:3', '8:9'):
410 message = False, 'TRANSCODE=YES, DAR %s not supported by BLACKLIST_169 tivos.' % vInfo['dar1']
411 break
413 for mode in supportedModes:
414 if (mode[0], mode[1]) == (vInfo['vWidth'], vInfo['vHeight']):
415 message = True, 'TRANSCODE=NO, %s x %s is valid.' % (vInfo['vWidth'], vInfo['vHeight'])
416 break
417 #print 'Not Tivo dimensions'
418 message = False, 'TRANSCODE=YES, %s x %s not in supported modes.' % (vInfo['vWidth'], vInfo['vHeight'])
419 break
421 logger.debug('%s, %s' % (message, inFile))
422 return message
425 def video_info(inFile):
426 vInfo = dict()
427 mtime = os.stat(inFile).st_mtime
428 if inFile != videotest:
429 if inFile in info_cache and info_cache[inFile][0] == mtime:
430 logging.debug('CACHE HIT! %s' % inFile)
431 return info_cache[inFile][1]
433 vInfo['Supported'] = True
435 if (inFile[-5:]).lower() == '.tivo':
436 vInfo['millisecs'] = 0
437 info_cache[inFile] = (mtime, vInfo)
438 logger.debug('VALID, ends in .tivo. %s' % inFile)
439 return vInfo
441 cmd = [ffmpeg_path(), '-i', inFile ]
442 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
443 err_tmp = tempfile.TemporaryFile()
444 ffmpeg = subprocess.Popen(cmd, stderr=err_tmp, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
446 # wait 10 sec if ffmpeg is not back give up
447 for i in xrange(200):
448 time.sleep(.05)
449 if not ffmpeg.poll() == None:
450 break
452 if ffmpeg.poll() == None:
453 kill(ffmpeg.pid)
454 vInfo['Supported'] = False
455 info_cache[inFile] = (mtime, vInfo)
456 return vInfo
458 err_tmp.seek(0)
459 output = err_tmp.read()
460 err_tmp.close()
461 logging.debug('ffmpeg output=%s' % output)
463 rezre = re.compile(r'.*Video: ([^,]+),.*')
464 x = rezre.search(output)
465 if x:
466 vInfo['vCodec'] = x.group(1)
467 else:
468 vInfo['vCodec'] = ''
469 vInfo['Supported'] = False
470 logger.debug('failed at vCodec')
472 rezre = re.compile(r'.*Video: .+, (\d+)x(\d+)[, ].*')
473 x = rezre.search(output)
474 if x:
475 vInfo['vWidth'] = int(x.group(1))
476 vInfo['vHeight'] = int(x.group(2))
477 else:
478 vInfo['vWidth'] = ''
479 vInfo['vHeight'] = ''
480 vInfo['Supported'] = False
481 logger.debug('failed at vWidth/vHeight')
483 rezre = re.compile(r'.*Video: .+, (.+) (?:fps|tb).*')
484 x = rezre.search(output)
485 if x:
486 vInfo['vFps'] = x.group(1)
487 # Allow override only if it is mpeg2 and frame rate was doubled to 59.94
488 if (not vInfo['vFps'] == '29.97') and (vInfo['vCodec'] == 'mpeg2video'):
489 # First look for the build 7215 version
490 rezre = re.compile(r'.*film source: 29.97.*')
491 x = rezre.search(output.lower() )
492 if x:
493 logger.debug('film source: 29.97 setting vFps to 29.97')
494 vInfo['vFps'] = '29.97'
495 else:
496 # for build 8047:
497 rezre = re.compile(r'.*frame rate differs from container frame rate: 29.97.*')
498 logger.debug('Bug in VideoReDo')
499 x = rezre.search(output.lower() )
500 if x:
501 vInfo['vFps'] = '29.97'
502 else:
503 vInfo['vFps'] = ''
504 vInfo['Supported'] = False
505 logger.debug('failed at vFps')
507 durre = re.compile(r'.*Duration: ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+),')
508 d = durre.search(output)
509 if d:
510 vInfo['millisecs'] = ((int(d.group(1))*3600) + (int(d.group(2))*60) + int(d.group(3)))*1000 + (int(d.group(4))*100)
511 else:
512 vInfo['millisecs'] = 0
514 #get bitrate of source for tivo compatibility test.
515 rezre = re.compile(r'.*bitrate: (.+) (?:kb/s).*')
516 x = rezre.search(output)
517 if x:
518 vInfo['kbps'] = x.group(1)
519 else:
520 vInfo['kbps'] = None
521 logger.debug('failed at kbps')
523 #get audio bitrate of source for tivo compatibility test.
524 rezre = re.compile(r'.*Audio: .+, (.+) (?:kb/s).*')
525 x = rezre.search(output)
526 if x:
527 vInfo['aKbps'] = x.group(1)
528 else:
529 vInfo['aKbps'] = None
530 logger.debug('failed at aKbps')
532 #get audio codec of source for tivo compatibility test.
533 rezre = re.compile(r'.*Audio: ([^,]+),.*')
534 x = rezre.search(output)
535 if x:
536 vInfo['aCodec'] = x.group(1)
537 else:
538 vInfo['aCodec'] = None
539 logger.debug('failed at aCodec')
541 #get audio frequency of source for tivo compatibility test.
542 rezre = re.compile(r'.*Audio: .+, (.+) (?:Hz).*')
543 x = rezre.search(output)
544 if x:
545 vInfo['aFreq'] = x.group(1)
546 else:
547 vInfo['aFreq'] = None
548 logger.debug('failed at aFreq')
550 #get par.
551 rezre = re.compile(r'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
552 x = rezre.search(output)
553 if x and x.group(1)!="0" and x.group(2)!="0":
554 vInfo['par1'], vInfo['par2'] = x.group(1)+':'+x.group(2), float(x.group(1))/float(x.group(2))
555 else:
556 vInfo['par1'], vInfo['par2'] = None, None
558 #get dar.
559 rezre = re.compile(r'.*Video: .+DAR ([0-9]+):([0-9]+).*')
560 x = rezre.search(output)
561 if x and x.group(1)!="0" and x.group(2)!="0":
562 vInfo['dar1'], vInfo['dar2'] = x.group(1)+':'+x.group(2), float(x.group(1))/float(x.group(2))
563 else:
564 vInfo['dar1'], vInfo['dar2'] = None, None
566 #get Video Stream mapping.
567 rezre = re.compile(r'([0-9]+\.[0-9]+).*: Video:.*')
568 x = rezre.search(output)
569 if x:
570 vInfo['mapVid'] = x.group(1)
571 else:
572 vInfo['mapVid'] = None
573 logger.debug('failed at mapVid')
576 #get Audio Stream mapping.
577 rezre = re.compile(r'([0-9]+\.[0-9]+)(.*): Audio:.*')
578 x = rezre.search(output)
579 amap = []
580 if x:
581 for x in rezre.finditer(output):
582 amap.append(x.groups())
583 else:
584 amap.append(('', ''))
585 logger.debug('failed at mapAud')
586 vInfo['mapAud'] = amap
589 videoPlugin = GetPlugin('video')
590 metadata = videoPlugin.getMetadataFromTxt(inFile)
592 for key in metadata:
593 if key.startswith('Override_'):
594 vInfo['Supported'] = True
595 vInfo[key.replace('Override_','')] = metadata[key]
596 if type(vInfo['mapAud']) != list:
597 vInfo[key.replace('Override_','')] = [('',''), config.str2tuple(metadata[key])]
599 info_cache[inFile] = (mtime, vInfo)
600 logger.debug("; ".join(["%s=%s" % (k, v) for k, v in vInfo.items()]))
601 return vInfo
603 def video_check(inFile, cmd_string):
604 cmd = [ffmpeg_path(), '-i', inFile] + cmd_string.split()
605 ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE)
606 try:
607 shutil.copyfileobj(ffmpeg.stdout, open(videotest, 'wb'))
608 return True
609 except:
610 kill(ffmpeg.pid)
611 return False
613 def supported_format(inFile):
614 if video_info(inFile)['Supported']:
615 return True
616 else:
617 logger.debug('FALSE, file not supported %s' % inFile)
618 return False
620 def kill(pid):
621 logger.debug('killing pid=%s' % str(pid))
622 if mswindows:
623 win32kill(pid)
624 else:
625 import os, signal
626 os.kill(pid, signal.SIGTERM)
628 def win32kill(pid):
629 import ctypes
630 handle = ctypes.windll.kernel32.OpenProcess(1, False, pid)
631 ctypes.windll.kernel32.TerminateProcess(handle, -1)
632 ctypes.windll.kernel32.CloseHandle(handle)
634 def gcd(a,b):
635 while b:
636 a, b = b, a % b
637 return a