M3U8 Protocol Principles
HLS Protocol Overview
HTTP Live Streaming (HLS) is an HTTP-based media streaming protocol proposed by Apple. It divides the entire stream into small HTTP-based files for download, downloading only a portion at a time. This design enables HLS to adapt to various network environments, providing smooth playback from high-speed WiFi to mobile cellular networks.
The core idea of HLS is to segment video content into a series of small file segments, each containing a few seconds of video. Players request and play these segments sequentially for streaming playback. Since each segment is an independent HTTP request, HLS can leverage existing HTTP infrastructure including CDNs, proxy servers, and caching systems.
M3U8 File Structure
M3U8 files consist of Tags and URLs. Tags start with # and describe playlist properties and segment information:
- #EXTM3U - M3U file header, must appear on the first line.
- #EXT-X-VERSION - HLS version number.
- #EXT-X-TARGETDURATION - Maximum segment duration in seconds.
- #EXT-X-MEDIA-SEQUENCE - Sequence number of the first segment.
- #EXTINF - Segment duration info, format: #EXTINF:
, . - #EXT-X-STREAM-INF - Multi-bitrate stream attributes in Master Playlist.
- #EXT-X-ENDLIST - Playlist end marker for VOD streams.
Multi-Bitrate Mechanism
The Master Playlist contains URLs for multiple Media Playlists, each corresponding to a bitrate. The #EXT-X-STREAM-INF tag describes stream attributes including BANDWIDTH, RESOLUTION, and CODECS. Players select appropriate bitrates based on network bandwidth and can seamlessly switch between bitrates at segment boundaries.
Segment Mechanism
Video is divided into 2-10 second TS (Transport Stream) segments. Each segment is independently decodable, allowing playback to start from any segment. Shorter segments reduce latency but increase HTTP requests; longer segments improve caching efficiency but increase latency. 6 seconds is a commonly used segment duration.
Live Update Mechanism
For live streams, M3U8 playlists don't include #EXT-X-ENDLIST. Players periodically refresh playlists for new segment addresses. Servers maintain a sliding window, keeping only recent N segments in the playlist.