Simple Automated Video Transcoding…

This post has been sitting in my drafts since 2012. I still use the system described below (occasionally) and it seemed a shame not to post the approach for others to use.

I had a ton of transcoding of videos for storage on my home server/mythbox. My tool of choice has been HandBrake, specifically the CLI version. As I had a fair few videos to get through I wanted to set up some automated system for doing the transcoding. Here is the simple bash script I came up with:

#!/bin/sh

HANDBRAKE_OPTS="-e x264 -q 20.0 -a 1 -E ac3 -B 160 -6 auto -R Auto,Auto -D 0.0 -f mkv --detelecine --decomb --loose-anamorphic -m -2 -T -x b-adapt=2:rc-lookahead=50"
MAILTO=me@webworxshop.com
MAILFROM=transcoder@webworxshop.com
BASEDIR=/mnt/media/transcoding
#BASEDIR=.
INDIR=$BASEDIR/queue
OUTDIR=$BASEDIR/mkvs
DONEDIR=$BASEDIR/done

if [ -e $BASEDIR/.lock ]
then
        echo "Lock file exists, exiting."
        exit 1
fi
touch $BASEDIR/.lock

echo $INDIR
for dir in $(find $INDIR/ -type d | grep VIDEO_TS); do

        toks=(`echo $dir | tr "/" "\n"`)
        HandBrakeCLI -i $dir --main-feature -o $OUTDIR/${toks[4]}.mkv $HANDBRAKE_OPTS
        mv $INDIR/${toks[4]} $DONEDIR/${toks[4]}

        # send the email
        echo "To: $MAILTO" > msg.txt
        echo "From: $MAILFROM" >> msg.txt
        echo "Subject: Transcode Complete" >> msg.txt
        echo "" >> msg.txt
        echo "Transcoding ${toks[4]} completed sucessfully!" >> msg.txt
        cat msg.txt | msmtp $MAILTO
        rm msg.txt

        rm $BASEDIR/.lock

        exit 0;
done

The script requires that you set it up in a directory (/mnt/media/transcoding  on my system) with three sub-directories (queue , mkvs  and done ). The script will transcode one video from the queue  directory on each run. The idea is that the script should be run from cron several times a day when your machine isn’t doing very much else (I run mine overnight and when I’m at work). When the script is done it will send you an email to tell you and move the source file into the done  directory. The transcoded file will be dropped into the mkvs  directory. Obviously, the script will just exit if there’s nothing in the queue. This means that once the system is set up all you have to do is drop new videos into the queue  directory and they will be transcoded automatically.

Let me know if you find this useful, or suggest improvements in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *