build: update gnulib to latest, for crc tweak
[gzip.git] / trees.c
blob23acd76135ebc12fd9f6013ec0ed75c63fa86758
1 /* trees.c -- output deflated data using Huffman coding
3 Copyright (C) 1997-1999, 2009-2024 Free Software Foundation, Inc.
4 Copyright (C) 1992-1993 Jean-loup Gailly
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 * PURPOSE
22 * Encode various sets of source values using variable-length
23 * binary code trees.
25 * DISCUSSION
27 * The PKZIP "deflation" process uses several Huffman trees. The more
28 * common source values are represented by shorter bit sequences.
30 * Each code tree is stored in the ZIP file in a compressed form
31 * which is itself a Huffman encoding of the lengths of
32 * all the code strings (in ascending order by source values).
33 * The actual code strings are reconstructed from the lengths in
34 * the UNZIP process, as described in the "application note"
35 * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
37 * REFERENCES
39 * Lynch, Thomas J.
40 * Data Compression: Techniques and Applications, pp. 53-55.
41 * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
43 * Storer, James A.
44 * Data Compression: Methods and Theory, pp. 49-50.
45 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
47 * Sedgewick, R.
48 * Algorithms, p290.
49 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
51 * INTERFACE
53 * void ct_init (ush *attr, int *methodp)
54 * Allocate the match buffer, initialize the various tables and save
55 * the location of the internal file attribute (ascii/binary) and
56 * method (DEFLATE/STORE)
58 * void ct_tally (int dist, int lc);
59 * Save the match info and tally the frequency counts.
61 * off_t flush_block (char *buf, ulg stored_len, int eof)
62 * Determine the best encoding for the current block: dynamic trees,
63 * static trees or store, and output the encoded block to the zip
64 * file. Returns the total compressed length for the file so far.
68 #include <config.h>
69 #include <ctype.h>
71 #include "tailor.h"
72 #include "gzip.h"
74 /* ===========================================================================
75 * Constants
78 #define MAX_BITS 15
79 /* All codes must not exceed MAX_BITS bits */
81 #define MAX_BL_BITS 7
82 /* Bit length codes must not exceed MAX_BL_BITS bits */
84 #define LENGTH_CODES 29
85 /* number of length codes, not counting the special END_BLOCK code */
87 #define LITERALS 256
88 /* number of literal bytes 0..255 */
90 #define END_BLOCK 256
91 /* end of block literal code */
93 #define L_CODES (LITERALS+1+LENGTH_CODES)
94 /* number of Literal or Length codes, including the END_BLOCK code */
96 #define D_CODES 30
97 /* number of distance codes */
99 #define BL_CODES 19
100 /* number of codes used to transfer the bit lengths */
103 static int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */
104 = {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};
106 static int near extra_dbits[D_CODES] /* extra bits for each distance code */
107 = {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};
109 static int near extra_blbits[BL_CODES]/* extra bits for each bit length code */
110 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
112 #define STORED_BLOCK 0
113 #define STATIC_TREES 1
114 #define DYN_TREES 2
115 /* The three kinds of block type */
117 #ifndef LIT_BUFSIZE
118 # ifdef SMALL_MEM
119 # define LIT_BUFSIZE 0x2000
120 # else
121 # ifdef MEDIUM_MEM
122 # define LIT_BUFSIZE 0x4000
123 # else
124 # define LIT_BUFSIZE 0x8000
125 # endif
126 # endif
127 #endif
128 #ifndef DIST_BUFSIZE
129 # define DIST_BUFSIZE LIT_BUFSIZE
130 #endif
131 /* Sizes of match buffers for literals/lengths and distances. There are
132 * 4 reasons for limiting LIT_BUFSIZE to 64K:
133 * - frequencies can be kept in 16 bit counters
134 * - if compression is not successful for the first block, all input data is
135 * still in the window so we can still emit a stored block even when input
136 * comes from standard input. (This can also be done for all blocks if
137 * LIT_BUFSIZE is not greater than 32K.)
138 * - if compression is not successful for a file smaller than 64K, we can
139 * even emit a stored file instead of a stored block (saving 5 bytes).
140 * - creating new Huffman trees less frequently may not provide fast
141 * adaptation to changes in the input data statistics. (Take for
142 * example a binary file with poorly compressible code followed by
143 * a highly compressible string table.) Smaller buffer sizes give
144 * fast adaptation but have of course the overhead of transmitting trees
145 * more frequently.
146 * - I can't count above 4
147 * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
148 * memory at the expense of compression). Some optimizations would be possible
149 * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
151 #if LIT_BUFSIZE > INBUFSIZ
152 error cannot overlay l_buf and inbuf
153 #endif
155 #define REP_3_6 16
156 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
158 #define REPZ_3_10 17
159 /* repeat a zero length 3-10 times (3 bits of repeat count) */
161 #define REPZ_11_138 18
162 /* repeat a zero length 11-138 times (7 bits of repeat count) */
164 /* ===========================================================================
165 * Local data
168 /* Data structure describing a single value and its code string. */
169 typedef struct ct_data {
170 union {
171 ush freq; /* frequency count */
172 ush code; /* bit string */
173 } fc;
174 union {
175 ush dad; /* father node in Huffman tree */
176 ush len; /* length of bit string */
177 } dl;
178 } ct_data;
180 #define Freq fc.freq
181 #define Code fc.code
182 #define Dad dl.dad
183 #define Len dl.len
185 #define HEAP_SIZE (2*L_CODES+1)
186 /* maximum heap size */
188 static ct_data near dyn_ltree[HEAP_SIZE]; /* literal and length tree */
189 static ct_data near dyn_dtree[2*D_CODES+1]; /* distance tree */
191 static ct_data near static_ltree[L_CODES+2];
192 /* The static literal tree. Since the bit lengths are imposed, there is no
193 * need for the L_CODES extra codes used during heap construction. However
194 * The codes 286 and 287 are needed to build a canonical tree (see ct_init
195 * below).
198 static ct_data near static_dtree[D_CODES];
199 /* The static distance tree. (Actually a trivial tree since all codes use
200 * 5 bits.)
203 static ct_data near bl_tree[2*BL_CODES+1];
204 /* Huffman tree for the bit lengths */
206 typedef struct tree_desc {
207 ct_data near *dyn_tree; /* the dynamic tree */
208 ct_data near *static_tree; /* corresponding static tree or NULL */
209 int near *extra_bits; /* extra bits for each code or NULL */
210 int extra_base; /* base index for extra_bits */
211 int elems; /* max number of elements in the tree */
212 int max_length; /* max bit length for the codes */
213 int max_code; /* largest code with non zero frequency */
214 } tree_desc;
216 static tree_desc near l_desc =
217 {dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0};
219 static tree_desc near d_desc =
220 {dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0};
222 static tree_desc near bl_desc =
223 {bl_tree, (ct_data near *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0};
226 static ush near bl_count[MAX_BITS+1];
227 /* number of codes at each bit length for an optimal tree */
229 static uch near bl_order[BL_CODES]
230 = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
231 /* The lengths of the bit length codes are sent in order of decreasing
232 * probability, to avoid transmitting the lengths for unused bit length codes.
235 static int near heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
236 static int heap_len; /* number of elements in the heap */
237 static int heap_max; /* element of largest frequency */
238 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
239 * The same heap array is used to build all trees.
242 static uch near depth[2*L_CODES+1];
243 /* Depth of each subtree used as tie breaker for trees of equal frequency */
245 static uch length_code[MAX_MATCH-MIN_MATCH+1];
246 /* length code for each normalized match length (0 == MIN_MATCH) */
248 static uch dist_code[512];
249 /* distance codes. The first 256 values correspond to the distances
250 * 3 .. 258, the last 256 values correspond to the top 8 bits of
251 * the 15 bit distances.
254 static int near base_length[LENGTH_CODES];
255 /* First normalized length for each code (0 = MIN_MATCH) */
257 static int near base_dist[D_CODES];
258 /* First normalized distance for each code (0 = distance of 1) */
260 #define l_buf inbuf
261 /* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */
263 /* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
265 static uch near flag_buf[(LIT_BUFSIZE/8)];
266 /* flag_buf is a bit array distinguishing literals from lengths in
267 * l_buf, thus indicating the presence or absence of a distance.
270 static unsigned last_lit; /* running index in l_buf */
271 static unsigned last_dist; /* running index in d_buf */
272 static unsigned last_flags; /* running index in flag_buf */
273 static uch flags; /* current flags not yet saved in flag_buf */
274 static uch flag_bit; /* current bit used in flags */
275 /* bits are filled in flags starting at bit 0 (least significant).
276 * Note: these flags are overkill in the current code since we don't
277 * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
280 static ulg opt_len; /* bit length of current block with optimal trees */
281 static ulg static_len; /* bit length of current block with static trees */
283 static off_t compressed_len; /* total bit length of compressed file */
285 static off_t input_len; /* total byte length of input file */
286 /* input_len is for debugging only since we can get it by other means. */
288 static ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
289 static int *file_method; /* pointer to DEFLATE or STORE */
291 #ifdef DEBUG
292 extern off_t bits_sent; /* bit length of the compressed data */
293 #endif
295 extern long block_start; /* window offset of current block */
296 extern unsigned near strstart; /* window offset of current string */
298 /* ===========================================================================
299 * Local (static) routines in this file.
302 static void init_block (void);
303 static void pqdownheap (ct_data near *tree, int k);
304 static void gen_bitlen (tree_desc near *desc);
305 static void gen_codes (ct_data near *tree, int max_code);
306 static void build_tree (tree_desc near *desc);
307 static void scan_tree (ct_data near *tree, int max_code);
308 static void send_tree (ct_data near *tree, int max_code);
309 static int build_bl_tree (void);
310 static void send_all_trees (int lcodes, int dcodes, int blcodes);
311 static void compress_block (ct_data near *ltree, ct_data near *dtree);
312 static void set_file_type (void);
315 #ifndef DEBUG
316 # define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
317 /* Send a code of the given tree. c and tree must not have side effects */
319 #else /* DEBUG */
320 # define send_code(c, tree) \
321 { if (verbose > 1) fprintf (stderr, "\ncd %3u ", (c) + 0u); \
322 send_bits(tree[c].Code, tree[c].Len); }
323 #endif
325 #define d_code(dist) \
326 ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
327 /* Mapping from a distance to a distance code. dist is the distance - 1 and
328 * must not have side effects. dist_code[256] and dist_code[257] are never
329 * used.
332 #define MAX(a,b) (a >= b ? a : b)
333 /* the arguments must not have side effects */
335 /* ===========================================================================
336 * Allocate the match buffer, initialize the various tables and save the
337 * location of the internal file attribute (ascii/binary) and method
338 * (DEFLATE/STORE).
339 * ATTR points to internal file attribute.
340 * METHODP points to the compression method.
342 void
343 ct_init (ush *attr, int *methodp)
345 int n; /* iterates over tree elements */
346 int bits; /* bit counter */
347 int length; /* length value */
348 int code; /* code value */
349 int dist; /* distance index */
351 file_type = attr;
352 file_method = methodp;
353 compressed_len = input_len = 0L;
355 if (static_dtree[0].Len != 0) return; /* ct_init already called */
357 /* Initialize the mapping length (0..255) -> length code (0..28) */
358 length = 0;
359 for (code = 0; code < LENGTH_CODES-1; code++) {
360 base_length[code] = length;
361 for (n = 0; n < (1<<extra_lbits[code]); n++) {
362 length_code[length++] = (uch)code;
365 Assert (length == 256, "ct_init: length != 256");
366 /* Note that the length 255 (match length 258) can be represented
367 * in two different ways: code 284 + 5 bits or code 285, so we
368 * overwrite length_code[255] to use the best encoding:
370 length_code[length-1] = (uch)code;
372 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
373 dist = 0;
374 for (code = 0 ; code < 16; code++) {
375 base_dist[code] = dist;
376 for (n = 0; n < (1<<extra_dbits[code]); n++) {
377 dist_code[dist++] = (uch)code;
380 Assert (dist == 256, "ct_init: dist != 256");
381 dist >>= 7; /* from now on, all distances are divided by 128 */
382 for ( ; code < D_CODES; code++) {
383 base_dist[code] = dist << 7;
384 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
385 dist_code[256 + dist++] = (uch)code;
388 Assert (dist == 256, "ct_init: 256+dist != 512");
390 /* Construct the codes of the static literal tree */
391 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
392 n = 0;
393 while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
394 while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
395 while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
396 while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
397 /* Codes 286 and 287 do not exist, but we must include them in the
398 * tree construction to get a canonical Huffman tree (longest code
399 * all ones)
401 gen_codes((ct_data near *)static_ltree, L_CODES+1);
403 /* The static distance tree is trivial: */
404 for (n = 0; n < D_CODES; n++) {
405 static_dtree[n].Len = 5;
406 static_dtree[n].Code = bi_reverse(n, 5);
409 /* Initialize the first block of the first file: */
410 init_block();
413 /* ===========================================================================
414 * Initialize a new block.
416 static void
417 init_block ()
419 int n; /* iterates over tree elements */
421 /* Initialize the trees. */
422 for (n = 0; n < L_CODES; n++) dyn_ltree[n].Freq = 0;
423 for (n = 0; n < D_CODES; n++) dyn_dtree[n].Freq = 0;
424 for (n = 0; n < BL_CODES; n++) bl_tree[n].Freq = 0;
426 dyn_ltree[END_BLOCK].Freq = 1;
427 opt_len = static_len = 0L;
428 last_lit = last_dist = last_flags = 0;
429 flags = 0; flag_bit = 1;
432 #define SMALLEST 1
433 /* Index within the heap array of least frequent node in the Huffman tree */
436 /* ===========================================================================
437 * Remove the smallest element from the heap and recreate the heap with
438 * one less element. Updates heap and heap_len.
440 #define pqremove(tree, top) \
442 top = heap[SMALLEST]; \
443 heap[SMALLEST] = heap[heap_len--]; \
444 pqdownheap(tree, SMALLEST); \
447 /* ===========================================================================
448 * Compares to subtrees, using the tree depth as tie breaker when
449 * the subtrees have equal frequency. This minimizes the worst case length.
451 #define smaller(tree, n, m) \
452 (tree[n].Freq < tree[m].Freq || \
453 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
455 /* ===========================================================================
456 * Restore the heap property by moving down the tree starting at node k,
457 * exchanging a node with the smallest of its two sons if necessary, stopping
458 * when the heap property is re-established (each father smaller than its
459 * two sons).
460 * TREE is the tree to restore.
461 * K is the node to move down.
463 static void
464 pqdownheap (ct_data near *tree, int k)
466 int v = heap[k];
467 int j = k << 1; /* left son of k */
468 while (j <= heap_len) {
469 /* Set j to the smallest of the two sons: */
470 if (j < heap_len && smaller(tree, heap[j+1], heap[j])) j++;
472 /* Exit if v is smaller than both sons */
473 if (smaller(tree, v, heap[j])) break;
475 /* Exchange v with the smallest son */
476 heap[k] = heap[j]; k = j;
478 /* And continue down the tree, setting j to the left son of k */
479 j <<= 1;
481 heap[k] = v;
484 /* ===========================================================================
485 * Compute the optimal bit lengths for a tree and update the total bit length
486 * for the current block.
487 * IN assertion: the fields freq and dad are set, heap[heap_max] and
488 * above are the tree nodes sorted by increasing frequency.
489 * OUT assertions: the field len is set to the optimal bit length, the
490 * array bl_count contains the frequencies for each bit length.
491 * The length opt_len is updated; static_len is also updated if stree is
492 * not null.
493 * DESC is the tree descriptor.
495 static void
496 gen_bitlen (tree_desc near *desc)
498 ct_data near *tree = desc->dyn_tree;
499 int near *extra = desc->extra_bits;
500 int base = desc->extra_base;
501 int max_code = desc->max_code;
502 int max_length = desc->max_length;
503 ct_data near *stree = desc->static_tree;
504 int h; /* heap index */
505 int n, m; /* iterate over the tree elements */
506 int bits; /* bit length */
507 int xbits; /* extra bits */
508 ush f; /* frequency */
509 int overflow = 0; /* number of elements with bit length too large */
511 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
513 /* In a first pass, compute the optimal bit lengths (which may
514 * overflow in the case of the bit length tree).
516 tree[heap[heap_max]].Len = 0; /* root of the heap */
518 for (h = heap_max+1; h < HEAP_SIZE; h++) {
519 n = heap[h];
520 bits = tree[tree[n].Dad].Len + 1;
521 if (bits > max_length) bits = max_length, overflow++;
522 tree[n].Len = (ush)bits;
523 /* We overwrite tree[n].Dad which is no longer needed */
525 if (n > max_code) continue; /* not a leaf node */
527 bl_count[bits]++;
528 xbits = 0;
529 if (n >= base) xbits = extra[n-base];
530 f = tree[n].Freq;
531 opt_len += (ulg)f * (bits + xbits);
532 if (stree) static_len += (ulg)f * (stree[n].Len + xbits);
534 if (overflow == 0) return;
536 Trace((stderr,"\nbit length overflow\n"));
537 /* This happens for example on obj2 and pic of the Calgary corpus */
539 /* Find the first bit length which could increase: */
540 do {
541 bits = max_length-1;
542 while (bl_count[bits] == 0) bits--;
543 bl_count[bits]--; /* move one leaf down the tree */
544 bl_count[bits+1] += 2; /* move one overflow item as its brother */
545 bl_count[max_length]--;
546 /* The brother of the overflow item also moves one step up,
547 * but this does not affect bl_count[max_length]
549 overflow -= 2;
550 } while (overflow > 0);
552 /* Now recompute all bit lengths, scanning in increasing frequency.
553 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
554 * lengths instead of fixing only the wrong ones. This idea is taken
555 * from 'ar' written by Haruhiko Okumura.)
557 for (bits = max_length; bits != 0; bits--) {
558 n = bl_count[bits];
559 while (n != 0) {
560 m = heap[--h];
561 if (m > max_code) continue;
562 if (tree[m].Len != (unsigned) bits) {
563 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
564 opt_len += ((long)bits-(long)tree[m].Len)*(long)tree[m].Freq;
565 tree[m].Len = (ush)bits;
567 n--;
572 /* ===========================================================================
573 * Generate the codes for a given tree and bit counts (which need not be
574 * optimal).
575 * IN assertion: the array bl_count contains the bit length statistics for
576 * the given tree and the field len is set for all tree elements.
577 * OUT assertion: the field code is set for all tree elements of non
578 * zero code length.
579 * TREE is the tree to decorate.
580 * MAX_CODE is the largest code with non zero frequency.
582 static void
583 gen_codes (ct_data near *tree, int max_code)
585 ush next_code[MAX_BITS+1]; /* next code value for each bit length */
586 ush code = 0; /* running code value */
587 int bits; /* bit index */
588 int n; /* code index */
590 /* The distribution counts are first used to generate the code values
591 * without bit reversal.
593 for (bits = 1; bits <= MAX_BITS; bits++) {
594 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
596 /* Check that the bit counts in bl_count are consistent. The last code
597 * must be all ones.
599 Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
600 "inconsistent bit counts");
601 Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
603 for (n = 0; n <= max_code; n++) {
604 int len = tree[n].Len;
605 if (len == 0) continue;
606 /* Now reverse the bits */
607 tree[n].Code = bi_reverse(next_code[len]++, len);
609 Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
610 n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1u));
614 /* ===========================================================================
615 * Construct one Huffman tree and assigns the code bit strings and lengths.
616 * Update the total bit length for the current block.
617 * IN assertion: the field freq is set for all tree elements.
618 * OUT assertions: the fields len and code are set to the optimal bit length
619 * and corresponding code. The length opt_len is updated; static_len is
620 * also updated if stree is not null. The field max_code is set.
621 * DESC is the tree descriptor.
623 static void
624 build_tree(tree_desc near *desc)
626 ct_data near *tree = desc->dyn_tree;
627 ct_data near *stree = desc->static_tree;
628 int elems = desc->elems;
629 int n, m; /* iterate over heap elements */
630 int max_code = -1; /* largest code with non zero frequency */
631 int node = elems; /* next internal node of the tree */
633 /* Construct the initial heap, with least frequent element in
634 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
635 * heap[0] is not used.
637 heap_len = 0, heap_max = HEAP_SIZE;
639 for (n = 0; n < elems; n++) {
640 if (tree[n].Freq != 0) {
641 heap[++heap_len] = max_code = n;
642 depth[n] = 0;
643 } else {
644 tree[n].Len = 0;
648 /* The pkzip format requires that at least one distance code exists,
649 * and that at least one bit should be sent even if there is only one
650 * possible code. So to avoid special checks later on we force at least
651 * two codes of non zero frequency.
653 while (heap_len < 2) {
654 int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
655 tree[new].Freq = 1;
656 depth[new] = 0;
657 opt_len--; if (stree) static_len -= stree[new].Len;
658 /* new is 0 or 1 so it does not have extra bits */
660 desc->max_code = max_code;
662 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
663 * establish sub-heaps of increasing lengths:
665 for (n = heap_len/2; n >= 1; n--) pqdownheap(tree, n);
667 /* Construct the Huffman tree by repeatedly combining the least two
668 * frequent nodes.
670 do {
671 pqremove(tree, n); /* n = node of least frequency */
672 m = heap[SMALLEST]; /* m = node of next least frequency */
674 heap[--heap_max] = n; /* keep the nodes sorted by frequency */
675 heap[--heap_max] = m;
677 /* Create a new node father of n and m */
678 tree[node].Freq = tree[n].Freq + tree[m].Freq;
679 depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
680 tree[n].Dad = tree[m].Dad = (ush)node;
681 #ifdef DUMP_BL_TREE
682 if (tree == bl_tree) {
683 fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
684 node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
686 #endif
687 /* and insert the new node in the heap */
688 heap[SMALLEST] = node++;
689 pqdownheap(tree, SMALLEST);
691 } while (heap_len >= 2);
693 heap[--heap_max] = heap[SMALLEST];
695 /* At this point, the fields freq and dad are set. We can now
696 * generate the bit lengths.
698 gen_bitlen((tree_desc near *)desc);
700 /* The field len is now set, we can generate the bit codes */
701 gen_codes ((ct_data near *)tree, max_code);
704 /* ===========================================================================
705 * Scan a literal or distance tree to determine the frequencies of the codes
706 * in the bit length tree. Updates opt_len to take into account the repeat
707 * counts. (The contribution of the bit length codes will be added later
708 * during the construction of bl_tree.)
709 * TREE is the tree to be scanned.
710 * MAX_CODE is its largest code of non zero frequency.
712 static void
713 scan_tree (ct_data near *tree, int max_code)
715 int n; /* iterates over all tree elements */
716 int prevlen = -1; /* last emitted length */
717 int curlen; /* length of current code */
718 int nextlen = tree[0].Len; /* length of next code */
719 int count = 0; /* repeat count of the current code */
720 int max_count = 7; /* max repeat count */
721 int min_count = 4; /* min repeat count */
723 if (nextlen == 0) max_count = 138, min_count = 3;
724 tree[max_code+1].Len = (ush)0xffff; /* guard */
726 for (n = 0; n <= max_code; n++) {
727 curlen = nextlen; nextlen = tree[n+1].Len;
728 if (++count < max_count && curlen == nextlen) {
729 continue;
730 } else if (count < min_count) {
731 bl_tree[curlen].Freq += count;
732 } else if (curlen != 0) {
733 if (curlen != prevlen) bl_tree[curlen].Freq++;
734 bl_tree[REP_3_6].Freq++;
735 } else if (count <= 10) {
736 bl_tree[REPZ_3_10].Freq++;
737 } else {
738 bl_tree[REPZ_11_138].Freq++;
740 count = 0; prevlen = curlen;
741 if (nextlen == 0) {
742 max_count = 138, min_count = 3;
743 } else if (curlen == nextlen) {
744 max_count = 6, min_count = 3;
745 } else {
746 max_count = 7, min_count = 4;
751 /* ===========================================================================
752 * Send a literal or distance tree in compressed form, using the codes in
753 * bl_tree.
754 * TREE is the tree to be scanned.
755 * MAX_CODE is its largest code of non zero frequency.
757 static void
758 send_tree (ct_data near *tree, int max_code)
760 int n; /* iterates over all tree elements */
761 int prevlen = -1; /* last emitted length */
762 int curlen; /* length of current code */
763 int nextlen = tree[0].Len; /* length of next code */
764 int count = 0; /* repeat count of the current code */
765 int max_count = 7; /* max repeat count */
766 int min_count = 4; /* min repeat count */
768 /* tree[max_code+1].Len = -1; */ /* guard already set */
769 if (nextlen == 0) max_count = 138, min_count = 3;
771 for (n = 0; n <= max_code; n++) {
772 curlen = nextlen; nextlen = tree[n+1].Len;
773 if (++count < max_count && curlen == nextlen) {
774 continue;
775 } else if (count < min_count) {
776 do { send_code(curlen, bl_tree); } while (--count != 0);
778 } else if (curlen != 0) {
779 if (curlen != prevlen) {
780 send_code(curlen, bl_tree); count--;
782 Assert(count >= 3 && count <= 6, " 3_6?");
783 send_code(REP_3_6, bl_tree); send_bits(count-3, 2);
785 } else if (count <= 10) {
786 send_code(REPZ_3_10, bl_tree); send_bits(count-3, 3);
788 } else {
789 send_code(REPZ_11_138, bl_tree); send_bits(count-11, 7);
791 count = 0; prevlen = curlen;
792 if (nextlen == 0) {
793 max_count = 138, min_count = 3;
794 } else if (curlen == nextlen) {
795 max_count = 6, min_count = 3;
796 } else {
797 max_count = 7, min_count = 4;
802 /* ===========================================================================
803 * Construct the Huffman tree for the bit lengths and return the index in
804 * bl_order of the last bit length code to send.
806 static int
807 build_bl_tree ()
809 int max_blindex; /* index of last bit length code of non zero freq */
811 /* Determine the bit length frequencies for literal and distance trees */
812 scan_tree((ct_data near *)dyn_ltree, l_desc.max_code);
813 scan_tree((ct_data near *)dyn_dtree, d_desc.max_code);
815 /* Build the bit length tree: */
816 build_tree((tree_desc near *)(&bl_desc));
817 /* opt_len now includes the length of the tree representations, except
818 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
821 /* Determine the number of bit length codes to send. The pkzip format
822 * requires that at least 4 bit length codes be sent. (appnote.txt says
823 * 3 but the actual value used is 4.)
825 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
826 if (bl_tree[bl_order[max_blindex]].Len != 0) break;
828 /* Update opt_len to include the bit length tree and counts */
829 opt_len += 3*(max_blindex+1) + 5+5+4;
830 Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu", opt_len, static_len));
832 return max_blindex;
835 /* ===========================================================================
836 * Send the header for a block using dynamic Huffman trees: the counts, the
837 * lengths of the bit length codes, the literal tree and the distance tree.
838 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
839 * LCODES, DCODES and BLCODES are the number of codes for each tree.
841 static void
842 send_all_trees (int lcodes, int dcodes, int blcodes)
844 int rank; /* index in bl_order */
846 Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
847 Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
848 "too many codes");
849 Tracev((stderr, "\nbl counts: "));
850 send_bits(lcodes-257, 5); /* not +255 as stated in appnote.txt */
851 send_bits(dcodes-1, 5);
852 send_bits(blcodes-4, 4); /* not -3 as stated in appnote.txt */
853 for (rank = 0; rank < blcodes; rank++) {
854 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
855 send_bits(bl_tree[bl_order[rank]].Len, 3);
858 send_tree((ct_data near *)dyn_ltree, lcodes-1); /* send the literal tree */
860 send_tree((ct_data near *)dyn_dtree, dcodes-1); /* send the distance tree */
863 /* ===========================================================================
864 * Determine the best encoding for the current block: dynamic trees, static
865 * trees or store, and output the encoded block to the zip file. This function
866 * returns the total compressed length for the file so far.
867 * BUF is the input block, or NULL if too old.
868 * STORED_LEN is BUF's length.
869 * PAD means pad output to byte boundary.
870 * EOF means this is the last block for a file.
872 off_t
873 flush_block (char *buf, ulg stored_len, int pad, int eof)
875 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
876 int max_blindex; /* index of last bit length code of non zero freq */
878 flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
880 /* Check if the file is ascii or binary */
881 if (*file_type == (ush)UNKNOWN) set_file_type();
883 /* Construct the literal and distance trees */
884 build_tree((tree_desc near *)(&l_desc));
885 Tracev((stderr, "\nlit data: dyn %lu, stat %lu", opt_len, static_len));
887 build_tree((tree_desc near *)(&d_desc));
888 Tracev((stderr, "\ndist data: dyn %lu, stat %lu", opt_len, static_len));
889 /* At this point, opt_len and static_len are the total bit lengths of
890 * the compressed block data, excluding the tree representations.
893 /* Build the bit length tree for the above two trees, and get the index
894 * in bl_order of the last bit length code to send.
896 max_blindex = build_bl_tree();
898 /* Determine the best encoding. Compute first the block length in bytes */
899 opt_lenb = (opt_len+3+7)>>3;
900 static_lenb = (static_len+3+7)>>3;
901 input_len += stored_len; /* for debugging only */
903 Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
904 opt_lenb, opt_len, static_lenb, static_len, stored_len,
905 last_lit, last_dist));
907 if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
909 /* If compression failed and this is the first and last block,
910 * and if we can seek through the zip file (to rewrite the local header),
911 * the whole file is transformed into a stored file:
913 #ifdef FORCE_METHOD
914 if (level == 1 && eof && compressed_len == 0L) { /* force stored file */
915 #else
916 if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) {
917 #endif
918 /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
919 if (!buf)
920 gzip_error ("block vanished");
922 copy_block(buf, (unsigned)stored_len, 0); /* without header */
923 compressed_len = stored_len << 3;
924 *file_method = STORED;
926 #ifdef FORCE_METHOD
927 } else if (level == 2 && buf != (char*)0) { /* force stored block */
928 #else
929 } else if (stored_len+4 <= opt_lenb && buf != (char*)0) {
930 /* 4: two words for the lengths */
931 #endif
932 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
933 * Otherwise we can't have processed more than WSIZE input bytes since
934 * the last block flush, because compression would have been
935 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
936 * transform a block into a stored block.
938 send_bits((STORED_BLOCK<<1)+eof, 3); /* send block type */
939 compressed_len = (compressed_len + 3 + 7) & ~7L;
940 compressed_len += (stored_len + 4) << 3;
942 copy_block(buf, (unsigned)stored_len, 1); /* with header */
944 #ifdef FORCE_METHOD
945 } else if (level == 3) { /* force static trees */
946 #else
947 } else if (static_lenb == opt_lenb) {
948 #endif
949 send_bits((STATIC_TREES<<1)+eof, 3);
950 compress_block((ct_data near *)static_ltree, (ct_data near *)static_dtree);
951 compressed_len += 3 + static_len;
952 } else {
953 send_bits((DYN_TREES<<1)+eof, 3);
954 send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
955 compress_block((ct_data near *)dyn_ltree, (ct_data near *)dyn_dtree);
956 compressed_len += 3 + opt_len;
958 Assert (compressed_len == bits_sent, "bad compressed size");
959 init_block();
961 if (eof) {
962 Assert (input_len == bytes_in, "bad input size");
963 bi_windup();
964 compressed_len += 7; /* align on byte boundary */
965 } else if (pad && (compressed_len % 8) != 0) {
966 send_bits((STORED_BLOCK<<1)+eof, 3); /* send block type */
967 compressed_len = (compressed_len + 3 + 7) & ~7L;
968 copy_block(buf, 0, 1); /* with header */
971 return compressed_len >> 3;
974 /* ===========================================================================
975 * Save the match info and tally the frequency counts. Return true if
976 * the current block must be flushed.
977 * DIST is the distance of matched string.
978 * LC is match length - MIN_MATCH or unmatched char (if DIST==0).
981 ct_tally (int dist, int lc)
983 l_buf[last_lit++] = (uch)lc;
984 if (dist == 0) {
985 /* lc is the unmatched char */
986 dyn_ltree[lc].Freq++;
987 } else {
988 /* Here, lc is the match length - MIN_MATCH */
989 dist--; /* dist = match distance - 1 */
990 Assert((ush)dist < (ush)MAX_DIST &&
991 (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
992 (ush)d_code(dist) < (ush)D_CODES, "ct_tally: bad match");
994 dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
995 dyn_dtree[d_code(dist)].Freq++;
997 d_buf[last_dist++] = (ush)dist;
998 flags |= flag_bit;
1000 flag_bit <<= 1;
1002 /* Output the flags if they fill a byte: */
1003 if ((last_lit & 7) == 0) {
1004 flag_buf[last_flags++] = flags;
1005 flags = 0, flag_bit = 1;
1007 /* Try to guess if it is profitable to stop the current block here */
1008 if (level > 2 && (last_lit & 0xfff) == 0) {
1009 /* Compute an upper bound for the compressed length */
1010 ulg out_length = (ulg)last_lit*8L;
1011 ulg in_length = (ulg)strstart-block_start;
1012 int dcode;
1013 for (dcode = 0; dcode < D_CODES; dcode++) {
1014 out_length += (ulg)dyn_dtree[dcode].Freq*(5L+extra_dbits[dcode]);
1016 out_length >>= 3;
1017 Trace((stderr,"\nlast_lit %u, last_dist %u, in %lu, out ~%lu(%lu%%) ",
1018 last_lit, last_dist, in_length, out_length,
1019 100L - out_length*100L/in_length));
1020 if (last_dist < last_lit/2 && out_length < in_length/2) return 1;
1022 return (last_lit == LIT_BUFSIZE-1 || last_dist == DIST_BUFSIZE);
1023 /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
1024 * on 16 bit machines and because stored blocks are restricted to
1025 * 64K-1 bytes.
1029 /* ===========================================================================
1030 * Send the block data compressed using the given Huffman trees
1031 * LTREE is the literal tree, DTREE the distance tree.
1033 static void
1034 compress_block (ct_data near *ltree, ct_data near *dtree)
1036 unsigned dist; /* distance of matched string */
1037 int lc; /* match length or unmatched char (if dist == 0) */
1038 unsigned lx = 0; /* running index in l_buf */
1039 unsigned dx = 0; /* running index in d_buf */
1040 unsigned fx = 0; /* running index in flag_buf */
1041 uch flag = 0; /* current flags */
1042 unsigned code; /* the code to send */
1043 int extra; /* number of extra bits to send */
1045 if (last_lit != 0) do {
1046 if ((lx & 7) == 0) flag = flag_buf[fx++];
1047 lc = l_buf[lx++];
1048 if ((flag & 1) == 0) {
1049 send_code(lc, ltree); /* send a literal byte */
1050 Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1051 } else {
1052 /* Here, lc is the match length - MIN_MATCH */
1053 code = length_code[lc];
1054 send_code(code+LITERALS+1, ltree); /* send the length code */
1055 extra = extra_lbits[code];
1056 if (extra != 0) {
1057 lc -= base_length[code];
1058 send_bits(lc, extra); /* send the extra length bits */
1060 dist = d_buf[dx++];
1061 /* Here, dist is the match distance - 1 */
1062 code = d_code(dist);
1063 Assert (code < D_CODES, "bad d_code");
1065 send_code(code, dtree); /* send the distance code */
1066 extra = extra_dbits[code];
1067 if (extra != 0) {
1068 dist -= base_dist[code];
1069 send_bits(dist, extra); /* send the extra distance bits */
1071 } /* literal or match pair ? */
1072 flag >>= 1;
1073 } while (lx < last_lit);
1075 send_code(END_BLOCK, ltree);
1078 /* ===========================================================================
1079 * Set the file type to ASCII or BINARY, using a crude approximation:
1080 * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
1081 * IN assertion: the fields freq of dyn_ltree are set and the total of all
1082 * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
1084 static void
1085 set_file_type ()
1087 int n = 0;
1088 unsigned ascii_freq = 0;
1089 unsigned bin_freq = 0;
1090 while (n < 7) bin_freq += dyn_ltree[n++].Freq;
1091 while (n < 128) ascii_freq += dyn_ltree[n++].Freq;
1092 while (n < LITERALS) bin_freq += dyn_ltree[n++].Freq;
1093 *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
1094 if (*file_type == BINARY && translate_eol) {
1095 warning ("-l used on binary file");