Create HLS Playlists and Segments Using FFmpeg
This guide provides a straightforward tutorial on how to convert a
live video feed into HTTP Live Streaming (HLS) format using the FFmpeg
command-line tool. You will learn how to write the correct FFmpeg
command to slice a live stream into small video segments (typically
.ts files) and generate the corresponding
.m3u8 playlist file required for modern web and mobile
players.
The Basic FFmpeg Command for Live HLS
To convert a live stream (such as an RTMP input, RTSP feed, or local webcam) into an HLS stream, run the following FFmpeg command:
ffmpeg -i rtmp://your-live-source/stream -c:v libx264 -c:a aac -f hls -hls_time 4 -hls_list_size 5 -hls_flags delete_segments output.m3u8Parameter Breakdown
Understanding each option in the command allows you to customize the output to fit your specific live-streaming requirements:
-i rtmp://your-live-source/stream: Specifies the input source. This can be an RTMP stream, an RTSP camera stream, an HTTP stream, or a local file/device.-c:v libx264: Encodes the video to H.264, which is the most widely compatible video codec for HLS playback.-c:a aac: Encodes the audio to AAC, the standard audio format for HLS.-f hls: Forces FFmpeg to use the HLS multiplexer, instructing it to generate the.m3u8index file and.tsdata segments.-hls_time 4: Sets the target segment duration in seconds. In this example, FFmpeg will attempt to split the video into 4-second segments. Shorter segment times reduce latency but increase HTTP request overhead.-hls_list_size 5: Defines the maximum number of segments kept in the active.m3u8playlist. For live streams, a rolling window of 5 segments is typical. If you set this to0, the playlist will grow indefinitely (ideal for Video-on-Demand, but not for continuous live streaming).-hls_flags delete_segments: Tells FFmpeg to automatically delete older segment files from the storage disk once they fall off the rolling playlist window. This prevents your server storage from filling up during a continuous live broadcast.output.m3u8: The name of the master playlist file. FFmpeg will automatically name the segments sequentially (e.g.,output0.ts,output1.ts, etc.) in the same directory.
Optimizing Segment Cuts with Keyframes
For HLS segmenting to work smoothly without visual stuttering, FFmpeg
must split segments at video keyframes (I-frames). You can force
keyframe intervals to match your desired segment duration using the
-g (group of pictures) flag.
If your stream runs at 30 frames per second (fps) and you want 4-second segments, set the keyframe interval to 120 (30 fps x 4 seconds):
ffmpeg -i rtmp://your-live-source/stream -c:v libx264 -g 120 -keyint_min 120 -sc_threshold 0 -c:a aac -f hls -hls_time 4 -hls_list_size 5 -hls_flags delete_segments output.m3u8Using -sc_threshold 0 prevents FFmpeg from inserting
extra keyframes during scene changes, ensuring strict 4-second
boundaries for every segment.