]> git.lizzy.rs Git - zlib.git/blob - inftrees.c
zlib 1.0.1
[zlib.git] / inftrees.c
1 /* inftrees.c -- generate Huffman trees for efficient decoding
2  * Copyright (C) 1995-1996 Mark Adler
3  * For conditions of distribution and use, see copyright notice in zlib.h 
4  */
5
6 #include "zutil.h"
7 #include "inftrees.h"
8
9 char inflate_copyright[] = " inflate 1.0.1 Copyright 1995-1996 Mark Adler ";
10 /*
11   If you use the zlib library in a product, an acknowledgment is welcome
12   in the documentation of your product. If for some reason you cannot
13   include such an acknowledgment, I would appreciate that you keep this
14   copyright string in the executable of your product.
15  */
16 struct internal_state  {int dummy;}; /* for buggy compilers */
17
18 /* simplify the use of the inflate_huft type with some defines */
19 #define base more.Base
20 #define next more.Next
21 #define exop word.what.Exop
22 #define bits word.what.Bits
23
24
25 local int huft_build OF((
26     uIntf *,            /* code lengths in bits */
27     uInt,               /* number of codes */
28     uInt,               /* number of "simple" codes */
29     uIntf *,            /* list of base values for non-simple codes */
30     uIntf *,            /* list of extra bits for non-simple codes */
31     inflate_huft * FAR*,/* result: starting table */
32     uIntf *,            /* maximum lookup bits (returns actual) */
33     z_stream *));       /* for zalloc function */
34
35 local voidpf falloc OF((
36     voidpf,             /* opaque pointer (not used) */
37     uInt,               /* number of items */
38     uInt));             /* size of item */
39
40 /* Tables for deflate from PKZIP's appnote.txt. */
41 local uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
42         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
43         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
44         /* actually lengths - 2; also see note #13 above about 258 */
45 local uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
46         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
47         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 192, 192}; /* 192==invalid */
48 local uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
49         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
50         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
51         8193, 12289, 16385, 24577};
52 local uInt cpdext[30] = { /* Extra bits for distance codes */
53         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
54         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
55         12, 12, 13, 13};
56
57 /*
58    Huffman code decoding is performed using a multi-level table lookup.
59    The fastest way to decode is to simply build a lookup table whose
60    size is determined by the longest code.  However, the time it takes
61    to build this table can also be a factor if the data being decoded
62    is not very long.  The most common codes are necessarily the
63    shortest codes, so those codes dominate the decoding time, and hence
64    the speed.  The idea is you can have a shorter table that decodes the
65    shorter, more probable codes, and then point to subsidiary tables for
66    the longer codes.  The time it costs to decode the longer codes is
67    then traded against the time it takes to make longer tables.
68
69    This results of this trade are in the variables lbits and dbits
70    below.  lbits is the number of bits the first level table for literal/
71    length codes can decode in one step, and dbits is the same thing for
72    the distance codes.  Subsequent tables are also less than or equal to
73    those sizes.  These values may be adjusted either when all of the
74    codes are shorter than that, in which case the longest code length in
75    bits is used, or when the shortest code is *longer* than the requested
76    table size, in which case the length of the shortest code in bits is
77    used.
78
79    There are two different values for the two tables, since they code a
80    different number of possibilities each.  The literal/length table
81    codes 286 possible values, or in a flat code, a little over eight
82    bits.  The distance table codes 30 possible values, or a little less
83    than five bits, flat.  The optimum values for speed end up being
84    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
85    The optimum values may differ though from machine to machine, and
86    possibly even between compilers.  Your mileage may vary.
87  */
88
89
90 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
91 #define BMAX 15         /* maximum bit length of any code */
92 #define N_MAX 288       /* maximum number of codes in any set */
93
94 #ifdef DEBUG
95   uInt inflate_hufts;
96 #endif
97
98 local int huft_build(b, n, s, d, e, t, m, zs)
99 uIntf *b;               /* code lengths in bits (all assumed <= BMAX) */
100 uInt n;                 /* number of codes (assumed <= N_MAX) */
101 uInt s;                 /* number of simple-valued codes (0..s-1) */
102 uIntf *d;               /* list of base values for non-simple codes */
103 uIntf *e;               /* list of extra bits for non-simple codes */  
104 inflate_huft * FAR *t;  /* result: starting table */
105 uIntf *m;               /* maximum lookup bits, returns actual */
106 z_stream *zs;           /* for zalloc function */
107 /* Given a list of code lengths and a maximum table size, make a set of
108    tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
109    if the given code set is incomplete (the tables are still built in this
110    case), Z_DATA_ERROR if the input is invalid (all zero length codes or an
111    over-subscribed set of lengths), or Z_MEM_ERROR if not enough memory. */
112 {
113
114   uInt a;                       /* counter for codes of length k */
115   uInt c[BMAX+1];               /* bit length count table */
116   uInt f;                       /* i repeats in table every f entries */
117   int g;                        /* maximum code length */
118   int h;                        /* table level */
119   register uInt i;              /* counter, current code */
120   register uInt j;              /* counter */
121   register int k;               /* number of bits in current code */
122   int l;                        /* bits per table (returned in m) */
123   register uIntf *p;            /* pointer into c[], b[], or v[] */
124   inflate_huft *q;              /* points to current table */
125   struct inflate_huft_s r;      /* table entry for structure assignment */
126   inflate_huft *u[BMAX];        /* table stack */
127   uInt v[N_MAX];                /* values in order of bit length */
128   register int w;               /* bits before this table == (l * h) */
129   uInt x[BMAX+1];               /* bit offsets, then code stack */
130   uIntf *xp;                    /* pointer into x */
131   int y;                        /* number of dummy codes added */
132   uInt z;                       /* number of entries in current table */
133
134
135   /* Generate counts for each bit length */
136   p = c;
137 #define C0 *p++ = 0;
138 #define C2 C0 C0 C0 C0
139 #define C4 C2 C2 C2 C2
140   C4                            /* clear c[]--assume BMAX+1 is 16 */
141   p = b;  i = n;
142   do {
143     c[*p++]++;                  /* assume all entries <= BMAX */
144   } while (--i);
145   if (c[0] == n)                /* null input--all zero length codes */
146   {
147     *t = (inflate_huft *)Z_NULL;
148     *m = 0;
149     return Z_OK;
150   }
151
152
153   /* Find minimum and maximum length, bound *m by those */
154   l = *m;
155   for (j = 1; j <= BMAX; j++)
156     if (c[j])
157       break;
158   k = j;                        /* minimum code length */
159   if ((uInt)l < j)
160     l = j;
161   for (i = BMAX; i; i--)
162     if (c[i])
163       break;
164   g = i;                        /* maximum code length */
165   if ((uInt)l > i)
166     l = i;
167   *m = l;
168
169
170   /* Adjust last length count to fill out codes, if needed */
171   for (y = 1 << j; j < i; j++, y <<= 1)
172     if ((y -= c[j]) < 0)
173       return Z_DATA_ERROR;
174   if ((y -= c[i]) < 0)
175     return Z_DATA_ERROR;
176   c[i] += y;
177
178
179   /* Generate starting offsets into the value table for each length */
180   x[1] = j = 0;
181   p = c + 1;  xp = x + 2;
182   while (--i) {                 /* note that i == g from above */
183     *xp++ = (j += *p++);
184   }
185
186
187   /* Make a table of values in order of bit lengths */
188   p = b;  i = 0;
189   do {
190     if ((j = *p++) != 0)
191       v[x[j]++] = i;
192   } while (++i < n);
193
194
195   /* Generate the Huffman codes and for each, make the table entries */
196   x[0] = i = 0;                 /* first Huffman code is zero */
197   p = v;                        /* grab values in bit order */
198   h = -1;                       /* no tables yet--level -1 */
199   w = -l;                       /* bits decoded == (l * h) */
200   u[0] = (inflate_huft *)Z_NULL;        /* just to keep compilers happy */
201   q = (inflate_huft *)Z_NULL;   /* ditto */
202   z = 0;                        /* ditto */
203
204   /* go through the bit lengths (k already is bits in shortest code) */
205   for (; k <= g; k++)
206   {
207     a = c[k];
208     while (a--)
209     {
210       /* here i is the Huffman code of length k bits for value *p */
211       /* make tables up to required level */
212       while (k > w + l)
213       {
214         h++;
215         w += l;                 /* previous table always l bits */
216
217         /* compute minimum size table less than or equal to l bits */
218         z = g - w;
219         z = z > (uInt)l ? l : z;        /* table size upper limit */
220         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
221         {                       /* too few codes for k-w bit table */
222           f -= a + 1;           /* deduct codes from patterns left */
223           xp = c + k;
224           if (j < z)
225             while (++j < z)     /* try smaller tables up to z bits */
226             {
227               if ((f <<= 1) <= *++xp)
228                 break;          /* enough codes to use up j bits */
229               f -= *xp;         /* else deduct codes from patterns */
230             }
231         }
232         z = 1 << j;             /* table entries for j-bit table */
233
234         /* allocate and link in new table */
235         if ((q = (inflate_huft *)ZALLOC
236              (zs,z + 1,sizeof(inflate_huft))) == Z_NULL)
237         {
238           if (h)
239             inflate_trees_free(u[0], zs);
240           return Z_MEM_ERROR;   /* not enough memory */
241         }
242 #ifdef DEBUG
243         inflate_hufts += z + 1;
244 #endif
245         *t = q + 1;             /* link to list for huft_free() */
246         *(t = &(q->next)) = Z_NULL;
247         u[h] = ++q;             /* table starts after link */
248
249         /* connect to last table, if there is one */
250         if (h)
251         {
252           x[h] = i;             /* save pattern for backing up */
253           r.bits = (Byte)l;     /* bits to dump before this table */
254           r.exop = (Byte)j;     /* bits in this table */
255           r.next = q;           /* pointer to this table */
256           j = i >> (w - l);     /* (get around Turbo C bug) */
257           u[h-1][j] = r;        /* connect to last table */
258         }
259       }
260
261       /* set up table entry in r */
262       r.bits = (Byte)(k - w);
263       if (p >= v + n)
264         r.exop = 128 + 64;      /* out of values--invalid code */
265       else if (*p < s)
266       {
267         r.exop = (Byte)(*p < 256 ? 0 : 32 + 64);     /* 256 is end-of-block */
268         r.base = *p++;          /* simple code is just the value */
269       }
270       else
271       {
272         r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
273         r.base = d[*p++ - s];
274       }
275
276       /* fill code-like entries with r */
277       f = 1 << (k - w);
278       for (j = i >> w; j < z; j += f)
279         q[j] = r;
280
281       /* backwards increment the k-bit code i */
282       for (j = 1 << (k - 1); i & j; j >>= 1)
283         i ^= j;
284       i ^= j;
285
286       /* backup over finished tables */
287       while ((i & ((1 << w) - 1)) != x[h])
288       {
289         h--;                    /* don't need to update q */
290         w -= l;
291       }
292     }
293   }
294
295
296   /* Return Z_BUF_ERROR if we were given an incomplete table */
297   return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
298 }
299
300
301 int inflate_trees_bits(c, bb, tb, z)
302 uIntf *c;               /* 19 code lengths */
303 uIntf *bb;              /* bits tree desired/actual depth */
304 inflate_huft * FAR *tb; /* bits tree result */
305 z_stream *z;            /* for zfree function */
306 {
307   int r;
308
309   r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL, tb, bb, z);
310   if (r == Z_DATA_ERROR)
311     z->msg = (char*)"oversubscribed dynamic bit lengths tree";
312   else if (r == Z_BUF_ERROR)
313   {
314     inflate_trees_free(*tb, z);
315     z->msg = (char*)"incomplete dynamic bit lengths tree";
316     r = Z_DATA_ERROR;
317   }
318   return r;
319 }
320
321
322 int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, z)
323 uInt nl;                /* number of literal/length codes */
324 uInt nd;                /* number of distance codes */
325 uIntf *c;               /* that many (total) code lengths */
326 uIntf *bl;              /* literal desired/actual bit depth */
327 uIntf *bd;              /* distance desired/actual bit depth */
328 inflate_huft * FAR *tl; /* literal/length tree result */
329 inflate_huft * FAR *td; /* distance tree result */
330 z_stream *z;            /* for zfree function */
331 {
332   int r;
333
334   /* build literal/length tree */
335   if ((r = huft_build(c, nl, 257, cplens, cplext, tl, bl, z)) != Z_OK)
336   {
337     if (r == Z_DATA_ERROR)
338       z->msg = (char*)"oversubscribed literal/length tree";
339     else if (r == Z_BUF_ERROR)
340     {
341       inflate_trees_free(*tl, z);
342       z->msg = (char*)"incomplete literal/length tree";
343       r = Z_DATA_ERROR;
344     }
345     return r;
346   }
347
348   /* build distance tree */
349   if ((r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, z)) != Z_OK)
350   {
351     if (r == Z_DATA_ERROR)
352       z->msg = (char*)"oversubscribed literal/length tree";
353     else if (r == Z_BUF_ERROR) {
354 #ifdef PKZIP_BUG_WORKAROUND
355       r = Z_OK;
356     }
357 #else
358       inflate_trees_free(*td, z);
359       z->msg = (char*)"incomplete literal/length tree";
360       r = Z_DATA_ERROR;
361     }
362     inflate_trees_free(*tl, z);
363     return r;
364 #endif
365   }
366
367   /* done */
368   return Z_OK;
369 }
370
371
372 /* build fixed tables only once--keep them here */
373 local int fixed_built = 0;
374 #define FIXEDH 530      /* number of hufts used by fixed tables */
375 local inflate_huft fixed_mem[FIXEDH];
376 local uInt fixed_bl;
377 local uInt fixed_bd;
378 local inflate_huft *fixed_tl;
379 local inflate_huft *fixed_td;
380
381
382 local voidpf falloc(q, n, s)
383 voidpf q;       /* opaque pointer */
384 uInt n;         /* number of items */
385 uInt s;         /* size of item */
386 {
387   Assert(s == sizeof(inflate_huft) && n <= *(intf *)q,
388          "inflate_trees falloc overflow");
389   *(intf *)q -= n+s-s; /* s-s to avoid warning */
390   return (voidpf)(fixed_mem + *(intf *)q);
391 }
392
393
394 int inflate_trees_fixed(bl, bd, tl, td)
395 uIntf *bl;               /* literal desired/actual bit depth */
396 uIntf *bd;               /* distance desired/actual bit depth */
397 inflate_huft * FAR *tl;  /* literal/length tree result */
398 inflate_huft * FAR *td;  /* distance tree result */
399 {
400   /* build fixed tables if not already (multiple overlapped executions ok) */
401   if (!fixed_built)
402   {
403     int k;              /* temporary variable */
404     unsigned c[288];    /* length list for huft_build */
405     z_stream z;         /* for falloc function */
406     int f = FIXEDH;     /* number of hufts left in fixed_mem */
407
408     /* set up fake z_stream for memory routines */
409     z.zalloc = falloc;
410     z.zfree = Z_NULL;
411     z.opaque = (voidpf)&f;
412
413     /* literal table */
414     for (k = 0; k < 144; k++)
415       c[k] = 8;
416     for (; k < 256; k++)
417       c[k] = 9;
418     for (; k < 280; k++)
419       c[k] = 7;
420     for (; k < 288; k++)
421       c[k] = 8;
422     fixed_bl = 7;
423     huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl, &z);
424
425     /* distance table */
426     for (k = 0; k < 30; k++)
427       c[k] = 5;
428     fixed_bd = 5;
429     huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd, &z);
430
431     /* done */
432     Assert(f == 0, "invalid build of fixed tables");
433     fixed_built = 1;
434   }
435   *bl = fixed_bl;
436   *bd = fixed_bd;
437   *tl = fixed_tl;
438   *td = fixed_td;
439   return Z_OK;
440 }
441
442
443 int inflate_trees_free(t, z)
444 inflate_huft *t;        /* table to free */
445 z_stream *z;            /* for zfree function */
446 /* Free the malloc'ed tables built by huft_build(), which makes a linked
447    list of the tables it made, with the links in a dummy first entry of
448    each table. */
449 {
450   register inflate_huft *p, *q, *r;
451
452   /* Reverse linked list */
453   p = Z_NULL;
454   q = t;
455   while (q != Z_NULL)
456   {
457     r = (q - 1)->next;
458     (q - 1)->next = p;
459     p = q;
460     q = r;
461   }
462   /* Go through linked list, freeing from the malloced (t[-1]) address. */
463   while (p != Z_NULL)
464   {
465     q = (--p)->next;
466     ZFREE(z,p);
467     p = q;
468   } 
469   return Z_OK;
470 }