Skip to content

Instantly share code, notes, and snippets.

@fellipec
Last active July 14, 2023 19:47
Show Gist options
  • Save fellipec/0c3ed1b3394a60f998b3ccd6ce0f2970 to your computer and use it in GitHub Desktop.
Save fellipec/0c3ed1b3394a60f998b3ccd6ce0f2970 to your computer and use it in GitHub Desktop.
Record from RTSP IP Camera
#!/usr/bin/bash
# Change to recording directory
cd /samba/ipcam
# Amount of time of the recording session
# Adjust to match the cron schedule
end=$((SECONDS+3599))
while [ $SECONDS -lt $end ]
do
#The ffmpeg parameters should be changed to account the camera and situation
/usr/local/bin/ffmpeg -fflags +genpts -r 15 -t 00:59:55 -rtsp_transport udp -i rtsp://admin:password@<CAMERA-IP>:554/onvif1 \
-strict -2 -vcodec copy -an -map 0 -f ssegment -strftime 1 -segment_time 900 \
-segment_format mp4 -reset_timestamps 1 -drop_pkts_on_overflow 1 -attempt_recovery 1 \
-recover_any_error 1 -blocksize 4096 -flush_packets 1 capture_%Y-%m-%d_%H-%M-%S.mp4 &
PID=$!
running=true
#After running the ffmpeg this will keep checking if there are recordings being made by
#counting the space in the record directory each minute. If it stops growing the script
#infers ffmpeg had some problem and asks it nicely to stop (signal 2 - SIGINT)
while [ "$running" = "true" ]
do
linea=`du -sc -- * | grep total`
echo A $linea
sleep 60
lineb=`du -sc -- * | grep total`
echo B $lineb
if [ "$linea" = "$lineb" ]
then
echo "ffmpeg has hung, restarting"
kill -2 $PID
#After sending a signal 2 to ffmpeg stop gracefully, check for 10 seconds if it indeed
#exit. If not, send a 9 SIGKILL
i=0
while ps -p $PID > /dev/null
do
sleep 1
((i++))
if [ $i -gt 10 ]
then
if ps -p $PID > /dev/null
then
kill -9 $PID
fi
fi
done
#This breaks the checking loop so the ffmpeg can be restarted by the main loop
running=false
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment