Skip to content

Instantly share code, notes, and snippets.

@hex128
Last active July 30, 2016 17:27
Show Gist options
  • Save hex128/4fb878ee82a1f5924969 to your computer and use it in GitHub Desktop.
Save hex128/4fb878ee82a1f5924969 to your computer and use it in GitHub Desktop.
RTMP streaming daemon based on FFmpeg
# Set settings and rename to rtsp-stream.conf
# Main video stream
camera="rtsp://127.0.0.1/stream"
# ALSA sound input
alsa_i="hw:0"
# RTMP server URL
server="rtmp://a.rtmp.youtube.com/live2"
# RTMP stream name
stream="username.1234-5678-90ad-cdef"
# Video size
v_size="1280x720"
# Video bitrate
v_bitr="2500k"
# Audio samplerate
a_samp="44100"
#!/bin/sh
### BEGIN INIT INFO
#
# Provides : rtmp-stream
# Required-Start : $network
# Required-Stop : $network
# Default-Start : 2 3 4 5
# Default-Stop : 0 1 6
# Short-Description : RTMP Stream
# Description : RTMP Stream
#
### END INIT INFO
prog="rtmp-stream"
config_file="/etc/rtmp-stream.conf"
pid_file="/var/run/rtmp-stream.pid"
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root"
exit 1
fi
start() {
if [ ! -f $config_file ]; then
echo "Configuration file missing"
exit 1
fi
if [ -f $pid_file ]; then
ffmpeg_pid=`cat $pid_file`
kill -0 $ffmpeg_pid > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "RTMP streaming is currently active"
exit 1
else
rm $pid_file > /dev/null 2>&1
fi
fi
$prog > /dev/null 2>&1 &
echo "RTMP streaming started"
}
stop() {
if [ -f $pid_file ]; then
ffmpeg_pid=`cat $pid_file`
kill -2 $ffmpeg_pid > /dev/null 2>&1
rm -r $pid_file > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "RTMP streaming is not running but PID file exists and was deleted"
else
echo "RTMP streaming stopped"
fi
else
echo "RTMP streaming is not started"
exit 1
fi
}
case "$1" in
start)
start
exit 0
;;
stop)
stop
exit 0
;;
restart)
stop
start
exit 0
;;
**)
echo "Usage: $0 {start|stop|restart}" 1>&2
exit 1
;;
esac
#!/bin/sh
running=true
config="/etc/rtmp-stream.conf"
pid_file="/var/run/rtmp-stream.pid"
log_file="/var/log/rtmp-stream.log"
source $config
if [ -z $log_level ]; then
log_level="error"
fi
while $running; do
ffmpeg -v "$log_level" -i "$camera" -f alsa -i "$alsa_i" -map 0 -map 1 -ar "$a_samp" -b:v "$v_bitr" -s "$v_size" -f flv "$server/$stream" >> $log_file 2>&1 &
ffmpeg_pid=$!
echo $ffmpeg_pid
echo $ffmpeg_pid > $pid_file
if [ $? -eq 0 ]; then
wait $ffmpeg_pid > /dev/null 2>&1
if [ ! -f $pid_file ]; then
running=false
rm $pid_file > /dev/null 2>&1
fi
else
echo "Unable to write PID file"
rm $pid_file > /dev/null 2>&1
exit 1
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment