How to Segment Video for HLS Streaming
Learn how to segment video files into HLS format for streaming. FFmpeg commands, segmenter tools, and best practices for HLS packaging.
Using FFmpeg as an HLS Segmenter
FFmpeg is the most versatile tool for creating HLS segments. Here's the basic command:
ffmpeg -i input.mp4 -c:v libx264 -crf 23 -c:a aac -b:a 128k -f hls -hls_time 6 -hls_playlist_type vod playlist.m3u8
This creates a VOD HLS stream with 6-second segments, H.264 video, and AAC audio.
Creating Multi-Bitrate HLS
For adaptive streaming, create multiple variants:
ffmpeg -i input.mp4 -filter_complex "
[0:v]split=3[v1][v2][v3];
[v1]scale=-2:360[v1out];
[v2]scale=-2:720[v2out];
[v3]scale=-2:1080[v3out]
"
-map [v1out] -map [v2out] -map [v3out] -map 0:a
-c:v libx264 -crf 23 -c:a aac
-f hls -var_stream_map "v:0,a:0 v:1,a:1 v:2,a:2"
-master_pl_name master.m3u8
-hls_time 6 -hls_playlist_type vod
"variant_%v.m3u8"
Segment Duration Considerations
Choosing the right segment duration:
- 2-4 seconds: Lower latency, more files, higher server load. Good for live streams.
- 6 seconds: Industry standard. Good balance for most use cases.
- 10 seconds: Better compression, fewer files, higher latency. Best for VOD.
Keyframe Alignment
For smooth quality switching, all variants must have aligned keyframes (GOP size equals segment duration):
ffmpeg -i input.mp4 -c:v libx264 -g 60 -keyint_min 60 -sc_threshold 0 ...
With -g 60 and a 30fps source, keyframes occur every 2 seconds. Adjust based on your segment duration.
Related Articles
M3U8 Streaming Architecture: From Server to Browser
Understand the complete M3U8 streaming architecture. How video moves from the encoder through CDN to the viewer's browser.
How HLS Streaming Works: Protocol Explained in Detail
Deep dive into the HLS protocol. Understand master playlists, media segments, adaptive bitrate, and the complete HLS delivery pipeline.
Build Your Own M3U8 Player with JavaScript
Step-by-step guide to building a custom M3U8/HLS video player using hls.js. Full source code and implementation walkthrough.