Debian Codegraph @

src/lib/deflate_tree.c

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