#!/bin/bash

# -------------------------------------------------------------------------------------------------------
# DESCRIPTION :
#
# IMAGES2MPG : convert images sequence on a MPEG files for create a VCD/SVCD/XVCD/DVD portfolio (with vcdimager)
#
# This script use this packages :  'ImageMagick' ver >= 5.4.8 [http://www.imagemagick.org/]
#                                  'MjpegTools'  ver >= 1.6.0 [http://mjpeg.sourceforge.net/]
#
# You give the images files names on the command line (see the options '--help').
# The images formats must be reconized by ImageMagick program.
#
# This script used this externals binary programs :
#
# - 'montage'   from ImageMagick for resize the images for the TV screen size.
# - 'composite' from ImageMagick for make the transition between images.
# - 'convert'   from ImageMagick for convert the images before MPEG encoding.
# - 'identify'  from ImageMagick for check the background image file size.
# - 'ppmtoy4m'  from MjpegTools for create a video stream from the image.
# - 'yuvscaler' from MjpegTools for adapt the video stream size before MPEG encoding.
# - 'mpeg2enc'  from MjpegTools for encode the video stream in MPEG file.
# - 'ogg123'    from vorbis-utils to transcode an ogg-audio file to wav
# - 'mpg123'    to transcode an mp3-audio file to wav
# - 'mp2enc'    from MjpegTools to transcode a WAV sound file to a MP2 file.
# - 'mplex'     from MjpegTools for multiplexe the MPEG file and the MP2 sound and convert
#               the final MPEG file to a DVD/XVCD/SVCD/VCD format compatible with vcdimager program.
#
# You can use the 'KIPI' KDE frontend with this script. Look this URL : http://extragear.kde.org/apps/kipi
#
# Return value : 0 -> Process finish succefuly.
#                1 -> Error.
#
# -------------------------------------------------------------------------------------------------------
#
# ABOUT VIDEO TYPES AND FORMATS SUPPORTED BY THIS SCRIPT :
#
#  Video type   ::         VCD         :        SVCD         :        XVCD         :         DVD         :
#               ::          :          :          :          :          :          :          :          :
#  Video format :: PAL/SECAM:   NTSC   : PAL/SECAM:   NTSC   : PAL/SECAM:   NTSC   : PAL/SECAM:   NTSC   :
#               ::          :          :          :          :          :          :          :          :
#  Resolution   ::  352x288 :  352x240 :  576x480 :  480x480 :  720x576 :  720x480 :  720x576 :  720x480 :
#               ::          :          :          :          :          :          :          :          :
#  Frame/s      ::    25    :    30    :     25   :     30   :     25   :    30    :     25   :    30    :
#               ::                     :                     :                     :                     :
#  MPEG type    ::        MPEG1        :        MPEG2        :        MPEG2        :        MPEG2        :
#               ::                     :                     :                     :                     :
#  Video CDR    ::        74 mn        :        60 mn        :        50 mn        :        15 mn        :
#  duration     ::                     :                     :                     :                     :
#               ::                     :                     :                     :                     :
#  Video        ::     1,150 kbit/s    :     2,500 kbit/s    :     2,500 kbit/s    :     8,000 kbit/s    :
#  bitrate      ::                     :                     :                     :                     :
#               ::                     :                     :                     :                     :
#  Sound format ::         MP2         :         MP2         :         MP2         :         MP2         :
#               ::                     :                     :                     :                     :
#  Audio        ::       224 kbit/s    :       224 kbit/s    :       224 kbit/s    :       224 kbit/s    :
#  biterate     ::                     :                     :                     :                     :
#               ::                     :                     :                     :                     :
#  DVD player   ::       excelent      :        good         :        medium       :       excelent      :
#  compatibility::                     :                     :                     :                     :
#               ::                     :                     :                     :                     :
#  Image        ::        medium       :        good         :       excelent      :       excelent      :
#  restitution  ::                     :                     :                     :                     :
#
#  Notes : - The XVCD resolution is the same of DVD !
#
# -------------------------------------------------------------------------------------------------------
#
# AUTHOR : CAULIER gilles <caulier dot gilles at gmail dot com>
#
# -------------------------------------------------------------------------------------------------------
#
# TODO :
#
# * Add an option for select PAL or NTSC video format.
# * Add transitions betwen the images in the MPEG sequence.
# * Write a man page file with some examples and more informations.
# * Don't use an default external black 'PNG' background image file.
# * Add an option with the RVB color for the background image color.
# * Add a trap signal fonction : clear temporary files when killed.
# * Add an option for a specific temporary folder.
# - Add DIVX support.
#
# -------------------------------------------------------------------------------------------------------
# LICENSE :
#
# 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, 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., 51 Franklin Steet, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# -------------------------------------------------------------------------------------------------------
# CHANGELOG :
#
# March 2002    : Original release by Gilles CAULIER <caulier.gilles@free.fr>.
# November 2002 : Add a convert image format fonction with ImageMagick.
#                 Add resize the image for the TV screen with ImageMagick.
#                 Add Endoding time measurement.
#                 Add many images files on the same MPEG file.
#                 Add using of temporary files.
#                 Add some command line options.
#                 Add encoding sound on the MPEG file.
# December 2002 : Fix some bugs.
#                 Add some command line parameters controls.
#                 Add some English comments.
#                 Add a video type command line option (PAL, NTSC, SECAM).
#                 Remove '-F' option (frame rate value -> fixed by video type option)
#                 Add an exiting test of input image files before encoding.
#                 Add an exiting test of input audio files and mask file before encoding.
#                 Add an exiting test if verbosity level is unknown.
#                 Add image sequence duration value test.
#                 Add an implementation for don't used a default 'black.png' file. ImageMagick create a
#                 temporary PNG file for this.
#                 Add warning if total duration is <=3 s.
#                 Remove 3s image duration limitation.
#                 Add test about image background size.
#                 Add an option for define the background image RGB color.
#                 Add a trap fonction for remove the temporary files.
#                 Add a transition fonction with 'composite' binary program from ImageMagick package.
#                 Add a final transition for the sequence.
#                 Add this script to the MjpegTools project on sourceforge repository.
# January 2003  : Add a manual page (on MjpegTools project package).
#                 Add an option for use a temporary folder.
#                 Add '--with-gui' option for run with 'kimg2mpg' KDE gui frontend program.
#                 Change the IFS variable for a correct interpretation of the whitespaces in the path
#                 files names.
#                 Add DVD video format option.
#                 Change trap fonction.
#                 Change some console messages for the KDE GUI.
# February 2003 : Update 'Kimg2mpg' KDE frontend  WEB site URL.
# September 2003: Moving to the Digikam project (http://digikam.sourceforge.net).
#                 Add options for ImageMagick and MjpegTools binary folders informations.
# October 2003  : Rename this file to 'images2mpg'.
#
# -------------------------------------------------------------------------------------------------------

# --------------------------------------FONCTIONS--------------------------------------------------------

#Clean the temporary file and exit. Used by the Trap fonction and at end of this script.
CleanUp()
{
if [ $WITHGUI = 0 ]; then
    echo -e "Removing temporary files..."
fi

if [ -e "$TMPFILENAME.tmp.m2v" ]; then
    rm "$TMPFILENAME.tmp.m2v"
fi
    
if [ -e "$TMPFILENAME.tmp.jpg" ]; then
    rm "$TMPFILENAME.tmp.jpg"
fi

if [ -e "$TMPFILENAME.tmp.pnm" ]; then
    rm "$TMPFILENAME.tmp.pnm"
fi
if [ "$AUDIO_WAV" ]; then
    if [ -e "$TMPFILENAME.tmp.wav" ]; then
        rm "$TMPFILENAME.tmp.wav"
    fi
    
    if [ -e "$TMPFILENAME.tmp.mp2" ]; then
        rm "$TMPFILENAME.tmp.mp2"
    fi
fi

if [ "$MASK"="$TMPFILENAME.black.tmp.png" ]; then
    if [ -e "$MASK" ]; then
	rm "$MASK"
    fi
fi

if [ $TRANSITIONENABLE = 1 ]; then
    if [ -e "$TMPFILENAME.prev_trans.tmp.pnm" ]; then
        rm "$TMPFILENAME.prev_trans.tmp.pnm"
    fi
    if [ -e "$TMPFILENAME.next_trans.tmp.pnm" ]; then
        rm "$TMPFILENAME.next_trans.tmp.pnm"
    fi
fi

exit 0
}


# ------------------------------------END OF FONCTIONS---------------------------------------------------

# --------------------------------------MAIN-------------------------------------------------------------

# Trap shell signals fonction.

trap CleanUp 2

# Default parameters values.

# Default MPEG video format.
VIDEO_FORMAT="XVCD"

# Default video type.
VIDEO_TYPE="PAL"

#Default Chroma subsampling mode (ppmtoy4m)
PPMTOY4M_CHROMA_OPT="-S 420mpeg2"

# Default verbosity level .
# 0 -> Just the error messages or warnings.
# 1 -> level 0 + informations messages.
# 2 -> level 1 + debug messages.
VERBOSE=0

# Default duration for one image in the MPEG sequence. Minimal value is 1s.
IMAGEDURATION=10

# Default transition parameters.
TRANSITIONENABLE=0
TRANSITIONDURATION=0

# Default temporary folder is local folder.
TEMPORARYFOLDER=""

# Default ImageMagick binary folder -> using PATH variable.
IMBINFOLDER=""

# Default MJPEGTools binary folder -> using PATH variable.
MJPEGTBINFOLDER=""

# Not running with 'KIPI' KDE gui frontend.
WITHGUI=0

# Command line parameters analyse...
CPT_IMG_FILE=0

if [ $# == 0 ]; then
    echo -e "No option specified... 'images2mpg -h' for more informations."
    exit 1
fi

while test $# -gt 0; do
  OPTIONMESSAGE=$1

  case $1 in

    # Verbosity...
    -v)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      VERBOSE=$1
      ;;

    # Running with 'KIPI' KDE frontend...
    --with-gui)
      WITHGUI=1
      ;;

    # Temporary folder...
    -T)
      OLD_IFS=$IFS	
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      TEMPORARYFOLDER=$1
      IFS=$OLD_IFS
      ;;

    # Transition between images...
    -t)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi

      if [ $[$1 == 1 || $1 == 2 || $1 == 4 || $1 == 5 || $1 == 10 || $1 == 20] = 1 ]; then
         # Increment value for dissolving the images with the transition.
         DISSOLVEVALUEINC=$1
         TRANSITIONENABLE=1
      else
         echo -e "Bad transition speed value (must be 1, 2, 4, 5, 10, or 20) !"
         exit -1
      fi
      ;;

    # Video format...
    -f)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      VIDEO_FORMAT=$1
      ;;

    # Video type...
    -n)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      VIDEO_TYPE=$1
      ;;

    # Chroma subsampling mode (ppmtoy4m option)...
    -S)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      PPMTOY4M_CHROMA_OPT="-S $1"
      ;;

    # Background image file...
    -b)
      OLD_IFS=$IFS
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      if [ -s $1 ]; then
	 MASKGEOMETRY=`$IDENTIFY_BIN -verbose $1 |grep Geometry |awk '{print $2}'`
         if [ $MASKGEOMETRY != "768x576" ]; then
	    echo -e "The size of background image file '$1' isn't 768x576 pixels [$MASKGEOMETRY]!!!"
	    exit -1
	 else
            MASK=$1
	 fi
      else
         echo -e "The background image file '$1' don't exist or can't be open !!!"
         exit -1
      fi
      IFS=$OLD_IFS
      ;;

    # Background color...
    -c)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      else
         BACKGROUNDCOLOR=$1
      fi
      ;;

    # Images duration...
    -d)
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      IMAGEDURATION=$1
      if [ $[$IMAGEDURATION == 0] = 1 ]; then
         echo -e "Image duration value must be >= 1 !"
         exit -1
      fi
      ;;

    # MP2 audio file...
    -a)
      OLD_IFS=$IFS	
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      if [ -s $1 ]; then
         AUDIO_MPEG=$1
      else
         echo -e "The MP2 audio file '$1' don't exist or can't be open !!!"
         exit -1
      fi
      IFS=$OLD_IFS	
      ;;

    # WAV/MP3/OGG audio file...
    -w)
      OLD_IFS=$IFS	
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      if [ -s $1 ]; then
         AUDIO_WAV=$1
      else
         echo -e "The WAV/OGG/MP3 audio file '$1' don't exist or can't be open !!!"
         exit -1
      fi
      IFS=$OLD_IFS	
      ;;

    # MPEG output file...
    -o)
      OLD_IFS=$IFS	
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      OUTPUT_MPEG_FILE=$1
      IFS=$OLD_IFS	
      ;;

    # Image input files...
    -i)
      OLD_IFS=$IFS
      IFS="\""
      shift
      while [ $1 ]; do
          INPUT_IMAGE_FILES[CPT_IMG_FILE]=$1
    	  CPT_IMG_FILE=`echo $(($CPT_IMG_FILE+1))`
	  shift
      done
      IFS=$OLD_IFS
      ;;

    # MJPEGTools binary folder...
    -M)
      OLD_IFS=$IFS
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      MJPEGTBINFOLDER=$1
      IFS=$OLD_IFS
      ;;

    # ImageMagick binary folder...
    -I)
      OLD_IFS=$IFS
      IFS="\""
      shift
      if [ -z $1 ]; then
         echo -e "Missing parameter after '$OPTIONMESSAGE' option !"
         exit -1
      fi
      IMBINFOLDER=$1
      IFS=$OLD_IFS
      ;;

    # Help...
    -h | --help)
      cat << EOF

IMAGES2MPG [KIPI Project] - MPEG portfolio images multiplexer.

Usage: images2mpg [options] -o <output MPEG file> -i <input image files>

Options:
   -v <num>                    : verbose level [0:none=default, 1:infos+warnings, 2:debug].
   --with-gui                  : running with 'KIPI' KDE GUI frontend [see http://extragear.kde.org/apps/kipi]. 
   -t <num>                    : enable transition between images with the speed [1=slow, 2, 4, 5, 10, 20=fast].
   -T <Temporary folder>       : use a specific folder for creating the temporary files (ex: '/tmp').
   -f <Video format>           : video format  [DVD, XVCD=default, SVCD, VCD].
   -S <mode>                   :  Set chroma subsampling mode. (default value depends on ppmtoy4m version)
                                  [444 - 4:4:4 (no subsampling)
                                   420jpeg - 4:2:0 JPEG/MPEG-1, interstitial cositing
                                   420mpeg2 - 4:2:0 MPEG-2, horizontal cositing]
   -n <Video type>             : video type    [PAL=default, NTSC, SECAM].
   -b <background file>        : 768x576 pixels background image file name [black color = default].
   -c <RGB color>              : hex RGB color for background image (ex: AA001F).
   -d <num>                    : duration for each image in MPEG file [10s = default, 1s = mini].
   -a <MP2 audio file>         : MP2 audio file to merge with the video sequence.
   -w <wav|ogg|mp3 audio file> : WAV/OGG/MP3 audio file to convert in MP2 and to merge with the video sequence.
   -o <output MPEG file>       : the ouput MPEG file name [temporary file name = default].
   -i <input images files>     : images files name to merge in MPEG.
   -I <ImageMagick bin folder> : folder for ImageMagick binary programs.
   -M <MjpegTools bin folder>  : folder for MjpegTools binary programs.
   -h | --help                 : this help.

The 'images2mpg' bash script convert some images on MPEG sequences with a specific
duration and merge all images on an single MPEG file. It use the 'MjpegTools' &
'ImageMagick' packages.
You can use this for to build some DVD/XVCD/SVCD/VCD portfolios for your home DVD player.
Use 'vcdimager' for create this...

Notes :

  - The input images files with the '-i' option must be the last command line parameters.
  - If you use some whitespaces in the path folders/files, use '"' around the complete path string.
  - With mjpegtools > 1.6.2 ppmtoy4m seems to have changed the default behavior for chroma subsampling 
    mode so '-S' option is needed
    
Examples :

#./images2mpg -f SVCD -d 15 -S 420mpeg2 -w Music.wav -o MyPortfolio.mpg -i 01.jpg 02.jpg 03.jpg 04.jpg

   Build PAL (default) SVCD MPEG file with the 'Music.wav' sound file and this image files sequence :

   01.jpg
   02.jpg
   03.jpg
   04.jpg

   For each image on the portfolio, the screen show duration is 15 seconds. The output file
   is 'MyPortfolio.mpg'. There isn't transition between images.

#./images2mpg -n NTSC -t 2 -o MyPortfolio.mpg -i *.png

   Build XVCD (default) NTSC MPEG file with a transition between image (speed 2) and all
   local PNG images files. The image files sequence use the local filesystem sort.

Author:
   CAULIER Gilles <caulier.gilles@free.fr>

Visit :
   URL PROJECT : http://extragear.kde.org/apps/kipi
   WEBSVN : http://websvn.kde.org/trunk/extragear/libs/kipi-plugins/mpegencoder

EOF
      exit 0
      ;;

    # Unknown option...
    -?*)
      echo "Option '$1' not recognized..."
      exit 1
      ;;
  esac
  shift
done

if [ $WITHGUI = 1 ]; then
    echo -e "Initialising...\n" >&2
fi

# Initialising full binary programs paths for ImageMagick and MJPEGTools.

if [ -z "$IMBINFOLDER" ]; then
   MONTAGE_BIN="montage"
   COMPOSITE_BIN="composite"
   CONVERT_BIN="convert"
   IDENTIFY_BIN="identify"
   #TODO add a check also when they are in the path mayby using which command
else
   MONTAGE_BIN="$IMBINFOLDER/montage"
   COMPOSITE_BIN="$IMBINFOLDER/composite"
   CONVERT_BIN="$IMBINFOLDER/convert"
   IDENTIFY_BIN="$IMBINFOLDER/identify"

   # check if programs are installed
   if [ ! -e $MONTAGE_BIN ]; then
	echo -e "\nCan't find $MONTAGE_BIN, please install it or check -I parameter"
	exit -1
   fi
   if [ ! -e $COMPOSITE_BIN ]; then
	echo -e "\nCan't find $COMPOSITE_BIN, please install it or check -I parameter"
	exit -1
   fi
   if [ ! -e $CONVERT_BIN ]; then
	echo -e "\nCan't find $CONVERT_BIN, please install it or check -I parameter"
	exit -1
   fi
   if [ ! -e $IDENTIFY_BIN ]; then
	echo -e "\nCan't find $IDENTIFY_BIN, please install it or check -I parameter"
	exit -1
   fi
fi


if [ -z "$MJPEGTBINFOLDER" ]; then
   PPMTOY4M_BIN="ppmtoy4m"
   YUVSCALER_BIN="yuvscaler"
   MPEG2ENC_BIN="mpeg2enc"
   MP2ENC_BIN="mp2enc"
   OGG_BIN="ogg123"
   MP3_BIN="mpg123"
   MPLEX_BIN="mplex"
else
   PPMTOY4M_BIN="$MJPEGTBINFOLDER/ppmtoy4m"
   YUVSCALER_BIN="$MJPEGTBINFOLDER/yuvscaler"
   MPEG2ENC_BIN="$MJPEGTBINFOLDER/mpeg2enc"
   MP2ENC_BIN="$MJPEGTBINFOLDER/mp2enc"
   OGG_BIN="$MJPEGTBINFOLDER/ogg123"
   MP3_BIN="$MJPEGTBINFOLDER/mpg123"   
   MPLEX_BIN="$MJPEGTBINFOLDER/mplex"
fi
# check if programs are installed
if [ ! -e $PPMTOY4M_BIN ]; then
	echo -e "\nCan't find $PPMTOY4M_BIN, please install it or check -M parameter"
	exit -1
fi
if [ ! -e $YUVSCALER_BIN ]; then
	echo -e "\nCan't find $YUVSCALER_BIN, please install it or check -M parameter"
	exit -1
fi
if [ ! -e $MPEG2ENC_BIN ]; then
	echo -e "\nCan't find $MPEG2ENC_BIN, please install it or check -M parameter"
	exit -1
fi
if [ ! -e $MP2ENC_BIN ]; then
	echo -e "\nCan't find $MP2ENC_BIN, please install it or check -M parameter"
	exit -1
fi
if [ ! -e $OGG_BIN ]; then
	echo -e "\nCan't find $OGG_BIN, please install it or check -M parameter"
	exit -1
fi
if [ ! -e $MP3_BIN ]; then
	echo -e "\nCan't find $MP3_BIN, please install it or check -M parameter"
	exit -1
fi
if [ ! -e $MPLEX_BIN ]; then
	echo -e "\nCan't find $MPLEX_BIN, please install it or check -M parameter"
	exit -1
fi

# Verify if some images file have been given on the command line.
if [ $CPT_IMG_FILE = 0 ]; then
    echo -e "\nNo image file to convert !!!"
    exit -1
else
    if [ $WITHGUI = 0 ]; then
	echo -e "------------------------------------------------"
	echo -e "\nNumber of image file(s)       :  $CPT_IMG_FILE."
	echo -e "Processing sequence :"
    fi

    CPT=$CPT_IMG_FILE

    while test $CPT -gt 0; do
        INPUT_FILE_NAME="${INPUT_IMAGE_FILES[`echo $(($CPT_IMG_FILE-CPT))`]}"
        if [ $WITHGUI = 0 ]; then
    	    echo -e "$INPUT_FILE_NAME"
	fi
        if [ -s "$INPUT_FILE_NAME" ]; then
           CPT=`echo $(($CPT-1))`
        else
           echo -e "The image file '$INPUT_FILE_NAME' don't exist or can't be open !!!"
           exit -1
        fi
    done
fi

# Start encoding time mesurement.
DATE_DEBUT=`date +%s`

# For the mutisessions of this script, we use the number of seconds behind 1970 for the temporary name files.
if [ -z "$TEMPORARYFOLDER" ]; then
   TMPFILENAME="$DATE_DEBUT"
else
   TMPFILENAME="$TEMPORARYFOLDER/$DATE_DEBUT"
fi

# Number of video type for MjpegTools. The possibles values are :
#
# 0 -> MPEG1 generic.                                         -> not used.
# 1 -> VCD standard MPEG1 (PAL/SECAM:352x288 - NTSC:352x240). -> VCD.
# 2 -> VCD no standard.                                       -> not used.
# 3 -> MPEG2 generic.                                         -> not used.
# 4 -> VCD standard MPEG2 (PAL/SECAM:576x480 - NTSC:480x480). -> SVCD.
# 5 -> SVCD no standard   (PAL/SECAM:720x576 - NTSC:720x480). -> XVCD.
# 6 -> VCD with fixed images (Still Frame).                   -> not used.
# 7 -> SVCD with fixed images (Still Frame).                  -> not used.
# 8 -> DVD MPEG2          (PAL/SECAM:720x576 - NTSC:720x480). -> DVD.

case $VIDEO_TYPE in
    PAL)
      VIDEO_TYPE_LETTER="p"
      IMAGES_SEC=25
      IMAGES_SEC_FORMAT="25:1"
      ;;
    NTSC)
      VIDEO_TYPE_LETTER="n"
      IMAGES_SEC=30
      IMAGES_SEC_FORMAT="30000:1001"
      ;;
    SECAM)
      VIDEO_TYPE_LETTER="s"
      IMAGES_SEC=25
      IMAGES_SEC_FORMAT="25:1"
      ;;
    *)
      echo "Video type '$VIDEO_TYPE' not recognized..."
      exit 1
      ;;
esac

case $VIDEO_FORMAT in
    VCD)
      VIDEO_FORMAT_NUMBER=1
      BIT_RATE=1150
      BUFFER_SIZE=46
      VIDEOFORMAT_MESSAGE="VCD"
      AUDIO_WAVE_CONVERSION="-V"
      ;;
    SVCD)
      VIDEO_FORMAT_NUMBER=4
      BIT_RATE=2500
      BUFFER_SIZE=230
      VIDEOFORMAT_MESSAGE="SVCD"
      AUDIO_WAVE_CONVERSION="-V"
      ;;
    XVCD)
      VIDEO_FORMAT_NUMBER=5
      if [ $VIDEO_TYPE = "NTSC" ]; then
        VIDEO_FORMAT="SIZE_720x480"
      else
        VIDEO_FORMAT="SIZE_720x576"
      fi
      BIT_RATE=2500
      BUFFER_SIZE=230
      VIDEOFORMAT_MESSAGE="XVCD"
      AUDIO_WAVE_CONVERSION="-V"      
      ;;
    DVD)
      VIDEO_FORMAT_NUMBER=8
      if [ $VIDEO_TYPE = "NTSC" ]; then
        VIDEO_FORMAT="SIZE_720x480"
      else
        VIDEO_FORMAT="SIZE_720x576"
      fi
      BIT_RATE=8000
      BUFFER_SIZE=230
      VIDEOFORMAT_MESSAGE="DVD"
      AUDIO_WAVE_CONVERSION="-b 224 -r 48000 -s"
      ;;
    *)
      echo "Video format '$VIDEO_FORMAT' not recognized..."
      exit 1
      ;;
esac

case $VERBOSE in
    0)
      VERBOSITY="none"
      ;;
    1)
      VERBOSITY="errors & warning"
      ;;
    2)
      VERBOSITY="debug"
      ;;
    *)
      echo "Invalid verbosity level '$VERBOSE'..."
      exit 1
      ;;
esac

# Creating the temporary default background file image. It's used by ImageMagick when it
# resizing image for the TV screen dimensions. ImageMagick add a border around the image with this.
# ImageMagick create this temporary background image file only if you don't give a specific backgroung
# image name on the command line.

if [ -z "$MASK" ]; then
    if [ -z $BACKGROUNDCOLOR ]; then
       BACKGROUNDCOLOR="000000"
    fi
    MASK="$TMPFILENAME.black.tmp.png"
    RET=`$CONVERT_BIN xc:#$BACKGROUNDCOLOR -resize '768x576!' "$MASK"`
fi

# Calculating the number of frames for one image sequence duration and the images number.
# Append all images on a MPEG file.

NBFRAMEIMAGE=`echo $(($IMAGEDURATION*$IMAGES_SEC))`
if [ $TRANSITIONENABLE = 1 ]; then
    NBFRAMETRANSITION=`echo $((100/$DISSOLVEVALUEINC))`
else
    NBFRAMETRANSITION=0
fi
TRANSITIONDURATION=`echo $(($NBFRAMETRANSITION/$IMAGES_SEC))`
NBFRAMETOTAL=`echo $(((($NBFRAMEIMAGE+$NBFRAMETRANSITION)*$CPT_IMG_FILE)+$NBFRAMETRANSITION))`
TOTALDURATION=`echo $(((($IMAGEDURATION+$TRANSITIONDURATION)*$CPT_IMG_FILE)+$TRANSITIONDURATION))`

WARNINGTOTALDURATION=""
if [ $[$TOTALDURATION <= 3] = 1 ]; then
   WARNINGTOTALDURATION="(WARNING : total duration <= 3s !!!)"
fi

if [ $WITHGUI = 0 ]; then
    echo -e "Video format                  : '$VIDEOFORMAT_MESSAGE'."
    echo -e "Video type                    : '$VIDEO_TYPE'."
    if [ "$AUDIO_MPEG" ]; then
	echo -e "MPEG audio file               : '$AUDIO_MPEG'."
    fi
    if [ "$AUDIO_WAV" ]; then
	echo -e "WAV audio file                : '$AUDIO_WAV'."
    fi
    echo -e "Frames per second             : '$IMAGES_SEC'."
    echo -e "Image duration                :  $IMAGEDURATION s."
    echo -e "Total video sequence duration :  $TOTALDURATION s $WARNINGTOTALDURATION."
    if [ $TRANSITIONENABLE = 1 ]; then
	echo -e "Transition frames             :  $NBFRAMETRANSITION."
    fi
    echo -e "Total frames processing       :  $NBFRAMETOTAL."
    echo -e "Background image file         : '$MASK'."
    echo -e "Verbosity                     : '$VERBOSITY'.\n"
    echo -e "------------------------------------------------"
fi

# Creating a MPEG flux with the images.

if [ $WITHGUI = 0 ]; then     
    echo -e "Encoding $CPT_IMG_FILE image(s) MPEG sequence with ImageMagick and MjpegTools.\n"
else 
    echo -e "Encoding image files...\n" >&2
fi

# Counter of frames for the MPEG conversion.
CPT=0

# Counter of image input files for the MPEG conversion.
CPF=1

# Counter of dissolve values.
CPD=0

# Initial dissolve value (%).
DISSOLVEVALUE=99

if [ $TRANSITIONENABLE = 1 ]; then
    $CONVERT_BIN -type TrueColor -quality 100 "$MASK" "$TMPFILENAME.prev_trans.tmp.pnm"
    INPUT_IMAGE_FILES[`echo $(($CPT_IMG_FILE))`]="$MASK"
    CPT_IMG_FILE=`echo $(($CPT_IMG_FILE+1))`
fi

while test $CPT -lt $NBFRAMETOTAL;\
     do
        CPT=`echo $(($CPT+1))`

        # For debugging...
        # echo -ne "Frame Num. $CPT / $NBFRAMETOTAL      - DISSOLVE=$DISSOLVEVALUE    - Image Num. $CPF / $CPT_IMG_FILE ["${INPUT_IMAGE_FILES[`echo $(($CPF-1))`]}"] \n" >&2

        if [ $WITHGUI = 0 ]; then     
    	    echo -ne "Frame Num. $CPT / $NBFRAMETOTAL      \r" >&2
	else 
	    COUNTERGUI=`echo $((($CPT*100)/$NBFRAMETOTAL))`
	    echo -ne "Images encoding (%) : $COUNTERGUI      [`echo $(($CPF-1))`      \n" >&2
	fi

        if [ $TRANSITIONENABLE = 0 ]; then
	    if [ $CPT = `echo $((($CPF*$NBFRAMEIMAGE)-$NBFRAMEIMAGE+1))` ]; then

		# Conversion and resizing the curent image file with ImageMagick.
    		$MONTAGE_BIN -type TrueColor -quality 100 -geometry 768x576 -texture "$MASK" "${INPUT_IMAGE_FILES[`echo $(($CPF-1))`]}" "$TMPFILENAME.tmp.jpg"
		$CONVERT_BIN -type TrueColor -quality 100 "$TMPFILENAME.tmp.jpg" "$TMPFILENAME.tmp.pnm"

		# Next input image...
    		CPF=`echo $(($CPF+1))`
	    fi

	else
	    if [ $[$CPT >= `echo $((($CPF*($NBFRAMEIMAGE+$NBFRAMETRANSITION)-$NBFRAMEIMAGE-$NBFRAMETRANSITION)))`] = 1 ]; then
		if [ $[$CPT <= `echo $((($CPF*($NBFRAMEIMAGE+$NBFRAMETRANSITION)-$NBFRAMEIMAGE)))`] = 1 ]; then

		    if [ $DISSOLVEVALUE = 99 ]; then
    			$MONTAGE_BIN -type TrueColor -quality 100 -geometry 768x576 -texture "$MASK" "${INPUT_IMAGE_FILES[`echo $(($CPF-1))`]}" "$TMPFILENAME.tmp.jpg"
    			$CONVERT_BIN -type TrueColor -quality 100 "$TMPFILENAME.tmp.jpg" "$TMPFILENAME.next_trans.tmp.pnm"
		    fi

		    $COMPOSITE_BIN "$TMPFILENAME.prev_trans.tmp.pnm" "$TMPFILENAME.next_trans.tmp.pnm" -type TrueColor -quality 100 -dissolve $DISSOLVEVALUE "$TMPFILENAME.tmp.pnm"

		    if [ $CPD = `echo $(($NBFRAMETRANSITION-1))` ]; then

		        # Next input image...
  			CPF=`echo $(($CPF+1))`

			DISSOLVEVALUE=99
			CPD=0
			cp -f "$TMPFILENAME.next_trans.tmp.pnm" "$TMPFILENAME.prev_trans.tmp.pnm"
    			mv -f "$TMPFILENAME.next_trans.tmp.pnm" "$TMPFILENAME.tmp.pnm"
		    else
	    	        CPD=`echo $(($CPD+1))`
			DISSOLVEVALUE=`echo $((100-($CPD*$DISSOLVEVALUEINC)))`
		    fi
		fi
	    fi
        fi

	# MjpegTools MPEG encoding with the number of frames and the current image.
        $CONVERT_BIN -depth 8  ppm:"$TMPFILENAME.tmp.pnm" - | cat 

     done | $PPMTOY4M_BIN -v $VERBOSE -n $NBFRAMETOTAL -F $IMAGES_SEC_FORMAT $PPMTOY4M_CHROMA_OPT | $YUVSCALER_BIN -v $VERBOSE -n $VIDEO_TYPE_LETTER -O $VIDEO_FORMAT | $MPEG2ENC_BIN -v $VERBOSE -n $VIDEO_TYPE_LETTER -b $BIT_RATE -V $BUFFER_SIZE -f $VIDEO_FORMAT_NUMBER -o "$TMPFILENAME.tmp.m2v"

DATE_FIN=`date +%s`
TEMPSCALCUL=`echo $(($DATE_FIN-DATE_DEBUT))`

if [ $WITHGUI = 0 ]; then
    echo -e "\nMPEG encoding terminated [$NBFRAMETOTAL frames - Encoding time : $TEMPSCALCUL s]."
fi

# Building sound track if necessary...

AUDIOFILENAME=""

if [ "$AUDIO_MPEG" ]; then
    AUDIOFILENAME="$AUDIO_MPEG"
else
    if [ "$AUDIO_WAV" ]; then
        if [ $WITHGUI = 0 ]; then     
            echo -e "\nEncoding MPG layer 2 audio file from $AUDIO_WAV WAV file with MjpegTools."
	else 
	    echo -e "\nEncoding audio file...\n" >&2
	fi
	file -i "$AUDIO_WAV" | grep "audio/x-wav" && cp -f "$AUDIO_WAV" "$TMPFILENAME.tmp.wav"
	file -i "$AUDIO_WAV" | grep "application/ogg" && $OGG_BIN -q -d wav -f "$TMPFILENAME.tmp.wav" "$AUDIO_WAV"
	file -i "$AUDIO_WAV" | grep "audio/mpeg" && $MP3_BIN -q -w "$TMPFILENAME.tmp.wav" "$AUDIO_WAV"
	cat "$TMPFILENAME.tmp.wav" | $MP2ENC_BIN -v $VERBOSE $AUDIO_WAVE_CONVERSION -o "$TMPFILENAME.tmp.mp2"
        AUDIOFILENAME="$TMPFILENAME.tmp.mp2"        
    fi
fi

# Video and audio streams final merge for VCDImager compatibility.

if [ $WITHGUI = 0 ]; then     
    echo -e "\nMerging MPEG flux with MjpegTools."
else 
    echo -e "\nMerging MPEG flux..." >&2
fi

# No output MPEG file name on command line -> take a temporary file.
if [ -z "$OUTPUT_MPEG_FILE" ]; then
    OUTPUT_MPEG_FILE="$TMPFILENAME.mpg"
fi

if [ "$AUDIOFILENAME" ]; then 
    $MPLEX_BIN -v $VERBOSE -f $VIDEO_FORMAT_NUMBER -b $BUFFER_SIZE "$AUDIOFILENAME" "$TMPFILENAME.tmp.m2v" -o "$OUTPUT_MPEG_FILE"
else
    $MPLEX_BIN -v $VERBOSE -f $VIDEO_FORMAT_NUMBER -b $BUFFER_SIZE "$TMPFILENAME.tmp.m2v" -o "$OUTPUT_MPEG_FILE"
fi    

if [ $WITHGUI = 0 ]; then     
    echo -e "\nThe video MPEG output file is '$OUTPUT_MPEG_FILE'."
else 
    echo -e "\nEncoding terminated..." >&2
fi

# Clean up & Bye...
CleanUp

# --------------------------------------END OF MAIN----------------------------------------------------------
