mathr / blog / #

Two-pass DVD encoding

Assume you have a PPM file video.ppm containing a sequence of uncompressed RGB frames in a resolution of 1024x576 (which has an aspect ratio of 16:9), and you need to encode to Anamorphic Widescreen PAL DVD MPEG2. Further assume that you're not happy with the quality of the output of the single pass of mpeg2enc, so you want to use two-pass encoding. Here's a script that does that, using mencoder with LAVC:

#!/bin/bash
NAME=$1
rm -f divx2pass.log &&
cat video.ppm |
ppmtoy4m -F 25:1 -S 420mpeg2 |
yuvscaler -M RATIO_1024_720_576_576 -O DVD |
mencoder -demuxer y4m -of mpeg \
-mpegopts format=dvd:vaspect=16/9:vframerate=25 -ovc lavc -lavcopts \
vcodec=mpeg2video:vrc_buf_size=1835:keyint=15:vrc_maxrate=9000:vbitrate=7000:\
aspect=16/9:vmax_b_frames=2:vb_strategy=0:mbd=1:trell=yes:vratetol=1000:\
cbp:mv0:cmp=2:subcmp=2:precmp=0:vpass=1 \
- -o out/$NAME.mpg &&
cat video.ppm |
ppmtoy4m -F 25:1 -S 420mpeg2 |
yuvscaler -M RATIO_1024_720_576_576 -O DVD |
mencoder -demuxer y4m -of mpeg \
-mpegopts format=dvd:vaspect=16/9:vframerate=25 -ovc lavc -lavcopts \
vcodec=mpeg2video:vrc_buf_size=1835:keyint=15:vrc_maxrate=9000:vbitrate=7000:\
aspect=16/9:vmax_b_frames=2:vb_strategy=0:mbd=1:trell=yes:vratetol=1000:\
cbp:mv0:cmp=2:subcmp=2:precmp=0:vpass=2 \
- -o out/$NAME.mpg &&
mplayer -dumpfile out/$NAME.m2v -dumpvideo out/$NAME.mpg &&
rm -f out/$NAME.mpg &&
mplex -f 8 -V out/$NAME.m2v audio.m2a -o out/$NAME.vob &&
rm -f out/$NAME.m2v &&
rm -f video.ppm

It took quite some fiddling with the options, I had huge problems with BUFFER UNDEFLOW (sic) Raising Muxrate messages output from LAVC, which basically meant the stream had bandwidth peaks outside the DVD specs and mplex would just give up.

I think the key to success was setting vb_strategy=0 to force the maximum number of B-Frames to be used at all times, combined with vratetol=1000 to restrict the bitrate tolerance by a tighter margin.