#!/usr/bin/env 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) 2010-2011 Markus Kohm <kohm at users.sf.net>
#   Copyright (c) 2009-2012 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/>.
#
# Changes:
#
#   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
#   2010-06-21  Markus Kohm
#               * renamed dvdwizardrc into dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#   2012-03-18  Joo Martin
#               * user config file always in $HOME/.config/dvdwizard/
#
# -------------------------------------------------------------------------

#
# i18n
#
export TEXTDOMAIN=dvdwizard
export TEXTDOMAINDIR="@LOCALEDIR@"

# We need some sub-routines from dvdwizard_common.
# This file must be found at PATH.
#
. dvdwizard_common || {
    echo $"FATAL ERROR: could not execute common function file \`dvdwizard_common'!
You have to install \`dvdwizard_common' somewhere at PATH." >&2
    exit 1
}

# Usage message
#
usagetext=$"
Usage:	${thisscript} -i dvd-image -o output-directory [options]
	${thisscript} -h|--help
	${thisscript} -v|--version

supported options:
------------------
-C | --config-file	filename of dvdwizard-configuration file
			[~/.config/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
-v | --version		print version information only
"

# ------------------------------
# Main Processing
#

#
# Is help wanted?
#
test_versionhelp "$@"

# 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"
            printf $"Batch-Mode chosen. Images will be selected automagically.\n"
   	    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
  	    ;;
  	*)
   	    error_help $"Unrecognized command line parameter %s." "$1" >&2
  	    ;;
    esac
done

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

if [ -z "$dvd" ]; then
    error_help $"No input directory specified."
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
printf $"Found %d chapters.\n" $cCount
if [ $cCount -lt 1 -o $cCount -gt 96 ]; then
    error_nohelp $"Chapter number not valid for authoring with dvdauthor.
May be something wrong with tcprobe?"
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
    printf $"Processing chapter No. %d.\n" $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
 	printf $"Displaying list of frameshots taken from chapter %d.
When decision is made, terminate display with the space-bar and tell me your 
choice.  I suggest choosing picture %d.\n" $chp $prefPic
	vidspec=tmp*.jpg
	(cd "$workDir" && display vid:$vidspec)
	echo $"Which picture shall persist?
[0-9]   - choose according Picture
<empty> - honor my suggestion [%d]
x       - Terminate\n" $prefPic
	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
	error_nohelp  $"Screenshot JPG file \`%s' not found!
Maybe your transcode have a CPU acceleration problem." "$picname"
    fi
    let "framenr=$picnr*$frameInt+$firstframe"
    mv "$prefPic" "$cshotsDir"/chapter$chapter.jpg
    printf "Selected %s as screenshot for chapter %d (should be frame number %d).\n" "$picname" $chp $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
