HTTP Live Streaming (HLS) is Apple's streaming protocol, now widely supported across all browsers and devices. This guide shows you how to create HLS streams with FFmpeg.
What is HLS?
HLS breaks video into small segments (typically 6-10 seconds) and creates a playlist file (.m3u8) that references them. Players download segments progressively, enabling adaptive bitrate streaming.
Basic HLS Encoding
ffmpeg -i input.mp4 -c:v libx264 -crf 21 -preset fast -c:a aac -b:a 128k -hls_time 6 -hls_list_size 0 -hls_segment_filename "segment_%03d.ts" playlist.m3u8
Key HLS Options
- -hls_time 6: Segment duration in seconds
- -hls_list_size 0: Keep all segments in playlist (for VOD)
- -hls_segment_filename: Pattern for segment files
Multi-Bitrate HLS (Adaptive Streaming)
Create multiple quality levels for adaptive playback:
# 1080p ffmpeg -i input.mp4 -c:v libx264 -b:v 5000k -s 1920x1080 -c:a aac -b:a 192k -hls_time 6 -hls_list_size 0 -hls_segment_filename "1080p_%03d.ts" 1080p.m3u8 # 720p ffmpeg -i input.mp4 -c:v libx264 -b:v 2500k -s 1280x720 -c:a aac -b:a 128k -hls_time 6 -hls_list_size 0 -hls_segment_filename "720p_%03d.ts" 720p.m3u8 # 480p ffmpeg -i input.mp4 -c:v libx264 -b:v 1000k -s 854x480 -c:a aac -b:a 96k -hls_time 6 -hls_list_size 0 -hls_segment_filename "480p_%03d.ts" 480p.m3u8
Master Playlist
Create a master playlist that references all quality levels:
#EXTM3U #EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080 1080p.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=2500000,RESOLUTION=1280x720 720p.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=854x480 480p.m3u8
Save this as master.m3u8
Serving HLS
Configure Nginx to serve HLS with proper MIME types:
location /hls/ {
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
add_header Cache-Control no-cache;
}
Tip: For production, consider using a CDN to distribute HLS segments globally.