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
37 # subprocess is broken for me on windows so super hack
38 def patchSubprocess():
39 o
= subprocess
.Popen
._make
_inheritable
41 def _make_inheritable(self
, handle
):
42 if not handle
: return subprocess
.GetCurrentProcess()
43 return o(self
, handle
)
45 subprocess
.Popen
._make
_inheritable
= _make_inheritable
46 mswindows
= (sys
.platform
== "win32")
53 msg
= msg
.decode('utf8')
55 if sys
.platform
== 'darwin':
56 msg
= msg
.decode('macroman')
58 msg
= msg
.decode('iso8859-1')
61 def transcode(isQuery
, inFile
, outFile
, tsn
='', mime
='', thead
=''):
62 settings
= {'video_codec': select_videocodec(inFile
, tsn
),
63 'video_br': select_videobr(inFile
, tsn
),
64 'video_fps': select_videofps(inFile
, tsn
),
65 'max_video_br': select_maxvideobr(tsn
),
66 'buff_size': select_buffsize(tsn
),
67 'aspect_ratio': ' '.join(select_aspect(inFile
, tsn
)),
68 'audio_br': select_audiobr(tsn
),
69 'audio_fr': select_audiofr(inFile
, tsn
),
70 'audio_ch': select_audioch(tsn
),
71 'audio_codec': select_audiocodec(isQuery
, inFile
, tsn
),
72 'audio_lang': select_audiolang(inFile
, tsn
),
73 'ffmpeg_pram': select_ffmpegprams(tsn
),
74 'format': select_format(tsn
, mime
)}
79 ffmpeg_path
= config
.get_bin('ffmpeg')
80 cmd_string
= config
.getFFmpegTemplate(tsn
) % settings
81 fname
= unicode(inFile
, 'utf-8')
83 fname
= fname
.encode('iso8859-1')
85 if inFile
[-5:].lower() == '.tivo':
86 tivodecode_path
= config
.get_bin('tivodecode')
87 tivo_mak
= config
.get_server('tivo_mak')
88 tcmd
= [tivodecode_path
, '-m', tivo_mak
, fname
]
89 tivodecode
= subprocess
.Popen(tcmd
, stdout
=subprocess
.PIPE
,
91 if tivo_compatible(inFile
, tsn
)[0]:
95 cmd
= [ffmpeg_path
, '-i', '-'] + cmd_string
.split()
96 ffmpeg
= subprocess
.Popen(cmd
, stdin
=tivodecode
.stdout
,
97 stdout
=subprocess
.PIPE
,
100 cmd
= [ffmpeg_path
, '-i', fname
] + cmd_string
.split()
101 ffmpeg
= subprocess
.Popen(cmd
, bufsize
=(512 * 1024),
102 stdout
=subprocess
.PIPE
)
105 debug('transcoding to tivo model ' + tsn
[:3] + ' using ffmpeg command:')
108 ffmpeg_procs
[inFile
] = {'process': ffmpeg
, 'start': 0, 'end': 0,
109 'last_read': time
.time(), 'blocks': []}
111 ffmpeg_procs
[inFile
]['blocks'].append(thead
)
113 return resume_transfer(inFile
, outFile
, 0)
115 def is_resumable(inFile
, offset
):
116 if inFile
in ffmpeg_procs
:
117 proc
= ffmpeg_procs
[inFile
]
118 if proc
['start'] <= offset
< proc
['end']:
122 kill(proc
['process'])
125 def resume_transfer(inFile
, outFile
, offset
):
126 proc
= ffmpeg_procs
[inFile
]
127 offset
-= proc
['start']
131 for block
in proc
['blocks']:
135 block
= block
[offset
:]
136 outFile
.write('%x\r\n' % len(block
))
138 outFile
.write('\r\n')
142 except Exception, msg
:
146 proc
['start'] = proc
['end']
149 return count
+ transfer_blocks(inFile
, outFile
)
151 def transfer_blocks(inFile
, outFile
):
152 proc
= ffmpeg_procs
[inFile
]
153 blocks
= proc
['blocks']
158 block
= proc
['process'].stdout
.read(BLOCKSIZE
)
159 proc
['last_read'] = time
.time()
160 except Exception, msg
:
163 kill(proc
['process'])
169 except Exception, msg
:
176 proc
['end'] += len(block
)
177 if len(blocks
) > MAXBLOCKS
:
178 proc
['start'] += len(blocks
[0])
182 outFile
.write('%x\r\n' % len(block
))
184 outFile
.write('\r\n')
186 except Exception, msg
:
192 def reap_process(inFile
):
193 if ffmpeg_procs
and inFile
in ffmpeg_procs
:
194 proc
= ffmpeg_procs
[inFile
]
195 if proc
['last_read'] + TIMEOUT
< time
.time():
196 del ffmpeg_procs
[inFile
]
198 kill(proc
['process'])
200 reaper
= threading
.Timer(TIMEOUT
, reap_process
, (inFile
,))
201 reapers
[inFile
] = reaper
205 del ffmpeg_procs
[inFile
]
206 reapers
[inFile
].cancel()
209 def select_audiocodec(isQuery
, inFile
, tsn
=''):
210 if inFile
[-5:].lower() == '.tivo':
211 return '-acodec copy'
212 vInfo
= video_info(inFile
)
213 codectype
= vInfo
['vCodec']
214 codec
= config
.get_tsn('audio_codec', tsn
)
216 # Default, compatible with all TiVo's
218 if vInfo
['aCodec'] in ('ac3', 'liba52', 'mp2'):
219 aKbps
= vInfo
['aKbps']
222 aKbps
= audio_check(inFile
, tsn
)
225 if aKbps
!= None and int(aKbps
) <= config
.getMaxAudioBR(tsn
):
226 # compatible codec and bitrate, do not reencode audio
228 copy_flag
= config
.get_tsn('copy_ts', tsn
)
230 if ((codec
== 'copy' and codectype
== 'mpeg2video' and not copy_flag
) or
231 (copy_flag
and copy_flag
.lower() == 'false')):
233 return '-acodec ' + codec
+ copyts
235 def select_audiofr(inFile
, tsn
):
236 freq
= '48000' #default
237 vInfo
= video_info(inFile
)
238 if not vInfo
['aFreq'] == None and vInfo
['aFreq'] in ('44100', '48000'):
239 # compatible frequency
240 freq
= vInfo
['aFreq']
241 audio_fr
= config
.get_tsn('audio_fr', tsn
)
246 def select_audioch(tsn
):
247 ch
= config
.get_tsn('audio_ch', tsn
)
252 def select_audiolang(inFile
, tsn
):
253 vInfo
= video_info(inFile
)
254 audio_lang
= config
.get_tsn('audio_lang', tsn
)
255 debug('audio_lang: %s' % audio_lang
)
256 if audio_lang
!= None and vInfo
['mapVideo'] != None:
257 stream
= vInfo
['mapAudio'][0][0]
259 langmatch_prev
= vInfo
['mapAudio'][:]
260 for lang
in audio_lang
.replace(' ','').lower().split(','):
261 for s
, l
in langmatch_prev
:
262 if lang
in s
+ (l
).replace(' ','').lower():
263 langmatch_curr
.append((s
, l
))
265 #if only 1 item matched we're done
266 if len(langmatch_curr
) == 1:
267 del langmatch_prev
[:]
269 #if more than 1 item matched copy the curr area to the prev array
270 #we only need to look at the new shorter list from now on
271 elif len(langmatch_curr
) > 1:
272 del langmatch_prev
[:]
273 langmatch_prev
= langmatch_curr
[:]
274 del langmatch_curr
[:]
275 #if nothing matched we'll keep the prev array and clear the curr array
277 del langmatch_curr
[:]
278 #if we drop out of the loop with more than 1 item default to the first item
279 if len(langmatch_prev
) > 1:
280 stream
= langmatch_prev
[0][0]
282 debug('selected audio stream: %s' % stream
)
283 return '-map ' + vInfo
['mapVideo'] + ' -map ' + stream
284 debug('selected audio stream: %s' % '')
287 def select_videofps(inFile
, tsn
):
288 vInfo
= video_info(inFile
)
289 fps
= '-r 29.97' # default
290 if config
.isHDtivo(tsn
) and vInfo
['vFps'] in GOOD_MPEG_FPS
:
292 video_fps
= config
.get_tsn('video_fps', tsn
)
293 if video_fps
!= None:
294 fps
= '-r ' + video_fps
297 def select_videocodec(inFile
, tsn
):
298 vInfo
= video_info(inFile
)
299 if tivo_compatible_video(vInfo
, tsn
)[0]:
302 codec
= 'mpeg2video' # default
303 return '-vcodec ' + codec
305 def select_videobr(inFile
, tsn
):
306 return '-b ' + str(select_videostr(inFile
, tsn
) / 1000) + 'k'
308 def select_videostr(inFile
, tsn
):
309 vInfo
= video_info(inFile
)
310 if tivo_compatible_video(vInfo
, tsn
)[0]:
311 video_str
= int(vInfo
['kbps'])
313 video_str
-= int(vInfo
['aKbps'])
316 video_str
= config
.strtod(config
.getVideoBR(tsn
))
317 if config
.isHDtivo(tsn
):
318 if vInfo
['kbps'] != None and config
.getVideoPCT(tsn
) > 0:
319 video_percent
= (int(vInfo
['kbps']) * 10 *
320 config
.getVideoPCT(tsn
))
321 video_str
= max(video_str
, video_percent
)
322 video_str
= int(min(config
.strtod(config
.getMaxVideoBR(tsn
)) * 0.95,
326 def select_audiobr(tsn
):
327 return '-ab ' + config
.getAudioBR(tsn
)
329 def select_maxvideobr(tsn
):
330 return '-maxrate ' + config
.getMaxVideoBR(tsn
)
332 def select_buffsize(tsn
):
333 return '-bufsize ' + config
.getBuffSize(tsn
)
335 def select_ffmpegprams(tsn
):
336 params
= config
.getFFmpegPrams(tsn
)
341 def select_format(tsn
, mime
):
342 if mime
== 'video/x-tivo-mpeg-ts':
346 return '-f %s -' % fmt
350 if pad_style
== UNSET
:
352 filters
= tempfile
.TemporaryFile()
353 cmd
= [config
.get_bin('ffmpeg'), '-filters']
354 ffmpeg
= subprocess
.Popen(cmd
, stdout
=filters
, stderr
=subprocess
.PIPE
)
358 if line
.startswith('pad'):
362 return pad_style
== NEW_PAD
364 def pad_TB(TIVO_WIDTH
, TIVO_HEIGHT
, multiplier
, vInfo
):
365 endHeight
= int(((TIVO_WIDTH
* vInfo
['vHeight']) /
366 vInfo
['vWidth']) * multiplier
)
369 if endHeight
< TIVO_HEIGHT
* 0.99:
370 topPadding
= (TIVO_HEIGHT
- endHeight
) / 2
375 return ['-s', '%sx%s' % (TIVO_WIDTH
, endHeight
), '-vf',
376 'pad=%d:%d:0:%d' % (TIVO_WIDTH
, TIVO_HEIGHT
, topPadding
)]
378 bottomPadding
= (TIVO_HEIGHT
- endHeight
) - topPadding
379 return ['-s', '%sx%s' % (TIVO_WIDTH
, endHeight
),
380 '-padtop', str(topPadding
),
381 '-padbottom', str(bottomPadding
)]
382 else: # if only very small amount of padding needed, then
384 return ['-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
386 def pad_LR(TIVO_WIDTH
, TIVO_HEIGHT
, multiplier
, vInfo
):
387 endWidth
= int((TIVO_HEIGHT
* vInfo
['vWidth']) /
388 (vInfo
['vHeight'] * multiplier
))
391 if endWidth
< TIVO_WIDTH
* 0.99:
392 leftPadding
= (TIVO_WIDTH
- endWidth
) / 2
397 return ['-s', '%sx%s' % (endWidth
, TIVO_HEIGHT
), '-vf',
398 'pad=%d:%d:%d:0' % (TIVO_WIDTH
, TIVO_HEIGHT
, leftPadding
)]
400 rightPadding
= (TIVO_WIDTH
- endWidth
) - leftPadding
401 return ['-s', '%sx%s' % (endWidth
, TIVO_HEIGHT
),
402 '-padleft', str(leftPadding
),
403 '-padright', str(rightPadding
)]
404 else: # if only very small amount of padding needed, then
406 return ['-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
408 def select_aspect(inFile
, tsn
= ''):
409 TIVO_WIDTH
= config
.getTivoWidth(tsn
)
410 TIVO_HEIGHT
= config
.getTivoHeight(tsn
)
412 vInfo
= video_info(inFile
)
414 debug('tsn: %s' % tsn
)
416 aspect169
= config
.get169Setting(tsn
)
418 debug('aspect169: %s' % aspect169
)
420 optres
= config
.getOptres(tsn
)
422 debug('optres: %s' % optres
)
425 optHeight
= config
.nearestTivoHeight(vInfo
['vHeight'])
426 optWidth
= config
.nearestTivoWidth(vInfo
['vWidth'])
427 if optHeight
< TIVO_HEIGHT
:
428 TIVO_HEIGHT
= optHeight
429 if optWidth
< TIVO_WIDTH
:
430 TIVO_WIDTH
= optWidth
432 if vInfo
.get('par2'):
434 elif vInfo
.get('par'):
435 par2
= float(vInfo
['par'])
440 debug(('File=%s vCodec=%s vWidth=%s vHeight=%s vFps=%s millisecs=%s ' +
441 'TIVO_HEIGHT=%s TIVO_WIDTH=%s') % (inFile
, vInfo
['vCodec'],
442 vInfo
['vWidth'], vInfo
['vHeight'], vInfo
['vFps'],
443 vInfo
['millisecs'], TIVO_HEIGHT
, TIVO_WIDTH
))
445 if config
.isHDtivo(tsn
) and not optres
:
446 if config
.getPixelAR(0) or vInfo
['par']:
447 if vInfo
['par2'] == None:
451 npar
= config
.getPixelAR(1)
455 # adjust for pixel aspect ratio, if set
458 return ['-s', '%dx%d' % (vInfo
['vWidth'],
459 math
.ceil(vInfo
['vHeight'] / npar
))]
461 # FFMPEG expects width to be a multiple of two
462 return ['-s', '%dx%d' % (math
.ceil(vInfo
['vWidth']*npar
/2.0)*2,
465 if vInfo
['vHeight'] <= TIVO_HEIGHT
:
466 # pass all resolutions to S3, except heights greater than
469 # else, resize video.
471 d
= gcd(vInfo
['vHeight'], vInfo
['vWidth'])
472 rheight
, rwidth
= vInfo
['vHeight'] / d
, vInfo
['vWidth'] / d
473 debug('rheight=%s rwidth=%s' % (rheight
, rwidth
))
475 if (rwidth
, rheight
) in [(1, 1)] and vInfo
['par1'] == '8:9':
476 debug('File + PAR is within 4:3.')
477 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
479 elif ((rwidth
, rheight
) in [(4, 3), (10, 11), (15, 11), (59, 54),
480 (59, 72), (59, 36), (59, 54)] or
481 vInfo
['dar1'] == '4:3'):
482 debug('File is within 4:3 list.')
483 return ['-aspect', '4:3', '-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
485 elif (((rwidth
, rheight
) in [(16, 9), (20, 11), (40, 33), (118, 81),
486 (59, 27)] or vInfo
['dar1'] == '16:9')
487 and (aspect169
or config
.get169Letterbox(tsn
))):
488 debug('File is within 16:9 list and 16:9 allowed.')
490 if config
.get169Blacklist(tsn
) or (aspect169
and
491 config
.get169Letterbox(tsn
)):
495 return ['-aspect', aspect
, '-s', '%sx%s' % (TIVO_WIDTH
, TIVO_HEIGHT
)]
498 settings
= ['-aspect']
500 multiplier16by9
= (16.0 * TIVO_HEIGHT
) / (9.0 * TIVO_WIDTH
) / par2
501 multiplier4by3
= (4.0 * TIVO_HEIGHT
) / (3.0 * TIVO_WIDTH
) / par2
502 ratio
= vInfo
['vWidth'] * 100 * par2
/ vInfo
['vHeight']
503 debug('par2=%.3f ratio=%.3f mult4by3=%.3f' % (par2
, ratio
,
506 # If video is wider than 4:3 add top and bottom padding
508 if ratio
> 133: # Might be 16:9 file, or just need padding on
511 if aspect169
and ratio
> 135: # If file would fall in 4:3
512 # assume it is supposed to be 4:3
514 if (config
.get169Blacklist(tsn
) or
515 config
.get169Letterbox(tsn
)):
516 settings
.append('4:3')
518 settings
.append('16:9')
520 if ratio
> 177: # too short needs padding top and bottom
521 settings
+= pad_TB(TIVO_WIDTH
, TIVO_HEIGHT
,
522 multiplier16by9
, vInfo
)
523 debug(('16:9 aspect allowed, file is wider ' +
524 'than 16:9 padding top and bottom\n%s') %
527 else: # too skinny needs padding on left and right.
528 settings
+= pad_LR(TIVO_WIDTH
, TIVO_HEIGHT
,
529 multiplier16by9
, vInfo
)
530 debug(('16:9 aspect allowed, file is narrower ' +
531 'than 16:9 padding left and right\n%s') %
534 else: # this is a 4:3 file or 16:9 output not allowed
535 if ratio
> 135 and config
.get169Letterbox(tsn
):
536 settings
.append('16:9')
537 multiplier
= multiplier16by9
539 settings
.append('4:3')
540 multiplier
= multiplier4by3
541 settings
+= pad_TB(TIVO_WIDTH
, TIVO_HEIGHT
,
543 debug(('File is wider than 4:3 padding ' +
544 'top and bottom\n%s') % ' '.join(settings
))
546 # If video is taller than 4:3 add left and right padding, this
547 # is rare. All of these files will always be sent in an aspect
548 # ratio of 4:3 since they are so narrow.
551 settings
.append('4:3')
552 settings
+= pad_LR(TIVO_WIDTH
, TIVO_HEIGHT
, multiplier4by3
, vInfo
)
553 debug('File is taller than 4:3 padding left and right\n%s'
554 % ' '.join(settings
))
558 def tivo_compatible_video(vInfo
, tsn
, mime
=''):
561 codec
= vInfo
.get('vCodec', '')
562 if mime
== 'video/mp4':
564 message
= (False, 'vCodec %s not compatible' % codec
)
568 if mime
== 'video/bif':
570 message
= (False, 'vCodec %s not compatible' % codec
)
574 if codec
not in ('mpeg2video', 'mpeg1video'):
575 message
= (False, 'vCodec %s not compatible' % codec
)
578 if vInfo
['kbps'] != None:
579 abit
= max('0', vInfo
['aKbps'])
580 if (int(vInfo
['kbps']) - int(abit
) >
581 config
.strtod(config
.getMaxVideoBR(tsn
)) / 1000):
582 message
= (False, '%s kbps exceeds max video bitrate' %
586 message
= (False, '%s kbps not supported' % vInfo
['kbps'])
589 if config
.isHDtivo(tsn
):
590 if vInfo
['par2'] != 1.0:
591 if config
.getPixelAR(0):
592 if vInfo
['par2'] != None or config
.getPixelAR(1) != 1.0:
593 message
= (False, '%s not correct PAR' % vInfo
['par2'])
595 # HD Tivo detected, skipping remaining tests.
598 if not vInfo
['vFps'] in ['29.97', '59.94']:
599 message
= (False, '%s vFps, should be 29.97' % vInfo
['vFps'])
602 if ((config
.get169Blacklist(tsn
) and not config
.get169Setting(tsn
))
603 or (config
.get169Letterbox(tsn
) and config
.get169Setting(tsn
))):
604 if vInfo
['dar1'] and vInfo
['dar1'] not in ('4:3', '8:9', '880:657'):
605 message
= (False, ('DAR %s not supported ' +
606 'by BLACKLIST_169 tivos') % vInfo
['dar1'])
609 mode
= (vInfo
['vWidth'], vInfo
['vHeight'])
610 if mode
not in [(720, 480), (704, 480), (544, 480),
611 (528, 480), (480, 480), (352, 480), (352, 240)]:
612 message
= (False, '%s x %s not in supported modes' % mode
)
617 def tivo_compatible_audio(vInfo
, inFile
, tsn
, mime
=''):
620 codec
= vInfo
.get('aCodec', '')
623 debug('No audio stream detected')
626 if mime
== 'video/mp4':
627 if codec
not in ('mpeg4aac', 'libfaad', 'mp4a', 'aac',
629 message
= (False, 'aCodec %s not compatible' % codec
)
633 if mime
== 'video/bif':
635 message
= (False, 'aCodec %s not compatible' % codec
)
639 if inFile
[-5:].lower() == '.tivo':
642 if mime
== 'video/x-tivo-mpeg-ts' and codec
not in ('ac3', 'liba52'):
643 message
= (False, 'aCodec %s not compatible' % codec
)
646 if codec
not in ('ac3', 'liba52', 'mp2'):
647 message
= (False, 'aCodec %s not compatible' % codec
)
650 if (not vInfo
['aKbps'] or
651 int(vInfo
['aKbps']) > config
.getMaxAudioBR(tsn
)):
652 message
= (False, '%s kbps exceeds max audio bitrate' %
656 audio_lang
= config
.get_tsn('audio_lang', tsn
)
658 if vInfo
['mapAudio'][0][0] != select_audiolang(inFile
, tsn
)[-3:]:
659 message
= (False, '%s preferred audio track exists' %
665 def tivo_compatible_container(vInfo
, inFile
, mime
=''):
667 container
= vInfo
.get('container', '')
668 if ((mime
== 'video/mp4' and
669 (container
!= 'mov' or inFile
.lower().endswith('.mov'))) or
670 (mime
== 'video/bif' and container
!= 'asf') or
671 (mime
== 'video/x-tivo-mpeg-ts' and container
!= 'mpegts') or
672 (mime
in ['video/x-tivo-mpeg', 'video/mpeg', ''] and
673 (container
!= 'mpeg' or vInfo
['vCodec'] == 'mpeg1video'))):
674 message
= (False, 'container %s not compatible' % container
)
678 def mp4_remuxable(inFile
, tsn
=''):
679 vInfo
= video_info(inFile
)
680 return (tivo_compatible_video(vInfo
, tsn
, 'video/mp4')[0] and
681 tivo_compatible_audio(vInfo
, inFile
, tsn
, 'video/mp4')[0])
683 def mp4_remux(inFile
, basename
):
684 outFile
= inFile
+ '.pyTivo-temp'
685 newname
= basename
+ '.pyTivo-temp'
686 if os
.path
.exists(outFile
):
689 ffmpeg_path
= config
.get_bin('ffmpeg')
690 fname
= unicode(inFile
, 'utf-8')
691 oname
= unicode(outFile
, 'utf-8')
693 fname
= fname
.encode('iso8859-1')
694 oname
= oname
.encode('iso8859-1')
696 cmd
= [ffmpeg_path
, '-i', fname
, '-vcodec', 'copy', '-acodec',
697 'copy', '-f', 'mp4', oname
]
698 ffmpeg
= subprocess
.Popen(cmd
)
699 debug('remuxing ' + inFile
+ ' to ' + outFile
)
701 debug('error during remuxing')
707 def tivo_compatible(inFile
, tsn
='', mime
=''):
708 vInfo
= video_info(inFile
)
710 message
= (True, 'all compatible')
711 if not config
.get_bin('ffmpeg'):
712 if mime
not in ['video/x-tivo-mpeg', 'video/mpeg', '']:
713 message
= (False, 'no ffmpeg')
717 vmessage
= tivo_compatible_video(vInfo
, tsn
, mime
)
722 amessage
= tivo_compatible_audio(vInfo
, inFile
, tsn
, mime
)
727 cmessage
= tivo_compatible_container(vInfo
, inFile
, mime
)
733 debug('TRANSCODE=%s, %s, %s' % (['YES', 'NO'][message
[0]],
737 def video_info(inFile
, cache
=True):
739 fname
= unicode(inFile
, 'utf-8')
740 mtime
= os
.stat(fname
).st_mtime
742 if inFile
in info_cache
and info_cache
[inFile
][0] == mtime
:
743 debug('CACHE HIT! %s' % inFile
)
744 return info_cache
[inFile
][1]
746 vInfo
['Supported'] = True
748 ffmpeg_path
= config
.get_bin('ffmpeg')
750 if os
.path
.splitext(inFile
)[1].lower() not in ['.mpg', '.mpeg',
752 vInfo
['Supported'] = False
753 vInfo
.update({'millisecs': 0, 'vWidth': 704, 'vHeight': 480,
756 info_cache
[inFile
] = (mtime
, vInfo
)
760 fname
= fname
.encode('iso8859-1')
761 cmd
= [ffmpeg_path
, '-i', fname
]
762 # Windows and other OS buffer 4096 and ffmpeg can output more than that.
763 err_tmp
= tempfile
.TemporaryFile()
764 ffmpeg
= subprocess
.Popen(cmd
, stderr
=err_tmp
, stdout
=subprocess
.PIPE
,
765 stdin
=subprocess
.PIPE
)
767 # wait configured # of seconds: if ffmpeg is not back give up
768 wait
= config
.getFFmpegWait()
769 debug('starting ffmpeg, will wait %s seconds for it to complete' % wait
)
770 for i
in xrange(wait
* 20):
772 if not ffmpeg
.poll() == None:
775 if ffmpeg
.poll() == None:
777 vInfo
['Supported'] = False
779 info_cache
[inFile
] = (mtime
, vInfo
)
783 output
= err_tmp
.read()
785 debug('ffmpeg output=%s' % output
)
787 attrs
= {'container': r
'Input #0, ([^,]+),',
788 'vCodec': r
'Video: ([^, ]+)', # video codec
789 'aKbps': r
'.*Audio: .+, (.+) (?:kb/s).*', # audio bitrate
790 'aCodec': r
'.*Audio: ([^, ]+)', # audio codec
791 'aFreq': r
'.*Audio: .+, (.+) (?:Hz).*', # audio frequency
792 'mapVideo': r
'([0-9]+[.:]+[0-9]+).*: Video:.*'} # video mapping
795 rezre
= re
.compile(attrs
[attr
])
796 x
= rezre
.search(output
)
798 vInfo
[attr
] = x
.group(1)
800 if attr
in ['container', 'vCodec']:
802 vInfo
['Supported'] = False
805 debug('failed at ' + attr
)
807 rezre
= re
.compile(r
'.*Video: .+, (\d+)x(\d+)[, ].*')
808 x
= rezre
.search(output
)
810 vInfo
['vWidth'] = int(x
.group(1))
811 vInfo
['vHeight'] = int(x
.group(2))
814 vInfo
['vHeight'] = ''
815 vInfo
['Supported'] = False
816 debug('failed at vWidth/vHeight')
818 rezre
= re
.compile(r
'.*Video: .+, (.+) (?:fps|tb\(r\)|tbr).*')
819 x
= rezre
.search(output
)
821 vInfo
['vFps'] = x
.group(1)
822 if '.' not in vInfo
['vFps']:
823 vInfo
['vFps'] += '.00'
825 # Allow override only if it is mpeg2 and frame rate was doubled
828 if vInfo
['vCodec'] == 'mpeg2video' and vInfo
['vFps'] != '29.97':
829 # First look for the build 7215 version
830 rezre
= re
.compile(r
'.*film source: 29.97.*')
831 x
= rezre
.search(output
.lower())
833 debug('film source: 29.97 setting vFps to 29.97')
834 vInfo
['vFps'] = '29.97'
837 rezre
= re
.compile(r
'.*frame rate differs from container ' +
838 r
'frame rate: 29.97.*')
839 debug('Bug in VideoReDo')
840 x
= rezre
.search(output
.lower())
842 vInfo
['vFps'] = '29.97'
845 vInfo
['Supported'] = False
846 debug('failed at vFps')
848 durre
= re
.compile(r
'.*Duration: ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+),')
849 d
= durre
.search(output
)
852 vInfo
['millisecs'] = ((int(d
.group(1)) * 3600 +
853 int(d
.group(2)) * 60 +
854 int(d
.group(3))) * 1000 +
855 int(d
.group(4)) * (10 ** (3 - len(d
.group(4)))))
857 vInfo
['millisecs'] = 0
859 # get bitrate of source for tivo compatibility test.
860 rezre
= re
.compile(r
'.*bitrate: (.+) (?:kb/s).*')
861 x
= rezre
.search(output
)
863 vInfo
['kbps'] = x
.group(1)
865 # Fallback method of getting video bitrate
866 # Sample line: Stream #0.0[0x1e0]: Video: mpeg2video, yuv420p,
867 # 720x480 [PAR 32:27 DAR 16:9], 9800 kb/s, 59.94 tb(r)
868 rezre
= re
.compile(r
'.*Stream #0\.0\[.*\]: Video: mpeg2video, ' +
869 r
'\S+, \S+ \[.*\], (\d+) (?:kb/s).*')
870 x
= rezre
.search(output
)
872 vInfo
['kbps'] = x
.group(1)
875 debug('failed at kbps')
878 rezre
= re
.compile(r
'.*Video: .+PAR ([0-9]+):([0-9]+) DAR [0-9:]+.*')
879 x
= rezre
.search(output
)
880 if x
and x
.group(1) != "0" and x
.group(2) != "0":
881 vInfo
['par1'] = x
.group(1) + ':' + x
.group(2)
882 vInfo
['par2'] = float(x
.group(1)) / float(x
.group(2))
884 vInfo
['par1'], vInfo
['par2'] = None, None
887 rezre
= re
.compile(r
'.*Video: .+DAR ([0-9]+):([0-9]+).*')
888 x
= rezre
.search(output
)
889 if x
and x
.group(1) != "0" and x
.group(2) != "0":
890 vInfo
['dar1'] = x
.group(1) + ':' + x
.group(2)
894 # get Audio Stream mapping.
895 rezre
= re
.compile(r
'([0-9]+\.[0-9]+)(.*): Audio:(.*)')
896 x
= rezre
.search(output
)
899 for x
in rezre
.finditer(output
):
900 amap
.append((x
.group(1), x
.group(2)+x
.group(3)))
902 amap
.append(('', ''))
903 debug('failed at mapAudio')
904 vInfo
['mapAudio'] = amap
908 # get Metadata dump (newer ffmpeg).
909 lines
= output
.split('\n')
914 if line
.startswith(' Metadata:'):
918 if line
.startswith(' Duration:'):
922 key
, value
= [x
.strip() for x
in line
.split(':', 1)]
924 value
= value
.decode('utf-8')
926 if sys
.platform
== 'darwin':
927 value
= value
.decode('macroman')
929 value
= value
.decode('iso8859-1')
930 rawmeta
[key
] = [value
]
934 vInfo
['rawmeta'] = rawmeta
936 data
= metadata
.from_text(inFile
)
938 if key
.startswith('Override_'):
939 vInfo
['Supported'] = True
940 if key
.startswith('Override_mapAudio'):
941 audiomap
= dict(vInfo
['mapAudio'])
942 stream
= key
.replace('Override_mapAudio', '').strip()
943 if stream
in audiomap
:
944 newaudiomap
= (stream
, data
[key
])
945 audiomap
.update([newaudiomap
])
946 vInfo
['mapAudio'] = sorted(audiomap
.items(),
947 key
=lambda (k
,v
): (k
,v
))
948 elif key
.startswith('Override_millisecs'):
949 vInfo
[key
.replace('Override_', '')] = int(data
[key
])
951 vInfo
[key
.replace('Override_', '')] = data
[key
]
954 info_cache
[inFile
] = (mtime
, vInfo
)
955 debug("; ".join(["%s=%s" % (k
, v
) for k
, v
in vInfo
.items()]))
958 def audio_check(inFile
, tsn
):
959 cmd_string
= ('-y -vcodec mpeg2video -r 29.97 -b 1000k -acodec copy ' +
960 select_audiolang(inFile
, tsn
) + ' -t 00:00:01 -f vob -')
961 fname
= unicode(inFile
, 'utf-8')
963 fname
= fname
.encode('iso8859-1')
964 cmd
= [config
.get_bin('ffmpeg'), '-i', fname
] + cmd_string
.split()
965 ffmpeg
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
)
966 fd
, testname
= tempfile
.mkstemp()
967 testfile
= os
.fdopen(fd
, 'wb')
969 shutil
.copyfileobj(ffmpeg
.stdout
, testfile
)
976 aKbps
= video_info(testname
, False)['aKbps']
980 def supported_format(inFile
):
981 if video_info(inFile
)['Supported']:
984 debug('FALSE, file not supported %s' % inFile
)
988 debug('killing pid=%s' % str(popen
.pid
))
994 debug('sending SIGTERM to pid: %s' % popen
.pid
)
995 os
.kill(popen
.pid
, signal
.SIGTERM
)
997 if popen
.poll() is not None:
998 debug('process %s has exited' % popen
.pid
)
1001 while popen
.poll() is None:
1002 debug('sending SIGKILL to pid: %s' % popen
.pid
)
1003 os
.kill(popen
.pid
, signal
.SIGKILL
)
1008 handle
= ctypes
.windll
.kernel32
.OpenProcess(1, False, pid
)
1009 ctypes
.windll
.kernel32
.TerminateProcess(handle
, -1)
1010 ctypes
.windll
.kernel32
.CloseHandle(handle
)