Saturday, December 06, 2008

Convert H264 Matroska files to MP4

Have you ever noticed how Matroska (*.mkv) support on OS X is, um, bad? Yes, Matroska is a wonderful container format in theory, but all the demuxers out there (okay, those in VLC and Perian) seem to be dog-slow. The combination of HD decoding and MKV demuxing brings my first-generation Intel mini to its knees. It seems much happier with MP4 files. Thankfully, one can extract the video and audio from MKV files and re-mux them into MP4 without transcoding. You'll need the following packages from MacPorts:

mkvtoolnix,ffmeg,mpeg4ip

You can grab yourself a coffee or 10 while those compile. Once done, the following script will convert MKV files to MP4 with a minimum of hassle:

#!/bin/sh
# Convert an H264 Matroska file to MP4
# hacked together by Jakob van Santen, December 2008

namelen=${#1}
let bnamelen=namelen-4
basename=${1:0:bnamelen}

info=`mkvinfo "$1"`
echo $info | grep AVC >/dev/null
if [ $? -eq 0 ];
then
    echo 'Found H.264 track'
else
    echo "I can only handle H.264 video. Bye!"
    exit 1
fi

if [[ "$info" =~ ([0-9]{2}\.[0-9]{1,3})\ fps ]]; then
    framerate=${BASH_REMATCH[1]}
    echo "Framerate = $framerate"
else
    echo "Couldn't get the framerate..bye!"
    exit 1
fi

mkvextract tracks "$1" 1:"$basename.h264"
ffmpeg -i "$1" -vn -acodec aac -ac 2 -ab 128 "$basename.aac"

mp4creator -c "$basename.h264" -rate=$framerate "$basename.mp4"
mp4creator -c "$basename.aac" -interleave -optimize "$basename.mp4"

rm "$basename.h264" "$basename.aac"