Skip to content
systemcoding.dev
Media

How H.264 Encodes Video: Macroblocks, Prediction and Entropy Coding

Follow one H.264 frame through the encoder: macroblocks, intra and inter prediction, the 4x4 integer transform, quantisation, deblocking and CAVLC or CABAC.

7 min read
Summarize in AI
Flat illustration of video frames passing through a codec, with the FFmpeg, GStreamer and C logos.

H.264, also called AVC and standardised as ITU-T H.264 and ISO/IEC 14496-10, is the most deployed video codec in the world. It compresses video by a large factor with a design that has not changed in its basic shape since 2003: split the picture into blocks, predict each block from something already known, transform and quantise the difference, and entropy code what is left. This post follows a frame through that pipeline in order, with the names that appear in encoder settings and the specification, and runs a small piece of the real arithmetic, the 4x4 integer transform, in C so that the numbers are concrete. It assumes you know what I, P and B frames are, and uses x264 in FFmpeg 7.1 for the commands.

The pipeline at a glance

For each block of each picture, an H.264 encoder does five things, and the decoder does the reverse:

  1. Predict the block from already-coded pixels, either inside the same picture (intra) or from other pictures (inter).

  2. Subtract the prediction from the real block to get the residual.

  3. Transform the residual into frequency coefficients.

  4. Quantise the coefficients, which is the only lossy step.

  5. Entropy code the quantised coefficients and the prediction instructions into bits.

A decoder needs the encoder to have used exactly the same reconstruction as it will, so the encoder also runs the reverse steps (inverse quantise, inverse transform, add prediction) to keep its own copy of the decoded picture for future prediction. A loop in the encoder always mirrors the decoder.

Macroblocks and partitions

H.264 divides each picture into macroblocks, squares of 16 by 16 luma samples with their associated chroma. In the usual 4:2:0 format, a macroblock has a 16x16 luma block and two 8x8 chroma blocks. A 1920x1080 picture has 120 macroblocks across and 68 down (1088 rows, padded from 1080), which is 8160 macroblocks per picture, a number that matters when reading level limits. Macroblocks are grouped into slices, which can be decoded independently and help with error resilience and parallelism.

A macroblock can be coded whole or split into smaller partitions to follow the shapes in the picture. For inter prediction, the partitions are 16x16, 16x8, 8x16 or 8x8, and 8x8 can be split further into 8x4, 4x8 or 4x4. Smaller partitions fit moving edges better and cost more side information, so the encoder chooses by trading bits against distortion, which is the job of rate-distortion optimisation.

Prediction

Intra prediction

For a block inside the picture with no suitable reference frame, H.264 predicts from the already-decoded pixels immediately above and to the left of the block. There are modes that extend those neighbouring pixels in a direction: vertical, horizontal, DC (the average), and diagonal ones. Luma can be predicted in 4x4 blocks with nine modes, in 8x8 blocks in High profile, or as a whole 16x16 macroblock with four modes. A smooth sky uses 16x16 DC or plane prediction, and a textured edge uses 4x4 directional modes. The encoder sends only the mode and the residual.

Inter prediction and motion vectors

For most blocks in P and B pictures, the best predictor is a block of a reference picture displaced by a motion vector. The vector points to a position with quarter-sample precision for luma, so the reference is interpolated: half-sample positions use a six-tap filter and quarter-sample positions average neighbouring samples. A block may refer to one of several previously decoded pictures (multiple reference frames), and a B-block can average two predictions. The encoder searches for the best vector, which is where most encoding time goes, and then codes the vector as a small difference from a predicted vector from its neighbours.

You can see the vectors in a real file. FFmpeg can export them and overlay them as arrows:

Shell
ffmpeg -flags2 +export_mvs -i input.mp4 -vf codecview=mv=pf+bf+bb -c:v libx264 -crf 20 vectors.mp4

+export_mvs asks the decoder to attach the motion vectors to each frame, and codecview draws them: pf for P-frame forward vectors, bf for B-frame forward and bb for B-frame backward. In the resulting video, arrows on a panning scene all point the same way, and arrows on a still background are tiny or absent.

The 4x4 integer transform

The residual block is transformed so that its energy gathers into a few coefficients. Older codecs used a floating-point discrete cosine transform whose rounding differed between implementations, which made encoder and decoder drift apart. H.264 uses an integer transform that approximates a 4x4 DCT with small integers, so the result is exact and identical everywhere. For a 4x4 block X, the forward core transform is Y = C X C^T, where C is:

Text
 1  1  1  1
 2  1 -1 -2
 1 -1 -1  1
 1 -2  2 -1

The following program computes it. It uses a flat block of 10s and a horizontal ramp, which are easy to check by hand.

transform4x4.cc
#include <stdio.h>

static const int C[4][4] = {
    { 1,  1,  1,  1},
    { 2,  1, -1, -2},
    { 1, -1, -1,  1},
    { 1, -2,  2, -1},
};

static void forward(const int x[4][4], int y[4][4])
{
    int t[4][4];
    for (int i = 0; i < 4; i++)            /* t = C * x */
        for (int j = 0; j < 4; j++) {
            t[i][j] = 0;
            for (int k = 0; k < 4; k++)
                t[i][j] += C[i][k] * x[k][j];
        }
    for (int i = 0; i < 4; i++)            /* y = t * C^T */
        for (int j = 0; j < 4; j++) {
            y[i][j] = 0;
            for (int k = 0; k < 4; k++)
                y[i][j] += t[i][k] * C[j][k];
        }
}

static void show(const char *name, const int y[4][4])
{
    printf("%s\n", name);
    for (int i = 0; i < 4; i++)
        printf("%5d %5d %5d %5d\n", y[i][0], y[i][1], y[i][2], y[i][3]);
}

int main(void)
{
    int flat[4][4], ramp[4][4], y[4][4];
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++) {
            flat[i][j] = 10;
            ramp[i][j] = j;               /* each row is 0 1 2 3 */
        }
    forward(flat, y); show("flat block of 10:", y);
    forward(ramp, y); show("horizontal ramp 0 1 2 3:", y);
    return 0;
}
Text
flat block of 10:
  160     0     0     0
    0     0     0     0
    0     0     0     0
    0     0     0     0
horizontal ramp 0 1 2 3:
   24   -28     0    -4
    0     0     0     0
    0     0     0     0
    0     0     0     0

A flat block puts everything in one coefficient, the DC at the top left, and the other fifteen are zero, so there is almost nothing to store. A ramp that changes only horizontally concentrates in the first row, and the rows below are zero because nothing varies vertically. This is the compaction the transform exists to provide: smooth blocks need very few coefficients. The real standard folds a scaling step into quantisation, and High profile adds an 8x8 integer transform with a similar structure.

Quantisation

Quantisation divides each coefficient by a step size and rounds, which discards precision. It is where the loss happens, and it is the main control of quality against size. H.264 has a quantisation parameter (QP) from 0 to 51 for 8-bit video, and the step size roughly doubles every 6 QP steps. Small QP means fine steps and high quality; large QP means coarse steps and visible blocking. The encoder's rate control chooses QP per macroblock to hit a bitrate, and CRF mode in x264 targets a constant quality by letting QP vary with the complexity of the scene. High-frequency coefficients are often rounded to zero, which is why details soften first at low bitrates.

Deblocking

Block-based coding leaves visible seams at block edges, especially at high QP. H.264 includes an in-loop deblocking filter that smooths edges between blocks, with strength depending on QP and on whether the neighbouring blocks were coded differently. It is "in-loop" because the filtered picture becomes the reference for later prediction, so the filter improves both what you see and what is predicted. x264 exposes it as -deblock alpha:beta, for example -x264-params deblock=1:1, with higher values smoother and lower values sharper.

Entropy coding: CAVLC and CABAC

The last stage writes the symbols as bits. H.264 offers two methods:

  • CAVLC (context-adaptive variable-length coding) uses lookup tables of variable-length codes chosen according to context. It is simpler and is the only method in Baseline profile.

  • CABAC (context-adaptive binary arithmetic coding) codes each decision with an adaptive probability model and arithmetic coding, which reaches higher compression at higher decode cost. It is available from Main profile upward.

This is why Baseline streams are larger and cheaper to decode, and why most streaming content uses High profile with CABAC. In x264 it is the cabac option, enabled by default except where the profile forbids it:

Shell
ffmpeg -i input.mp4 -c:v libx264 -profile:v baseline -level 3.0 -x264-params cabac=0 base.mp4

Putting it together

An encoder pass over one frame therefore produces: a choice of partitioning per macroblock, a prediction (intra mode or motion vectors with reference indices), a quantised set of transform coefficients for the residual, and parameters such as QP, all entropy coded into slices. The decoder reads those, rebuilds each prediction, adds the dequantised and inverse-transformed residual, and runs the deblocking filter. Everything that makes encoders differ in quality at the same bitrate, such as mode decision, motion search and rate control, happens on the encoder side and is not fixed by the standard, which defines only the decoder.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.