Here’s a little script that calls HandBrake‘s CLI interface to convert a whole directory full of media in a recursive manner.
No Instructions. No warranty. No guarantees. Your mileage may vary. Yadda Yadda Yadda.
Tested on Ubuntu and MacOS 10.6
Download it here or just read it (better to download it, since my blog removes the whitespace and hence the flow of the script):
#!/usr/bin/python
# This script requires the HandBrake CLI program
# Download it at http://handbrake.fr/downloads2.php
# You’ll need to change this to fit where everything is on your system
sFromDirectory = “/home/jeff/Videos/”
sToDirectory = “/home/jeff/Desktop/converted_video_output/”
sFullPathToHandbrakeCLI = “/usr/bin/HandBrakeCLI”
# Don’t mess with anything below this…..
import os.path
import shutil
def ConvertFile(sPath, sFile):
global sToDirectory
global sFromDirectory
global sFullPathToHandbrakeCLI
sExtension = os.path.splitext( sFile )
sNewFileName = sFile.replace(sExtension[len(sExtension) – 1], “.m4v”)
sNewDirectory = sPath.replace(sFromDirectory, sToDirectory)
if sPath != “”:
sOldFullPath = sPath + “/” + sFile
else:
sOldFullPath = sPath + sFile
if sPath != “”:
sNewFullPath = sNewDirectory + “/” + sNewFileName
else:
sNewFullPath = sNewDirectory + sNewFileName
# Don’t re-encode if it’s already a m4v
if not os.path.exists(sNewFullPath):
if sExtension == “.m4v”:
# Copy it instead of re-encoding it…
shutil.copyfile(sOldFullPath, sNewFullPath)
else:
sHandbrakeCommand = sFullPathToHandbrakeCLI + ‘ -i “‘ + sOldFullPath + ‘” -o “‘ + sNewFullPath + ‘” -v -m -E aac,ac3 -e x264 -q 0.65 -x ref=3:mixed-refs:bframes=6:b-pyramid=1:weightb=1:analyse=all:8x8dct=1:subme=7:me=umh:merange=24:filter=-2,-2:trellis=1:no-fast-pskip=1:no-dct-decimate=1:direct=auto’
os.system(sHandbrakeCommand)
def callback( arg, sDirectory, aFilenames ):
global sToDirectory
global sFromDirectory
print “Checking files in ” + sDirectory
sSubPath = sDirectory.replace(sFromDirectory, “”)
for sFile in aFilenames:
if sSubPath == “”:
sOldFullPath = sDirectory + sFile
else:
sOldFullPath = sDirectory + “/” + sFile
if os.path.isdir(sOldFullPath):
sNewDirectory = sOldFullPath.replace(sFromDirectory, sToDirectory)
print “”
if not os.path.exists(sNewDirectory):
print “Making new directory: ” + sNewDirectory
print “”
os.mkdir(sNewDirectory)
else:
ConvertFile(sDirectory,sFile)
if not os.path.exists(sToDirectory):
os.mkdir(sToDirectory)
arglist = []
os.path.walk(sFromDirectory,callback,arglist)
Updated (September 3rd): Fixed a directory recursion issue.