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
9 * The "deflation" process uses several Huffman trees. The more
10 * common source values are represented by shorter bit sequences.
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.
20 * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
21 * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
24 * Data Compression: Methods and Theory, pp. 49-50.
25 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
29 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
32 /* $Id: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */
40 /* ===========================================================================
45 /* Bit length codes must not exceed MAX_BL_BITS bits */
48 /* end of block literal code */
51 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
54 /* repeat a zero length 3-10 times (3 bits of repeat count) */
56 #define REPZ_11_138 18
57 /* repeat a zero length 11-138 times (7 bits of repeat count) */
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};
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};
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};
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.
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.)
79 /* ===========================================================================
80 * Local data. These are initialized only once.
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
90 local ct_data static_dtree[D_CODES];
91 /* The static distance tree. (Actually a trivial tree since all codes use
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.
101 local uch length_code[MAX_MATCH-MIN_MATCH+1];
102 /* length code for each normalized match length (0 == MIN_MATCH) */
104 local int base_length[LENGTH_CODES];
105 /* First normalized length for each code (0 = MIN_MATCH) */
107 local int base_dist[D_CODES];
108 /* First normalized distance for each code (0 = distance of 1) */
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 */
118 local static_tree_desc static_l_desc =
119 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
121 local static_tree_desc static_d_desc =
122 {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
124 local static_tree_desc static_bl_desc =
125 {(ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
127 /* ===========================================================================
128 * Local (static) routines in this file.
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,
142 local void compress_block OF((deflate_state *s, ct_data *ltree,
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,
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 */
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); }
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
168 /* ===========================================================================
169 * Output a short LSB first on the stream.
170 * IN assertion: there is enough room in pendingBuf.
172 #define put_short(s, w) { \
173 put_byte(s, (uch)((w) & 0xff)); \
174 put_byte(s, (uch)((ush)(w) >> 8)); \
177 /* ===========================================================================
178 * Send a value on a given number of bits.
179 * IN assertion: length <= 16 and value fits in length bits.
182 local void send_bits OF((deflate_state *s, int value, int length));
184 local void send_bits(s, value, length)
186 int value; /* value to send */
187 int length; /* number of bits */
189 Tracevv((stderr," l %2d v %4x ", length, value));
190 Assert(length > 0 && length <= 15, "invalid length");
191 s->bits_sent += (ulg)length;
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.
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;
203 s->bi_buf |= value << s->bi_valid;
204 s->bi_valid += length;
209 #define send_bits(s, value, length) \
211 if (s->bi_valid > (int)Buf_size - len) {\
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;\
218 s->bi_buf |= (value) << s->bi_valid;\
225 #define MAX(a,b) (a >= b ? a : b)
226 /* the arguments must not have side effects */
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.
233 local void tr_static_init()
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 */
244 if (static_init_done) return;
246 /* Initialize the mapping length (0..255) -> length code (0..28) */
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;
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:
259 length_code[length-1] = (uch)code;
261 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
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;
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;
277 Assert (dist == 256, "tr_static_init: 256+dist != 512");
279 /* Construct the codes of the static literal tree */
280 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 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
290 gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
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);
297 static_init_done = 1;
300 /* ===========================================================================
301 * Initialize the tree data structures for a new zlib stream.
308 s->compressed_len = 0L;
310 s->l_desc.dyn_tree = s->dyn_ltree;
311 s->l_desc.stat_desc = &static_l_desc;
313 s->d_desc.dyn_tree = s->dyn_dtree;
314 s->d_desc.stat_desc = &static_d_desc;
316 s->bl_desc.dyn_tree = s->bl_tree;
317 s->bl_desc.stat_desc = &static_bl_desc;
321 s->last_eob_len = 8; /* enough lookahead for inflate */
326 /* Initialize the first block of the first file: */
330 /* ===========================================================================
331 * Initialize a new block.
333 local void init_block(s)
336 int n; /* iterates over tree elements */
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;
343 s->dyn_ltree[END_BLOCK].Freq = 1;
344 s->opt_len = s->static_len = 0L;
345 s->last_lit = s->matches = 0;
349 /* Index within the heap array of least frequent node in the Huffman tree */
352 /* ===========================================================================
353 * Remove the smallest element from the heap and recreate the heap with
354 * one less element. Updates heap and heap_len.
356 #define pqremove(s, tree, top) \
358 top = s->heap[SMALLEST]; \
359 s->heap[SMALLEST] = s->heap[s->heap_len--]; \
360 pqdownheap(s, tree, SMALLEST); \
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.
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]))
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
377 local void pqdownheap(s, tree, k)
379 ct_data *tree; /* the tree to restore */
380 int k; /* node to move down */
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)) {
390 /* Exit if v is smaller than both sons */
391 if (smaller(tree, v, s->heap[j], s->depth)) break;
393 /* Exchange v with the smallest son */
394 s->heap[k] = s->heap[j]; k = j;
396 /* And continue down the tree, setting j to the left son of k */
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
412 local void gen_bitlen(s, desc)
414 tree_desc *desc; /* the tree descriptor */
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 */
429 for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
431 /* In a first pass, compute the optimal bit lengths (which may
432 * overflow in the case of the bit length tree).
434 tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
436 for (h = s->heap_max+1; h < HEAP_SIZE; 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 */
443 if (n > max_code) continue; /* not a leaf node */
447 if (n >= base) xbits = extra[n-base];
449 s->opt_len += (ulg)f * (bits + xbits);
450 if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
452 if (overflow == 0) return;
454 Trace((stderr,"\nbit length overflow\n"));
455 /* This happens for example on obj2 and pic of the Calgary corpus */
457 /* Find the first bit length which could increase: */
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]
468 } while (overflow > 0);
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.)
475 for (bits = max_length; bits != 0; bits--) {
476 n = s->bl_count[bits];
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)
484 tree[m].Len = (ush)bits;
491 /* ===========================================================================
492 * Generate the codes for a given tree and bit counts (which need not be
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
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 */
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 */
509 /* The distribution counts are first used to generate the code values
510 * without bit reversal.
512 for (bits = 1; bits <= MAX_BITS; bits++) {
513 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
515 /* Check that the bit counts in bl_count are consistent. The last code
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));
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);
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));
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.
541 local void build_tree(s, desc)
543 tree_desc *desc; /* the tree descriptor */
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 */
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.
556 s->heap_len = 0, s->heap_max = HEAP_SIZE;
558 for (n = 0; n < elems; n++) {
559 if (tree[n].Freq != 0) {
560 s->heap[++(s->heap_len)] = max_code = n;
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.
572 while (s->heap_len < 2) {
573 node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 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 */
579 desc->max_code = max_code;
581 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
582 * establish sub-heaps of increasing lengths:
584 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
586 /* Construct the Huffman tree by repeatedly combining the least two
589 node = elems; /* next internal node of the tree */
591 pqremove(s, tree, n); /* n = node of least frequency */
592 m = s->heap[SMALLEST]; /* m = node of next least frequency */
594 s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
595 s->heap[--(s->heap_max)] = m;
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;
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);
607 /* and insert the new node in the heap */
608 s->heap[SMALLEST] = node++;
609 pqdownheap(s, tree, SMALLEST);
611 } while (s->heap_len >= 2);
613 s->heap[--(s->heap_max)] = s->heap[SMALLEST];
615 /* At this point, the fields freq and dad are set. We can now
616 * generate the bit lengths.
618 gen_bitlen(s, (tree_desc *)desc);
620 /* The field len is now set, we can generate the bit codes */
621 gen_codes ((ct_data *)tree, max_code, s->bl_count);
624 /* ===========================================================================
625 * Scan a literal or distance tree to determine the frequencies of the codes
626 * in the bit length tree.
628 local void scan_tree (s, tree, max_code)
630 ct_data *tree; /* the tree to be scanned */
631 int max_code; /* and its largest code of non zero frequency */
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 */
641 if (nextlen == 0) max_count = 138, min_count = 3;
642 tree[max_code+1].Len = (ush)0xffff; /* guard */
644 for (n = 0; n <= max_code; n++) {
645 curlen = nextlen; nextlen = tree[n+1].Len;
646 if (++count < max_count && curlen == nextlen) {
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++;
656 s->bl_tree[REPZ_11_138].Freq++;
658 count = 0; prevlen = curlen;
660 max_count = 138, min_count = 3;
661 } else if (curlen == nextlen) {
662 max_count = 6, min_count = 3;
664 max_count = 7, min_count = 4;
669 /* ===========================================================================
670 * Send a literal or distance tree in compressed form, using the codes in
673 local void send_tree (s, tree, max_code)
675 ct_data *tree; /* the tree to be scanned */
676 int max_code; /* and its largest code of non zero frequency */
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 */
686 /* tree[max_code+1].Len = -1; */ /* guard already set */
687 if (nextlen == 0) max_count = 138, min_count = 3;
689 for (n = 0; n <= max_code; n++) {
690 curlen = nextlen; nextlen = tree[n+1].Len;
691 if (++count < max_count && curlen == nextlen) {
693 } else if (count < min_count) {
694 do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
696 } else if (curlen != 0) {
697 if (curlen != prevlen) {
698 send_code(s, curlen, s->bl_tree); count--;
700 Assert(count >= 3 && count <= 6, " 3_6?");
701 send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
703 } else if (count <= 10) {
704 send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
707 send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
709 count = 0; prevlen = curlen;
711 max_count = 138, min_count = 3;
712 } else if (curlen == nextlen) {
713 max_count = 6, min_count = 3;
715 max_count = 7, min_count = 4;
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.
724 local int build_bl_tree(s)
727 int max_blindex; /* index of last bit length code of non zero freq */
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);
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.
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.)
743 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
744 if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
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));
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.
759 local void send_all_trees(s, lcodes, dcodes, blcodes)
761 int lcodes, dcodes, blcodes; /* number of codes for each tree */
763 int rank; /* index in bl_order */
765 Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
766 Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_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);
776 Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
778 send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
779 Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
781 send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
782 Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
785 /* ===========================================================================
786 * Send a stored block
788 void _tr_stored_block(s, buf, stored_len, eof)
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 */
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;
798 copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
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
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 */
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.
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;
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.
838 ulg _tr_flush_block(s, buf, stored_len, eof)
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 */
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 */
847 /* Build the Huffman trees unless a stored block is forced */
850 /* Check if the file is ascii or binary */
851 if (s->data_type == Z_UNKNOWN) set_data_type(s);
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,
858 build_tree(s, (tree_desc *)(&(s->d_desc)));
859 Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_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.
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.
868 max_blindex = build_bl_tree(s);
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;
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,
878 if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
881 Assert(buf != (char*)0, "lost buf");
882 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
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:
889 #ifdef STORED_FILE_OK
890 # ifdef FORCE_STORED_FILE
891 if (eof && s->compressed_len == 0L) { /* force stored file */
893 if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable()) {
895 /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
896 if (buf == (charf*)0) error ("block vanished");
898 copy_block(buf, (unsigned)stored_len, 0); /* without header */
899 s->compressed_len = stored_len << 3;
902 #endif /* STORED_FILE_OK */
905 if (buf != (char*)0) { /* force stored block */
907 if (stored_len+4 <= opt_lenb && buf != (char*)0) {
908 /* 4: two words for the lengths */
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.
916 _tr_stored_block(s, buf, stored_len, eof);
919 } else if (static_lenb >= 0) { /* force static trees */
921 } else if (static_lenb == opt_lenb) {
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;
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,
930 compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
931 s->compressed_len += 3 + s->opt_len;
933 Assert (s->compressed_len == s->bits_sent, "bad compressed size");
938 s->compressed_len += 7; /* align on byte boundary */
940 Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
941 s->compressed_len-7*eof));
943 return s->compressed_len >> 3;
946 /* ===========================================================================
947 * Save the match info and tally the frequency counts. Return true if
948 * the current block must be flushed.
950 int _tr_tally (s, dist, lc)
952 unsigned dist; /* distance of matched string */
953 unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
955 s->d_buf[s->last_lit] = (ush)dist;
956 s->l_buf[s->last_lit++] = (uch)lc;
958 /* lc is the unmatched char */
959 s->dyn_ltree[lc].Freq++;
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");
968 s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
969 s->dyn_dtree[d_code(dist)].Freq++;
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);
978 for (dcode = 0; dcode < D_CODES; dcode++) {
979 out_length += (ulg)s->dyn_dtree[dcode].Freq *
980 (5L+extra_dbits[dcode]);
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;
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
995 /* ===========================================================================
996 * Send the block data compressed using the given Huffman trees
998 local void compress_block(s, ltree, dtree)
1000 ct_data *ltree; /* literal tree */
1001 ct_data *dtree; /* distance tree */
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 */
1009 if (s->last_lit != 0) do {
1010 dist = s->d_buf[lx];
1011 lc = s->l_buf[lx++];
1013 send_code(s, lc, ltree); /* send a literal byte */
1014 Tracecv(isgraph(lc), (stderr," '%c' ", lc));
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];
1021 lc -= base_length[code];
1022 send_bits(s, lc, extra); /* send the extra length bits */
1024 dist--; /* dist is now the match distance - 1 */
1025 code = d_code(dist);
1026 Assert (code < D_CODES, "bad d_code");
1028 send_code(s, code, dtree); /* send the distance code */
1029 extra = extra_dbits[code];
1031 dist -= base_dist[code];
1032 send_bits(s, dist, extra); /* send the extra distance bits */
1034 } /* literal or match pair ? */
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");
1039 } while (lx < s->last_lit);
1041 send_code(s, END_BLOCK, ltree);
1042 s->last_eob_len = ltree[END_BLOCK].Len;
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).
1051 local void set_data_type(s)
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);
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
1068 local unsigned bi_reverse(code, len)
1069 unsigned code; /* the value to invert */
1070 int len; /* its bit length */
1072 register unsigned res = 0;
1075 code >>= 1, res <<= 1;
1076 } while (--len > 0);
1080 /* ===========================================================================
1081 * Flush the bit buffer, keeping at most 7 bits in it.
1083 local void bi_flush(s)
1086 if (s->bi_valid == 16) {
1087 put_short(s, s->bi_buf);
1090 } else if (s->bi_valid >= 8) {
1091 put_byte(s, (Byte)s->bi_buf);
1097 /* ===========================================================================
1098 * Flush the bit buffer and align the output on a byte boundary
1100 local void bi_windup(s)
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);
1111 s->bits_sent = (s->bits_sent+7) & ~7;
1115 /* ===========================================================================
1116 * Copy a stored block, storing first the length and its
1117 * one's complement if requested.
1119 local void copy_block(s, buf, len, header)
1121 charf *buf; /* the input data */
1122 unsigned len; /* its length */
1123 int header; /* true if block header must be written */
1125 bi_windup(s); /* align on byte boundary */
1126 s->last_eob_len = 8; /* enough lookahead for inflate */
1129 put_short(s, (ush)len);
1130 put_short(s, (ush)~len);
1132 s->bits_sent += 2*16;
1136 s->bits_sent += (ulg)len<<3;
1139 put_byte(s, *buf++);