Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Entropy coding: Huffman, Shannon-Fano and arithmetic coding

ProblemCompress a sequence of symbols losslessly by giving frequent symbols short codes and rare ones long codes, as close to the entropy as possible
Devised byClaude Shannon (1948) and Robert Fano (1949), Shannon-Fano coding; David Huffman (1952), optimal prefix codes; Jorma Rissanen and Richard Pasco (1976), Ian Witten, Radford Neal and John Cleary (1987), practical arithmetic coding
AccuracyHuffman is within 1 bit per symbol of the entropy, Shannon-Fano within 2; arithmetic coding reaches the entropy of its model to within a few bytes per message (tables below)
Cost for bytes and distinct symbols; arithmetic coding is several times slower per symbol than table lookup
Read firstEntropy, divergence and mutual information
APISourceCoder, try_huffman_compress, try_huffman_decompress, try_shannon_fano_compress, try_shannon_fano_decompress, try_arithmetic_compress, try_arithmetic_decompress

Overview

An entropy coder compresses by exploiting unequal symbol frequencies. Morse code already gave the common letter E a single dot. A prefix code assigns each symbol a bit string, none the prefix of another, so the concatenated codes can be decoded without separators. Shannon-Fano coding builds one top-down by splitting the symbols into halves of nearly equal probability. Huffman coding builds one bottom-up by merging the two least likely symbols, which is provably optimal among prefix codes. But any prefix code spends a whole number of bits per symbol. Arithmetic coding escapes that limit by encoding the entire message as one number in an interval that shrinks with each symbol. It reaches the entropy even for highly skewed sources. All three coders here use a static order-0 model: the byte frequencies of the whole input, stored in the header.

Where it is used

Entropy coders reach the limit set by the statistics of the data.

  • Image, audio and video compression. JPEG and MP3 end with Huffman coding; modern video codecs (H.264/H.265, AV1) use arithmetic coding of the quantised data.
  • General-purpose compressors. DEFLATE and its relatives use Huffman codes to code literals and match lengths.
  • Fax machines and telemetry. Run-length plus Huffman coding in fax; arithmetic coding in space-data compression.

History

Shannon’s 1948 paper and Robert Fano’s 1949 MIT report described the top-down splitting construction. In 1951 Fano set his information-theory students the term-paper problem of finding an optimal code. David Huffman, about to give up and sit the exam instead, found the bottom-up construction and proved it optimal. It was published in 1952 and became the entropy-coding stage of fax, JPEG, MP3 and DEFLATE. Arithmetic coding grew from ideas of Peter Elias (early 1960s, unpublished) and was made practical with finite-precision arithmetic by Jorma Rissanen and Richard Pasco (1976). Ian Witten, Radford Neal and John Cleary’s 1987 article gave the integer implementation with underflow handling followed here. Patents slowed its adoption until the 2000s. It is now standard in H.264, HEVC and modern compressors.

The idea

Prefix codes and Kraft’s inequality

To compress, give frequent symbols short codewords and rare symbols long ones. The codewords are simply written one after another, so the decoder must be able to tell where each one ends. A prefix code guarantees this: no codeword is the beginning of another, so as soon as the bits read so far form a codeword, it is the right one.

For example, for four symbols with probabilities , the code

symbolABCD
probability1/21/41/81/8
codeword010110111

is a prefix code. The string 0100110 can only be read as A, B, A, C. Its average length is bits per symbol, against 2 bits for a fixed-length code, and 1.75 bits is exactly the entropy of this source.

How short can the codewords be? Short codewords are a limited resource: a codeword of length rules out the fraction of all longer bit strings, those that begin with it. The fractions used by all the codewords cannot exceed the whole. This is Kraft’s inequality: a binary prefix code with lengths exists if and only if

Minimising the average length subject to this constraint, and ignoring for the moment that lengths must be whole numbers, gives : each symbol’s ideal length is its surprise, and then . Rounding the lengths up to whole bits, (Shannon’s code), still satisfies the inequality and costs less than one extra bit per symbol: .

Shannon-Fano coding

Sort the symbols by decreasing frequency. Split the list where the two parts’ total frequencies are as equal as possible, give the first part a 0 and the second a 1, and recurse. The result is a prefix code, usually good but not always optimal: an early split that is slightly unbalanced is never revisited.

Huffman coding

Huffman’s algorithm builds the optimal prefix code, from the bottom up. A prefix code is a binary tree whose leaves are the symbols; the codeword of a symbol is the sequence of left (0) and right (1) branches on the path from the root to its leaf.

Put every symbol in a priority queue keyed by frequency. Repeatedly remove the two least frequent nodes and join them as the two children of a new node, whose frequency is their sum, and put that node back in the queue. When one node remains, it is the root. In the example above, C and D (1/8 each) are joined first into a node of weight 1/4; that node and B (1/4) are joined into one of weight 1/2; and that is joined with A. The result is the code in the table.

Why is the greedy choice right? Two facts. First, the two least likely symbols can always be siblings at the deepest level of an optimal tree. Suppose a less likely symbol sits shallower, at depth , than a more likely symbol at depth . Swapping them changes the average length from to , a change of , so the swap never hurts. Repeating it puts the least likely symbols at the greatest depth, and in an optimal tree every leaf has a sibling leaf (otherwise its parent could be replaced by the leaf, shortening the code), so the two deepest leaves can be taken to be siblings. Second, merging those two into one symbol of probability leaves a code for one fewer symbol whose average length is smaller by exactly (the pair is now one step shorter), whatever the rest of the tree is. So an optimal tree for the original problem is an optimal tree for the merged one with the pair split again, and induction on the number of symbols proves that the greedy merge is optimal. Ties are broken by the smallest symbol in each subtree, so encoder and decoder build the same tree from the stored frequencies.

Arithmetic coding

A prefix code must spend a whole number of bits on every symbol, at least one. For a very predictable source that is far too many: a symbol of probability 0.99 deserves 0.014 bits. Arithmetic coding removes the restriction by encoding the whole message as a single number.

Divide the interval into sub-intervals, one per symbol, with widths equal to the symbol probabilities. To encode a symbol, replace the current interval by the sub-interval for that symbol, and divide that in the same proportions for the next symbol. For two symbols A (probability 0.75) and B (0.25), with A assigned the lower part, the message “AB” narrows the interval first to and then to its upper quarter, .

After symbols the interval has width , the probability of the message, and any number inside it identifies the message. Specifying a number inside an interval of width takes about bits, so the message costs about bits: the sum of the surprises of its symbols, with no rounding per symbol. On average that is the entropy.

The interval soon becomes far narrower than any floating-point number can represent, so a practical coder never holds it in full. In finite precision the interval is kept as 32-bit integers . Whenever it lies wholly in the lower or upper half, the leading bit of every number in it is known: the coder emits that bit and doubles the interval (E1, E2). When it straddles the middle within the central half, the next bit is not yet known. The coder doubles about the centre and counts a pending bit, emitted with the opposite value once the next E1 or E2 resolves it (E3). The decoder mirrors these steps. A symbol’s sub-interval must never become empty, which requires the model’s total frequency to stay below a quarter of the code range, . For larger inputs the library rescales the model.

Table 18.3. Entropy coders against the empirical entropy of synthetic sources.

source (200 000 symbols)empirical entropyHuffmanShannon-Fanoarithmetic
uniform over 256 values7.99918.00008.01317.9991
dyadic: 1/2, 1/4, 1/8, …1.99541.99551.99551.9954
binary, P(1) = 0.10.46951.00001.00000.4695
binary, P(1) = 0.010.08171.00001.00000.0817
geometric over 64 values, ratio 0.83.60533.63473.63473.6053

The figures are payload bits per symbol, excluding the stored frequency table. For a dyadic source, with probabilities , the ideal lengths are whole numbers and all three coders reach the entropy. A skewed binary source shows the prefix codes’ weakness: a symbol cannot take less than one bit, so they spend 1 bit where 0.08 suffice, while the arithmetic coder matches the entropy.

On real text

The text has 4606957 bytes and an order-0 entropy of 4.621 bits per byte. The order-0 coders all land near that figure; the dictionary coders do better by exploiting repeated words:

Table 18.4. Compression ratio and speed of each coder on the test text.

codercompressed bytesbits per bytecompress (MB/s)decompress (MB/s)
Huffman26825634.65813099
Shannon-Fano26873054.667135106
arithmetic26616024.6222924
LZ7716736152.9066756
LZ7829572515.13513129
LZW18110143.14513124
zlib, level 9 (Python)13506392.345
bzip2, level 9 (Python)9616511.670
xz/LZMA, preset 9 (Python)10110921.756

The standard compressors combine a dictionary stage with an entropy stage (zlib: LZ77 then Huffman), or use block sorting (bzip2) or context modelling with arithmetic coding (LZMA).

Algorithm

All three coders share the same framework.

Encoding.

  1. Model. Count how often each byte value occurs in the input.
  2. Header. Write the length of the input and the model: for each byte value that occurs, the value and its 32-bit count. The decoder needs these to rebuild the same code.
  3. Code the bytes, by one of the three methods below.

Shannon-Fano codes: sort the symbols by decreasing frequency. split(list): if the list has one symbol, stop; otherwise find the place that divides the list into two parts whose total frequencies are as nearly equal as possible, append a 0 to the codes of the first part and a 1 to those of the second, and split each part.

Huffman codes:

  1. put a leaf node for each symbol into a priority queue keyed by frequency;
  2. remove the two nodes of lowest frequency, make them the children of a new node whose frequency is their sum, and insert the new node;
  3. repeat until one node remains, the root;
  4. the code of each symbol is the sequence of branches, 0 or 1, on the path from the root to its leaf.

For both prefix codes, the output is the codewords of the input bytes written one after another, packed into bytes with the most significant bit first.

Arithmetic coding: compute the cumulative frequencies, which assign each symbol a sub-range of . Start with low = 0 and high at the top of the 32-bit range. For each input byte:

  1. narrow the interval to the part that corresponds to the symbol’s sub-range;
  2. renormalise: while the interval lies entirely in the lower half (E1) or the upper half (E2), emit the corresponding bit, followed by any pending bits with the opposite value, and double the interval; while it straddles the midpoint but lies within the middle half (E3), count one more pending bit and double the interval about its centre.

At the end, emit two more bits, which select a value certain to lie inside the final interval.

Decoding.

  1. Read the header and rebuild the model, and from it exactly the same code or cumulative table.
  2. Prefix codes: starting at the root of the tree, follow one branch for each input bit; on reaching a leaf, output its symbol and return to the root. Arithmetic: keep a 32-bit window of the code stream; find the symbol whose sub-range contains the window’s value, scaled to the current interval; output it; then narrow and renormalise exactly as the encoder did, shifting new bits into the window.
  3. Stop when the number of symbols given in the header has been produced.

Implementation

    while heap.len() > 1 {
        // Repeatedly merge the two lightest subtrees. That greedy step is the
        // core of the Huffman construction.
        let left = heap.pop().ok_or(ErrorsJSL::RuntimeError("Huffman heap unexpectedly emptied while building the tree."))?;
        let right = heap.pop().ok_or(ErrorsJSL::RuntimeError("Huffman heap unexpectedly emptied while building the tree."))?;

        heap.push(HeapEntry {
            frequency: left.frequency.saturating_add(right.frequency),
            min_symbol: left.min_symbol.min(right.min_symbol),
            node: HuffmanNode::Internal {
                left: Box::new(left.node),
                right: Box::new(right.node),
            },
        });
    }
    let split_index = choose_split_index(symbols);

    // Every symbol in the left half gains a `0` at this recursion depth.
    for entry in &symbols[..split_index] {
        codes[entry.symbol as usize].push(false);
    }
    // Every symbol in the right half gains a `1` at this recursion depth.
    for entry in &symbols[split_index..] {
        codes[entry.symbol as usize].push(true);
    }

    let (left, right) = symbols.split_at_mut(split_index);
    assign_codes_recursive(left, codes);
    assign_codes_recursive(right, codes);
        let range = (high - low + 1) as u128;
        let cum_low = model.cumulative[symbol_index] as u128;
        let cum_high = model.cumulative[symbol_index + 1] as u128;
        let total = model.total as u128;

        // Narrow the current interval down to the slice owned by this symbol.
        high = low + ((range * cum_high) / total - 1) as u64;
        low += ((range * cum_low) / total) as u64;

        // Renormalize whenever the interval has moved entirely into the low
        // half, high half, or the middle "underflow" band.
        loop {
            if high < HALF {
                // E1 scaling: the whole interval lies in the low half, so we
                // can safely emit a leading `0` bit.
                output_bit_plus_pending(&mut writer, false, &mut pending_bits);
            } else if low >= HALF {
                // E2 scaling: the whole interval lies in the high half, so we
                // emit a leading `1` bit and subtract that half before
                // rescaling back to the full range.
                output_bit_plus_pending(&mut writer, true, &mut pending_bits);
                low -= HALF;
                high -= HALF;
            } else if low >= FIRST_QTR && high < THIRD_QTR {
                // E3 scaling: the interval sits in the ambiguous middle band.
                // We cannot emit a stable leading bit yet, so we count one
                // "pending" bit that will be resolved later.
                pending_bits += 1;
                low -= FIRST_QTR;
                high -= FIRST_QTR;
            } else {
                break;
            }

            // After any renormalization step, stretch the interval back to the
            // full fixed-precision range so the next symbol still has room to
            // carve out a meaningful sub-interval.
            low = low.saturating_mul(2);
            high = high.saturating_mul(2).saturating_add(1);
        }
  • All six coders of this chapter implement SourceCoder (try_compress, try_decompress), so generic code can swap them. The plain *_compress and *_decompress functions return an empty vector on error.
  • The decoders validate the header (magic, table, lengths) and return an error for malformed input.
  • A single-symbol input is stored as its header alone.

In practice

//! Lossless compression with the six source coders, through the shared `SourceCoder` trait.

use lib_jsl_information::operators::entropy;
use lib_jsl_information::source_coder::{
    ArithmeticSourceCoder, HuffmanSourceCoder, Lz77SourceCoder, Lz78SourceCoder, LzwSourceCoder, ShannonFanoSourceCoder, SourceCoder,
};

fn report<C: SourceCoder>(name: &str, data: &[u8]) {
    let packed = C::try_compress(data).unwrap();
    let unpacked = C::try_decompress(&packed).unwrap();
    assert_eq!(unpacked, data);
    println!("{name:>13}: {:5} bytes ({:.2} bits per input byte)", packed.len(), 8.0 * packed.len() as f64 / data.len() as f64);
}

fn main() {
    let text = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, \
                it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness. "
        .repeat(8);
    let data = text.as_bytes();
    println!("{} bytes, order-0 entropy {:.3} bits per byte", data.len(), entropy(data));
    report::<HuffmanSourceCoder>("Huffman", data);
    report::<ShannonFanoSourceCoder>("Shannon-Fano", data);
    report::<ArithmeticSourceCoder>("arithmetic", data);
    report::<Lz77SourceCoder>("LZ77", data);
    report::<Lz78SourceCoder>("LZ78", data);
    report::<LzwSourceCoder>("LZW", data);
}
1840 bytes, order-0 entropy 3.917 bits per byte
      Huffman:  1061 bytes (4.61 bits per input byte)
 Shannon-Fano:  1062 bytes (4.62 bits per input byte)
   arithmetic:  1058 bytes (4.60 bits per input byte)
         LZ77:   176 bytes (0.77 bits per input byte)
         LZ78:  1708 bytes (7.43 bits per input byte)
          LZW:   984 bytes (4.28 bits per input byte)

On a short message the stored model is a large overhead: 27 symbols × 5 bytes, an eighth of the output. The repeated text suits the dictionary coders, LZ77 above all.

Strengths

  • Simple, fast prefix coding (Huffman is optimal among symbol-by-symbol codes); arithmetic coding reaches the model’s entropy.
  • Self-contained streams with validated headers.

Weaknesses

  • An order-0 static model ignores context, and its stored table is costly for short inputs; adaptive and context models do far better.
  • Arithmetic coding is slower and harder to implement correctly.

Exercises

  1. Prove Kraft’s inequality for prefix codes.
  2. Construct the Huffman code for probabilities (0.4, 0.2, 0.2, 0.1, 0.1) and find its average length and the entropy.
  3. Find a distribution on which Shannon-Fano coding is worse than Huffman coding.
  4. Show that the Huffman code of a dyadic distribution has exactly.
  5. Encode “ABA” with , by exact interval arithmetic, and find the shortest binary fraction inside the final interval.
Hints and answers
  1. Kraft: if the codeword has length and the code is prefix-free, the subintervals of assigned to the words are disjoint, so .
  2. Huffman for gives lengths such as with average bits; the entropy is bits.
  3. Take . Shannon-Fano splits from (the most even split) and gives lengths with average bits; Huffman gives with average bits.
  4. For dyadic probabilities , Huffman’s tree is full and the lengths meet the Kraft sum with equality.
  5. takes ; then takes ; then takes . The shortest binary fraction in it is (two bits).

Further reading

  • D. A. Huffman, “A method for the construction of minimum-redundancy codes”, Proceedings of the IRE 40 (1952) 1098–1101.
  • I. H. Witten, R. M. Neal and J. G. Cleary, “Arithmetic coding for data compression”, Communications of the ACM 30 (1987) 520–540.
  • T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed., Wiley, 2006, chapter 5.
  • D. Salomon and G. Motta, Handbook of Data Compression, 5th ed., Springer, 2010.