Shell Script for recursive video transcoding

So here is the situation, you have a folder of videos in MKV format that you need demuxed and converted to avi’s using xvid codec and AC3 sound. How to do this? First step would be to run mkvextract to demux the original MKV down to a video file and an AC3 track.

Next, you need to run mencoder to remux the video and audio into a nice avi. Mencoder is infamous for creating A/V sync issues, however with the correct parameters it is possible.

Below is a script I wrote to batch demux/remux some MKV’s to avi format, and store them in a new folder.  It takes three paramters at the top:

source_folder: – where the original MKV files are located
destination_folder: – where the new AVI’s will be stores.
word_folder: – a place where temporary files can be created and removed.

Keep in mind, my conversion source and destination folders were on a Western Digital MyBook Essential, and using it as a destination for mencoder transcodes was taking forever ( thats why I am using a temp folder ) Please feel free to adjust this script to suit your situation:

source_folder="/media/MyBook/mkvs";
dest_folder="/media/MyBook/avis";
work_folder="/tmp";

recursive () {
cd "$1"
echo "cd $1"
folder=`pwd | cut -c ${#source_folder}- | cut -c 2-`

directory_array=(*);
for directory in "${directory_array[@]}" ; do
if [ -d "$directory" ] ; then
echo "IN $directory"

if [ ! -d $dest_folder$folder/$directory ]; then
echo "Making Folder $dest_folder$folder/$directory"
mkdir $dest_folder$folder/$directory
chmod 755 $dest_folder$folder/$directory
fi
recursive "$directory"
cd ..
folder=`pwd | cut -c ${#source_folder}- | cut -c 2-`
fi

if [  -f "$directory"  -a  "${directory#*.}" == "mkv" ]; then
if [ ! -f $dest_folder$folder/${directory%%.*}.avi ]; then
echo "ENCODING $dest_folder$folder/${directory%%.*}.avi"
rm $work_folder/temp.*

mkvextract tracks $directory --raw -f 1:$work_folder/temp.m2v --raw -f 2:$work_folder/temp.ac3

mencoder -ffourcc XVID -forcedsubsonly -ovc lavc -of lavf -lavfopts format=avi -oac lavc -channels 6 -lavdopts threads=8 -lavcopts vcodec=mpeg4:vqscale=1:vrc_maxrate=25000:vrc_buf_size=5000:acodec=ac3:abitrate=640 -vf filmdint -noskip $work_folder/temp.m2v -audiofile $work_folder/temp.ac3 -o $work_folder/final.avi  -ofps 24000/1001

mv $work_folder/final.avi $dest_folder$folder/${directory%%.*}.avi
rm $work_folder/temp.*
fi
fi
done
}

recursive $source_folder
Bookmark the permalink.

Leave a Reply

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