A simple Python script for automated conversion.
# FFmpeg batch conversion script
# Yunzhu Li
import os
import subprocess
# Convert a single file with FFmpeg
def ffmpeg_conv(file_in, file_out, crf=17, max_bitrate=None, start=None, length=None):
ffmpeg_path = '/path/to/ffmpeg'
cmd = [ffmpeg_path]
# Input
cmd.append('-i')
cmd.append(file_in)
# Video (x264)
cmd.append('-c:v')
cmd.append('libx264')
cmd.append('-profile:v')
cmd.append('high')
cmd.append('-level')
cmd.append('4.2')
cmd.append('-crf')
cmd.append(str(crf))
# Limit maximum bit-rate
if max_bitrate != None:
cmd.append('-maxrate')
cmd.append(str(max_bitrate) + 'M')
cmd.append('-bufsize')
cmd.append(str(max_bitrate * 10) + 'M')
# Audio (AAC)
cmd.append('-c:a')
cmd.append('aac')
# Copy subtitle stream
cmd.append('-scodec')
cmd.append('copy')
# Add start time and length
if start != None and length != None:
cmd.append('-ss')
cmd.append(start)
cmd.append('-t')
cmd.append(length)
# Output path
cmd.append(file_out)
# Execute command
process = subprocess.Popen(cmd)
process.wait()
# Convert all files in a given directory recursively
def conv_path_recursive(path, crf=17, max_bitrate=None):
for root, dirs, files in os.walk(path):
for file_name in files:
file_in = root + '/' + file_name
file_out = root + '/' + file_name + '.conv.mkv'
ffmpeg_conv(file_in, file_out, crf, max_bitrate)
# Convert all files '/to/some/path' with crf=17 and 20Mbps max bit-rate.
conv_path_recursive('/to/some/path', 17, 20)
Another script to remove all trailing .conv.mkv
in file names.
import os
path = '/to/some/path'
for root, dirs, files in os.walk(path):
for file_name in files:
if '.conv.mkv' in file_name:
file_name_new = file_name.replace('.conv.mkv', '')
os.rename(root + '/' + file_name, root + '/' + file_name_new)