#!/usr/bin/perl
#
opendir( CDIR, "." ) || die "no such dir\n";
while( $file = readdir( CDIR ) )
{
  next if( $file !~ /^z.+\.m..$/ );
  $fout = $file =~ s/\.m..$/.mp4/r;
  $fpng = $fout =~ s/\.mp4$/.png/r;
  $fout =~ s/^z//;
  $filters = `delogo -c "$file" 2>/dev/null`;
  rename "delogo.png", $fpng;
  $audio = "-acodec copy";
  $audio = "-acodec libfdk_aac -b:a 128k" if( $file !~ /.mp4$/ );

  if( $filters =~ /\nSize:\s(\d+)x(\d+)\n/ )
  {
    $w = $1, $h = $2;
    print "=== $file ${w}x${h} ===\n";
    $bitrate = $1 if( $filters =~ /BitRate:\s(\d+)\n/ );
    $bitrate -= 128000;
    $bitrate = int( ( $bitrate + 500 ) / 1000 );
    $delogo  = "";
    $delogo  = $1 if( $filters =~ /\n(delogo=.+)\n/ );
    $crop    = "";
    $crop    = $1 if( $filters =~ /\n(crop=.+)\n/ );
    $w       = $1, $h = $2 if( $crop =~ /crop=(\d+):(\d+):/ );
    $w = int( $w * 720 / $h + .5 ), $h = 720 if( $h > 720 );
    $w-- if( ( $w & 1 ) == 1 );
    $filters = join( ',', $delogo, $crop );
    $filters = $1 if( $filters =~ /^,?([^,]*),?$/ );
    $filters = "-vf " . $filters if( $filters ne "" );
    `ffmpeg -i \"$file\" $filters -vcodec libx264 -s ${w}x${h} -preset slow -crf 21 -maxrate ${bitrate}k -bufsize 5M $audio -threads 6 \"$fout\"`;
  }
}
closedir( CDIR );
exit;

# end
