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