Loop a Single Video to RTMP with FFmpeg
This article provides a straightforward guide on how to continuously loop a single video file and stream it to an RTMP endpoint using FFmpeg on a Linux system. You will learn the exact command-line syntax required, the explanation behind each parameter, and how to handle potential issues like audio-video desynchronization.
To loop a single video indefinitely and stream it to an RTMP
destination (such as YouTube, Twitch, or a private media server), you
need to use FFmpeg’s -stream_loop input option. This flag
tells FFmpeg to loop the source file before it processes the stream for
output.
The Standard FFmpeg Command
Open your Linux terminal and use the following command structure to start the continuous stream:
ffmpeg -stream_loop -1 -re -i input.mp4 -c:v libx264 -preset veryfast -b:v 3000k -maxrate 3000k -bufsize 6000k -pix_fmt yuv420p -g 60 -c:a aac -b:a 128k -f flv rtmp://your-endpoint-url/stream-keyParameter Breakdown
Understanding what each flag does will help you modify the command to fit your specific bandwidth and quality requirements:
-stream_loop -1: This must be placed before the input file (-i). The value-1instructs FFmpeg to loop the video infinitely.-re: This forces FFmpeg to read the input file at its native frame rate (real-time). Without this, FFmpeg will read and encode the video as fast as your CPU allows, which will overwhelm the RTMP server and cause the stream to fail.-i input.mp4: Specifies the path to your source video file.-c:v libx264: Encodes the video to H.264 format, which is the standard requirement for almost all RTMP ingestion servers.-preset veryfast: Balances CPU usage and video quality. If your server has a weaker CPU, you can change this toultrafast.-b:v 3000k -maxrate 3000k -bufsize 6000k: Controls the video bitrate. This example sets a target and maximum bitrate of 3000 Kbps with a 6000 KB buffer to maintain a stable stream.-pix_fmt yuv420p: Ensures maximum compatibility with web players by using the YUV 4:2:0 pixel format.-g 60: Sets the GOP (Group of Pictures) size, also known as the keyframe interval. Setting this to 60 for a 30fps video ensures a keyframe is sent every 2 seconds, which is a strict requirement for platforms like YouTube and Twitch.-c:a aac -b:a 128k: Encodes the audio to AAC format at a bitrate of 128 Kbps.-f flv: Specifies the container format. RTMP streaming requires the Flash Video (FLV) muxer wrapper.
Stream Optimization and Troubleshooting
When looping a single file continuously, you may encounter timestamp
issues at the loop point where the video ends and starts over. If your
stream stutters or drops connection after the first playback cycle, add
the -async 1 flag or use the
-use_wallclock_as_timestamps 1 option. This forces FFmpeg
to generate fresh, linear timestamps for the RTMP server, preventing
playback synchronization errors.