#!/bin/bash

# ======================== vid2gp - FAST video resizer =========================
# Author    : Alberto Cavalin
# Home page : http://www.camelsoft.tk
# Released  : 2007-08-03
# Requires  : transcode, mplayer, xvid4, lame, sed, bc
# ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
# This is a bash script that uses transcode in order to RESIZE your videos.
#
# This script only resizes your videos and NOT reencodes them, this means that
# you can SAVE a lot of TIME and about 30-50% of disk space!! ^___^
#
# Given an Mplayer compatible video file, this script outputs a standard video
# in an AVI container using Xvid4 and MP3 as default codecs (fully readable from
# your GP2X).
#
# This script will automatically adjust the video size in order to minimize it
# to 320x240 (keeping the aspect ratio), and eventually adds some pixels of
# black border so the W or H can be a multiple of 8 (this speeds up the resizing
# process a lot).
# In addition it will add an additional black border in order to obtain a full
# 320x240 screen. This feature was added to overcome to a GP2X Mplayer/MP2X bug
# which wrongly cuts *some* videos, making the subtitles unreadable.
# ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
# v1.5: * all videos to 320x240, keeping aspect ratio, adding black border
#       * made some cleanup on the source
# v1.4: * corrected the returned size format (XXX.YY instead of XXX)
#       * $TMP now points to "/tmp" and not "/tmp/ram"
# v1.3: * rewrited the entire script in a better manner
#       * rewrited dimensions calculation steps
#       * added 5 presetted profiles! (see quality parameter)
#       * customizable temp dir ($TMP) and file suffix ($SFIX)
# v1.2: * added the customization of the temp directory (look in default params)
#       * corrected the printed frame count
#       * adjusted the help
# v1.1: * corrected a dimension calculation error (W based on H)
# v1.0: * first release
# =================================================================[set TAB=4]==


# __ script settings ___________________________________________________________
SVER="1.5"			# script version     - #.#
COLORS="y"			# colors usage flag  - y|n
TMP="/tmp"			# temp files dir     - string
SFIX="gp2x"			# output file suffix - string
NICE=19				# process priority   - 0-19
DBG=1				# debug level        - 0, 2^(0-8) <-> 0, 1, 2, 4, ..., 256


# __ setting up color variables ________________________________________________
if [ $COLORS = "y" ]; then
	# foreground
	FG_BLACK="\033[0;30m";    FG_RED="\033[0;31m";     FG_GREEN="\033[0;32m";
	FG_YELLOW="\033[0;33m";   FG_BLUE="\033[0;34m";    FG_MAGENTA="\033[0;35m";
	FG_CYAN="\033[0;36m";     FG_WHITE="\033[0;37m";
	# light foreground
	FG_LTBLACK="\033[1;30m";  FG_LTRED="\033[1;31m";   FG_LTGREEN="\033[1;32m";
	FG_LTYELLOW="\033[1;33m"; FG_LTBLUE="\033[1;34m";  FG_LTMAGENTA="\033[1;35m";
	FG_LTCYAN="\033[1;36m";   FG_LTWHITE="\033[1;37m";
	# background
	BG_BLACK="\033[0;40m";    BG_RED="\033[0;41m";     BG_GREEN="\033[0;42m";
	BG_YELLOW="\033[0;43m";   BG_BLUE="\033[0;44m";    BG_MAGENTA="\033[0;45m";
	BG_CYAN="\033[0;46m";     BG_WHITE="\033[0;47m";
	# styles
	FG_BD="\033[1m";          FG_UL="\033[4m";         NOCOLOR="\033[0m";
fi
function normcol () { if [ $COLORS = "y" ]; then tput sgr0; fi; }


# __ print the title ___________________________________________________________
echo -en "$BG_BLACK$FG_LTWHITE"
echo "._______________________________________________________________________."
echo "|     >>>        FAST video resizer \`\`vid2gp'' Ver. $SVER         <<<     |"
echo "'-----------------------------------------------------------------------'"
echo -en "$NOCOLOR"
echo


# __ checking arguments ________________________________________________________
if [ -z "$1" ]; then
	echo "USAGE: `basename $0` video.ext [quality]"
	echo
	echo "       Quality goes from 0(fastest) to 5(insane):"
 	echo -e "         $FG_CYAN""0$NOCOLOR - fast    -> -Q=0,0 -Z fast,fast (default)"
	echo -e "         $FG_LTGREEN""1$NOCOLOR - good    -> -Q=5,5 -Z fast"
	echo -e "         $FG_GREEN""2$NOCOLOR - great   -> -Q=4,4"
	echo -e "         $FG_YELLOW""3$NOCOLOR - best    -> -Q=5,5"
	echo -e "         $FG_LTBLUE""4$NOCOLOR - perfect -> -Q=5,5 -J smartdeinter"
	echo -e "         $FG_LTRED""5$NOCOLOR - insane  -> -Q=5,5 + a lot of options"
	exit
fi


# __ setting up script variables _______________________________________________
infile="$1"			# input file name
outfile=`basename "$infile" | sed "s/^\(.*\.\)\(.*\)$/\1$SFIX.\2/"`
if [ -z "$outfile" ]; then outfile="$SFIX.$infile"; fi
PROF=""; PROFN=""	# compression profiles settings
case "$2" in
	"1")	PROF=",fast  -Q=5,5";			PROFN="# good";;
	"2")	PROF="  -Q=4,4";				PROFN="# great";;
	"3")	PROF="  -Q=5,5";				PROFN="# best";;
	"4")	PROF="  -Q=5,5  -J smartdeinter"; PROFN="# perfect";;
	"5")	PROF="  -Q=5,5  -J smartdeinter  -J hqdn3d  --zoom_filter Triangle"
			PROFN="# insane!";;
	  *)	PROF=",fast,fast  -Q=0,0";		PROFN="# fast!";;
esac


# __ setting up functions ______________________________________________________
# get offsets from the nearest multiple of 8
function get1stClip () {
	# $1 = width|height
	# return (2 lines): offset1, offset2;
	echo "scale=4; v=$1/8; scale=0; if (v-v/1>0) v=v/1+1; o=(v*8-$1); o/2;     \
	      o/2+o%2;" | bc
}
# get the half difference between 2 numbers
function get2ndClip () {
	# $1 = width|height
	# $2 = size (usually 320 or 240)
	echo "($2-$1)/2;" | bc
}
# calculate the other dimension
function getDim () {
	# $1 = width, $2 = height
	# return (2 lines): 0|1 -> h|w;  h|w;
	echo "x=$1; y=$2; scale=8; if (x/y >= 4/3) { l=320; 0; } else { l=240; t=x;\
          x=y; y=t; 1; }; h=(y/x)*l; scale=0; if (h/1%8>0) { h=(h/1/8+1)*8 };  \
          h/1;" | bc
}


# __ start the conversion ______________________________________________________
echo "===== calculating new video size ========================================"
# read width and height from the input file
wh=`tcprobe -i "$infile" 2> /dev/null | grep "frame size" | \
	sed 's/.*g* \([0-9]\+\)x\([0-9]\+\) \[*.*/\1\n\2/'`
w=`echo "$wh" | head -n 1`
h=`echo "$wh" | tail -n 1`
# checking $w and $h content
if [ -z "$w" -o -z "$h" ]; then
	echo "Can't get video dimensions, please enter them:"
	echo -n "  width  = "
	read w
	echo -n "  height = "
	read h
fi
# calculating the other dimension
res_w=0; res_h=0; hc1=0; hc2=0; vc1=0; vc2=0;
flag=`getDim $w $h | head -n1`
if [ $flag -eq 0 ]; then
	# get height
	res_w=320
	res_h=`getDim $w $h | head -n2 | tail -n1`
else
	# get width
	res_w=`getDim $w $h | head -n2 | tail -n1`
	res_h=240
fi
# calculate extra border to add (1st clip)
lc=`get1stClip $w | head -n1`	# left   clip offset
rc=`get1stClip $w | tail -n1`	# right  clip offset
tc=`get1stClip $h | head -n1`	# top    clip offset
bc=`get1stClip $h | tail -n1`	# bottom clip offset
# calculate extra border to add (2nd clip)
hc=`get2ndClip $res_w 320`		# horizontal clip offset
vc=`get2ndClip $res_h 240`		# vertical clip offset
# print report
echo "`basename -- "$infile"`      @ [$w] x [$h] + [$lc,$rc] x [$tc,$bc]"
echo "$outfile @ [$res_w] x [$res_h] + [$hc,$hc] x [$vc,$vc]"
echo


echo "===== resizing the video ================================================"
echo -e "$FG_LTYELLOW***$FG_CYAN transcode -i \"$infile\" \\ \n\t"             \
        "-o \"$TMP/_out.vid\" \\ \n\t"                                         \
        "-x mplayer  -y xvid4,lame  --nice $NICE  -q $DBG \\ \n\t"             \
        "-j -$tc,-$lc,-$bc,-$rc  -Y -$vc,-$hc,-$vc,-$hc \\ \n\t"               \
        "-Z $res_w""x$res_h$PROF $PROFN"
echo -e -n "$FG_LTYELLOW***$FG_CYAN `tcprobe -i "$infile" 2> /dev/null | grep  \
        "frames=" | sed 's/.*\(frames=[0-9]\+\)[^0-9].*/number of \1\n/'`" |   \
        grep "number of frames"
normcol
transcode -i "$infile" -o "$TMP/_out.vid"                                      \
          -x mplayer  -y xvid4,lame                                            \
          --nice $NICE  -q $DBG                                                \
          -j -$tc,-$lc,-$bc,-$rc  -Y -$vc,-$hc,-$vc,-$hc                       \
          -Z $res_w""x$res_h$PROF
echo


echo "===== merging video and audio streams ==================================="
echo -e "$FG_LTYELLOW***$FG_CYAN creating $outfile..."
normcol
avimerge -i "$TMP/_out.vid" -p "$TMP/_out.vid.mp3" -o "$outfile"
echo -e "$FG_LTYELLOW***$FG_CYAN flushing buffers..."
sync
echo


echo "===== deleting temporary files =========================================="
rm -f "$TMP/_out.vid"* "$TMP/stream.yuv" stream.yuv
echo -e "$FG_GREEN""All done!$NOCOLOR"
normcol
sync
