Stream Local Video to RTMP with FFmpeg on Linux

Streaming a local video file to an RTMP server on Linux is a highly efficient way to broadcast pre-recorded content to platforms like YouTube, Twitch, or a self-hosted server. By utilizing FFmpeg, a powerful command-line tool, you can transcode, scale, and push your media smoothly without the overhead of a graphical user interface. This guide will walk you through the precise command-line syntax required, explain how to optimize your encoding settings for stable streaming, and provide troubleshooting steps for common playback issues.

Prerequisite: Installing FFmpeg on Linux

Before streaming, ensure you have FFmpeg installed with the necessary encoders (libx264 for video and aac for audio). You can install it via your distribution’s package manager:

Verify your installation and available encoders by running ffmpeg -encoders in your terminal.

The Basic RTMP Streaming Command

To stream a local MP4 file to an RTMP destination without re-encoding (which saves CPU power but requires the file to already be in a web-compatible format), use the following syntax:

ffmpeg -re -i input.mp4 -c copy -f flv rtmp://your-server-url/live/stream-key

Optimizing and Re-encoding for Live Streaming

If your source video is not optimized for streaming, or if you have a strict upload bandwidth limit, you should re-encode the video on the fly. The command below transcodes the video to H.264 and audio to AAC, applies a constant bitrate, and sets a strict keyframe interval, which is mandatory for most RTMP servers:

ffmpeg -re -i input.mp4 -c:v libx264 -pix_fmt yuv420p -preset veryfast -b:v 3000k -maxrate 3000k -bufsize 6000k -g 60 -c:a aac -b:a 128k -f flv rtmp://your-server-url/live/stream-key

Breaking Down the Command Arguments

Understanding each flag allows you to tweak the command to match your network speed and hardware capabilities: