Sub topic 3
Video basics: codecs, containers and bitrate
This chapter covers the three ideas every later design decision rests on: what a codec does, what a container does, and what bitrate controls. It assumes you know basic web architecture, HTTP and caching, and object storage, and that you can read short shell and Python snippets. No video background is needed.
Raw video is too big to ship
A video is a sequence of frames, and each frame is a grid of pixels. Uncompressed 1080p video at 30 frames per second, with 3 bytes per pixel, is about 1920 × 1080 × 3 × 30 ≈ 187 MB per second. That is roughly 1.5 Gbit/s. A home connection cannot carry it, and storing a one-hour film would take about 670 GB.
Compression closes this gap. A typical 1080p stream delivered to a viewer runs at 3 to 6 Mbit/s, a reduction of several hundred times. The component that does the compressing is the codec.
Codecs
A codec (coder-decoder) is an algorithm that compresses video into a compact bitstream and decompresses it for display. The encoder runs once on your servers. The decoder runs on every viewer's device, often in dedicated hardware.
Codecs save space with two main techniques:
- Spatial compression finds redundancy inside one frame, for example a large patch of blue sky.
- Temporal compression finds redundancy between frames. Most of a frame looks like the previous one, so the codec stores only what changed, plus motion vectors that say how blocks of pixels moved.
Frame types and the GOP
Temporal compression creates three frame types:
| Frame type | What it stores | Can it be decoded alone? |
|---|---|---|
| I-frame (keyframe) | A complete picture | Yes |
| P-frame | Differences from earlier frames | No |
| B-frame | Differences from earlier and later frames | No |
A group of pictures (GOP) is a keyframe followed by the P and B frames that depend on it, up to the next keyframe. The GOP length matters for streaming because a player can only start decoding, or switch quality, at a keyframe. Later chapters cut video into segments, and every segment must begin on a keyframe so it can be played independently.
Common codecs
| Codec | Typical use | Compression efficiency | Trade-off |
|---|---|---|---|
| H.264 (AVC) | Default for compatibility | Baseline | Plays nearly everywhere, including old devices |
| H.265 (HEVC) | 4K and HDR | About 30 to 50% smaller than H.264 at similar quality | Patent licensing is complex and browser support is uneven |
| VP9 | YouTube-style web delivery | Similar to HEVC | Royalty-free, but weaker hardware support on some devices |
| AV1 | Large-scale, cost-sensitive delivery | Better than HEVC | Encoding is slow and costly, and older devices cannot decode it in hardware |
The efficiency percentages are approximate and depend on content and encoder settings. The design lesson is that a better codec cuts storage and bandwidth but raises encoding cost and shrinks the set of devices that can play the result. Most platforms keep H.264 as the universal fallback and add newer codecs for popular titles and capable devices.
Audio uses its own codecs. AAC is the common choice, and Opus is common on the web. Audio is a small share of the total, typically 64 to 192 kbit/s.
Containers
A container is a file format that packages one or more encoded streams (video, audio, subtitles) together with timing information and metadata. The container does not compress anything. It answers the question of how to store and interleave the streams so a player can find and sync them.
| Container | Extension | Notes |
|---|---|---|
| MP4 (ISO BMFF) | .mp4, .m4s | Standard for downloads. Fragmented MP4 (fMP4) is used by both HLS and DASH |
| MPEG-TS | .ts | Designed for broadcast. Used by classic HLS segments |
| WebM | .webm | Matroska subset, used with VP9 and AV1 on the web |
| Matroska | .mkv | Flexible, common for source files |
Keep the codec and container separate in your head. A file named video.mp4 could hold H.264, HEVC or AV1. Support depends on both, so a player needs to know the codec string, such as avc1.4d401f, and not just the file extension.
One container detail affects streaming. A regular MP4 stores its index (the moov box) either at the end or the start of the file. If it is at the end, a player must download the whole file before it can start. Fragmented MP4 splits the file into small self-contained pieces, each with its own index, which suits segment-by-segment delivery.
Bitrate
Bitrate is the amount of data used per second of video, usually in kbit/s or Mbit/s. It is the main control over file size, bandwidth cost and quality.
File size follows directly from bitrate and duration:
def size_gb(bitrate_bps: int, duration_s: int) -> float:
"""Approximate size in gigabytes (decimal) for a constant bitrate."""
return bitrate_bps * duration_s / 8 / 1e9
# One hour of 3 Mbit/s video plus 128 kbit/s audio
print(round(size_gb(3_000_000 + 128_000, 3600), 2)) # 1.41The same arithmetic drives delivery cost. A viewer watching that stream for an hour downloads about 1.4 GB, and you pay for every gigabyte your CDN sends.
Constant and variable bitrate
- Constant bitrate (CBR) holds the rate steady. It is predictable for networks, but it wastes bits on simple scenes and starves complex ones.
- Variable bitrate (VBR) gives more bits to complex scenes (fast motion, fine detail) and fewer to simple ones. Quality is more even for the same average size.
- Constrained VBR sets a ceiling with
-maxrateand a buffer size with-bufsize. This is the usual choice for streaming, because it keeps quality good while capping the peaks that could stall a player.
For adaptive streaming, constrained VBR is common because the player's decision logic assumes each rendition stays close to its advertised bandwidth.
Resolution, frame rate and quality
Bitrate does not fix quality by itself. Three other factors interact with it:
- Resolution: more pixels need more bits. 1080p needs about twice the bitrate of 720p at the same quality.
- Frame rate: 60 fps needs more bits than 30 fps, though less than double because adjacent frames are very similar.
- Content: a static talking head compresses far better than a football match.
Pushing a low bitrate onto a high resolution produces visible blocking and blur. That is why a rendition at each resolution gets its own bitrate, which is the subject of the bitrate ladder chapter.
A worked example with ffmpeg
The command below encodes a source file with settings you will see again when building the transcoding pipeline. It uses H.264 and AAC and places keyframes at fixed intervals.
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.m3u8Reading the options in terms of this chapter:
-c:v libx264and-c:a aacchoose the codecs.-b:v 2800k -maxrate 3000k -bufsize 6000kset constrained VBR: a 2.8 Mbit/s target, a 3 Mbit/s ceiling, and a 6 Mbit/s buffer window over which the ceiling is enforced.-g 48 -keyint_min 48fix the GOP at 48 frames. At 24 fps that is 2 seconds.-sc_threshold 0stops the encoder from inserting extra keyframes at scene changes, so the GOP stays regular.-hls_time 4makes 4-second segments, which is two GOPs each. Segment length should be a whole multiple of the GOP length so every segment starts on a keyframe.-preset mediumtrades encoding speed against compression efficiency. Slower presets give smaller files at the same quality but cost more CPU time.
Common mistakes
- Treating the container as the codec. Check the codec string, not the extension.
- Letting the encoder place keyframes freely. Irregular GOPs lead to segments with uneven lengths, or segments that cannot be switched cleanly between renditions.
- Using only the newest codec. Devices without support get a playback error, so keep a fallback rendition.
- Ignoring
-maxrate. Unbounded peaks make a rendition's real bandwidth exceed its advertised value, and the player then picks quality levels it cannot sustain. - Estimating cost from average bitrate alone. Peak rate affects buffering, and audio adds to the total.
How this connects to the rest of the design
Each concept here feeds a later decision:
- Codec choice sets encoding cost and device reach, which shapes the transcoding pipeline.
- Bitrate and duration set storage and CDN volume, which drive capacity estimates and cost.
- GOP structure and container choice determine how video can be segmented for HLS and DASH.
Exercise
A platform stores one rendition at 4 Mbit/s video plus 128 kbit/s audio. A film lasts 2 hours. About how many gigabytes does the file take (decimal GB), and how many gigabytes does the CDN send if 10,000 viewers each watch the whole film once?
Show answer
Total bitrate is 4,128,000 bit/s. Over 7,200 seconds that is 29,721,600,000 bits, or about 3.71 GB per copy (divide by 8 for bytes). For 10,000 viewers the CDN sends about 37,100 GB, which is roughly 37 TB.
Exercise
You encode at 30 fps with -g 48 and -hls_time 4. Why is this a problem, and what value of -g fixes it?
Show answer
At 30 fps, 48 frames last 1.6 seconds, so a 4-second segment does not end on a keyframe boundary (4 seconds is 2.5 GOPs). Use -g 60 (and -keyint_min 60) to get 2-second GOPs, so each 4-second segment holds exactly two GOPs and starts on a keyframe.
Exercise
A colleague says "we already use MP4, so every device can play our files." What is wrong with this claim?
Show answer
MP4 is only a container. Playback also depends on the codec inside it. An MP4 holding HEVC or AV1 will fail on devices that cannot decode those codecs, while the same container holding H.264 plays almost everywhere.