Bulk convert mkv h264 to mkv hevc

A nifty script to convert every mkv or mp4 file on a folder from h264 to hevc ( h265 ) maintaining an acceptable quality, my gains were at least 60% reduction in file sizes but YMMV, dependencies are ffmpeg and mediainfo

Start by installing the dependencies.

For Centos 7:


yum install epel-release -y
yum localinstall --nogpgcheck https://download1.rpmfusion.org/free/el/rpmfusion-free-release-7.noarch.rpm -y
yum install  mediainfo libmediainfo ffmpeg ffmpeg-devel -y

 

For Debian:


apt install mediainfo ffmpeg -y

 

Then just copy the script bellow and drop it in a file on your *bin folder and you are good to go, the script keeps the original and create a new file with ‘_hevc.mkv’ suffix but it’s easy enough to mass move/remove the old files.



#!/bin/bash
# Setting a few Default Options
LOGLEVEL="error"
CRFLEVEL="24"
HIDEBANNER="-hide_banner"
SHOWSTATS="-stats"

# Fixing bash 'for' for files with blanks in the name
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

# Gather the files
EXTENSION=".mkv
.mp4"
for j in ${EXTENSION}
do
    echo $j
    FILES=$(find . -iname "*${j}")
    echo $FILES
    for i in $FILES
    do

        IS_HVEC=$(mediainfo $i | grep HEVC -q;echo $?)
        NAME=$(basename $i ${j})
        NAME=${NAME}_hevc.mkv
        AUDIOMODE="copy"
        if [ $IS_HVEC = 0 ];
        then
            echo "File ${i} already already hevc encoded: skipping"
        else
            if [[ -f "${NAME}" ]];
            then
                echo "File ${NAME} already exists ( maybe you already ran the script once?) : skipping"
            else
                echo "Conversion Staring on File :${i} the output will be named ${NAME}"
                ffmpeg -loglevel ${LOGLEVEL}  ${HIDEBANNER} ${SHOWSTATS} -i "$i" -map 0 -c:v libx265 -crf ${CRFLEVEL} -c:a ${AUDIOMODE} -c:s copy "${NAME}"
            fi
        fi
    done
done
# Restoring bash previous behavior
IFS=$SAVEIFS


Sources:

https://slhck.info/video/2017/02/24/crf-guide.html
https://slhck.info/video/2017/03/01/rate-control.html
https://kokomins.wordpress.com/2019/10/10/anime-encoding-guide-for-x265-and-why-to-never-use-flac/
https://trac.ffmpeg.org/wiki/Encode/H.264
https://trac.ffmpeg.org/wiki/Encode/H.265