Advertisement
qiwichupa

Merging different size/format video with avconv and MP4Box

Mar 19th, 2014
528
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.21 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. """
  4. Script: avmerge.py
  5. Author: Sergey "Qiwichupa" Pavlov
  6. Version: 2.03
  7.  
  8. This script was created for merging stream parts from twitch.tv service (but should be versatile). Sometimes it is very simple task, but sometimes resizing and reencoding is needed.
  9. Ok, to the code. First of all this script was written for executing in current directory. I use 'os.listdir' for searching files by extension ('fileExt' variable). Then I use 'avconv' for scaling to 'maxWidth' and 'maxHeight', adding black borders if it's needed, and reencoding video to mp4 container with 'libx264' and 'libmp3lame' codecs. In the end I merge temporary files into one 'out.mp4' with 'MP4Box' from GPAC package.
  10.  
  11. This script was tested on Linux Mint with:
  12. avconv version 0.8.10-6:0.8.10-0ubuntu0.13.10.1
  13. MP4Box - GPAC version 0.5.1-DEV-rev4065
  14. also it's fully operational on Windows 7 x64 with 'avconv' and 'MP4Box' binaries from http://win32.libav.org/win64/ and http://gpac.wp.mines-telecom.fr/downloads/, and Python installed of course.
  15.  
  16. Thanks to Kevin Locke for his mighty scale options: http://kevinlocke.name/bits/2012/08/25/letterboxing-with-ffmpeg-avconv-for-mobile/
  17.  
  18. ChangeLog:
  19. === 2.03 ===
  20. * First parameter for MP4Box (in 'mp4boxmerge' function, outside the cycle) was changed from '-add' to '-cat'. This part of code must be rewritten in the future.
  21. === 2.02 ===
  22. * minor fix
  23. === 2.01 ===
  24. * minor fix
  25. === 2.0 ===
  26. + default Width/Heigth options for wide resolution
  27. + params module with wide/resolution rewrite/extention rewrite options
  28. = code rewrite and optimizing
  29. """
  30.  
  31. import os
  32. import subprocess
  33. import argparse
  34.  
  35. # # # # # # # #
  36. # # SETTINGS  #
  37. # # # # # # # #
  38.  
  39. # Width and Height default value
  40. maxWidth  = '960'
  41. maxHeight = '720'
  42. # Width and Height default value for -w (--wide) option
  43. maxWidthWide  = '1280'
  44. maxHeightWide = '720'
  45. # Tool path
  46. # (Use absolute path in windows (for example: 'C:\Program Files\GPAC\MP4Box')
  47. # if MP4Box.exe and avconv.exe not in PATH-folders)
  48. MP4BoxCmd = 'MP4Box'
  49. avconvCmd = 'avconv'
  50. # default extention of source files
  51. fileExt   = '.flv'
  52.  
  53.  
  54.  
  55. # # # # # # # # # #
  56. # # HELP & PARAMS #
  57. # # # # # # # # # #
  58.  
  59. parser = argparse.ArgumentParser(prog='avmerge.py', description='Script for merging video files with re-encoding. Run it from directory with video files. Use "Settings" section of script for tuning.')
  60. resolutionArgsGroup = parser.add_mutually_exclusive_group()
  61. resolutionArgsGroup.add_argument("-r", "--resolution", metavar=('W','H'), type=int, nargs=2, help="rewrite resolution settings with 'Width Height'")
  62. resolutionArgsGroup.add_argument("-w", "--wide", help= "use wide resolution from in-script settings", action="store_true")
  63. parser.add_argument('-e', '--extention', type=str, help='rewrite extention option (use "ext" or ".ext" format as you like)' )
  64. args = parser.parse_args()
  65.  
  66. if args.wide:
  67.     maxWidth  = maxWidthWide
  68.     maxHeight = maxHeightWide
  69. if args.resolution:
  70.     maxWidth  = str(args.resolution[0])
  71.     maxHeight = str(args.resolution[1])
  72. if args.extention:
  73.    fileExt = args.extention
  74.  
  75.  
  76. # # # # # # # #
  77. # # FUNCTIONS #
  78. # # # # # # # #
  79.  
  80. def avconvert (avconvPath, sourceFile, maxWidth, maxHeight):
  81.     #import os
  82.     #import subprocess
  83.  
  84.     frameRate    = '30'
  85.     outFile      = "tmp_" + sourceFile + ".mp4"
  86.     scaleOptions = 'scale=iw*sar*min(' + maxWidth + '/(iw*sar)\,' + maxHeight + '/ih):ih*min(' + maxWidth+ '/(iw*sar)\,' + maxHeight + '/ih),pad=' + maxWidth+ ':' + maxHeight + ':(ow-iw)/2:(oh-ih)/2'
  87.     convertCmdString = [avconvPath,
  88.                   '-i', sourceFile,
  89.                   '-map', '0',
  90.                   '-vf',  scaleOptions,
  91.                   '-c:a', 'libmp3lame', #libvo_aacenc, libmp3lame
  92.                   '-ar', '48000',
  93. #                 '-ab', '128k',    # uncomment for constant audio bitrate
  94. #                 '-async', '30',       # uncomment if audio is not synchronized after converting
  95.                   '-c:v', 'libx264',
  96.                   '-r', frameRate,
  97.                   '-bf', '2',
  98.                   '-g', '30',
  99.                   '-profile:v', 'high',
  100.                   '-preset', 'fast',
  101.                   '-level', '42',
  102.                   outFile]
  103.     if os.path.isfile(outFile):
  104.         print('File Exist: ' + outFile)
  105.     else:
  106.         output = subprocess.Popen(convertCmdString).communicate()
  107.         print(output)
  108.     return os.path.abspath(outFile)
  109.  
  110. def mp4boxmerge (MP4BoxCmd, inFiles, outFile):
  111.     #import os
  112.     #import subprocess
  113.  
  114.     if len(inFiles) > 1:
  115.         MP4BoxCmdString = []
  116.         MP4BoxCmdString.append(MP4BoxCmd)
  117.         MP4BoxCmdString.append('-cat')
  118.         MP4BoxCmdString.append(inFiles[0])
  119.         for i in range (1,len(inFiles)):
  120.             MP4BoxCmdString.append('-cat')
  121.             MP4BoxCmdString.append(inFiles[i])
  122.         MP4BoxCmdString.append(outFile)
  123.         output = subprocess.Popen(MP4BoxCmdString).communicate()
  124.         print(output)
  125.  
  126.  
  127.  
  128. # # # # # # # #
  129. # # MAIN CODE #
  130. # # # # # # # #
  131.  
  132. convertedFiles = []
  133.  
  134. for inFile in sorted(os.listdir('.')):
  135.     if not inFile.endswith(fileExt):
  136.         continue
  137.     outFile  = avconvert(avconvCmd, inFile, maxWidth, maxHeight)
  138.     convertedFiles.append(outFile)
  139.  
  140.  
  141. mp4boxmerge(MP4BoxCmd,convertedFiles,'out.mp4')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement