Search topics and sections

Data compression, also called source coding, is the practice of encoding information using fewer bits than the original representation. Compressed data takes less space to store and less time to send, and a decoder turns it back into usable form. Images on the web, digital television, and some file systems rely on it.[1]

Compression comes in two kinds. Lossless compression rebuilds the original exactly, while lossy compression rebuilds only a close approximation, which is acceptable for images and sound. Both kinds find patterns in the data and give likely data short codes and unlikely data long ones.[1]

How compression works

Redundancy

Most real data is partly predictable. In English, some letters are far more common than others, and each letter depends on those before it.

Claude Shannon estimated that ordinary English, judged over spans of about eight letters, is roughly 50% redundant. In his words, "half of what we write is determined by the structure of the language and half is chosen freely."[2]

A compressor removes this redundancy. The simplest example is run-length encoding, which replaces a run of equal values with one value and a count. The string acccbbaaabb becomes (a,1), (c,3), (b,2), (a,3), (b,2).[1]

Model and coder

A compression method is usually described as two parts working together.[1]

  • The model estimates how likely each possible next piece of data is, using what it knows or has learned about the input.
  • The coder turns those probabilities into bits. It gives short codes to likely data and long codes to unlikely data.

The decoder runs the same model as the encoder. For that reason, the model may only use data that has already been sent.[1]

Models range from simple letter counts to detailed statistics of context. Classic coders, by contrast, are almost all based on Huffman coding or arithmetic coding.[1]

Compression and decompression pipeline Original data Model Coder Encoder Compressed bits Model Coder Decoder Lossless: exact copy Lossy: close approximation
A compressor uses a model and a coder to turn the original data into fewer bits. The decoder uses the same model to rebuild the data, either as an exact copy (lossless) or as a close approximation (lossy).

Lossless and lossy compression

Lossless Lossy
Output after decoding Exact copy of the input Approximation of the input
Typical data Text, programs, data files Photos, sound, video
Main tools Entropy coding, dictionary methods, context models Quantization, transforms, models of perception, then a lossless stage
Examples gzip, PNG, bzip2, Zstandard JPEG, MP3, MPEG video

Lossy does not mean that random pixels go missing. It usually means dropping detail that people are unlikely to notice, such as very high frequencies or noise. Lossy image methods can often compress about twice as well as lossless ones with no visible loss of quality.[1]

Most lossy systems end with a lossless stage. JPEG, for example, first rounds off detail and then compresses the result with Huffman or arithmetic coding.[3]

No method compresses everything

No lossless method can shrink every possible input. The proof is a simple counting argument.[4] Count the strings that are shorter than nn bits:

1+2+4+⋯+2n−1=2n−1<2n1 + 2 + 4 + \cdots + 2^{n-1} = 2^n - 1 < 2^n

The left side counts every string shorter than nn bits, including the empty string, and 2n2^n is the number of strings of exactly nn bits. If every nn-bit input shrank, two inputs would have to share an output, and the decoder could not tell them apart. This is an instance of the pigeonhole principle.

So if a method shortens some inputs, it must lengthen others.[1] Practical formats keep the loss small. The Deflate format, for example, expands data by at most 5 bytes per 32K-byte block, about 0.015% for large inputs.[4]

Every compressor therefore assumes that some inputs are more likely than others, such as text with repeated words or images with large plain areas.[1] Random data does not fit that assumption, since a uniformly random string is almost always incompressible.[5]

Counting argument for lossless compression of 3-bit strings All 3-bit inputs (8) All shorter outputs (7) 000001010011100101110111 empty0100011011 8 inputs, only 7 shorter strings No room left
No lossless compressor can shorten every input. There are 8 three-bit strings but only 7 strings shorter than 3 bits, counting the empty string, so at least one input has no shorter output left to map to.

Limits from information theory

The limits of compression come from information theory, which Shannon set out in his 1948 paper "A Mathematical Theory of Communication".[2]

Entropy

Shannon measured the average information produced by a source with a quantity he called entropy.[2] For a source that emits each symbol independently, with symbol ii having probability pip_i, the entropy is

H=−∑ipilog⁡2piH = -\sum_{i} p_i \log_2 p_i

Here HH is in bits per symbol because the logarithm is base 2, and the sum runs over all symbols with pi>0p_i > 0. Entropy is highest when the probabilities are even and zero when the next symbol is certain.[1]

Shannon gave a worked example. A source picks A, B, C, or D independently with probabilities 1/2, 1/4, 1/8, and 1/8, so its entropy is 7/4 bits per symbol.[2] The code A = 0, B = 10, C = 110, D = 111 reaches this limit exactly, since its average length is 12⋅1+14⋅2+18⋅3+18⋅3=1.75\tfrac12 \cdot 1 + \tfrac14 \cdot 2 + \tfrac18 \cdot 3 + \tfrac18 \cdot 3 = 1.75 bits.[2]

Source coding theorem

Shannon's source coding theorem makes entropy the limit for lossless compression. In Shannon's form, a source with entropy HH bits per symbol can be sent over a noiseless channel of capacity CC bits per second at an average rate as close as desired to C/HC/H symbols per second, but no faster.[2]

For codes that give each symbol its own codeword, entropy bounds the average codeword length Lˉ\bar{L} from below, and the best such codes stay within one bit of it:

H≤Lˉ≤H+1H \le \bar{L} \le H + 1

The lower bound holds for every uniquely decodable code, meaning one whose bit stream splits into codewords in only one way. Every optimal prefix code, such as a Huffman code, satisfies the upper bound; a prefix code is one in which no codeword is the start of another.[1] Coding kk symbols at a time cuts the extra cost from 1 bit per symbol to 1/k1/k bits per symbol, when the symbols come from the same distribution.[1]

The lower bound rests on the Kraft-McMillan inequality, ∑w2−ℓ(w)≤1\sum_w 2^{-\ell(w)} \le 1. Every uniquely decodable code with codeword lengths ℓ(w)\ell(w) satisfies it.[1]

Context lowers entropy

Using context can only lower entropy. If the next symbol depends on what came before, the conditional entropy H(S∣C)H(S \mid C) is less than H(S)H(S), and the two are equal only when the symbol is independent of the context.[1] Estimates for English show how much this matters.[1]

Model of English text Bits per character
Fixed-length code for 96 printable characters 7
All 96 characters equally likely 6.6
Single-letter frequencies about 4.5
Blocks of 8 characters 2.4
Very long blocks (estimate) about 1.3 or lower

The last value cannot be measured directly, because no body of text is large enough to count such long strings.[1]

Kolmogorov complexity

Kolmogorov complexity measures the information in a single string rather than in a source. It is the length of the shortest program that prints the string and halts.[5] A string is called incompressible when no program for it is much shorter than the string itself.

Counting shows that most strings are incompressible. At most a fraction 1/2d−11/2^{d-1} of the strings of a given length can be compressed by dd bits.[5] Kolmogorov complexity is not computable, so no program can find the shortest description of every string.[5]

Rate-distortion theory

For lossy compression, the question is how few bits are needed for a given quality. Shannon addressed it in 1959 with the rate-distortion function R(d)R(d).[6]

R(d)R(d) is the lowest rate at which a source can be coded while keeping the average distortion at or below dd. Shannon showed that when a distortion dd can be tolerated, the source acts like one with information rate R(d)R(d).[6] Allowing more distortion never raises the required rate, since a code that meets a strict limit also meets a looser one.

Entropy coding

Entropy coding is the coder stage. It turns probabilities into bits with an average length close to the entropy.

Huffman coding

David Huffman invented his method in a term paper for Robert Fano's information theory course at MIT in 1951, and published it in 1952.[7][8] It builds a minimum-redundancy code, one with the lowest possible average length for a given set of message probabilities.[8] The steps are:[1]

  1. Make one single-node tree for each symbol, weighted by its probability.
  2. Take the two trees with the lowest weights.
  3. Join them under a new root whose weight is the sum of theirs.
  4. Repeat steps 2 and 3 until one tree remains.

The path from the root to each symbol, with 0 for one branch and 1 for the other, gives its codeword.[1]

Huffman code tree for four symbols11/21/4A p = 1/2 code 0B p = 1/4 code 10C p = 1/8 code 110D p = 1/8 code 111010101Average length = 1.75 bits = entropy
A binary prefix-code tree for four symbols with probabilities 1/21/2, 1/41/4, 1/81/8 and 1/81/8, which gives the codewords 0, 10, 110 and 111. The average codeword length is 1.75 bits, which equals the entropy of the source.

Huffman coding is a common back end for compressors, including gzip and JPEG.[1] Its weakness is that every symbol costs at least one whole bit, which wastes space when one symbol is very likely.[1]

Arithmetic coding

Arithmetic coding avoids that limit by coding a whole sequence as one number. It starts with the interval from 0 to 1 and, for each symbol, shrinks the interval to the part assigned to that symbol, in proportion to its probability.[1] Any number inside the final interval identifies the whole sequence, and a short binary fraction inside it becomes the output.[1]

Arithmetic coding of the sequence b a b c abc abc abc abc babc 0 0.2 0.7 1 0.2 0.3 0.55 0.7 0.2 0.22 0.27 0.3 0.22 0.23 0.255 0.27 Final interval [0.255, 0.27) identifies b a b c
Arithmetic coding of the sequence b, a, b, c with P(a)=0.2P(a)=0.2, P(b)=0.5P(b)=0.5, P(c)=0.3P(c)=0.3. Each symbol narrows the current interval to its subinterval, and the final interval [0.255,0.27)[0.255, 0.27) identifies the whole sequence.

The width of the final interval is the product of the symbol probabilities, so the output comes within 2 bits of the total information in the sequence.[1] In an extreme case, 1,000 symbols that each have probability 0.999 need at least 1,000 bits with a Huffman code but only 3 bits with arithmetic coding.[1]

The idea of arithmetic coding goes back to Shannon's 1948 paper and was later rediscovered by Elias.[9] Jorma Rissanen and Pasco published practical versions in 1976.[10][11] Later work, including that of Witten, Neal, and Cleary, refined ways to run it with fixed-precision arithmetic and to output bits as it goes.[9]

Asymmetric numeral systems

Asymmetric numeral systems (ANS) are another family of entropy coders. They carry a state value from one symbol to the next, so decoding runs in the opposite direction to encoding.[12] The Zstandard format uses an ANS-based coder called Finite State Entropy for lengths and offsets, and Huffman coding for literal bytes.[12]

Modeling and dictionary methods

Prediction and context

Better models give the coder sharper probabilities. Common approaches are:[1]

  • Residual coding predicts each value from its neighbors and codes only the difference, which is usually small. JPEG-LS predicts each pixel from nearby pixels above and to the left.
  • Context modeling keeps separate statistics for each context. Prediction by partial matching (PPM) predicts each character from the few characters before it and falls back to shorter contexts when a context is new.
  • Adaptive models update their statistics as they go, so no probability table needs to be sent.

In Blelloch's survey, variants of PPM gave the best or nearly the best compression ratios but were not very fast.[1] PNG images also use a form of prediction, applying a reversible filter such as the Paeth predictor to each row before compression.[13]

Dictionary methods

Dictionary methods replace repeated strings with references to earlier copies. Jacob Ziv and Abraham Lempel published the two main variants in 1977 and 1978, known as LZ77 and LZ78.[14][15][1]

  • LZ77 searches a sliding window of recent data for the longest match and refers back to it by position and length. gzip and ZIP are based on it.[1]
  • LZ78 builds an explicit dictionary of strings seen so far and outputs dictionary indices. Its variant Lempel-Ziv-Welch (LZW), published by Terry Welch in 1984, is used in Unix compress and GIF images.[1][16] The V.42bis modem standard uses the same kind of dictionary, which grows by adding a matched string plus the next character.[17]

In 2004 the IEEE named the Lempel-Ziv algorithm a milestone in electronics and computer engineering, saying it "made a significant contribution to making the internet an effective means of global communication."[18]

Deflate, designed by Phil Katz, combines LZ77 with Huffman coding.[4] It refers back to repeated strings up to 32K bytes earlier and up to 258 bytes long, and codes literals, lengths, and distances with Huffman codes. English text usually compresses by a factor of 2.5 to 3.[4]

PNG images store their pixel data as a zlib stream compressed with Deflate.[13]

LZ77 back-reference in abracadabra 1234567891011 abracadabra distance 7, length 4 literals Input Output abracad <length 4, distance 7> the repeat is replaced by a pointer to the earlier copy
LZ77 encodes 'abracadabra' as seven literals followed by one back-reference. The final 'abra' starts 7 positions back and is 4 characters long, so it becomes the pointer ⟨4,7⟩\langle 4, 7 \rangle (length 4, distance 7).

Block sorting

The Burrows-Wheeler transform (BWT) takes a different path. Michael Burrows and David Wheeler described it in a 1994 report.[19] It reorders a block of text so that characters with similar preceding contexts end up next to each other.[1]

Repeated substrings then become runs of repeated characters, which are easy to compress, and the original can be rebuilt from the reordered block.[19] A move-to-front step turns those runs into small numbers before entropy coding.[1] The bzip2 program uses the BWT with Huffman coding, and its compression approaches that of the PPM family.[20]

Lossy techniques

Lossy methods depend heavily on the kind of media, so image compression works very differently from sound compression.[1] Most combine the tools below.

Quantization

Quantization maps many input values to fewer output values. Dropping the lowest two bits of an 8-bit number is one example. Because the mapping is many-to-one, it cannot be undone, and in JPEG it is the main source of loss.[1]

Scalar quantization treats each value alone. Vector quantization maps groups of values, such as the three color values of a pixel, to the nearest of a set of representative points. It works best when the values in a group are correlated.[1]

Transform coding

Transform coding rewrites data as a weighted sum of fixed basis patterns, such as cosine waves. The weight of each pattern is called a coefficient.[1]

A good transform removes the correlation between neighboring values, makes many coefficients small, and separates terms that matter more to perception from terms that matter less.[1] The small or less important coefficients can then be stored coarsely or dropped with little visible loss.

The discrete cosine transform (DCT) is one of the most common transforms for images. It is used more than the discrete Fourier transform partly because it does not assume the data repeats, so it needs smaller high-frequency terms.[1]

JPEG

JPEG is the standard example of transform coding. Its DCT-based processes, defined in ITU-T Recommendation T.81, are lossy.[3] The main steps are:

  1. Optionally convert the color image to one brightness channel and two color channels, and store the color channels at lower resolution, since getting brightness right matters more to perception.[1]
  2. Split each channel into 8×8 blocks.[3]
  3. Apply the DCT to each block, giving 64 coefficients. One is the DC coefficient, whose frequency is zero in both directions, and the other 63 are AC coefficients, which have a nonzero frequency in at least one direction.[3]
  4. Quantize each coefficient using one of 64 values from a quantization table. High frequencies, to which the eye is less sensitive, usually get coarser steps.[3][1]
  5. Read the coefficients in zigzag order so that most zeros end up together at the end, and code the runs of zeros.[1]
  6. Compress the result with Huffman or arithmetic coding.[3]

The standard sets no default quantization tables, so applications choose values that suit their images, displays, and viewing conditions.[3]

JPEG lossy encoder pipeline Image Split into 8×8 blocks DCT 1 DC 63 AC Quantize main loss Zigzag scan, code zero runs Huffman or arithmetic coding Compressed file DC, low frequency High frequency
The JPEG lossy encoder splits an image into 8×8 blocks and turns each block into 64 DCT coefficients: one DC coefficient, whose frequency is zero in both directions, and 63 AC coefficients with higher frequencies. It then quantizes them, which is the step that loses data, scans them in zigzag order to code runs of zeros, and entropy-codes the result. The inset shows the zigzag path from the DC coefficient at the top left to the highest frequency at the bottom right.

Perceptual audio coding

Perceptual coding uses knowledge from psychoacoustics, the study of how people hear, to compress sound without audible change.[21] Its key effect is auditory masking, in which louder sounds hide softer sounds close to them in frequency or time.[22] Coders use masking to hide their coding error.[22]

The masking threshold around a loud sound has a shallow slope toward higher frequencies and a steeper slope toward lower frequencies.[22]

Auditory masking Loud tone (masker) Softer tone: masked (inaudible) Masking threshold Audible Coding error can hide here Frequency Sound level
In auditory masking, a loud tone raises the masking threshold at nearby frequencies. The threshold falls steeply toward lower frequencies and more gradually toward higher ones. Softer tones below the threshold cannot be heard, so a perceptual coder can put coding error there.

MP3, formally MPEG-1 Layer 3, is the best-known perceptual audio format. It was defined in 1991.[21] Its best trade-off between size and quality is around 1.33 bits per audio sample, which is 128 kbit/s for a stereo signal at 48 kHz.[21]

Video coding

Video adds another kind of redundancy, since neighboring frames are usually very similar. MPEG video coders use three frame types to exploit this.[1]

  • I-frames are coded as standalone images, using a variant of JPEG (intra-frame coding). They let a player start decoding without going back to earlier frames.
  • P-frames are predicted from the previous I- or P-frame.
  • B-frames are predicted from the previous I- or P-frame, the next one, or both.

To predict a block, the encoder searches the reference frame for the closest-matching block, which may be shifted to follow motion. It sends the shift, called a motion vector, plus the coded difference between the two blocks.[1] This is motion compensation, and in MPEG it works on 16×16 blocks.[1]

I, P and B frames in display order and transmission order Display order I0 B1 B2 P3 B4 B5 P6 B7 B8 I9 Transmission order I0 P3 B1 B2 P6 B4 B5 I9 B7 B8 I P B Coded alone Predicted from earlier frame Predicted from both sides
In a group of pictures, I-frames are coded alone, P-frames are predicted from the previous I- or P-frame, and B-frames are predicted from the nearest I- or P-frame on each side. Because a B-frame needs the later I- or P-frame before it can be decoded, the encoder sends frames in a different order from the one in which they are displayed.

Because a B-frame depends on a later frame, the encoder sends frames out of display order.[1] In one textbook example for MPEG-1, I-, P-, and B-frames compressed about 7:1, 20:1, and 50:1, for an average of 27:1. MPEG-1 was designed to fit video and stereo audio into about 1.5 Mbit/s, and MPEG-2 was later adopted for high-definition television.[1]

Artifacts

Lossy coding leaves visible or audible errors when pushed too far. JPEG at high compression shows odd effects along the edges of its 8×8 blocks, and wavelet methods appear to give more pleasing results at those ratios.[1] Such errors are called compression artifacts.

Measuring compression

Methods are judged on several things at once.[1]

  • The size of the compressed output.
  • The time to compress and the time to decompress.
  • How well the method works across different kinds of data.
  • For lossy methods, the quality of the result.

Size is reported as a compression ratio, such as 27:1, or for text as bits per character, where plain 8-bit text starts at 8. The Calgary corpus, made up mostly of English text, is a standard benchmark.[1] The table shows results on it for several methods, with lower values meaning better compression.[1]

Method Bits per character
LZ77 (Ziv and Lempel) 3.94
LZMW 3.32
gzip 2.71
PPMC 2.48
Burrows-Wheeler 2.29
BOA 1.99
RK 1.89

History

Year Event
1948 Shannon defines entropy and proves the source coding theorem.[2]
1952 Huffman publishes minimum-redundancy codes.[8]
1959 Shannon introduces the rate-distortion function for lossy coding.[6]
1976 Rissanen and Pasco publish practical arithmetic coding.[10][11]
1977 Ziv and Lempel publish LZ77.[14]
1978 Ziv and Lempel publish LZ78.[15]
1984 Welch publishes LZW.[16]
1991 MPEG-1 Layer 3 (MP3) is defined.[21]
1992 JPEG is published as ITU-T Recommendation T.81.[3]
1994 Burrows and Wheeler describe block-sorting compression.[19]
1996 Deflate is published as RFC 1951.[4]
2006 Marcus Hutter launches a prize for compressing Wikipedia text.[23]

Compression and prediction

A model that predicts data well can be turned into a lossless compressor, and a compressor can be turned into a predictor.[24] In the model-and-coder picture, the model supplies the probabilities and a coder such as an arithmetic coder turns them into bits.[1]

This link motivates the Hutter Prize for lossless compression of Wikipedia text. Its organizer, Marcus Hutter, argues that compressing well is closely related to acting intelligently.[23]

The prize started in 2006 at 50,000 euros, using enwik8, a 100 MB extract of Wikipedia. In 2020 it was raised to 500,000 euros and switched to enwik9, a 1 GB extract.[23]

In 2023, Delétang and colleagues showed that large language models are strong general compressors. Their Chinchilla 70B model, trained mainly on text, compressed ImageNet image patches to 43.4% of their raw size and LibriSpeech audio to 16.4%, beating PNG (58.5%) and FLAC (30.3%).[24]

Such compressors are still very slow. A 2024 study reports that LLMZip, using the Llama3-8B model, needed 9.5 days to compress 10 MB of text.[25]

References

  1. Introduction to Data Compression, Guy E. Blelloch, Carnegie Mellon University, 2013.
  2. A Mathematical Theory of Communication, C. E. Shannon, Bell System Technical Journal, 1948.
  3. Recommendation T.81: Digital Compression and Coding of Continuous-tone Still Images, CCITT (ITU-T), 1992.
  4. RFC 1951: DEFLATE Compressed Data Format Specification version 1.3, IETF, 1996.
  5. Lecture 17: Kolmogorov Complexity, Abraham Ladha, Georgia Institute of Technology, 2024.
  6. Coding Theorems for a Discrete Source With a Fidelity Criterion, C. E. Shannon, IRE National Convention Record, 1959.
  7. David A. Huffman (editorial), Resonance, 2006.
  8. A Method for the Construction of Minimum-Redundancy Codes, D. A. Huffman, Proceedings of the IRE (reprinted in Resonance), 1952.
  9. Practical Implementations of Arithmetic Coding, P. G. Howard and J. S. Vitter, in Image and Text Compression, Kluwer, 1992.
  10. Generalized Kraft Inequality and Arithmetic Coding, J. J. Rissanen, IBM Journal of Research and Development, 1976.
  11. Data Compression, Section 3: Static Defined-Word Schemes, D. A. Lelewer and D. S. Hirschberg, ACM Computing Surveys, 1987.
  12. RFC 8878: Zstandard Compression and the application/zstd Media Type, IETF, 2021.
  13. Portable Network Graphics (PNG) Specification (Third Edition), W3C, 2025.
  14. A Universal Algorithm for Sequential Data Compression, J. Ziv and A. Lempel, IEEE Transactions on Information Theory IT-23(3), 1977.
  15. Compression of Individual Sequences via Variable-Rate Coding, J. Ziv and A. Lempel, IEEE Transactions on Information Theory IT-24(5), 1978.
  16. A Technique for High-Performance Data Compression, T. A. Welch, Computer 17(6), 1984.
  17. Recommendation V.42 bis: Data compression procedures for data circuit terminating equipment (DCE) using error correction procedures, ITU-T, 1990.
  18. Dist. Prof. Jacob Ziv 1931-2023, Technion, 2023.
  19. Burrows-Wheeler transform, Dictionary of Algorithms and Data Structures, NIST, 2022.
  20. bzip2 and libbzip2, version 1.0.8, Julian Seward, 2019.
  21. MP3 and AAC Explained, Karlheinz Brandenburg, AES 17th International Conference, 1999.
  22. Perceptual Audio Coding: A 40-Year Historical Perspective, arXiv, 2025.
  23. 500'000€ Prize for Compressing Human Knowledge, Marcus Hutter, 2020.
  24. Language Modeling Is Compression, G. Delétang et al., arXiv, 2023.
  25. FineZip: Pushing the Limits of Large Language Models for Practical Lossless Text Compression, arXiv, 2024.

Figure