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