How to Loop Video to RTMP with FFmpeg
This article explains how to use FFmpeg to stream a single video file in an infinite loop to an RTMP destination, such as YouTube, Twitch, or a custom media server. You will learn the exact FFmpeg command required for this setup, the purpose of each command parameter, and best practices for maintaining a stable, continuous live stream.
The Command
To stream a video file in an infinite loop, run the following FFmpeg
command in your terminal. Replace input.mp4 with your
source file path and the RTMP URL at the end with your actual ingest
server and stream key:
ffmpeg -re -stream_loop -1 -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-rtmp-server/live/stream_keyParameter Breakdown
Understanding how each flag works is critical to ensuring your stream does not drop or lag:
-re: Instructs FFmpeg to read the input file at its native frame rate. Without this flag, FFmpeg would read and upload the file as fast as possible, crashing the live stream. This must be placed before the input file.-stream_loop -1: Defines the loop behavior. Setting this to-1forces FFmpeg to loop the input file infinitely. This parameter must also be placed before the input file (-i).-i input.mp4: Specifies the path to your source video file.-c:v libx264: Encodes the video to the H.264 format, which is the standard codec required by almost all RTMP ingestion platforms.-preset veryfast: Balances CPU usage and video quality. A faster preset ensures the encoder can keep up in real time without dropping frames.-b:v 3000k -maxrate 3000k -bufsize 6000k: Configures a stable Constant Bitrate (CBR). Standardizing the bitrate prevents buffering spikes at the transition point when the video loops.-pix_fmt yuv420p: Sets the pixel format to YUV 4:2:0, ensuring maximum player compatibility across web browsers and mobile devices.-g 60: Sets the keyframe interval (GOP size). For a 30fps video, a GOP of 60 ensures a keyframe is sent every 2 seconds, which is standard for platforms like Twitch and YouTube.-c:a aac -b:a 128k: Encodes the audio track to AAC at a stable bitrate of 128kbps.-f flv: Forces the output format to FLV, the required wrapper format for RTMP streaming.
Why Re-encoding is Recommended
While copying the codecs directly using
-c:v copy -c:a copy uses significantly less CPU, it often
causes timestamp desynchronization at the loop boundary. When the video
restarts, the timecodes reset, which can cause RTMP servers to reject
the stream or freeze. Re-encoding the video using libx264
and aac standardizes the timestamps and guarantees a
seamless loop transition.