Configure SDP Output in FFmpeg RTSP Stream
When streaming video or audio over RTP/RTSP using FFmpeg, the Session Description Protocol (SDP) file is essential for receivers to understand the media initialization parameters, codecs, and transport ports. This article explains how to configure and output an SDP file using FFmpeg, covering command-line options, direct file redirection, and transport protocol configurations to ensure compatibility with your media player or streaming server.
Method 1:
Exporting SDP using the -sdp_file Flag
The most direct way to configure and output an SDP file during an RTP
stream (which is the underlying transport for RTSP) is by using the
-sdp_file option. This tells FFmpeg to write the SDP data
directly to a specified path on your disk while the stream is
active.
Run the following command to encode an input file and output both the RTP stream and the corresponding SDP file:
ffmpeg -re -i input.mp4 -c:v libx264 -an -f rtp rtp://127.0.0.1:5004 -sdp_file stream.sdpIn this command: * -re reads the input at native frame
rate. * -f rtp specifies the RTP muxer. *
rtp://127.0.0.1:5004 is the destination IP and port. *
-sdp_file stream.sdp generates the SDP configuration file
named stream.sdp.
Method 2: Redirecting Standard Output (stdout)
If you are using an older version of FFmpeg that does not support the
-sdp_file option, or if you want to pipe the SDP data into
another process, you can redirect standard output.
By default, when streaming over RTP without specifying an output file name, FFmpeg prints the SDP definition to the console. You can redirect this output to a file:
ffmpeg -re -i input.mp4 -c:v libx264 -an -f rtp rtp://127.0.0.1:5004 > stream.sdpConfiguring SDP Transport and Protocol Parameters
The SDP file is generated dynamically based on the arguments you pass to the FFmpeg command. You can customize the SDP output by adjusting the following streaming parameters:
1. Setting the Protocol (TCP vs. UDP)
By default, RTP streams use UDP. If you are publishing to an RTSP
server and need to force TCP interleaved mode (which embeds the RTP/SDP
data within the RTSP control connection), use the
-rtsp_transport flag:
ffmpeg -re -i input.mp4 -c:v libx264 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live/stream2. Configuring Audio and Video Payloads
If your stream contains both audio and video, the SDP file must define both media streams. FFmpeg will automatically generate multi-stream SDP files if you include both codecs in the command:
ffmpeg -re -i input.mp4 -c:v libx264 -c:a aac -f rtp rtp://127.0.0.1:5004 -sdp_file multi_stream.sdpThe resulting multi_stream.sdp file will contain two
separate m= blocks (one for video, one for audio) with
their respective payload types, sampling rates, and port
configurations.