#!/bin/bash
#
# livecam	This shell script start and stop ffmpeg and ffserver.
#
# chkconfig: 345 97 11
# description: Starts and stops the ffmpeg and ffserver daemons \
#              used to provide Live Camera services.

### BEGIN INIT INFO
# Provides: livecam
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: $network $local_fs $remote_fs
# Should-Start: $syslog $named 
# Should-Stop: $syslog $named
# Short-Description: start and stop livecam
# Description: livecam is the ffserver and ffmpeg video streaming service.
### END INIT INFO

#CAMERA_MODULE=pwc
CAMERA_MODULE=""

#export LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so

# ffmpeg を起動する場合は 1 起動しない場合は 0
ffm=1
# 他機のffmpegでキャプチャした画像を自機のffserverで配信する場合など
#ffm=0		# no ffmpeg (ffserver only)

# ffserver を起動する場合は 1 起動しない場合は 0
ffs=1
# 自機のffmpegでキャプチャした画像を他機のffserverで配信する場合など
#ffs=0		# no ffserver (ffmpeg only)

SERVER="localhost:8090"

CONFIG=/usr/local/etc/ffserver.conf
FFSERVER=/usr/local/bin/ffserver

FFMPEG=/usr/local/bin/ffmpeg
FFMPEG_OPT="-f video4linux2 -an -s 320x240 -i /dev/video0 http://${SERVER}/feed1.ffm"
#FFMPEG_OPT="-f video4linux2 -an -s 640x480 -i /dev/video0 http://${SERVER}/feed1.ffm"

LOCKFILE=/var/lock/subsys/ffserver

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

RETVAL=0
RETVAL2=0

start() {
	echo "livecam start..."
	/bin/ps ax | /bin/grep -v grep | /bin/grep -q ${FFMPEG} >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo "ffmpeg is running..."
		ffm=0
	fi
	/bin/ps ax | /bin/grep -v grep | /bin/grep -q ${FFSERVER} >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo "ffserver is running ..."
		ffs=0
	fi
	if [ x"$CAMERA_MODULE" != x"" ]; then
		if ! /sbin/lsmod | grep -q ${CAMERA_MODULE} ; then
			echo -n $"Loading camera modules: "
			/sbin/modprobe ${CAMERA_MODULE}
			sleep 3
		fi 
	fi
	if [ $ffs -eq 1 ]; then
		echo "starting livecam ..."
        	echo -n $"Starting ffserver services: "
        	${FFSERVER} -f ${CONFIG} >/dev/null 2>&1 &
#        	${FFSERVER} -f ${CONFIG} &
        	RETVAL=$?
        	echo
		sleep 3
	fi
	if [ $ffm -eq 1 ]; then
        	echo -n $"Starting ffmpeg services: "
        	${FFMPEG} ${FFMPEG_OPT} >/dev/null 2>&1 &
#        	${FFMPEG} ${FFMPEG_OPT} &
        	RETVAL2=$?
        	echo
	fi
	[ $RETVAL -eq 0 -a $RETVAL2 -eq 0 ] && touch ${LOCKFILE} || RETVAL=1
	echo ""
	return $RETVAL
}

stop() {
	echo "livecam stop..."
	if [ $ffm -eq 1 ]; then
        	echo -n $"Shutting down ffmpeg services: "
        	killproc ffmpeg
        	RETVAL=$?
        	echo
	fi
	if [ $ffs -eq 1 ]; then
        	echo -n $"Shutting down ffserver services: "
        	killproc ffserver
        	RETVAL2=$?
        	echo
	fi
	[ $RETVAL -eq 0 -a $RETVAL2 -eq 0 ] && rm -f ${LOCKFILE}
	echo ""
	return $RETVAL
}


#
# Usage statement.
#

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	*)
		echo "usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit $RETVAL

