Encoding to h.264/x264 with mencoder and ffmpeg

Sunday, November 02, 2008 Posted by Psyk 0 comments
Looking at ways to compress and encode movies/videos to a more compact size with minimal noticeable quality loss, led a search to some solid and well developed open source utilities. I run both Windows (home theatre) and Linux on a separate workstation so an open source solution made it much more flexible to use on both platforms.

Windows dvr-ms format is an absolute pain. Don't know why they don't just stick with an open standard like Matroska :) anyways...

First things first. Mencoder etc. has a hard time with DVR-MS files, so strip it using ffmpeg:

ffmpeg -y -i movie.dvr-ms -vcodec copy -acodec copy -f dvd movie.mpg



This extracts the mpg from the dvr-ms file to a more user-friendly format. Yes you'll lose the metadata information...

The following mencoder command creates a high quality h264 movie scaled to roughly 720x480 with aac audio (it all needs to be on one line).
mencoder -vf pullup,softskip,pp=fd,scale=720:-10,hqdn3d,harddup -lavdopts threads=2 -ovc x264 -x264encopts bitrate=1200:subq=6:frameref=6:qcomp=0.8:8x8dct:b_pyramid:weight_b:me=umh:partitions=p8x8,i4x4:bime:brdo:nodct_decimate:trellis=1:direct_pred=auto:level_idc=30:nocabac:threads=auto -oac faac -faacopts br=128:raw:mpeg=4:tns:object=2 -of lavf -lavfopts format=mp4 -sws 9 -ofps 24000/1001 -srate 48000 -alang en movie.mpg -o movie.mp4


Rather than typing all that out, you can use mencoder's "-profile" parameter by creating a mencoder.conf file in ~/.mplayer/mencoder.conf with the following contents:
[h264mp4]
profile-desc="H.264 MP4"
vf=pullup,softskip,pp=fd,scale=720:-10,hqdn3d,harddup
lavdopts=threads=2
ovc=x264=yes
x264encopts=bitrate=1200:subq=6:frameref=6:qcomp=0.8:8x8dct=yes:b_pyramid=yes:weight_b=yes:me=umh:partitions=p8x8,i4x4:bime=yes:brdo=yes:nodct_dec
imate=yes:trellis=1:direct_pred=auto:level_idc=30:nocabac=yes:threads=auto
oac=faac=yes
faacopts=br=128:raw=yes:mpeg=4:tns=yes:object=2
of=lavf=yes
lavfopts=format=mp4
sws=9
ofps=24000/1001
srate=48000


In which case you can then run :
mencoder -profile h264mp4 movie.mpg -o movie.mp4


This creates a h.264 video stream and an aac encoded audio stream perfect for muxing into an MP4 container. Unfortunately mencoder's MP4 muxing is a little broken and will more than likely not play correctly in anything other than mplayer.

To mux it back into a more compliant MP4 format, run ffmpeg again:
ffmpeg -y -i movie.mp4 -vcodec copy -acodec copy movie-remuxed.mp4

Make sure you use a different name for the mp4 output from ffmpeg above so you don't overwrite the original input file.
Labels: