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