RTSP Authentication with Custom Headers in FFmpeg

This article provides a quick guide on how to configure RTSP stream authentication in FFmpeg using custom headers. While FFmpeg natively supports standard basic and digest authentication through the connection URL, passing custom headers for token-based RTSP authentication requires specific workarounds, such as header injection via the User-Agent parameter or utilizing RTSP-over-HTTP transport options.


Method 1: Header Injection via the User-Agent Option

FFmpeg’s native RTSP demuxer does not feature a dedicated -headers command-line option for standard UDP/TCP transport. However, you can inject custom authentication headers (such as bearer tokens or API keys) by exploiting the -user_agent field. By inserting a Carriage Return Line Feed (\r\n) into the User-Agent string, you can force FFmpeg to append your custom header to the RTSP request.

In a Bash-compliant terminal, use the following syntax:

ffmpeg -user_agent "FFmpeg"$'\r\n'"Authorization: Bearer YOUR_AUTH_TOKEN" -i rtsp://your_stream_url/path -c copy output.mp4

How it works: * -user_agent: Sets the user agent string. * $'\r\n': Evaluates to a network-standard newline in Bash, terminating the User-Agent header line. * Authorization: Bearer YOUR_AUTH_TOKEN: Injects the custom authentication header into the RTSP handshake request.

Note: If you are using Windows Command Prompt (cmd.exe) or PowerShell, the syntax for escaping and inserting newlines will vary. For example, in PowerShell, use `r`n instead of $'\r\n'.


Method 2: RTSP over HTTP Tunneling

If your RTSP server supports tunneling over HTTP (often used to bypass firewalls on port 80 or 443), you can use FFmpeg’s native HTTP header support. When transport is forced over HTTP, FFmpeg respects the -headers parameter.

Run the following command to pass custom headers over an HTTP-tunneled RTSP stream:

ffmpeg -rtsp_transport http -headers "Authorization: Bearer YOUR_AUTH_TOKEN"$'\r\n' -i rtsp://your_stream_url/path -c copy output.mp4

Key parameters: * -rtsp_transport http: Forces FFmpeg to tunnel the RTSP protocol via HTTP. * -headers: Specifies the exact HTTP headers to send during the handshake. Ensure the string ends with a trailing $'\r\n' to properly format the HTTP request.


Method 3: Standard URL Authentication (Alternative)

If custom headers are not strictly required by your server’s API and standard authentication is supported, you should embed the credentials directly into the RTSP URL. This is the most stable and natively supported method in FFmpeg:

ffmpeg -i rtsp://username:password@your_stream_url:port/path -c copy output.mp4