17 logger
= logging
.getLogger('pyTivo.video.transcode')
19 info_cache
= lrucache
.LRUCache(1000)
23 GOOD_MPEG_FPS
= ['23.98', '24.00', '25.00', '29.97',
24 '30.00', '50.00', '59.94', '60.00']
26 BLOCKSIZE
= 512 * 1024
31 # subprocess is broken for me on windows so super hack
32 def patchSubprocess():
33 o
= subprocess
.Popen
._make
_inheritable
35 def _make_inheritable(self
, handle
):
36 if not handle
: return subprocess
.GetCurrentProcess()
37 return o(self
, handle
)
39 subprocess
.Popen
._make
_inheritable
= _make_inheritable
40 mswindows
= (sys
.platform
== "win32")
47 msg
= msg
.decode('utf8')
49 if sys
.platform
== 'darwin':
50 msg
= msg
.decode('macroman')
52 msg
= msg
.decode('iso8859-1')
55 def transcode(isQuery
, inFile
, outFile
, tsn
=''):
56 settings
= {'video_codec': select_videocodec(inFile
, tsn
),
57 'video_br': select_videobr(inFile
, tsn
),
58 'video_fps': select_videofps(inFile
, tsn
),
59 'max_video_br': select_maxvideobr(tsn
),
60 'buff_size': select_buffsize(tsn
),
61 'aspect_ratio': ' '.join(select_aspect(inFile
, tsn
)),
62 'audio_br': select_audiobr(tsn
),
63 'audio_fr': select_audiofr(inFile
, tsn
),
64 'audio_ch': select_audioch(tsn
),
65 'audio_codec': select_audiocodec(isQuery
, inFile
, tsn
),
66 'audio_lang': select_audiolang(inFile
, tsn
),
67 'ffmpeg_pram': select_ffmpegprams(tsn
),
68 'format': select_format(tsn
)}
73 ffmpeg_path
= config
.get_bin('ffmpeg')
74 cmd_string
= config
.getFFmpegTemplate(tsn
) % settings
76 if inFile
[-5:].lower() == '.tivo':
77 tivodecode_path
= config
.get_bin('tivodecode')
78 tivo_mak
= config
.get_server('tivo_mak')
79 tcmd
= [tivodecode_path
, '-m', tivo_mak
, inFile
]
80 tivodecode
= subprocess
.Popen(tcmd
, stdout
=subprocess
.PIPE
,
82 if tivo_compatible(inFile
, tsn
)[0]:
86 cmd
= [ffmpeg_path
, '-i', '-'] + cmd_string
.split()
87 ffmpeg
= subprocess
.Popen(cmd
, stdin
=tivodecode
.stdout
,
88 stdout
=subprocess
.PIPE
,
91 cmd
= [ffmpeg_path
, '-i', inFile
] + cmd_string
.split()
92 ffmpeg
= subprocess
.Popen(cmd
, bufsize
=(512 * 1024),
93 stdout
=subprocess
.PIPE
)
96 debug('transcoding to tivo model ' + tsn
[:3] + ' using ffmpeg command:')
99 ffmpeg_procs
[inFile
] = {'process': ffmpeg
, 'start': 0, 'end': 0,
100 'last_read': time
.time(), 'blocks': []}
102 transfer_blocks(inFile
, outFile
)
104 def is_resumable(inFile
, offset
):
105 if inFile
in ffmpeg_procs
:
106 proc
= ffmpeg_procs
[inFile
]
107 if proc
['start'] <= offset
< proc
['end']:
111 kill(proc
['process'])
114 def resume_transfer(inFile
, outFile
, offset
):
115 proc
= ffmpeg_procs
[inFile
]
116 offset
-= proc
['start']
118 for block
in proc
['blocks']:
122 block
= block
[offset
:]
123 outFile
.write('%x\r\n' % len(block
))
125 outFile
.write('\r\n')
128 except Exception, msg
:
131 proc
['start'] = proc
['end']
134 transfer_blocks(inFile
, outFile
)
136 def transfer_blocks(inFile
, outFile
):
137 proc
= ffmpeg_procs
[inFile
]
138 blocks
= proc
['blocks']
142 block
= proc
['process'].stdout
.read(BLOCKSIZE
)
143 proc
['last_read'] = time
.time()
144 except Exception, msg
:
147 kill(proc
['process'])
153 except Exception, msg
:
160 proc
['end'] += len(block
)
161 if len(blocks
) > MAXBLOCKS
:
162 proc
['start'] += len(blocks
[0])
166 outFile
.write('%x\r\n' % len(block
))
168 outFile
.write('\r\n')
169 except Exception, msg
:
173 def reap_process(inFile
):
174 if inFile
in ffmpeg_procs
:
175 proc
= ffmpeg_procs
[inFile
]
176 if proc
['last_read'] + TIMEOUT
< time
.time():
177 del ffmpeg_procs
[inFile
]
179 kill(proc
['process'])
181 reaper
= threading
.Timer(TIMEOUT
, reap_process
, (inFile
,))
182 reapers
[inFile
] = reaper
186 del ffmpeg_procs
[inFile
]
187 reapers
[inFile
].cancel()
190 def select_audiocodec(isQuery
, inFile
, tsn
=''):
191 if inFile
[-5:].lower() == '.tivo':
192 return '-acodec copy'
193 vInfo
= video_info(inFile
)
194 codectype
= vInfo
['vCodec']
195 codec
= config
.get_tsn('audio_codec', tsn
)
197 # Default, compatible with all TiVo's
199 if vInfo
['aCodec'] in ('ac3', 'liba52', 'mp2'):
200 aKbps
= vInfo
['aKbps']
203 aKbps
= audio_check(inFile
, tsn
)
206 if aKbps
!= None and int(aKbps
) <= config
.getMaxAudioBR(tsn
):
207 # compatible codec and bitrate, do not reencode audio
209 copy_flag
= config
.get_tsn('copy_ts', tsn
)
211 if ((codec
== 'copy' and codectype
== 'mpeg2video' and not copy_flag
) or
212 (copy_flag
and copy_flag
.lower() == 'false')):
214 return '-acodec ' + codec
+ copyts
216 def select_audiofr(inFile
, tsn
):
217 freq
= '48000' #default
218 vInfo
= video_info(inFile
)
219 if not vInfo
['aFreq'] == None and vInfo
['aFreq'] in ('44100', '48000'):
220 # compatible frequency
221 freq
= vInfo
['aFreq']
222 audio_fr
= config
.get_tsn('audio_fr', tsn
)
227 def select_audioch(tsn
):
228 ch
= config
.get_tsn('audio_ch', tsn
)
233 def select_audiolang(inFile
, tsn
):
234 vInfo
= video_info(inFile
)
235 audio_lang
= config
.get_tsn('audio_lang', tsn
)
236 if audio_lang
!= None and vInfo
['mapVideo'] != None:
237 stream
= vInfo
['mapAudio'][0][0]
239 for lang
in audio_lang
.replace(' ','').lower().split(','):
240 for s
, l
in vInfo
['mapAudio']:
241 if lang
in s
+ l
.replace(' ','').lower():
247 return '-map ' + vInfo
['mapVideo'] + ' -map ' + stream
250 def select_videofps(inFile
, tsn
):
251 vInfo
= video_info(inFile
)
252 fps
= '-r 29.97' # default
253 if config
.isHDtivo(tsn
) and vInfo
['vFps'] in GOOD_MPEG_FPS
:
255 video_fps
= config
.get_tsn('video_fps', tsn
)
256 if video_fps
!= None:
257 fps
= '-r ' + video_fps
260 def select_videocodec(inFile
, tsn
):
261 vInfo
= video_info(inFile
)
262 if tivo_compatible_video(vInfo
, tsn
)[0]:
265 codec
= 'mpeg2video' # default
266 return '-vcodec ' + codec
268 def select_videobr(inFile
, tsn
):
269 return '-b ' + str(select_videostr(inFile
, tsn
) / 1000) + 'k'
271 def select_videostr(inFile
, tsn
):
272 vInfo
= video_info(inFile
)
273 if tivo_compatible_video(vInfo
, tsn
)[0]:
274 video_str
= int(vInfo
['kbps'])
276 video_str
-= int(vInfo
['aKbps'])
279 video_str
= config
.strtod(config
.getVideoBR(tsn
))
280 if config
.isHDtivo(tsn
):
281 if vInfo
['kbps'] != None and config
.getVideoPCT(tsn
) > 0:
282 video_percent
= (int(vInfo
['kbps']) * 10 *
283 config
.getVideoPCT(tsn
))
284 video_str
= max(video_str
, video_percent
)
285 video_str
= int(min(config
.strtod(config
.getMaxVideoBR(tsn
)) * 0.95,
289 def select_audiobr(tsn
):
290 return '-ab ' + config
.getAudioBR(tsn
)
292 def select_maxvideobr(tsn
):
293 return '-maxrate ' + config
.getMaxVideoBR(tsn
)
295 def select_buffsize(tsn
):
296 return '-bufsize ' + config
.getBuffSize(tsn
)
298 def select_ffmpegprams(tsn
):
299 params
= config
.getFFmpegPrams(tsn
)
304 def select_format(tsn
):
306 return '-f %s -' % fmt
308 def pad_TB(TIVO_WIDTH
, TIVO_HEIGHT
, multiplier
, vInfo
):
309 endHeight
= int(((TIVO_WIDTH
* vInfo
['vHeight']) /
310 vInfo
['vWidth']) * multiplier
)
313 if endHeight
< TIVO_HEIGHT
* 0.99:
314 topPadding
= (TIVO_HEIGHT
- endHeight
) / 2
317 bottomPadding
= (TIVO_HEIGHT
- endHeight
) - topPadding
318 return ['-s', '%sx%s' % (TIVO_WIDTH
, endHeight
),
319 '-padtop', str(topPadding
),
320 '-padbottom', str(bottomPadding
)]
321 else: # if only very small amount of padding needed, then
323 return ['-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
325 def pad_LR(TIVO_WIDTH
, TIVO_HEIGHT
, multiplier
, vInfo
):
326 endWidth
= int((TIVO_HEIGHT
* vInfo
['vWidth']) /
327 (vInfo
['vHeight'] * multiplier
))
330 if endWidth
< TIVO_WIDTH
* 0.99:
331 leftPadding
= (TIVO_WIDTH
- endWidth
) / 2
334 rightPadding
= (TIVO_WIDTH
- endWidth
) - leftPadding
335 return ['-s', '%sx%s' % (endWidth
, TIVO_HEIGHT
),
336 '-padleft', str(leftPadding
),
337 '-padright', str(rightPadding
)]
338 else: # if only very small amount of padding needed, then
340 return ['-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
342 def select_aspect(inFile
, tsn
= ''):
343 TIVO_WIDTH
= config
.getTivoWidth(tsn
)
344 TIVO_HEIGHT
= config
.getTivoHeight(tsn
)
346 vInfo
= video_info(inFile
)
348 debug('tsn: %s' % tsn
)
350 aspect169
= config
.get169Setting(tsn
)
352 debug('aspect169: %s' % aspect169
)
354 optres
= config
.getOptres(tsn
)
356 debug('optres: %s' % optres
)
359 optHeight
= config
.nearestTivoHeight(vInfo
['vHeight'])
360 optWidth
= config
.nearestTivoWidth(vInfo
['vWidth'])
361 if optHeight
< TIVO_HEIGHT
:
362 TIVO_HEIGHT
= optHeight
363 if optWidth
< TIVO_WIDTH
:
364 TIVO_WIDTH
= optWidth
366 if vInfo
.get('par2'):
368 elif vInfo
.get('par'):
369 par2
= float(vInfo
['par'])
374 debug(('File=%s vCodec=%s vWidth=%s vHeight=%s vFps=%s millisecs=%s ' +
375 'TIVO_HEIGHT=%s TIVO_WIDTH=%s') % (inFile
, vInfo
['vCodec'],
376 vInfo
['vWidth'], vInfo
['vHeight'], vInfo
['vFps'],
377 vInfo
['millisecs'], TIVO_HEIGHT
, TIVO_WIDTH
))
379 if config
.isHDtivo(tsn
) and not optres
:
380 if config
.getPixelAR(0) or vInfo
['par']:
381 if vInfo
['par2'] == None:
385 npar
= config
.getPixelAR(1)
389 # adjust for pixel aspect ratio, if set
392 return ['-s', '%dx%d' % (vInfo
['vWidth'],
393 math
.ceil(vInfo
['vHeight'] / npar
))]
395 # FFMPEG expects width to be a multiple of two
396 return ['-s', '%dx%d' % (math
.ceil(vInfo
['vWidth']*npar
/2.0)*2,
399 if vInfo
['vHeight'] <= TIVO_HEIGHT
:
400 # pass all resolutions to S3, except heights greater than
403 # else, resize video.
405 d
= gcd(vInfo
['vHeight'], vInfo
['vWidth'])
406 rheight
, rwidth
= vInfo
['vHeight'] / d
, vInfo
['vWidth'] / d
407 debug('rheight=%s rwidth=%s' % (rheight
, rwidth
))
409 if (rwidth
, rheight
) in [(1, 1)] and vInfo
['par1'] == '8:9':
410 debug('File + PAR is within 4:3.')
411 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
413 elif ((rwidth
, rheight
) in [(4, 3), (10, 11), (15, 11), (59, 54),
414 (59, 72), (59, 36), (59, 54)] or
415 vInfo
['dar1'] == '4:3'):
416 debug('File is within 4:3 list.')
417 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
419 elif (((rwidth
, rheight
) in [(16, 9), (20, 11), (40, 33), (118, 81),
420 (59, 27)] or vInfo
['dar1'] == '16:9')
421 and (aspect169
or config
.get169Letterbox(tsn
))):
422 debug('File is within 16:9 list and 16:9 allowed.')
424 if config
.get169Blacklist(tsn
) or (aspect169
and
425 config
.get169Letterbox(tsn
)):
429 return ['-aspect', aspect
, '-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
432 settings
= ['-aspect']
434 multiplier16by9
= (16.0 * TIVO_HEIGHT
) / (9.0 * TIVO_WIDTH
) / par2
435 multiplier4by3
= (4.0 * TIVO_HEIGHT
) / (3.0 * TIVO_WIDTH
) / par2
436 ratio
= vInfo
['vWidth'] * 100 * par2
/ vInfo
['vHeight']
437 debug('par2=%.3f ratio=%.3f mult4by3=%.3f' % (par2
, ratio
,
440 # If video is wider than 4:3 add top and bottom padding
442 if ratio
> 133: # Might be 16:9 file, or just need padding on
445 if aspect169
and ratio
> 135: # If file would fall in 4:3
446 # assume it is supposed to be 4:3
448 if (config
.get169Blacklist(tsn
) or
449 config
.get169Letterbox(tsn
)):
450 settings
.append('4:3')
452 settings
.append('16:9')
454 if ratio
> 177: # too short needs padding top and bottom
455 settings
+= pad_TB(TIVO_WIDTH
, TIVO_HEIGHT
,
456 multiplier16by9
, vInfo
)
457 debug(('16:9 aspect allowed, file is wider ' +
458 'than 16:9 padding top and bottom\n%s') %
461 else: # too skinny needs padding on left and right.
462 settings
+= pad_LR(TIVO_WIDTH
, TIVO_HEIGHT
,
463 multiplier16by9
, vInfo
)
464 debug(('16:9 aspect allowed, file is narrower ' +
465 'than 16:9 padding left and right\n%s') %
468 else: # this is a 4:3 file or 16:9 output not allowed
469 if ratio
> 135 and config
.get169Letterbox(tsn
):
470 settings
.append('16:9')
471 multiplier
= multiplier16by9
473 settings
.append('4:3')
474 multiplier
= multiplier4by3
475 settings
+= pad_TB(TIVO_WIDTH
, TIVO_HEIGHT
,
477 debug(('File is wider than 4:3 padding ' +
478 'top and bottom\n%s') % ' '.join(settings
))
480 # If video is taller than 4:3 add left and right padding, this
481 # is rare. All of these files will always be sent in an aspect
482 # ratio of 4:3 since they are so narrow.
485 settings
.append('4:3')
486 settings
+= pad_LR(TIVO_WIDTH
, TIVO_HEIGHT
, multiplier4by3
, vInfo
)
487 debug('File is taller than 4:3 padding left and right\n%s'
488 % ' '.join(settings
))
492 def tivo_compatible_video(vInfo
, tsn
, mime
=''):
495 codec
= vInfo
['vCodec']
496 if mime
== 'video/mp4':
498 message
= (False, 'vCodec %s not compatible' % codec
)
502 if mime
== 'video/bif':
504 message
= (False, 'vCodec %s not compatible' % codec
)
508 if codec
not in ('mpeg2video', 'mpeg1video'):
509 message
= (False, 'vCodec %s not compatible' % codec
)
512 if vInfo
['kbps'] != None:
513 abit
= max('0', vInfo
['aKbps'])
514 if (int(vInfo
['kbps']) - int(abit
) >
515 config
.strtod(config
.getMaxVideoBR(tsn
)) / 1000):
516 message
= (False, '%s kbps exceeds max video bitrate' %
520 message
= (False, '%s kbps not supported' % vInfo
['kbps'])
523 if config
.isHDtivo(tsn
):
524 if vInfo
['par2'] != 1.0:
525 if config
.getPixelAR(0):
526 if vInfo
['par2'] != None or config
.getPixelAR(1) != 1.0:
527 message
= (False, '%s not correct PAR' % vInfo
['par2'])
529 # HD Tivo detected, skipping remaining tests.
532 if not vInfo
['vFps'] in ['29.97', '59.94']:
533 message
= (False, '%s vFps, should be 29.97' % vInfo
['vFps'])
536 if ((config
.get169Blacklist(tsn
) and not config
.get169Setting(tsn
))
537 or (config
.get169Letterbox(tsn
) and config
.get169Setting(tsn
))):
538 if vInfo
['dar1'] and vInfo
['dar1'] not in ('4:3', '8:9', '880:657'):
539 message
= (False, ('DAR %s not supported ' +
540 'by BLACKLIST_169 tivos') % vInfo
['dar1'])
543 mode
= (vInfo
['vWidth'], vInfo
['vHeight'])
544 if mode
not in [(720, 480), (704, 480), (544, 480),
545 (528, 480), (480, 480), (352, 480), (352, 240)]:
546 message
= (False, '%s x %s not in supported modes' % mode
)
551 def tivo_compatible_audio(vInfo
, inFile
, tsn
, mime
=''):
554 codec
= vInfo
['aCodec']
555 if mime
== 'video/mp4':
556 if codec
not in ('mpeg4aac', 'libfaad', 'mp4a', 'aac',
558 message
= (False, 'aCodec %s not compatible' % codec
)
562 if mime
== 'video/bif':
564 message
= (False, 'aCodec %s not compatible' % codec
)
568 if inFile
[-5:].lower() == '.tivo':
571 if codec
not in ('ac3', 'liba52', 'mp2'):
572 message
= (False, 'aCodec %s not compatible' % codec
)
575 if (not vInfo
['aKbps'] or
576 int(vInfo
['aKbps']) > config
.getMaxAudioBR(tsn
)):
577 message
= (False, '%s kbps exceeds max audio bitrate' %
581 audio_lang
= config
.get_tsn('audio_lang', tsn
)
583 if vInfo
['mapAudio'][0][0] != select_audiolang(inFile
, tsn
)[-3:]:
584 message
= (False, '%s preferred audio track exists' %
590 def tivo_compatible_container(vInfo
, mime
=''):
592 container
= vInfo
['container']
593 if ((mime
== 'video/mp4' and container
!= 'mov') or
594 (mime
== 'video/bif' and container
!= 'asf') or
595 (mime
in ['video/mpeg', ''] and
596 (container
!= 'mpeg' or vInfo
['vCodec'] == 'mpeg1video'))):
597 message
= (False, 'container %s not compatible' % container
)
601 def tivo_compatible(inFile
, tsn
='', mime
=''):
602 vInfo
= video_info(inFile
)
604 message
= (True, 'all compatible')
605 if not config
.get_bin('ffmpeg'):
606 if mime
not in ['video/x-tivo-mpeg', 'video/mpeg', '']:
607 message
= (False, 'no ffmpeg')
611 vmessage
= tivo_compatible_video(vInfo
, tsn
, mime
)
616 amessage
= tivo_compatible_audio(vInfo
, inFile
, tsn
, mime
)
621 cmessage
= tivo_compatible_container(vInfo
, mime
)
627 debug('TRANSCODE=%s, %s, %s' % (['YES', 'NO'][message
[0]],
631 def video_info(inFile
, cache
=True):
633 mtime
= os
.stat(inFile
).st_mtime
635 if inFile
in info_cache
and info_cache
[inFile
][0] == mtime
:
636 debug('CACHE HIT! %s' % inFile
)
637 return info_cache
[inFile
][1]
639 vInfo
['Supported'] = True
641 ffmpeg_path
= config
.get_bin('ffmpeg')
643 if os
.path
.splitext(inFile
)[1].lower() not in ['.mpg', '.mpeg',
645 vInfo
['Supported'] = False
646 vInfo
.update({'millisecs': 0, 'vWidth': 704, 'vHeight': 480})
648 info_cache
[inFile
] = (mtime
, vInfo
)
651 cmd
= [ffmpeg_path
, '-i', inFile
]
652 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
653 err_tmp
= tempfile
.TemporaryFile()
654 ffmpeg
= subprocess
.Popen(cmd
, stderr
=err_tmp
, stdout
=subprocess
.PIPE
,
655 stdin
=subprocess
.PIPE
)
657 # wait configured # of seconds: if ffmpeg is not back give up
658 wait
= config
.getFFmpegWait()
659 debug('starting ffmpeg, will wait %s seconds for it to complete' % wait
)
660 for i
in xrange(wait
* 20):
662 if not ffmpeg
.poll() == None:
665 if ffmpeg
.poll() == None:
667 vInfo
['Supported'] = False
669 info_cache
[inFile
] = (mtime
, vInfo
)
673 output
= err_tmp
.read()
675 debug('ffmpeg output=%s' % output
)
677 attrs
= {'container': r
'Input #0, ([^,]+),',
678 'vCodec': r
'.*Video: ([^,]+),.*', # video codec
679 'aKbps': r
'.*Audio: .+, (.+) (?:kb/s).*', # audio bitrate
680 'aCodec': r
'.*Audio: ([^,]+),.*', # audio codec
681 'aFreq': r
'.*Audio: .+, (.+) (?:Hz).*', # audio frequency
682 'mapVideo': r
'([0-9]+\.[0-9]+).*: Video:.*'} # video mapping
685 rezre
= re
.compile(attrs
[attr
])
686 x
= rezre
.search(output
)
688 vInfo
[attr
] = x
.group(1)
690 if attr
in ['container', 'vCodec']:
692 vInfo
['Supported'] = False
695 debug('failed at ' + attr
)
697 rezre
= re
.compile(r
'.*Video: .+, (\d+)x(\d+)[, ].*')
698 x
= rezre
.search(output
)
700 vInfo
['vWidth'] = int(x
.group(1))
701 vInfo
['vHeight'] = int(x
.group(2))
704 vInfo
['vHeight'] = ''
705 vInfo
['Supported'] = False
706 debug('failed at vWidth/vHeight')
708 rezre
= re
.compile(r
'.*Video: .+, (.+) (?:fps|tb\(r\)|tbr).*')
709 x
= rezre
.search(output
)
711 vInfo
['vFps'] = x
.group(1)
712 if '.' not in vInfo
['vFps']:
713 vInfo
['vFps'] += '.00'
715 # Allow override only if it is mpeg2 and frame rate was doubled
718 if vInfo
['vCodec'] == 'mpeg2video' and vInfo
['vFps'] != '29.97':
719 # First look for the build 7215 version
720 rezre
= re
.compile(r
'.*film source: 29.97.*')
721 x
= rezre
.search(output
.lower())
723 debug('film source: 29.97 setting vFps to 29.97')
724 vInfo
['vFps'] = '29.97'
727 rezre
= re
.compile(r
'.*frame rate differs from container ' +
728 r
'frame rate: 29.97.*')
729 debug('Bug in VideoReDo')
730 x
= rezre
.search(output
.lower())
732 vInfo
['vFps'] = '29.97'
735 vInfo
['Supported'] = False
736 debug('failed at vFps')
738 durre
= re
.compile(r
'.*Duration: ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+),')
739 d
= durre
.search(output
)
742 vInfo
['millisecs'] = ((int(d
.group(1)) * 3600 +
743 int(d
.group(2)) * 60 +
744 int(d
.group(3))) * 1000 +
745 int(d
.group(4)) * (10 ** (3 - len(d
.group(4)))))
747 vInfo
['millisecs'] = 0
749 # get bitrate of source for tivo compatibility test.
750 rezre
= re
.compile(r
'.*bitrate: (.+) (?:kb/s).*')
751 x
= rezre
.search(output
)
753 vInfo
['kbps'] = x
.group(1)
755 # Fallback method of getting video bitrate
756 # Sample line: Stream #0.0[0x1e0]: Video: mpeg2video, yuv420p,
757 # 720x480 [PAR 32:27 DAR 16:9], 9800 kb/s, 59.94 tb(r)
758 rezre
= re
.compile(r
'.*Stream #0\.0\[.*\]: Video: mpeg2video, ' +
759 r
'\S+, \S+ \[.*\], (\d+) (?:kb/s).*')
760 x
= rezre
.search(output
)
762 vInfo
['kbps'] = x
.group(1)
765 debug('failed at kbps')
768 rezre
= re
.compile(r
'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
769 x
= rezre
.search(output
)
770 if x
and x
.group(1) != "0" and x
.group(2) != "0":
771 vInfo
['par1'] = x
.group(1) + ':' + x
.group(2)
772 vInfo
['par2'] = float(x
.group(1)) / float(x
.group(2))
774 vInfo
['par1'], vInfo
['par2'] = None, None
777 rezre
= re
.compile(r
'.*Video: .+DAR ([0-9]+):([0-9]+).*')
778 x
= rezre
.search(output
)
779 if x
and x
.group(1) != "0" and x
.group(2) != "0":
780 vInfo
['dar1'] = x
.group(1) + ':' + x
.group(2)
784 # get Audio Stream mapping.
785 rezre
= re
.compile(r
'([0-9]+\.[0-9]+)(.*): Audio:.*')
786 x
= rezre
.search(output
)
789 for x
in rezre
.finditer(output
):
790 amap
.append(x
.groups())
792 amap
.append(('', ''))
793 debug('failed at mapAudio')
794 vInfo
['mapAudio'] = amap
798 data
= metadata
.from_text(inFile
)
800 if key
.startswith('Override_'):
801 vInfo
['Supported'] = True
802 if key
.startswith('Override_mapAudio'):
803 audiomap
= dict(vInfo
['mapAudio'])
804 stream
= key
.replace('Override_mapAudio', '').strip()
805 if stream
in audiomap
:
806 newaudiomap
= (stream
, data
[key
])
807 audiomap
.update([newaudiomap
])
808 vInfo
['mapAudio'] = sorted(audiomap
.items(),
809 key
=lambda (k
,v
): (k
,v
))
810 elif key
.startswith('Override_millisecs'):
811 vInfo
[key
.replace('Override_', '')] = int(data
[key
])
813 vInfo
[key
.replace('Override_', '')] = data
[key
]
816 info_cache
[inFile
] = (mtime
, vInfo
)
817 debug("; ".join(["%s=%s" % (k
, v
) for k
, v
in vInfo
.items()]))
820 def audio_check(inFile
, tsn
):
821 cmd_string
= ('-y -vcodec mpeg2video -r 29.97 -b 1000k -acodec copy ' +
822 select_audiolang(inFile
, tsn
) + ' -t 00:00:01 -f vob -')
823 cmd
= [config
.get_bin('ffmpeg'), '-i', inFile
] + cmd_string
.split()
824 ffmpeg
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
825 fd
, testname
= tempfile
.mkstemp()
826 testfile
= os
.fdopen(fd
, 'wb')
828 shutil
.copyfileobj(ffmpeg
.stdout
, testfile
)
835 aKbps
= video_info(testname
, False)['aKbps']
839 def supported_format(inFile
):
840 if video_info(inFile
)['Supported']:
843 debug('FALSE, file not supported %s' % inFile
)
847 debug('killing pid=%s' % str(popen
.pid
))
853 debug('sending SIGTERM to pid: %s' % popen
.pid
)
854 os
.kill(popen
.pid
, signal
.SIGTERM
)
856 if popen
.poll() is not None:
857 debug('process %s has exited' % popen
.pid
)
860 while popen
.poll() is None:
861 debug('sending SIGKILL to pid: %s' % popen
.pid
)
862 os
.kill(popen
.pid
, signal
.SIGKILL
)
867 handle
= ctypes
.windll
.kernel32
.OpenProcess(1, False, pid
)
868 ctypes
.windll
.kernel32
.TerminateProcess(handle
, -1)
869 ctypes
.windll
.kernel32
.CloseHandle(handle
)