1168404Spjd/* trees.c -- output deflated data using Huffman coding
2168404Spjd * Copyright (C) 1995-2005 Jean-loup Gailly
3168404Spjd * For conditions of distribution and use, see copyright notice in zlib.h
4168404Spjd */
5168404Spjd
6168404Spjd#pragma ident	"%Z%%M%	%I%	%E% SMI"
7168404Spjd
8168404Spjd/*
9168404Spjd *  ALGORITHM
10168404Spjd *
11168404Spjd *      The "deflation" process uses several Huffman trees. The more
12168404Spjd *      common source values are represented by shorter bit sequences.
13168404Spjd *
14168404Spjd *      Each code tree is stored in a compressed form which is itself
15168404Spjd * a Huffman encoding of the lengths of all the code strings (in
16168404Spjd * ascending order by source values).  The actual code strings are
17168404Spjd * reconstructed from the lengths in the inflate process, as described
18168404Spjd * in the deflate specification.
19168404Spjd *
20168404Spjd *  REFERENCES
21168404Spjd *
22168404Spjd *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
23168404Spjd *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
24168404Spjd *
25168404Spjd *      Storer, James A.
26168404Spjd *          Data Compression:  Methods and Theory, pp. 49-50.
27168404Spjd *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
28168404Spjd *
29168404Spjd *      Sedgewick, R.
30168404Spjd *          Algorithms, p290.
31168404Spjd *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
32168404Spjd */
33168404Spjd
34168404Spjd/* #define GEN_TREES_H */
35168404Spjd
36168404Spjd#include "deflate.h"
37168404Spjd
38168404Spjd#ifdef DEBUG
39168404Spjd#  include <ctype.h>
40168404Spjd#endif
41168404Spjd
42168404Spjd/* ===========================================================================
43168404Spjd * Constants
44168404Spjd */
45168404Spjd
46168404Spjd#define MAX_BL_BITS 7
47168404Spjd/* Bit length codes must not exceed MAX_BL_BITS bits */
48168404Spjd
49168404Spjd#define END_BLOCK 256
50168404Spjd/* end of block literal code */
51168404Spjd
52168404Spjd#define REP_3_6      16
53168404Spjd/* repeat previous bit length 3-6 times (2 bits of repeat count) */
54168404Spjd
55168404Spjd#define REPZ_3_10    17
56168404Spjd/* repeat a zero length 3-10 times  (3 bits of repeat count) */
57168404Spjd
58168404Spjd#define REPZ_11_138  18
59168404Spjd/* repeat a zero length 11-138 times  (7 bits of repeat count) */
60168404Spjd
61168404Spjdlocal const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
62168404Spjd   = {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};
63168404Spjd
64168404Spjdlocal const int extra_dbits[D_CODES] /* extra bits for each distance code */
65168404Spjd   = {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};
66168404Spjd
67168404Spjdlocal const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
68168404Spjd   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
69168404Spjd
70168404Spjdlocal const uch bl_order[BL_CODES]
71168404Spjd   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
72168404Spjd/* The lengths of the bit length codes are sent in order of decreasing
73168404Spjd * probability, to avoid transmitting the lengths for unused bit length codes.
74168404Spjd */
75168404Spjd
76168404Spjd#define Buf_size (8 * 2*sizeof(char))
77168404Spjd/* Number of bits used within bi_buf. (bi_buf might be implemented on
78168404Spjd * more than 16 bits on some systems.)
79168404Spjd */
80168404Spjd
81168404Spjd/* ===========================================================================
82168404Spjd * Local data. These are initialized only once.
83168404Spjd */
84168404Spjd
85168404Spjd#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
86168404Spjd
87168404Spjd#if defined(GEN_TREES_H) || !defined(STDC)
88168404Spjd/* non ANSI compilers may not accept trees.h */
89168404Spjd
90168404Spjdlocal ct_data static_ltree[L_CODES+2];
91168404Spjd/* The static literal tree. Since the bit lengths are imposed, there is no
92168404Spjd * need for the L_CODES extra codes used during heap construction. However
93168404Spjd * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
94168404Spjd * below).
95168404Spjd */
96168404Spjd
97168404Spjdlocal ct_data static_dtree[D_CODES];
98168404Spjd/* The static distance tree. (Actually a trivial tree since all codes use
99168404Spjd * 5 bits.)
100168404Spjd */
101168404Spjd
102168404Spjduch _dist_code[DIST_CODE_LEN];
103168404Spjd/* Distance codes. The first 256 values correspond to the distances
104168404Spjd * 3 .. 258, the last 256 values correspond to the top 8 bits of
105168404Spjd * the 15 bit distances.
106168404Spjd */
107168404Spjd
108168404Spjduch _length_code[MAX_MATCH-MIN_MATCH+1];
109168404Spjd/* length code for each normalized match length (0 == MIN_MATCH) */
110168404Spjd
111168404Spjdlocal int base_length[LENGTH_CODES];
112168404Spjd/* First normalized length for each code (0 = MIN_MATCH) */
113168404Spjd
114168404Spjdlocal int base_dist[D_CODES];
115168404Spjd/* First normalized distance for each code (0 = distance of 1) */
116168404Spjd
117168404Spjd#else
118168404Spjd#  include "trees.h"
119168404Spjd#endif /* GEN_TREES_H */
120168404Spjd
121168404Spjdstruct static_tree_desc_s {
122168404Spjd    const ct_data *static_tree;  /* static tree or NULL */
123168404Spjd    const intf *extra_bits;      /* extra bits for each code or NULL */
124168404Spjd    int     extra_base;          /* base index for extra_bits */
125168404Spjd    int     elems;               /* max number of elements in the tree */
126168404Spjd    int     max_length;          /* max bit length for the codes */
127168404Spjd};
128168404Spjd
129168404Spjdlocal static_tree_desc  static_l_desc =
130168404Spjd{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
131168404Spjd
132168404Spjdlocal static_tree_desc  static_d_desc =
133168404Spjd{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
134168404Spjd
135168404Spjdlocal static_tree_desc  static_bl_desc =
136168404Spjd{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
137168404Spjd
138168404Spjd/* ===========================================================================
139168404Spjd * Local (static) routines in this file.
140168404Spjd */
141168404Spjd
142168404Spjdlocal void tr_static_init OF((void));
143168404Spjdlocal void init_block     OF((deflate_state *s));
144168404Spjdlocal void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
145168404Spjdlocal void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
146168404Spjdlocal void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
147168404Spjdlocal void build_tree     OF((deflate_state *s, tree_desc *desc));
148168404Spjdlocal void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
149168404Spjdlocal void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
150168404Spjdlocal int  build_bl_tree  OF((deflate_state *s));
151168404Spjdlocal void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
152168404Spjd                              int blcodes));
153168404Spjdlocal void compress_block OF((deflate_state *s, ct_data *ltree,
154168404Spjd                              ct_data *dtree));
155168404Spjdlocal void set_data_type  OF((deflate_state *s));
156168404Spjdlocal unsigned bi_reverse OF((unsigned value, int length));
157168404Spjdlocal void bi_windup      OF((deflate_state *s));
158168404Spjdlocal void bi_flush       OF((deflate_state *s));
159168404Spjdlocal void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
160168404Spjd                              int header));
161168404Spjd
162168404Spjd#ifdef GEN_TREES_H
163168404Spjdlocal void gen_trees_header OF((void));
164168404Spjd#endif
165168404Spjd
166168404Spjd#ifndef DEBUG
167168404Spjd#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
168168404Spjd   /* Send a code of the given tree. c and tree must not have side effects */
169168404Spjd
170168404Spjd#else /* DEBUG */
171168404Spjd#  define send_code(s, c, tree) \
172168404Spjd     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
173168404Spjd       send_bits(s, tree[c].Code, tree[c].Len); }
174168404Spjd#endif
175168404Spjd
176168404Spjd/* ===========================================================================
177168404Spjd * Output a short LSB first on the stream.
178168404Spjd * IN assertion: there is enough room in pendingBuf.
179168404Spjd */
180168404Spjd#define put_short(s, w) { \
181168404Spjd    put_byte(s, (uch)((w) & 0xff)); \
182168404Spjd    put_byte(s, (uch)((ush)(w) >> 8)); \
183168404Spjd}
184168404Spjd
185168404Spjd/* ===========================================================================
186168404Spjd * Send a value on a given number of bits.
187168404Spjd * IN assertion: length <= 16 and value fits in length bits.
188168404Spjd */
189168404Spjd#ifdef DEBUG
190168404Spjdlocal void send_bits      OF((deflate_state *s, int value, int length));
191168404Spjd
192168404Spjdlocal void send_bits(s, value, length)
193168404Spjd    deflate_state *s;
194168404Spjd    int value;  /* value to send */
195168404Spjd    int length; /* number of bits */
196168404Spjd{
197168404Spjd    Tracevv((stderr," l %2d v %4x ", length, value));
198168404Spjd    Assert(length > 0 && length <= 15, "invalid length");
199168404Spjd    s->bits_sent += (ulg)length;
200168404Spjd
201168404Spjd    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
202168404Spjd     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
203168404Spjd     * unused bits in value.
204168404Spjd     */
205168404Spjd    if (s->bi_valid > (int)Buf_size - length) {
206168404Spjd        s->bi_buf |= (value << s->bi_valid);
207168404Spjd        put_short(s, s->bi_buf);
208168404Spjd        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
209168404Spjd        s->bi_valid += length - Buf_size;
210168404Spjd    } else {
211168404Spjd        s->bi_buf |= value << s->bi_valid;
212168404Spjd        s->bi_valid += length;
213168404Spjd    }
214168404Spjd}
215168404Spjd#else /* !DEBUG */
216168404Spjd
217168404Spjd#define send_bits(s, value, length) \
218168404Spjd{ int len = length;\
219168404Spjd  if (s->bi_valid > (int)Buf_size - len) {\
220168404Spjd    int val = value;\
221168404Spjd    s->bi_buf |= (val << s->bi_valid);\
222168404Spjd    put_short(s, s->bi_buf);\
223168404Spjd    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
224168404Spjd    s->bi_valid += len - Buf_size;\
225168404Spjd  } else {\
226168404Spjd    s->bi_buf |= (value) << s->bi_valid;\
227168404Spjd    s->bi_valid += len;\
228168404Spjd  }\
229168404Spjd}
230168404Spjd#endif /* DEBUG */
231168404Spjd
232168404Spjd
233168404Spjd/* the arguments must not have side effects */
234168404Spjd
235168404Spjd/* ===========================================================================
236168404Spjd * Initialize the various 'constant' tables.
237168404Spjd */
238168404Spjdlocal void tr_static_init()
239168404Spjd{
240168404Spjd#if defined(GEN_TREES_H) || !defined(STDC)
241168404Spjd    static int static_init_done = 0;
242168404Spjd    int n;        /* iterates over tree elements */
243168404Spjd    int bits;     /* bit counter */
244168404Spjd    int length;   /* length value */
245168404Spjd    int code;     /* code value */
246168404Spjd    int dist;     /* distance index */
247168404Spjd    ush bl_count[MAX_BITS+1];
248168404Spjd    /* number of codes at each bit length for an optimal tree */
249168404Spjd
250168404Spjd    if (static_init_done) return;
251168404Spjd
252168404Spjd    /* For some embedded targets, global variables are not initialized: */
253168404Spjd    static_l_desc.static_tree = static_ltree;
254168404Spjd    static_l_desc.extra_bits = extra_lbits;
255168404Spjd    static_d_desc.static_tree = static_dtree;
256168404Spjd    static_d_desc.extra_bits = extra_dbits;
257168404Spjd    static_bl_desc.extra_bits = extra_blbits;
258168404Spjd
259168404Spjd    /* Initialize the mapping length (0..255) -> length code (0..28) */
260168404Spjd    length = 0;
261168404Spjd    for (code = 0; code < LENGTH_CODES-1; code++) {
262168404Spjd        base_length[code] = length;
263168404Spjd        for (n = 0; n < (1<<extra_lbits[code]); n++) {
264168404Spjd            _length_code[length++] = (uch)code;
265168404Spjd        }
266168404Spjd    }
267168404Spjd    Assert (length == 256, "tr_static_init: length != 256");
268168404Spjd    /* Note that the length 255 (match length 258) can be represented
269168404Spjd     * in two different ways: code 284 + 5 bits or code 285, so we
270168404Spjd     * overwrite length_code[255] to use the best encoding:
271168404Spjd     */
272168404Spjd    _length_code[length-1] = (uch)code;
273168404Spjd
274168404Spjd    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
275168404Spjd    dist = 0;
276168404Spjd    for (code = 0 ; code < 16; code++) {
277168404Spjd        base_dist[code] = dist;
278168404Spjd        for (n = 0; n < (1<<extra_dbits[code]); n++) {
279168404Spjd            _dist_code[dist++] = (uch)code;
280168404Spjd        }
281168404Spjd    }
282168404Spjd    Assert (dist == 256, "tr_static_init: dist != 256");
283168404Spjd    dist >>= 7; /* from now on, all distances are divided by 128 */
284168404Spjd    for ( ; code < D_CODES; code++) {
285168404Spjd        base_dist[code] = dist << 7;
286168404Spjd        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
287168404Spjd            _dist_code[256 + dist++] = (uch)code;
288168404Spjd        }
289168404Spjd    }
290168404Spjd    Assert (dist == 256, "tr_static_init: 256+dist != 512");
291168404Spjd
292168404Spjd    /* Construct the codes of the static literal tree */
293168404Spjd    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
294168404Spjd    n = 0;
295168404Spjd    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
296168404Spjd    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
297168404Spjd    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
298168404Spjd    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
299168404Spjd    /* Codes 286 and 287 do not exist, but we must include them in the
300168404Spjd     * tree construction to get a canonical Huffman tree (longest code
301168404Spjd     * all ones)
302168404Spjd     */
303168404Spjd    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
304168404Spjd
305168404Spjd    /* The static distance tree is trivial: */
306168404Spjd    for (n = 0; n < D_CODES; n++) {
307168404Spjd        static_dtree[n].Len = 5;
308168404Spjd        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
309168404Spjd    }
310168404Spjd    static_init_done = 1;
311168404Spjd
312168404Spjd#  ifdef GEN_TREES_H
313168404Spjd    gen_trees_header();
314168404Spjd#  endif
315168404Spjd#endif /* defined(GEN_TREES_H) || !defined(STDC) */
316168404Spjd}
317168404Spjd
318168404Spjd/* ===========================================================================
319168404Spjd * Genererate the file trees.h describing the static trees.
320168404Spjd */
321168404Spjd#ifdef GEN_TREES_H
322168404Spjd#  ifndef DEBUG
323168404Spjd#    include <stdio.h>
324168404Spjd#  endif
325168404Spjd
326168404Spjd#  define SEPARATOR(i, last, width) \
327168404Spjd      ((i) == (last)? "\n};\n\n" :    \
328168404Spjd       ((i) % (width) == (width)-1 ? ",\n" : ", "))
329168404Spjd
330168404Spjdvoid gen_trees_header()
331168404Spjd{
332168404Spjd    FILE *header = fopen("trees.h", "w");
333168404Spjd    int i;
334168404Spjd
335168404Spjd    Assert (header != NULL, "Can't open trees.h");
336168404Spjd    fprintf(header,
337168404Spjd            "/* header created automatically with -DGEN_TREES_H */\n\n");
338168404Spjd
339168404Spjd    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
340168404Spjd    for (i = 0; i < L_CODES+2; i++) {
341168404Spjd        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
342168404Spjd                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
343168404Spjd    }
344168404Spjd
345168404Spjd    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
346168404Spjd    for (i = 0; i < D_CODES; i++) {
347168404Spjd        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
348168404Spjd                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
349168404Spjd    }
350168404Spjd
351168404Spjd    fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
352168404Spjd    for (i = 0; i < DIST_CODE_LEN; i++) {
353168404Spjd        fprintf(header, "%2u%s", _dist_code[i],
354168404Spjd                SEPARATOR(i, DIST_CODE_LEN-1, 20));
355168404Spjd    }
356168404Spjd
357168404Spjd    fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
358168404Spjd    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
359168404Spjd        fprintf(header, "%2u%s", _length_code[i],
360168404Spjd                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
361168404Spjd    }
362168404Spjd
363168404Spjd    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
364168404Spjd    for (i = 0; i < LENGTH_CODES; i++) {
365168404Spjd        fprintf(header, "%1u%s", base_length[i],
366168404Spjd                SEPARATOR(i, LENGTH_CODES-1, 20));
367168404Spjd    }
368168404Spjd
369168404Spjd    fprintf(header, "local const int base_dist[D_CODES] = {\n");
370168404Spjd    for (i = 0; i < D_CODES; i++) {
371168404Spjd        fprintf(header, "%5u%s", base_dist[i],
372168404Spjd                SEPARATOR(i, D_CODES-1, 10));
373168404Spjd    }
374168404Spjd
375168404Spjd    fclose(header);
376168404Spjd}
377168404Spjd#endif /* GEN_TREES_H */
378168404Spjd
379168404Spjd/* ===========================================================================
380168404Spjd * Initialize the tree data structures for a new zlib stream.
381168404Spjd */
382168404Spjdvoid _tr_init(s)
383168404Spjd    deflate_state *s;
384168404Spjd{
385168404Spjd    tr_static_init();
386168404Spjd
387168404Spjd    s->l_desc.dyn_tree = s->dyn_ltree;
388168404Spjd    s->l_desc.stat_desc = &static_l_desc;
389168404Spjd
390168404Spjd    s->d_desc.dyn_tree = s->dyn_dtree;
391168404Spjd    s->d_desc.stat_desc = &static_d_desc;
392168404Spjd
393168404Spjd    s->bl_desc.dyn_tree = s->bl_tree;
394168404Spjd    s->bl_desc.stat_desc = &static_bl_desc;
395168404Spjd
396168404Spjd    s->bi_buf = 0;
397168404Spjd    s->bi_valid = 0;
398168404Spjd    s->last_eob_len = 8; /* enough lookahead for inflate */
399168404Spjd#ifdef DEBUG
400168404Spjd    s->compressed_len = 0L;
401168404Spjd    s->bits_sent = 0L;
402168404Spjd#endif
403168404Spjd
404168404Spjd    /* Initialize the first block of the first file: */
405168404Spjd    init_block(s);
406168404Spjd}
407168404Spjd
408168404Spjd/* ===========================================================================
409168404Spjd * Initialize a new block.
410168404Spjd */
411168404Spjdlocal void init_block(s)
412168404Spjd    deflate_state *s;
413168404Spjd{
414168404Spjd    int n; /* iterates over tree elements */
415168404Spjd
416168404Spjd    /* Initialize the trees. */
417168404Spjd    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
418168404Spjd    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
419168404Spjd    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
420168404Spjd
421168404Spjd    s->dyn_ltree[END_BLOCK].Freq = 1;
422168404Spjd    s->opt_len = s->static_len = 0L;
423168404Spjd    s->last_lit = s->matches = 0;
424168404Spjd}
425168404Spjd
426168404Spjd#define SMALLEST 1
427168404Spjd/* Index within the heap array of least frequent node in the Huffman tree */
428168404Spjd
429168404Spjd
430168404Spjd/* ===========================================================================
431168404Spjd * Remove the smallest element from the heap and recreate the heap with
432168404Spjd * one less element. Updates heap and heap_len.
433168404Spjd */
434168404Spjd#define pqremove(s, tree, top) \
435168404Spjd{\
436168404Spjd    top = s->heap[SMALLEST]; \
437168404Spjd    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
438168404Spjd    pqdownheap(s, tree, SMALLEST); \
439168404Spjd}
440168404Spjd
441168404Spjd/* ===========================================================================
442168404Spjd * Compares to subtrees, using the tree depth as tie breaker when
443168404Spjd * the subtrees have equal frequency. This minimizes the worst case length.
444168404Spjd */
445168404Spjd#define smaller(tree, n, m, depth) \
446168404Spjd   (tree[n].Freq < tree[m].Freq || \
447168404Spjd   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
448168404Spjd
449168404Spjd/* ===========================================================================
450168404Spjd * Restore the heap property by moving down the tree starting at node k,
451168404Spjd * exchanging a node with the smallest of its two sons if necessary, stopping
452168404Spjd * when the heap property is re-established (each father smaller than its
453168404Spjd * two sons).
454168404Spjd */
455168404Spjdlocal void pqdownheap(s, tree, k)
456168404Spjd    deflate_state *s;
457168404Spjd    ct_data *tree;  /* the tree to restore */
458168404Spjd    int k;               /* node to move down */
459168404Spjd{
460168404Spjd    int v = s->heap[k];
461168404Spjd    int j = k << 1;  /* left son of k */
462168404Spjd    while (j <= s->heap_len) {
463168404Spjd        /* Set j to the smallest of the two sons: */
464168404Spjd        if (j < s->heap_len &&
465168404Spjd            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
466168404Spjd            j++;
467168404Spjd        }
468168404Spjd        /* Exit if v is smaller than both sons */
469168404Spjd        if (smaller(tree, v, s->heap[j], s->depth)) break;
470168404Spjd
471168404Spjd        /* Exchange v with the smallest son */
472168404Spjd        s->heap[k] = s->heap[j];  k = j;
473168404Spjd
474168404Spjd        /* And continue down the tree, setting j to the left son of k */
475168404Spjd        j <<= 1;
476168404Spjd    }
477168404Spjd    s->heap[k] = v;
478168404Spjd}
479168404Spjd
480168404Spjd/* ===========================================================================
481168404Spjd * Compute the optimal bit lengths for a tree and update the total bit length
482168404Spjd * for the current block.
483168404Spjd * IN assertion: the fields freq and dad are set, heap[heap_max] and
484168404Spjd *    above are the tree nodes sorted by increasing frequency.
485168404Spjd * OUT assertions: the field len is set to the optimal bit length, the
486168404Spjd *     array bl_count contains the frequencies for each bit length.
487168404Spjd *     The length opt_len is updated; static_len is also updated if stree is
488168404Spjd *     not null.
489168404Spjd */
490168404Spjdlocal void gen_bitlen(s, desc)
491168404Spjd    deflate_state *s;
492168404Spjd    tree_desc *desc;    /* the tree descriptor */
493168404Spjd{
494168404Spjd    ct_data *tree        = desc->dyn_tree;
495168404Spjd    int max_code         = desc->max_code;
496168404Spjd    const ct_data *stree = desc->stat_desc->static_tree;
497168404Spjd    const intf *extra    = desc->stat_desc->extra_bits;
498168404Spjd    int base             = desc->stat_desc->extra_base;
499168404Spjd    int max_length       = desc->stat_desc->max_length;
500168404Spjd    int h;              /* heap index */
501168404Spjd    int n, m;           /* iterate over the tree elements */
502168404Spjd    int bits;           /* bit length */
503168404Spjd    int xbits;          /* extra bits */
504168404Spjd    ush f;              /* frequency */
505168404Spjd    int overflow = 0;   /* number of elements with bit length too large */
506168404Spjd
507168404Spjd    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
508168404Spjd
509168404Spjd    /* In a first pass, compute the optimal bit lengths (which may
510168404Spjd     * overflow in the case of the bit length tree).
511168404Spjd     */
512168404Spjd    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
513168404Spjd
514168404Spjd    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
515168404Spjd        n = s->heap[h];
516168404Spjd        bits = tree[tree[n].Dad].Len + 1;
517168404Spjd        if (bits > max_length) bits = max_length, overflow++;
518168404Spjd        tree[n].Len = (ush)bits;
519168404Spjd        /* We overwrite tree[n].Dad which is no longer needed */
520168404Spjd
521168404Spjd        if (n > max_code) continue; /* not a leaf node */
522168404Spjd
523168404Spjd        s->bl_count[bits]++;
524168404Spjd        xbits = 0;
525168404Spjd        if (n >= base) xbits = extra[n-base];
526168404Spjd        f = tree[n].Freq;
527168404Spjd        s->opt_len += (ulg)f * (bits + xbits);
528168404Spjd        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
529168404Spjd    }
530168404Spjd    if (overflow == 0) return;
531168404Spjd
532168404Spjd    Trace((stderr,"\nbit length overflow\n"));
533168404Spjd    /* This happens for example on obj2 and pic of the Calgary corpus */
534168404Spjd
535168404Spjd    /* Find the first bit length which could increase: */
536168404Spjd    do {
537168404Spjd        bits = max_length-1;
538168404Spjd        while (s->bl_count[bits] == 0) bits--;
539168404Spjd        s->bl_count[bits]--;      /* move one leaf down the tree */
540168404Spjd        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
541168404Spjd        s->bl_count[max_length]--;
542168404Spjd        /* The brother of the overflow item also moves one step up,
543168404Spjd         * but this does not affect bl_count[max_length]
544168404Spjd         */
545168404Spjd        overflow -= 2;
546168404Spjd    } while (overflow > 0);
547168404Spjd
548168404Spjd    /* Now recompute all bit lengths, scanning in increasing frequency.
549168404Spjd     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
550168404Spjd     * lengths instead of fixing only the wrong ones. This idea is taken
551168404Spjd     * from 'ar' written by Haruhiko Okumura.)
552168404Spjd     */
553168404Spjd    for (bits = max_length; bits != 0; bits--) {
554168404Spjd        n = s->bl_count[bits];
555168404Spjd        while (n != 0) {
556168404Spjd            m = s->heap[--h];
557168404Spjd            if (m > max_code) continue;
558168404Spjd            if ((unsigned) tree[m].Len != (unsigned) bits) {
559168404Spjd                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
560168404Spjd                s->opt_len += ((long)bits - (long)tree[m].Len)
561168404Spjd                              *(long)tree[m].Freq;
562168404Spjd                tree[m].Len = (ush)bits;
563168404Spjd            }
564168404Spjd            n--;
565168404Spjd        }
566168404Spjd    }
567168404Spjd}
568168404Spjd
569168404Spjd/* ===========================================================================
570168404Spjd * Generate the codes for a given tree and bit counts (which need not be
571168404Spjd * optimal).
572168404Spjd * IN assertion: the array bl_count contains the bit length statistics for
573168404Spjd * the given tree and the field len is set for all tree elements.
574168404Spjd * OUT assertion: the field code is set for all tree elements of non
575168404Spjd *     zero code length.
576168404Spjd */
577168404Spjdlocal void gen_codes (tree, max_code, bl_count)
578168404Spjd    ct_data *tree;             /* the tree to decorate */
579168404Spjd    int max_code;              /* largest code with non zero frequency */
580168404Spjd    ushf *bl_count;            /* number of codes at each bit length */
581168404Spjd{
582168404Spjd    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
583168404Spjd    ush code = 0;              /* running code value */
584168404Spjd    int bits;                  /* bit index */
585168404Spjd    int n;                     /* code index */
586168404Spjd
587168404Spjd    /* The distribution counts are first used to generate the code values
588168404Spjd     * without bit reversal.
589168404Spjd     */
590168404Spjd    for (bits = 1; bits <= MAX_BITS; bits++) {
591168404Spjd        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
592168404Spjd    }
593168404Spjd    /* Check that the bit counts in bl_count are consistent. The last code
594168404Spjd     * must be all ones.
595168404Spjd     */
596168404Spjd    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
597168404Spjd            "inconsistent bit counts");
598168404Spjd    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
599168404Spjd
600168404Spjd    for (n = 0;  n <= max_code; n++) {
601168404Spjd        int len = tree[n].Len;
602168404Spjd        if (len == 0) continue;
603168404Spjd        /* Now reverse the bits */
604168404Spjd        tree[n].Code = bi_reverse(next_code[len]++, len);
605168404Spjd
606168404Spjd        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
607168404Spjd             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
608168404Spjd    }
609168404Spjd}
610168404Spjd
611168404Spjd/* ===========================================================================
612168404Spjd * Construct one Huffman tree and assigns the code bit strings and lengths.
613168404Spjd * Update the total bit length for the current block.
614168404Spjd * IN assertion: the field freq is set for all tree elements.
615168404Spjd * OUT assertions: the fields len and code are set to the optimal bit length
616168404Spjd *     and corresponding code. The length opt_len is updated; static_len is
617168404Spjd *     also updated if stree is not null. The field max_code is set.
618168404Spjd */
619168404Spjdlocal void build_tree(s, desc)
620168404Spjd    deflate_state *s;
621168404Spjd    tree_desc *desc; /* the tree descriptor */
622168404Spjd{
623168404Spjd    ct_data *tree         = desc->dyn_tree;
624168404Spjd    const ct_data *stree  = desc->stat_desc->static_tree;
625168404Spjd    int elems             = desc->stat_desc->elems;
626168404Spjd    int n, m;          /* iterate over heap elements */
627168404Spjd    int max_code = -1; /* largest code with non zero frequency */
628168404Spjd    int node;          /* new node being created */
629168404Spjd
630168404Spjd    /* Construct the initial heap, with least frequent element in
631168404Spjd     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
632168404Spjd     * heap[0] is not used.
633168404Spjd     */
634168404Spjd    s->heap_len = 0, s->heap_max = HEAP_SIZE;
635168404Spjd
636168404Spjd    for (n = 0; n < elems; n++) {
637168404Spjd        if (tree[n].Freq != 0) {
638168404Spjd            s->heap[++(s->heap_len)] = max_code = n;
639168404Spjd            s->depth[n] = 0;
640168404Spjd        } else {
641168404Spjd            tree[n].Len = 0;
642168404Spjd        }
643168404Spjd    }
644168404Spjd
645168404Spjd    /* The pkzip format requires that at least one distance code exists,
646168404Spjd     * and that at least one bit should be sent even if there is only one
647168404Spjd     * possible code. So to avoid special checks later on we force at least
648168404Spjd     * two codes of non zero frequency.
649168404Spjd     */
650168404Spjd    while (s->heap_len < 2) {
651168404Spjd        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
652168404Spjd        tree[node].Freq = 1;
653168404Spjd        s->depth[node] = 0;
654168404Spjd        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
655168404Spjd        /* node is 0 or 1 so it does not have extra bits */
656168404Spjd    }
657168404Spjd    desc->max_code = max_code;
658168404Spjd
659168404Spjd    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
660168404Spjd     * establish sub-heaps of increasing lengths:
661168404Spjd     */
662168404Spjd    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
663168404Spjd
664168404Spjd    /* Construct the Huffman tree by repeatedly combining the least two
665168404Spjd     * frequent nodes.
666168404Spjd     */
667168404Spjd    node = elems;              /* next internal node of the tree */
668168404Spjd    do {
669168404Spjd        pqremove(s, tree, n);  /* n = node of least frequency */
670168404Spjd        m = s->heap[SMALLEST]; /* m = node of next least frequency */
671168404Spjd
672168404Spjd        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
673168404Spjd        s->heap[--(s->heap_max)] = m;
674168404Spjd
675168404Spjd        /* Create a new node father of n and m */
676168404Spjd        tree[node].Freq = tree[n].Freq + tree[m].Freq;
677168404Spjd        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
678168404Spjd                                s->depth[n] : s->depth[m]) + 1);
679168404Spjd        tree[n].Dad = tree[m].Dad = (ush)node;
680168404Spjd#ifdef DUMP_BL_TREE
681168404Spjd        if (tree == s->bl_tree) {
682168404Spjd            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
683168404Spjd                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
684168404Spjd        }
685168404Spjd#endif
686168404Spjd        /* and insert the new node in the heap */
687168404Spjd        s->heap[SMALLEST] = node++;
688168404Spjd        pqdownheap(s, tree, SMALLEST);
689168404Spjd
690168404Spjd    } while (s->heap_len >= 2);
691168404Spjd
692168404Spjd    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
693168404Spjd
694168404Spjd    /* At this point, the fields freq and dad are set. We can now
695168404Spjd     * generate the bit lengths.
696168404Spjd     */
697168404Spjd    gen_bitlen(s, (tree_desc *)desc);
698168404Spjd
699168404Spjd    /* The field len is now set, we can generate the bit codes */
700168404Spjd    gen_codes ((ct_data *)tree, max_code, s->bl_count);
701168404Spjd}
702168404Spjd
703168404Spjd/* ===========================================================================
704168404Spjd * Scan a literal or distance tree to determine the frequencies of the codes
705168404Spjd * in the bit length tree.
706168404Spjd */
707168404Spjdlocal void scan_tree (s, tree, max_code)
708168404Spjd    deflate_state *s;
709168404Spjd    ct_data *tree;   /* the tree to be scanned */
710168404Spjd    int max_code;    /* and its largest code of non zero frequency */
711168404Spjd{
712168404Spjd    int n;                     /* iterates over all tree elements */
713168404Spjd    int prevlen = -1;          /* last emitted length */
714168404Spjd    int curlen;                /* length of current code */
715168404Spjd    int nextlen = tree[0].Len; /* length of next code */
716168404Spjd    int count = 0;             /* repeat count of the current code */
717168404Spjd    int max_count = 7;         /* max repeat count */
718168404Spjd    int min_count = 4;         /* min repeat count */
719168404Spjd
720168404Spjd    if (nextlen == 0) max_count = 138, min_count = 3;
721168404Spjd    tree[max_code+1].Len = (ush)0xffff; /* guard */
722168404Spjd
723168404Spjd    for (n = 0; n <= max_code; n++) {
724168404Spjd        curlen = nextlen; nextlen = tree[n+1].Len;
725168404Spjd        if (++count < max_count && curlen == nextlen) {
726168404Spjd            continue;
727168404Spjd        } else if (count < min_count) {
728168404Spjd            s->bl_tree[curlen].Freq += count;
729168404Spjd        } else if (curlen != 0) {
730168404Spjd            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
731168404Spjd            s->bl_tree[REP_3_6].Freq++;
732168404Spjd        } else if (count <= 10) {
733168404Spjd            s->bl_tree[REPZ_3_10].Freq++;
734168404Spjd        } else {
735168404Spjd            s->bl_tree[REPZ_11_138].Freq++;
736168404Spjd        }
737168404Spjd        count = 0; prevlen = curlen;
738168404Spjd        if (nextlen == 0) {
739168404Spjd            max_count = 138, min_count = 3;
740168404Spjd        } else if (curlen == nextlen) {
741168404Spjd            max_count = 6, min_count = 3;
742168404Spjd        } else {
743168404Spjd            max_count = 7, min_count = 4;
744168404Spjd        }
745168404Spjd    }
746168404Spjd}
747168404Spjd
748168404Spjd/* ===========================================================================
749168404Spjd * Send a literal or distance tree in compressed form, using the codes in
750168404Spjd * bl_tree.
751168404Spjd */
752168404Spjdlocal void send_tree (s, tree, max_code)
753168404Spjd    deflate_state *s;
754168404Spjd    ct_data *tree; /* the tree to be scanned */
755168404Spjd    int max_code;       /* and its largest code of non zero frequency */
756168404Spjd{
757168404Spjd    int n;                     /* iterates over all tree elements */
758168404Spjd    int prevlen = -1;          /* last emitted length */
759168404Spjd    int curlen;                /* length of current code */
760168404Spjd    int nextlen = tree[0].Len; /* length of next code */
761168404Spjd    int count = 0;             /* repeat count of the current code */
762168404Spjd    int max_count = 7;         /* max repeat count */
763168404Spjd    int min_count = 4;         /* min repeat count */
764168404Spjd
765168404Spjd    /* tree[max_code+1].Len = -1; */  /* guard already set */
766168404Spjd    if (nextlen == 0) max_count = 138, min_count = 3;
767168404Spjd
768168404Spjd    for (n = 0; n <= max_code; n++) {
769168404Spjd        curlen = nextlen; nextlen = tree[n+1].Len;
770168404Spjd        if (++count < max_count && curlen == nextlen) {
771168404Spjd            continue;
772168404Spjd        } else if (count < min_count) {
773168404Spjd            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
774168404Spjd
775168404Spjd        } else if (curlen != 0) {
776168404Spjd            if (curlen != prevlen) {
777168404Spjd                send_code(s, curlen, s->bl_tree); count--;
778168404Spjd            }
779168404Spjd            Assert(count >= 3 && count <= 6, " 3_6?");
780168404Spjd            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
781168404Spjd
782168404Spjd        } else if (count <= 10) {
783168404Spjd            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
784168404Spjd
785168404Spjd        } else {
786168404Spjd            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
787168404Spjd        }
788168404Spjd        count = 0; prevlen = curlen;
789168404Spjd        if (nextlen == 0) {
790168404Spjd            max_count = 138, min_count = 3;
791168404Spjd        } else if (curlen == nextlen) {
792168404Spjd            max_count = 6, min_count = 3;
793168404Spjd        } else {
794168404Spjd            max_count = 7, min_count = 4;
795168404Spjd        }
796168404Spjd    }
797168404Spjd}
798168404Spjd
799168404Spjd/* ===========================================================================
800168404Spjd * Construct the Huffman tree for the bit lengths and return the index in
801168404Spjd * bl_order of the last bit length code to send.
802168404Spjd */
803168404Spjdlocal int build_bl_tree(s)
804168404Spjd    deflate_state *s;
805168404Spjd{
806168404Spjd    int max_blindex;  /* index of last bit length code of non zero freq */
807168404Spjd
808168404Spjd    /* Determine the bit length frequencies for literal and distance trees */
809168404Spjd    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
810168404Spjd    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
811168404Spjd
812168404Spjd    /* Build the bit length tree: */
813168404Spjd    build_tree(s, (tree_desc *)(&(s->bl_desc)));
814168404Spjd    /* opt_len now includes the length of the tree representations, except
815168404Spjd     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
816168404Spjd     */
817168404Spjd
818168404Spjd    /* Determine the number of bit length codes to send. The pkzip format
819168404Spjd     * requires that at least 4 bit length codes be sent. (appnote.txt says
820168404Spjd     * 3 but the actual value used is 4.)
821168404Spjd     */
822168404Spjd    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
823168404Spjd        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
824168404Spjd    }
825168404Spjd    /* Update opt_len to include the bit length tree and counts */
826168404Spjd    s->opt_len += 3*(max_blindex+1) + 5+5+4;
827168404Spjd    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
828168404Spjd            s->opt_len, s->static_len));
829168404Spjd
830168404Spjd    return max_blindex;
831168404Spjd}
832168404Spjd
833168404Spjd/* ===========================================================================
834168404Spjd * Send the header for a block using dynamic Huffman trees: the counts, the
835168404Spjd * lengths of the bit length codes, the literal tree and the distance tree.
836168404Spjd * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
837168404Spjd */
838168404Spjdlocal void send_all_trees(s, lcodes, dcodes, blcodes)
839168404Spjd    deflate_state *s;
840168404Spjd    int lcodes, dcodes, blcodes; /* number of codes for each tree */
841168404Spjd{
842168404Spjd    int rank;                    /* index in bl_order */
843168404Spjd
844168404Spjd    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
845168404Spjd    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
846168404Spjd            "too many codes");
847168404Spjd    Tracev((stderr, "\nbl counts: "));
848168404Spjd    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
849168404Spjd    send_bits(s, dcodes-1,   5);
850168404Spjd    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
851168404Spjd    for (rank = 0; rank < blcodes; rank++) {
852168404Spjd        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
853168404Spjd        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
854168404Spjd    }
855168404Spjd    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
856168404Spjd
857168404Spjd    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
858168404Spjd    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
859168404Spjd
860168404Spjd    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
861168404Spjd    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
862168404Spjd}
863168404Spjd
864168404Spjd/* ===========================================================================
865168404Spjd * Send a stored block
866168404Spjd */
867168404Spjdvoid _tr_stored_block(s, buf, stored_len, eof)
868168404Spjd    deflate_state *s;
869168404Spjd    charf *buf;       /* input block */
870168404Spjd    ulg stored_len;   /* length of input block */
871168404Spjd    int eof;          /* true if this is the last block for a file */
872168404Spjd{
873168404Spjd    send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
874168404Spjd#ifdef DEBUG
875168404Spjd    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
876168404Spjd    s->compressed_len += (stored_len + 4) << 3;
877168404Spjd#endif
878168404Spjd    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
879168404Spjd}
880168404Spjd
881168404Spjd/* ===========================================================================
882168404Spjd * Send one empty static block to give enough lookahead for inflate.
883168404Spjd * This takes 10 bits, of which 7 may remain in the bit buffer.
884168404Spjd * The current inflate code requires 9 bits of lookahead. If the
885168404Spjd * last two codes for the previous block (real code plus EOB) were coded
886168404Spjd * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
887168404Spjd * the last real code. In this case we send two empty static blocks instead
888168404Spjd * of one. (There are no problems if the previous block is stored or fixed.)
889168404Spjd * To simplify the code, we assume the worst case of last real code encoded
890168404Spjd * on one bit only.
891168404Spjd */
892168404Spjdvoid _tr_align(s)
893168404Spjd    deflate_state *s;
894168404Spjd{
895168404Spjd    send_bits(s, STATIC_TREES<<1, 3);
896168404Spjd    send_code(s, END_BLOCK, static_ltree);
897168404Spjd#ifdef DEBUG
898168404Spjd    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
899168404Spjd#endif
900168404Spjd    bi_flush(s);
901168404Spjd    /* Of the 10 bits for the empty block, we have already sent
902168404Spjd     * (10 - bi_valid) bits. The lookahead for the last real code (before
903168404Spjd     * the EOB of the previous block) was thus at least one plus the length
904168404Spjd     * of the EOB plus what we have just sent of the empty static block.
905168404Spjd     */
906168404Spjd    if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
907168404Spjd        send_bits(s, STATIC_TREES<<1, 3);
908168404Spjd        send_code(s, END_BLOCK, static_ltree);
909168404Spjd#ifdef DEBUG
910168404Spjd        s->compressed_len += 10L;
911168404Spjd#endif
912168404Spjd        bi_flush(s);
913168404Spjd    }
914168404Spjd    s->last_eob_len = 7;
915168404Spjd}
916168404Spjd
917168404Spjd/* ===========================================================================
918168404Spjd * Determine the best encoding for the current block: dynamic trees, static
919168404Spjd * trees or store, and output the encoded block to the zip file.
920168404Spjd */
921168404Spjdvoid _tr_flush_block(s, buf, stored_len, eof)
922168404Spjd    deflate_state *s;
923168404Spjd    charf *buf;       /* input block, or NULL if too old */
924168404Spjd    ulg stored_len;   /* length of input block */
925168404Spjd    int eof;          /* true if this is the last block for a file */
926168404Spjd{
927168404Spjd    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
928168404Spjd    int max_blindex = 0;  /* index of last bit length code of non zero freq */
929168404Spjd
930168404Spjd    /* Build the Huffman trees unless a stored block is forced */
931168404Spjd    if (s->level > 0) {
932168404Spjd
933168404Spjd        /* Check if the file is binary or text */
934168404Spjd        if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
935168404Spjd            set_data_type(s);
936168404Spjd
937168404Spjd        /* Construct the literal and distance trees */
938168404Spjd        build_tree(s, (tree_desc *)(&(s->l_desc)));
939168404Spjd        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
940168404Spjd                s->static_len));
941168404Spjd
942168404Spjd        build_tree(s, (tree_desc *)(&(s->d_desc)));
943168404Spjd        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
944168404Spjd                s->static_len));
945168404Spjd        /* At this point, opt_len and static_len are the total bit lengths of
946168404Spjd         * the compressed block data, excluding the tree representations.
947168404Spjd         */
948168404Spjd
949168404Spjd        /* Build the bit length tree for the above two trees, and get the index
950168404Spjd         * in bl_order of the last bit length code to send.
951168404Spjd         */
952168404Spjd        max_blindex = build_bl_tree(s);
953168404Spjd
954168404Spjd        /* Determine the best encoding. Compute the block lengths in bytes. */
955168404Spjd        opt_lenb = (s->opt_len+3+7)>>3;
956168404Spjd        static_lenb = (s->static_len+3+7)>>3;
957168404Spjd
958168404Spjd        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
959168404Spjd                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
960168404Spjd                s->last_lit));
961168404Spjd
962168404Spjd        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
963168404Spjd
964168404Spjd    } else {
965168404Spjd        Assert(buf != (char*)0, "lost buf");
966168404Spjd        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
967168404Spjd    }
968168404Spjd
969168404Spjd#ifdef FORCE_STORED
970168404Spjd    if (buf != (char*)0) { /* force stored block */
971168404Spjd#else
972168404Spjd    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
973168404Spjd                       /* 4: two words for the lengths */
974168404Spjd#endif
975168404Spjd        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
976168404Spjd         * Otherwise we can't have processed more than WSIZE input bytes since
977168404Spjd         * the last block flush, because compression would have been
978168404Spjd         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
979168404Spjd         * transform a block into a stored block.
980168404Spjd         */
981168404Spjd        _tr_stored_block(s, buf, stored_len, eof);
982168404Spjd
983168404Spjd#ifdef FORCE_STATIC
984168404Spjd    } else if (static_lenb >= 0) { /* force static trees */
985168404Spjd#else
986168404Spjd    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
987168404Spjd#endif
988168404Spjd        send_bits(s, (STATIC_TREES<<1)+eof, 3);
989168404Spjd        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
990168404Spjd#ifdef DEBUG
991168404Spjd        s->compressed_len += 3 + s->static_len;
992168404Spjd#endif
993168404Spjd    } else {
994168404Spjd        send_bits(s, (DYN_TREES<<1)+eof, 3);
995168404Spjd        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
996168404Spjd                       max_blindex+1);
997168404Spjd        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
998168404Spjd#ifdef DEBUG
999168404Spjd        s->compressed_len += 3 + s->opt_len;
1000168404Spjd#endif
1001168404Spjd    }
1002168404Spjd    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1003168404Spjd    /* The above check is made mod 2^32, for files larger than 512 MB
1004168404Spjd     * and uLong implemented on 32 bits.
1005168404Spjd     */
1006168404Spjd    init_block(s);
1007168404Spjd
1008168404Spjd    if (eof) {
1009168404Spjd        bi_windup(s);
1010168404Spjd#ifdef DEBUG
1011168404Spjd        s->compressed_len += 7;  /* align on byte boundary */
1012168404Spjd#endif
1013168404Spjd    }
1014168404Spjd    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1015168404Spjd           s->compressed_len-7*eof));
1016168404Spjd}
1017168404Spjd
1018168404Spjd/* ===========================================================================
1019168404Spjd * Save the match info and tally the frequency counts. Return true if
1020168404Spjd * the current block must be flushed.
1021168404Spjd */
1022168404Spjdint _tr_tally (s, dist, lc)
1023168404Spjd    deflate_state *s;
1024168404Spjd    unsigned dist;  /* distance of matched string */
1025168404Spjd    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
1026168404Spjd{
1027168404Spjd    s->d_buf[s->last_lit] = (ush)dist;
1028168404Spjd    s->l_buf[s->last_lit++] = (uch)lc;
1029168404Spjd    if (dist == 0) {
1030168404Spjd        /* lc is the unmatched char */
1031168404Spjd        s->dyn_ltree[lc].Freq++;
1032168404Spjd    } else {
1033168404Spjd        s->matches++;
1034168404Spjd        /* Here, lc is the match length - MIN_MATCH */
1035168404Spjd        dist--;             /* dist = match distance - 1 */
1036168404Spjd        Assert((ush)dist < (ush)MAX_DIST(s) &&
1037168404Spjd               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1038168404Spjd               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1039168404Spjd
1040168404Spjd        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1041168404Spjd        s->dyn_dtree[d_code(dist)].Freq++;
1042168404Spjd    }
1043168404Spjd
1044168404Spjd#ifdef TRUNCATE_BLOCK
1045168404Spjd    /* Try to guess if it is profitable to stop the current block here */
1046168404Spjd    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
1047168404Spjd        /* Compute an upper bound for the compressed length */
1048168404Spjd        ulg out_length = (ulg)s->last_lit*8L;
1049168404Spjd        ulg in_length = (ulg)((long)s->strstart - s->block_start);
1050168404Spjd        int dcode;
1051168404Spjd        for (dcode = 0; dcode < D_CODES; dcode++) {
1052168404Spjd            out_length += (ulg)s->dyn_dtree[dcode].Freq *
1053168404Spjd                (5L+extra_dbits[dcode]);
1054168404Spjd        }
1055168404Spjd        out_length >>= 3;
1056168404Spjd        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
1057168404Spjd               s->last_lit, in_length, out_length,
1058168404Spjd               100L - out_length*100L/in_length));
1059168404Spjd        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
1060168404Spjd    }
1061168404Spjd#endif
1062168404Spjd    return (s->last_lit == s->lit_bufsize-1);
1063168404Spjd    /* We avoid equality with lit_bufsize because of wraparound at 64K
1064168404Spjd     * on 16 bit machines and because stored blocks are restricted to
1065168404Spjd     * 64K-1 bytes.
1066168404Spjd     */
1067168404Spjd}
1068168404Spjd
1069168404Spjd/* ===========================================================================
1070168404Spjd * Send the block data compressed using the given Huffman trees
1071168404Spjd */
1072168404Spjdlocal void compress_block(s, ltree, dtree)
1073168404Spjd    deflate_state *s;
1074168404Spjd    ct_data *ltree; /* literal tree */
1075168404Spjd    ct_data *dtree; /* distance tree */
1076168404Spjd{
1077168404Spjd    unsigned dist;      /* distance of matched string */
1078168404Spjd    int lc;             /* match length or unmatched char (if dist == 0) */
1079168404Spjd    unsigned lx = 0;    /* running index in l_buf */
1080168404Spjd    unsigned code;      /* the code to send */
1081168404Spjd    int extra;          /* number of extra bits to send */
1082168404Spjd
1083168404Spjd    if (s->last_lit != 0) do {
1084168404Spjd        dist = s->d_buf[lx];
1085168404Spjd        lc = s->l_buf[lx++];
1086168404Spjd        if (dist == 0) {
1087168404Spjd            send_code(s, lc, ltree); /* send a literal byte */
1088168404Spjd            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1089168404Spjd        } else {
1090168404Spjd            /* Here, lc is the match length - MIN_MATCH */
1091168404Spjd            code = _length_code[lc];
1092168404Spjd            send_code(s, code+LITERALS+1, ltree); /* send the length code */
1093168404Spjd            extra = extra_lbits[code];
1094168404Spjd            if (extra != 0) {
1095168404Spjd                lc -= base_length[code];
1096168404Spjd                send_bits(s, lc, extra);       /* send the extra length bits */
1097168404Spjd            }
1098168404Spjd            dist--; /* dist is now the match distance - 1 */
1099168404Spjd            code = d_code(dist);
1100168404Spjd            Assert (code < D_CODES, "bad d_code");
1101168404Spjd
1102168404Spjd            send_code(s, code, dtree);       /* send the distance code */
1103168404Spjd            extra = extra_dbits[code];
1104168404Spjd            if (extra != 0) {
1105168404Spjd                dist -= base_dist[code];
1106168404Spjd                send_bits(s, dist, extra);   /* send the extra distance bits */
1107168404Spjd            }
1108168404Spjd        } /* literal or match pair ? */
1109168404Spjd
1110168404Spjd        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1111168404Spjd        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
1112168404Spjd               "pendingBuf overflow");
1113168404Spjd
1114168404Spjd    } while (lx < s->last_lit);
1115168404Spjd
1116168404Spjd    send_code(s, END_BLOCK, ltree);
1117168404Spjd    s->last_eob_len = ltree[END_BLOCK].Len;
1118168404Spjd}
1119168404Spjd
1120168404Spjd/* ===========================================================================
1121168404Spjd * Set the data type to BINARY or TEXT, using a crude approximation:
1122168404Spjd * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
1123168404Spjd * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
1124168404Spjd * IN assertion: the fields Freq of dyn_ltree are set.
1125168404Spjd */
1126168404Spjdlocal void set_data_type(s)
1127168404Spjd    deflate_state *s;
1128168404Spjd{
1129168404Spjd    int n;
1130168404Spjd
1131168404Spjd    for (n = 0; n < 9; n++)
1132168404Spjd        if (s->dyn_ltree[n].Freq != 0)
1133168404Spjd            break;
1134168404Spjd    if (n == 9)
1135168404Spjd        for (n = 14; n < 32; n++)
1136168404Spjd            if (s->dyn_ltree[n].Freq != 0)
1137168404Spjd                break;
1138168404Spjd    s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
1139168404Spjd}
1140168404Spjd
1141168404Spjd/* ===========================================================================
1142168404Spjd * Reverse the first len bits of a code, using straightforward code (a faster
1143168404Spjd * method would use a table)
1144168404Spjd * IN assertion: 1 <= len <= 15
1145168404Spjd */
1146168404Spjdlocal unsigned bi_reverse(code, len)
1147168404Spjd    unsigned code; /* the value to invert */
1148168404Spjd    int len;       /* its bit length */
1149168404Spjd{
1150168404Spjd    register unsigned res = 0;
1151168404Spjd    do {
1152168404Spjd        res |= code & 1;
1153168404Spjd        code >>= 1, res <<= 1;
1154168404Spjd    } while (--len > 0);
1155168404Spjd    return res >> 1;
1156168404Spjd}
1157168404Spjd
1158168404Spjd/* ===========================================================================
1159168404Spjd * Flush the bit buffer, keeping at most 7 bits in it.
1160168404Spjd */
1161168404Spjdlocal void bi_flush(s)
1162168404Spjd    deflate_state *s;
1163168404Spjd{
1164168404Spjd    if (s->bi_valid == 16) {
1165168404Spjd        put_short(s, s->bi_buf);
1166168404Spjd        s->bi_buf = 0;
1167168404Spjd        s->bi_valid = 0;
1168168404Spjd    } else if (s->bi_valid >= 8) {
1169168404Spjd        put_byte(s, (Byte)s->bi_buf);
1170168404Spjd        s->bi_buf >>= 8;
1171168404Spjd        s->bi_valid -= 8;
1172168404Spjd    }
1173168404Spjd}
1174168404Spjd
1175168404Spjd/* ===========================================================================
1176168404Spjd * Flush the bit buffer and align the output on a byte boundary
1177168404Spjd */
1178168404Spjdlocal void bi_windup(s)
1179168404Spjd    deflate_state *s;
1180168404Spjd{
1181168404Spjd    if (s->bi_valid > 8) {
1182168404Spjd        put_short(s, s->bi_buf);
1183168404Spjd    } else if (s->bi_valid > 0) {
1184168404Spjd        put_byte(s, (Byte)s->bi_buf);
1185168404Spjd    }
1186168404Spjd    s->bi_buf = 0;
1187168404Spjd    s->bi_valid = 0;
1188168404Spjd#ifdef DEBUG
1189168404Spjd    s->bits_sent = (s->bits_sent+7) & ~7;
1190168404Spjd#endif
1191168404Spjd}
1192168404Spjd
1193168404Spjd/* ===========================================================================
1194168404Spjd * Copy a stored block, storing first the length and its
1195168404Spjd * one's complement if requested.
1196168404Spjd */
1197168404Spjdlocal void copy_block(s, buf, len, header)
1198168404Spjd    deflate_state *s;
1199168404Spjd    charf    *buf;    /* the input data */
1200168404Spjd    unsigned len;     /* its length */
1201168404Spjd    int      header;  /* true if block header must be written */
1202168404Spjd{
1203168404Spjd    bi_windup(s);        /* align on byte boundary */
1204168404Spjd    s->last_eob_len = 8; /* enough lookahead for inflate */
1205168404Spjd
1206168404Spjd    if (header) {
1207168404Spjd        put_short(s, (ush)len);
1208168404Spjd        put_short(s, (ush)~len);
1209168404Spjd#ifdef DEBUG
1210168404Spjd        s->bits_sent += 2*16;
1211168404Spjd#endif
1212168404Spjd    }
1213168404Spjd#ifdef DEBUG
1214168404Spjd    s->bits_sent += (ulg)len<<3;
1215168404Spjd#endif
1216168404Spjd    while (len--) {
1217168404Spjd        put_byte(s, *buf++);
1218168404Spjd    }
1219168404Spjd}
1220