Sub topic 13
Video: Transcoding and Adaptive Bitrate Streaming with HLS or DASH
This chapter assumes you know how presigned uploads work, how a CDN caches objects, and what an event-driven post-upload pipeline looks like. Those topics come from earlier chapters. Here you will turn an uploaded video into a set of files that play well on any network.
Why you should not serve the original upload
A user uploads a 4K, 60 fps, 80 Mbit/s file from a phone. If you serve that file as it is, three things go wrong:
- Viewers on slow connections stall, because the file's bitrate is higher than their bandwidth.
- Viewers waste data and you pay egress for bytes they never needed.
- Some uploads use codecs or containers that a browser cannot play.
Two techniques fix this. Transcoding converts the video into formats and sizes you choose. Adaptive bitrate streaming (ABR) lets the player switch between those sizes while the video plays.
The working model
Codec, container, and rendition
A codec compresses video or audio, for example H.264 (AVC), H.265 (HEVC), VP9, AV1, or AAC for audio. A container packages the compressed streams into a file, for example MP4, MPEG-TS, or WebM. A rendition is one encoded version of the video at a specific resolution and bitrate.
H.264 with AAC is the safe baseline because every mainstream browser and device decodes it. AV1 and HEVC compress better, but support and encoding cost vary, so teams usually add them as extra renditions later.
The bitrate ladder
The set of renditions is called the bitrate ladder. A typical starting point:
| Rendition | Resolution | Video bitrate | Audio bitrate |
|---|---|---|---|
| 1080p | 1920x1080 | 5000 kbit/s | 128 kbit/s |
| 720p | 1280x720 | 2800 kbit/s | 128 kbit/s |
| 480p | 854x480 | 1200 kbit/s | 128 kbit/s |
Never upscale. If the source is 540p, skip the 720p and 1080p rungs. Longer or more complex content may justify a per-title ladder, where you analyze the video and pick bitrates that fit its complexity.
Segments and manifests
Each rendition is cut into segments, short files that usually last 2 to 6 seconds. A manifest is a small text file that lists the renditions and their segments. The player downloads the manifest first, picks a rendition from its bandwidth estimate, and fetches segments one by one. Before each segment it can switch to a different rendition.
Two protocols dominate:
- HLS (HTTP Live Streaming) uses
.m3u8playlists. Safari and iOS play it natively. Other browsers need a JavaScript library such as hls.js. - DASH (Dynamic Adaptive Streaming over HTTP) uses an XML manifest called an MPD. It is an open standard, played in browsers through libraries such as dash.js or Shaka Player.
Both are plain HTTP, so a CDN caches them like any other file. No special streaming server is needed.
Segments can be MPEG-TS (.ts, HLS only) or fragmented MP4 (.m4s). Fragmented MP4 in the CMAF layout works for both HLS and DASH, so you can store one set of segments and write two manifests. That halves storage and cache footprint if you must support both protocols.
The pipeline
Transcoding is slow and CPU-heavy, so it runs asynchronously after the upload is validated and scanned.
Design points for the worker:
- Make jobs idempotent. Queues redeliver messages, so a retried job must overwrite the same output keys and not create duplicates.
- Write output under a prefix derived from the content hash or video ID, such as
video/9b1c4e/. - Write the master manifest last, then mark the video as ready in your database. A player must never see a manifest that points to segments not yet uploaded.
- Store the original in a separate prefix with a lifecycle rule. You may need it to re-encode later.
- Use a managed service (AWS Elemental MediaConvert, Mux, Cloudflare Stream) if you do not want to operate encoders. Self-hosting with FFmpeg is cheaper at volume but needs autoscaling and failure handling.
Producing HLS with FFmpeg
The script below creates three renditions in one pass. It assumes a 24 fps source, so a keyframe every 48 frames is a 2-second interval. For other frame rates, set -g to twice the frame rate.
#!/usr/bin/env bash
set -euo pipefail
INPUT="$1"
OUT="out"
mkdir -p "$OUT/stream_0" "$OUT/stream_1" "$OUT/stream_2"
ffmpeg -i "$INPUT" \
-filter_complex "[0:v]split=3[v1][v2][v3];[v1]scale=-2:1080[v1out];[v2]scale=-2:720[v2out];[v3]scale=-2:480[v3out]" \
-map "[v1out]" -c:v:0 libx264 -b:v:0 5000k -maxrate:v:0 5350k -bufsize:v:0 7500k \
-map "[v2out]" -c:v:1 libx264 -b:v:1 2800k -maxrate:v:1 3000k -bufsize:v:1 4200k \
-map "[v3out]" -c:v:2 libx264 -b:v:2 1200k -maxrate:v:2 1300k -bufsize:v:2 1800k \
-map a:0 -c:a:0 aac -b:a:0 128k \
-map a:0 -c:a:1 aac -b:a:1 128k \
-map a:0 -c:a:2 aac -b:a:2 128k \
-g 48 -keyint_min 48 -sc_threshold 0 \
-f hls -hls_time 6 -hls_playlist_type vod \
-hls_flags independent_segments \
-hls_segment_filename "$OUT/stream_%v/seg_%03d.ts" \
-master_pl_name master.m3u8 \
-var_stream_map "v:0,a:0 v:1,a:1 v:2,a:2" \
"$OUT/stream_%v/index.m3u8"The options that matter most:
-g 48 -keyint_min 48 -sc_threshold 0forces keyframes at fixed intervals and disables scene-cut keyframes. Every rendition then has keyframes at the same timestamps, which lets the player switch cleanly at segment boundaries.-hls_time 6asks for 6-second segments. FFmpeg can only cut at keyframes, so the segment length is a multiple of the keyframe interval.-maxrateand-bufsizecap bitrate spikes so a rendition does not exceed what its manifest advertises.-hls_playlist_type vodwrites a complete playlist with an end marker.
The result is a master playlist that lists the renditions:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=5128000,RESOLUTION=1920x1080,CODECS="avc1.640028,mp4a.40.2"
stream_0/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2928000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"
stream_1/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1328000,RESOLUTION=854x480,CODECS="avc1.64001e,mp4a.40.2"
stream_2/index.m3u8Each index.m3u8 is a media playlist listing that rendition's segments. The player compares BANDWIDTH against its measured throughput to choose a line.
Publishing with correct headers
Object storage must serve the right Content-Type, and each file type needs its own caching policy. Segments never change once written, so they can be cached for a year. For VOD, manifests under a versioned prefix can also be long-lived. If you rewrite manifests in place, for example to add a rendition later, give them a short lifetime.
aws s3 sync out/ s3://example-media/video/9b1c4e/ \
--exclude "*" --include "*.ts" \
--content-type "video/mp2t" \
--cache-control "public, max-age=31536000, immutable"
aws s3 sync out/ s3://example-media/video/9b1c4e/ \
--exclude "*" --include "*.m3u8" \
--content-type "application/vnd.apple.mpegurl" \
--cache-control "public, max-age=300"Upload the manifests after the segments. For fragmented MP4 output, use video/iso.segment for .m4s files, video/mp4 for init segments, and application/dash+xml for .mpd files.
Playing the stream
Safari plays HLS natively. Other browsers need hls.js, which feeds segments to the browser through Media Source Extensions.
import Hls from "hls.js";
export function play(video, manifestUrl) {
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(manifestUrl);
hls.attachMedia(video);
hls.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal) {
console.error("Fatal playback error", data.type, data.details);
hls.destroy();
}
});
return hls;
}
if (video.canPlayType("application/vnd.apple.mpegurl")) {
video.src = manifestUrl; // native HLS, for example Safari on iOS
return null;
}
throw new Error("HLS is not supported in this browser");
}Common errors
- Mismatched keyframes across renditions. Without a fixed
-gand-sc_threshold 0, switching causes visible glitches or stalls. - Wrong
Content-Type. Some players refuse manifests served asapplication/octet-stream. - Missing CORS headers. hls.js loads the manifest with
fetch, so a CDN on another origin must sendAccess-Control-Allow-Origin. - Absolute URLs inside manifests. They break when you move the files to a new domain or prefix. Use relative paths, as in the example above.
- Signed URLs that do not cover segments. A signature on the manifest URL does not authorize the segment requests it triggers. Use signed cookies or a CDN policy that covers the whole prefix, as described in the access-control chapter.
- Publishing the manifest before the segments. Viewers get 404 errors for the first few segments.
- Over-long ladders. Each added rendition costs encode time and storage. Add rungs only when analytics show viewers needing them.
- Ignoring audio-only edge cases. A source with no audio track makes
-map a:0fail. Probe the input withffprobefirst and build the command from what it finds.
Exercise
A video is transcoded to three renditions with 6-second segments. Viewers report visible glitches whenever the player switches rendition, and the master manifest is served with Cache-Control: public, max-age=300. Name the encoding setting most likely to cause the glitches, and say whether the cache header is a problem for a finished VOD file under a hashed prefix.
Show answer
The likely cause is renditions whose keyframes do not line up. Fix it by setting a fixed keyframe interval (-g and -keyintmin) and disabling scene-cut keyframes (-scthreshold 0), so all renditions have keyframes at the same timestamps and segment boundaries match. The 300-second manifest cache is not a problem here. It only delays updates by up to five minutes, and a finished VOD manifest under a hashed prefix rarely changes. A longer lifetime would also work if you version the prefix when the manifest changes.