xref: /plan9/sys/src/cmd/gs/zlib/algorithm.txt (revision 593dc095aefb2a85c828727bbfa9da139a49bdf4)
1*593dc095SDavid du Colombier1. Compression algorithm (deflate)
2*593dc095SDavid du Colombier
3*593dc095SDavid du ColombierThe deflation algorithm used by gzip (also zip and zlib) is a variation of
4*593dc095SDavid du ColombierLZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
5*593dc095SDavid du Colombierthe input data.  The second occurrence of a string is replaced by a
6*593dc095SDavid du Colombierpointer to the previous string, in the form of a pair (distance,
7*593dc095SDavid du Colombierlength).  Distances are limited to 32K bytes, and lengths are limited
8*593dc095SDavid du Colombierto 258 bytes. When a string does not occur anywhere in the previous
9*593dc095SDavid du Colombier32K bytes, it is emitted as a sequence of literal bytes.  (In this
10*593dc095SDavid du Colombierdescription, `string' must be taken as an arbitrary sequence of bytes,
11*593dc095SDavid du Colombierand is not restricted to printable characters.)
12*593dc095SDavid du Colombier
13*593dc095SDavid du ColombierLiterals or match lengths are compressed with one Huffman tree, and
14*593dc095SDavid du Colombiermatch distances are compressed with another tree. The trees are stored
15*593dc095SDavid du Colombierin a compact form at the start of each block. The blocks can have any
16*593dc095SDavid du Colombiersize (except that the compressed data for one block must fit in
17*593dc095SDavid du Colombieravailable memory). A block is terminated when deflate() determines that
18*593dc095SDavid du Colombierit would be useful to start another block with fresh trees. (This is
19*593dc095SDavid du Colombiersomewhat similar to the behavior of LZW-based _compress_.)
20*593dc095SDavid du Colombier
21*593dc095SDavid du ColombierDuplicated strings are found using a hash table. All input strings of
22*593dc095SDavid du Colombierlength 3 are inserted in the hash table. A hash index is computed for
23*593dc095SDavid du Colombierthe next 3 bytes. If the hash chain for this index is not empty, all
24*593dc095SDavid du Colombierstrings in the chain are compared with the current input string, and
25*593dc095SDavid du Colombierthe longest match is selected.
26*593dc095SDavid du Colombier
27*593dc095SDavid du ColombierThe hash chains are searched starting with the most recent strings, to
28*593dc095SDavid du Colombierfavor small distances and thus take advantage of the Huffman encoding.
29*593dc095SDavid du ColombierThe hash chains are singly linked. There are no deletions from the
30*593dc095SDavid du Colombierhash chains, the algorithm simply discards matches that are too old.
31*593dc095SDavid du Colombier
32*593dc095SDavid du ColombierTo avoid a worst-case situation, very long hash chains are arbitrarily
33*593dc095SDavid du Colombiertruncated at a certain length, determined by a runtime option (level
34*593dc095SDavid du Colombierparameter of deflateInit). So deflate() does not always find the longest
35*593dc095SDavid du Colombierpossible match but generally finds a match which is long enough.
36*593dc095SDavid du Colombier
37*593dc095SDavid du Colombierdeflate() also defers the selection of matches with a lazy evaluation
38*593dc095SDavid du Colombiermechanism. After a match of length N has been found, deflate() searches for
39*593dc095SDavid du Colombiera longer match at the next input byte. If a longer match is found, the
40*593dc095SDavid du Colombierprevious match is truncated to a length of one (thus producing a single
41*593dc095SDavid du Colombierliteral byte) and the process of lazy evaluation begins again. Otherwise,
42*593dc095SDavid du Colombierthe original match is kept, and the next match search is attempted only N
43*593dc095SDavid du Colombiersteps later.
44*593dc095SDavid du Colombier
45*593dc095SDavid du ColombierThe lazy match evaluation is also subject to a runtime parameter. If
46*593dc095SDavid du Colombierthe current match is long enough, deflate() reduces the search for a longer
47*593dc095SDavid du Colombiermatch, thus speeding up the whole process. If compression ratio is more
48*593dc095SDavid du Colombierimportant than speed, deflate() attempts a complete second search even if
49*593dc095SDavid du Colombierthe first match is already long enough.
50*593dc095SDavid du Colombier
51*593dc095SDavid du ColombierThe lazy match evaluation is not performed for the fastest compression
52*593dc095SDavid du Colombiermodes (level parameter 1 to 3). For these fast modes, new strings
53*593dc095SDavid du Colombierare inserted in the hash table only when no match was found, or
54*593dc095SDavid du Colombierwhen the match is not too long. This degrades the compression ratio
55*593dc095SDavid du Colombierbut saves time since there are both fewer insertions and fewer searches.
56*593dc095SDavid du Colombier
57*593dc095SDavid du Colombier
58*593dc095SDavid du Colombier2. Decompression algorithm (inflate)
59*593dc095SDavid du Colombier
60*593dc095SDavid du Colombier2.1 Introduction
61*593dc095SDavid du Colombier
62*593dc095SDavid du ColombierThe key question is how to represent a Huffman code (or any prefix code) so
63*593dc095SDavid du Colombierthat you can decode fast.  The most important characteristic is that shorter
64*593dc095SDavid du Colombiercodes are much more common than longer codes, so pay attention to decoding the
65*593dc095SDavid du Colombiershort codes fast, and let the long codes take longer to decode.
66*593dc095SDavid du Colombier
67*593dc095SDavid du Colombierinflate() sets up a first level table that covers some number of bits of
68*593dc095SDavid du Colombierinput less than the length of longest code.  It gets that many bits from the
69*593dc095SDavid du Colombierstream, and looks it up in the table.  The table will tell if the next
70*593dc095SDavid du Colombiercode is that many bits or less and how many, and if it is, it will tell
71*593dc095SDavid du Colombierthe value, else it will point to the next level table for which inflate()
72*593dc095SDavid du Colombiergrabs more bits and tries to decode a longer code.
73*593dc095SDavid du Colombier
74*593dc095SDavid du ColombierHow many bits to make the first lookup is a tradeoff between the time it
75*593dc095SDavid du Colombiertakes to decode and the time it takes to build the table.  If building the
76*593dc095SDavid du Colombiertable took no time (and if you had infinite memory), then there would only
77*593dc095SDavid du Colombierbe a first level table to cover all the way to the longest code.  However,
78*593dc095SDavid du Colombierbuilding the table ends up taking a lot longer for more bits since short
79*593dc095SDavid du Colombiercodes are replicated many times in such a table.  What inflate() does is
80*593dc095SDavid du Colombiersimply to make the number of bits in the first table a variable, and  then
81*593dc095SDavid du Colombierto set that variable for the maximum speed.
82*593dc095SDavid du Colombier
83*593dc095SDavid du ColombierFor inflate, which has 286 possible codes for the literal/length tree, the size
84*593dc095SDavid du Colombierof the first table is nine bits.  Also the distance trees have 30 possible
85*593dc095SDavid du Colombiervalues, and the size of the first table is six bits.  Note that for each of
86*593dc095SDavid du Colombierthose cases, the table ended up one bit longer than the ``average'' code
87*593dc095SDavid du Colombierlength, i.e. the code length of an approximately flat code which would be a
88*593dc095SDavid du Colombierlittle more than eight bits for 286 symbols and a little less than five bits
89*593dc095SDavid du Colombierfor 30 symbols.
90*593dc095SDavid du Colombier
91*593dc095SDavid du Colombier
92*593dc095SDavid du Colombier2.2 More details on the inflate table lookup
93*593dc095SDavid du Colombier
94*593dc095SDavid du ColombierOk, you want to know what this cleverly obfuscated inflate tree actually
95*593dc095SDavid du Colombierlooks like.  You are correct that it's not a Huffman tree.  It is simply a
96*593dc095SDavid du Colombierlookup table for the first, let's say, nine bits of a Huffman symbol.  The
97*593dc095SDavid du Colombiersymbol could be as short as one bit or as long as 15 bits.  If a particular
98*593dc095SDavid du Colombiersymbol is shorter than nine bits, then that symbol's translation is duplicated
99*593dc095SDavid du Colombierin all those entries that start with that symbol's bits.  For example, if the
100*593dc095SDavid du Colombiersymbol is four bits, then it's duplicated 32 times in a nine-bit table.  If a
101*593dc095SDavid du Colombiersymbol is nine bits long, it appears in the table once.
102*593dc095SDavid du Colombier
103*593dc095SDavid du ColombierIf the symbol is longer than nine bits, then that entry in the table points
104*593dc095SDavid du Colombierto another similar table for the remaining bits.  Again, there are duplicated
105*593dc095SDavid du Colombierentries as needed.  The idea is that most of the time the symbol will be short
106*593dc095SDavid du Colombierand there will only be one table look up.  (That's whole idea behind data
107*593dc095SDavid du Colombiercompression in the first place.)  For the less frequent long symbols, there
108*593dc095SDavid du Colombierwill be two lookups.  If you had a compression method with really long
109*593dc095SDavid du Colombiersymbols, you could have as many levels of lookups as is efficient.  For
110*593dc095SDavid du Colombierinflate, two is enough.
111*593dc095SDavid du Colombier
112*593dc095SDavid du ColombierSo a table entry either points to another table (in which case nine bits in
113*593dc095SDavid du Colombierthe above example are gobbled), or it contains the translation for the symbol
114*593dc095SDavid du Colombierand the number of bits to gobble.  Then you start again with the next
115*593dc095SDavid du Colombierungobbled bit.
116*593dc095SDavid du Colombier
117*593dc095SDavid du ColombierYou may wonder: why not just have one lookup table for how ever many bits the
118*593dc095SDavid du Colombierlongest symbol is?  The reason is that if you do that, you end up spending
119*593dc095SDavid du Colombiermore time filling in duplicate symbol entries than you do actually decoding.
120*593dc095SDavid du ColombierAt least for deflate's output that generates new trees every several 10's of
121*593dc095SDavid du Colombierkbytes.  You can imagine that filling in a 2^15 entry table for a 15-bit code
122*593dc095SDavid du Colombierwould take too long if you're only decoding several thousand symbols.  At the
123*593dc095SDavid du Colombierother extreme, you could make a new table for every bit in the code.  In fact,
124*593dc095SDavid du Colombierthat's essentially a Huffman tree.  But then you spend two much time
125*593dc095SDavid du Colombiertraversing the tree while decoding, even for short symbols.
126*593dc095SDavid du Colombier
127*593dc095SDavid du ColombierSo the number of bits for the first lookup table is a trade of the time to
128*593dc095SDavid du Colombierfill out the table vs. the time spent looking at the second level and above of
129*593dc095SDavid du Colombierthe table.
130*593dc095SDavid du Colombier
131*593dc095SDavid du ColombierHere is an example, scaled down:
132*593dc095SDavid du Colombier
133*593dc095SDavid du ColombierThe code being decoded, with 10 symbols, from 1 to 6 bits long:
134*593dc095SDavid du Colombier
135*593dc095SDavid du ColombierA: 0
136*593dc095SDavid du ColombierB: 10
137*593dc095SDavid du ColombierC: 1100
138*593dc095SDavid du ColombierD: 11010
139*593dc095SDavid du ColombierE: 11011
140*593dc095SDavid du ColombierF: 11100
141*593dc095SDavid du ColombierG: 11101
142*593dc095SDavid du ColombierH: 11110
143*593dc095SDavid du ColombierI: 111110
144*593dc095SDavid du ColombierJ: 111111
145*593dc095SDavid du Colombier
146*593dc095SDavid du ColombierLet's make the first table three bits long (eight entries):
147*593dc095SDavid du Colombier
148*593dc095SDavid du Colombier000: A,1
149*593dc095SDavid du Colombier001: A,1
150*593dc095SDavid du Colombier010: A,1
151*593dc095SDavid du Colombier011: A,1
152*593dc095SDavid du Colombier100: B,2
153*593dc095SDavid du Colombier101: B,2
154*593dc095SDavid du Colombier110: -> table X (gobble 3 bits)
155*593dc095SDavid du Colombier111: -> table Y (gobble 3 bits)
156*593dc095SDavid du Colombier
157*593dc095SDavid du ColombierEach entry is what the bits decode as and how many bits that is, i.e. how
158*593dc095SDavid du Colombiermany bits to gobble.  Or the entry points to another table, with the number of
159*593dc095SDavid du Colombierbits to gobble implicit in the size of the table.
160*593dc095SDavid du Colombier
161*593dc095SDavid du ColombierTable X is two bits long since the longest code starting with 110 is five bits
162*593dc095SDavid du Colombierlong:
163*593dc095SDavid du Colombier
164*593dc095SDavid du Colombier00: C,1
165*593dc095SDavid du Colombier01: C,1
166*593dc095SDavid du Colombier10: D,2
167*593dc095SDavid du Colombier11: E,2
168*593dc095SDavid du Colombier
169*593dc095SDavid du ColombierTable Y is three bits long since the longest code starting with 111 is six
170*593dc095SDavid du Colombierbits long:
171*593dc095SDavid du Colombier
172*593dc095SDavid du Colombier000: F,2
173*593dc095SDavid du Colombier001: F,2
174*593dc095SDavid du Colombier010: G,2
175*593dc095SDavid du Colombier011: G,2
176*593dc095SDavid du Colombier100: H,2
177*593dc095SDavid du Colombier101: H,2
178*593dc095SDavid du Colombier110: I,3
179*593dc095SDavid du Colombier111: J,3
180*593dc095SDavid du Colombier
181*593dc095SDavid du ColombierSo what we have here are three tables with a total of 20 entries that had to
182*593dc095SDavid du Colombierbe constructed.  That's compared to 64 entries for a single table.  Or
183*593dc095SDavid du Colombiercompared to 16 entries for a Huffman tree (six two entry tables and one four
184*593dc095SDavid du Colombierentry table).  Assuming that the code ideally represents the probability of
185*593dc095SDavid du Colombierthe symbols, it takes on the average 1.25 lookups per symbol.  That's compared
186*593dc095SDavid du Colombierto one lookup for the single table, or 1.66 lookups per symbol for the
187*593dc095SDavid du ColombierHuffman tree.
188*593dc095SDavid du Colombier
189*593dc095SDavid du ColombierThere, I think that gives you a picture of what's going on.  For inflate, the
190*593dc095SDavid du Colombiermeaning of a particular symbol is often more than just a letter.  It can be a
191*593dc095SDavid du Colombierbyte (a "literal"), or it can be either a length or a distance which
192*593dc095SDavid du Colombierindicates a base value and a number of bits to fetch after the code that is
193*593dc095SDavid du Colombieradded to the base value.  Or it might be the special end-of-block code.  The
194*593dc095SDavid du Colombierdata structures created in inftrees.c try to encode all that information
195*593dc095SDavid du Colombiercompactly in the tables.
196*593dc095SDavid du Colombier
197*593dc095SDavid du Colombier
198*593dc095SDavid du ColombierJean-loup Gailly        Mark Adler
199*593dc095SDavid du Colombierjloup@gzip.org          madler@alumni.caltech.edu
200*593dc095SDavid du Colombier
201*593dc095SDavid du Colombier
202*593dc095SDavid du ColombierReferences:
203*593dc095SDavid du Colombier
204*593dc095SDavid du Colombier[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
205*593dc095SDavid du ColombierCompression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
206*593dc095SDavid du Colombierpp. 337-343.
207*593dc095SDavid du Colombier
208*593dc095SDavid du Colombier``DEFLATE Compressed Data Format Specification'' available in
209*593dc095SDavid du Colombierhttp://www.ietf.org/rfc/rfc1951.txt
210