Skip to content

Instantly share code, notes, and snippets.

@wechain
Forked from philroche/recursive-m4v-convert.sh
Last active November 20, 2022 10:35
Show Gist options
  • Save wechain/1696b6fae350ea6f8dc5c1ae3e669e88 to your computer and use it in GitHub Desktop.
Save wechain/1696b6fae350ea6f8dc5c1ae3e669e88 to your computer and use it in GitHub Desktop.
Recursively convert all files using HandbrakeCLI and save to new folder.
#!/bin/bash
#
# Change this to specify a different handbrake preset. You can list them by running: "HandBrakeCLI --preset-list"
#
#set -ux
set +e
PRESET="Vimeo YouTube 720p30" # or Fast 720p30 or Fast 1080p30
if [ -z "$1" ] ; then
TRANSCODEDIR="."
else
TRANSCODEDIR="$1"
fi
BURN_SUBS=${2:-"false"}
abs_basefolder=`realpath "$TRANSCODEDIR"`
folder_base=`dirname "$abs_basefolder"`
folder_name=`basename "$abs_basefolder"`
output_basedirectory="$folder_base/$folder_name-converted"
mkdir -p "$output_basedirectory"
function recursive_convert {
find "$1" -type d -print0 |
while IFS= read -rd '' directory_to_convert; do
echo "Converting files in $directory_to_convert";
output_directory=$output_basedirectory
if [ "$directory_to_convert" != "$1" ]; then
abs_subfolder=`realpath "$directory_to_convert"`
rel_subfolder=${abs_subfolder#$abs_basefolder/}
#Create output directory
output_subdirectory="$output_basedirectory/$rel_subfolder"
mkdir -p "$output_subdirectory"
output_directory=$output_subdirectory
fi
echo "Converted files will be saved in $output_directory";
# TODO only find video files
# *.mkv *.webm *.flv *.avi *.mov *.wmv *.mp4 *.mp4$ *.m4v *.flv
find "$directory_to_convert" -maxdepth 1 -mindepth 1 -type f -print0 |
while IFS= read -r -d '' file_to_convert; do
file_to_convert_filename=$(basename "$file_to_convert")
if [[ ${file_to_convert_filename: -4} == ".mp4" ]] || [[ ${file_to_convert_filename: -4} == ".mkv" ]]; then
converted_filepath="$output_directory/${file_to_convert_filename%.*}.m4v"
subtitle_srt="$abs_basefolder/${file_to_convert_filename%.*}.srt"
# If the file doesn't exist then convert
if [ ! -e "$converted_filepath" ]; then
if [ -e "$subtitle_srt" ] && [ "$BURN_SUBS" = "true" ]; then
echo "Converting $file_to_convert with hardcoded subs"
HandBrakeCLI --input "$file_to_convert" --output "$converted_filepath" --preset="$PRESET" --srt-file "$subtitle_srt" --srt-codeset UTF-8 --srt-burn -e x265 -B 160 -E ca_aac --loose-anamorphic -w 720 -l 480</dev/null
else
echo "Converting $file_to_convert"
HandBrakeCLI --input "$file_to_convert" --output "$converted_filepath" --preset="$PRESET" -e x265 -B 160 -E ca_aac --loose-anamorphic -w 720 -l 480</dev/null
fi
else
echo "$converted_filepath already exists"
fi
fi
done
done
}
recursive_convert "$abs_basefolder"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment