#!/usr/bin/perl -w
# munge lavc's multipass stats file to force closed gop
# by Loren Merritt
# last updated 2004-12-22

$usage = <<'EOT';
usage:

LAVCOPT="mbd=2:trell:v4mv"
mencoder $infile -o /dev/null -ovc lavc -lavcopts vpass=1:vqscale=2
close_gop.pl divx2pass.log
mencoder $infile -o /dev/null -ovc lavc -lavcopts vpass=3:vqscale=2:vmax_b_frames=1:sc_threshold=1000000:$LAVCOPT
mencoder $infile -o $outfile  -ovc lavc -lavcopts vpass=3:vbitrate=$BR:vmax_b_frames=1:sc_threshold=1000000:$LAVCOPT

This example just uses simple encoding settings.
Feel free to add a 4th pass (i.e. 3rd pass from the perspective of ratecontrol)
and tweak the lavcopts (e.g. use slower options on the last pass).
The important part is that the pre-pass does _not_ use B-frames, and that
subsequent passes have scenechange detection disabled.
Also, the "vpass=3" in the 2nd pass is not a typo.

The pre-pass (vpass=1) is not used for ratecontrol, so there's no point in
using slow settings. Maybe try mbcmp=1:subcmp=1:dia=-1 (I haven't tested how
much this helps).
EOT

$file = shift or die $usage;
open FH, "<", $file or die "can't read $file: $!";
$txt = join "", <FH>;
close FH;

if($txt =~ /type:3/){
    die "$file already contains B-frames! GOP closing failed.\n";
}

$txt =~ s/
in:(\d+)\s+out: \1 \s+type:2(.+)\n
in:(\d+)\s+out: \3 \s+type:2(.+)\n
/in:$3 out:$1 type:2$4
in:$1 out:$3 type:3$2
/xg;

rename $file, "$file.bak";
open FH, ">", $file or die "can't write $file: $!";
print FH $txt;
close FH;

