trees.c revision 237410
1122394Sharti/* trees.c -- output deflated data using Huffman coding
2122394Sharti * Copyright (C) 1995-2012 Jean-loup Gailly
3122394Sharti * detect_data_type() function provided freely by Cosmin Truta, 2006
4122394Sharti * For conditions of distribution and use, see copyright notice in zlib.h
5122394Sharti */
6159063Sharti
7133211Sharti/*
8133211Sharti *  ALGORITHM
9133211Sharti *
10122394Sharti *      The "deflation" process uses several Huffman trees. The more
11133211Sharti *      common source values are represented by shorter bit sequences.
12133211Sharti *
13133211Sharti *      Each code tree is stored in a compressed form which is itself
14133211Sharti * a Huffman encoding of the lengths of all the code strings (in
15133211Sharti * ascending order by source values).  The actual code strings are
16133211Sharti * reconstructed from the lengths in the inflate process, as described
17122394Sharti * in the deflate specification.
18122394Sharti *
19122394Sharti *  REFERENCES
20133211Sharti *
21133211Sharti *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
22133211Sharti *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
23133211Sharti *
24133211Sharti *      Storer, James A.
25133211Sharti *          Data Compression:  Methods and Theory, pp. 49-50.
26133211Sharti *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
27133211Sharti *
28133211Sharti *      Sedgewick, R.
29133211Sharti *          Algorithms, p290.
30133211Sharti *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
31133211Sharti */
32122394Sharti
33159063Sharti/* @(#) $Id$ */
34122394Sharti
35122394Sharti/* #define GEN_TREES_H */
36122394Sharti
37122394Sharti#include "deflate.h"
38122394Sharti
39159063Sharti#ifdef DEBUG
40133211Sharti#  include <ctype.h>
41159063Sharti#endif
42159063Sharti
43122394Sharti/* ===========================================================================
44122394Sharti * Constants
45122394Sharti */
46122394Sharti
47159063Sharti#define MAX_BL_BITS 7
48122394Sharti/* Bit length codes must not exceed MAX_BL_BITS bits */
49159063Sharti
50122394Sharti#define END_BLOCK 256
51159063Sharti/* end of block literal code */
52159063Sharti
53159063Sharti#define REP_3_6      16
54159063Sharti/* repeat previous bit length 3-6 times (2 bits of repeat count) */
55159063Sharti
56159063Sharti#define REPZ_3_10    17
57159063Sharti/* repeat a zero length 3-10 times  (3 bits of repeat count) */
58159063Sharti
59159063Sharti#define REPZ_11_138  18
60159063Sharti/* repeat a zero length 11-138 times  (7 bits of repeat count) */
61159063Sharti
62159063Shartilocal const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
63122394Sharti   = {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};
64122394Sharti
65122394Shartilocal const int extra_dbits[D_CODES] /* extra bits for each distance code */
66122394Sharti   = {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};
67142810Sharti
68122394Shartilocal const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
69159063Sharti   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
70122394Sharti
71159063Shartilocal const uch bl_order[BL_CODES]
72159063Sharti   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
73159063Sharti/* The lengths of the bit length codes are sent in order of decreasing
74159063Sharti * probability, to avoid transmitting the lengths for unused bit length codes.
75159063Sharti */
76122394Sharti
77122394Sharti/* ===========================================================================
78122394Sharti * Local data. These are initialized only once.
79122394Sharti */
80122394Sharti
81122394Sharti#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
82122394Sharti
83122394Sharti#if defined(GEN_TREES_H) || !defined(STDC)
84122394Sharti/* non ANSI compilers may not accept trees.h */
85133429Sharti
86133211Shartilocal ct_data static_ltree[L_CODES+2];
87133211Sharti/* The static literal tree. Since the bit lengths are imposed, there is no
88122394Sharti * need for the L_CODES extra codes used during heap construction. However
89133211Sharti * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
90122394Sharti * below).
91133211Sharti */
92122394Sharti
93122394Shartilocal ct_data static_dtree[D_CODES];
94122394Sharti/* The static distance tree. (Actually a trivial tree since all codes use
95122394Sharti * 5 bits.)
96122394Sharti */
97122394Sharti
98122394Shartiuch _dist_code[DIST_CODE_LEN];
99122394Sharti/* Distance codes. The first 256 values correspond to the distances
100122394Sharti * 3 .. 258, the last 256 values correspond to the top 8 bits of
101122394Sharti * the 15 bit distances.
102122394Sharti */
103122394Sharti
104122394Shartiuch _length_code[MAX_MATCH-MIN_MATCH+1];
105122394Sharti/* length code for each normalized match length (0 == MIN_MATCH) */
106122394Sharti
107122394Shartilocal int base_length[LENGTH_CODES];
108159063Sharti/* First normalized length for each code (0 = MIN_MATCH) */
109159063Sharti
110159063Shartilocal int base_dist[D_CODES];
111122394Sharti/* First normalized distance for each code (0 = distance of 1) */
112159063Sharti
113159063Sharti#else
114159063Sharti#  include "trees.h"
115122394Sharti#endif /* GEN_TREES_H */
116159063Sharti
117159063Shartistruct static_tree_desc_s {
118159063Sharti    const ct_data *static_tree;  /* static tree or NULL */
119122394Sharti    const intf *extra_bits;      /* extra bits for each code or NULL */
120159063Sharti    int     extra_base;          /* base index for extra_bits */
121159063Sharti    int     elems;               /* max number of elements in the tree */
122122394Sharti    int     max_length;          /* max bit length for the codes */
123122394Sharti};
124159063Sharti
125122394Shartilocal static_tree_desc  static_l_desc =
126122394Sharti{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
127122394Sharti
128122394Shartilocal static_tree_desc  static_d_desc =
129122394Sharti{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
130122394Sharti
131122394Shartilocal static_tree_desc  static_bl_desc =
132122394Sharti{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
133122394Sharti
134122394Sharti/* ===========================================================================
135122394Sharti * Local (static) routines in this file.
136122394Sharti */
137122394Sharti
138122394Shartilocal void tr_static_init OF((void));
139122394Shartilocal void init_block     OF((deflate_state *s));
140122394Shartilocal void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
141122394Shartilocal void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
142122394Shartilocal void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
143122394Shartilocal void build_tree     OF((deflate_state *s, tree_desc *desc));
144122394Shartilocal void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
145122394Shartilocal void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
146122394Shartilocal int  build_bl_tree  OF((deflate_state *s));
147122394Shartilocal void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
148122394Sharti                              int blcodes));
149122394Shartilocal void compress_block OF((deflate_state *s, ct_data *ltree,
150122394Sharti                              ct_data *dtree));
151122394Shartilocal int  detect_data_type OF((deflate_state *s));
152122394Shartilocal unsigned bi_reverse OF((unsigned value, int length));
153122394Shartilocal void bi_windup      OF((deflate_state *s));
154122394Shartilocal void bi_flush       OF((deflate_state *s));
155122394Shartilocal void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
156122394Sharti                              int header));
157122394Sharti
158122394Sharti#ifdef GEN_TREES_H
159133211Shartilocal void gen_trees_header OF((void));
160122394Sharti#endif
161122394Sharti
162122394Sharti#ifndef DEBUG
163122394Sharti#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
164122394Sharti   /* Send a code of the given tree. c and tree must not have side effects */
165122394Sharti
166122394Sharti#else /* DEBUG */
167122394Sharti#  define send_code(s, c, tree) \
168122394Sharti     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
169122394Sharti       send_bits(s, tree[c].Code, tree[c].Len); }
170122394Sharti#endif
171122394Sharti
172122394Sharti/* ===========================================================================
173122394Sharti * Output a short LSB first on the stream.
174122394Sharti * IN assertion: there is enough room in pendingBuf.
175122394Sharti */
176122394Sharti#define put_short(s, w) { \
177122394Sharti    put_byte(s, (uch)((w) & 0xff)); \
178122394Sharti    put_byte(s, (uch)((ush)(w) >> 8)); \
179122394Sharti}
180122394Sharti
181122394Sharti/* ===========================================================================
182159063Sharti * Send a value on a given number of bits.
183159063Sharti * IN assertion: length <= 16 and value fits in length bits.
184159063Sharti */
185159063Sharti#ifdef DEBUG
186159063Shartilocal void send_bits      OF((deflate_state *s, int value, int length));
187159063Sharti
188159063Shartilocal void send_bits(s, value, length)
189159063Sharti    deflate_state *s;
190159063Sharti    int value;  /* value to send */
191159063Sharti    int length; /* number of bits */
192159063Sharti{
193159063Sharti    Tracevv((stderr," l %2d v %4x ", length, value));
194159063Sharti    Assert(length > 0 && length <= 15, "invalid length");
195159063Sharti    s->bits_sent += (ulg)length;
196159063Sharti
197159063Sharti    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
198159063Sharti     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
199159063Sharti     * unused bits in value.
200159063Sharti     */
201159063Sharti    if (s->bi_valid > (int)Buf_size - length) {
202159063Sharti        s->bi_buf |= (ush)value << s->bi_valid;
203159063Sharti        put_short(s, s->bi_buf);
204159063Sharti        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
205122394Sharti        s->bi_valid += length - Buf_size;
206122394Sharti    } else {
207122394Sharti        s->bi_buf |= (ush)value << s->bi_valid;
208122394Sharti        s->bi_valid += length;
209122394Sharti    }
210122394Sharti}
211122394Sharti#else /* !DEBUG */
212122394Sharti
213122394Sharti#define send_bits(s, value, length) \
214122394Sharti{ int len = length;\
215145557Sharti  if (s->bi_valid > (int)Buf_size - len) {\
216122394Sharti    int val = value;\
217122394Sharti    s->bi_buf |= (ush)val << s->bi_valid;\
218122394Sharti    put_short(s, s->bi_buf);\
219122394Sharti    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
220159063Sharti    s->bi_valid += len - Buf_size;\
221159063Sharti  } else {\
222159063Sharti    s->bi_buf |= (ush)(value) << s->bi_valid;\
223159063Sharti    s->bi_valid += len;\
224159063Sharti  }\
225159063Sharti}
226159063Sharti#endif /* DEBUG */
227159063Sharti
228159063Sharti
229122394Sharti/* the arguments must not have side effects */
230122394Sharti
231159063Sharti/* ===========================================================================
232159063Sharti * Initialize the various 'constant' tables.
233159063Sharti */
234159063Shartilocal void tr_static_init()
235159063Sharti{
236159063Sharti#if defined(GEN_TREES_H) || !defined(STDC)
237159063Sharti    static int static_init_done = 0;
238159063Sharti    int n;        /* iterates over tree elements */
239159063Sharti    int bits;     /* bit counter */
240159063Sharti    int length;   /* length value */
241159063Sharti    int code;     /* code value */
242159063Sharti    int dist;     /* distance index */
243159063Sharti    ush bl_count[MAX_BITS+1];
244159063Sharti    /* number of codes at each bit length for an optimal tree */
245159063Sharti
246159063Sharti    if (static_init_done) return;
247159063Sharti
248159063Sharti    /* For some embedded targets, global variables are not initialized: */
249159063Sharti#ifdef NO_INIT_GLOBAL_POINTERS
250159063Sharti    static_l_desc.static_tree = static_ltree;
251159063Sharti    static_l_desc.extra_bits = extra_lbits;
252159063Sharti    static_d_desc.static_tree = static_dtree;
253159063Sharti    static_d_desc.extra_bits = extra_dbits;
254159063Sharti    static_bl_desc.extra_bits = extra_blbits;
255159063Sharti#endif
256159063Sharti
257159063Sharti    /* Initialize the mapping length (0..255) -> length code (0..28) */
258159063Sharti    length = 0;
259159063Sharti    for (code = 0; code < LENGTH_CODES-1; code++) {
260159063Sharti        base_length[code] = length;
261159063Sharti        for (n = 0; n < (1<<extra_lbits[code]); n++) {
262159063Sharti            _length_code[length++] = (uch)code;
263159063Sharti        }
264159063Sharti    }
265159063Sharti    Assert (length == 256, "tr_static_init: length != 256");
266159063Sharti    /* Note that the length 255 (match length 258) can be represented
267159063Sharti     * in two different ways: code 284 + 5 bits or code 285, so we
268159063Sharti     * overwrite length_code[255] to use the best encoding:
269159063Sharti     */
270159063Sharti    _length_code[length-1] = (uch)code;
271159063Sharti
272159063Sharti    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
273159063Sharti    dist = 0;
274159063Sharti    for (code = 0 ; code < 16; code++) {
275159063Sharti        base_dist[code] = dist;
276159063Sharti        for (n = 0; n < (1<<extra_dbits[code]); n++) {
277159063Sharti            _dist_code[dist++] = (uch)code;
278159063Sharti        }
279159063Sharti    }
280159063Sharti    Assert (dist == 256, "tr_static_init: dist != 256");
281159063Sharti    dist >>= 7; /* from now on, all distances are divided by 128 */
282159063Sharti    for ( ; code < D_CODES; code++) {
283159063Sharti        base_dist[code] = dist << 7;
284159063Sharti        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
285159063Sharti            _dist_code[256 + dist++] = (uch)code;
286159063Sharti        }
287159063Sharti    }
288159063Sharti    Assert (dist == 256, "tr_static_init: 256+dist != 512");
289159063Sharti
290159063Sharti    /* Construct the codes of the static literal tree */
291159063Sharti    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
292159063Sharti    n = 0;
293159063Sharti    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
294159063Sharti    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
295159063Sharti    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
296159063Sharti    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
297159063Sharti    /* Codes 286 and 287 do not exist, but we must include them in the
298159063Sharti     * tree construction to get a canonical Huffman tree (longest code
299159063Sharti     * all ones)
300159063Sharti     */
301159063Sharti    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
302159063Sharti
303159063Sharti    /* The static distance tree is trivial: */
304159063Sharti    for (n = 0; n < D_CODES; n++) {
305159063Sharti        static_dtree[n].Len = 5;
306159063Sharti        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
307159063Sharti    }
308159063Sharti    static_init_done = 1;
309159063Sharti
310159063Sharti#  ifdef GEN_TREES_H
311159063Sharti    gen_trees_header();
312159063Sharti#  endif
313159063Sharti#endif /* defined(GEN_TREES_H) || !defined(STDC) */
314159063Sharti}
315159063Sharti
316159063Sharti/* ===========================================================================
317159063Sharti * Genererate the file trees.h describing the static trees.
318159063Sharti */
319159063Sharti#ifdef GEN_TREES_H
320159063Sharti#  ifndef DEBUG
321159063Sharti#    include <stdio.h>
322159063Sharti#  endif
323159063Sharti
324159063Sharti#  define SEPARATOR(i, last, width) \
325159063Sharti      ((i) == (last)? "\n};\n\n" :    \
326159063Sharti       ((i) % (width) == (width)-1 ? ",\n" : ", "))
327159063Sharti
328159063Shartivoid gen_trees_header()
329159063Sharti{
330159063Sharti    FILE *header = fopen("trees.h", "w");
331159063Sharti    int i;
332159063Sharti
333159063Sharti    Assert (header != NULL, "Can't open trees.h");
334159063Sharti    fprintf(header,
335159063Sharti            "/* header created automatically with -DGEN_TREES_H */\n\n");
336159063Sharti
337159063Sharti    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
338159063Sharti    for (i = 0; i < L_CODES+2; i++) {
339159063Sharti        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
340159063Sharti                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
341159063Sharti    }
342159063Sharti
343159063Sharti    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
344159063Sharti    for (i = 0; i < D_CODES; i++) {
345159063Sharti        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
346159063Sharti                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
347159063Sharti    }
348159063Sharti
349159063Sharti    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
350159063Sharti    for (i = 0; i < DIST_CODE_LEN; i++) {
351159063Sharti        fprintf(header, "%2u%s", _dist_code[i],
352159063Sharti                SEPARATOR(i, DIST_CODE_LEN-1, 20));
353159063Sharti    }
354159063Sharti
355159063Sharti    fprintf(header,
356159063Sharti        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
357159063Sharti    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
358159063Sharti        fprintf(header, "%2u%s", _length_code[i],
359159063Sharti                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
360159063Sharti    }
361159063Sharti
362159063Sharti    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
363159063Sharti    for (i = 0; i < LENGTH_CODES; i++) {
364159063Sharti        fprintf(header, "%1u%s", base_length[i],
365159063Sharti                SEPARATOR(i, LENGTH_CODES-1, 20));
366159063Sharti    }
367159063Sharti
368159063Sharti    fprintf(header, "local const int base_dist[D_CODES] = {\n");
369159063Sharti    for (i = 0; i < D_CODES; i++) {
370159063Sharti        fprintf(header, "%5u%s", base_dist[i],
371159063Sharti                SEPARATOR(i, D_CODES-1, 10));
372159063Sharti    }
373159063Sharti
374159063Sharti    fclose(header);
375159063Sharti}
376159063Sharti#endif /* GEN_TREES_H */
377159063Sharti
378159063Sharti/* ===========================================================================
379159063Sharti * Initialize the tree data structures for a new zlib stream.
380122394Sharti */
381122394Shartivoid ZLIB_INTERNAL _tr_init(s)
382122394Sharti    deflate_state *s;
383122394Sharti{
384122394Sharti    tr_static_init();
385122394Sharti
386122394Sharti    s->l_desc.dyn_tree = s->dyn_ltree;
387122394Sharti    s->l_desc.stat_desc = &static_l_desc;
388159063Sharti
389159063Sharti    s->d_desc.dyn_tree = s->dyn_dtree;
390159063Sharti    s->d_desc.stat_desc = &static_d_desc;
391159063Sharti
392159063Sharti    s->bl_desc.dyn_tree = s->bl_tree;
393159063Sharti    s->bl_desc.stat_desc = &static_bl_desc;
394122394Sharti
395122394Sharti    s->bi_buf = 0;
396122394Sharti    s->bi_valid = 0;
397122394Sharti#ifdef DEBUG
398122394Sharti    s->compressed_len = 0L;
399122394Sharti    s->bits_sent = 0L;
400122394Sharti#endif
401122394Sharti
402122394Sharti    /* Initialize the first block of the first file: */
403122394Sharti    init_block(s);
404122394Sharti}
405122394Sharti
406122394Sharti/* ===========================================================================
407122394Sharti * Initialize a new block.
408122394Sharti */
409122394Shartilocal void init_block(s)
410122394Sharti    deflate_state *s;
411122394Sharti{
412122394Sharti    int n; /* iterates over tree elements */
413122394Sharti
414159063Sharti    /* Initialize the trees. */
415159063Sharti    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
416159063Sharti    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
417159063Sharti    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
418122394Sharti
419122394Sharti    s->dyn_ltree[END_BLOCK].Freq = 1;
420122394Sharti    s->opt_len = s->static_len = 0L;
421122394Sharti    s->last_lit = s->matches = 0;
422122394Sharti}
423122394Sharti
424122394Sharti#define SMALLEST 1
425133211Sharti/* Index within the heap array of least frequent node in the Huffman tree */
426159063Sharti
427122394Sharti
428122394Sharti/* ===========================================================================
429122394Sharti * Remove the smallest element from the heap and recreate the heap with
430122394Sharti * one less element. Updates heap and heap_len.
431122394Sharti */
432122394Sharti#define pqremove(s, tree, top) \
433122394Sharti{\
434122394Sharti    top = s->heap[SMALLEST]; \
435122394Sharti    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
436122394Sharti    pqdownheap(s, tree, SMALLEST); \
437122394Sharti}
438159063Sharti
439122394Sharti/* ===========================================================================
440122394Sharti * Compares to subtrees, using the tree depth as tie breaker when
441122394Sharti * the subtrees have equal frequency. This minimizes the worst case length.
442159063Sharti */
443122394Sharti#define smaller(tree, n, m, depth) \
444122394Sharti   (tree[n].Freq < tree[m].Freq || \
445122394Sharti   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
446122394Sharti
447122394Sharti/* ===========================================================================
448122394Sharti * Restore the heap property by moving down the tree starting at node k,
449122394Sharti * exchanging a node with the smallest of its two sons if necessary, stopping
450122394Sharti * when the heap property is re-established (each father smaller than its
451122394Sharti * two sons).
452122394Sharti */
453122394Shartilocal void pqdownheap(s, tree, k)
454122394Sharti    deflate_state *s;
455122394Sharti    ct_data *tree;  /* the tree to restore */
456122394Sharti    int k;               /* node to move down */
457122394Sharti{
458122394Sharti    int v = s->heap[k];
459122394Sharti    int j = k << 1;  /* left son of k */
460122394Sharti    while (j <= s->heap_len) {
461122394Sharti        /* Set j to the smallest of the two sons: */
462122394Sharti        if (j < s->heap_len &&
463122394Sharti            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
464122394Sharti            j++;
465122394Sharti        }
466122394Sharti        /* Exit if v is smaller than both sons */
467159063Sharti        if (smaller(tree, v, s->heap[j], s->depth)) break;
468122394Sharti
469122394Sharti        /* Exchange v with the smallest son */
470122394Sharti        s->heap[k] = s->heap[j];  k = j;
471122394Sharti
472122394Sharti        /* And continue down the tree, setting j to the left son of k */
473122394Sharti        j <<= 1;
474159063Sharti    }
475122394Sharti    s->heap[k] = v;
476122394Sharti}
477159063Sharti
478122394Sharti/* ===========================================================================
479159063Sharti * Compute the optimal bit lengths for a tree and update the total bit length
480159063Sharti * for the current block.
481159063Sharti * IN assertion: the fields freq and dad are set, heap[heap_max] and
482159063Sharti *    above are the tree nodes sorted by increasing frequency.
483159063Sharti * OUT assertions: the field len is set to the optimal bit length, the
484159063Sharti *     array bl_count contains the frequencies for each bit length.
485122394Sharti *     The length opt_len is updated; static_len is also updated if stree is
486122394Sharti *     not null.
487122394Sharti */
488122394Shartilocal void gen_bitlen(s, desc)
489159063Sharti    deflate_state *s;
490122394Sharti    tree_desc *desc;    /* the tree descriptor */
491159063Sharti{
492122394Sharti    ct_data *tree        = desc->dyn_tree;
493122394Sharti    int max_code         = desc->max_code;
494122394Sharti    const ct_data *stree = desc->stat_desc->static_tree;
495122394Sharti    const intf *extra    = desc->stat_desc->extra_bits;
496122394Sharti    int base             = desc->stat_desc->extra_base;
497122394Sharti    int max_length       = desc->stat_desc->max_length;
498122394Sharti    int h;              /* heap index */
499122394Sharti    int n, m;           /* iterate over the tree elements */
500122394Sharti    int bits;           /* bit length */
501122394Sharti    int xbits;          /* extra bits */
502122394Sharti    ush f;              /* frequency */
503122394Sharti    int overflow = 0;   /* number of elements with bit length too large */
504159063Sharti
505122394Sharti    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
506159063Sharti
507122394Sharti    /* In a first pass, compute the optimal bit lengths (which may
508122394Sharti     * overflow in the case of the bit length tree).
509122394Sharti     */
510122394Sharti    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
511122394Sharti
512122394Sharti    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
513122394Sharti        n = s->heap[h];
514122394Sharti        bits = tree[tree[n].Dad].Len + 1;
515122394Sharti        if (bits > max_length) bits = max_length, overflow++;
516159063Sharti        tree[n].Len = (ush)bits;
517122394Sharti        /* We overwrite tree[n].Dad which is no longer needed */
518122394Sharti
519159063Sharti        if (n > max_code) continue; /* not a leaf node */
520159063Sharti
521159063Sharti        s->bl_count[bits]++;
522159063Sharti        xbits = 0;
523159063Sharti        if (n >= base) xbits = extra[n-base];
524159063Sharti        f = tree[n].Freq;
525159063Sharti        s->opt_len += (ulg)f * (bits + xbits);
526159063Sharti        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
527159063Sharti    }
528159063Sharti    if (overflow == 0) return;
529159063Sharti
530159063Sharti    Trace((stderr,"\nbit length overflow\n"));
531159063Sharti    /* This happens for example on obj2 and pic of the Calgary corpus */
532159063Sharti
533159063Sharti    /* Find the first bit length which could increase: */
534159063Sharti    do {
535159063Sharti        bits = max_length-1;
536159063Sharti        while (s->bl_count[bits] == 0) bits--;
537159063Sharti        s->bl_count[bits]--;      /* move one leaf down the tree */
538159063Sharti        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
539159063Sharti        s->bl_count[max_length]--;
540159063Sharti        /* The brother of the overflow item also moves one step up,
541159063Sharti         * but this does not affect bl_count[max_length]
542122394Sharti         */
543122394Sharti        overflow -= 2;
544122394Sharti    } while (overflow > 0);
545122394Sharti
546159063Sharti    /* Now recompute all bit lengths, scanning in increasing frequency.
547159063Sharti     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
548159063Sharti     * lengths instead of fixing only the wrong ones. This idea is taken
549159063Sharti     * from 'ar' written by Haruhiko Okumura.)
550159063Sharti     */
551159063Sharti    for (bits = max_length; bits != 0; bits--) {
552159063Sharti        n = s->bl_count[bits];
553159063Sharti        while (n != 0) {
554159063Sharti            m = s->heap[--h];
555159063Sharti            if (m > max_code) continue;
556159063Sharti            if ((unsigned) tree[m].Len != (unsigned) bits) {
557159063Sharti                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
558159063Sharti                s->opt_len += ((long)bits - (long)tree[m].Len)
559159063Sharti                              *(long)tree[m].Freq;
560159063Sharti                tree[m].Len = (ush)bits;
561122394Sharti            }
562122394Sharti            n--;
563122394Sharti        }
564122394Sharti    }
565122394Sharti}
566122394Sharti
567122394Sharti/* ===========================================================================
568122394Sharti * Generate the codes for a given tree and bit counts (which need not be
569122394Sharti * optimal).
570159063Sharti * IN assertion: the array bl_count contains the bit length statistics for
571159063Sharti * the given tree and the field len is set for all tree elements.
572159063Sharti * OUT assertion: the field code is set for all tree elements of non
573122394Sharti *     zero code length.
574122394Sharti */
575122394Shartilocal void gen_codes (tree, max_code, bl_count)
576122394Sharti    ct_data *tree;             /* the tree to decorate */
577122394Sharti    int max_code;              /* largest code with non zero frequency */
578122394Sharti    ushf *bl_count;            /* number of codes at each bit length */
579122394Sharti{
580122394Sharti    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
581122394Sharti    ush code = 0;              /* running code value */
582122394Sharti    int bits;                  /* bit index */
583122394Sharti    int n;                     /* code index */
584122394Sharti
585122394Sharti    /* The distribution counts are first used to generate the code values
586122394Sharti     * without bit reversal.
587122394Sharti     */
588122394Sharti    for (bits = 1; bits <= MAX_BITS; bits++) {
589122394Sharti        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
590122394Sharti    }
591122394Sharti    /* Check that the bit counts in bl_count are consistent. The last code
592159063Sharti     * must be all ones.
593159063Sharti     */
594159063Sharti    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
595159063Sharti            "inconsistent bit counts");
596159063Sharti    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
597159063Sharti
598122394Sharti    for (n = 0;  n <= max_code; n++) {
599122394Sharti        int len = tree[n].Len;
600122394Sharti        if (len == 0) continue;
601159063Sharti        /* Now reverse the bits */
602122394Sharti        tree[n].Code = bi_reverse(next_code[len]++, len);
603159063Sharti
604159063Sharti        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
605122394Sharti             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
606159063Sharti    }
607159063Sharti}
608159063Sharti
609159063Sharti/* ===========================================================================
610122394Sharti * Construct one Huffman tree and assigns the code bit strings and lengths.
611159063Sharti * Update the total bit length for the current block.
612159063Sharti * IN assertion: the field freq is set for all tree elements.
613159063Sharti * OUT assertions: the fields len and code are set to the optimal bit length
614159063Sharti *     and corresponding code. The length opt_len is updated; static_len is
615159063Sharti *     also updated if stree is not null. The field max_code is set.
616159063Sharti */
617159063Shartilocal void build_tree(s, desc)
618159063Sharti    deflate_state *s;
619159063Sharti    tree_desc *desc; /* the tree descriptor */
620159063Sharti{
621159063Sharti    ct_data *tree         = desc->dyn_tree;
622159063Sharti    const ct_data *stree  = desc->stat_desc->static_tree;
623159063Sharti    int elems             = desc->stat_desc->elems;
624159063Sharti    int n, m;          /* iterate over heap elements */
625159063Sharti    int max_code = -1; /* largest code with non zero frequency */
626159063Sharti    int node;          /* new node being created */
627159063Sharti
628159063Sharti    /* Construct the initial heap, with least frequent element in
629159063Sharti     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
630159063Sharti     * heap[0] is not used.
631159063Sharti     */
632159063Sharti    s->heap_len = 0, s->heap_max = HEAP_SIZE;
633159063Sharti
634159063Sharti    for (n = 0; n < elems; n++) {
635159063Sharti        if (tree[n].Freq != 0) {
636159063Sharti            s->heap[++(s->heap_len)] = max_code = n;
637159063Sharti            s->depth[n] = 0;
638159063Sharti        } else {
639159063Sharti            tree[n].Len = 0;
640159063Sharti        }
641159063Sharti    }
642159063Sharti
643159063Sharti    /* The pkzip format requires that at least one distance code exists,
644159063Sharti     * and that at least one bit should be sent even if there is only one
645159063Sharti     * possible code. So to avoid special checks later on we force at least
646159063Sharti     * two codes of non zero frequency.
647159063Sharti     */
648159063Sharti    while (s->heap_len < 2) {
649159063Sharti        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
650159063Sharti        tree[node].Freq = 1;
651159063Sharti        s->depth[node] = 0;
652159063Sharti        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
653159063Sharti        /* node is 0 or 1 so it does not have extra bits */
654159063Sharti    }
655159063Sharti    desc->max_code = max_code;
656159063Sharti
657159063Sharti    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
658159063Sharti     * establish sub-heaps of increasing lengths:
659159063Sharti     */
660159063Sharti    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
661159063Sharti
662159063Sharti    /* Construct the Huffman tree by repeatedly combining the least two
663159063Sharti     * frequent nodes.
664159063Sharti     */
665159063Sharti    node = elems;              /* next internal node of the tree */
666159063Sharti    do {
667159063Sharti        pqremove(s, tree, n);  /* n = node of least frequency */
668159063Sharti        m = s->heap[SMALLEST]; /* m = node of next least frequency */
669159063Sharti
670159063Sharti        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
671159063Sharti        s->heap[--(s->heap_max)] = m;
672159063Sharti
673159063Sharti        /* Create a new node father of n and m */
674159063Sharti        tree[node].Freq = tree[n].Freq + tree[m].Freq;
675159063Sharti        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
676159063Sharti                                s->depth[n] : s->depth[m]) + 1);
677159063Sharti        tree[n].Dad = tree[m].Dad = (ush)node;
678159063Sharti#ifdef DUMP_BL_TREE
679159063Sharti        if (tree == s->bl_tree) {
680159063Sharti            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
681159063Sharti                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
682159063Sharti        }
683159063Sharti#endif
684159063Sharti        /* and insert the new node in the heap */
685159063Sharti        s->heap[SMALLEST] = node++;
686122394Sharti        pqdownheap(s, tree, SMALLEST);
687159063Sharti
688159063Sharti    } while (s->heap_len >= 2);
689159063Sharti
690159063Sharti    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
691159063Sharti
692159063Sharti    /* At this point, the fields freq and dad are set. We can now
693159063Sharti     * generate the bit lengths.
694159063Sharti     */
695159063Sharti    gen_bitlen(s, (tree_desc *)desc);
696159063Sharti
697159063Sharti    /* The field len is now set, we can generate the bit codes */
698159063Sharti    gen_codes ((ct_data *)tree, max_code, s->bl_count);
699159063Sharti}
700159063Sharti
701159063Sharti/* ===========================================================================
702159063Sharti * Scan a literal or distance tree to determine the frequencies of the codes
703159063Sharti * in the bit length tree.
704159063Sharti */
705159063Shartilocal void scan_tree (s, tree, max_code)
706159063Sharti    deflate_state *s;
707159063Sharti    ct_data *tree;   /* the tree to be scanned */
708159063Sharti    int max_code;    /* and its largest code of non zero frequency */
709159063Sharti{
710159063Sharti    int n;                     /* iterates over all tree elements */
711159063Sharti    int prevlen = -1;          /* last emitted length */
712159063Sharti    int curlen;                /* length of current code */
713159063Sharti    int nextlen = tree[0].Len; /* length of next code */
714159063Sharti    int count = 0;             /* repeat count of the current code */
715159063Sharti    int max_count = 7;         /* max repeat count */
716159063Sharti    int min_count = 4;         /* min repeat count */
717159063Sharti
718159063Sharti    if (nextlen == 0) max_count = 138, min_count = 3;
719159063Sharti    tree[max_code+1].Len = (ush)0xffff; /* guard */
720159063Sharti
721159063Sharti    for (n = 0; n <= max_code; n++) {
722159063Sharti        curlen = nextlen; nextlen = tree[n+1].Len;
723159063Sharti        if (++count < max_count && curlen == nextlen) {
724159063Sharti            continue;
725159063Sharti        } else if (count < min_count) {
726159063Sharti            s->bl_tree[curlen].Freq += count;
727159063Sharti        } else if (curlen != 0) {
728159063Sharti            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
729159063Sharti            s->bl_tree[REP_3_6].Freq++;
730159063Sharti        } else if (count <= 10) {
731159063Sharti            s->bl_tree[REPZ_3_10].Freq++;
732159063Sharti        } else {
733159063Sharti            s->bl_tree[REPZ_11_138].Freq++;
734159063Sharti        }
735159063Sharti        count = 0; prevlen = curlen;
736159063Sharti        if (nextlen == 0) {
737159063Sharti            max_count = 138, min_count = 3;
738159063Sharti        } else if (curlen == nextlen) {
739159063Sharti            max_count = 6, min_count = 3;
740159063Sharti        } else {
741159063Sharti            max_count = 7, min_count = 4;
742159063Sharti        }
743159063Sharti    }
744159063Sharti}
745159063Sharti
746298450Sngie/* ===========================================================================
747298450Sngie * Send a literal or distance tree in compressed form, using the codes in
748159063Sharti * bl_tree.
749159063Sharti */
750159063Shartilocal void send_tree (s, tree, max_code)
751159063Sharti    deflate_state *s;
752159063Sharti    ct_data *tree; /* the tree to be scanned */
753159063Sharti    int max_code;       /* and its largest code of non zero frequency */
754159063Sharti{
755159063Sharti    int n;                     /* iterates over all tree elements */
756159063Sharti    int prevlen = -1;          /* last emitted length */
757159063Sharti    int curlen;                /* length of current code */
758159063Sharti    int nextlen = tree[0].Len; /* length of next code */
759159063Sharti    int count = 0;             /* repeat count of the current code */
760159063Sharti    int max_count = 7;         /* max repeat count */
761159063Sharti    int min_count = 4;         /* min repeat count */
762159063Sharti
763159063Sharti    /* tree[max_code+1].Len = -1; */  /* guard already set */
764159063Sharti    if (nextlen == 0) max_count = 138, min_count = 3;
765159063Sharti
766159063Sharti    for (n = 0; n <= max_code; n++) {
767159063Sharti        curlen = nextlen; nextlen = tree[n+1].Len;
768122394Sharti        if (++count < max_count && curlen == nextlen) {
769122394Sharti            continue;
770122394Sharti        } else if (count < min_count) {
771122394Sharti            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
772122394Sharti
773122394Sharti        } else if (curlen != 0) {
774122394Sharti            if (curlen != prevlen) {
775122394Sharti                send_code(s, curlen, s->bl_tree); count--;
776122394Sharti            }
777122394Sharti            Assert(count >= 3 && count <= 6, " 3_6?");
778159063Sharti            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
779154182Sharti
780122394Sharti        } else if (count <= 10) {
781122394Sharti            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
782122394Sharti
783122394Sharti        } else {
784122394Sharti            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
785122394Sharti        }
786122394Sharti        count = 0; prevlen = curlen;
787122394Sharti        if (nextlen == 0) {
788122394Sharti            max_count = 138, min_count = 3;
789122394Sharti        } else if (curlen == nextlen) {
790122394Sharti            max_count = 6, min_count = 3;
791122394Sharti        } else {
792159063Sharti            max_count = 7, min_count = 4;
793159063Sharti        }
794122394Sharti    }
795159063Sharti}
796122394Sharti
797159063Sharti/* ===========================================================================
798122394Sharti * Construct the Huffman tree for the bit lengths and return the index in
799122394Sharti * bl_order of the last bit length code to send.
800122394Sharti */
801122394Shartilocal int build_bl_tree(s)
802122394Sharti    deflate_state *s;
803122394Sharti{
804122394Sharti    int max_blindex;  /* index of last bit length code of non zero freq */
805122394Sharti
806122394Sharti    /* Determine the bit length frequencies for literal and distance trees */
807122394Sharti    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
808122394Sharti    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
809122394Sharti
810122394Sharti    /* Build the bit length tree: */
811122394Sharti    build_tree(s, (tree_desc *)(&(s->bl_desc)));
812122394Sharti    /* opt_len now includes the length of the tree representations, except
813122394Sharti     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
814122394Sharti     */
815122394Sharti
816122394Sharti    /* Determine the number of bit length codes to send. The pkzip format
817122394Sharti     * requires that at least 4 bit length codes be sent. (appnote.txt says
818122394Sharti     * 3 but the actual value used is 4.)
819122394Sharti     */
820122394Sharti    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
821122394Sharti        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
822122394Sharti    }
823159063Sharti    /* Update opt_len to include the bit length tree and counts */
824159063Sharti    s->opt_len += 3*(max_blindex+1) + 5+5+4;
825159063Sharti    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
826159063Sharti            s->opt_len, s->static_len));
827122394Sharti
828122394Sharti    return max_blindex;
829122394Sharti}
830159063Sharti
831122394Sharti/* ===========================================================================
832122394Sharti * Send the header for a block using dynamic Huffman trees: the counts, the
833122394Sharti * lengths of the bit length codes, the literal tree and the distance tree.
834122394Sharti * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
835122394Sharti */
836122394Shartilocal void send_all_trees(s, lcodes, dcodes, blcodes)
837122394Sharti    deflate_state *s;
838122394Sharti    int lcodes, dcodes, blcodes; /* number of codes for each tree */
839122394Sharti{
840122394Sharti    int rank;                    /* index in bl_order */
841122394Sharti
842122394Sharti    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
843122394Sharti    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
844122394Sharti            "too many codes");
845122394Sharti    Tracev((stderr, "\nbl counts: "));
846122394Sharti    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
847122394Sharti    send_bits(s, dcodes-1,   5);
848122394Sharti    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
849122394Sharti    for (rank = 0; rank < blcodes; rank++) {
850122394Sharti        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
851122394Sharti        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
852122394Sharti    }
853122394Sharti    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
854122394Sharti
855122394Sharti    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
856122394Sharti    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
857122394Sharti
858122394Sharti    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
859122394Sharti    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
860122394Sharti}
861122394Sharti
862122394Sharti/* ===========================================================================
863159063Sharti * Send a stored block
864159063Sharti */
865159063Shartivoid ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
866159063Sharti    deflate_state *s;
867159063Sharti    charf *buf;       /* input block */
868159063Sharti    ulg stored_len;   /* length of input block */
869159063Sharti    int last;         /* one if this is the last block for a file */
870159063Sharti{
871159063Sharti    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
872159063Sharti#ifdef DEBUG
873159063Sharti    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
874159063Sharti    s->compressed_len += (stored_len + 4) << 3;
875159063Sharti#endif
876159063Sharti    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
877159063Sharti}
878159063Sharti
879159063Sharti/* ===========================================================================
880159063Sharti * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
881159063Sharti */
882159063Shartivoid ZLIB_INTERNAL _tr_flush_bits(s)
883159063Sharti    deflate_state *s;
884159063Sharti{
885159063Sharti    bi_flush(s);
886159063Sharti}
887159063Sharti
888159063Sharti/* ===========================================================================
889159063Sharti * Send one empty static block to give enough lookahead for inflate.
890159063Sharti * This takes 10 bits, of which 7 may remain in the bit buffer.
891159063Sharti */
892159063Shartivoid ZLIB_INTERNAL _tr_align(s)
893159063Sharti    deflate_state *s;
894159063Sharti{
895159063Sharti    send_bits(s, STATIC_TREES<<1, 3);
896159063Sharti    send_code(s, END_BLOCK, static_ltree);
897159063Sharti#ifdef DEBUG
898159063Sharti    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
899159063Sharti#endif
900159063Sharti    bi_flush(s);
901122394Sharti}
902122394Sharti
903122394Sharti/* ===========================================================================
904159063Sharti * Determine the best encoding for the current block: dynamic trees, static
905159063Sharti * trees or store, and output the encoded block to the zip file.
906122394Sharti */
907122394Shartivoid ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
908122394Sharti    deflate_state *s;
909122394Sharti    charf *buf;       /* input block, or NULL if too old */
910122394Sharti    ulg stored_len;   /* length of input block */
911122394Sharti    int last;         /* one if this is the last block for a file */
912122394Sharti{
913122394Sharti    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
914122394Sharti    int max_blindex = 0;  /* index of last bit length code of non zero freq */
915122394Sharti
916122394Sharti    /* Build the Huffman trees unless a stored block is forced */
917159063Sharti    if (s->level > 0) {
918122394Sharti
919122394Sharti        /* Check if the file is binary or text */
920122394Sharti        if (s->strm->data_type == Z_UNKNOWN)
921122394Sharti            s->strm->data_type = detect_data_type(s);
922122394Sharti
923159063Sharti        /* Construct the literal and distance trees */
924159063Sharti        build_tree(s, (tree_desc *)(&(s->l_desc)));
925122394Sharti        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
926122394Sharti                s->static_len));
927122394Sharti
928122394Sharti        build_tree(s, (tree_desc *)(&(s->d_desc)));
929122394Sharti        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
930122394Sharti                s->static_len));
931122394Sharti        /* At this point, opt_len and static_len are the total bit lengths of
932122394Sharti         * the compressed block data, excluding the tree representations.
933122394Sharti         */
934122394Sharti
935122394Sharti        /* Build the bit length tree for the above two trees, and get the index
936122394Sharti         * in bl_order of the last bit length code to send.
937122394Sharti         */
938122394Sharti        max_blindex = build_bl_tree(s);
939122394Sharti
940122394Sharti        /* Determine the best encoding. Compute the block lengths in bytes. */
941122394Sharti        opt_lenb = (s->opt_len+3+7)>>3;
942122394Sharti        static_lenb = (s->static_len+3+7)>>3;
943122394Sharti
944122394Sharti        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
945122394Sharti                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
946122394Sharti                s->last_lit));
947122394Sharti
948122394Sharti        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
949122394Sharti
950122394Sharti    } else {
951122394Sharti        Assert(buf != (char*)0, "lost buf");
952122394Sharti        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
953122394Sharti    }
954122394Sharti
955122394Sharti#ifdef FORCE_STORED
956122394Sharti    if (buf != (char*)0) { /* force stored block */
957122394Sharti#else
958122394Sharti    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
959122394Sharti                       /* 4: two words for the lengths */
960122394Sharti#endif
961122394Sharti        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
962122394Sharti         * Otherwise we can't have processed more than WSIZE input bytes since
963122394Sharti         * the last block flush, because compression would have been
964122394Sharti         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
965122394Sharti         * transform a block into a stored block.
966122394Sharti         */
967122394Sharti        _tr_stored_block(s, buf, stored_len, last);
968122394Sharti
969122394Sharti#ifdef FORCE_STATIC
970122394Sharti    } else if (static_lenb >= 0) { /* force static trees */
971122394Sharti#else
972122394Sharti    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
973122394Sharti#endif
974122394Sharti        send_bits(s, (STATIC_TREES<<1)+last, 3);
975122394Sharti        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
976122394Sharti#ifdef DEBUG
977122394Sharti        s->compressed_len += 3 + s->static_len;
978122394Sharti#endif
979122394Sharti    } else {
980122394Sharti        send_bits(s, (DYN_TREES<<1)+last, 3);
981122394Sharti        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
982122394Sharti                       max_blindex+1);
983122394Sharti        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
984122394Sharti#ifdef DEBUG
985122394Sharti        s->compressed_len += 3 + s->opt_len;
986122394Sharti#endif
987122394Sharti    }
988122394Sharti    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
989122394Sharti    /* The above check is made mod 2^32, for files larger than 512 MB
990122394Sharti     * and uLong implemented on 32 bits.
991122394Sharti     */
992122394Sharti    init_block(s);
993122394Sharti
994122394Sharti    if (last) {
995122394Sharti        bi_windup(s);
996122394Sharti#ifdef DEBUG
997122394Sharti        s->compressed_len += 7;  /* align on byte boundary */
998122394Sharti#endif
999122394Sharti    }
1000128237Sharti    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1001122394Sharti           s->compressed_len-7*last));
1002122394Sharti}
1003122394Sharti
1004122394Sharti/* ===========================================================================
1005122394Sharti * Save the match info and tally the frequency counts. Return true if
1006122394Sharti * the current block must be flushed.
1007122394Sharti */
1008122394Shartiint ZLIB_INTERNAL _tr_tally (s, dist, lc)
1009159063Sharti    deflate_state *s;
1010122394Sharti    unsigned dist;  /* distance of matched string */
1011122394Sharti    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
1012122394Sharti{
1013122394Sharti    s->d_buf[s->last_lit] = (ush)dist;
1014122394Sharti    s->l_buf[s->last_lit++] = (uch)lc;
1015122394Sharti    if (dist == 0) {
1016122394Sharti        /* lc is the unmatched char */
1017122394Sharti        s->dyn_ltree[lc].Freq++;
1018159063Sharti    } else {
1019122394Sharti        s->matches++;
1020122394Sharti        /* Here, lc is the match length - MIN_MATCH */
1021122394Sharti        dist--;             /* dist = match distance - 1 */
1022122394Sharti        Assert((ush)dist < (ush)MAX_DIST(s) &&
1023159063Sharti               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1024122394Sharti               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1025122394Sharti
1026122394Sharti        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1027122394Sharti        s->dyn_dtree[d_code(dist)].Freq++;
1028122394Sharti    }
1029122394Sharti
1030142810Sharti#ifdef TRUNCATE_BLOCK
1031142810Sharti    /* Try to guess if it is profitable to stop the current block here */
1032142810Sharti    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
1033142810Sharti        /* Compute an upper bound for the compressed length */
1034122394Sharti        ulg out_length = (ulg)s->last_lit*8L;
1035142810Sharti        ulg in_length = (ulg)((long)s->strstart - s->block_start);
1036122394Sharti        int dcode;
1037122394Sharti        for (dcode = 0; dcode < D_CODES; dcode++) {
1038122394Sharti            out_length += (ulg)s->dyn_dtree[dcode].Freq *
1039122394Sharti                (5L+extra_dbits[dcode]);
1040122394Sharti        }
1041122394Sharti        out_length >>= 3;
1042122394Sharti        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
1043122394Sharti               s->last_lit, in_length, out_length,
1044159063Sharti               100L - out_length*100L/in_length));
1045122394Sharti        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
1046122394Sharti    }
1047122394Sharti#endif
1048122394Sharti    return (s->last_lit == s->lit_bufsize-1);
1049122394Sharti    /* We avoid equality with lit_bufsize because of wraparound at 64K
1050122394Sharti     * on 16 bit machines and because stored blocks are restricted to
1051122394Sharti     * 64K-1 bytes.
1052122394Sharti     */
1053122394Sharti}
1054122394Sharti
1055122394Sharti/* ===========================================================================
1056122394Sharti * Send the block data compressed using the given Huffman trees
1057122394Sharti */
1058122394Shartilocal void compress_block(s, ltree, dtree)
1059159063Sharti    deflate_state *s;
1060122394Sharti    ct_data *ltree; /* literal tree */
1061122394Sharti    ct_data *dtree; /* distance tree */
1062122394Sharti{
1063122394Sharti    unsigned dist;      /* distance of matched string */
1064122394Sharti    int lc;             /* match length or unmatched char (if dist == 0) */
1065150920Sharti    unsigned lx = 0;    /* running index in l_buf */
1066133211Sharti    unsigned code;      /* the code to send */
1067150920Sharti    int extra;          /* number of extra bits to send */
1068122394Sharti
1069122394Sharti    if (s->last_lit != 0) do {
1070122394Sharti        dist = s->d_buf[lx];
1071122394Sharti        lc = s->l_buf[lx++];
1072122394Sharti        if (dist == 0) {
1073122394Sharti            send_code(s, lc, ltree); /* send a literal byte */
1074122394Sharti            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1075122394Sharti        } else {
1076122394Sharti            /* Here, lc is the match length - MIN_MATCH */
1077122394Sharti            code = _length_code[lc];
1078122394Sharti            send_code(s, code+LITERALS+1, ltree); /* send the length code */
1079122394Sharti            extra = extra_lbits[code];
1080122394Sharti            if (extra != 0) {
1081122394Sharti                lc -= base_length[code];
1082122394Sharti                send_bits(s, lc, extra);       /* send the extra length bits */
1083122394Sharti            }
1084159063Sharti            dist--; /* dist is now the match distance - 1 */
1085122394Sharti            code = d_code(dist);
1086122394Sharti            Assert (code < D_CODES, "bad d_code");
1087122394Sharti
1088122394Sharti            send_code(s, code, dtree);       /* send the distance code */
1089133211Sharti            extra = extra_dbits[code];
1090133211Sharti            if (extra != 0) {
1091133211Sharti                dist -= base_dist[code];
1092133211Sharti                send_bits(s, dist, extra);   /* send the extra distance bits */
1093133211Sharti            }
1094133211Sharti        } /* literal or match pair ? */
1095133211Sharti
1096133211Sharti        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1097133211Sharti        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
1098133211Sharti               "pendingBuf overflow");
1099133211Sharti
1100133211Sharti    } while (lx < s->last_lit);
1101133211Sharti
1102133211Sharti    send_code(s, END_BLOCK, ltree);
1103133211Sharti}
1104133211Sharti
1105133211Sharti/* ===========================================================================
1106133211Sharti * Check if the data type is TEXT or BINARY, using the following algorithm:
1107133211Sharti * - TEXT if the two conditions below are satisfied:
1108133211Sharti *    a) There are no non-portable control characters belonging to the
1109133211Sharti *       "black list" (0..6, 14..25, 28..31).
1110133211Sharti *    b) There is at least one printable character belonging to the
1111133211Sharti *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1112133211Sharti * - BINARY otherwise.
1113133211Sharti * - The following partially-portable control characters form a
1114133211Sharti *   "gray list" that is ignored in this detection algorithm:
1115133211Sharti *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
1116133211Sharti * IN assertion: the fields Freq of dyn_ltree are set.
1117133211Sharti */
1118133211Shartilocal int detect_data_type(s)
1119133211Sharti    deflate_state *s;
1120133211Sharti{
1121133211Sharti    /* black_mask is the bit mask of black-listed bytes
1122133211Sharti     * set bits 0..6, 14..25, and 28..31
1123133211Sharti     * 0xf3ffc07f = binary 11110011111111111100000001111111
1124133211Sharti     */
1125133211Sharti    unsigned long black_mask = 0xf3ffc07fUL;
1126133211Sharti    int n;
1127133211Sharti
1128133211Sharti    /* Check for non-textual ("black-listed") bytes. */
1129133211Sharti    for (n = 0; n <= 31; n++, black_mask >>= 1)
1130133211Sharti        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
1131133211Sharti            return Z_BINARY;
1132133211Sharti
1133133211Sharti    /* Check for textual ("white-listed") bytes. */
1134133211Sharti    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1135133211Sharti            || s->dyn_ltree[13].Freq != 0)
1136133211Sharti        return Z_TEXT;
1137133211Sharti    for (n = 32; n < LITERALS; n++)
1138133211Sharti        if (s->dyn_ltree[n].Freq != 0)
1139133211Sharti            return Z_TEXT;
1140133211Sharti
1141133211Sharti    /* There are no "black-listed" or "white-listed" bytes:
1142133211Sharti     * this stream either is empty or has tolerated ("gray-listed") bytes only.
1143133211Sharti     */
1144133211Sharti    return Z_BINARY;
1145133211Sharti}
1146133211Sharti
1147133211Sharti/* ===========================================================================
1148133211Sharti * Reverse the first len bits of a code, using straightforward code (a faster
1149133211Sharti * method would use a table)
1150133211Sharti * IN assertion: 1 <= len <= 15
1151133211Sharti */
1152133211Shartilocal unsigned bi_reverse(code, len)
1153122394Sharti    unsigned code; /* the value to invert */
1154159063Sharti    int len;       /* its bit length */
1155133211Sharti{
1156122394Sharti    register unsigned res = 0;
1157122394Sharti    do {
1158122394Sharti        res |= code & 1;
1159122394Sharti        code >>= 1, res <<= 1;
1160122394Sharti    } while (--len > 0);
1161122394Sharti    return res >> 1;
1162122394Sharti}
1163122394Sharti
1164122394Sharti/* ===========================================================================
1165133211Sharti * Flush the bit buffer, keeping at most 7 bits in it.
1166133211Sharti */
1167133211Shartilocal void bi_flush(s)
1168133211Sharti    deflate_state *s;
1169133211Sharti{
1170133211Sharti    if (s->bi_valid == 16) {
1171133211Sharti        put_short(s, s->bi_buf);
1172133211Sharti        s->bi_buf = 0;
1173122394Sharti        s->bi_valid = 0;
1174122394Sharti    } else if (s->bi_valid >= 8) {
1175133211Sharti        put_byte(s, (Byte)s->bi_buf);
1176133211Sharti        s->bi_buf >>= 8;
1177122394Sharti        s->bi_valid -= 8;
1178122394Sharti    }
1179122394Sharti}
1180122394Sharti
1181122394Sharti/* ===========================================================================
1182122394Sharti * Flush the bit buffer and align the output on a byte boundary
1183159063Sharti */
1184122394Shartilocal void bi_windup(s)
1185122394Sharti    deflate_state *s;
1186122394Sharti{
1187159063Sharti    if (s->bi_valid > 8) {
1188122394Sharti        put_short(s, s->bi_buf);
1189122394Sharti    } else if (s->bi_valid > 0) {
1190122394Sharti        put_byte(s, (Byte)s->bi_buf);
1191122394Sharti    }
1192122394Sharti    s->bi_buf = 0;
1193122394Sharti    s->bi_valid = 0;
1194122394Sharti#ifdef DEBUG
1195159063Sharti    s->bits_sent = (s->bits_sent+7) & ~7;
1196122394Sharti#endif
1197122394Sharti}
1198133211Sharti
1199133211Sharti/* ===========================================================================
1200133211Sharti * Copy a stored block, storing first the length and its
1201133211Sharti * one's complement if requested.
1202122394Sharti */
1203133211Shartilocal void copy_block(s, buf, len, header)
1204133211Sharti    deflate_state *s;
1205133211Sharti    charf    *buf;    /* the input data */
1206133211Sharti    unsigned len;     /* its length */
1207133211Sharti    int      header;  /* true if block header must be written */
1208133211Sharti{
1209133211Sharti    bi_windup(s);        /* align on byte boundary */
1210133211Sharti
1211133211Sharti    if (header) {
1212133211Sharti        put_short(s, (ush)len);
1213133211Sharti        put_short(s, (ush)~len);
1214133211Sharti#ifdef DEBUG
1215133211Sharti        s->bits_sent += 2*16;
1216133211Sharti#endif
1217133211Sharti    }
1218133211Sharti#ifdef DEBUG
1219133211Sharti    s->bits_sent += (ulg)len<<3;
1220133211Sharti#endif
1221133211Sharti    while (len--) {
1222133211Sharti        put_byte(s, *buf++);
1223133211Sharti    }
1224133211Sharti}
1225133211Sharti