The UDP port closed error in FFmpeg typically occurs because the default transport protocol for RTSP streams is UDP, which is connectionless and often blocked by firewalls or NAT devices. To resolve this, you must explicitly instruct FFmpeg to use TCP instead of UDP by adding the
-rtsp_transport tcp flag to your input command. This ensures a reliable, stateful connection that can traverse most network configurations without dropping packets or failing to establish the stream handshake.
Understanding the Root Cause
RTSP (Real Time Streaming Protocol) supports multiple transport mechanisms, primarily UDP and TCP. When you do not specify a transport method, FFmpeg defaults to UDP for performance reasons. However, UDP does not guarantee packet delivery. If a firewall, router, or ISP blocks the specific ephemeral ports used by the UDP session, the stream fails immediately with a "port closed" or similar connectivity error. This is particularly common when streaming from IP cameras located behind strict network security policies or when attempting to relay streams through web servers that only allow standard HTTP/HTTPS traffic.
Using TCP resolves this because it operates over port 554 (the standard RTSP port) and behaves like a standard HTTP connection. It establishes a handshake, maintains state, and retransmits lost packets. While UDP is faster, TCP is significantly more robust for internet-based streaming where packet loss and network filtering are prevalent. By forcing TCP, you eliminate the ambiguity that leads to the port closed error.
Correcting the Protocol Syntax
A common misconception is that one should change the URL scheme to
rtspt:// to force TCP. This is incorrect. FFmpeg does not recognize
rtspt:// as a valid input protocol. Attempting to use this syntax will cause an immediate parsing error before any network connection is attempted. The correct approach is to keep the standard
rtsp:// URL and pass the transport preference via command-line flags. This distinction is critical; the URL scheme defines the service, while the flag defines the transport layer behavior.
Implementing the Solution
To fix the issue, you need to modify your FFmpeg command line to include the transport flag. Below is a basic example of how to structure the command for converting an RTSP feed into HLS segments.
ffmpeg -rtsp_transport tcp -i rtsp://user:password@camera-ip/live -c:v libx264 -preset veryfast -b:v 1000k -f hls output.m3u8
In this command,
-rtsp_transport tcp is placed before the
-i (input) flag. This tells FFmpeg to negotiate the RTSP session using TCP. The rest of the command handles the transcoding and packaging. The video codec is set to H.264 (
libx264), which is widely supported by web browsers. The preset
veryfast balances encoding speed and quality, while the bitrate is capped at 1000k to ensure smooth playback on varying connections. The output format is set to HLS (
-f hls), which generates the necessary
.ts segment files and the master playlist
output.m3u8.
Adjusting Buffer and Timeout Settings
Sometimes, even with TCP enabled, initial connection timeouts can occur if the camera takes too long to respond. You can mitigate this by increasing the timeout values. Add
-stimeout 5000000 to wait up to five seconds for a response. Additionally, using
-reorder_queue_size 0 can help if you encounter audio-video desync issues during the initial handshake, though this is less common with TCP.
If you are experiencing intermittent drops after the stream has started, consider adjusting the buffer size. Adding
-bufsize 1000k helps regulate the data flow. For more granular control over segment duration, refer to our guide on
Exact HLS Segment Duration with FFmpeg: An Efficient Alternative. Proper segment sizing can reduce the likelihood of buffering issues that might be mistaken for transport errors.
Verifying the Stream
After applying the TCP flag, verify the connection by checking FFmpeg's console output. Look for lines indicating the RTSP session establishment. You should see messages confirming the transport mode. If the stream starts successfully, you will see continuous logging of encoded frames being written to the HLS directory.
If the error persists, check if the camera actually supports TCP. Most modern IP cameras do, but older or proprietary models may strictly require UDP. In such cases, you may need to adjust the camera's network settings to allow wider port ranges or configure your firewall to permit UDP traffic on the specific ports used by the camera. For broader troubleshooting on RTSP connectivity, see our article on
Need Help Streaming RTSP Camera IP using ffmpeg Library.
Handling Authentication Issues
When switching transports, authentication challenges might behave differently. Ensure that your credentials are correctly formatted in the URL. If the camera uses digest authentication, FFmpeg usually handles this transparently with TCP. However, if you encounter 401 Unauthorized errors, verify that the username and password do not contain special characters that need URL encoding. Special characters like
@ or
: in passwords must be percent-encoded to prevent parsing errors.
For issues related to token expiration or authentication tokens in the final HLS stream, consult
FFmpeg Fails to Download M3U8/HLS Stream. While this addresses the output side, ensuring stable input transport is the first step in resolving complex streaming pipelines.
Frequently Asked Questions
Why does my stream drop after a few minutes with TCP?
TCP streams can drop if the server or camera sends malformed packets that confuse the parser. Check your FFmpeg logs for "invalid data" warnings. Increasing the
-max_muxing_queue_size parameter can sometimes alleviate buffer overflows that cause mid-stream drops.
Can I use UDP with a firewall rule instead of TCP?
Yes, you can open the specific UDP ports used by the RTSP session. However, since these ports are ephemeral and change per session, configuring static firewall rules for UDP is difficult. TCP is generally preferred for simplicity and reliability in dynamic network environments.
What if the camera does not support TCP transport?
If the camera rejects TCP connections, you must use UDP. In this case, ensure your network infrastructure allows high-numbered ephemeral ports. You may also need to use a proxy or gateway that converts UDP to TCP for the FFmpeg instance.
Does using TCP increase latency compared to UDP?
TCP introduces slight latency due to the handshake and retransmission overhead. For real-time monitoring, this delay is usually negligible (often under one second). However, for ultra-low-latency applications, UDP might still be required despite its reliability risks.
How do I debug if the TCP connection is timing out?
Use the
-v verbose flag in FFmpeg to get detailed connection logs. Look for RTSP negotiation steps. If the connection times out, check if the camera's IP address is reachable via ping and if port 554 is open using tools like
telnet or
nc.