Skip to content

Instantly share code, notes, and snippets.

@chrisstubbs93
Last active January 11, 2024 22:40
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save chrisstubbs93/f1ee6220dbb3e5a92398feed48ed6cb8 to your computer and use it in GitHub Desktop.
Save chrisstubbs93/f1ee6220dbb3e5a92398feed48ed6cb8 to your computer and use it in GitHub Desktop.
auto-restart FFMPEG when it stops sending frames to youtube
#!/bin/sh
sleep 5
ffmpeg -re -f mjpeg -r 10 -i "http://localhost/?action=stream" -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /dev/zero -acodec aac -ab 1k -strict experimental -s 640x360 -vcodec h264 -pix_fmt yuv420p -g 20 -vb 500k -preset ultrafast -crf 31 -r 10 -f flv "rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx" 2> /home/pi/ffmpeg.log
#!/bin/sh
sleep 10
while true
do
frameA=$(tail /home/pi/ffmpeg.log -n 1 | sed -nr 's/.*frame=(.*)fps.*/\1/p')
echo "$frameA"
sleep 5
frameB=$(tail /home/pi/ffmpeg.log -n 1 | sed -nr 's/.*frame=(.*)fps.*/\1/p')
echo "$frameB"
if [ "$frameA" = "$frameB" ]
then
echo "Stream has hung"
printf "%s - Stream has hung\n" "$(date)" >> stream.log
pkill ffmpeg
echo "killed ffmpeg..."
printf "%s - Killed ffmpeg...\n" "$(date)" >> stream.log
echo "Waiting 5 secs"
sleep 5
bash /home/pi/ffmpeg.sh &
echo "started ffpmeg.."
printf "%s - Started ffmpeg..\n" "$(date)" >> stream.log
echo "Waiting 15 secs"
sleep 15
else
echo "Stream looks ok."
fi
sleep 2
done
@kupietools
Copy link

This just got me where I needed to go on a solution. Thanks.

@WinsDominoes
Copy link

Really awesome! Got mine working with my custom rtmp server. Thanks a lot!

@simpletvlc
Copy link

When I do this it also kills other streams. I want to do it for only 1 broadcast.

@Matt-Yao
Copy link

I am completely new to Pi's, scripting and such. Is this a command to execute or do i paste this (with changed URL) it in a config file?

@chrisstubbs93
Copy link
Author

I am completely new to Pi's, scripting and such. Is this a command to execute or do i paste this (with changed URL) it in a config file?

These are shell scripts. It's a simple language to automate terminal commands.

Take a look at https://www.circuitbasics.com/how-to-write-and-run-a-shell-script-on-the-raspberry-pi/

Have fun!

@senkron24
Copy link

When I do this it also kills other streams. I want to do it for only 1 broadcast.

exackt this problem have to how to kill just pid or samthink like this ...

@merentitis
Copy link

Nice job :)
Is there a way to truncate the logs without effect to the process ? Running 24/7 for multiple streams creates large files.
@simpletvlc I created a softlink to /bin/ffmpeg with different name, e.g. ffmpeg-stream1. I now have to kill the ffmpeg-stream1 process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment