import sys, getopt, time, os, pipes
try:
from ffprobe import FFProbe
except ImportError:
raise ImportError('Please install the python ffprobe package. E.g with: sudo pip2 install ffprobe')
def printHelp(argv):
print argv[0] + ' -i <inputfile> -o <outputfile> [-s <start hh:mm:ss> -e <end hh:mm:ss> -ac <audio codec name> --overwrite]'
def errorMsg(msg):
print msg
sys.exit(2)
def isTimeFormat(input):
try:
time.strptime(input, '%H:%M:%S')
return True
except ValueError:
return False
def main(argv):
ffmpeg_args = ["ffmpeg"]
inputfile = ''
concatfile = ''
outputfile = None
start = None
end = None
acodec = None
overwrite = False
audio_index = None
try:
opts, args = getopt.getopt(argv[1:],"hi:o:s:e:a:c:f",["ifile=","ofile=","start=","end=","acodec=", "concat=", "overwrite"])
except getopt.GetoptError:
printHelp(argv)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
printHelp(argv)
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-c", "--concat"):
concatfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
elif opt in ("-s", "--start"):
start = arg
elif opt in ("-e", "--end"):
end = arg
elif opt in ("-a", "--acodec"):
acodec = arg
elif opt in ("-f", "--overwrite"):
overwrite = True
if concatfile is not '':
concat_file = open(concatfile, "r")
videofiles = concat_file.read().splitlines()
inputfile = videofiles[0].replace("file '", "").replace("'", "")
ffmpeg_args.append("-f concat")
ffmpeg_args.append("-i")
if not os.path.isfile(inputfile):
errorMsg("Input file '" + inputfile + "' doesn't exist")
if outputfile is None:
outputfile = inputfile.replace(".m2t", ".mkv");
outputfile = outputfile.replace("raw/", "");
if os.path.isfile(outputfile) and not overwrite:
errorMsg("Output file '" + inputfile + "' does exist. Use -f to overwrite")
if concatfile is not '':
ffmpeg_args.append(pipes.quote(concatfile))
else:
ffmpeg_args.append(pipes.quote(inputfile))
ffmpeg_args.append("-sn")
if start is not None:
if isTimeFormat(start):
ffmpeg_args.append("-ss " + start)
else:
errorMsg("Start time '" + start + "' has wrong format")
if end is not None:
if isTimeFormat(end):
ffmpeg_args.append("-to " + end)
else:
errorMsg("End time '" + end + "' has wrong format")
ffmpeg_args.append("-c:v libx264 -map 0:0 -c:a copy")
if acodec is not None:
metadata=FFProbe(inputfile)
for stream in metadata.streams:
if stream.isAudio() and stream.codec() == acodec:
audio_index = stream.__dict__['index']
break
if audio_index is None:
print("Audio stream with codec '" + acodec + "' not found, using 0")
else:
ffmpeg_args.append("-map 0:" + audio_index)
ffmpeg_args.append("-f matroska")
ffmpeg_args.append(pipes.quote(outputfile))
print ' '.join(ffmpeg_args)
if __name__ == "__main__":
main(sys.argv)