How to Parse M3U8 Files
M3U8 File Parsing Steps
Parsing M3U8 files is the first step in playing HLS streams. The basic workflow involves fetching the M3U8 file content, determining whether it's a Master Playlist or Media Playlist, and extracting segment information for playback.
1. Fetch the M3U8 File
Fetch the M3U8 file content via HTTP request. M3U8 files are plain text files that can be read directly. In browser environments, use fetch API or XMLHttpRequest; in Node.js, use axios or built-in http module.
When fetching M3U8 files, note: use correct HTTP method (usually GET), handle CORS issues, and handle redirects (301/302) as files may be hosted on CDN.
2. Determine File Type
Check if the file contains the #EXT-X-STREAM-INF tag. If yes, it's a Master Playlist requiring bitrate selection; otherwise, it's a Media Playlist ready for playback.
3. Parse Master Playlist
Extract URLs and attributes for each bitrate stream. Each #EXT-X-STREAM-INF tag is followed by a URL pointing to the corresponding Media Playlist. Attributes include BANDWIDTH, RESOLUTION, CODECS, AUDIO, etc.
4. Parse Media Playlist
Extract key information:
- Segment URL list: Each #EXTINF tag followed by a URL to the TS segment file.
- Segment duration: From #EXTINF tag, format: #EXTINF:
, . - Maximum segment duration: From #EXT-X-TARGETDURATION tag.
- Media sequence number: From #EXT-X-MEDIA-SEQUENCE tag.
- Whether it's live: Missing #EXT-X-ENDLIST indicates live stream.
5. Parsing Tools
Common M3U8 parsing tools:
- hls.js - JavaScript library for browser-side parsing and playback.
- video.js - Universal video player framework with HLS support.
- ffprobe - FFmpeg tool for command-line parsing.
- m3u8-parser - Dedicated M3U8 parsing library.