#!/bin/bash
#set -n		# read but do not execute commands (check on syntax errors)
#
# File: /usr/local/bin/audiowaves
#
# Show the audio samples waves of an audio.
#
#    Copyright (C) 2023  Juergen Kaesmann (JK)
#
##############################################################################
# GPL NOTICE
#
#    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
#
##############################################################################
# FIND SAMPLES
#
##############################################################################
# FILTER SAMPLES
#
##############################################################################
# AWK SAMPLES
#
##############################################################################
# SED SAMPLES
#
##############################################################################
# RSYNC OPTIONS
#
##############################################################################
# DIALOG SAMPLES
#
##############################################################################
# REPLACE STRINGS
#
##############################################################################
# EXIT CODES

##############################################################################
# SOURCE FILES
#
. /usr/local/etc/main.conf				# config main
#. $LLIBDIR/libfuncerr-sh				# functions error
. $LLIBDIR/libfuncstd-sh				# functions standard
. $LLIBDIR/libfuncmath-sh				# functions math
#. $LLIBDIR/libfuncip-sh				# functions IP
#. /usr/local/etc/sample.conf				# config sample
#
#if [ ! -e ~/.samplerc ]; then				# install config user
#	cp /usr/local/share/ksm-sample/samplerc ~/.samplerc
#fi
#. ~/.samplerc						# config user

##############################################################################
# DECLARATION OF STANDARD CONSTANTS AND VARIABLES
#
readonly package=Multimedia				# package name
readonly package_file=ksm-multimedia			# package file name
readonly vinfopath="/usr/local/share/$package_file"	# path to package dir
readonly version=$(/bin/cat $vinfopath/VERSION)		# package version
readonly release=$(/bin/cat $vinfopath/RELEASE)		# package release
readonly scriptname=$(basename $0)			# name of script
#readonly tempfile=$TEMPDIR/$scriptname.$UID.tmp	# temporary file name
#tempfile=$(mktemp $TEMPDIR/$scriptname.$UID.XXXXXX)	# temporary file name
#readonly lockfile=$TEMPDIR/lock/$scriptname.$UID.lock	# lock file name
readonly debuglog="/usr/bin/logger -p user.debug -t $scriptname -- DEBUG:"	# log dbg msg
readonly errlog="/usr/bin/logger -p user.err -t $scriptname -- ERROR:"		# log err msg
readonly infolog="/usr/bin/logger -p user.info -t $scriptname -- INFO:"		# log inf msg
cmd=''							# sub command
debug=no						# debug=yes/no
verbose=''						# verbose=yes/''/no
err=${_ERR_OK_}						# error code

##############################################################################
# USER FILL IN AT FIRST RUN

##############################################################################
# SYSTEM

##############################################################################
# USER-CONSTANTS

##############################################################################
# USER-VARIABLES
#
# STRINGS
tempnut=/tmp/$scriptname.$UID.nut	# temporary file name

#args=''				# all args from cmdline
arg1=''					# 1. arg from cmdline
#opt_o=''				# option -o (yes)
					# option --output (yes)
#opt_i=''				# option -i (arg)
					# option --infile (arg)
#opt_o=''				# option -o (arg)
					# option --outfile (arg)
#opt_p=''				# option -p (arg)
					# option --pages (arg)
opt_S=''				# option -S (arg)
opt_s=''				# option -s (arg)
size='1920x900'				# def. video window size
psize='1920x1000'			# def. picture size
outpic=''

# NUMBERS
#p_first=0				# first page
#p_last=0				# last page

# ARRAYS
# Indexed arrays are always zero based string arrays.
# If index starts with 1 and all members are assigned then
# count of members of array = last index of array
#declare -a arr
#maxarr="${#arr[@]}"			# get number of elements in arr
#unset arr[@]				# remove the entire array

##############################################################################
# SIGNAL HANDLING

##############################################################################
# FUNCTIONS
##############################################################################
#
##############################################################################
# HELP
#
#=============================================================================
function helptext ()
{
# Output helptext
# Uses cat, echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG helptext: $# $@" >&2
	$debuglog helptext: $# $@
fi

cat <<EOT
NAME
$scriptname - Show the audio samples waves of an audio.

SYNOPSIS
$scriptname [options] [inf]

<AUDIOSTREAM> | $scriptname [options] -

DESCRIPTION
Show the audio samples waves of an audio. Left channel is at top, right
channel is at bottom. Press 'SPACE' to pause or 'Q' to quit. Defaualt
size = $size

If <inf> is '-' then we process an incoming audio stream (type nut)
from STDIN.

OPTIONS
Gnu style options:

  -h|--help    = Output help, then exit.
  -V|--version = Output version info, then exit.
  -d|--debug   = Turn on DEBUG mode.
  -q|--quiet   = Be quiet.
  -v|--verbose = Be verbose.
  -m           = Make a waves picture of an audio.
                 Picture is <inf>.waves.png
  -p           = Show an already created waves picture of an audio.
  -S           = Picture size (def. = $psize).
  -s           = Video window size (def. = $size).
  --           = End of options.

ARGUMENTS
Give if needed:

  inf = The input file name (give '-' to input from STDIN).

EXIT STATUS
On program exit:

  Code 0 = OK

  See output of 'showerrmsg'.

FILES
Used directories and files:

  Config global = /usr/local/etc/multimedia.conf

SEE ALSO
Related manpages:

  showerrmsg(1), ffmpeg(1), media2media(1), audiofilter-compand(1),
  audiofilter-dynaudnorm(1), audiofilter-dynvol(1),
  audiofilter-fade(1), audiofilter-limiter(1), audiofilter-tempo(1),
  audiofilter-volcomp(1), audioshow-avectorscope(1).

AUTHORS
Juergen Kaesmann <juergen@kaesmann-online.de>
EOT
#  -o|--output  = Output to STDOUT.
#  -i f         = Input from file <f>.
#  --infile=f   = Input from file <f>.
#  -o f         = Output to file <f>.
#  --outfile=f  = Output to file <f>.
#  -p s,e       = Pages s=START e=END.
#  --pages=s,e  = Pages s=START e=END.

#EXAMPLES
#For instance:
#
#  Do it:
#  $scriptname

return
}

#=============================================================================
function make_picture ()
{
# Make a picture
# par1 = inf
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG make_picture: $# $@" >&2
	$debuglog make_picture: $# $@
fi

local inf="$1"
local ret=0

if [ -n "$opt_S" ]; then
	psize="$opt_S"
fi

ffmpeg -hide_banner -y -i $inf -lavfi "showwavespic=size=$psize:split_channels=1:colors=green|red:scale=lin" $outpic
ret=$?
if [ "$ret" -ne 0 ]; then				# from ffplay
	if [ "$verbose" != no ]; then
		echo "${ErrMsg[${_ERR_GENERAL_}]} $ret from ffplay!" >&2
	else
		$errlog ${ErrMsg[${_ERR_GENERAL_}]} $ret from ffplay
	fi
	ret=${_ERR_GENERAL_}
fi

return $ret
}

#=============================================================================
function mainproc ()
{
# Apply volume to the fiven file.
# par1 = inf
# Uses echo, logger
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG mainproc: $# $@" >&2
	$debuglog mainproc: $# $@
fi

local inf="$1"
local ret=0
#local -a arr
#maxarr="${#arr[@]}"			# get number of elements in arr
#unset arr[@]				# remove the entire array

if [ -n "$opt_s" ]; then
	size="$opt_s"
fi

ffplay -hide_banner -f lavfi "amovie=$inf,asplit[out0],showwaves=size=$size:mode=cline:split_channels=1:colors=green|red[out1]"
ret=$?
if [ "$ret" -ne 0 ]; then				# from ffplay
	if [ "$verbose" != no ]; then
		echo "${ErrMsg[${_ERR_GENERAL_}]} $ret from ffplay!" >&2
	else
		$errlog ${ErrMsg[${_ERR_GENERAL_}]} $ret from ffplay
	fi
	ret=${_ERR_GENERAL_}
fi

return $ret
}

##############################################################################
# GET OPTIONS
##############################################################################
# Give 2 strings and all cmdline_args to function Get Opt
# (POSIX_options Gnu_long_options cmdline_args):
# Get Opt 'hVdqvi:m:' 'help version debug quiet verbose infile= myval=' $@
#
# A ':' after a POSIX option means this option needs an arg.
# A '=' after a Gnu long option means this option needs an arg.
#
# All cmd/options have to be initialised to ''!
#
# POSIX options are classified in 2 categories:
#   a) cmds (mutually exclusive). All cmds are given to var 'cmd'.
#   b) options (as many as you like). Each option is given to it's own var.
# As a general rule: If cmds/options are given multiple then last given wins.
#
# Options can take 1 argument (no whitespace in arg). If you want to give more
# than 1 arg or want to use multiple strings as 1 arg then concatenate them
# together with ',' as delimiter:
# sampleprog -m val1,val2
# sampleprog --myval=val1,val2
# It's at the programmers responsibility to do meaningfull things with the
# content of the options.
#
# If err != 0 then all args are processed, else continue to look for options.
# When Get Opt finishes then all options are removed from cmdline.
#
if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG Parse Commandline: $# $@" >&2
	$debuglog Parse Commandline: $# $@
fi
#
err=${_ERR_OK_}
while [ "$err" -eq 0 ]; do
	GetOpt 'hVdqvmpSs:' 'help version debug quiet verbose' $@
	err=$?
	#echo "DEBUG GET OPTIONS: err=${err}  _OPTNAME_=${_OPTNAME_}  _OPTVAL_=${_OPTVAL_}  _OPTPOS_=${_OPTPOS_}  _OPTIDX_=${_OPTIDX_}" >&2
	if [ $err -eq 0 ]; then
		case "$_OPTNAME_" in
		    h|help)	cmd="-h";;
		    V|version)	cmd="-V";;
		    m)		cmd="-${_OPTNAME_}";;
		    p)		cmd="-${_OPTNAME_}";;
		    d|debug)	debug=yes;;
		    q|quiet)	verbose=no;;
		    v|verbose)	verbose=yes;;
#		    o|output)	opt_o=yes;;
#		    i|infile)	opt_i="${_OPTVAL_}";;
#		    o|outfile)	opt_o="${_OPTVAL_}";;
#		    p|pages)	opt_p="${_OPTVAL_}";;
		    S)		opt_S="${_OPTVAL_}";;
		    s)		opt_s="${_OPTVAL_}";;
		    --)		break;;
		    :)	if [ "$verbose" != no ]; then
				echo "${ErrMsg[${_ERR_MISSING_ARG_FOR_OPT_}]} -${_OPTVAL_}" >&2
			else
				$errlog ${ErrMsg[${_ERR_MISSING_ARG_FOR_OPT_}]} -${_OPTVAL_}
			fi; exit ${_ERR_MISSING_ARG_FOR_OPT_};;
		    ?)	if [ "$verbose" != no ]; then
				echo "${ErrMsg[${_ERR_UNKNOWN_OPT_}]} -${_OPTVAL_}" >&2
			else
				$errlog ${ErrMsg[${_ERR_UNKNOWN_OPT_}]} -${_OPTVAL_}
			fi; exit ${_ERR_UNKNOWN_OPT_};;
		    *)	if [ "$verbose" != no ]; then
				echo "${ErrMsg[${_ERR_UNKNOWN_ERR_}]} _OPTNAME_=${_OPTNAME_} _OPTVAL_=${_OPTVAL_}" >&2
			else
				$errlog ${ErrMsg[${_ERR_UNKNOWN_ERR_}]} _OPTNAME_=${_OPTNAME_} _OPTVAL_=${_OPTVAL_}
			fi; exit ${_ERR_UNKNOWN_ERR_};;
		esac
	fi
done
err=${_ERR_OK_}
shift ${_OPTIDX_}				# rm all opts from cmdline
#
# Uncomment if giving a cmd is mandatory
#if [ -z "$cmd" ]; then					# error no cmd given
#	if [ "$verbose" != no ]; then
#		echo "${ErrMsg[7]}" >&2
#	else
#		$errlog ${ErrMsg[7]}
#	fi
#	exit 7
#fi

##############################################################################
# CHECK LINK NAMES

##############################################################################
# CHECK OPTIONS

##############################################################################
# CHECK VERSION

##############################################################################
# CHECK ARGUMENTS
#
case "$cmd" in
    ''|-m|-p)
	if [ "$#" -eq 1 ]; then				# parameter count ok
		arg1="$1"
		shift
		#args="$@"
		#shift $#
	else						# error in param count
		if [ "$verbose" != no ]; then
			echo "${ErrMsg[${_ERR_WRONG_PAR_COUNT_}]}" >&2
		else
			$errlog ${ErrMsg[${_ERR_WRONG_PAR_COUNT_}]}
		fi
		exit ${_ERR_WRONG_PAR_COUNT_}
	fi
	;;
    *)
	if [ "$#" -ne 0 ]; then				# error in param count
		if [ "$verbose" != no ]; then
			echo "${ErrMsg[${_ERR_WRONG_PAR_COUNT_}]}" >&2
		else
			$errlog ${ErrMsg[${_ERR_WRONG_PAR_COUNT_}]}
		fi
		exit ${_ERR_WRONG_PAR_COUNT_}
	fi
	;;
esac

##############################################################################
# LOCK

##############################################################################
# MAINPROGRAM
##############################################################################
#
if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG Main: $# $@" >&2
	$debuglog Main: $# $@
fi
#
outpic="${arg1}.waves.png"
#
# Check what to do (sub commands, options and args are removed from cmdline)
case "$cmd" in
    '')
	if [ "$arg1" == "-" ]; then
		cat > $tempnut
		mainproc $tempnut
		err=$?
		rm -f $tempnut
	else
		mainproc $arg1
		err=$?
	fi
	;;
    -h)
	helptext
	exit 0
	;;
    -V)
	echo "${scriptname}: (${package}) $package_file ${version}-${release}"
	exit 0
	;;
    -m)
	if [ "$arg1" == "-" ]; then
		cat > $tempnut
		make_picture $tempnut
		err=$?
		rm -f $tempnut
	else
		make_picture $arg1
		err=$?
	fi
	;;
    -p)
	showpicture $outpic 1>&/dev/null
	err=$?
	;;
    *)							# error
	if [ "$verbose" != no ]; then
		echo "${ErrMsg[${_ERR_SUB_CMD_NOT_FOUND_}]}" >&2
	else
		$errlog ${ErrMsg[${_ERR_SUB_CMD_NOT_FOUND_}]}
	fi
	err=${_ERR_SUB_CMD_NOT_FOUND_}
	;;
esac

#rm -f $lockfile

exit $err
