Sub topic 13
Video: Transcoding and Adaptive Bitrate Streaming with HLS or DASH
This chapter assumes you know how the post-upload pipeline works (an object-created event triggers asynchronous jobs) and how a CDN caches files by URL. It also assumes you know what a range request is. Here you will see how a raw uploaded video becomes something a browser can play smoothly on any connection.
Why you should not serve the original upload
An uploaded video is usually a large file in whatever codec and resolution the user's camera chose. Serving it directly causes three problems:
- Some devices cannot decode the codec.
- A viewer on a slow connection must download a very large file before playback runs smoothly.
- One fixed bitrate cannot suit both a phone on mobile data and a TV on fiber.
The fix is to transcode the video (re-encode it) into several renditions, then let the player pick among them while it plays.
Adaptive bitrate streaming
In adaptive bitrate (ABR) streaming, each rendition is cut into short segments, usually 2 to 6 seconds long. A text file called a manifest lists the renditions and their segments. The player downloads the manifest, measures its download speed and buffer level, and requests each next segment from the rendition that fits best.
Two protocols are common:
| Row | HLS | DASH |
|---|---|---|
| Manifest | `.m3u8` playlists | `.mpd` XML file |
| Native support | Safari and Apple devices | Most other browsers, through a JavaScript player |
| Segment format | MPEG-TS or fragmented MP4 | Fragmented MP4 |
Because both can use fragmented MP4 segments (CMAF), you can often store one set of segments and publish two manifests. For a simple start, HLS alone covers most devices, since players such as hls.js handle it in browsers without native support.
The pipeline
Transcoding is slow and CPU-heavy, so it must never run inside the request that finished the upload. Use the event and queue from the previous chapters. Record a status such as processing, ready, or failed in your database, and show the video only when it is ready.
Transcoding with FFmpeg
This command creates a 720p and a 360p HLS rendition and a master playlist. It assumes input.mp4 contains an audio track.
ffmpeg -i input.mp4 \
-filter_complex "[0:v]split=2[v1][v2];[v1]scale=-2:720[v720];[v2]scale=-2:360[v360]" \
-map "[v720]" -map 0:a -map "[v360]" -map 0:a \
-c:v libx264 -preset medium -g 48 -keyint_min 48 -sc_threshold 0 \
-b:v:0 2800k -b:v:1 800k \
-c:a aac -b:a 128k \
-f hls -hls_time 4 -hls_playlist_type vod \
-hls_segment_filename "out/v%v/seg_%03d.ts" \
-master_pl_name master.m3u8 \
-var_stream_map "v:0,a:0 v:1,a:1" \
"out/v%v/index.m3u8"Important details:
-g 48 -keyint_min 48 -sc_threshold 0forces a keyframe at fixed intervals. Segments must start on a keyframe, and renditions must align, so the player can switch between them cleanly.-hls_time 4aims for 4-second segments.- The output is
out/master.m3u8plus one folder of segments per rendition. Upload the whole folder to storage.
Delivering segments
Segments and playlists have different caching needs:
- Segments of a finished video never change, so give them a content-addressed or versioned path and cache them for a year with
immutable. - Playlists for finished videos can also be cached for a long time if the path includes a version. For live streams, playlists change constantly and need a very short lifetime.
- Segment requests are many and small, so the CDN hit rate matters a great deal for egress cost.
If the video is private, remember that the player requests many URLs, not one. A single signed URL does not cover them. Use signed cookies or a signed path prefix, as the access control chapter describes.
Common errors
- Mismatched keyframes between renditions. Playback stutters or glitches when the player switches quality.
- Transcoding in the request path. Uploads time out and servers run out of CPU.
- Marking the video ready too early. Show it only after the master playlist and all renditions are written.
- Skipping a fallback. Keep the original file so you can re-transcode later with new settings or codecs.
- Too many renditions. Each one adds compute and storage cost. Three or four steps are usually enough.
Exercise
A viewer on a fast connection suddenly moves to a slow network in the middle of a video. What does the player do, and what must be true of the renditions for this to look smooth?
Show answer
The player measures that segment downloads are slowing and its buffer is shrinking, so it requests the next segment from a lower-bitrate rendition listed in the manifest. This looks smooth only if the renditions have keyframes at the same timestamps and use the same segment boundaries, so a new segment from the lower rendition can begin exactly where the previous one ended.