#!/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 - $hours * 360000 - $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 "#######################"
	nice transcode -i "$filename" -m "audio1.wav" -x null,mplayer -y null,wav $range
	echo "[dvd-encode] Doing 44Khz-48Khz translation..."
	## normalize audio here!
	volume=$( sox audio1.wav -e stat -v )
#	volume=$(( $volume * 9 / 10 ))
#	volume="0.95"
	echo "Volume adjust=$volume"
#	nice sox "audio1.wav" -v "$volume" -c 2 -r 48000 audio.wav 
	nice sox "audio1.wav" -c 2 -r 48000 audio.wav 

	echo "[dvd-encode] Creating ac3 audio file"
	nice ffmpeg -i "audio.wav" -y -vn -ab 192 -acodec ac3 -ar 48000 -ac 6 audio.ac3
	if [ "$pal" -eq 1 ] ; then 
		echo "PAL fomat..."	### PAL 
	else
		### NTSC
		nice transcode -i "$filename" -x mplayer,null -w 5000 -Z 720x480 -J modfps --export_fps 29.97,4 -y mpeg2enc,null  -F 8,"-a 2 -q 8 -s -M 3 -f 8 -b 5000 -I 0" -o video $deint $range
#		nice transcode -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 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}'`
	size=`tcprobe -i "$filename" | grep 'frame size: -g' | awk -F'-g ' '{print $2}' | awk '{print $1}'`
	audio=`tcprobe -i "$filename" | grep 'audio track: -a' | awk -F'-e ' '{print $2}' | awk '{print $1}'`
	audiotype=`tcprobe -i "$filename" | grep 'audio track: -a' | awk -F'-n ' '{print $2}' | awk '{print $1}'`
	echo "framerate=$framerate"
	echo "size=$size"
	echo "audio=$audio"
	echo "audiotype=$audiotype"
	
	#audio_delay='-D-210'
	audio_delay=''
	
	## get zoom options:
	zoom=`zoomto "$size" "720x480" | grep '32:' | head -n 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:
	volume=$( sox audio1.wav -e stat -v )
#	volume="0.95"
	echo "Volume adjust=$volume"
#	nice sox "audio1.wav" -v "$volume" -c 2 -r 48000 audio.wav 
	nice sox "audio1.wav" -c 2 -r 48000 audio.wav 

	## use this command:
	if [ "$pal" -eq 1 ] ; then 
		echo "PAL fomat..."	### PAL 
	else
		### NTSC
#		if [ "$framerate" != '29.970' ] ; then
#			nice transcode -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 -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 -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  
	ffmpeg -i "audio.wav" -y -vn -ab 192 -acodec ac3 -ar 48000 -ac 6 audio.ac3
else  # not avi or mpeg
	if [ "$pal" -eq 1 ] ; then 
		echo "PAL fomat..."	### PAL 
	else
		### NTSC
#		nice transcode -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 -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 -V -M -f 8 audio.ac3 video.m2v -o video.vob

mv video.vob "$moviename".vob

## now, remove temporary files:
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.vob'"  />' > "$moviename".xml


