How to Set FFmpeg RTSP Timeout and Transport Protocol
This article provides a quick guide on how to configure the connection timeout and choose between UDP and TCP transport protocols when handling Real-Time Streaming Protocol (RTSP) streams in FFmpeg. By configuring these settings, you can prevent your stream from hanging indefinitely and optimize your network connection for latency or reliability.
Configuring the RTSP Transport Protocol (UDP vs. TCP)
By default, FFmpeg attempts to connect to RTSP streams using UDP. If
UDP packets are blocked or lost, it automatically falls back to TCP.
However, you can explicitly force either protocol using the
-rtsp_transport flag. This flag must be placed
before the input file parameter (-i).
Force TCP
TCP is recommended for unstable networks or when streaming over the internet, as it guarantees packet delivery and prevents visual artifacts caused by packet loss.
ffmpeg -rtsp_transport tcp -i rtsp://your_stream_url -c copy output.mp4Force UDP
UDP is ideal for local networks where low latency is the priority and occasional frame drops are acceptable.
ffmpeg -rtsp_transport udp -i rtsp://your_stream_url -c copy output.mp4Configuring the Connection Timeout
When an RTSP stream disconnects or becomes unreachable, FFmpeg can
hang indefinitely while waiting for a response. To prevent this, you can
set a socket timeout using the -stimeout flag.
The -stimeout option accepts values in
microseconds (\(1 \text{
second} = 1,000,000 \text{ microseconds}\)). Like the transport
flag, this must be placed before the input URL.
To set a timeout of 5 seconds (5,000,000 microseconds):
ffmpeg -stimeout 5000000 -i rtsp://your_stream_url -c copy output.mp4Combining Timeout and Transport Protocol
For a robust and production-ready RTSP streaming setup, it is best practice to combine both flags.
The following command forces a reliable TCP connection and sets a strict 5-second connection timeout:
ffmpeg -rtsp_transport tcp -stimeout 5000000 -i rtsp://your_stream_url -c copy output.mp4