#!/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"
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"`
if [ "$suffix" == 'mpg' ] || [ "$suffix" == 'mpeg' ] ; then
	moviename="$name"_new
else	
	moviename="$name"
fi



echo " "
if [ "$suffix" == 'mpg' ] || [ "$suffix" == 'mpeg' ] ; 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 
	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 224 -E 48000 $deint
	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,mp2enc  -F4,"-M 3 -n n -f 8 -s -a 2" -o video -m audio -b 224 -E 48000 $deint
	fi
	echo " "
	echo "## combining audio and video..."
	## now combine the audio and video:
	nice mplex -f 8 audio.mpa video.m2v -o video.mpg
	mv video.mpg "$moviename".mpg
	rm audio.mpa video.m2v audio1.wav
	exit 0
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 224 -E 48000 $deint
		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 224 -E 48000 $deint
		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 224 -E 48000
		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 224 -E 48000 
		fi
	fi
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 224 -E 48000 $deint
	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 224 -E 48000
	fi
fi

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

mv video.mpg "$moviename".mpg

rm audio.mpa video.m2v audio1.wav audio.wav

## 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

