#!/bin/bash
#
#   dvdcpics - Extract Screenshots from DVD-chapters
#              as input for mk_vtsm (menu creation)
#
#   Copyright (C) 2004-2008 W. Wershofen <itconsult at wershofen.de>
#   Copyright (C) 2009 Joo Martin <joomart2009 at users.sf.net>
#
#   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 3 of the License, or
#   (at your option) any later version.
#
#   This package 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, see <http://www.gnu.org/licenses/>.
#
#   2004-01-26  Wolfgang Wershofen
#               * initial version
#   2009-12-02  Joo Martin
#               * transcode 1.1.5 workaround for cpu accelerations
#   2009-12-05  Joo Martin
#               * add tvnorm option (-N) for right work with NTSC
#
# -------------------------------------------------------------------------

usage()
{
 cat <<EOF

Usage:	`basename $0` -i dvd-image -o output-directory [options]
	`basename $0` -h|--help

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
-N | --tvnorm		TV-Norm to use <PAL|NTSC>         [PAL]
-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
#
rcfile="@DW_RC_FILE@"
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 "$@"
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
		;;
	-N|--tvnorm)
		shift
		TVNORM=$(echo "$1" | tr [a-z] [A-Z])
		[ ! "$TVNORM" == "PAL" -a ! "$TVNORM" == "NTSC" ] && TVNORM="PAL"
		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"

#
# compute some format values
#
set_format

#
#  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 option depending on transcode version
   #
   tcversion=$(transcode -v 2>&1 | cut -d' ' -f2)
   [ "$tcversion" \< "v1.1.0" ] && TRANS_DELAY="--dvd_access_delay 0" || TRANS_DELAY=""
   [ "$tcversion" == "v1.1.5" ] && COLOR_LAYOUT="-V rgb24" || COLOR_LAYOUT=""
   [ "$tcversion" == "v1.1.5" ] && echo "transcode: using color layout RGB24 as workaround"
   # we need this workaround, because transcode works suspect with some CPU accelerations

   #
   # Extract frames as JPEGs to choose snapshot from
   #
   transcode -q 0 -i "$dvd" $TRANS_DELAY $COLOR_LAYOUT -x dvd,null -y jpg,null \
        $fsparm -c $firstframe-$lastframe -T $vts,$chp-$chp -o "$workDir"/tmp \
        --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}      # remove first eight characters
	if [ ! "$picnr" ]; then
		echo "Screenshot JPG file '" $picname "' not found!"
		echo "Maybe your transcode have a CPU acceleration problem!"
		error_out
	fi
	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
