Limit HLS Playlist Segments in FFmpeg
This guide explains how to configure the sliding window size in FFmpeg to restrict the number of media segments kept in an HTTP Live Streaming (HLS) playlist. You will learn the specific FFmpeg flags required to manage playlist length, control disk space usage, and ensure efficient live streaming delivery.
To limit the number of segments in an HLS playlist, you must use the
-hls_list_size option. This parameter defines the maximum
number of segment files listed in the .m3u8 index file at
any given time.
The Basic Command
Here is a standard FFmpeg command to create a sliding window of 5 segments:
ffmpeg -i input.mp4 -c:v libx264 -c:a aac -f hls -hls_time 4 -hls_list_size 5 -hls_flags delete_segments output.m3u8Parameter Breakdown
-f hls: Specifies the output format as HLS.-hls_time 4: Sets the target segment duration to 4 seconds.-hls_list_size 5: Sets the sliding window size. The playlist (output.m3u8) will only contain a maximum of 5 segments. As new segments are created, the oldest ones are removed from the playlist.-hls_flags delete_segments: This is a crucial flag for live streaming. By default, FFmpeg removes segments from the playlist file but keeps the actual.tsvideo files on your storage. Addingdelete_segmentsforces FFmpeg to delete the physical segment files from your disk once they drop off the playlist, preventing your storage from filling up.
Understanding the Default Behavior
If you do not specify -hls_list_size, or if you set it
to 0, FFmpeg will default to keeping all segments in the
playlist. This behavior is ideal for Video on Demand (VOD) where viewers
need access to the entire video from the beginning, but it is highly
inefficient for live streams where only the most recent couple of
minutes are required.