FFMPEG Web Video Processing Tool

Posted by PR on

In this short article, I cover a small Python script I wrote that uses FFMPEG to generate optimized video components for publishing to the web.

Script was written in Python for wide compatibility and ease of use.

Figure:Python was chosen for its wide compatibility and ease of use.

The purpose of this script was to automate very tedious processes that occur when I author blog articles: the optimization of .MP4 video assets in order to reduce page load time, and the conversion of video assets to support a wider array of web browsers. When running the script, it provides the option of processing a single file or an entire directory, as well as optional .WebM, .Jpg, or .Png file generation. The primary function of the script is to generate an FFMPEG-optimized .MP4 file of the original .MP4 file - using the FFMPEG arguments in the script, a filesize reduction of roughly 80-90% is able to be achieved with only minor reduction in quality. The -webm flag results in the generation a .WebM video comparable to the quality of the input video. The .jpg and .png files result in the generation of an image taken from the first frame of the input video. All resulting filenames consist of the input filename appended with an "_out" suffix.

def process_file(inputFile):
	filename, ext = os.path.splitext(inputFile)
	if ext == ".mp4":
		outFile = filename + "_out" + ext
		os.system("ffmpeg -hide_banner -loglevel warning -i {0} {1}".format(inputFile, outFile))
		
		if makeJpg == True or makePng == True:
			imageExt = ".png"
			if makeJpg == True:
				imageExt = ".jpg"
			outFileThumbnail = filename + "_out" + imageExt
			os.system("ffmpeg -i {0} -vf scale=iw*sar:ih,setsar=1 -vframes 1 {1}".format(inputFile, outFileThumbnail))

		if makeWebm == True:
			outFileWebm = filename + "_out" + ".webm"
			os.system("ffmpeg -hide_banner -loglevel warning -i {0} -c:v libvpx -crf 10 -b:v 320K -c:a libvorbis {1}".format(inputFile, outFileWebm))
			
	else:
		print(usageString)
		sys.exit()

Source:ffmpeg-processing.py


Using this script enables me to capture all of the video media I need, and then process it all in one fell swoop. The resulting files are less than one third the total filesize of the original high quality video file:

Reduced filesizes of video assets after processing the original video.

Figure:Reduced filesizes of video assets after processing the original video.

An example comparison of original and script-processed videos:

Figure:Original video.

Figure:Processed video.

Copyright © ptr-cs