Skip to content

Instantly share code, notes, and snippets.

@tekkub
Forked from innerfence/mkv2m4v.sh
Created October 11, 2010 03:37
Show Gist options
  • Save tekkub/619933 to your computer and use it in GitHub Desktop.
Save tekkub/619933 to your computer and use it in GitHub Desktop.
mkv to m4v remuxer
#!/bin/bash
#
# mkv2m4v inputfile.mkv
#
# Given an MKV container with H.264 video and AC3 audio, converts
# quickly to an iPad-compatible MP4 container without re-encoding the
# video (so it must already be in an iPad-compatible resolution); the
# audio is downmixed to stereo with Dynamic Range Compression.
#
# Video is not transcoded, just demuxed/muxed
# Audio is downmixed to stereo with DRC
#
# You need these tools:
# * mkvextract (to demux the Matroska file)
# * http://www.bunkus.org/videotools/mkvtoolnix/
# * Just install through MacPorts, it doesn't pull in anything annoying
# * a52dec (to decompress and downmix the ac3)
# * http://liba52.sourceforge.net/
# * Compile from source
# * faac (to recompress the audio to mp4a/aac)
# * http://www.audiocoding.com/
# * Compile from source
# * MP4Box (to remux into MPEG-4 container)
# * http://kurtnoise.free.fr/mp4tools/
# * Pre-compiled standalone OS X executable
ME=$(basename $0)
usage() {
echo "usage: ${ME} inputfile.mkv" 1>&2
exit 1
}
message() {
echo ${ME}: "$@"
}
error() {
message "$@" 1>&2
exit 1
}
checkdep() {
[ ! -z $(which "$@") ] || error "Can't find dependency:" "$@"
}
checkdep mkvmerge
checkdep mkvextract
checkdep a52dec
checkdep faac
checkdep MP4Box
INFILE=$1
shift
if [ "${INFILE}" == "" ]; then
usage
fi
if [ ! -r $INFILE ]; then
error "Can't read $INFILE"
fi
DESTDIR=$(dirname $INFILE)
INFILE_BASE=$(basename $INFILE)
BASE=$DESTDIR/${INFILE_BASE%.*}
message "Analyzing Matroska ..."
mkvmerge -i ${INFILE} > ${BASE}.tid
AC3TID=$(grep A_AC3 ${BASE}.tid | perl -ne '/(\d+)/ and print $1')
AVCTID=$(grep AVC ${BASE}.tid | perl -ne '/(\d+)/ and print $1')
if [ "${AC3TID}" == "" ]; then
error "Couldn't find AC3 stream"
fi
if [ "${AVCTID}" == "" ]; then
error "Couldn't find AVC stream"
fi
message "Demultiplexing Matroska ..."
mkvextract tracks ${INFILE} ${AC3TID}:${BASE}.ac3 ${AVCTID}:${BASE}.264
message "Downmixing AC3 ..."
a52dec -o wav ${BASE}.ac3 > ${BASE}.wav
message "Encoding audio for MP4 ..."
faac -b 96 --mpeg-vers 4 -o ${BASE}.aac ${BASE}.wav
message "Creating MP4 container ..."
MP4Box -add ${BASE}.264:fps=23.976 -add ${BASE}.aac ${BASE}.m4v
message "Cleaning up ..."
rm ${BASE}.{tid,264,ac3,wav,aac}
@mferrier
Copy link

Great script. FYI, all four prerequisites are available as Homebrew packages:
brew install mkvtoolnix a52dec faac mp4box

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment