#!/bin/bash
#
# Script to transcode and stream video using VLC
# Graham Grindlay
# 09/25/2010
#
# Much of this script is taken from VLC Wiki at:
# http://wiki.videolan.org/Transcode
#

VLC=/usr/bin/vlc

# aspect ratio
aspect=16:9

# video codec
vcodec=h264

# video bitrate
vbitrate=192

# audio codec
acodec=mp3

# audio bitrate
abitrate=96

# deinterlace?
deint=no

# scale
scale=0.8

# channels
channels=2

# FPS
fps=24

# destination
dest=192.168.1.2:1234

# mux type
mux=asf


#### Program, do not change below this line ####
usage() {
	cat 1>&2 <<EOF
Usage: $0 [-nwdD] [-o <output destination>] [-x <video codec>] [-y <audio codec>] [-m <mux>] [-f <fps>] [-s <scale>] [-c <channels>] [-b <rate>] [-a <rate>] <source file>
	-n	4:3 aspect ratio (default=$aspect)
	-w	16:9 aspect ratio
	-d	Perform de-interlacing (default=$deint)
	-D	Do not perform de-interlacing
        -x	Video codec (default=$vcodec)
	-y	Audio codec (default=$acodec)
	-b	Video bitrate kb/s (default=$vbitrate)
	-a	Audio bitrate kb/s (default=$abitrate)
        -c      Channels (default=$channels)
        -s      Scale (default=$scale)
        -f      FPS (default=$fps)
        -m      Mux type (default=$mux)
        -o      Output destination (default=$dest)

EOF
	exit 1
}

error() {
	echo "ERROR: $*" 1>&2
	exit 2
}

while getopts 'nwdDo:m:f:s:c:b:a:x:y:h' opt; do
	case $opt in
		n) aspect=4:3 ;;
		w) aspect=16:9 ;;
		d) deint=yes ;;
		D) deint=no ;;
	        o) dest=$OPTARG ;;
		m) mux=$OPTARG ;;
	        f) fps=$OPTARG ;;
		s) scale=$OPTARG ;;
		c) channel=$OPTARG ;;
		b) vbitrate=$OPTARG ;;
		a) abitrate=$OPTARG ;;
	        x) vcodec=$OPTARG ;;
		y) acodec=$OPTARG ;;
		h) usage ;;
		*) echo "Unknown option $opt" 1>&2; usage ;;
	esac
done

shift $(( $OPTIND - 1 ))
[ $# -ne 1 ] && usage

infile="$1"

[ -r "$infile" ] || error "Can't read from $infile"

case $aspect in
	16:9) sizestr="width=800,height=448" ;;
	4:3) sizestr="width=608,height=448" ;;
	*) error "Could not handle $src,$aspect,$crop. This shouldn't happen!" ;;
esac

if [ "$deint" = "yes" ]; then
	deintstr=",deinterlace=enable"
else
	deintstr=
fi

# Let's do it
echo "Input file: $infile"
echo "Destination: $dest"
echo "Encoding with $vcodec+$acodec at $vbitrate+$vbitrate kb/s using $mux mux, de-interlace $deint"
echo
echo '>>>' $VLC -vvv "$infile" --sout "#transcode{$sizestr$deintstr,vcodec=$vcodec,vb=$vbitrate,acodec=$acodec,ab=$abitrate,fps=$fps,scale=$scale,channels=$channels}:standard{access=http,mux=$mux,dst=$dest}"
echo

$VLC -vvv "$infile" --sout "#transcode{$sizestr$deintstr,vcodec=$vcodec,vb=$vbitrate,acodec=$acodec,ab=$abitrate,fps=$fps,scale=$scale,channels=$channels}:standard{access=http,mux=$mux,dst=$dest}"
