Sub topic 15
Huffman Coding in DEFLATE and JPEG
This chapter assumes you have read the earlier chapters on canonical Huffman codes, shipping the code table, and length-limited codes. You should be comfortable reading Python that does bit manipulation. The chapter shows how two widely used formats use the same few ideas: canonical codes, code lengths stored in the header, and a cap on code length.
DEFLATE is the compression format inside ZIP, gzip, zlib, and PNG. JPEG is the standard lossy image format. Neither one applies Huffman coding to raw bytes. Each format first turns its input into a stream of symbols that fits Huffman coding well, and then encodes those symbols with canonical codes.
DEFLATE: LZ77 First, Huffman Second
DEFLATE is specified in RFC 1951. It works in two stages. An LZ77 stage replaces repeated substrings with back-references, where each back-reference is a pair (length, distance) meaning "copy length bytes starting distance bytes back". The Huffman stage then encodes the resulting sequence of literals and back-references.
Two Alphabets, Plus Extra Bits
A single literal/length alphabet carries three kinds of symbol:
| Symbol range | Meaning |
|---|---|
| 0–255 | A literal byte |
| 256 | End of block |
| 257–285 | A match length bucket, followed by 0–5 raw extra bits |
Distances use a separate alphabet of 30 symbols (0–29). Each distance symbol names a bucket, and 0–13 extra bits select the exact distance within it. The extra bits are written raw, with no Huffman coding. This keeps each alphabet small enough that its code table is cheap to transmit. Within a bucket, values are close to equally likely, so Huffman coding them would gain little.
The decoder knows which alphabet to use from context. After decoding a length symbol, the next Huffman code always comes from the distance alphabet.
Three Block Types
A DEFLATE stream is a sequence of blocks. Each block begins with a 3-bit header: one BFINAL bit that marks the last block, then 2 bits of BTYPE.
| BTYPE | Block type | Code table |
|---|---|---|
| 00 | Stored | None. Raw bytes are copied as-is |
| 01 | Fixed Huffman | Predefined in the spec, so nothing is transmitted |
| 10 | Dynamic Huffman | Code lengths transmitted in the block header |
| 11 | Reserved | Error |
The fixed code assigns 8 bits to literals 0–143, 9 bits to literals 144–255, 7 bits to symbols 256–279, and 8 bits to symbols 280–287. Every fixed distance code is 5 bits. Because the decoder already knows these lengths, it builds the canonical codes without reading any header. For short inputs this beats paying for a dynamic table.
The encoder picks a type for each block by estimating the size under each option. You can see the choice from Python by reading the first byte of a raw DEFLATE stream:
import random
import zlib
NAMES = {0: "stored", 1: "fixed", 2: "dynamic", 3: "reserved"}
def first_block_type(data, level=6):
# wbits=-15 produces a raw DEFLATE stream with no zlib header
comp = zlib.compressobj(level, zlib.DEFLATED, -15)
raw = comp.compress(data) + comp.flush()
first = raw[0]
bfinal = first & 1
btype = (first >> 1) & 0b11
return NAMES[btype], bfinal, len(raw)
random.seed(1)
words = ["the", "of", "huffman", "tree", "code", "bit", "symbol", "length"]
long_text = " ".join(random.choice(words) for _ in range(5000)).encode()
print(first_block_type(b"hello hello hello"))
print(first_block_type(long_text))
print(first_block_type(long_text, level=0))The short string usually comes out as a fixed block. The long text gets a dynamic block, because a table fitted to its skewed statistics more than pays for itself. Level 0 produces stored blocks.
How a Dynamic Block Ships Its Table
A dynamic block applies the earlier chapters' advice twice. It sends only code lengths, and it compresses those lengths too.
HLIT(5 bits) gives the number of literal/length codes minus 257.HDIST(5 bits) gives the number of distance codes minus 1.HCLEN(4 bits) gives the number of code-length codes minus 4.- The block sends the lengths of a small code-length code in 3 bits each, in the fixed order 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15. Lengths that are often zero come at the end of this order, so
HCLENcan truncate them. - The literal/length and distance code lengths are then sent with that code-length code. Its alphabet has symbols 0–15 for a literal length, 16 for "repeat the previous length 3–6 times" (2 extra bits), 17 for "3–10 zeros" (3 extra bits), and 18 for "11–138 zeros" (7 extra bits).
Run-length symbols matter because many byte values never occur in a given block, which leaves long runs of zero lengths. The format caps literal/length and distance codes at 15 bits and code-length codes at 7 bits. A real encoder must therefore produce length-limited codes. zlib does this by adjusting an ordinary Huffman tree when it overflows, which is faster than running package-merge.
JPEG: Huffman Coding Quantized Coefficients
Baseline JPEG splits the image into 8×8 blocks and applies the discrete cosine transform (DCT) to each block. It then quantizes the coefficients, which is where the loss happens. Huffman coding is the final, lossless step. As in DEFLATE, the coefficients are first reshaped into symbols that suit Huffman coding.
Symbols: Categories and Run/Size Pairs
The DC coefficient is the block's average value. It is coded as the difference from the previous block's DC. The difference is split into a size category SSSS, which is the number of bits needed for its magnitude (0–11), followed by SSSS raw extra bits. Only the category is Huffman coded, so the DC alphabet has just 12 symbols.
AC coefficients are read in zigzag order, so the high-frequency terms, which are mostly zero after quantization, come last. Each nonzero coefficient becomes a byte RRRRSSSS. RRRR is the number of zeros before the coefficient (0–15) and SSSS is its size category (1–10). Two special symbols cover the zero runs: 0x00 (EOB) means "the rest of the block is zero", and 0xF0 (ZRL) means "16 zeros". Again, only the byte is Huffman coded and the value bits follow raw.
DHT Segments Are Canonical Code Tables
JPEG stores tables in a DHT (Define Huffman Table) marker segment, 0xFFC4. Each table has a class (0 for DC, 1 for AC), an ID, 16 bytes giving the number of codes of each length from 1 to 16, and then the symbol values in code order. That is a canonical Huffman table: a count per length plus a sorted symbol list. Annex C of the standard rebuilds the codes like this:
def jpeg_codes(bits, huffval):
# bits[i] = number of codes of length i+1, for lengths 1..16
codes = {}
code = 0
k = 0
for length in range(1, 17):
for _ in range(bits[length - 1]):
codes[huffval[k]] = format(code, "0{}b".format(length))
code += 1
k += 1
code <<= 1
return codes
# Annex K example table for luminance DC differences
BITS = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
HUFFVAL = list(range(12))
for sym, c in jpeg_codes(BITS, HUFFVAL).items():
print(sym, c)
# 0 00, 1 010, 2 011, 3 100, 4 101, 5 110, 6 1110, ... 11 111111110JPEG caps codes at 16 bits, and no code may consist entirely of 1-bits. Annex K.2 describes how an encoder adjusts code lengths to meet both rules. Many encoders simply reuse the Annex K example tables, which were derived from typical images. Optimized encoding, such as libjpeg's -optimize option, makes a second pass to collect actual symbol counts and writes image-specific tables. This usually shrinks the file by a few percent with no loss of quality.
Side-by-Side Comparison
| Aspect | DEFLATE | Baseline JPEG |
|---|---|---|
| Symbols before Huffman | LZ77 literals, lengths, distances | DC size categories, AC run/size bytes |
| Number of alphabets | 2 per block (+ code-length code) | Up to 2 DC and 2 AC tables |
| Table format | Code lengths, RLE-compressed and Huffman-coded | Count per length + symbol list |
| Maximum code length | 15 bits (7 for code-length code) | 16 bits, no all-ones code |
| Built-in default | Fixed Huffman block type | Annex K example tables (conventional, not mandatory) |
| Raw extra bits | Yes, after length and distance symbols | Yes, after every category |
| Table changes | Every block | Per scan, via new DHT segments |
Common Errors When Implementing These Formats
- Treating extra bits as part of the Huffman code. In both formats, the Huffman symbol tells you how many raw bits come next. Decode the symbol first, then read the extra bits.
- Forgetting the DEFLATE single-code edge case. If a block uses only one distance code, RFC 1951 encodes it with one bit rather than zero, so the canonical rebuild produces an incomplete code. Decoders must accept this.
- Ignoring JPEG byte stuffing. Inside entropy-coded data, a
0xFFbyte is followed by a stuffed0x00so that it cannot be mistaken for a marker. Remove the stuffing before feeding bits to the Huffman decoder. - Assuming a single block or table. DEFLATE can switch tables at every block, and a JPEG file can redefine its tables between scans.
Exercise
A DEFLATE block contains 40 bytes of text. Why would an encoder likely choose a fixed Huffman block instead of a dynamic one, even though a dynamic code fitted to the text would give shorter codes for its symbols?
Show answer
A dynamic block must transmit HLIT, HDIST, HCLEN, the code-length code, and the run-length-coded lengths for both alphabets. That header often costs tens of bytes. For 40 bytes of input, the header outweighs the bits saved by better-fitted codes, so the fixed code, which costs nothing to transmit, gives a smaller block overall.
Exercise
A JPEG DHT segment has BITS = [0, 2, 1, 0, ...zeros] and HUFFVAL = [0x01, 0x00, 0x02]. List the code for each symbol.
Show answer
Length 2 has two codes: 0x01 gets 00 and 0x00 gets 01. The code counter is then 2, which shifts to 4 (binary 100) for length 3, so 0x02 gets 100. The codes are 0x01 = 00, 0x00 = 01, 0x02 = 100.
Exercise
Why does DEFLATE send the code-length code's lengths in the odd order 16, 17, 18, 0, 8, 7, 9, 6, ... rather than 0 through 18?
Show answer
The order puts the symbols most likely to be used first. These are the run-length symbols and mid-range lengths. Rarely used lengths such as 1, 2, 14, and 15 come last. HCLEN states how many entries are sent, so the encoder can cut off the trailing zero-length entries and save 3 bits for each one omitted.