Skip to content

Instantly share code, notes, and snippets.

@chauek
Created March 11, 2018 07:11
Show Gist options
  • Save chauek/e69d6c6292437ad031b09d95a854677d to your computer and use it in GitHub Desktop.
Save chauek/e69d6c6292437ad031b09d95a854677d to your computer and use it in GitHub Desktop.
Bash script to re-encode all movies in current and sub directories to x265.
#!/bin/bash
# Install ffmpeg on OSX
# brew install ffmpeg --with-fdk-aac --with-ffplay --with-freetype --with-libass --with-libvorbis --with-libvpx --with-opus --with-x265
IFS=$'\n'
FILES=$(find . -iname "*.mp4" -o -iname "*.avi" -o -iname "*.MPG" -o -iname "*.MTS" -o -iname "*.mkv" | grep -v -E "_x26[4-5].mp4" | grep -v -E "_x26[4-5].avi")
AMOUNT=$(echo "$FILES" | sed '/^\s*$/d' | wc -l)
AMOUNT="$(echo -e "${AMOUNT}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
echo "FOUND $AMOUNT FILES"
COUNTER=0
for src in $FILES
do
COUNTER=$((COUNTER + 1))
FILESIZE=$(du -h "$src" | cut -f1)
WIDTH=$(ffprobe -v quiet -show_streams "$src" | grep coded_width)
WIDTH=${WIDTH#*=}
dest="${src/.mp4/_x265.mp4}"
dest="${dest/.avi/_x265.mp4}"
dest="${dest/.MPG/_x265.mp4}"
dest="${dest/.MTS/_x265.mp4}"
dest="${dest/.mkv/_x265.mp4}"
if [ "$WIDTH" -gt "1920" ];
then
dest="${src/.mp4/_1080p_x265.mp4}"
dest="${dest/.avi/_1080p_x265.mp4}"
dest="${dest/.MPG/_1080p_x265.mp4}"
dest="${dest/.MTS/_1080p_x265.mp4}"
dest="${dest/.mkv/_1080p_x265.mp4}"
fi;
echo "CONVERTING: $COUNTER($AMOUNT) $FILESIZE $src -> $dest"
echo "CONVERTING: $COUNTER($AMOUNT) $src -> $dest" >> convert_all_movies.log
rc=0
if [ "$WIDTH" -gt "1920" ];
then
ffmpeg -stats -i "$src" -vf "scale=1920:1080,setsar=1" -c:v libx265 "$dest" || rc=$?
else
ffmpeg -stats -i "$src" -c:v libx265 "$dest" || rc=$?
fi;
if [ ! "$rc" -eq "0" ]
then
echo "ERROR: $rc Removing dest and exit"
rm "$dest" 2>/dev/null
exit 1
fi
FILESIZE_AFTER=$(du -h "$dest" | cut -f1)
echo "DONE: $COUNTER($AMOUNT) $FILESIZE -> $FILESIZE_AFTER $src -> $dest"
echo "DONE: $FILESIZE -> $FILESIZE_AFTER $src -> $dest" >> convert_all_movies.log
# TO REMOVE SOURCE
# rm "$src"
# TO LEAVE SOURVE
echo "$src" >> convert_all_movies.to_remove.log
sleep 10
done
# Remove from convert_all_movies.to_remove.log
# cat convert_all_movies.to_remove.log | xargs -I{} rm -v {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment