1 /* trees.c -- output deflated data using Huffman coding
2 * Copyright (C) 1995-2010 Jean-loup Gailly
3 * detect_data_type() function provided freely by Cosmin Truta, 2006
4 * For conditions of distribution and use, see copyright notice in zlib.h
10 * The "deflation" process uses several Huffman trees. The more
11 * common source values are represented by shorter bit sequences.
13 * Each code tree is stored in a compressed form which is itself
14 * a Huffman encoding of the lengths of all the code strings (in
15 * ascending order by source values). The actual code strings are
16 * reconstructed from the lengths in the inflate process, as
17 * described in the deflate specification.
22 * RFC 1951, DEFLATE Compressed Data Format Specification version 1.3
23 * https://tools.ietf.org/html/rfc1951, 1996
26 * Data Compression: Methods and Theory, pp. 49-50.
27 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
31 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
36 /* #define GEN_TREES_H */
41 # include <linux/ctype.h>
44 /* ===========================================================================
49 /* Bit length codes must not exceed MAX_BL_BITS bits */
52 /* end of block literal code */
55 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
58 /* repeat a zero length 3-10 times (3 bits of repeat count) */
60 #define REPZ_11_138 18
61 /* repeat a zero length 11-138 times (7 bits of repeat count) */
63 local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
64 = {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};
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};
69 local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
70 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
72 local const uch bl_order[BL_CODES]
73 = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
74 /* The lengths of the bit length codes are sent in order of decreasing
75 * probability, to avoid transmitting the lengths for unused bit length codes.
78 #define Buf_size (8 * 2*sizeof(char))
79 /* Number of bits used within bi_buf. (bi_buf might be implemented on
80 * more than 16 bits on some systems.)
83 /* ===========================================================================
84 * Local data. These are initialized only once.
87 #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
89 #if defined(GEN_TREES_H) || !defined(STDC)
90 /* non ANSI compilers may not accept trees.h */
92 local ct_data static_ltree[L_CODES+2];
93 /* The static literal tree. Since the bit lengths are imposed, there is no
94 * need for the L_CODES extra codes used during heap construction. However
95 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
99 local ct_data static_dtree[D_CODES];
100 /* The static distance tree. (Actually a trivial tree since all codes use
104 uch _dist_code[DIST_CODE_LEN];
105 /* Distance codes. The first 256 values correspond to the distances
106 * 3 .. 258, the last 256 values correspond to the top 8 bits of
107 * the 15 bit distances.
110 uch _length_code[MAX_MATCH-MIN_MATCH+1];
111 /* length code for each normalized match length (0 == MIN_MATCH) */
113 local int base_length[LENGTH_CODES];
114 /* First normalized length for each code (0 = MIN_MATCH) */
116 local int base_dist[D_CODES];
117 /* First normalized distance for each code (0 = distance of 1) */
121 #endif /* GEN_TREES_H */
123 struct static_tree_desc_s {
124 const ct_data *static_tree; /* static tree or NULL */
125 const intf *extra_bits; /* extra bits for each code or NULL */
126 int extra_base; /* base index for extra_bits */
127 int elems; /* max number of elements in the tree */
128 int max_length; /* max bit length for the codes */
131 local static_tree_desc static_l_desc =
132 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
134 local static_tree_desc static_d_desc =
135 {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
137 local static_tree_desc static_bl_desc =
138 {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
140 /* ===========================================================================
141 * Local (static) routines in this file.
144 local void tr_static_init OF((void));
145 local void init_block OF((deflate_state *s));
146 local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
147 local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
148 local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
149 local void build_tree OF((deflate_state *s, tree_desc *desc));
150 local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
151 local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
152 local int build_bl_tree OF((deflate_state *s));
153 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
155 local void compress_block OF((deflate_state *s, ct_data *ltree,
157 local int detect_data_type OF((deflate_state *s));
158 local unsigned bi_reverse OF((unsigned value, int length));
159 local void bi_windup OF((deflate_state *s));
160 local void bi_flush OF((deflate_state *s));
161 local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
165 local void gen_trees_header OF((void));
169 # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
170 /* Send a code of the given tree. c and tree must not have side effects */
173 # define send_code(s, c, tree) \
174 { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
175 send_bits(s, tree[c].Code, tree[c].Len); }
178 /* ===========================================================================
179 * Output a short LSB first on the stream.
180 * IN assertion: there is enough room in pendingBuf.
182 #define put_short(s, w) { \
183 put_byte(s, (uch)((w) & 0xff)); \
184 put_byte(s, (uch)((ush)(w) >> 8)); \
187 /* ===========================================================================
188 * Send a value on a given number of bits.
189 * IN assertion: length <= 16 and value fits in length bits.
192 local void send_bits OF((deflate_state *s, int value, int length));
194 local void send_bits(s, value, length)
196 int value; /* value to send */
197 int length; /* number of bits */
199 Tracevv((stderr," l %2d v %4x ", length, value));
200 Assert(length > 0 && length <= 15, "invalid length");
201 s->bits_sent += (ulg)length;
203 /* If not enough room in bi_buf, use (valid) bits from bi_buf and
204 * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
205 * unused bits in value.
207 if (s->bi_valid > (int)Buf_size - length) {
208 s->bi_buf |= (ush)value << s->bi_valid;
209 put_short(s, s->bi_buf);
210 s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
211 s->bi_valid += length - Buf_size;
213 s->bi_buf |= (ush)value << s->bi_valid;
214 s->bi_valid += length;
219 #define send_bits(s, value, length) \
221 if (s->bi_valid > (int)Buf_size - len) {\
223 s->bi_buf |= (ush)val << s->bi_valid;\
224 put_short(s, s->bi_buf);\
225 s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
226 s->bi_valid += len - Buf_size;\
228 s->bi_buf |= (ush)(value) << s->bi_valid;\
235 /* the arguments must not have side effects */
237 /* ===========================================================================
238 * Initialize the various 'constant' tables.
240 local void tr_static_init()
242 #if defined(GEN_TREES_H) || !defined(STDC)
243 static int static_init_done = 0;
244 int n; /* iterates over tree elements */
245 int bits; /* bit counter */
246 int length; /* length value */
247 int code; /* code value */
248 int dist; /* distance index */
249 ush bl_count[MAX_BITS+1];
250 /* number of codes at each bit length for an optimal tree */
252 if (static_init_done) return;
254 /* For some embedded targets, global variables are not initialized: */
255 #ifdef NO_INIT_GLOBAL_POINTERS
256 static_l_desc.static_tree = static_ltree;
257 static_l_desc.extra_bits = extra_lbits;
258 static_d_desc.static_tree = static_dtree;
259 static_d_desc.extra_bits = extra_dbits;
260 static_bl_desc.extra_bits = extra_blbits;
263 /* Initialize the mapping length (0..255) -> length code (0..28) */
265 for (code = 0; code < LENGTH_CODES-1; code++) {
266 base_length[code] = length;
267 for (n = 0; n < (1<<extra_lbits[code]); n++) {
268 _length_code[length++] = (uch)code;
271 Assert (length == 256, "tr_static_init: length != 256");
272 /* Note that the length 255 (match length 258) can be represented
273 * in two different ways: code 284 + 5 bits or code 285, so we
274 * overwrite length_code[255] to use the best encoding:
276 _length_code[length-1] = (uch)code;
278 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
280 for (code = 0 ; code < 16; code++) {
281 base_dist[code] = dist;
282 for (n = 0; n < (1<<extra_dbits[code]); n++) {
283 _dist_code[dist++] = (uch)code;
286 Assert (dist == 256, "tr_static_init: dist != 256");
287 dist >>= 7; /* from now on, all distances are divided by 128 */
288 for ( ; code < D_CODES; code++) {
289 base_dist[code] = dist << 7;
290 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
291 _dist_code[256 + dist++] = (uch)code;
294 Assert (dist == 256, "tr_static_init: 256+dist != 512");
296 /* Construct the codes of the static literal tree */
297 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
299 while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
300 while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
301 while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
302 while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
303 /* Codes 286 and 287 do not exist, but we must include them in the
304 * tree construction to get a canonical Huffman tree (longest code
307 gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
309 /* The static distance tree is trivial: */
310 for (n = 0; n < D_CODES; n++) {
311 static_dtree[n].Len = 5;
312 static_dtree[n].Code = bi_reverse((unsigned)n, 5);
314 static_init_done = 1;
319 #endif /* defined(GEN_TREES_H) || !defined(STDC) */
322 /* ===========================================================================
323 * Genererate the file trees.h describing the static trees.
330 # define SEPARATOR(i, last, width) \
331 ((i) == (last)? "\n};\n\n" : \
332 ((i) % (width) == (width)-1 ? ",\n" : ", "))
334 void gen_trees_header()
336 FILE *header = fopen("trees.h", "w");
339 Assert (header != NULL, "Can't open trees.h");
341 "/* header created automatically with -DGEN_TREES_H */\n\n");
343 fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
344 for (i = 0; i < L_CODES+2; i++) {
345 fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
346 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
349 fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
350 for (i = 0; i < D_CODES; i++) {
351 fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
352 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
355 fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
356 for (i = 0; i < DIST_CODE_LEN; i++) {
357 fprintf(header, "%2u%s", _dist_code[i],
358 SEPARATOR(i, DIST_CODE_LEN-1, 20));
362 "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
363 for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
364 fprintf(header, "%2u%s", _length_code[i],
365 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
368 fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
369 for (i = 0; i < LENGTH_CODES; i++) {
370 fprintf(header, "%1u%s", base_length[i],
371 SEPARATOR(i, LENGTH_CODES-1, 20));
374 fprintf(header, "local const int base_dist[D_CODES] = {\n");
375 for (i = 0; i < D_CODES; i++) {
376 fprintf(header, "%5u%s", base_dist[i],
377 SEPARATOR(i, D_CODES-1, 10));
382 #endif /* GEN_TREES_H */
384 /* ===========================================================================
385 * Initialize the tree data structures for a new zlib stream.
387 void ZLIB_INTERNAL _tr_init(s)
392 s->l_desc.dyn_tree = s->dyn_ltree;
393 s->l_desc.stat_desc = &static_l_desc;
395 s->d_desc.dyn_tree = s->dyn_dtree;
396 s->d_desc.stat_desc = &static_d_desc;
398 s->bl_desc.dyn_tree = s->bl_tree;
399 s->bl_desc.stat_desc = &static_bl_desc;
403 s->last_eob_len = 8; /* enough lookahead for inflate */
405 s->compressed_len = 0L;
409 /* Initialize the first block of the first file: */
413 /* ===========================================================================
414 * Initialize a new block.
416 local void init_block(s)
419 int n; /* iterates over tree elements */
421 /* Initialize the trees. */
422 for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
423 for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
424 for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
426 s->dyn_ltree[END_BLOCK].Freq = 1;
427 s->opt_len = s->static_len = 0L;
428 s->last_lit = s->matches = 0;
432 /* Index within the heap array of least frequent node in the Huffman tree */
435 /* ===========================================================================
436 * Remove the smallest element from the heap and recreate the heap with
437 * one less element. Updates heap and heap_len.
439 #define pqremove(s, tree, top) \
441 top = s->heap[SMALLEST]; \
442 s->heap[SMALLEST] = s->heap[s->heap_len--]; \
443 pqdownheap(s, tree, SMALLEST); \
446 /* ===========================================================================
447 * Compares to subtrees, using the tree depth as tie breaker when
448 * the subtrees have equal frequency. This minimizes the worst case length.
450 #define smaller(tree, n, m, depth) \
451 (tree[n].Freq < tree[m].Freq || \
452 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
454 /* ===========================================================================
455 * Restore the heap property by moving down the tree starting at node k,
456 * exchanging a node with the smallest of its two sons if necessary, stopping
457 * when the heap property is re-established (each father smaller than its
460 local void pqdownheap(s, tree, k)
462 ct_data *tree; /* the tree to restore */
463 int k; /* node to move down */
466 int j = k << 1; /* left son of k */
467 while (j <= s->heap_len) {
468 /* Set j to the smallest of the two sons: */
469 if (j < s->heap_len &&
470 smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
473 /* Exit if v is smaller than both sons */
474 if (smaller(tree, v, s->heap[j], s->depth)) break;
476 /* Exchange v with the smallest son */
477 s->heap[k] = s->heap[j]; k = j;
479 /* And continue down the tree, setting j to the left son of k */
485 /* ===========================================================================
486 * Compute the optimal bit lengths for a tree and update the total bit length
487 * for the current block.
488 * IN assertion: the fields freq and dad are set, heap[heap_max] and
489 * above are the tree nodes sorted by increasing frequency.
490 * OUT assertions: the field len is set to the optimal bit length, the
491 * array bl_count contains the frequencies for each bit length.
492 * The length opt_len is updated; static_len is also updated if stree is
495 local void gen_bitlen(s, desc)
497 tree_desc *desc; /* the tree descriptor */
499 ct_data *tree = desc->dyn_tree;
500 int max_code = desc->max_code;
501 const ct_data *stree = desc->stat_desc->static_tree;
502 const intf *extra = desc->stat_desc->extra_bits;
503 int base = desc->stat_desc->extra_base;
504 int max_length = desc->stat_desc->max_length;
505 int h; /* heap index */
506 int n, m; /* iterate over the tree elements */
507 int bits; /* bit length */
508 int xbits; /* extra bits */
509 ush f; /* frequency */
510 int overflow = 0; /* number of elements with bit length too large */
512 for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
514 /* In a first pass, compute the optimal bit lengths (which may
515 * overflow in the case of the bit length tree).
517 tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
519 for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
521 bits = tree[tree[n].Dad].Len + 1;
522 if (bits > max_length) bits = max_length, overflow++;
523 tree[n].Len = (ush)bits;
524 /* We overwrite tree[n].Dad which is no longer needed */
526 if (n > max_code) continue; /* not a leaf node */
530 if (n >= base) xbits = extra[n-base];
532 s->opt_len += (ulg)f * (bits + xbits);
533 if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
535 if (overflow == 0) return;
537 Trace((stderr,"\nbit length overflow\n"));
538 /* This happens for example on obj2 and pic of the Calgary corpus */
540 /* Find the first bit length which could increase: */
543 while (s->bl_count[bits] == 0) bits--;
544 s->bl_count[bits]--; /* move one leaf down the tree */
545 s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
546 s->bl_count[max_length]--;
547 /* The brother of the overflow item also moves one step up,
548 * but this does not affect bl_count[max_length]
551 } while (overflow > 0);
553 /* Now recompute all bit lengths, scanning in increasing frequency.
554 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
555 * lengths instead of fixing only the wrong ones. This idea is taken
556 * from 'ar' written by Haruhiko Okumura.)
558 for (bits = max_length; bits != 0; bits--) {
559 n = s->bl_count[bits];
562 if (m > max_code) continue;
563 if ((unsigned) tree[m].Len != (unsigned) bits) {
564 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
565 s->opt_len += ((long)bits - (long)tree[m].Len)
567 tree[m].Len = (ush)bits;
574 /* ===========================================================================
575 * Generate the codes for a given tree and bit counts (which need not be
577 * IN assertion: the array bl_count contains the bit length statistics for
578 * the given tree and the field len is set for all tree elements.
579 * OUT assertion: the field code is set for all tree elements of non
582 local void gen_codes (tree, max_code, bl_count)
583 ct_data *tree; /* the tree to decorate */
584 int max_code; /* largest code with non zero frequency */
585 ushf *bl_count; /* number of codes at each bit length */
587 ush next_code[MAX_BITS+1]; /* next code value for each bit length */
588 ush code = 0; /* running code value */
589 int bits; /* bit index */
590 int n; /* code index */
592 /* The distribution counts are first used to generate the code values
593 * without bit reversal.
595 for (bits = 1; bits <= MAX_BITS; bits++) {
596 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
598 /* Check that the bit counts in bl_count are consistent. The last code
601 Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
602 "inconsistent bit counts");
603 Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
605 for (n = 0; n <= max_code; n++) {
606 int len = tree[n].Len;
607 if (len == 0) continue;
608 /* Now reverse the bits */
609 tree[n].Code = bi_reverse(next_code[len]++, len);
611 Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
612 n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
616 /* ===========================================================================
617 * Construct one Huffman tree and assigns the code bit strings and lengths.
618 * Update the total bit length for the current block.
619 * IN assertion: the field freq is set for all tree elements.
620 * OUT assertions: the fields len and code are set to the optimal bit length
621 * and corresponding code. The length opt_len is updated; static_len is
622 * also updated if stree is not null. The field max_code is set.
624 local void build_tree(s, desc)
626 tree_desc *desc; /* the tree descriptor */
628 ct_data *tree = desc->dyn_tree;
629 const ct_data *stree = desc->stat_desc->static_tree;
630 int elems = desc->stat_desc->elems;
631 int n, m; /* iterate over heap elements */
632 int max_code = -1; /* largest code with non zero frequency */
633 int node; /* new node being created */
635 /* Construct the initial heap, with least frequent element in
636 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
637 * heap[0] is not used.
639 s->heap_len = 0, s->heap_max = HEAP_SIZE;
641 for (n = 0; n < elems; n++) {
642 if (tree[n].Freq != 0) {
643 s->heap[++(s->heap_len)] = max_code = n;
650 /* The pkzip format requires that at least one distance code exists,
651 * and that at least one bit should be sent even if there is only one
652 * possible code. So to avoid special checks later on we force at least
653 * two codes of non zero frequency.
655 while (s->heap_len < 2) {
656 node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
659 s->opt_len--; if (stree) s->static_len -= stree[node].Len;
660 /* node is 0 or 1 so it does not have extra bits */
662 desc->max_code = max_code;
664 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
665 * establish sub-heaps of increasing lengths:
667 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
669 /* Construct the Huffman tree by repeatedly combining the least two
672 node = elems; /* next internal node of the tree */
674 pqremove(s, tree, n); /* n = node of least frequency */
675 m = s->heap[SMALLEST]; /* m = node of next least frequency */
677 s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
678 s->heap[--(s->heap_max)] = m;
680 /* Create a new node father of n and m */
681 tree[node].Freq = tree[n].Freq + tree[m].Freq;
682 s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
683 s->depth[n] : s->depth[m]) + 1);
684 tree[n].Dad = tree[m].Dad = (ush)node;
686 if (tree == s->bl_tree) {
687 fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
688 node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
691 /* and insert the new node in the heap */
692 s->heap[SMALLEST] = node++;
693 pqdownheap(s, tree, SMALLEST);
695 } while (s->heap_len >= 2);
697 s->heap[--(s->heap_max)] = s->heap[SMALLEST];
699 /* At this point, the fields freq and dad are set. We can now
700 * generate the bit lengths.
702 gen_bitlen(s, (tree_desc *)desc);
704 /* The field len is now set, we can generate the bit codes */
705 gen_codes ((ct_data *)tree, max_code, s->bl_count);
708 /* ===========================================================================
709 * Scan a literal or distance tree to determine the frequencies of the codes
710 * in the bit length tree.
712 local void scan_tree (s, tree, max_code)
714 ct_data *tree; /* the tree to be scanned */
715 int max_code; /* and its largest code of non zero frequency */
717 int n; /* iterates over all tree elements */
718 int prevlen = -1; /* last emitted length */
719 int curlen; /* length of current code */
720 int nextlen = tree[0].Len; /* length of next code */
721 int count = 0; /* repeat count of the current code */
722 int max_count = 7; /* max repeat count */
723 int min_count = 4; /* min repeat count */
725 if (nextlen == 0) max_count = 138, min_count = 3;
726 tree[max_code+1].Len = (ush)0xffff; /* guard */
728 for (n = 0; n <= max_code; n++) {
729 curlen = nextlen; nextlen = tree[n+1].Len;
730 if (++count < max_count && curlen == nextlen) {
732 } else if (count < min_count) {
733 s->bl_tree[curlen].Freq += count;
734 } else if (curlen != 0) {
735 if (curlen != prevlen) s->bl_tree[curlen].Freq++;
736 s->bl_tree[REP_3_6].Freq++;
737 } else if (count <= 10) {
738 s->bl_tree[REPZ_3_10].Freq++;
740 s->bl_tree[REPZ_11_138].Freq++;
742 count = 0; prevlen = curlen;
744 max_count = 138, min_count = 3;
745 } else if (curlen == nextlen) {
746 max_count = 6, min_count = 3;
748 max_count = 7, min_count = 4;
753 /* ===========================================================================
754 * Send a literal or distance tree in compressed form, using the codes in
757 local void send_tree (s, tree, max_code)
759 ct_data *tree; /* the tree to be scanned */
760 int max_code; /* and its largest code of non zero frequency */
762 int n; /* iterates over all tree elements */
763 int prevlen = -1; /* last emitted length */
764 int curlen; /* length of current code */
765 int nextlen = tree[0].Len; /* length of next code */
766 int count = 0; /* repeat count of the current code */
767 int max_count = 7; /* max repeat count */
768 int min_count = 4; /* min repeat count */
770 /* tree[max_code+1].Len = -1; */ /* guard already set */
771 if (nextlen == 0) max_count = 138, min_count = 3;
773 for (n = 0; n <= max_code; n++) {
774 curlen = nextlen; nextlen = tree[n+1].Len;
775 if (++count < max_count && curlen == nextlen) {
777 } else if (count < min_count) {
778 do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
780 } else if (curlen != 0) {
781 if (curlen != prevlen) {
782 send_code(s, curlen, s->bl_tree); count--;
784 Assert(count >= 3 && count <= 6, " 3_6?");
785 send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
787 } else if (count <= 10) {
788 send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
791 send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
793 count = 0; prevlen = curlen;
795 max_count = 138, min_count = 3;
796 } else if (curlen == nextlen) {
797 max_count = 6, min_count = 3;
799 max_count = 7, min_count = 4;
804 /* ===========================================================================
805 * Construct the Huffman tree for the bit lengths and return the index in
806 * bl_order of the last bit length code to send.
808 local int build_bl_tree(s)
811 int max_blindex; /* index of last bit length code of non zero freq */
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);
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.
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.)
827 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
828 if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
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));
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.
843 local void send_all_trees(s, lcodes, dcodes, blcodes)
845 int lcodes, dcodes, blcodes; /* number of codes for each tree */
847 int rank; /* index in bl_order */
849 Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
850 Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
852 Tracev((stderr, "\nbl counts: "));
853 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
854 send_bits(s, dcodes-1, 5);
855 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
856 for (rank = 0; rank < blcodes; rank++) {
857 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
858 send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
860 Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
862 send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
863 Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
865 send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
866 Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
869 /* ===========================================================================
870 * Send a stored block
872 void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
874 charf *buf; /* input block */
875 ulg stored_len; /* length of input block */
876 int last; /* one if this is the last block for a file */
878 send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */
880 s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
881 s->compressed_len += (stored_len + 4) << 3;
883 copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
886 /* ===========================================================================
887 * Send one empty static block to give enough lookahead for inflate.
888 * This takes 10 bits, of which 7 may remain in the bit buffer.
889 * The current inflate code requires 9 bits of lookahead. If the
890 * last two codes for the previous block (real code plus EOB) were coded
891 * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
892 * the last real code. In this case we send two empty static blocks instead
893 * of one. (There are no problems if the previous block is stored or fixed.)
894 * To simplify the code, we assume the worst case of last real code encoded
897 void ZLIB_INTERNAL _tr_align(s)
900 send_bits(s, STATIC_TREES<<1, 3);
901 send_code(s, END_BLOCK, static_ltree);
903 s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
906 /* Of the 10 bits for the empty block, we have already sent
907 * (10 - bi_valid) bits. The lookahead for the last real code (before
908 * the EOB of the previous block) was thus at least one plus the length
909 * of the EOB plus what we have just sent of the empty static block.
911 if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
912 send_bits(s, STATIC_TREES<<1, 3);
913 send_code(s, END_BLOCK, static_ltree);
915 s->compressed_len += 10L;
922 /* ===========================================================================
923 * Determine the best encoding for the current block: dynamic trees, static
924 * trees or store, and output the encoded block to the zip file.
926 void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
928 charf *buf; /* input block, or NULL if too old */
929 ulg stored_len; /* length of input block */
930 int last; /* one if this is the last block for a file */
932 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
933 int max_blindex = 0; /* index of last bit length code of non zero freq */
935 /* Build the Huffman trees unless a stored block is forced */
938 /* Check if the file is binary or text */
939 if (s->strm->data_type == Z_UNKNOWN)
940 s->strm->data_type = detect_data_type(s);
942 /* Construct the literal and distance trees */
943 build_tree(s, (tree_desc *)(&(s->l_desc)));
944 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
947 build_tree(s, (tree_desc *)(&(s->d_desc)));
948 Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
950 /* At this point, opt_len and static_len are the total bit lengths of
951 * the compressed block data, excluding the tree representations.
954 /* Build the bit length tree for the above two trees, and get the index
955 * in bl_order of the last bit length code to send.
957 max_blindex = build_bl_tree(s);
959 /* Determine the best encoding. Compute the block lengths in bytes. */
960 opt_lenb = (s->opt_len+3+7)>>3;
961 static_lenb = (s->static_len+3+7)>>3;
963 Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
964 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
967 if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
970 Assert(buf != (char*)0, "lost buf");
971 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
975 if (buf != (char*)0) { /* force stored block */
977 if (stored_len+4 <= opt_lenb && buf != (char*)0) {
978 /* 4: two words for the lengths */
980 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
981 * Otherwise we can't have processed more than WSIZE input bytes since
982 * the last block flush, because compression would have been
983 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
984 * transform a block into a stored block.
986 _tr_stored_block(s, buf, stored_len, last);
989 } else if (static_lenb >= 0) { /* force static trees */
991 } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
993 send_bits(s, (STATIC_TREES<<1)+last, 3);
994 compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
996 s->compressed_len += 3 + s->static_len;
999 send_bits(s, (DYN_TREES<<1)+last, 3);
1000 send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
1002 compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
1004 s->compressed_len += 3 + s->opt_len;
1007 Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1008 /* The above check is made mod 2^32, for files larger than 512 MB
1009 * and uLong implemented on 32 bits.
1016 s->compressed_len += 7; /* align on byte boundary */
1019 Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1020 s->compressed_len-7*last));
1023 /* ===========================================================================
1024 * Save the match info and tally the frequency counts. Return true if
1025 * the current block must be flushed.
1027 int ZLIB_INTERNAL _tr_tally (s, dist, lc)
1029 unsigned dist; /* distance of matched string */
1030 unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
1032 s->d_buf[s->last_lit] = (ush)dist;
1033 s->l_buf[s->last_lit++] = (uch)lc;
1035 /* lc is the unmatched char */
1036 s->dyn_ltree[lc].Freq++;
1039 /* Here, lc is the match length - MIN_MATCH */
1040 dist--; /* dist = match distance - 1 */
1041 Assert((ush)dist < (ush)MAX_DIST(s) &&
1042 (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1043 (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
1045 s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1046 s->dyn_dtree[d_code(dist)].Freq++;
1049 #ifdef TRUNCATE_BLOCK
1050 /* Try to guess if it is profitable to stop the current block here */
1051 if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
1052 /* Compute an upper bound for the compressed length */
1053 ulg out_length = (ulg)s->last_lit*8L;
1054 ulg in_length = (ulg)((long)s->strstart - s->block_start);
1056 for (dcode = 0; dcode < D_CODES; dcode++) {
1057 out_length += (ulg)s->dyn_dtree[dcode].Freq *
1058 (5L+extra_dbits[dcode]);
1061 Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
1062 s->last_lit, in_length, out_length,
1063 100L - out_length*100L/in_length));
1064 if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
1067 return (s->last_lit == s->lit_bufsize-1);
1068 /* We avoid equality with lit_bufsize because of wraparound at 64K
1069 * on 16 bit machines and because stored blocks are restricted to
1074 /* ===========================================================================
1075 * Send the block data compressed using the given Huffman trees
1077 local void compress_block(s, ltree, dtree)
1079 ct_data *ltree; /* literal tree */
1080 ct_data *dtree; /* distance tree */
1082 unsigned dist; /* distance of matched string */
1083 int lc; /* match length or unmatched char (if dist == 0) */
1084 unsigned lx = 0; /* running index in l_buf */
1085 unsigned code; /* the code to send */
1086 int extra; /* number of extra bits to send */
1088 if (s->last_lit != 0) do {
1089 dist = s->d_buf[lx];
1090 lc = s->l_buf[lx++];
1092 send_code(s, lc, ltree); /* send a literal byte */
1093 Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1095 /* Here, lc is the match length - MIN_MATCH */
1096 code = _length_code[lc];
1097 send_code(s, code+LITERALS+1, ltree); /* send the length code */
1098 extra = extra_lbits[code];
1100 lc -= base_length[code];
1101 send_bits(s, lc, extra); /* send the extra length bits */
1103 dist--; /* dist is now the match distance - 1 */
1104 code = d_code(dist);
1105 Assert (code < D_CODES, "bad d_code");
1107 send_code(s, code, dtree); /* send the distance code */
1108 extra = extra_dbits[code];
1110 dist -= base_dist[code];
1111 send_bits(s, dist, extra); /* send the extra distance bits */
1113 } /* literal or match pair ? */
1115 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1116 Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
1117 "pendingBuf overflow");
1119 } while (lx < s->last_lit);
1121 send_code(s, END_BLOCK, ltree);
1122 s->last_eob_len = ltree[END_BLOCK].Len;
1125 /* ===========================================================================
1126 * Check if the data type is TEXT or BINARY, using the following algorithm:
1127 * - TEXT if the two conditions below are satisfied:
1128 * a) There are no non-portable control characters belonging to the
1129 * "black list" (0..6, 14..25, 28..31).
1130 * b) There is at least one printable character belonging to the
1131 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1132 * - BINARY otherwise.
1133 * - The following partially-portable control characters form a
1134 * "gray list" that is ignored in this detection algorithm:
1135 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
1136 * IN assertion: the fields Freq of dyn_ltree are set.
1138 local int detect_data_type(s)
1141 /* black_mask is the bit mask of black-listed bytes
1142 * set bits 0..6, 14..25, and 28..31
1143 * 0xf3ffc07f = binary 11110011111111111100000001111111
1145 unsigned long black_mask = 0xf3ffc07fUL;
1148 /* Check for non-textual ("black-listed") bytes. */
1149 for (n = 0; n <= 31; n++, black_mask >>= 1)
1150 if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
1153 /* Check for textual ("white-listed") bytes. */
1154 if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1155 || s->dyn_ltree[13].Freq != 0)
1157 for (n = 32; n < LITERALS; n++)
1158 if (s->dyn_ltree[n].Freq != 0)
1161 /* There are no "black-listed" or "white-listed" bytes:
1162 * this stream either is empty or has tolerated ("gray-listed") bytes only.
1167 /* ===========================================================================
1168 * Reverse the first len bits of a code, using straightforward code (a faster
1169 * method would use a table)
1170 * IN assertion: 1 <= len <= 15
1172 local unsigned bi_reverse(value, len)
1173 unsigned value; /* the value to invert */
1174 int len; /* its bit length */
1176 register unsigned res = 0;
1179 value >>= 1, res <<= 1;
1180 } while (--len > 0);
1184 /* ===========================================================================
1185 * Flush the bit buffer, keeping at most 7 bits in it.
1187 local void bi_flush(s)
1190 if (s->bi_valid == 16) {
1191 put_short(s, s->bi_buf);
1194 } else if (s->bi_valid >= 8) {
1195 put_byte(s, (Byte)s->bi_buf);
1201 /* ===========================================================================
1202 * Flush the bit buffer and align the output on a byte boundary
1204 local void bi_windup(s)
1207 if (s->bi_valid > 8) {
1208 put_short(s, s->bi_buf);
1209 } else if (s->bi_valid > 0) {
1210 put_byte(s, (Byte)s->bi_buf);
1215 s->bits_sent = (s->bits_sent+7) & ~7;
1219 /* ===========================================================================
1220 * Copy a stored block, storing first the length and its
1221 * one's complement if requested.
1223 local void copy_block(s, buf, len, header)
1225 charf *buf; /* the input data */
1226 unsigned len; /* its length */
1227 int header; /* true if block header must be written */
1229 bi_windup(s); /* align on byte boundary */
1230 s->last_eob_len = 8; /* enough lookahead for inflate */
1233 put_short(s, (ush)len);
1234 put_short(s, (ush)~len);
1236 s->bits_sent += 2*16;
1240 s->bits_sent += (ulg)len<<3;
1243 put_byte(s, *buf++);