How to Restart FFmpeg Stream Automatically

Live streaming with FFmpeg can easily interrupt due to temporary network drops, ISP changes, or server-side disconnections. This article provides a quick guide and ready-to-use scripts to wrap your FFmpeg command in a resilient loop, ensuring your stream automatically restarts and maintains maximum uptime on Linux, macOS, and Windows.

The Shell Loop Solution (Linux and macOS)

The most reliable way to handle network failures is to wrap your FFmpeg command inside a while loop using a Bash script. If FFmpeg terminates due to a network drop, the script waits for a few seconds and then launches the command again.

Create a file named stream.sh and add the following code:

#!/bin/bash

# Configuration
STREAM_URL="rtmp://your-streaming-destination/live"
STREAM_KEY="your-stream-key"
INPUT_SOURCE="input.mp4" # Can be a local file, RTMP pull, or camera input

echo "Starting resilient streaming loop..."

while true; do
    echo "Launching FFmpeg..."
    
    ffmpeg -re -i "$INPUT_SOURCE" \
      -c:v libx264 -preset veryfast -b:v 3000k -maxrate 3000k -bufsize 6000k \
      -pix_fmt yuv420p -g 50 -c:a aac -b:a 128k \
      -f flv "$STREAM_URL/$STREAM_KEY"
    
    echo "FFmpeg exited with code $?. Reconnecting in 5 seconds..."
    sleep 5
done

Make the script executable and run it:

chmod +x stream.sh
./stream.sh

How it works:


The Batch Loop Solution (Windows)

If you are running FFmpeg on Windows, you can achieve the same resilient behavior using a Command Prompt batch file (.bat).

Create a file named stream.bat and add the following code:

@echo off
:: Configuration
set STREAM_URL=rtmp://your-streaming-destination/live
set STREAM_KEY=your-stream-key
set INPUT_SOURCE=input.mp4

:loop
echo Launching FFmpeg...

ffmpeg -re -i "%INPUT_SOURCE%" ^
  -c:v libx264 -preset veryfast -b:v 3000k -maxrate 3000k -bufsize 6000k ^
  -pix_fmt yuv420p -g 50 -c:a aac -b:a 128k ^
  -f flv "%STREAM_URL%/%STREAM_KEY%"

echo FFmpeg exited. Reconnecting in 5 seconds...
timeout /t 5
goto loop

Double-click the stream.bat file to run it. Press Ctrl + C in the command window to stop the loop.


Optimizing FFmpeg Network Flags

To make FFmpeg even more resilient before the loop has to trigger, you can add native reconnection parameters directly into your command. These flags force FFmpeg to try reconnecting internally during minor packet losses, preventing the loop from having to restart the entire process.

If your input is an HTTP/HTTPS stream or an RTSP feed, add these flags before the -i (input) option:

ffmpeg -reconnect 1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 5 -i "http://your-input-stream" ...