Sub topic 8
Segmenting and packaging with HLS and DASH
This chapter assumes you know what a codec, a container and a bitrate are, and that you have seen how a transcoding pipeline produces several renditions of one video. You should also be comfortable with HTTP caching and object storage. Here we turn those renditions into something a player can fetch over plain HTTP and switch between while playing.
Why video is cut into segments
A transcoded rendition is one long file. Serving it as a single object has two problems. A player cannot change quality in the middle of the file, and a CDN has to cache or re-fetch a large object even when a viewer only watches the first minute.
Segmenting solves both. The packager cuts each rendition into short pieces, usually 2 to 10 seconds long. A small text file called a manifest lists the pieces in order. The player downloads the manifest, then requests segments one at a time with ordinary HTTP GET requests. Because every rendition is cut at the same time boundaries, the player can request segment 7 from the 360p rendition and segment 8 from the 720p rendition without a visible break.
This design keeps the servers simple. Segments are static files. Any HTTP cache or CDN can store them, and the player makes all quality decisions.
HLS and DASH at a glance
Two protocols dominate.
- HLS (HTTP Live Streaming) was created by Apple. Its manifests are text files in the
.m3u8format. It is required on iOS and Safari, and it is supported almost everywhere else. - DASH (Dynamic Adaptive Streaming over HTTP) is an international standard. Its manifest is an XML file called an MPD (Media Presentation Description). It is common on Android, smart TVs and web players built on Media Source Extensions.
| Aspect | HLS | DASH |
|---|---|---|
| Manifest | `.m3u8` text playlists | `.mpd` XML document |
| Manifest structure | Master playlist plus one media playlist per rendition | One MPD describing all renditions |
| Segment container | MPEG-TS or fragmented MP4 (fMP4) | Usually fMP4 |
| Native support | Apple devices | Most non-Apple devices through players |
| DRM | FairPlay, plus others with fMP4 | Widevine, PlayReady |
The container is the part that matters most for your storage bill. If you produce MPEG-TS for HLS and fMP4 for DASH, you store every rendition twice. If you package both protocols as fMP4, the media segments can be shared, and only the manifests differ. This approach is often called CMAF (Common Media Application Format). It is the usual choice for new platforms.
Segment boundaries and keyframes
A video stream is made of frames. A keyframe (also called an IDR frame) can be decoded on its own. Other frames depend on earlier frames. A player can only start decoding at a keyframe, so every segment must begin with one.
This is why the transcoding command in the earlier chapter fixed the keyframe interval:
ffmpeg -i input.mp4 \
-vf scale=-2:720 \
-c:v libx264 -preset medium -b:v 2800k -maxrate 3000k -bufsize 6000k \
-g 48 -keyint_min 48 -sc_threshold 0 \
-c:a aac -b:a 128k \
-f hls -hls_time 4 -hls_playlist_type vod \
-hls_segment_filename "720p/seg_%04d.ts" \
720p/index.m3u8The options that control segmentation are these:
-g 48sets a keyframe every 48 frames. At 24 frames per second that is every 2 seconds.-keyint_min 48stops the encoder from inserting keyframes more often than that.-sc_threshold 0turns off scene-change detection. Without it, the encoder adds extra keyframes at cuts, and the keyframes stop lining up with segment boundaries.-hls_time 4asks for 4-second segments. The segmenter can only cut at keyframes, so 4 seconds works because it is a multiple of the 2-second keyframe interval.-hls_playlist_type vodwrites a complete playlist that ends with an end marker.
Every rendition must use the same keyframe positions. If the 360p rendition has keyframes at 0, 2, 4 seconds and the 720p rendition has them at 0, 2.5, 5 seconds, a switch between them lands mid-segment and the player has to discard or re-download data. Encode all renditions from the same source with the same frame rate and the same -g value in seconds.
The HLS manifests
HLS uses two levels of playlist. The master playlist lists the renditions:
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360,CODECS="avc1.4d401e,mp4a.40.2"
360p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720,CODECS="avc1.4d401f,mp4a.40.2"
720p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=6000000,RESOLUTION=1920x1080,CODECS="avc1.640028,mp4a.40.2"
1080p/index.m3u8Each EXT-X-STREAM-INF line describes the rendition on the next line. BANDWIDTH is the peak bitrate in bits per second, RESOLUTION is the frame size, and CODECS lets the player skip renditions its device cannot decode. A wrong CODECS string is a common bug. A player may refuse to start, or it may pick a rendition it then fails to decode.
Each rendition then has its own media playlist. A short example for the 720p rendition:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXTINF:4.000,
seg_0000.ts
#EXTINF:4.000,
seg_0001.ts
#EXTINF:3.500,
seg_0002.ts
#EXT-X-ENDLISTEXT-X-TARGETDURATION must be at least as long as the longest segment, rounded up to a whole number. EXTINF gives each segment's real duration. EXT-X-ENDLIST tells the player that the stream is complete, which is what separates video on demand from live.
DASH manifests and segment addressing
A DASH MPD groups content into periods, adaptation sets and representations. An adaptation set holds interchangeable versions of one kind of media, such as video. A representation is one rendition within it. The MPD also says how to build segment URLs. Common methods are:
SegmentTemplatewith$Number$, where the player computesseg_1.m4s,seg_2.m4sand so on from a pattern.SegmentTemplatewithSegmentTimeline, which lists exact durations and allows uneven segments.SegmentBase, where a single file per representation is read with HTTP byte-range requests using an index.
The template approach keeps the MPD small. A two-hour film does not need a line per segment.
Packaging in practice
Many teams use a tool such as Shaka Packager or Bento4 instead of writing manifests by hand. The packager takes the encoded renditions and writes segments and manifests. A typical output layout looks like this:
video-123/
master.m3u8
manifest.mpd
360p/index.m3u8
360p/init.mp4
360p/seg_0001.m4s
720p/index.m3u8
720p/init.mp4
720p/seg_0001.m4s
audio/index.m3u8
audio/seg_0001.m4sWith fMP4, each rendition has an initialization segment (init.mp4) that holds codec setup data. The player fetches it once, then appends media segments to it. Audio is often packaged as its own rendition. This lets one audio track serve every video quality, and it also makes it simple to add languages.
Use the diagram below to follow the data flow.
Choosing a segment duration
Segment length is a trade-off.
| Shorter segments (2 s) | Longer segments (6 to 10 s) |
|---|---|
| Faster quality switches | Fewer requests and smaller manifests |
| Lower live latency | Better compression, since fewer forced keyframes |
| More HTTP requests and more CDN cache entries | Slower reaction to a bandwidth drop |
| Larger keyframe overhead | Longer wait before playback can start in some players |
For on-demand video, 4 to 6 seconds is a common middle. Live streams push toward 2 seconds or less, which a later chapter covers.
Caching and operational details
Packaging decisions affect the CDN directly.
- Segments never change once written, so give them a long
Cache-Controllifetime, such as one year withimmutable. - A VOD manifest is also stable, but it may be rewritten if you add a rendition or fix an error. Use a shorter lifetime for manifests, or version the path.
- Use predictable, content-addressed or versioned paths. Overwriting
seg_0001.m4sin place can leave a mix of old and new objects in different CDN caches. - Set the right
Content-Typevalues:application/vnd.apple.mpegurlfor.m3u8andapplication/dash+xmlfor.mpd. - If the player runs in a browser on a different domain from the CDN, configure CORS headers on manifests and segments.
Common errors
- Keyframes that do not line up across renditions, which causes stutter or a failed switch.
- Variable frame rate in the source. Convert it to a constant frame rate before encoding.
- A
BANDWIDTHvalue far below the real peak bitrate. The player then overestimates what it can sustain. - Audio and video segments with different durations, which causes drift over a long playback.
- Missing
EXT-X-ENDLISTon a finished video, so the player keeps polling for new segments.
Exercise
A team encodes the 360p rendition with keyframes every 2 seconds and the 1080p rendition with keyframes every 2.5 seconds, then cuts both into segments. Playback stutters when the player switches quality. Explain why, and name two ffmpeg options that fix it.
Show answer
Segments can only start at keyframes, so the two renditions have segment boundaries at different times. When the player switches, the next segment from the new rendition does not start where the previous one ended, so content is repeated or missing. Encode every rendition with the same keyframe interval in seconds, for example -g 48 -keyint_min 48 at 24 frames per second, and disable scene-change keyframes with -sc_threshold 0.
Exercise
You want to support Safari and Android players while storing each rendition only once. Which segment container and which manifests do you produce?
Show answer
Package the renditions as fragmented MP4 (CMAF) segments. Write both an HLS master and media playlists and a DASH MPD that point at the same segment files. Only the manifests differ between the two protocols.