]> git.lizzy.rs Git - zlib.git/blob - trees.c
zlib 1.0.4
[zlib.git] / trees.c
1 /* trees.c -- output deflated data using Huffman coding
2  * Copyright (C) 1995-1996 Jean-loup Gailly
3  * For conditions of distribution and use, see copyright notice in zlib.h 
4  */
5
6 /*
7  *  ALGORITHM
8  *
9  *      The "deflation" process uses several Huffman trees. The more
10  *      common source values are represented by shorter bit sequences.
11  *
12  *      Each code tree is stored in a compressed form which is itself
13  * a Huffman encoding of the lengths of all the code strings (in
14  * ascending order by source values).  The actual code strings are
15  * reconstructed from the lengths in the inflate process, as described
16  * in the deflate specification.
17  *
18  *  REFERENCES
19  *
20  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
21  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
22  *
23  *      Storer, James A.
24  *          Data Compression:  Methods and Theory, pp. 49-50.
25  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
26  *
27  *      Sedgewick, R.
28  *          Algorithms, p290.
29  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
30  */
31
32 /* $Id: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */
33
34 #include "deflate.h"
35
36 #ifdef DEBUG
37 #  include <ctype.h>
38 #endif
39
40 /* ===========================================================================
41  * Constants
42  */
43
44 #define MAX_BL_BITS 7
45 /* Bit length codes must not exceed MAX_BL_BITS bits */
46
47 #define END_BLOCK 256
48 /* end of block literal code */
49
50 #define REP_3_6      16
51 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
52
53 #define REPZ_3_10    17
54 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
55
56 #define REPZ_11_138  18
57 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
58
59 local int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
60    = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
61
62 local int extra_dbits[D_CODES] /* extra bits for each distance code */
63    = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
64
65 local int extra_blbits[BL_CODES]/* extra bits for each bit length code */
66    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
67
68 local uch bl_order[BL_CODES]
69    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
70 /* The lengths of the bit length codes are sent in order of decreasing
71  * probability, to avoid transmitting the lengths for unused bit length codes.
72  */
73
74 #define Buf_size (8 * 2*sizeof(char))
75 /* Number of bits used within bi_buf. (bi_buf might be implemented on
76  * more than 16 bits on some systems.)
77  */
78
79 /* ===========================================================================
80  * Local data. These are initialized only once.
81  */
82
83 local ct_data static_ltree[L_CODES+2];
84 /* The static literal tree. Since the bit lengths are imposed, there is no
85  * need for the L_CODES extra codes used during heap construction. However
86  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
87  * below).
88  */
89
90 local ct_data static_dtree[D_CODES];
91 /* The static distance tree. (Actually a trivial tree since all codes use
92  * 5 bits.)
93  */
94
95 local uch dist_code[512];
96 /* distance codes. The first 256 values correspond to the distances
97  * 3 .. 258, the last 256 values correspond to the top 8 bits of
98  * the 15 bit distances.
99  */
100
101 local uch length_code[MAX_MATCH-MIN_MATCH+1];
102 /* length code for each normalized match length (0 == MIN_MATCH) */
103
104 local int base_length[LENGTH_CODES];
105 /* First normalized length for each code (0 = MIN_MATCH) */
106
107 local int base_dist[D_CODES];
108 /* First normalized distance for each code (0 = distance of 1) */
109
110 struct static_tree_desc_s {
111     ct_data *static_tree;        /* static tree or NULL */
112     intf    *extra_bits;         /* extra bits for each code or NULL */
113     int     extra_base;          /* base index for extra_bits */
114     int     elems;               /* max number of elements in the tree */
115     int     max_length;          /* max bit length for the codes */
116 };
117
118 local static_tree_desc  static_l_desc =
119 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
120
121 local static_tree_desc  static_d_desc =
122 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
123
124 local static_tree_desc  static_bl_desc =
125 {(ct_data *)0, extra_blbits, 0,      BL_CODES, MAX_BL_BITS};
126
127 /* ===========================================================================
128  * Local (static) routines in this file.
129  */
130
131 local void tr_static_init OF((void));
132 local void init_block     OF((deflate_state *s));
133 local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
134 local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
135 local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
136 local void build_tree     OF((deflate_state *s, tree_desc *desc));
137 local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
138 local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
139 local int  build_bl_tree  OF((deflate_state *s));
140 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
141                               int blcodes));
142 local void compress_block OF((deflate_state *s, ct_data *ltree,
143                               ct_data *dtree));
144 local void set_data_type  OF((deflate_state *s));
145 local unsigned bi_reverse OF((unsigned value, int length));
146 local void bi_windup      OF((deflate_state *s));
147 local void bi_flush       OF((deflate_state *s));
148 local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
149                               int header));
150
151 #ifndef DEBUG
152 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
153    /* Send a code of the given tree. c and tree must not have side effects */
154
155 #else /* DEBUG */
156 #  define send_code(s, c, tree) \
157      { if (verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
158        send_bits(s, tree[c].Code, tree[c].Len); }
159 #endif
160
161 #define d_code(dist) \
162    ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
163 /* Mapping from a distance to a distance code. dist is the distance - 1 and
164  * must not have side effects. dist_code[256] and dist_code[257] are never
165  * used.
166  */
167
168 /* ===========================================================================
169  * Output a short LSB first on the stream.
170  * IN assertion: there is enough room in pendingBuf.
171  */
172 #define put_short(s, w) { \
173     put_byte(s, (uch)((w) & 0xff)); \
174     put_byte(s, (uch)((ush)(w) >> 8)); \
175 }
176
177 /* ===========================================================================
178  * Send a value on a given number of bits.
179  * IN assertion: length <= 16 and value fits in length bits.
180  */
181 #ifdef DEBUG
182 local void send_bits      OF((deflate_state *s, int value, int length));
183
184 local void send_bits(s, value, length)
185     deflate_state *s;
186     int value;  /* value to send */
187     int length; /* number of bits */
188 {
189     Tracevv((stderr," l %2d v %4x ", length, value));
190     Assert(length > 0 && length <= 15, "invalid length");
191     s->bits_sent += (ulg)length;
192
193     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
194      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
195      * unused bits in value.
196      */
197     if (s->bi_valid > (int)Buf_size - length) {
198         s->bi_buf |= (value << s->bi_valid);
199         put_short(s, s->bi_buf);
200         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
201         s->bi_valid += length - Buf_size;
202     } else {
203         s->bi_buf |= value << s->bi_valid;
204         s->bi_valid += length;
205     }
206 }
207 #else /* !DEBUG */
208
209 #define send_bits(s, value, length) \
210 { int len = length;\
211   if (s->bi_valid > (int)Buf_size - len) {\
212     int val = value;\
213     s->bi_buf |= (val << s->bi_valid);\
214     put_short(s, s->bi_buf);\
215     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
216     s->bi_valid += len - Buf_size;\
217   } else {\
218     s->bi_buf |= (value) << s->bi_valid;\
219     s->bi_valid += len;\
220   }\
221 }
222 #endif /* DEBUG */
223
224
225 #define MAX(a,b) (a >= b ? a : b)
226 /* the arguments must not have side effects */
227
228 /* ===========================================================================
229  * Initialize the various 'constant' tables. In a multi-threaded environment,
230  * this function may be called by two threads concurrently, but this is
231  * harmless since both invocations do exactly the same thing.
232  */
233 local void tr_static_init()
234 {
235     static int static_init_done = 0;
236     int n;        /* iterates over tree elements */
237     int bits;     /* bit counter */
238     int length;   /* length value */
239     int code;     /* code value */
240     int dist;     /* distance index */
241     ush bl_count[MAX_BITS+1];
242     /* number of codes at each bit length for an optimal tree */
243
244     if (static_init_done) return;
245
246     /* Initialize the mapping length (0..255) -> length code (0..28) */
247     length = 0;
248     for (code = 0; code < LENGTH_CODES-1; code++) {
249         base_length[code] = length;
250         for (n = 0; n < (1<<extra_lbits[code]); n++) {
251             length_code[length++] = (uch)code;
252         }
253     }
254     Assert (length == 256, "tr_static_init: length != 256");
255     /* Note that the length 255 (match length 258) can be represented
256      * in two different ways: code 284 + 5 bits or code 285, so we
257      * overwrite length_code[255] to use the best encoding:
258      */
259     length_code[length-1] = (uch)code;
260
261     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
262     dist = 0;
263     for (code = 0 ; code < 16; code++) {
264         base_dist[code] = dist;
265         for (n = 0; n < (1<<extra_dbits[code]); n++) {
266             dist_code[dist++] = (uch)code;
267         }
268     }
269     Assert (dist == 256, "tr_static_init: dist != 256");
270     dist >>= 7; /* from now on, all distances are divided by 128 */
271     for ( ; code < D_CODES; code++) {
272         base_dist[code] = dist << 7;
273         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
274             dist_code[256 + dist++] = (uch)code;
275         }
276     }
277     Assert (dist == 256, "tr_static_init: 256+dist != 512");
278
279     /* Construct the codes of the static literal tree */
280     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
281     n = 0;
282     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
283     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
284     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
285     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
286     /* Codes 286 and 287 do not exist, but we must include them in the
287      * tree construction to get a canonical Huffman tree (longest code
288      * all ones)
289      */
290     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
291
292     /* The static distance tree is trivial: */
293     for (n = 0; n < D_CODES; n++) {
294         static_dtree[n].Len = 5;
295         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
296     }
297     static_init_done = 1;
298 }
299
300 /* ===========================================================================
301  * Initialize the tree data structures for a new zlib stream.
302  */
303 void _tr_init(s)
304     deflate_state *s;
305 {
306     tr_static_init();
307
308     s->compressed_len = 0L;
309
310     s->l_desc.dyn_tree = s->dyn_ltree;
311     s->l_desc.stat_desc = &static_l_desc;
312
313     s->d_desc.dyn_tree = s->dyn_dtree;
314     s->d_desc.stat_desc = &static_d_desc;
315
316     s->bl_desc.dyn_tree = s->bl_tree;
317     s->bl_desc.stat_desc = &static_bl_desc;
318
319     s->bi_buf = 0;
320     s->bi_valid = 0;
321     s->last_eob_len = 8; /* enough lookahead for inflate */
322 #ifdef DEBUG
323     s->bits_sent = 0L;
324 #endif
325
326     /* Initialize the first block of the first file: */
327     init_block(s);
328 }
329
330 /* ===========================================================================
331  * Initialize a new block.
332  */
333 local void init_block(s)
334     deflate_state *s;
335 {
336     int n; /* iterates over tree elements */
337
338     /* Initialize the trees. */
339     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
340     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
341     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
342
343     s->dyn_ltree[END_BLOCK].Freq = 1;
344     s->opt_len = s->static_len = 0L;
345     s->last_lit = s->matches = 0;
346 }
347
348 #define SMALLEST 1
349 /* Index within the heap array of least frequent node in the Huffman tree */
350
351
352 /* ===========================================================================
353  * Remove the smallest element from the heap and recreate the heap with
354  * one less element. Updates heap and heap_len.
355  */
356 #define pqremove(s, tree, top) \
357 {\
358     top = s->heap[SMALLEST]; \
359     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
360     pqdownheap(s, tree, SMALLEST); \
361 }
362
363 /* ===========================================================================
364  * Compares to subtrees, using the tree depth as tie breaker when
365  * the subtrees have equal frequency. This minimizes the worst case length.
366  */
367 #define smaller(tree, n, m, depth) \
368    (tree[n].Freq < tree[m].Freq || \
369    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
370
371 /* ===========================================================================
372  * Restore the heap property by moving down the tree starting at node k,
373  * exchanging a node with the smallest of its two sons if necessary, stopping
374  * when the heap property is re-established (each father smaller than its
375  * two sons).
376  */
377 local void pqdownheap(s, tree, k)
378     deflate_state *s;
379     ct_data *tree;  /* the tree to restore */
380     int k;               /* node to move down */
381 {
382     int v = s->heap[k];
383     int j = k << 1;  /* left son of k */
384     while (j <= s->heap_len) {
385         /* Set j to the smallest of the two sons: */
386         if (j < s->heap_len &&
387             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
388             j++;
389         }
390         /* Exit if v is smaller than both sons */
391         if (smaller(tree, v, s->heap[j], s->depth)) break;
392
393         /* Exchange v with the smallest son */
394         s->heap[k] = s->heap[j];  k = j;
395
396         /* And continue down the tree, setting j to the left son of k */
397         j <<= 1;
398     }
399     s->heap[k] = v;
400 }
401
402 /* ===========================================================================
403  * Compute the optimal bit lengths for a tree and update the total bit length
404  * for the current block.
405  * IN assertion: the fields freq and dad are set, heap[heap_max] and
406  *    above are the tree nodes sorted by increasing frequency.
407  * OUT assertions: the field len is set to the optimal bit length, the
408  *     array bl_count contains the frequencies for each bit length.
409  *     The length opt_len is updated; static_len is also updated if stree is
410  *     not null.
411  */
412 local void gen_bitlen(s, desc)
413     deflate_state *s;
414     tree_desc *desc;    /* the tree descriptor */
415 {
416     ct_data *tree  = desc->dyn_tree;
417     int max_code   = desc->max_code;
418     ct_data *stree = desc->stat_desc->static_tree;
419     intf *extra    = desc->stat_desc->extra_bits;
420     int base       = desc->stat_desc->extra_base;
421     int max_length = desc->stat_desc->max_length;
422     int h;              /* heap index */
423     int n, m;           /* iterate over the tree elements */
424     int bits;           /* bit length */
425     int xbits;          /* extra bits */
426     ush f;              /* frequency */
427     int overflow = 0;   /* number of elements with bit length too large */
428
429     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
430
431     /* In a first pass, compute the optimal bit lengths (which may
432      * overflow in the case of the bit length tree).
433      */
434     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
435
436     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
437         n = s->heap[h];
438         bits = tree[tree[n].Dad].Len + 1;
439         if (bits > max_length) bits = max_length, overflow++;
440         tree[n].Len = (ush)bits;
441         /* We overwrite tree[n].Dad which is no longer needed */
442
443         if (n > max_code) continue; /* not a leaf node */
444
445         s->bl_count[bits]++;
446         xbits = 0;
447         if (n >= base) xbits = extra[n-base];
448         f = tree[n].Freq;
449         s->opt_len += (ulg)f * (bits + xbits);
450         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
451     }
452     if (overflow == 0) return;
453
454     Trace((stderr,"\nbit length overflow\n"));
455     /* This happens for example on obj2 and pic of the Calgary corpus */
456
457     /* Find the first bit length which could increase: */
458     do {
459         bits = max_length-1;
460         while (s->bl_count[bits] == 0) bits--;
461         s->bl_count[bits]--;      /* move one leaf down the tree */
462         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
463         s->bl_count[max_length]--;
464         /* The brother of the overflow item also moves one step up,
465          * but this does not affect bl_count[max_length]
466          */
467         overflow -= 2;
468     } while (overflow > 0);
469
470     /* Now recompute all bit lengths, scanning in increasing frequency.
471      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
472      * lengths instead of fixing only the wrong ones. This idea is taken
473      * from 'ar' written by Haruhiko Okumura.)
474      */
475     for (bits = max_length; bits != 0; bits--) {
476         n = s->bl_count[bits];
477         while (n != 0) {
478             m = s->heap[--h];
479             if (m > max_code) continue;
480             if (tree[m].Len != (unsigned) bits) {
481                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
482                 s->opt_len += ((long)bits - (long)tree[m].Len)
483                               *(long)tree[m].Freq;
484                 tree[m].Len = (ush)bits;
485             }
486             n--;
487         }
488     }
489 }
490
491 /* ===========================================================================
492  * Generate the codes for a given tree and bit counts (which need not be
493  * optimal).
494  * IN assertion: the array bl_count contains the bit length statistics for
495  * the given tree and the field len is set for all tree elements.
496  * OUT assertion: the field code is set for all tree elements of non
497  *     zero code length.
498  */
499 local void gen_codes (tree, max_code, bl_count)
500     ct_data *tree;             /* the tree to decorate */
501     int max_code;              /* largest code with non zero frequency */
502     ushf *bl_count;            /* number of codes at each bit length */
503 {
504     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
505     ush code = 0;              /* running code value */
506     int bits;                  /* bit index */
507     int n;                     /* code index */
508
509     /* The distribution counts are first used to generate the code values
510      * without bit reversal.
511      */
512     for (bits = 1; bits <= MAX_BITS; bits++) {
513         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
514     }
515     /* Check that the bit counts in bl_count are consistent. The last code
516      * must be all ones.
517      */
518     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
519             "inconsistent bit counts");
520     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
521
522     for (n = 0;  n <= max_code; n++) {
523         int len = tree[n].Len;
524         if (len == 0) continue;
525         /* Now reverse the bits */
526         tree[n].Code = bi_reverse(next_code[len]++, len);
527
528         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
529              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
530     }
531 }
532
533 /* ===========================================================================
534  * Construct one Huffman tree and assigns the code bit strings and lengths.
535  * Update the total bit length for the current block.
536  * IN assertion: the field freq is set for all tree elements.
537  * OUT assertions: the fields len and code are set to the optimal bit length
538  *     and corresponding code. The length opt_len is updated; static_len is
539  *     also updated if stree is not null. The field max_code is set.
540  */
541 local void build_tree(s, desc)
542     deflate_state *s;
543     tree_desc *desc; /* the tree descriptor */
544 {
545     ct_data *tree   = desc->dyn_tree;
546     ct_data *stree  = desc->stat_desc->static_tree;
547     int elems       = desc->stat_desc->elems;
548     int n, m;          /* iterate over heap elements */
549     int max_code = -1; /* largest code with non zero frequency */
550     int node;          /* new node being created */
551
552     /* Construct the initial heap, with least frequent element in
553      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
554      * heap[0] is not used.
555      */
556     s->heap_len = 0, s->heap_max = HEAP_SIZE;
557
558     for (n = 0; n < elems; n++) {
559         if (tree[n].Freq != 0) {
560             s->heap[++(s->heap_len)] = max_code = n;
561             s->depth[n] = 0;
562         } else {
563             tree[n].Len = 0;
564         }
565     }
566
567     /* The pkzip format requires that at least one distance code exists,
568      * and that at least one bit should be sent even if there is only one
569      * possible code. So to avoid special checks later on we force at least
570      * two codes of non zero frequency.
571      */
572     while (s->heap_len < 2) {
573         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
574         tree[node].Freq = 1;
575         s->depth[node] = 0;
576         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
577         /* node is 0 or 1 so it does not have extra bits */
578     }
579     desc->max_code = max_code;
580
581     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
582      * establish sub-heaps of increasing lengths:
583      */
584     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
585
586     /* Construct the Huffman tree by repeatedly combining the least two
587      * frequent nodes.
588      */
589     node = elems;              /* next internal node of the tree */
590     do {
591         pqremove(s, tree, n);  /* n = node of least frequency */
592         m = s->heap[SMALLEST]; /* m = node of next least frequency */
593
594         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
595         s->heap[--(s->heap_max)] = m;
596
597         /* Create a new node father of n and m */
598         tree[node].Freq = tree[n].Freq + tree[m].Freq;
599         s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
600         tree[n].Dad = tree[m].Dad = (ush)node;
601 #ifdef DUMP_BL_TREE
602         if (tree == s->bl_tree) {
603             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
604                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
605         }
606 #endif
607         /* and insert the new node in the heap */
608         s->heap[SMALLEST] = node++;
609         pqdownheap(s, tree, SMALLEST);
610
611     } while (s->heap_len >= 2);
612
613     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
614
615     /* At this point, the fields freq and dad are set. We can now
616      * generate the bit lengths.
617      */
618     gen_bitlen(s, (tree_desc *)desc);
619
620     /* The field len is now set, we can generate the bit codes */
621     gen_codes ((ct_data *)tree, max_code, s->bl_count);
622 }
623
624 /* ===========================================================================
625  * Scan a literal or distance tree to determine the frequencies of the codes
626  * in the bit length tree.
627  */
628 local void scan_tree (s, tree, max_code)
629     deflate_state *s;
630     ct_data *tree;   /* the tree to be scanned */
631     int max_code;    /* and its largest code of non zero frequency */
632 {
633     int n;                     /* iterates over all tree elements */
634     int prevlen = -1;          /* last emitted length */
635     int curlen;                /* length of current code */
636     int nextlen = tree[0].Len; /* length of next code */
637     int count = 0;             /* repeat count of the current code */
638     int max_count = 7;         /* max repeat count */
639     int min_count = 4;         /* min repeat count */
640
641     if (nextlen == 0) max_count = 138, min_count = 3;
642     tree[max_code+1].Len = (ush)0xffff; /* guard */
643
644     for (n = 0; n <= max_code; n++) {
645         curlen = nextlen; nextlen = tree[n+1].Len;
646         if (++count < max_count && curlen == nextlen) {
647             continue;
648         } else if (count < min_count) {
649             s->bl_tree[curlen].Freq += count;
650         } else if (curlen != 0) {
651             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
652             s->bl_tree[REP_3_6].Freq++;
653         } else if (count <= 10) {
654             s->bl_tree[REPZ_3_10].Freq++;
655         } else {
656             s->bl_tree[REPZ_11_138].Freq++;
657         }
658         count = 0; prevlen = curlen;
659         if (nextlen == 0) {
660             max_count = 138, min_count = 3;
661         } else if (curlen == nextlen) {
662             max_count = 6, min_count = 3;
663         } else {
664             max_count = 7, min_count = 4;
665         }
666     }
667 }
668
669 /* ===========================================================================
670  * Send a literal or distance tree in compressed form, using the codes in
671  * bl_tree.
672  */
673 local void send_tree (s, tree, max_code)
674     deflate_state *s;
675     ct_data *tree; /* the tree to be scanned */
676     int max_code;       /* and its largest code of non zero frequency */
677 {
678     int n;                     /* iterates over all tree elements */
679     int prevlen = -1;          /* last emitted length */
680     int curlen;                /* length of current code */
681     int nextlen = tree[0].Len; /* length of next code */
682     int count = 0;             /* repeat count of the current code */
683     int max_count = 7;         /* max repeat count */
684     int min_count = 4;         /* min repeat count */
685
686     /* tree[max_code+1].Len = -1; */  /* guard already set */
687     if (nextlen == 0) max_count = 138, min_count = 3;
688
689     for (n = 0; n <= max_code; n++) {
690         curlen = nextlen; nextlen = tree[n+1].Len;
691         if (++count < max_count && curlen == nextlen) {
692             continue;
693         } else if (count < min_count) {
694             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
695
696         } else if (curlen != 0) {
697             if (curlen != prevlen) {
698                 send_code(s, curlen, s->bl_tree); count--;
699             }
700             Assert(count >= 3 && count <= 6, " 3_6?");
701             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
702
703         } else if (count <= 10) {
704             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
705
706         } else {
707             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
708         }
709         count = 0; prevlen = curlen;
710         if (nextlen == 0) {
711             max_count = 138, min_count = 3;
712         } else if (curlen == nextlen) {
713             max_count = 6, min_count = 3;
714         } else {
715             max_count = 7, min_count = 4;
716         }
717     }
718 }
719
720 /* ===========================================================================
721  * Construct the Huffman tree for the bit lengths and return the index in
722  * bl_order of the last bit length code to send.
723  */
724 local int build_bl_tree(s)
725     deflate_state *s;
726 {
727     int max_blindex;  /* index of last bit length code of non zero freq */
728
729     /* Determine the bit length frequencies for literal and distance trees */
730     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
731     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
732
733     /* Build the bit length tree: */
734     build_tree(s, (tree_desc *)(&(s->bl_desc)));
735     /* opt_len now includes the length of the tree representations, except
736      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
737      */
738
739     /* Determine the number of bit length codes to send. The pkzip format
740      * requires that at least 4 bit length codes be sent. (appnote.txt says
741      * 3 but the actual value used is 4.)
742      */
743     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
744         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
745     }
746     /* Update opt_len to include the bit length tree and counts */
747     s->opt_len += 3*(max_blindex+1) + 5+5+4;
748     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
749             s->opt_len, s->static_len));
750
751     return max_blindex;
752 }
753
754 /* ===========================================================================
755  * Send the header for a block using dynamic Huffman trees: the counts, the
756  * lengths of the bit length codes, the literal tree and the distance tree.
757  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
758  */
759 local void send_all_trees(s, lcodes, dcodes, blcodes)
760     deflate_state *s;
761     int lcodes, dcodes, blcodes; /* number of codes for each tree */
762 {
763     int rank;                    /* index in bl_order */
764
765     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
766     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
767             "too many codes");
768     Tracev((stderr, "\nbl counts: "));
769     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
770     send_bits(s, dcodes-1,   5);
771     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
772     for (rank = 0; rank < blcodes; rank++) {
773         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
774         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
775     }
776     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
777
778     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
779     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
780
781     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
782     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
783 }
784
785 /* ===========================================================================
786  * Send a stored block
787  */
788 void _tr_stored_block(s, buf, stored_len, eof)
789     deflate_state *s;
790     charf *buf;       /* input block */
791     ulg stored_len;   /* length of input block */
792     int eof;          /* true if this is the last block for a file */
793 {
794     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
795     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
796     s->compressed_len += (stored_len + 4) << 3;
797
798     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
799 }
800
801 /* ===========================================================================
802  * Send one empty static block to give enough lookahead for inflate.
803  * This takes 10 bits, of which 7 may remain in the bit buffer.
804  * The current inflate code requires 9 bits of lookahead. If the
805  * last two codes for the previous block (real code plus EOB) were coded
806  * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
807  * the last real code. In this case we send two empty static blocks instead
808  * of one. (There are no problems if the previous block is stored or fixed.)
809  * To simplify the code, we assume the worst case of last real code encoded
810  * on one bit only.
811  */
812 void _tr_align(s)
813     deflate_state *s;
814 {
815     send_bits(s, STATIC_TREES<<1, 3);
816     send_code(s, END_BLOCK, static_ltree);
817     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
818     bi_flush(s);
819     /* Of the 10 bits for the empty block, we have already sent
820      * (10 - bi_valid) bits. The lookahead for the last real code (before
821      * the EOB of the previous block) was thus at least one plus the length
822      * of the EOB plus what we have just sent of the empty static block.
823      */
824     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
825         send_bits(s, STATIC_TREES<<1, 3);
826         send_code(s, END_BLOCK, static_ltree);
827         s->compressed_len += 10L;
828         bi_flush(s);
829     }
830     s->last_eob_len = 7;
831 }
832
833 /* ===========================================================================
834  * Determine the best encoding for the current block: dynamic trees, static
835  * trees or store, and output the encoded block to the zip file. This function
836  * returns the total compressed length for the file so far.
837  */
838 ulg _tr_flush_block(s, buf, stored_len, eof)
839     deflate_state *s;
840     charf *buf;       /* input block, or NULL if too old */
841     ulg stored_len;   /* length of input block */
842     int eof;          /* true if this is the last block for a file */
843 {
844     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
845     int max_blindex = 0;  /* index of last bit length code of non zero freq */
846
847     /* Build the Huffman trees unless a stored block is forced */
848     if (s->level > 0) {
849
850          /* Check if the file is ascii or binary */
851         if (s->data_type == Z_UNKNOWN) set_data_type(s);
852
853         /* Construct the literal and distance trees */
854         build_tree(s, (tree_desc *)(&(s->l_desc)));
855         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
856                 s->static_len));
857
858         build_tree(s, (tree_desc *)(&(s->d_desc)));
859         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
860                 s->static_len));
861         /* At this point, opt_len and static_len are the total bit lengths of
862          * the compressed block data, excluding the tree representations.
863          */
864
865         /* Build the bit length tree for the above two trees, and get the index
866          * in bl_order of the last bit length code to send.
867          */
868         max_blindex = build_bl_tree(s);
869
870         /* Determine the best encoding. Compute first the block length in bytes*/
871         opt_lenb = (s->opt_len+3+7)>>3;
872         static_lenb = (s->static_len+3+7)>>3;
873
874         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
875                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
876                 s->last_lit));
877
878         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
879
880     } else {
881         Assert(buf != (char*)0, "lost buf");
882         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
883     }
884
885     /* If compression failed and this is the first and last block,
886      * and if the .zip file can be seeked (to rewrite the local header),
887      * the whole file is transformed into a stored file:
888      */
889 #ifdef STORED_FILE_OK
890 #  ifdef FORCE_STORED_FILE
891     if (eof && s->compressed_len == 0L) { /* force stored file */
892 #  else
893     if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable()) {
894 #  endif
895         /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
896         if (buf == (charf*)0) error ("block vanished");
897
898         copy_block(buf, (unsigned)stored_len, 0); /* without header */
899         s->compressed_len = stored_len << 3;
900         s->method = STORED;
901     } else
902 #endif /* STORED_FILE_OK */
903
904 #ifdef FORCE_STORED
905     if (buf != (char*)0) { /* force stored block */
906 #else
907     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
908                        /* 4: two words for the lengths */
909 #endif
910         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
911          * Otherwise we can't have processed more than WSIZE input bytes since
912          * the last block flush, because compression would have been
913          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
914          * transform a block into a stored block.
915          */
916         _tr_stored_block(s, buf, stored_len, eof);
917
918 #ifdef FORCE_STATIC
919     } else if (static_lenb >= 0) { /* force static trees */
920 #else
921     } else if (static_lenb == opt_lenb) {
922 #endif
923         send_bits(s, (STATIC_TREES<<1)+eof, 3);
924         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
925         s->compressed_len += 3 + s->static_len;
926     } else {
927         send_bits(s, (DYN_TREES<<1)+eof, 3);
928         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
929                        max_blindex+1);
930         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
931         s->compressed_len += 3 + s->opt_len;
932     }
933     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
934     init_block(s);
935
936     if (eof) {
937         bi_windup(s);
938         s->compressed_len += 7;  /* align on byte boundary */
939     }
940     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
941            s->compressed_len-7*eof));
942
943     return s->compressed_len >> 3;
944 }
945
946 /* ===========================================================================
947  * Save the match info and tally the frequency counts. Return true if
948  * the current block must be flushed.
949  */
950 int _tr_tally (s, dist, lc)
951     deflate_state *s;
952     unsigned dist;  /* distance of matched string */
953     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
954 {
955     s->d_buf[s->last_lit] = (ush)dist;
956     s->l_buf[s->last_lit++] = (uch)lc;
957     if (dist == 0) {
958         /* lc is the unmatched char */
959         s->dyn_ltree[lc].Freq++;
960     } else {
961         s->matches++;
962         /* Here, lc is the match length - MIN_MATCH */
963         dist--;             /* dist = match distance - 1 */
964         Assert((ush)dist < (ush)MAX_DIST(s) &&
965                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
966                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
967
968         s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
969         s->dyn_dtree[d_code(dist)].Freq++;
970     }
971
972     /* Try to guess if it is profitable to stop the current block here */
973     if (s->level > 2 && (s->last_lit & 0xfff) == 0) {
974         /* Compute an upper bound for the compressed length */
975         ulg out_length = (ulg)s->last_lit*8L;
976         ulg in_length = (ulg)((long)s->strstart - s->block_start);
977         int dcode;
978         for (dcode = 0; dcode < D_CODES; dcode++) {
979             out_length += (ulg)s->dyn_dtree[dcode].Freq *
980                 (5L+extra_dbits[dcode]);
981         }
982         out_length >>= 3;
983         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
984                s->last_lit, in_length, out_length,
985                100L - out_length*100L/in_length));
986         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
987     }
988     return (s->last_lit == s->lit_bufsize-1);
989     /* We avoid equality with lit_bufsize because of wraparound at 64K
990      * on 16 bit machines and because stored blocks are restricted to
991      * 64K-1 bytes.
992      */
993 }
994
995 /* ===========================================================================
996  * Send the block data compressed using the given Huffman trees
997  */
998 local void compress_block(s, ltree, dtree)
999     deflate_state *s;
1000     ct_data *ltree; /* literal tree */
1001     ct_data *dtree; /* distance tree */
1002 {
1003     unsigned dist;      /* distance of matched string */
1004     int lc;             /* match length or unmatched char (if dist == 0) */
1005     unsigned lx = 0;    /* running index in l_buf */
1006     unsigned code;      /* the code to send */
1007     int extra;          /* number of extra bits to send */
1008
1009     if (s->last_lit != 0) do {
1010         dist = s->d_buf[lx];
1011         lc = s->l_buf[lx++];
1012         if (dist == 0) {
1013             send_code(s, lc, ltree); /* send a literal byte */
1014             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1015         } else {
1016             /* Here, lc is the match length - MIN_MATCH */
1017             code = length_code[lc];
1018             send_code(s, code+LITERALS+1, ltree); /* send the length code */
1019             extra = extra_lbits[code];
1020             if (extra != 0) {
1021                 lc -= base_length[code];
1022                 send_bits(s, lc, extra);       /* send the extra length bits */
1023             }
1024             dist--; /* dist is now the match distance - 1 */
1025             code = d_code(dist);
1026             Assert (code < D_CODES, "bad d_code");
1027
1028             send_code(s, code, dtree);       /* send the distance code */
1029             extra = extra_dbits[code];
1030             if (extra != 0) {
1031                 dist -= base_dist[code];
1032                 send_bits(s, dist, extra);   /* send the extra distance bits */
1033             }
1034         } /* literal or match pair ? */
1035
1036         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1037         Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
1038
1039     } while (lx < s->last_lit);
1040
1041     send_code(s, END_BLOCK, ltree);
1042     s->last_eob_len = ltree[END_BLOCK].Len;
1043 }
1044
1045 /* ===========================================================================
1046  * Set the data type to ASCII or BINARY, using a crude approximation:
1047  * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
1048  * IN assertion: the fields freq of dyn_ltree are set and the total of all
1049  * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
1050  */
1051 local void set_data_type(s)
1052     deflate_state *s;
1053 {
1054     int n = 0;
1055     unsigned ascii_freq = 0;
1056     unsigned bin_freq = 0;
1057     while (n < 7)        bin_freq += s->dyn_ltree[n++].Freq;
1058     while (n < 128)    ascii_freq += s->dyn_ltree[n++].Freq;
1059     while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
1060     s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
1061 }
1062
1063 /* ===========================================================================
1064  * Reverse the first len bits of a code, using straightforward code (a faster
1065  * method would use a table)
1066  * IN assertion: 1 <= len <= 15
1067  */
1068 local unsigned bi_reverse(code, len)
1069     unsigned code; /* the value to invert */
1070     int len;       /* its bit length */
1071 {
1072     register unsigned res = 0;
1073     do {
1074         res |= code & 1;
1075         code >>= 1, res <<= 1;
1076     } while (--len > 0);
1077     return res >> 1;
1078 }
1079
1080 /* ===========================================================================
1081  * Flush the bit buffer, keeping at most 7 bits in it.
1082  */
1083 local void bi_flush(s)
1084     deflate_state *s;
1085 {
1086     if (s->bi_valid == 16) {
1087         put_short(s, s->bi_buf);
1088         s->bi_buf = 0;
1089         s->bi_valid = 0;
1090     } else if (s->bi_valid >= 8) {
1091         put_byte(s, (Byte)s->bi_buf);
1092         s->bi_buf >>= 8;
1093         s->bi_valid -= 8;
1094     }
1095 }
1096
1097 /* ===========================================================================
1098  * Flush the bit buffer and align the output on a byte boundary
1099  */
1100 local void bi_windup(s)
1101     deflate_state *s;
1102 {
1103     if (s->bi_valid > 8) {
1104         put_short(s, s->bi_buf);
1105     } else if (s->bi_valid > 0) {
1106         put_byte(s, (Byte)s->bi_buf);
1107     }
1108     s->bi_buf = 0;
1109     s->bi_valid = 0;
1110 #ifdef DEBUG
1111     s->bits_sent = (s->bits_sent+7) & ~7;
1112 #endif
1113 }
1114
1115 /* ===========================================================================
1116  * Copy a stored block, storing first the length and its
1117  * one's complement if requested.
1118  */
1119 local void copy_block(s, buf, len, header)
1120     deflate_state *s;
1121     charf    *buf;    /* the input data */
1122     unsigned len;     /* its length */
1123     int      header;  /* true if block header must be written */
1124 {
1125     bi_windup(s);        /* align on byte boundary */
1126     s->last_eob_len = 8; /* enough lookahead for inflate */
1127
1128     if (header) {
1129         put_short(s, (ush)len);   
1130         put_short(s, (ush)~len);
1131 #ifdef DEBUG
1132         s->bits_sent += 2*16;
1133 #endif
1134     }
1135 #ifdef DEBUG
1136     s->bits_sent += (ulg)len<<3;
1137 #endif
1138     while (len--) {
1139         put_byte(s, *buf++);
1140     }
1141 }