How to Set RTMP Retry Interval in FFmpeg
When streaming via RTMP using FFmpeg, network instability can cause connections to drop. This article provides a quick guide on how to configure connection timeout parameters in FFmpeg and implement an automatic reconnection loop to keep your RTMP stream online during network disruptions.
Configuring RTMP Timeouts in FFmpeg
FFmpeg does not have a native, infinite auto-reconnect flag for the RTMP protocol. Instead, it relies on socket-level timeouts to detect disconnects, combined with system-level loops to initiate the retry.
To configure the connection and read/write timeout for an RTMP
stream, use the -rw_timeout option. This option tells
FFmpeg how long to wait (in microseconds) before terminating the
connection due to inactivity or a network drop.
The FFmpeg Command Syntax
Add -rw_timeout followed by the timeout value in
microseconds (1 second = 1,000,000 microseconds) before
your output RTMP URL:
ffmpeg -re -i input.mp4 -c:v libx264 -preset veryfast -c:a aac -f flv -rw_timeout 5000000 rtmp://your-server-address/live/stream_keyIn this example, -rw_timeout 5000000 configures FFmpeg
to wait for 5 seconds before closing the connection if the network
drops.
Setting Up Automatic Connection Retries
Because FFmpeg exits completely when a connection is lost beyond the timeout period, you must wrap the command in a script loop to achieve continuous connection retries.
For Linux / macOS (Bash Script)
Create a bash script that automatically restarts FFmpeg after a 5-second delay if the connection drops:
#!/bin/bash
while true
do
echo "Starting FFmpeg stream..."
ffmpeg -re -i input.mp4 -c:v libx264 -preset veryfast -c:a aac -f flv -rw_timeout 5000000 rtmp://your-server-address/live/stream_key
echo "Stream disconnected. Retrying in 5 seconds..."
sleep 5
doneFor Windows (Command Prompt / Batch File)
Create a .bat file with the following loop
configuration:
@echo off
:loop
echo Starting FFmpeg stream...
ffmpeg -re -i input.mp4 -c:v libx264 -preset veryfast -c:a aac -f flv -rw_timeout 5000000 rtmp://your-server-address/live/stream_key
echo Stream disconnected. Retrying in 5 seconds...
timeout /t 5
goto loop