#!/usr/bin/bash

# 
# File: live-stream.sh
# Version: 0.1
# Authors: Stéphane Cousot <http://www.ubaa.net/>
# License: live-stream.sh is released under GNU General Public License, version 3 or later
#
# ----------------------------------------------------------------------------------
#
# This file is part of the π-view project.
#
# 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 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, see <http://www.gnu.org/licenses/>.
#



# TOFIX
# stop raspivid if pipeline commands are stopped or crashed while running on service
# mmal: Failed to write buffer data

# TODO
# use ffmpeg -i /dev/video0 to grab image instead of raspivid


set -o pipefail

ERR=0
IMG="/srv/http/img/preview.jpg"
NOW=`TZ=Europe/Paris date -R`
CMD=""


if [ -z "$CMD" ]; then
	echo "NO COMMAND LINES FOUND ?"
	exit 1
fi


usage()
{
	echo "$0 {OPTIONS}"
	echo ""
	echo "Piview live stream manager"
	echo "no options to start streaming"
	echo 
	echo "  -h --help    show this help"
	echo "  -i --image   save a picture"
}

run()
{
	# !!! IMPORTANT: disable command line banner/progress/statistics for system logs
	CMD=`echo "$CMD" | sed 's/ffmpeg/ffmpeg -nostats -hide_banner/g'`
	CMD=`echo "$CMD" | sed 's/mplayer/mplayer -really-quiet/g'`

	echo "-- start live stream"
	echo "-- $NOW"
	eval "${CMD}"
	ERR=$?

	# fix ffmpeg status code
	if [ "$ERR" == 255 ]; then ERR=0; fi
	echo "-- exit with status $ERR"
}

save_image()
{
	if [ `pidof raspivid` ]; then
		echo "Failed to run camera, raspivid is already running"
		exit 0
	fi
	if [ -f $IMG ]; then rm $IMG; fi

	RASP=`echo "$CMD" | pcregrep -o1 -e "raspivid (.*) -o"`
	if [ "$RASP" == "" ]; then RASP=`echo "$CMD" | pcregrep -o1 -e "raspivid (.*)"`; fi
	OPTS=`echo "$RASP" | sed 's/-t [0-9]*//' | sed 's/--roi [0-9\.,]*//'`

	raspivid -t 1000 $OPTS -o - | ffmpeg -loglevel quiet -i - -qscale:v 2 -vframes 1 $IMG
	echo "image saved to $IMG"
}


case $1 in
	-i|--image )
		save_image
		;;
	-h|--help )
		usage
		exit 1
		;;
	* )
		run
		;;
esac
exit $ERR
