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.m3u8

Parameter Breakdown

Understanding each option in the command allows you to customize the output to fit your specific live-streaming requirements:

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.m3u8

Using -sc_threshold 0 prevents FFmpeg from inserting extra keyframes during scene changes, ensuring strict 4-second boundaries for every segment.