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