How to Stream RTP with Custom Ports in FFmpeg

Streaming media over RTP (Real-time Transport Protocol) using FFmpeg allows for low-latency audio and video transmission across a network. This guide provides a straightforward walkthrough on how to configure FFmpeg to stream over RTP while specifying custom network ports for both payload and control data. You will learn the exact command syntax for single and multi-stream setups, how to define ports for audio and video separately, and how to access the stream on the receiving end.

Basic RTP Stream (Single Stream)

If you are streaming only one stream (such as video-only or audio-only), you can direct FFmpeg to send the payload to a specific IP address and custom port using the following syntax:

ffmpeg -re -i input.mp4 -c:v libx264 -an -f rtp rtp://192.168.1.50:6000

In this command: * -re reads the input file at its native frame rate (essential for live streaming). * -an disables audio, leaving only the video stream. * -f rtp forces the output format to RTP. * rtp://192.168.1.50:6000 sends the RTP stream to the destination IP 192.168.1.50 on custom port 6000.

Streaming Audio and Video to Custom Ports

When streaming both audio and video, RTP requires separate ports for each media type. By default, FFmpeg will assign the specified port to the first stream and automatically increment the port number (usually by 2) for the second stream.

To gain full control over the exact ports used for both audio and video, you can map the streams to separate RTP destinations in a single command:

ffmpeg -re -i input.mp4 \
  -map 0:v -c:v libx264 -f rtp rtp://192.168.1.50:5000 \
  -map 0:a -c:a aac -f rtp rtp://192.168.1.50:6000

In this command: * -map 0:v selects the video stream and outputs it to port 5000. * -map 0:a selects the audio stream and outputs it to port 6000.

Generating and Using an SDP File

RTP streams require a Session Description Protocol (SDP) file for the receiver to understand the stream codecs, IP addresses, and port mappings. FFmpeg can automatically output this information to a file during the streaming process.

To generate an SDP file, redirect the output of your FFmpeg command to a .sdp file:

ffmpeg -re -i input.mp4 -c:v libx264 -c:a aac -f rtp rtp://192.168.1.50:5004 > stream.sdp

In this setup, FFmpeg will use port 5004 for the video stream and automatically assign port 5006 for the audio stream. The resulting stream.sdp file will contain the exact configuration details.

Receiving the Stream

To play the stream on the receiving machine, copy the generated stream.sdp file to the player’s system. You can then open the stream using FFplay or VLC:

Using FFplay:

ffplay -protocol_whitelist file,rtp,udp stream.sdp

Using VLC: Open VLC, navigate to Media > Open File, and select the stream.sdp file.