#!/bin/bash
#    dvd-encode
#    Copyright 2003 Scott Dylewski  <scott at dylewski.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Changes:
#
version='0.3'

help ()
{
echo "dvd-encode $version "
echo 'Copyright 2003-2004 Scott Dylewski <scott at dylewski.com>'
echo ' Usage:
dvd-encode <file.mpg | file.avi | any transcode supported video format>

Description:
        Converts videos to mpeg2 ntsc format for DVDs.  "Quick" and dirty.
	If the original content is already in 29.97 fps, it may be faster
	to use another method.  
	This is just a simple script to help you write or modify your own 
	script using transcode to encode video to mpeg2 format.  It is not
	intended for wide distribution, but I am including it anyway.
	I have not tested it on much.

Options:
 [-d]
        Deinterlace video

 <filename>
        Name of the video file you want to transcode to dvd

 -h or -help
   Prints this help.

Requires:
        transcode
Examples:
 '
}

if [ $# -lt 1 ]; then
        help
        exit 1
fi
                                                                                                      
## setup initial variables:
pal=0
istest=0
deinterlace=0
                                                                                             
for arg
do
        case "$arg" in
        -o) shift; outdir="$1"; shift ;;  # output dir
        -i) shift; filename="$1"; shift ;;  # video file
        -test) shift; istest=1 ;;
        -t) shift; istest=1 ;;
        -d) shift; deinterlace=1 ;;
        esac
done

if [ -z "$outdir" ] ; then
	## use current dir:
	outdir='.'
elif [ ! -d "$outdir" ] ; then
        ## create directory
        mkdir "$outdir"
fi

if [ -z "$filename" ] ; then
	filename="$1"
fi

if [ ! -f "$filename" ] ; then
	echo "ERROR:  input file does not exist."
	exit 1
fi

if [ $istest -eq 1 ]; then
	range="-c 1000-1500"
	echo "USING TEST MODE"
else	
	range=''
fi

if [ $deinterlace -eq 1 ]; then
	echo "Using deinterlacer..."
	deint="-J smartdeinter"
else	
	deint=''
fi

frames2hms ()
{
        ## pass a number in hundreths of seconds and get back a
        ## time code of the form HR:MM:SS:HU
        if [ -z "$1" ] ; then
                echo ''
        else
		newframes="$(( $1 * 10000 / 2997 ))"
                hours=$(( $newframes / 360000 ))
                it=$(( $newframes - $hours * 360000 ))
                minutes=$(( $it / 6000 ))
                it=$(( $newframes - $minutes * 6000 ))
                seconds=$(( $it / 100 ))
                hundreths=$(( $it - $seconds * 100 ))
                it="$hours:$minutes:$seconds.$hundreths"
                echo "${it}"
        fi
}


suffix=`echo "$filename" | awk -F. '{print tolower($NF)}'`
name=`basename "$filename" ."$suffix"`
moviename="$name"



echo " "
if [ "$suffix" == 'mpg' ] || [ "$suffix" == 'mpeg' ] ; then
	echo "[dvd-encode] Extracting audio with mplayer"
	echo "#######################"
#	mpgprobe "$filename"
	echo "#######################"
	nice transcode -i "$filename" -m "audio1.wav" -x null,mplayer -y null,wav $range
#	rm audio.mpg
#	ffmpeg -i "$filename" -vn -ab 192 -acodec mp2 -ar 48000 -ac 2 audio.mpg 
#	mv audio.mpg audio.mpa
#	audioprocess1="$!"
	echo "[dvd-encode] Doing 44Khz-48Khz translation..."
	## normalize audio here!
	volume=$( sox audio1.wav -e stat -v )
#	volume=$(( $volume * 9 / 10 ))
	echo "Volume adjust=$volume"
	sox "audio1.wav" -c 2 -r 48000 audio.wav 
#        ## toolame is way faster! (3x in my test)
#        it=`which toolame`
#        if [ -n "$it" ] ; then
#                echo "[dvd-encod3] using toolame..."
#                toolame -s 48 -b 192 "$outdir/audio.wav" "$outdir/audio.mpa"
#        else
#                echo "[dvd-encode] using mp2enc"
#                mp2enc -v $verbosity -b 192 -r 48000 -s -o "$outdir/audio.mpa" < "$outdir/audio.wav" 
#        fi

	echo "[dvd-encode] Creating ac3 audio file"
	ffmpeg -i "audio.wav" -y -vn -ab 192 -acodec ac3 -ar 48000 -ac 6 audio.ac3
#	audioprocess2="$!"
	if [ "$pal" -eq 1 ] ; then 
		echo "PAL fomat..."	### PAL 
		nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer -Z 720x576 -J modfps --export_fps 25,3 -y mpeg2enc,mp2enc  -F4,"-M 3 -n p -f 8 -s -a 2" -o video -m audio -b 192 -E 48000 $deint $range
	else
		### NTSC
#		nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,null  -F4,"-M 3 -n n -f 8 -s -a 2" -o video -m audio -b 192 -E 48000 $deint $range
		nice transcode -V -k -i "$filename" -x mplayer,null -w 8000 -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,null  -F 8,"-c -q 6 -4 2 -2 1 -R 2 -M 3 -n n -f 8 -a 2" -o video $deint $range
#		nice ffmpeg -i "$filename" -an -vcodec mpegvideo -b 4500 -s 720x480 -r 29.97 -aspect 4:3 video.mpg
#		mv video.mpg video.m2v
	fi
	echo " "
elif [ "$suffix" == 'avi' ] || [ "$suffix" == 'AVI' ] ; then
	tcprobe -i "$filename"
	
	## get current framerate and only do the fps conversion if it's different!
	framerate=`tcprobe -i "$filename" | grep 'frame rate: -f' | awk -F'-f ' '{print $2}' | awk '{print $1}'`
	echo "framerate=$framerate"
	
	size=`tcprobe -i "$filename" | grep 'frame size: -g' | awk -F'-g ' '{print $2}' | awk '{print $1}'`
	echo "size=$size"
	
	audio=`tcprobe -i "$filename" | grep 'audio track: -a' | awk -F'-e ' '{print $2}' | awk '{print $1}'`
	echo "audio=$audio"
	
	audiotype=`tcprobe -i "$filename" | grep 'audio track: -a' | awk -F'-n ' '{print $2}' | awk '{print $1}'`
	echo "audiotype=$audiotype"
	
	#audio_delay='-D-210'
	audio_delay=''
	
	## get zoom options:
	zoom=`zoomto "$size" "720x480" | grep '32:' | head 1 | awk -F'of 32:' '{print $2}'`
	echo "zoom parameters=$zoom"
	zoomto "$size" "720x480"
	
	# extract audio:
#	echo '####### extracting audio:'
#	echo " "
#	echo "## Encoding audio to 48KHz stereo audio for dvd"
#	if [ "$audiotype" == '0x55' ] ; then
#		echo "[dvd-encode] Extracting mp3 audio"
#		nice transcode -i "$filename" -m "audio1.wav" -x null,mp3 -y null,wav
#		echo "[dvd-encode] Doing 44Khz-48Khz translation..."
#		sox "audio1.wav" -c 2 -r 48000 audio.wav 
#	elif [ "$audiotype" == '0x1' ] ; then
#		echo "[dvd-encode] Extracting PCM audio"
#		nice transcode -i "$filename" -m "audio1.wav" -x null,raw -y null,wav
#		echo "[dvd-encode] Doing 44Khz-48Khz translation..."
#		sox "audio1.wav" -c 2 -r 48000 audio.wav 
#	elif [ "$audiotype" == '0x50' ] ; then
#		echo "[dvd-encode] Extracting audio with mplayer"
#		nice transcode -i "$filename" -m "audio1.wav" -x null,mplayer -y null,wav
#		echo "[dvd-encode] Doing 44Khz-48Khz translation..."
#		sox "audio1.wav" -c 2 -r 48000 audio.wav 
#	else 
#		echo "[dvd-encode] Extracting audio with mplayer"
#		nice transcode -i "$filename" -m "audio1.wav" -x null,mplayer -y null,wav
#		echo "[dvd-encode] Doing 44Khz-48Khz translation..."
#		sox "audio1.wav" -c 2 -r 48000 audio.wav 
#	fi
	
	## get volume adjust:

	## use this command:
	if [ "$pal" -eq 1 ] ; then 
		echo "PAL fomat..."	### PAL 
		if [ "$framerate" != '25' ] && [ "$framerate" != '25.000' ] ; then
			echo "first"
			nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer -Z 720x576 -J modfps --export_fps 25,3 -y mpeg2enc,mp2enc  -F4,"-M 3 -n p -f 8 -s -a 2" -o video -m audio -b 192 -E 48000 $deint $range
		else
			echo "no fps translation:"
#			nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer -Z 720x576 --export_asr 2 -y mpeg2enc,mp2enc -F4,"-M 3 -n p -f 8 -s" -o video -m audio -b 192 -E 48000 $deint $range
		nice transcode -V -k -i "$filename" -x mplayer,null -w 8000 -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,null  -F 8,"-c -q 6 -4 2 -2 1 -R 2 -M 3 -n n -f 8 -a 2" -o video $deint $range
		fi
	else
		### NTSC
#		if [ "$framerate" != '29.970' ] ; then
			echo "first"
#			nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer $deint $zoom -J modfps --export_fps 29.97,4 -y mpeg2enc,mp2enc  -F4,"-M 3 -n n -f 8 -s -a 2" -o video -m audio -b 192 -E 48000 $range
		nice transcode -V -k -i "$filename" -x mplayer,null -w 8000 -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,null  -F 8,"-c -q 6 -4 2 -2 1 -R 2 -M 3 -n n -f 8 -a 2" -o video $deint $range
#		else
#			echo "no fps translation:"
#			nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer $deint $zoom --export_asr 2 -y mpeg2enc,mp2enc -F4,"-M 3 -n n -f 8 -s" -o video -m audio -b 192 -E 48000  $range
#		fi
	fi
	echo "[dvd-encode] Creating ac3 audio file"
	ffmpeg -i "$filename" -y -vn -ab 192 -acodec ac3 -ar 48000 -ac 6 audio.ac3
else
	if [ "$pal" -eq 1 ] ; then 
		echo "PAL fomat..."	### PAL 
		nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer -Z 720x576 -J modfps --export_fps 25,3 -y mpeg2enc,mp2enc  -F4,"-M 3 -n p -f 8 -s -a 2" -o video -m audio -b 192 -E 48000 $deint $range
	else
		### NTSC
#		nice transcode -V -k -i "$filename" -p audio.wav -x mplayer,mplayer $deint -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,mp2enc  -F4,"-M 3 -n n -f 8 -s -a 2" -o video -m audio -b 192 -E 48000 $range
		nice transcode -V -k -i "$filename" -x mplayer,null -w 8000 -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,null  -F 8,"-c -q 6 -4 2 -2 1 -R 2 -M 3 -n n -f 8 -a 2" -o video $deint $range
	fi
fi

echo " "
echo "## combining audio and video..."
## now combine the audio and video:
#nice mplex -f 8 audio.ac3 video.m2v -o video.mpg
nice mplex -f 8 -r 10000 audio.ac3 video.m2v -o video.vob

mv video.vob "$moviename".vob

#rm audio1.wav audio.wav
#rm audio.ac3 video.m2v

## create chapter markers:
frames=`tcprobe -i "$filename" | grep 'length: ' | awk '{print $2}' | awk '{print $1}'`
echo "frames=$frames"

this_chap=0
i=0
chapters="0"
if [ -n "$frames" ] ; then
	if [ "$frames" -gt "$(( 60 * 1800 ))" ] ; then
		## video is over an hour long.  Do chapters every 5 minutes.
		step="$(( 5 * 60 * 2997 / 100 ))"
		while [ $this_chap -lt $frames ] ;  
		do
			this_chap="$(( $this_chap + $step ))"
			chap=`frames2hms $this_chap`
			chapters="$chapters,$chap"
		done
	else
		## video is under an hour long.  Do chapters every 1 minutes.
		step="$(( 1 * 60 * 2997 / 100 ))"
		while [ $this_chap -lt $frames ] ;  
		do
			this_chap="$(( $this_chap + $step ))"
			chap=`frames2hms $this_chap`
			chapters="$chapters,$chap"
		done
	fi
else
	chapters="0"
fi

echo "chapters=$chapters"

echo '          <vob chapters="'$chapters'" file="'`pwd`/$moviename.mpg'"  />' > "$moviename".xml

