#!/bin/bash
#
# dvdcpics - Extract Screenshots from DVD-chapters
#            as input for mk_vtsm (menu creation)
#
# Version   0.01a written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#
usage()
{
 cat <<EOF
Usage:	`basename $0` -i <dvd-image> -o <output-directory> [options]
	`basename $0` -h|--help

currently supported options:
----------------------------
-C | --config-file	filename of dvdwizard-configuration file
			[~/.dvdwizard/dvdwizard.conf]
-i | --input		Path where the DVD can be found
-t | --vts		Titleset on the DVD to process [1]
-o | --output		Path where the Pictures will be stored
-b | --batch		no user interaction - image will be choosen automagically
			Interactive mode is the default (User chooses picture)
-f | --fsize		Frame-Size (eg 720x576) for Screenshots. If not specified,
			defaults to attributes of the video stream
-h | --help		print this lot out

EOF
exit 1
}

# ------------------------------
# Main Processing
#
#
# Is help wanted?
#
case "$1" in
  	-h|--help)
   	    usage
  	;;
esac

# We need some sub-routines from dvdwizardrc
# This file must reside in the same directory as the called script
# Should maybe go into a directory like /usr/local/share/dvdwizard
# but this would require an installation procedure - maybe in some
# later version.
#
rcfile="`dirname $0`/dvdwizardrc"
#echo $rcfile
if [ -e "$rcfile" -a -r "$rcfile" ]; then
	. "$rcfile"
else
	echo "dvdwizardrc not found or is not readable. Aborting" >&2
    exit 1
fi

#
# Ok, first define some default values
#
set_defaults "$@"
set_format
dvd=""
cshotsDir="$(pwd)/cshots"
mode="I"
firstframe=5
frames=200
let "frameInt=$frames/10"
fsize=""
vts=1

#
# Check for needed tools
#
check_tools

#
# Now deal with command line arguments
#
while [ -n "$*" ]; do
    case "$1" in
  	-C|--config-file)
    	shift
# -C and it's following parm already processed in set_defaults()
        shift
  	;;
	-i|--input)
 		shift
		dvd="$1"
	    shift
  	;;
	-o|--output)
 		shift
		cshotsDir="$1"
	    shift
  	;;
  	-t|--vts)
	    shift
   	    vts="$1"
   	    shift
  	;;
	-b|--batch)
   		mode="B"
         echo Batch-Mode chosen. Images will be selected automagically >&2
   		shift
  		;;
	-f|--fsize)
   		shift
   		fsize="$1"
   		shift
  		;;
  	*)
   	    echo "Unrecognized command line parameter $1. Aborting" >&2
        echo "See $thisscript -h for more infos" >&2
        exit 1
  	;;
    esac
done

#
# Check if DVD-Directory was specified - No point in working without !
#

if [ -z "$dvd" ]; then
    echo No input directory specified
    echo "See $thisscript -h for more infos"
    exit 1
else
    if [ ! -b "$dvd" ]; then
	mk_check_dir "$dvd" "OLD" "\$dvd -i|--input"
	dvd="`(cd "$dvd" && pwd)`"
    fi
fi >&2

#
# Do some file and directory preparation
#
mk_check_dir "$cshotsDir" "NEW"	"\$cshotsDir -o|--output"
workDir="$TMPDIR"/cshots
mk_check_dir "$workDir" "NEW" "$\workDir"

#
#  Check, how many chapters are on the DVD
#
cCount=`tcprobe -i "$dvd" -T $vts 2>&1 | grep chapter | awk -F: '{ print $2 }' | cut -d' ' -f2` || error_out
echo Found $cCount chapters
if [ $cCount -lt 1 -o $cCount -gt 96 ]; then
   echo "chapter number not valid for authoring with dvdauthor. May be something wrong with tcprobe?" >&2
   exit 1
fi

#
# If Frame-Size was specified, set appropriate parm
#
[ -z "$fsize" ] && fsparm="" || fsparm="-g $fsize"

#
# If Frame-Size is different from TV-Norm resolution (PAL or NTSC), scale it
#
[ ! -z "$fsparm" -a "$fsize" != "$normSize" ] && fsparm="$fsparm -Z $normSize"

#
# So then, let's go through the chapters one by one
#
for ((chp=1; chp <= cCount ; chp++)); do
   echo Processing chapter No. $chp
   let "lastframe=$firstframe+$frames"
   if [ $chp -lt 10 ]; then
   	chapter="0$chp"
   else
   	chapter=$chp
   fi

   #
   # Set some options depending on transcode version
   #
   tcversion=$(transcode -v 2>&1 | cut -d' ' -f2)
   [ "$tcversion" \< "v0.6.13" ] && TRANSCODE_OPTS="-z -k" || TRANSCODE_OPTS=""
   
   #
   # Extract frames as JPEGs to choose snapshot from
   #
   transcode -q 0 -i "$dvd" -x dvd,null --dvd_access_delay 0 -y jpg,null $fsparm \
   			 -c $firstframe-$lastframe -T $vts,$chp-$chp -o "$workDir"/tmp $TRANSCODE_OPTS \
             --frame_interval $frameInt >/dev/null 2>&1 || error_out

   #
   # In batch mode, the script judges to best frame to take by the jpeg's size
   # The biggest jpg must have the most grafical aspect - this is to avoid generating black screenshots
   # if a chapters starts with a fade-in.
   #
   prefPic="$(ls -S "$workDir"/tmp*.jpg | head -n1)"

   #
   # if we're running in interactive mode, tell the user what's going on
   # and display thumbnails of the captured frames
   # let the user choose one and give hint, which one would have been picked by the script
   #
   if [ $mode == "I" ]; then
 		echo Displaying list of frameshots taken from chapter $chp.
		echo When decision is made, terminate display with the space-bar and tell me your choice
		echo I suggest choosing picture $prefPic
		vidspec=tmp*.jpg
		(cd "$workDir" && display vid:$vidspec)
		cat <<EOF
Which picture shall persist?
[0-9]   - choose according Picture
<empty> - honor my suggestion [$prefPic]
x       - Terminate
EOF
		ok=0
		until [ $ok -eq 1 ]; do
			ok=1
			read INPUT
            case "$INPUT" in
      		""   )
         		:
         	;;
      		[0-9])
         		prefPic="$workDir"/tmp00000$INPUT.jpg
         	;;
      		x|X  )
            	echo "Ok, bailing out at your request. Bye"
					rm -R "$workDir"
        			exit 1
       		;;
      		*    )
					ok=0
      		;;
			esac
   		done
	fi
	picname=`basename "$prefPic" .jpg`
	picnr=${picname:8}
	let "framenr=$picnr*$frameInt+$firstframe"
	mv "$prefPic" "$cshotsDir"/chapter$chapter.jpg
	echo "Selected $picname as Screenshot for chapter $chp (should be frame number $framenr)"
done

#
# All chapters are through. Let's see the results
# Maybe a good place to choose one of the pictures as background-picture for the menu
#
if [ $mode == "I" ]; then
	echo "This is the result of my work. Hope you like it. ;-)"
 	(cd "$cshotsDir" && display vid:/chapter*.jpg)
fi
rm -R "$workDir"

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

echo Processing completed. Bye!
exit 0
