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