15. Video Compression
Motion estimation, I/P/B frames, and why video files are so small
A single frame of 1080p video is 1920 × 1080 pixels × 3 bytes per pixel ≈ 6.2 MB. At 30 frames per second, that's 186 MB/s of raw data — an hour of video would be 670 GB. Yet a two-hour Blu-ray movie fits on a 50 GB disc, and streaming services deliver 1080p video at about 5 Mbps (0.6 MB/s). That's a compression ratio of over 300:1.
How? By exploiting two kinds of redundancy that video has in abundance:
- Spatial redundancy — within a single frame, neighboring pixels are similar (the same trick JPEG uses)
- Temporal redundancy — consecutive frames are nearly identical (the new trick)
Temporal redundancy is the big one. In a typical video, 90–95% of each frame is identical to the previous frame. A person talking, a car driving, a game being played — most of the scene stays the same from frame to frame. Video compression's core insight is: don't re-encode pixels that haven't changed.
Frame Types: I, P, and B
Video codecs organize frames into three types:
The three frame types
I P B B P B B P
[full] [diff] [bi] [bi] [diff] [bi] [bi] [diff]
│ │ ││ ││ │ ││ ││ │
│ ◄───────┘│ │└───►│ ││ ││ │
└───────►│ │ │ │◄──────┘│ │└───►│
│ └──►│ └───────►│ │ │
└────────────┘ └──►│ │
└────►│
I-frames (Intra-coded) are compressed independently, like a JPEG. They use only spatial compression (DCT + quantization). They're the largest frames but serve as reference points — you can seek to any I-frame without decoding anything before it.
P-frames (Predicted) encode only the differences from a previous reference frame. For each 16×16 block (macroblock), the encoder asks: "Is there a block in the previous frame that looks like this one?" If yes, store just the offset (motion vector) and the small residual difference. If no good match exists, encode the block independently like an I-frame macroblock.
B-frames (Bi-predicted) can reference both a past and a future frame. This allows even better prediction: if an object is moving, its position between two reference frames can be interpolated. B-frames are the smallest but require more computation and introduce a decode delay (you need the future reference frame before you can decode the B-frame).
Typical frame sizes
In a well-compressed stream, an I-frame might be 50–100 KB, a P-frame 10–30 KB, and a B-frame 5–15 KB. A typical pattern is IBBPBBPBBPBBI... — one I-frame per 30–60 frames (1–2 seconds). Since B-frames are the smallest and most common, average per-frame size drops dramatically.
Motion Estimation: The Heart of Video Compression
Motion estimation is the process of finding, for each macroblock in the current frame, the best-matching block in a reference frame. The difference between the two is the motion-compensated residual — and if the match is good, this residual is nearly zero and compresses extremely well.
Full search (brute force)
The simplest approach: for each macroblock, compare it against every possible position in the reference frame within a search range (say, ±32 pixels in each direction). That's 65 × 65 = 4,225 comparisons per macroblock, each comparing 256 pixels. For a 1080p frame, that's about 33 billion pixel comparisons per frame.
The comparison metric is usually SAD (Sum of Absolute Differences):
where C is the current macroblock and R is the candidate block in the reference frame. The position with the lowest SAD wins.
Faster search algorithms
Full search is too slow for real-time encoding. Practical encoders use hierarchical and heuristic search strategies:
Three-Step Search (TSS): Start with a coarse grid (step size 4), find the best position, reduce step size by half, search the neighborhood, repeat. Finds a good match in about 25 comparisons instead of 4,225.
Diamond search: Search in a diamond-shaped pattern, moving the center to the best match and repeating until no improvement is found. Good for smooth motion.
Hierarchical search: Downsample both frames by 2× or 4×, find approximate motion at low resolution, then refine at full resolution. Handles large motions efficiently.
Modern codecs like H.264 and H.265 combine all of these with sub-pixel motion estimation — the best match position might be at (3.5, -1.25) pixels, not just integer positions. The reference frame is interpolated (using 6-tap or 8-tap filters) to generate sub-pixel positions. Half-pixel and quarter-pixel precision gives 2–4 dB better quality at the same bitrate.
The Encoding Pipeline
Here's how a modern video codec (H.264/AVC or H.265/HEVC) encodes a single P-frame:
Video Frame Encoding Pipeline
┌─────────────────────────────────────────────┐
│ │
│ Current frame │
│ │ │
│ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Partition │ │ Reference │ │
│ │ into blocks │ │ frame(s) │ │
│ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │
│ ▼ │ │
│ ┌──────────────┐ │ │
│ │ Motion │◄───────────┘ │
│ │ Estimation │ │
│ └──────┬───────┘ │
│ │ motion vectors │
│ ▼ │
│ ┌──────────────┐ │
│ │ Motion │ Subtract prediction │
│ │ Compensation │ from actual → residual │
│ └──────┬───────┘ │
│ │ residual │
│ ▼ │
│ ┌──────────────┐ │
│ │ Transform │ DCT (or integer │
│ │ + Quantize │ transform in H.264) │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Entropy │ CABAC or CAVLC │
│ │ Coding │ │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ Compressed bitstream │
│ │
└─────────────────────────────────────────────┘
The residual (prediction error) is what gets transformed and quantized — just like in JPEG, but applied to the difference rather than the original pixels. Since a good motion prediction makes the residual mostly zero, the transformed coefficients are tiny, and quantization crushes almost everything to zero. That's where the 300:1 compression comes from.
Block Partitioning
Early codecs (MPEG-1, MPEG-2) used fixed 16×16 macroblocks. Modern codecs use variable block sizes to adapt to image content:
| Codec | Block sizes |
|---|---|
| H.264/AVC | 16×16, 16×8, 8×16, 8×8, 8×4, 4×8, 4×4 |
| H.265/HEVC | CTUs up to 64×64, recursively split into CUs down to 8×8 |
| AV1 | Superblocks up to 128×128, recursively split down to 4×4 |
Why variable block sizes matter
A static background can use one large block (64×64) with a single motion vector of (0,0). A moving face needs small blocks (8×8 or 4×4) to capture the detailed motion around eyes and mouth. Adaptive partitioning puts bits where they're needed — few bits for static areas, more bits for complex motion.
Intra Prediction
Even within I-frames (and intra-coded blocks in P/B-frames), modern codecs don't just apply DCT to raw pixels like JPEG does. They use intra prediction: predict each block from its already-decoded neighbors within the same frame.
H.264 defines 9 directional prediction modes for 4×4 blocks:
Mode 0: Vertical — copy the row above
Mode 1: Horizontal — copy the column to the left
Mode 2: DC — fill with average of neighbors
Mode 3: Diagonal ↘ — predict from upper-left to lower-right
Mode 4: Diagonal ↗ — predict from lower-left to upper-right
...
Mode 8: Horizontal-Up — predict horizontally upward
H.265 extends this to 35 modes (33 directional + planar + DC). AV1 goes further with 56 modes plus cross-component prediction.
The encoder tries all modes, picks the one with the smallest residual, and signals the mode choice in the bitstream. The residual (actual pixels minus predicted pixels) is then transformed and quantized — just like the motion-compensated residual for inter-coded blocks.
Entropy Coding in Video
Modern video codecs use more sophisticated entropy coding than JPEG's plain Huffman:
CABAC (Context-Adaptive Binary Arithmetic Coding) — used in H.264, H.265, and VVC. It's arithmetic coding where the probability model is continuously updated based on previously coded symbols. "Context-adaptive" means different contexts (e.g., "motion vector horizontal component when neighboring blocks have small motion") get their own probability estimates. CABAC typically saves 10–15% over simpler methods.
CAVLC (Context-Adaptive Variable-Length Coding) — a simpler alternative in H.264 for faster encoding. Uses VLC (Huffman-like) tables that adapt based on neighboring coded data.
Rate-Distortion Optimization
A video encoder faces a constant tradeoff: more bits means better quality, fewer bits means smaller files. The encoder makes hundreds of decisions per frame:
- Which block partition size?
- Which intra prediction mode?
- Which reference frame for inter prediction?
- How aggressively to quantize?
The optimal choice for each decision depends on the rate-distortion cost:
where D is the distortion (e.g., sum of squared differences from the original), R is the number of bits needed, and λ is a Lagrange multiplier that controls the quality/size tradeoff.
The encoder evaluates multiple options for each block and picks the one that minimizes J. A higher λ (lower quality setting) pushes the encoder toward cheaper representations even if they're less accurate. This is why video encoding is so computationally expensive — every block requires evaluating dozens of options.
The Evolution of Video Codecs
| Codec | Year | Key innovation | Typical bitrate (1080p) |
|---|---|---|---|
| MPEG-1 | 1993 | I/P/B frames, motion compensation | ~5 Mbps |
| MPEG-2/H.262 | 1995 | Interlaced video, scalability | ~4 Mbps |
| H.264/AVC | 2003 | Variable block sizes, B-frames with multiple references, CABAC, quarter-pixel motion, in-loop deblocking | ~2 Mbps |
| H.265/HEVC | 2013 | CTUs up to 64×64, 35 intra modes, SAO filter, improved CABAC | ~1 Mbps |
| AV1 | 2018 | 128×128 superblocks, CDEF filter, film grain synthesis, royalty-free | ~0.8 Mbps |
| VVC/H.266 | 2020 | 128×128 CTUs, 67 intra modes, affine motion, geometric partitioning | ~0.5 Mbps |
Each generation roughly halves the bitrate for equivalent quality. The improvement comes from better prediction (more block sizes, more intra modes, sub-pixel motion), better entropy coding (refined CABAC), and better in-loop filtering (deblocking, SAO, CDEF).
Group of Pictures (GOP) Structure
Frames aren't encoded independently — they're organized into GOPs (Groups of Pictures). A GOP starts with an I-frame and contains a pattern of P and B-frames:
GOP with M=3, N=12:
I B B P B B P B B P B B I B B P ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Decode order:
I P B B P B B P B B P B B I ...
0 3 1 2 6 4 5 9 7 8 12 10 11 12 ...
Notice that decode order differs from display order. Frame 3 (a P-frame) must be decoded before frames 1 and 2 (B-frames that reference it). This is why video players need to buffer a few frames ahead — and why seeking in a video isn't instant (you must decode from the nearest I-frame).
GOP length tradeoffs
Shorter GOPs (I-frame every 15–30 frames): faster seeking, more error
resilience, but larger files since I-frames are expensive.
Longer GOPs (I-frame every 60–250 frames): better compression, but
seeking requires decoding more frames and errors propagate further.
Streaming services typically use 2-second GOPs (60 frames at 30fps). Blu-ray uses longer GOPs for better compression since seeking is less critical.
Loop Filters: Fixing Artifacts
Block-based coding creates blocking artifacts at block boundaries — the same problem JPEG has. Video codecs apply in-loop deblocking filters after decoding each frame to smooth these boundaries before the frame is used as a reference for future frames.
This is critical: if blocking artifacts in frame N aren't smoothed, they propagate to frame N+1 through motion compensation, and accumulate over time. The deblocking filter breaks this feedback loop.
H.265 adds SAO (Sample Adaptive Offset) — a second filter that corrects for systematic biases in edge regions. AV1 adds CDEF (Constrained Directional Enhancement Filter), which applies directional smoothing along edge directions to reduce ringing.
Putting It All Together
Consider encoding 10 seconds of 1080p video at 30 fps:
Raw: 300 frames × 6.2 MB = 1,860 MB
Target: 300 frames × ~17 KB = 5 MB (at 4 Mbps)
Compression ratio: 372:1
Where does the compression come from?
| Technique | Contribution |
|---|---|
| Temporal prediction (motion compensation) | ~20:1 (residual is 95% smaller than raw) |
| Spatial prediction (intra) | ~3:1 (within I-frames and intra blocks) |
| Transform + quantization | ~5:1 (crush small residuals to zero) |
| Entropy coding (CABAC) | ~1.5:1 (variable-length coding of quantized values) |
| Chroma subsampling (4:2:0) | ~2:1 (1.5× from subsampling + better chroma compression) |
These multiply together: 20 × 3 × 5 × 1.5 × 2 ≈ 900:1 theoretical — though in practice the stages overlap and interact, the achieved 300:1 is well within this budget.
Try It Yourself — Motion Estimation
This demo shows two frames and the motion vectors found by block matching. Drag the object in the reference frame to see how motion vectors change. The residual panel shows the difference between the predicted and actual frames — darker means less data to encode.
Statistics
Key Takeaways
- Video compression exploits temporal redundancy (consecutive frames are mostly identical) on top of spatial redundancy (JPEG-like techniques within frames)
- I-frames are self-contained (like JPEG); P-frames predict from past frames; B-frames predict from past and future frames
- Motion estimation finds matching blocks between frames; only the motion vector and small residual are encoded
- Modern codecs use variable block sizes, sub-pixel motion, dozens of intra prediction modes, and context-adaptive arithmetic coding
- In-loop deblocking filters prevent artifacts from accumulating across frames
- Each codec generation roughly halves the bitrate for equivalent quality
- These techniques combine for 300:1+ compression ratios on typical video
We've now covered both lossy compression (JPEG, video) and the lossless building blocks they rely on. But the lossless story isn't complete. The LZ77 variant we discussed earlier is the foundation, but practical archivers like 7-Zip use a refined version — LZSS and LZMA — that pushes dictionary compression to its limits.