1168404Spjd/* inftrees.c -- generate Huffman trees for efficient decoding
2168404Spjd * Copyright (C) 1995-2005 Mark Adler
3168404Spjd * For conditions of distribution and use, see copyright notice in zlib.h
4168404Spjd */
5168404Spjd
6168404Spjd#pragma ident	"%Z%%M%	%I%	%E% SMI"
7168404Spjd
8168404Spjd#include "zutil.h"
9168404Spjd#include "inftrees.h"
10168404Spjd
11168404Spjd#define MAXBITS 15
12168404Spjd
13168404Spjdstatic const char inflate_copyright[] =
14168404Spjd   " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
15168404Spjd/*
16168404Spjd  If you use the zlib library in a product, an acknowledgment is welcome
17168404Spjd  in the documentation of your product. If for some reason you cannot
18168404Spjd  include such an acknowledgment, I would appreciate that you keep this
19168404Spjd  copyright string in the executable of your product.
20168404Spjd */
21168404Spjd
22168404Spjd/*
23168404Spjd   Build a set of tables to decode the provided canonical Huffman code.
24168404Spjd   The code lengths are lens[0..codes-1].  The result starts at *table,
25168404Spjd   whose indices are 0..2^bits-1.  work is a writable array of at least
26168404Spjd   lens shorts, which is used as a work area.  type is the type of code
27168404Spjd   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
28168404Spjd   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
29168404Spjd   on return points to the next available entry's address.  bits is the
30168404Spjd   requested root table index bits, and on return it is the actual root
31168404Spjd   table index bits.  It will differ if the request is greater than the
32168404Spjd   longest code or if it is less than the shortest code.
33168404Spjd */
34168404Spjdint inflate_table(type, lens, codes, table, bits, work)
35168404Spjdcodetype type;
36168404Spjdunsigned short FAR *lens;
37168404Spjdunsigned codes;
38168404Spjdcode FAR * FAR *table;
39168404Spjdunsigned FAR *bits;
40168404Spjdunsigned short FAR *work;
41168404Spjd{
42168404Spjd    unsigned len;               /* a code's length in bits */
43168404Spjd    unsigned sym;               /* index of code symbols */
44168404Spjd    unsigned min, max;          /* minimum and maximum code lengths */
45168404Spjd    unsigned root;              /* number of index bits for root table */
46168404Spjd    unsigned curr;              /* number of index bits for current table */
47168404Spjd    unsigned drop;              /* code bits to drop for sub-table */
48168404Spjd    int left;                   /* number of prefix codes available */
49168404Spjd    unsigned used;              /* code entries in table used */
50168404Spjd    unsigned huff;              /* Huffman code */
51168404Spjd    unsigned incr;              /* for incrementing code, index */
52168404Spjd    unsigned fill;              /* index for replicating entries */
53168404Spjd    unsigned low;               /* low bits for current root entry */
54168404Spjd    unsigned mask;              /* mask for low root bits */
55168404Spjd    code this;                  /* table entry for duplication */
56168404Spjd    code FAR *next;             /* next available space in table */
57168404Spjd    const unsigned short FAR *base;     /* base value table to use */
58168404Spjd    const unsigned short FAR *extra;    /* extra bits table to use */
59168404Spjd    int end;                    /* use base and extra for symbol > end */
60168404Spjd    unsigned short count[MAXBITS+1];    /* number of codes of each length */
61168404Spjd    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
62168404Spjd    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
63168404Spjd        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
64168404Spjd        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
65168404Spjd    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
66168404Spjd        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
67168404Spjd        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
68168404Spjd    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
69168404Spjd        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
70168404Spjd        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
71168404Spjd        8193, 12289, 16385, 24577, 0, 0};
72168404Spjd    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
73168404Spjd        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
74168404Spjd        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
75168404Spjd        28, 28, 29, 29, 64, 64};
76168404Spjd
77168404Spjd    /*
78168404Spjd       Process a set of code lengths to create a canonical Huffman code.  The
79168404Spjd       code lengths are lens[0..codes-1].  Each length corresponds to the
80168404Spjd       symbols 0..codes-1.  The Huffman code is generated by first sorting the
81168404Spjd       symbols by length from short to long, and retaining the symbol order
82168404Spjd       for codes with equal lengths.  Then the code starts with all zero bits
83168404Spjd       for the first code of the shortest length, and the codes are integer
84168404Spjd       increments for the same length, and zeros are appended as the length
85168404Spjd       increases.  For the deflate format, these bits are stored backwards
86168404Spjd       from their more natural integer increment ordering, and so when the
87168404Spjd       decoding tables are built in the large loop below, the integer codes
88168404Spjd       are incremented backwards.
89168404Spjd
90168404Spjd       This routine assumes, but does not check, that all of the entries in
91168404Spjd       lens[] are in the range 0..MAXBITS.  The caller must assure this.
92168404Spjd       1..MAXBITS is interpreted as that code length.  zero means that that
93168404Spjd       symbol does not occur in this code.
94168404Spjd
95168404Spjd       The codes are sorted by computing a count of codes for each length,
96168404Spjd       creating from that a table of starting indices for each length in the
97168404Spjd       sorted table, and then entering the symbols in order in the sorted
98168404Spjd       table.  The sorted table is work[], with that space being provided by
99168404Spjd       the caller.
100168404Spjd
101168404Spjd       The length counts are used for other purposes as well, i.e. finding
102168404Spjd       the minimum and maximum length codes, determining if there are any
103168404Spjd       codes at all, checking for a valid set of lengths, and looking ahead
104168404Spjd       at length counts to determine sub-table sizes when building the
105168404Spjd       decoding tables.
106168404Spjd     */
107168404Spjd
108168404Spjd    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
109168404Spjd    for (len = 0; len <= MAXBITS; len++)
110168404Spjd        count[len] = 0;
111168404Spjd    for (sym = 0; sym < codes; sym++)
112168404Spjd        count[lens[sym]]++;
113168404Spjd
114168404Spjd    /* bound code lengths, force root to be within code lengths */
115168404Spjd    root = *bits;
116168404Spjd    for (max = MAXBITS; max >= 1; max--)
117168404Spjd        if (count[max] != 0) break;
118168404Spjd    if (root > max) root = max;
119168404Spjd    if (max == 0) {                     /* no symbols to code at all */
120168404Spjd        this.op = (unsigned char)64;    /* invalid code marker */
121168404Spjd        this.bits = (unsigned char)1;
122168404Spjd        this.val = (unsigned short)0;
123168404Spjd        *(*table)++ = this;             /* make a table to force an error */
124168404Spjd        *(*table)++ = this;
125168404Spjd        *bits = 1;
126168404Spjd        return 0;     /* no symbols, but wait for decoding to report error */
127168404Spjd    }
128168404Spjd    for (min = 1; min <= MAXBITS; min++)
129168404Spjd        if (count[min] != 0) break;
130168404Spjd    if (root < min) root = min;
131168404Spjd
132168404Spjd    /* check for an over-subscribed or incomplete set of lengths */
133168404Spjd    left = 1;
134168404Spjd    for (len = 1; len <= MAXBITS; len++) {
135168404Spjd        left <<= 1;
136168404Spjd        left -= count[len];
137168404Spjd        if (left < 0) return -1;        /* over-subscribed */
138168404Spjd    }
139168404Spjd    if (left > 0 && (type == CODES || max != 1))
140168404Spjd        return -1;                      /* incomplete set */
141168404Spjd
142168404Spjd    /* generate offsets into symbol table for each length for sorting */
143168404Spjd    offs[1] = 0;
144168404Spjd    for (len = 1; len < MAXBITS; len++)
145168404Spjd        offs[len + 1] = offs[len] + count[len];
146168404Spjd
147168404Spjd    /* sort symbols by length, by symbol order within each length */
148168404Spjd    for (sym = 0; sym < codes; sym++)
149168404Spjd        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
150168404Spjd
151168404Spjd    /*
152168404Spjd       Create and fill in decoding tables.  In this loop, the table being
153168404Spjd       filled is at next and has curr index bits.  The code being used is huff
154168404Spjd       with length len.  That code is converted to an index by dropping drop
155168404Spjd       bits off of the bottom.  For codes where len is less than drop + curr,
156168404Spjd       those top drop + curr - len bits are incremented through all values to
157168404Spjd       fill the table with replicated entries.
158168404Spjd
159168404Spjd       root is the number of index bits for the root table.  When len exceeds
160168404Spjd       root, sub-tables are created pointed to by the root entry with an index
161168404Spjd       of the low root bits of huff.  This is saved in low to check for when a
162168404Spjd       new sub-table should be started.  drop is zero when the root table is
163168404Spjd       being filled, and drop is root when sub-tables are being filled.
164168404Spjd
165168404Spjd       When a new sub-table is needed, it is necessary to look ahead in the
166168404Spjd       code lengths to determine what size sub-table is needed.  The length
167168404Spjd       counts are used for this, and so count[] is decremented as codes are
168168404Spjd       entered in the tables.
169168404Spjd
170168404Spjd       used keeps track of how many table entries have been allocated from the
171168404Spjd       provided *table space.  It is checked when a LENS table is being made
172168404Spjd       against the space in *table, ENOUGH, minus the maximum space needed by
173168404Spjd       the worst case distance code, MAXD.  This should never happen, but the
174168404Spjd       sufficiency of ENOUGH has not been proven exhaustively, hence the check.
175168404Spjd       This assumes that when type == LENS, bits == 9.
176168404Spjd
177168404Spjd       sym increments through all symbols, and the loop terminates when
178168404Spjd       all codes of length max, i.e. all codes, have been processed.  This
179168404Spjd       routine permits incomplete codes, so another loop after this one fills
180168404Spjd       in the rest of the decoding tables with invalid code markers.
181168404Spjd     */
182168404Spjd
183168404Spjd    /* set up for code type */
184168404Spjd    switch (type) {
185168404Spjd    case CODES:
186168404Spjd        base = extra = work;    /* dummy value--not used */
187168404Spjd        end = 19;
188168404Spjd        break;
189168404Spjd    case LENS:
190168404Spjd        base = lbase;
191168404Spjd        base -= 257;
192168404Spjd        extra = lext;
193168404Spjd        extra -= 257;
194168404Spjd        end = 256;
195168404Spjd        break;
196168404Spjd    default:            /* DISTS */
197168404Spjd        base = dbase;
198168404Spjd        extra = dext;
199168404Spjd        end = -1;
200168404Spjd    }
201168404Spjd
202168404Spjd    /* initialize state for loop */
203168404Spjd    huff = 0;                   /* starting code */
204168404Spjd    sym = 0;                    /* starting code symbol */
205168404Spjd    len = min;                  /* starting code length */
206168404Spjd    next = *table;              /* current table to fill in */
207168404Spjd    curr = root;                /* current table index bits */
208168404Spjd    drop = 0;                   /* current bits to drop from code for index */
209168404Spjd    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
210168404Spjd    used = 1U << root;          /* use root table entries */
211168404Spjd    mask = used - 1;            /* mask for comparing low */
212168404Spjd
213168404Spjd    /* check available table space */
214168404Spjd    if (type == LENS && used >= ENOUGH - MAXD)
215168404Spjd        return 1;
216168404Spjd
217168404Spjd    /* process all codes and make table entries */
218168404Spjd    for (;;) {
219168404Spjd        /* create table entry */
220168404Spjd        this.bits = (unsigned char)(len - drop);
221168404Spjd        if ((int)(work[sym]) < end) {
222168404Spjd            this.op = (unsigned char)0;
223168404Spjd            this.val = work[sym];
224168404Spjd        }
225168404Spjd        else if ((int)(work[sym]) > end) {
226168404Spjd            this.op = (unsigned char)(extra[work[sym]]);
227168404Spjd            this.val = base[work[sym]];
228168404Spjd        }
229168404Spjd        else {
230168404Spjd            this.op = (unsigned char)(32 + 64);         /* end of block */
231168404Spjd            this.val = 0;
232168404Spjd        }
233168404Spjd
234168404Spjd        /* replicate for those indices with low len bits equal to huff */
235168404Spjd        incr = 1U << (len - drop);
236168404Spjd        fill = 1U << curr;
237168404Spjd        min = fill;                 /* save offset to next table */
238168404Spjd        do {
239168404Spjd            fill -= incr;
240168404Spjd            next[(huff >> drop) + fill] = this;
241168404Spjd        } while (fill != 0);
242168404Spjd
243168404Spjd        /* backwards increment the len-bit code huff */
244168404Spjd        incr = 1U << (len - 1);
245168404Spjd        while (huff & incr)
246168404Spjd            incr >>= 1;
247168404Spjd        if (incr != 0) {
248168404Spjd            huff &= incr - 1;
249168404Spjd            huff += incr;
250168404Spjd        }
251168404Spjd        else
252168404Spjd            huff = 0;
253168404Spjd
254168404Spjd        /* go to next symbol, update count, len */
255168404Spjd        sym++;
256168404Spjd        if (--(count[len]) == 0) {
257168404Spjd            if (len == max) break;
258168404Spjd            len = lens[work[sym]];
259168404Spjd        }
260168404Spjd
261168404Spjd        /* create new sub-table if needed */
262168404Spjd        if (len > root && (huff & mask) != low) {
263168404Spjd            /* if first time, transition to sub-tables */
264168404Spjd            if (drop == 0)
265168404Spjd                drop = root;
266168404Spjd
267168404Spjd            /* increment past last table */
268168404Spjd            next += min;            /* here min is 1 << curr */
269168404Spjd
270168404Spjd            /* determine length of next table */
271168404Spjd            curr = len - drop;
272168404Spjd            left = (int)(1 << curr);
273168404Spjd            while (curr + drop < max) {
274168404Spjd                left -= count[curr + drop];
275168404Spjd                if (left <= 0) break;
276168404Spjd                curr++;
277168404Spjd                left <<= 1;
278168404Spjd            }
279168404Spjd
280168404Spjd            /* check for enough space */
281168404Spjd            used += 1U << curr;
282168404Spjd            if (type == LENS && used >= ENOUGH - MAXD)
283168404Spjd                return 1;
284168404Spjd
285168404Spjd            /* point entry in root table to sub-table */
286168404Spjd            low = huff & mask;
287168404Spjd            (*table)[low].op = (unsigned char)curr;
288168404Spjd            (*table)[low].bits = (unsigned char)root;
289168404Spjd            (*table)[low].val = (unsigned short)(next - *table);
290168404Spjd        }
291168404Spjd    }
292168404Spjd
293168404Spjd    /*
294168404Spjd       Fill in rest of table for incomplete codes.  This loop is similar to the
295168404Spjd       loop above in incrementing huff for table indices.  It is assumed that
296168404Spjd       len is equal to curr + drop, so there is no loop needed to increment
297168404Spjd       through high index bits.  When the current sub-table is filled, the loop
298168404Spjd       drops back to the root table to fill in any remaining entries there.
299168404Spjd     */
300168404Spjd    this.op = (unsigned char)64;                /* invalid code marker */
301168404Spjd    this.bits = (unsigned char)(len - drop);
302168404Spjd    this.val = (unsigned short)0;
303168404Spjd    while (huff != 0) {
304168404Spjd        /* when done with sub-table, drop back to root table */
305168404Spjd        if (drop != 0 && (huff & mask) != low) {
306168404Spjd            drop = 0;
307168404Spjd            len = root;
308168404Spjd            next = *table;
309168404Spjd            this.bits = (unsigned char)len;
310168404Spjd        }
311168404Spjd
312168404Spjd        /* put invalid code marker in table */
313168404Spjd        next[huff >> drop] = this;
314168404Spjd
315168404Spjd        /* backwards increment the len-bit code huff */
316168404Spjd        incr = 1U << (len - 1);
317168404Spjd        while (huff & incr)
318168404Spjd            incr >>= 1;
319168404Spjd        if (incr != 0) {
320168404Spjd            huff &= incr - 1;
321168404Spjd            huff += incr;
322168404Spjd        }
323168404Spjd        else
324168404Spjd            huff = 0;
325168404Spjd    }
326168404Spjd
327168404Spjd    /* set return parameters */
328168404Spjd    *table += used;
329168404Spjd    *bits = root;
330168404Spjd    return 0;
331168404Spjd}
332