Guest User

Untitled

a guest
Jul 20th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.19 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Created By: Christian Blades <christian DOT blades AT docblades DOT com>
  3. # Requires mkvtoolnix, python-argparse, ffmpeg, libfaac and gpac
  4.  
  5. import os, uuid, argparse, mkvinfo_parser, re, subprocess
  6.  
  7. MKVEXTRACT = 'mkvextract'
  8. MKVINFO = 'mkvinfo-text'
  9. FFMPEG = 'ffmpeg'
  10. FFPROBE = 'ffprobe'
  11. AAC = 'libfaac'
  12. MP4BOX = 'MP4Box'
  13.  
  14. def sanitize_in(inStr):
  15. clean = re.sub("[\n;&]", " ", inStr).strip()
  16. return clean
  17.  
  18. def get_audio_rate(path):
  19. """ Uses ffprobe and grabs the kb/s from the bitrate line"""
  20. #pout, perr = os.popen4("{0} {1}".format(FFPROBE, path))
  21. p = subprocess.Popen("{0} {1}".format(FFPROBE, path),
  22. shell=True, stdin=subprocess.PIPE,
  23. stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
  24. close_fds=True)
  25. perr = p.stdout
  26. bitrate = None
  27. reBitrate = re.compile("bitrate: ([0-9]+) kb/s")
  28. for line in perr:
  29. match = reBitrate.findall(line)
  30. if len(match) > 0:
  31. bitrate = match[0]
  32. break
  33. if bitrate is None:
  34. raise Exception("ffprobe did not return a bitrate for {0}".format(path))
  35. perr.close()
  36. return bitrate
  37.  
  38. def get_video_fps(path):
  39. """ Parse MKVInfo into a tree, then extract the video FPS """
  40. cmdStr = "{0} {1}".format(MKVINFO, path)
  41. myFile = os.popen(cmdStr)
  42. myTree = mkvinfo_parser.parse(myFile)
  43. myFile.close()
  44. fps = mkvinfo_parser.get_vid_fps(myTree)
  45. return fps
  46.  
  47. def existing_file(path):
  48. """ Argparser type """
  49. path = sanitize_in(path)
  50. if not os.path.isfile(path):
  51. raise argparse.ArgumentTypeError("{0} does not exist".format(path))
  52. return path
  53.  
  54. def new_file(path):
  55. """ Argparser type """
  56. path = sanitize_in(path)
  57. try:
  58. aFile = open(path, 'w')
  59. aFile.close()
  60. except IOError:
  61. raise argparse.ArgumentTypeError("{0} is a bad path, or you do not have write permissions")
  62. return path
  63.  
  64. def existing_dir(path):
  65. """ Argparser type """
  66. path = sanitize_in(path)
  67. if not os.path.isdir(path):
  68. raise argparse.ArgumentTypeError("{0} is not a valid path".format(path))
  69. return path
  70.  
  71. parser = argparse.ArgumentParser(
  72. description="Transcodes the audio from a MKV into AAC and then repacks into an avi")
  73. parser.add_argument('inFile', help='Input Filename',
  74. type=existing_file, metavar='FILE')
  75. parser.add_argument('--out', help='Output Filename',
  76. type=new_file)
  77. parser.add_argument('--brate', help='Audio Bitrate (0 = same as source)',
  78. type=int, default=0, nargs=1)
  79. parser.add_argument('--cleanup', help='Clean up temporary files',
  80. default=False, type=bool, nargs=1, metavar='True|False')
  81. parser.add_argument('--tempdir', help='Where to put the temp files. Default is current directory."',
  82. default=os.path.curdir, type=existing_dir)
  83. parser.add_argument('--reverse', help='Audio and Video tracks are in opposite order',
  84. default=False, type=bool, nargs=1, metavar='True|False')
  85.  
  86. theVars = parser.parse_args()
  87. theuuid = str(uuid.uuid1())
  88. tmpPath = os.path.join(theVars.tempdir, theuuid)
  89.  
  90. if theVars.out is None:
  91. theVars.out = "{0}.mp4".format(os.path.splitext(theVars.inFile)[0])
  92.  
  93. print "===Extracting audio and video tracks"
  94. if theVars.reverse:
  95. cmdStr = "{0} tracks {1} 1:{2}.dts 2:{2}.264"
  96. else:
  97. cmdStr = "{0} tracks {1} 1:{2}.264 2:{2}.dts"
  98. cmdStr = cmdStr.format(MKVEXTRACT, theVars.inFile, tmpPath)
  99. os.system(cmdStr)
  100.  
  101. print "===Converting audio"
  102. brate = theVars.brate
  103. if brate == 0:
  104. brate = get_audio_rate("{0}.dts".format(tmpPath))
  105. cmdStr = "{0} -i {1}.dts -acodec libfaac -ab {2}k {1}.aac"
  106. cmdStr = cmdStr.format(FFMPEG, tmpPath, brate)
  107. os.system(cmdStr)
  108.  
  109. try:
  110. os.remove("{0}.dts".format(tmpPath))
  111. except OSError:
  112. print "Failed to remove temp file {0}.dts".format(tmpPath)
  113.  
  114. print "===Repacking as MP4"
  115. fps = get_video_fps(theVars.inFile)
  116. cmdStr = "{0} -new {1} -add {2}.264 -add {2}.aac -fps {3}"
  117. cmdStr = cmdStr.format(MP4BOX, theVars.out, tmpPath, fps)
  118. os.system(cmdStr)
  119.  
  120. try:
  121. os.remove("{0}.264".format(tmpPath))
  122. os.remove("{0}.aac".format(tmpPath))
  123. except OSError:
  124. print "There was an error while cleaning up temporary files. Sorry."
Add Comment
Please, Sign In to add comment