sodnpoo.com

encode to filesize

The script below encodes to a mpeg2/ac3 (dvd standard) recalculating the video bitrate to fit the filesize specified. Audio is fixed at 192kbps and estimates a 5% mux overhead.

  
#!/bin/bash

echo usage: $0 file_size filename

audiobitrate="192"
#take 5% mux overhead off
muxoverhead="5"
filesize=`echo "($1-(($1/100)*${muxoverhead}))*1048576" | bc`

skip=0

for filename in "$@"
do
  if [ "$skip" -gt 0 ] #skip first(filesize) param
  then
    length=`mplayer "$filename" -identify -endpos 0 -vo null -vc null -ao null -nosound 2> /dev/null 
    | grep ID_LENGTH= | cut -d "=" -f 2`
    bitrate=`echo "((($filesize/$length)*8)/1024)-$audiobitrate" | bc`
    
    echo "filename: $filename"
    echo "filelen : $length"
    echo "bitrate : $bitrate"
    
    output="${filename%.*}.mpeg"
    output="./${output##*/}"
    
    flags="-oac lavc -ovc lavc -of mpeg -mpegopts format=dvd:tsaf -vf scale=720:576,harddup -srate 48000 
    -af lavcresample=48000 -ofps 25 -lavcopts vcodec=mpeg2video:vrc_buf_size=1835:vrc_maxrate=$bitrate:
    vbitrate=$bitrate:keyint=15:vstrict=0:acodec=ac3:abitrate=$audiobitrate:aspect=16/9:"
    
    flags="-quiet ${flags}"
    
    #add threading
    flags="${flags}threads=8:"
    
    echo "flags: $flags"

    nice mencoder "$filename" -o "/dev/null" ${flags}vpass=1
    nice mencoder "$filename" -o "$output" ${flags}vpass=2

  fi
  
  skip=`echo "$skip+1" | bc`
done