1205194Sdelphij1. Compression algorithm (deflate)
2205194Sdelphij
3205194SdelphijThe deflation algorithm used by gzip (also zip and zlib) is a variation of
4205194SdelphijLZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
5205194Sdelphijthe input data.  The second occurrence of a string is replaced by a
6205194Sdelphijpointer to the previous string, in the form of a pair (distance,
7205194Sdelphijlength).  Distances are limited to 32K bytes, and lengths are limited
8205194Sdelphijto 258 bytes. When a string does not occur anywhere in the previous
9205194Sdelphij32K bytes, it is emitted as a sequence of literal bytes.  (In this
10205194Sdelphijdescription, `string' must be taken as an arbitrary sequence of bytes,
11205194Sdelphijand is not restricted to printable characters.)
12205194Sdelphij
13205194SdelphijLiterals or match lengths are compressed with one Huffman tree, and
14205194Sdelphijmatch distances are compressed with another tree. The trees are stored
15205194Sdelphijin a compact form at the start of each block. The blocks can have any
16205194Sdelphijsize (except that the compressed data for one block must fit in
17205194Sdelphijavailable memory). A block is terminated when deflate() determines that
18205194Sdelphijit would be useful to start another block with fresh trees. (This is
19205194Sdelphijsomewhat similar to the behavior of LZW-based _compress_.)
20205194Sdelphij
21205194SdelphijDuplicated strings are found using a hash table. All input strings of
22205194Sdelphijlength 3 are inserted in the hash table. A hash index is computed for
23205194Sdelphijthe next 3 bytes. If the hash chain for this index is not empty, all
24205194Sdelphijstrings in the chain are compared with the current input string, and
25205194Sdelphijthe longest match is selected.
26205194Sdelphij
27205194SdelphijThe hash chains are searched starting with the most recent strings, to
28205194Sdelphijfavor small distances and thus take advantage of the Huffman encoding.
29205194SdelphijThe hash chains are singly linked. There are no deletions from the
30205194Sdelphijhash chains, the algorithm simply discards matches that are too old.
31205194Sdelphij
32205194SdelphijTo avoid a worst-case situation, very long hash chains are arbitrarily
33205194Sdelphijtruncated at a certain length, determined by a runtime option (level
34205194Sdelphijparameter of deflateInit). So deflate() does not always find the longest
35205194Sdelphijpossible match but generally finds a match which is long enough.
36205194Sdelphij
37205194Sdelphijdeflate() also defers the selection of matches with a lazy evaluation
38205194Sdelphijmechanism. After a match of length N has been found, deflate() searches for
39205194Sdelphija longer match at the next input byte. If a longer match is found, the
40205194Sdelphijprevious match is truncated to a length of one (thus producing a single
41205194Sdelphijliteral byte) and the process of lazy evaluation begins again. Otherwise,
42205194Sdelphijthe original match is kept, and the next match search is attempted only N
43205194Sdelphijsteps later.
44205194Sdelphij
45205194SdelphijThe lazy match evaluation is also subject to a runtime parameter. If
46205194Sdelphijthe current match is long enough, deflate() reduces the search for a longer
47205194Sdelphijmatch, thus speeding up the whole process. If compression ratio is more
48205194Sdelphijimportant than speed, deflate() attempts a complete second search even if
49205194Sdelphijthe first match is already long enough.
50205194Sdelphij
51205194SdelphijThe lazy match evaluation is not performed for the fastest compression
52205194Sdelphijmodes (level parameter 1 to 3). For these fast modes, new strings
53205194Sdelphijare inserted in the hash table only when no match was found, or
54205194Sdelphijwhen the match is not too long. This degrades the compression ratio
55205194Sdelphijbut saves time since there are both fewer insertions and fewer searches.
56205194Sdelphij
57205194Sdelphij
58205194Sdelphij2. Decompression algorithm (inflate)
59205194Sdelphij
60205194Sdelphij2.1 Introduction
61205194Sdelphij
62205194SdelphijThe key question is how to represent a Huffman code (or any prefix code) so
63205194Sdelphijthat you can decode fast.  The most important characteristic is that shorter
64205194Sdelphijcodes are much more common than longer codes, so pay attention to decoding the
65205194Sdelphijshort codes fast, and let the long codes take longer to decode.
66205194Sdelphij
67205194Sdelphijinflate() sets up a first level table that covers some number of bits of
68205194Sdelphijinput less than the length of longest code.  It gets that many bits from the
69205194Sdelphijstream, and looks it up in the table.  The table will tell if the next
70205194Sdelphijcode is that many bits or less and how many, and if it is, it will tell
71205194Sdelphijthe value, else it will point to the next level table for which inflate()
72205194Sdelphijgrabs more bits and tries to decode a longer code.
73205194Sdelphij
74205194SdelphijHow many bits to make the first lookup is a tradeoff between the time it
75205194Sdelphijtakes to decode and the time it takes to build the table.  If building the
76205194Sdelphijtable took no time (and if you had infinite memory), then there would only
77205194Sdelphijbe a first level table to cover all the way to the longest code.  However,
78205194Sdelphijbuilding the table ends up taking a lot longer for more bits since short
79205194Sdelphijcodes are replicated many times in such a table.  What inflate() does is
80205194Sdelphijsimply to make the number of bits in the first table a variable, and  then
81205194Sdelphijto set that variable for the maximum speed.
82205194Sdelphij
83205194SdelphijFor inflate, which has 286 possible codes for the literal/length tree, the size
84205194Sdelphijof the first table is nine bits.  Also the distance trees have 30 possible
85205194Sdelphijvalues, and the size of the first table is six bits.  Note that for each of
86205194Sdelphijthose cases, the table ended up one bit longer than the ``average'' code
87205194Sdelphijlength, i.e. the code length of an approximately flat code which would be a
88205194Sdelphijlittle more than eight bits for 286 symbols and a little less than five bits
89205194Sdelphijfor 30 symbols.
90205194Sdelphij
91205194Sdelphij
92205194Sdelphij2.2 More details on the inflate table lookup
93205194Sdelphij
94205194SdelphijOk, you want to know what this cleverly obfuscated inflate tree actually
95205194Sdelphijlooks like.  You are correct that it's not a Huffman tree.  It is simply a
96205194Sdelphijlookup table for the first, let's say, nine bits of a Huffman symbol.  The
97205194Sdelphijsymbol could be as short as one bit or as long as 15 bits.  If a particular
98205194Sdelphijsymbol is shorter than nine bits, then that symbol's translation is duplicated
99205194Sdelphijin all those entries that start with that symbol's bits.  For example, if the
100205194Sdelphijsymbol is four bits, then it's duplicated 32 times in a nine-bit table.  If a
101205194Sdelphijsymbol is nine bits long, it appears in the table once.
102205194Sdelphij
103205194SdelphijIf the symbol is longer than nine bits, then that entry in the table points
104205194Sdelphijto another similar table for the remaining bits.  Again, there are duplicated
105205194Sdelphijentries as needed.  The idea is that most of the time the symbol will be short
106205194Sdelphijand there will only be one table look up.  (That's whole idea behind data
107205194Sdelphijcompression in the first place.)  For the less frequent long symbols, there
108205194Sdelphijwill be two lookups.  If you had a compression method with really long
109205194Sdelphijsymbols, you could have as many levels of lookups as is efficient.  For
110205194Sdelphijinflate, two is enough.
111205194Sdelphij
112205194SdelphijSo a table entry either points to another table (in which case nine bits in
113205194Sdelphijthe above example are gobbled), or it contains the translation for the symbol
114205194Sdelphijand the number of bits to gobble.  Then you start again with the next
115205194Sdelphijungobbled bit.
116205194Sdelphij
117205194SdelphijYou may wonder: why not just have one lookup table for how ever many bits the
118205194Sdelphijlongest symbol is?  The reason is that if you do that, you end up spending
119205194Sdelphijmore time filling in duplicate symbol entries than you do actually decoding.
120205194SdelphijAt least for deflate's output that generates new trees every several 10's of
121205194Sdelphijkbytes.  You can imagine that filling in a 2^15 entry table for a 15-bit code
122205194Sdelphijwould take too long if you're only decoding several thousand symbols.  At the
123205194Sdelphijother extreme, you could make a new table for every bit in the code.  In fact,
124205194Sdelphijthat's essentially a Huffman tree.  But then you spend too much time
125205194Sdelphijtraversing the tree while decoding, even for short symbols.
126205194Sdelphij
127205194SdelphijSo the number of bits for the first lookup table is a trade of the time to
128205194Sdelphijfill out the table vs. the time spent looking at the second level and above of
129205194Sdelphijthe table.
130205194Sdelphij
131205194SdelphijHere is an example, scaled down:
132205194Sdelphij
133205194SdelphijThe code being decoded, with 10 symbols, from 1 to 6 bits long:
134205194Sdelphij
135205194SdelphijA: 0
136205194SdelphijB: 10
137205194SdelphijC: 1100
138205194SdelphijD: 11010
139205194SdelphijE: 11011
140205194SdelphijF: 11100
141205194SdelphijG: 11101
142205194SdelphijH: 11110
143205194SdelphijI: 111110
144205194SdelphijJ: 111111
145205194Sdelphij
146205194SdelphijLet's make the first table three bits long (eight entries):
147205194Sdelphij
148205194Sdelphij000: A,1
149205194Sdelphij001: A,1
150205194Sdelphij010: A,1
151205194Sdelphij011: A,1
152205194Sdelphij100: B,2
153205194Sdelphij101: B,2
154205194Sdelphij110: -> table X (gobble 3 bits)
155205194Sdelphij111: -> table Y (gobble 3 bits)
156205194Sdelphij
157205194SdelphijEach entry is what the bits decode as and how many bits that is, i.e. how
158205194Sdelphijmany bits to gobble.  Or the entry points to another table, with the number of
159205194Sdelphijbits to gobble implicit in the size of the table.
160205194Sdelphij
161205194SdelphijTable X is two bits long since the longest code starting with 110 is five bits
162205194Sdelphijlong:
163205194Sdelphij
164205194Sdelphij00: C,1
165205194Sdelphij01: C,1
166205194Sdelphij10: D,2
167205194Sdelphij11: E,2
168205194Sdelphij
169205194SdelphijTable Y is three bits long since the longest code starting with 111 is six
170205194Sdelphijbits long:
171205194Sdelphij
172205194Sdelphij000: F,2
173205194Sdelphij001: F,2
174205194Sdelphij010: G,2
175205194Sdelphij011: G,2
176205194Sdelphij100: H,2
177205194Sdelphij101: H,2
178205194Sdelphij110: I,3
179205194Sdelphij111: J,3
180205194Sdelphij
181205194SdelphijSo what we have here are three tables with a total of 20 entries that had to
182205194Sdelphijbe constructed.  That's compared to 64 entries for a single table.  Or
183205194Sdelphijcompared to 16 entries for a Huffman tree (six two entry tables and one four
184205194Sdelphijentry table).  Assuming that the code ideally represents the probability of
185205194Sdelphijthe symbols, it takes on the average 1.25 lookups per symbol.  That's compared
186205194Sdelphijto one lookup for the single table, or 1.66 lookups per symbol for the
187205194SdelphijHuffman tree.
188205194Sdelphij
189205194SdelphijThere, I think that gives you a picture of what's going on.  For inflate, the
190205194Sdelphijmeaning of a particular symbol is often more than just a letter.  It can be a
191205194Sdelphijbyte (a "literal"), or it can be either a length or a distance which
192205194Sdelphijindicates a base value and a number of bits to fetch after the code that is
193205194Sdelphijadded to the base value.  Or it might be the special end-of-block code.  The
194205194Sdelphijdata structures created in inftrees.c try to encode all that information
195205194Sdelphijcompactly in the tables.
196205194Sdelphij
197205194Sdelphij
198205194SdelphijJean-loup Gailly        Mark Adler
199205194Sdelphijjloup@gzip.org          madler@alumni.caltech.edu
200205194Sdelphij
201205194Sdelphij
202205194SdelphijReferences:
203205194Sdelphij
204205194Sdelphij[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
205205194SdelphijCompression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
206205194Sdelphijpp. 337-343.
207205194Sdelphij
208205194Sdelphij``DEFLATE Compressed Data Format Specification'' available in
209237691Sdelphijhttp://tools.ietf.org/html/rfc1951
210