Skip to content

Instantly share code, notes, and snippets.

@tree-s
Last active August 21, 2024 00:10
Show Gist options
  • Save tree-s/e0229791e51a7773fb83afeca2981676 to your computer and use it in GitHub Desktop.
Save tree-s/e0229791e51a7773fb83afeca2981676 to your computer and use it in GitHub Desktop.
Batch convert scripts for normalizing video file encoding
#!/bin/sh
################################################################################
#
# Script to recursively search a directory and batch convert all files of a
# given file type into another file type via HandBrake conversion.
#
# To run in your environment set the variables:
# hbcli - Path to your HandBrakeCLI
# ffmpeg - Path to the ffmpeg
#
# dirs - Array of starting directories for recursive search
#
# input_file_type - Input file type to search for
#
# output_file_type - Output file type to convert into
#
#
# Change log:
# 2017-10-13: Publish to Gist.
# 2016-05-01: Added support for aditional processors.
# 2016-03-06: Initial release. Tested on Mac OS X Lion.
# 2012-02-09: Added ability to process multiple directories.
# 2012-02-12: Added default system beep to signal end of all processing.
#
###############################################################################
hbcli=./HandBrakeCLI
ffmpeg=./ffmpeg
input_file_type="mkv"
output_file_type="mp4"
handbrake=false
dirs=( "searchdirs" )
echo "# Using HandBrakeCLI at "$hbcli
echo "# Using ffmpeg at "$ffmpeg
echo "# Converting "$input_file_type" to "$output_file_type
# Convert from one file to another
convert_handbrake() {
# The beginning part, echo "" | , is really important. Without that, HandBrake exits the while loop.
echo ""# | $hbcli -i "$1" -o "$2" --preset="High Profile";
}
convert_ffmpeg() {
echo ""# | $ffmpeg -i "$1" -preset ultrafast -strict -2 -c:v libx264 -c:a aac -b:a 192k "$2";
}
# Iterate over the array of directories
for i in "${dirs[@]}"
do
echo "Processing source directory: " $i
# Find the files and pipe the results into the read command because the read command properly handles spaces in directories and files names.
find "$i" -name *.$input_file_type | while read in_file
do
echo "Processing file..."
echo ">Input "$in_file
# Replace the file type
out_file=$(echo $in_file|sed "s/\(.*\.\)$input_file_type/\1$output_file_type/g")
echo ">Output "$out_file
if [ "$handbrake" = "true" ]
then
# Convert the file using handbrake
convert_handbrake "$in_file" "$out_file"
else
# Convert the file using ffmpg
convert_ffmpeg "$in_file" "$out_file"
fi
if [ $? != 0 ]
then
echo "$in_file had problems" >> handbrake-errors.log
fi
echo ">Finished "$out_file "\n\n"
done
done
echo "DONE CONVERTING FILES"
echo -en "\007"
echo -en "\007"
echo -en "\007"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment