xref: /freebsd/sys/contrib/zlib/trees.c (revision 6255c67c3d1a268535c50de74d3300fd86d8f15d)
1c9083b85SXin LI /* trees.c -- output deflated data using Huffman coding
2*6255c67cSXin LI  * Copyright (C) 1995-2024 Jean-loup Gailly
3c9083b85SXin LI  * detect_data_type() function provided freely by Cosmin Truta, 2006
4c9083b85SXin LI  * For conditions of distribution and use, see copyright notice in zlib.h
5c9083b85SXin LI  */
6c9083b85SXin LI 
7c9083b85SXin LI /*
8c9083b85SXin LI  *  ALGORITHM
9c9083b85SXin LI  *
10c9083b85SXin LI  *      The "deflation" process uses several Huffman trees. The more
11c9083b85SXin LI  *      common source values are represented by shorter bit sequences.
12c9083b85SXin LI  *
13c9083b85SXin LI  *      Each code tree is stored in a compressed form which is itself
14c9083b85SXin LI  * a Huffman encoding of the lengths of all the code strings (in
15c9083b85SXin LI  * ascending order by source values).  The actual code strings are
16c9083b85SXin LI  * reconstructed from the lengths in the inflate process, as described
17c9083b85SXin LI  * in the deflate specification.
18c9083b85SXin LI  *
19c9083b85SXin LI  *  REFERENCES
20c9083b85SXin LI  *
21c9083b85SXin LI  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
22c9083b85SXin LI  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
23c9083b85SXin LI  *
24c9083b85SXin LI  *      Storer, James A.
25c9083b85SXin LI  *          Data Compression:  Methods and Theory, pp. 49-50.
26c9083b85SXin LI  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
27c9083b85SXin LI  *
28c9083b85SXin LI  *      Sedgewick, R.
29c9083b85SXin LI  *          Algorithms, p290.
30c9083b85SXin LI  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
31c9083b85SXin LI  */
32c9083b85SXin LI 
33c9083b85SXin LI /* @(#) $Id$ */
34c9083b85SXin LI 
35c9083b85SXin LI /* #define GEN_TREES_H */
36c9083b85SXin LI 
37c9083b85SXin LI #include "deflate.h"
38c9083b85SXin LI 
39c9083b85SXin LI #ifdef ZLIB_DEBUG
40c9083b85SXin LI #  include <ctype.h>
41c9083b85SXin LI #endif
42c9083b85SXin LI 
43c9083b85SXin LI /* ===========================================================================
44c9083b85SXin LI  * Constants
45c9083b85SXin LI  */
46c9083b85SXin LI 
47c9083b85SXin LI #define MAX_BL_BITS 7
48c9083b85SXin LI /* Bit length codes must not exceed MAX_BL_BITS bits */
49c9083b85SXin LI 
50c9083b85SXin LI #define END_BLOCK 256
51c9083b85SXin LI /* end of block literal code */
52c9083b85SXin LI 
53c9083b85SXin LI #define REP_3_6      16
54c9083b85SXin LI /* repeat previous bit length 3-6 times (2 bits of repeat count) */
55c9083b85SXin LI 
56c9083b85SXin LI #define REPZ_3_10    17
57c9083b85SXin LI /* repeat a zero length 3-10 times  (3 bits of repeat count) */
58c9083b85SXin LI 
59c9083b85SXin LI #define REPZ_11_138  18
60c9083b85SXin LI /* repeat a zero length 11-138 times  (7 bits of repeat count) */
61c9083b85SXin LI 
62c9083b85SXin LI local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
63c9083b85SXin LI    = {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};
64c9083b85SXin LI 
65c9083b85SXin LI local const int extra_dbits[D_CODES] /* extra bits for each distance code */
66c9083b85SXin LI    = {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};
67c9083b85SXin LI 
68c9083b85SXin LI local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
69c9083b85SXin LI    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
70c9083b85SXin LI 
71c9083b85SXin LI local const uch bl_order[BL_CODES]
72c9083b85SXin LI    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
73c9083b85SXin LI /* The lengths of the bit length codes are sent in order of decreasing
74c9083b85SXin LI  * probability, to avoid transmitting the lengths for unused bit length codes.
75c9083b85SXin LI  */
76c9083b85SXin LI 
77c9083b85SXin LI /* ===========================================================================
78c9083b85SXin LI  * Local data. These are initialized only once.
79c9083b85SXin LI  */
80c9083b85SXin LI 
81c9083b85SXin LI #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
82c9083b85SXin LI 
83c9083b85SXin LI #if defined(GEN_TREES_H) || !defined(STDC)
84c9083b85SXin LI /* non ANSI compilers may not accept trees.h */
85c9083b85SXin LI 
86c9083b85SXin LI local ct_data static_ltree[L_CODES+2];
87c9083b85SXin LI /* The static literal tree. Since the bit lengths are imposed, there is no
88c9083b85SXin LI  * need for the L_CODES extra codes used during heap construction. However
89c9083b85SXin LI  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
90c9083b85SXin LI  * below).
91c9083b85SXin LI  */
92c9083b85SXin LI 
93c9083b85SXin LI local ct_data static_dtree[D_CODES];
94c9083b85SXin LI /* The static distance tree. (Actually a trivial tree since all codes use
95c9083b85SXin LI  * 5 bits.)
96c9083b85SXin LI  */
97c9083b85SXin LI 
98c9083b85SXin LI uch _dist_code[DIST_CODE_LEN];
99c9083b85SXin LI /* Distance codes. The first 256 values correspond to the distances
100c9083b85SXin LI  * 3 .. 258, the last 256 values correspond to the top 8 bits of
101c9083b85SXin LI  * the 15 bit distances.
102c9083b85SXin LI  */
103c9083b85SXin LI 
104c9083b85SXin LI uch _length_code[MAX_MATCH-MIN_MATCH+1];
105c9083b85SXin LI /* length code for each normalized match length (0 == MIN_MATCH) */
106c9083b85SXin LI 
107c9083b85SXin LI local int base_length[LENGTH_CODES];
108c9083b85SXin LI /* First normalized length for each code (0 = MIN_MATCH) */
109c9083b85SXin LI 
110c9083b85SXin LI local int base_dist[D_CODES];
111c9083b85SXin LI /* First normalized distance for each code (0 = distance of 1) */
112c9083b85SXin LI 
113c9083b85SXin LI #else
114c9083b85SXin LI #  include "trees.h"
115c9083b85SXin LI #endif /* GEN_TREES_H */
116c9083b85SXin LI 
117c9083b85SXin LI struct static_tree_desc_s {
118c9083b85SXin LI     const ct_data *static_tree;  /* static tree or NULL */
119c9083b85SXin LI     const intf *extra_bits;      /* extra bits for each code or NULL */
120c9083b85SXin LI     int     extra_base;          /* base index for extra_bits */
121c9083b85SXin LI     int     elems;               /* max number of elements in the tree */
122c9083b85SXin LI     int     max_length;          /* max bit length for the codes */
123c9083b85SXin LI };
124c9083b85SXin LI 
1254717628eSXin LI #ifdef NO_INIT_GLOBAL_POINTERS
1264717628eSXin LI #  define TCONST
1274717628eSXin LI #else
1284717628eSXin LI #  define TCONST const
1294717628eSXin LI #endif
1304717628eSXin LI 
1314717628eSXin LI local TCONST static_tree_desc static_l_desc =
132c9083b85SXin LI {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
133c9083b85SXin LI 
1344717628eSXin LI local TCONST static_tree_desc static_d_desc =
135c9083b85SXin LI {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
136c9083b85SXin LI 
1374717628eSXin LI local TCONST static_tree_desc static_bl_desc =
138c9083b85SXin LI {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
139c9083b85SXin LI 
140c9083b85SXin LI /* ===========================================================================
1414717628eSXin LI  * Output a short LSB first on the stream.
1424717628eSXin LI  * IN assertion: there is enough room in pendingBuf.
143c9083b85SXin LI  */
1444717628eSXin LI #define put_short(s, w) { \
1454717628eSXin LI     put_byte(s, (uch)((w) & 0xff)); \
1464717628eSXin LI     put_byte(s, (uch)((ush)(w) >> 8)); \
1474717628eSXin LI }
148c9083b85SXin LI 
1494717628eSXin LI /* ===========================================================================
1504717628eSXin LI  * Reverse the first len bits of a code, using straightforward code (a faster
1514717628eSXin LI  * method would use a table)
1524717628eSXin LI  * IN assertion: 1 <= len <= 15
1534717628eSXin LI  */
bi_reverse(unsigned code,int len)1544717628eSXin LI local unsigned bi_reverse(unsigned code, int len) {
1554717628eSXin LI     register unsigned res = 0;
1564717628eSXin LI     do {
1574717628eSXin LI         res |= code & 1;
1584717628eSXin LI         code >>= 1, res <<= 1;
1594717628eSXin LI     } while (--len > 0);
1604717628eSXin LI     return res >> 1;
1614717628eSXin LI }
1624717628eSXin LI 
1634717628eSXin LI /* ===========================================================================
1644717628eSXin LI  * Flush the bit buffer, keeping at most 7 bits in it.
1654717628eSXin LI  */
bi_flush(deflate_state * s)1664717628eSXin LI local void bi_flush(deflate_state *s) {
1674717628eSXin LI     if (s->bi_valid == 16) {
1684717628eSXin LI         put_short(s, s->bi_buf);
1694717628eSXin LI         s->bi_buf = 0;
1704717628eSXin LI         s->bi_valid = 0;
1714717628eSXin LI     } else if (s->bi_valid >= 8) {
1724717628eSXin LI         put_byte(s, (Byte)s->bi_buf);
1734717628eSXin LI         s->bi_buf >>= 8;
1744717628eSXin LI         s->bi_valid -= 8;
1754717628eSXin LI     }
1764717628eSXin LI }
1774717628eSXin LI 
1784717628eSXin LI /* ===========================================================================
1794717628eSXin LI  * Flush the bit buffer and align the output on a byte boundary
1804717628eSXin LI  */
bi_windup(deflate_state * s)1814717628eSXin LI local void bi_windup(deflate_state *s) {
1824717628eSXin LI     if (s->bi_valid > 8) {
1834717628eSXin LI         put_short(s, s->bi_buf);
1844717628eSXin LI     } else if (s->bi_valid > 0) {
1854717628eSXin LI         put_byte(s, (Byte)s->bi_buf);
1864717628eSXin LI     }
1874717628eSXin LI     s->bi_buf = 0;
1884717628eSXin LI     s->bi_valid = 0;
1894717628eSXin LI #ifdef ZLIB_DEBUG
1904717628eSXin LI     s->bits_sent = (s->bits_sent + 7) & ~7;
1914717628eSXin LI #endif
1924717628eSXin LI }
1934717628eSXin LI 
1944717628eSXin LI /* ===========================================================================
1954717628eSXin LI  * Generate the codes for a given tree and bit counts (which need not be
1964717628eSXin LI  * optimal).
1974717628eSXin LI  * IN assertion: the array bl_count contains the bit length statistics for
1984717628eSXin LI  * the given tree and the field len is set for all tree elements.
1994717628eSXin LI  * OUT assertion: the field code is set for all tree elements of non
2004717628eSXin LI  *     zero code length.
2014717628eSXin LI  */
gen_codes(ct_data * tree,int max_code,ushf * bl_count)2024717628eSXin LI local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) {
2034717628eSXin LI     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
2044717628eSXin LI     unsigned code = 0;         /* running code value */
2054717628eSXin LI     int bits;                  /* bit index */
2064717628eSXin LI     int n;                     /* code index */
2074717628eSXin LI 
2084717628eSXin LI     /* The distribution counts are first used to generate the code values
2094717628eSXin LI      * without bit reversal.
2104717628eSXin LI      */
2114717628eSXin LI     for (bits = 1; bits <= MAX_BITS; bits++) {
2124717628eSXin LI         code = (code + bl_count[bits - 1]) << 1;
2134717628eSXin LI         next_code[bits] = (ush)code;
2144717628eSXin LI     }
2154717628eSXin LI     /* Check that the bit counts in bl_count are consistent. The last code
2164717628eSXin LI      * must be all ones.
2174717628eSXin LI      */
2184717628eSXin LI     Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
2194717628eSXin LI             "inconsistent bit counts");
2204717628eSXin LI     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
2214717628eSXin LI 
2224717628eSXin LI     for (n = 0;  n <= max_code; n++) {
2234717628eSXin LI         int len = tree[n].Len;
2244717628eSXin LI         if (len == 0) continue;
2254717628eSXin LI         /* Now reverse the bits */
2264717628eSXin LI         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
2274717628eSXin LI 
2284717628eSXin LI         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
2294717628eSXin LI             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1));
2304717628eSXin LI     }
2314717628eSXin LI }
232c9083b85SXin LI 
233c9083b85SXin LI #ifdef GEN_TREES_H
2344717628eSXin LI local void gen_trees_header(void);
235c9083b85SXin LI #endif
236c9083b85SXin LI 
237c9083b85SXin LI #ifndef ZLIB_DEBUG
238c9083b85SXin LI #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
239c9083b85SXin LI    /* Send a code of the given tree. c and tree must not have side effects */
240c9083b85SXin LI 
241c9083b85SXin LI #else /* !ZLIB_DEBUG */
242c9083b85SXin LI #  define send_code(s, c, tree) \
243c9083b85SXin LI      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
244c9083b85SXin LI        send_bits(s, tree[c].Code, tree[c].Len); }
245c9083b85SXin LI #endif
246c9083b85SXin LI 
247c9083b85SXin LI /* ===========================================================================
248c9083b85SXin LI  * Send a value on a given number of bits.
249c9083b85SXin LI  * IN assertion: length <= 16 and value fits in length bits.
250c9083b85SXin LI  */
251c9083b85SXin LI #ifdef ZLIB_DEBUG
send_bits(deflate_state * s,int value,int length)2524717628eSXin LI local void send_bits(deflate_state *s, int value, int length) {
253c9083b85SXin LI     Tracevv((stderr," l %2d v %4x ", length, value));
254c9083b85SXin LI     Assert(length > 0 && length <= 15, "invalid length");
255c9083b85SXin LI     s->bits_sent += (ulg)length;
256c9083b85SXin LI 
257c9083b85SXin LI     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
258c9083b85SXin LI      * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid))
259c9083b85SXin LI      * unused bits in value.
260c9083b85SXin LI      */
261c9083b85SXin LI     if (s->bi_valid > (int)Buf_size - length) {
262c9083b85SXin LI         s->bi_buf |= (ush)value << s->bi_valid;
263c9083b85SXin LI         put_short(s, s->bi_buf);
264c9083b85SXin LI         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
265c9083b85SXin LI         s->bi_valid += length - Buf_size;
266c9083b85SXin LI     } else {
267c9083b85SXin LI         s->bi_buf |= (ush)value << s->bi_valid;
268c9083b85SXin LI         s->bi_valid += length;
269c9083b85SXin LI     }
270c9083b85SXin LI }
271c9083b85SXin LI #else /* !ZLIB_DEBUG */
272c9083b85SXin LI 
273c9083b85SXin LI #define send_bits(s, value, length) \
274c9083b85SXin LI { int len = length;\
275c9083b85SXin LI   if (s->bi_valid > (int)Buf_size - len) {\
276c9083b85SXin LI     int val = (int)value;\
277c9083b85SXin LI     s->bi_buf |= (ush)val << s->bi_valid;\
278c9083b85SXin LI     put_short(s, s->bi_buf);\
279c9083b85SXin LI     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
280c9083b85SXin LI     s->bi_valid += len - Buf_size;\
281c9083b85SXin LI   } else {\
282c9083b85SXin LI     s->bi_buf |= (ush)(value) << s->bi_valid;\
283c9083b85SXin LI     s->bi_valid += len;\
284c9083b85SXin LI   }\
285c9083b85SXin LI }
286c9083b85SXin LI #endif /* ZLIB_DEBUG */
287c9083b85SXin LI 
288c9083b85SXin LI 
289c9083b85SXin LI /* the arguments must not have side effects */
290c9083b85SXin LI 
291c9083b85SXin LI /* ===========================================================================
292c9083b85SXin LI  * Initialize the various 'constant' tables.
293c9083b85SXin LI  */
tr_static_init(void)2944717628eSXin LI local void tr_static_init(void) {
295c9083b85SXin LI #if defined(GEN_TREES_H) || !defined(STDC)
296c9083b85SXin LI     static int static_init_done = 0;
297c9083b85SXin LI     int n;        /* iterates over tree elements */
298c9083b85SXin LI     int bits;     /* bit counter */
299c9083b85SXin LI     int length;   /* length value */
300c9083b85SXin LI     int code;     /* code value */
301c9083b85SXin LI     int dist;     /* distance index */
302c9083b85SXin LI     ush bl_count[MAX_BITS+1];
303c9083b85SXin LI     /* number of codes at each bit length for an optimal tree */
304c9083b85SXin LI 
305c9083b85SXin LI     if (static_init_done) return;
306c9083b85SXin LI 
307c9083b85SXin LI     /* For some embedded targets, global variables are not initialized: */
308c9083b85SXin LI #ifdef NO_INIT_GLOBAL_POINTERS
309c9083b85SXin LI     static_l_desc.static_tree = static_ltree;
310c9083b85SXin LI     static_l_desc.extra_bits = extra_lbits;
311c9083b85SXin LI     static_d_desc.static_tree = static_dtree;
312c9083b85SXin LI     static_d_desc.extra_bits = extra_dbits;
313c9083b85SXin LI     static_bl_desc.extra_bits = extra_blbits;
314c9083b85SXin LI #endif
315c9083b85SXin LI 
316c9083b85SXin LI     /* Initialize the mapping length (0..255) -> length code (0..28) */
317c9083b85SXin LI     length = 0;
318c9083b85SXin LI     for (code = 0; code < LENGTH_CODES-1; code++) {
319c9083b85SXin LI         base_length[code] = length;
320c9083b85SXin LI         for (n = 0; n < (1 << extra_lbits[code]); n++) {
321c9083b85SXin LI             _length_code[length++] = (uch)code;
322c9083b85SXin LI         }
323c9083b85SXin LI     }
324c9083b85SXin LI     Assert (length == 256, "tr_static_init: length != 256");
325c9083b85SXin LI     /* Note that the length 255 (match length 258) can be represented
326c9083b85SXin LI      * in two different ways: code 284 + 5 bits or code 285, so we
327c9083b85SXin LI      * overwrite length_code[255] to use the best encoding:
328c9083b85SXin LI      */
329c9083b85SXin LI     _length_code[length - 1] = (uch)code;
330c9083b85SXin LI 
331c9083b85SXin LI     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
332c9083b85SXin LI     dist = 0;
333c9083b85SXin LI     for (code = 0 ; code < 16; code++) {
334c9083b85SXin LI         base_dist[code] = dist;
335c9083b85SXin LI         for (n = 0; n < (1 << extra_dbits[code]); n++) {
336c9083b85SXin LI             _dist_code[dist++] = (uch)code;
337c9083b85SXin LI         }
338c9083b85SXin LI     }
339c9083b85SXin LI     Assert (dist == 256, "tr_static_init: dist != 256");
340c9083b85SXin LI     dist >>= 7; /* from now on, all distances are divided by 128 */
341c9083b85SXin LI     for ( ; code < D_CODES; code++) {
342c9083b85SXin LI         base_dist[code] = dist << 7;
343c9083b85SXin LI         for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
344c9083b85SXin LI             _dist_code[256 + dist++] = (uch)code;
345c9083b85SXin LI         }
346c9083b85SXin LI     }
347c9083b85SXin LI     Assert (dist == 256, "tr_static_init: 256 + dist != 512");
348c9083b85SXin LI 
349c9083b85SXin LI     /* Construct the codes of the static literal tree */
350c9083b85SXin LI     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
351c9083b85SXin LI     n = 0;
352c9083b85SXin LI     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
353c9083b85SXin LI     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
354c9083b85SXin LI     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
355c9083b85SXin LI     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
356c9083b85SXin LI     /* Codes 286 and 287 do not exist, but we must include them in the
357c9083b85SXin LI      * tree construction to get a canonical Huffman tree (longest code
358c9083b85SXin LI      * all ones)
359c9083b85SXin LI      */
360c9083b85SXin LI     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
361c9083b85SXin LI 
362c9083b85SXin LI     /* The static distance tree is trivial: */
363c9083b85SXin LI     for (n = 0; n < D_CODES; n++) {
364c9083b85SXin LI         static_dtree[n].Len = 5;
365c9083b85SXin LI         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
366c9083b85SXin LI     }
367c9083b85SXin LI     static_init_done = 1;
368c9083b85SXin LI 
369c9083b85SXin LI #  ifdef GEN_TREES_H
370c9083b85SXin LI     gen_trees_header();
371c9083b85SXin LI #  endif
372c9083b85SXin LI #endif /* defined(GEN_TREES_H) || !defined(STDC) */
373c9083b85SXin LI }
374c9083b85SXin LI 
375c9083b85SXin LI /* ===========================================================================
376e37bb444SXin LI  * Generate the file trees.h describing the static trees.
377c9083b85SXin LI  */
378c9083b85SXin LI #ifdef GEN_TREES_H
379c9083b85SXin LI #  ifndef ZLIB_DEBUG
380c9083b85SXin LI #    include <stdio.h>
381c9083b85SXin LI #  endif
382c9083b85SXin LI 
383c9083b85SXin LI #  define SEPARATOR(i, last, width) \
384c9083b85SXin LI       ((i) == (last)? "\n};\n\n" :    \
385c9083b85SXin LI        ((i) % (width) == (width) - 1 ? ",\n" : ", "))
386c9083b85SXin LI 
gen_trees_header(void)3874717628eSXin LI void gen_trees_header(void) {
388c9083b85SXin LI     FILE *header = fopen("trees.h", "w");
389c9083b85SXin LI     int i;
390c9083b85SXin LI 
391c9083b85SXin LI     Assert (header != NULL, "Can't open trees.h");
392c9083b85SXin LI     fprintf(header,
393c9083b85SXin LI             "/* header created automatically with -DGEN_TREES_H */\n\n");
394c9083b85SXin LI 
395c9083b85SXin LI     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
396c9083b85SXin LI     for (i = 0; i < L_CODES+2; i++) {
397c9083b85SXin LI         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
398c9083b85SXin LI                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
399c9083b85SXin LI     }
400c9083b85SXin LI 
401c9083b85SXin LI     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
402c9083b85SXin LI     for (i = 0; i < D_CODES; i++) {
403c9083b85SXin LI         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
404c9083b85SXin LI                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
405c9083b85SXin LI     }
406c9083b85SXin LI 
407c9083b85SXin LI     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
408c9083b85SXin LI     for (i = 0; i < DIST_CODE_LEN; i++) {
409c9083b85SXin LI         fprintf(header, "%2u%s", _dist_code[i],
410c9083b85SXin LI                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
411c9083b85SXin LI     }
412c9083b85SXin LI 
413c9083b85SXin LI     fprintf(header,
414c9083b85SXin LI         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
415c9083b85SXin LI     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
416c9083b85SXin LI         fprintf(header, "%2u%s", _length_code[i],
417c9083b85SXin LI                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
418c9083b85SXin LI     }
419c9083b85SXin LI 
420c9083b85SXin LI     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
421c9083b85SXin LI     for (i = 0; i < LENGTH_CODES; i++) {
422c9083b85SXin LI         fprintf(header, "%1u%s", base_length[i],
423c9083b85SXin LI                 SEPARATOR(i, LENGTH_CODES-1, 20));
424c9083b85SXin LI     }
425c9083b85SXin LI 
426c9083b85SXin LI     fprintf(header, "local const int base_dist[D_CODES] = {\n");
427c9083b85SXin LI     for (i = 0; i < D_CODES; i++) {
428c9083b85SXin LI         fprintf(header, "%5u%s", base_dist[i],
429c9083b85SXin LI                 SEPARATOR(i, D_CODES-1, 10));
430c9083b85SXin LI     }
431c9083b85SXin LI 
432c9083b85SXin LI     fclose(header);
433c9083b85SXin LI }
434c9083b85SXin LI #endif /* GEN_TREES_H */
435c9083b85SXin LI 
436c9083b85SXin LI /* ===========================================================================
4374717628eSXin LI  * Initialize a new block.
4384717628eSXin LI  */
init_block(deflate_state * s)4394717628eSXin LI local void init_block(deflate_state *s) {
4404717628eSXin LI     int n; /* iterates over tree elements */
4414717628eSXin LI 
4424717628eSXin LI     /* Initialize the trees. */
4434717628eSXin LI     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
4444717628eSXin LI     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
4454717628eSXin LI     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
4464717628eSXin LI 
4474717628eSXin LI     s->dyn_ltree[END_BLOCK].Freq = 1;
4484717628eSXin LI     s->opt_len = s->static_len = 0L;
4494717628eSXin LI     s->sym_next = s->matches = 0;
4504717628eSXin LI }
4514717628eSXin LI 
4524717628eSXin LI /* ===========================================================================
453c9083b85SXin LI  * Initialize the tree data structures for a new zlib stream.
454c9083b85SXin LI  */
_tr_init(deflate_state * s)4554717628eSXin LI void ZLIB_INTERNAL _tr_init(deflate_state *s) {
456c9083b85SXin LI     tr_static_init();
457c9083b85SXin LI 
458c9083b85SXin LI     s->l_desc.dyn_tree = s->dyn_ltree;
459c9083b85SXin LI     s->l_desc.stat_desc = &static_l_desc;
460c9083b85SXin LI 
461c9083b85SXin LI     s->d_desc.dyn_tree = s->dyn_dtree;
462c9083b85SXin LI     s->d_desc.stat_desc = &static_d_desc;
463c9083b85SXin LI 
464c9083b85SXin LI     s->bl_desc.dyn_tree = s->bl_tree;
465c9083b85SXin LI     s->bl_desc.stat_desc = &static_bl_desc;
466c9083b85SXin LI 
467c9083b85SXin LI     s->bi_buf = 0;
468c9083b85SXin LI     s->bi_valid = 0;
469c9083b85SXin LI #ifdef ZLIB_DEBUG
470c9083b85SXin LI     s->compressed_len = 0L;
471c9083b85SXin LI     s->bits_sent = 0L;
472c9083b85SXin LI #endif
473c9083b85SXin LI 
474c9083b85SXin LI     /* Initialize the first block of the first file: */
475c9083b85SXin LI     init_block(s);
476c9083b85SXin LI }
477c9083b85SXin LI 
478c9083b85SXin LI #define SMALLEST 1
479c9083b85SXin LI /* Index within the heap array of least frequent node in the Huffman tree */
480c9083b85SXin LI 
481c9083b85SXin LI 
482c9083b85SXin LI /* ===========================================================================
483c9083b85SXin LI  * Remove the smallest element from the heap and recreate the heap with
484c9083b85SXin LI  * one less element. Updates heap and heap_len.
485c9083b85SXin LI  */
486c9083b85SXin LI #define pqremove(s, tree, top) \
487c9083b85SXin LI {\
488c9083b85SXin LI     top = s->heap[SMALLEST]; \
489c9083b85SXin LI     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
490c9083b85SXin LI     pqdownheap(s, tree, SMALLEST); \
491c9083b85SXin LI }
492c9083b85SXin LI 
493c9083b85SXin LI /* ===========================================================================
494c9083b85SXin LI  * Compares to subtrees, using the tree depth as tie breaker when
495c9083b85SXin LI  * the subtrees have equal frequency. This minimizes the worst case length.
496c9083b85SXin LI  */
497c9083b85SXin LI #define smaller(tree, n, m, depth) \
498c9083b85SXin LI    (tree[n].Freq < tree[m].Freq || \
499c9083b85SXin LI    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
500c9083b85SXin LI 
501c9083b85SXin LI /* ===========================================================================
502c9083b85SXin LI  * Restore the heap property by moving down the tree starting at node k,
503c9083b85SXin LI  * exchanging a node with the smallest of its two sons if necessary, stopping
504c9083b85SXin LI  * when the heap property is re-established (each father smaller than its
505c9083b85SXin LI  * two sons).
506c9083b85SXin LI  */
pqdownheap(deflate_state * s,ct_data * tree,int k)5074717628eSXin LI local void pqdownheap(deflate_state *s, ct_data *tree, int k) {
508c9083b85SXin LI     int v = s->heap[k];
509c9083b85SXin LI     int j = k << 1;  /* left son of k */
510c9083b85SXin LI     while (j <= s->heap_len) {
511c9083b85SXin LI         /* Set j to the smallest of the two sons: */
512c9083b85SXin LI         if (j < s->heap_len &&
513c9083b85SXin LI             smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) {
514c9083b85SXin LI             j++;
515c9083b85SXin LI         }
516c9083b85SXin LI         /* Exit if v is smaller than both sons */
517c9083b85SXin LI         if (smaller(tree, v, s->heap[j], s->depth)) break;
518c9083b85SXin LI 
519c9083b85SXin LI         /* Exchange v with the smallest son */
520c9083b85SXin LI         s->heap[k] = s->heap[j];  k = j;
521c9083b85SXin LI 
522c9083b85SXin LI         /* And continue down the tree, setting j to the left son of k */
523c9083b85SXin LI         j <<= 1;
524c9083b85SXin LI     }
525c9083b85SXin LI     s->heap[k] = v;
526c9083b85SXin LI }
527c9083b85SXin LI 
528c9083b85SXin LI /* ===========================================================================
529c9083b85SXin LI  * Compute the optimal bit lengths for a tree and update the total bit length
530c9083b85SXin LI  * for the current block.
531c9083b85SXin LI  * IN assertion: the fields freq and dad are set, heap[heap_max] and
532c9083b85SXin LI  *    above are the tree nodes sorted by increasing frequency.
533c9083b85SXin LI  * OUT assertions: the field len is set to the optimal bit length, the
534c9083b85SXin LI  *     array bl_count contains the frequencies for each bit length.
535c9083b85SXin LI  *     The length opt_len is updated; static_len is also updated if stree is
536c9083b85SXin LI  *     not null.
537c9083b85SXin LI  */
gen_bitlen(deflate_state * s,tree_desc * desc)5384717628eSXin LI local void gen_bitlen(deflate_state *s, tree_desc *desc) {
539c9083b85SXin LI     ct_data *tree        = desc->dyn_tree;
540c9083b85SXin LI     int max_code         = desc->max_code;
541c9083b85SXin LI     const ct_data *stree = desc->stat_desc->static_tree;
542c9083b85SXin LI     const intf *extra    = desc->stat_desc->extra_bits;
543c9083b85SXin LI     int base             = desc->stat_desc->extra_base;
544c9083b85SXin LI     int max_length       = desc->stat_desc->max_length;
545c9083b85SXin LI     int h;              /* heap index */
546c9083b85SXin LI     int n, m;           /* iterate over the tree elements */
547c9083b85SXin LI     int bits;           /* bit length */
548c9083b85SXin LI     int xbits;          /* extra bits */
549c9083b85SXin LI     ush f;              /* frequency */
550c9083b85SXin LI     int overflow = 0;   /* number of elements with bit length too large */
551c9083b85SXin LI 
552c9083b85SXin LI     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
553c9083b85SXin LI 
554c9083b85SXin LI     /* In a first pass, compute the optimal bit lengths (which may
555c9083b85SXin LI      * overflow in the case of the bit length tree).
556c9083b85SXin LI      */
557c9083b85SXin LI     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
558c9083b85SXin LI 
559c9083b85SXin LI     for (h = s->heap_max + 1; h < HEAP_SIZE; h++) {
560c9083b85SXin LI         n = s->heap[h];
561c9083b85SXin LI         bits = tree[tree[n].Dad].Len + 1;
562c9083b85SXin LI         if (bits > max_length) bits = max_length, overflow++;
563c9083b85SXin LI         tree[n].Len = (ush)bits;
564c9083b85SXin LI         /* We overwrite tree[n].Dad which is no longer needed */
565c9083b85SXin LI 
566c9083b85SXin LI         if (n > max_code) continue; /* not a leaf node */
567c9083b85SXin LI 
568c9083b85SXin LI         s->bl_count[bits]++;
569c9083b85SXin LI         xbits = 0;
570c9083b85SXin LI         if (n >= base) xbits = extra[n - base];
571c9083b85SXin LI         f = tree[n].Freq;
572c9083b85SXin LI         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
573c9083b85SXin LI         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
574c9083b85SXin LI     }
575c9083b85SXin LI     if (overflow == 0) return;
576c9083b85SXin LI 
577c9083b85SXin LI     Tracev((stderr,"\nbit length overflow\n"));
578c9083b85SXin LI     /* This happens for example on obj2 and pic of the Calgary corpus */
579c9083b85SXin LI 
580c9083b85SXin LI     /* Find the first bit length which could increase: */
581c9083b85SXin LI     do {
582c9083b85SXin LI         bits = max_length - 1;
583c9083b85SXin LI         while (s->bl_count[bits] == 0) bits--;
584c9083b85SXin LI         s->bl_count[bits]--;        /* move one leaf down the tree */
585c9083b85SXin LI         s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */
586c9083b85SXin LI         s->bl_count[max_length]--;
587c9083b85SXin LI         /* The brother of the overflow item also moves one step up,
588c9083b85SXin LI          * but this does not affect bl_count[max_length]
589c9083b85SXin LI          */
590c9083b85SXin LI         overflow -= 2;
591c9083b85SXin LI     } while (overflow > 0);
592c9083b85SXin LI 
593c9083b85SXin LI     /* Now recompute all bit lengths, scanning in increasing frequency.
594c9083b85SXin LI      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
595c9083b85SXin LI      * lengths instead of fixing only the wrong ones. This idea is taken
596c9083b85SXin LI      * from 'ar' written by Haruhiko Okumura.)
597c9083b85SXin LI      */
598c9083b85SXin LI     for (bits = max_length; bits != 0; bits--) {
599c9083b85SXin LI         n = s->bl_count[bits];
600c9083b85SXin LI         while (n != 0) {
601c9083b85SXin LI             m = s->heap[--h];
602c9083b85SXin LI             if (m > max_code) continue;
603c9083b85SXin LI             if ((unsigned) tree[m].Len != (unsigned) bits) {
604c9083b85SXin LI                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
605c9083b85SXin LI                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
606c9083b85SXin LI                 tree[m].Len = (ush)bits;
607c9083b85SXin LI             }
608c9083b85SXin LI             n--;
609c9083b85SXin LI         }
610c9083b85SXin LI     }
611c9083b85SXin LI }
612c9083b85SXin LI 
6134717628eSXin LI #ifdef DUMP_BL_TREE
6144717628eSXin LI #  include <stdio.h>
6154717628eSXin LI #endif
616c9083b85SXin LI 
617c9083b85SXin LI /* ===========================================================================
618c9083b85SXin LI  * Construct one Huffman tree and assigns the code bit strings and lengths.
619c9083b85SXin LI  * Update the total bit length for the current block.
620c9083b85SXin LI  * IN assertion: the field freq is set for all tree elements.
621c9083b85SXin LI  * OUT assertions: the fields len and code are set to the optimal bit length
622c9083b85SXin LI  *     and corresponding code. The length opt_len is updated; static_len is
623c9083b85SXin LI  *     also updated if stree is not null. The field max_code is set.
624c9083b85SXin LI  */
build_tree(deflate_state * s,tree_desc * desc)6254717628eSXin LI local void build_tree(deflate_state *s, tree_desc *desc) {
626c9083b85SXin LI     ct_data *tree         = desc->dyn_tree;
627c9083b85SXin LI     const ct_data *stree  = desc->stat_desc->static_tree;
628c9083b85SXin LI     int elems             = desc->stat_desc->elems;
629c9083b85SXin LI     int n, m;          /* iterate over heap elements */
630c9083b85SXin LI     int max_code = -1; /* largest code with non zero frequency */
631c9083b85SXin LI     int node;          /* new node being created */
632c9083b85SXin LI 
633c9083b85SXin LI     /* Construct the initial heap, with least frequent element in
634c9083b85SXin LI      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1].
635c9083b85SXin LI      * heap[0] is not used.
636c9083b85SXin LI      */
637c9083b85SXin LI     s->heap_len = 0, s->heap_max = HEAP_SIZE;
638c9083b85SXin LI 
639c9083b85SXin LI     for (n = 0; n < elems; n++) {
640c9083b85SXin LI         if (tree[n].Freq != 0) {
641c9083b85SXin LI             s->heap[++(s->heap_len)] = max_code = n;
642c9083b85SXin LI             s->depth[n] = 0;
643c9083b85SXin LI         } else {
644c9083b85SXin LI             tree[n].Len = 0;
645c9083b85SXin LI         }
646c9083b85SXin LI     }
647c9083b85SXin LI 
648c9083b85SXin LI     /* The pkzip format requires that at least one distance code exists,
649c9083b85SXin LI      * and that at least one bit should be sent even if there is only one
650c9083b85SXin LI      * possible code. So to avoid special checks later on we force at least
651c9083b85SXin LI      * two codes of non zero frequency.
652c9083b85SXin LI      */
653c9083b85SXin LI     while (s->heap_len < 2) {
654c9083b85SXin LI         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
655c9083b85SXin LI         tree[node].Freq = 1;
656c9083b85SXin LI         s->depth[node] = 0;
657c9083b85SXin LI         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
658c9083b85SXin LI         /* node is 0 or 1 so it does not have extra bits */
659c9083b85SXin LI     }
660c9083b85SXin LI     desc->max_code = max_code;
661c9083b85SXin LI 
662c9083b85SXin LI     /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree,
663c9083b85SXin LI      * establish sub-heaps of increasing lengths:
664c9083b85SXin LI      */
665c9083b85SXin LI     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
666c9083b85SXin LI 
667c9083b85SXin LI     /* Construct the Huffman tree by repeatedly combining the least two
668c9083b85SXin LI      * frequent nodes.
669c9083b85SXin LI      */
670c9083b85SXin LI     node = elems;              /* next internal node of the tree */
671c9083b85SXin LI     do {
672c9083b85SXin LI         pqremove(s, tree, n);  /* n = node of least frequency */
673c9083b85SXin LI         m = s->heap[SMALLEST]; /* m = node of next least frequency */
674c9083b85SXin LI 
675c9083b85SXin LI         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
676c9083b85SXin LI         s->heap[--(s->heap_max)] = m;
677c9083b85SXin LI 
678c9083b85SXin LI         /* Create a new node father of n and m */
679c9083b85SXin LI         tree[node].Freq = tree[n].Freq + tree[m].Freq;
680c9083b85SXin LI         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
681c9083b85SXin LI                                 s->depth[n] : s->depth[m]) + 1);
682c9083b85SXin LI         tree[n].Dad = tree[m].Dad = (ush)node;
683c9083b85SXin LI #ifdef DUMP_BL_TREE
684c9083b85SXin LI         if (tree == s->bl_tree) {
685c9083b85SXin LI             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
686c9083b85SXin LI                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
687c9083b85SXin LI         }
688c9083b85SXin LI #endif
689c9083b85SXin LI         /* and insert the new node in the heap */
690c9083b85SXin LI         s->heap[SMALLEST] = node++;
691c9083b85SXin LI         pqdownheap(s, tree, SMALLEST);
692c9083b85SXin LI 
693c9083b85SXin LI     } while (s->heap_len >= 2);
694c9083b85SXin LI 
695c9083b85SXin LI     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
696c9083b85SXin LI 
697c9083b85SXin LI     /* At this point, the fields freq and dad are set. We can now
698c9083b85SXin LI      * generate the bit lengths.
699c9083b85SXin LI      */
700c9083b85SXin LI     gen_bitlen(s, (tree_desc *)desc);
701c9083b85SXin LI 
702c9083b85SXin LI     /* The field len is now set, we can generate the bit codes */
703c9083b85SXin LI     gen_codes ((ct_data *)tree, max_code, s->bl_count);
704c9083b85SXin LI }
705c9083b85SXin LI 
706c9083b85SXin LI /* ===========================================================================
707c9083b85SXin LI  * Scan a literal or distance tree to determine the frequencies of the codes
708c9083b85SXin LI  * in the bit length tree.
709c9083b85SXin LI  */
scan_tree(deflate_state * s,ct_data * tree,int max_code)7104717628eSXin LI local void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
711c9083b85SXin LI     int n;                     /* iterates over all tree elements */
712c9083b85SXin LI     int prevlen = -1;          /* last emitted length */
713c9083b85SXin LI     int curlen;                /* length of current code */
714c9083b85SXin LI     int nextlen = tree[0].Len; /* length of next code */
715c9083b85SXin LI     int count = 0;             /* repeat count of the current code */
716c9083b85SXin LI     int max_count = 7;         /* max repeat count */
717c9083b85SXin LI     int min_count = 4;         /* min repeat count */
718c9083b85SXin LI 
719c9083b85SXin LI     if (nextlen == 0) max_count = 138, min_count = 3;
720c9083b85SXin LI     tree[max_code + 1].Len = (ush)0xffff; /* guard */
721c9083b85SXin LI 
722c9083b85SXin LI     for (n = 0; n <= max_code; n++) {
723c9083b85SXin LI         curlen = nextlen; nextlen = tree[n + 1].Len;
724c9083b85SXin LI         if (++count < max_count && curlen == nextlen) {
725c9083b85SXin LI             continue;
726c9083b85SXin LI         } else if (count < min_count) {
727c9083b85SXin LI             s->bl_tree[curlen].Freq += count;
728c9083b85SXin LI         } else if (curlen != 0) {
729c9083b85SXin LI             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
730c9083b85SXin LI             s->bl_tree[REP_3_6].Freq++;
731c9083b85SXin LI         } else if (count <= 10) {
732c9083b85SXin LI             s->bl_tree[REPZ_3_10].Freq++;
733c9083b85SXin LI         } else {
734c9083b85SXin LI             s->bl_tree[REPZ_11_138].Freq++;
735c9083b85SXin LI         }
736c9083b85SXin LI         count = 0; prevlen = curlen;
737c9083b85SXin LI         if (nextlen == 0) {
738c9083b85SXin LI             max_count = 138, min_count = 3;
739c9083b85SXin LI         } else if (curlen == nextlen) {
740c9083b85SXin LI             max_count = 6, min_count = 3;
741c9083b85SXin LI         } else {
742c9083b85SXin LI             max_count = 7, min_count = 4;
743c9083b85SXin LI         }
744c9083b85SXin LI     }
745c9083b85SXin LI }
746c9083b85SXin LI 
747c9083b85SXin LI /* ===========================================================================
748c9083b85SXin LI  * Send a literal or distance tree in compressed form, using the codes in
749c9083b85SXin LI  * bl_tree.
750c9083b85SXin LI  */
send_tree(deflate_state * s,ct_data * tree,int max_code)7514717628eSXin LI local void send_tree(deflate_state *s, ct_data *tree, int max_code) {
752c9083b85SXin LI     int n;                     /* iterates over all tree elements */
753c9083b85SXin LI     int prevlen = -1;          /* last emitted length */
754c9083b85SXin LI     int curlen;                /* length of current code */
755c9083b85SXin LI     int nextlen = tree[0].Len; /* length of next code */
756c9083b85SXin LI     int count = 0;             /* repeat count of the current code */
757c9083b85SXin LI     int max_count = 7;         /* max repeat count */
758c9083b85SXin LI     int min_count = 4;         /* min repeat count */
759c9083b85SXin LI 
760c9083b85SXin LI     /* tree[max_code + 1].Len = -1; */  /* guard already set */
761c9083b85SXin LI     if (nextlen == 0) max_count = 138, min_count = 3;
762c9083b85SXin LI 
763c9083b85SXin LI     for (n = 0; n <= max_code; n++) {
764c9083b85SXin LI         curlen = nextlen; nextlen = tree[n + 1].Len;
765c9083b85SXin LI         if (++count < max_count && curlen == nextlen) {
766c9083b85SXin LI             continue;
767c9083b85SXin LI         } else if (count < min_count) {
768c9083b85SXin LI             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
769c9083b85SXin LI 
770c9083b85SXin LI         } else if (curlen != 0) {
771c9083b85SXin LI             if (curlen != prevlen) {
772c9083b85SXin LI                 send_code(s, curlen, s->bl_tree); count--;
773c9083b85SXin LI             }
774c9083b85SXin LI             Assert(count >= 3 && count <= 6, " 3_6?");
775c9083b85SXin LI             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2);
776c9083b85SXin LI 
777c9083b85SXin LI         } else if (count <= 10) {
778c9083b85SXin LI             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3);
779c9083b85SXin LI 
780c9083b85SXin LI         } else {
781c9083b85SXin LI             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7);
782c9083b85SXin LI         }
783c9083b85SXin LI         count = 0; prevlen = curlen;
784c9083b85SXin LI         if (nextlen == 0) {
785c9083b85SXin LI             max_count = 138, min_count = 3;
786c9083b85SXin LI         } else if (curlen == nextlen) {
787c9083b85SXin LI             max_count = 6, min_count = 3;
788c9083b85SXin LI         } else {
789c9083b85SXin LI             max_count = 7, min_count = 4;
790c9083b85SXin LI         }
791c9083b85SXin LI     }
792c9083b85SXin LI }
793c9083b85SXin LI 
794c9083b85SXin LI /* ===========================================================================
795c9083b85SXin LI  * Construct the Huffman tree for the bit lengths and return the index in
796c9083b85SXin LI  * bl_order of the last bit length code to send.
797c9083b85SXin LI  */
build_bl_tree(deflate_state * s)7984717628eSXin LI local int build_bl_tree(deflate_state *s) {
799c9083b85SXin LI     int max_blindex;  /* index of last bit length code of non zero freq */
800c9083b85SXin LI 
801c9083b85SXin LI     /* Determine the bit length frequencies for literal and distance trees */
802c9083b85SXin LI     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
803c9083b85SXin LI     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
804c9083b85SXin LI 
805c9083b85SXin LI     /* Build the bit length tree: */
806c9083b85SXin LI     build_tree(s, (tree_desc *)(&(s->bl_desc)));
807e37bb444SXin LI     /* opt_len now includes the length of the tree representations, except the
808e37bb444SXin LI      * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts.
809c9083b85SXin LI      */
810c9083b85SXin LI 
811c9083b85SXin LI     /* Determine the number of bit length codes to send. The pkzip format
812c9083b85SXin LI      * requires that at least 4 bit length codes be sent. (appnote.txt says
813c9083b85SXin LI      * 3 but the actual value used is 4.)
814c9083b85SXin LI      */
815c9083b85SXin LI     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
816c9083b85SXin LI         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
817c9083b85SXin LI     }
818c9083b85SXin LI     /* Update opt_len to include the bit length tree and counts */
819c9083b85SXin LI     s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4;
820c9083b85SXin LI     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
821c9083b85SXin LI             s->opt_len, s->static_len));
822c9083b85SXin LI 
823c9083b85SXin LI     return max_blindex;
824c9083b85SXin LI }
825c9083b85SXin LI 
826c9083b85SXin LI /* ===========================================================================
827c9083b85SXin LI  * Send the header for a block using dynamic Huffman trees: the counts, the
828c9083b85SXin LI  * lengths of the bit length codes, the literal tree and the distance tree.
829c9083b85SXin LI  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
830c9083b85SXin LI  */
send_all_trees(deflate_state * s,int lcodes,int dcodes,int blcodes)8314717628eSXin LI local void send_all_trees(deflate_state *s, int lcodes, int dcodes,
8324717628eSXin LI                           int blcodes) {
833c9083b85SXin LI     int rank;                    /* index in bl_order */
834c9083b85SXin LI 
835c9083b85SXin LI     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
836c9083b85SXin LI     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
837c9083b85SXin LI             "too many codes");
838c9083b85SXin LI     Tracev((stderr, "\nbl counts: "));
839c9083b85SXin LI     send_bits(s, lcodes - 257, 5);  /* not +255 as stated in appnote.txt */
840c9083b85SXin LI     send_bits(s, dcodes - 1,   5);
841c9083b85SXin LI     send_bits(s, blcodes - 4,  4);  /* not -3 as stated in appnote.txt */
842c9083b85SXin LI     for (rank = 0; rank < blcodes; rank++) {
843c9083b85SXin LI         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
844c9083b85SXin LI         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
845c9083b85SXin LI     }
846c9083b85SXin LI     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
847c9083b85SXin LI 
848c9083b85SXin LI     send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1);  /* literal tree */
849c9083b85SXin LI     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
850c9083b85SXin LI 
851c9083b85SXin LI     send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1);  /* distance tree */
852c9083b85SXin LI     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
853c9083b85SXin LI }
854c9083b85SXin LI 
855c9083b85SXin LI /* ===========================================================================
856c9083b85SXin LI  * Send a stored block
857c9083b85SXin LI  */
_tr_stored_block(deflate_state * s,charf * buf,ulg stored_len,int last)8584717628eSXin LI void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf,
8594717628eSXin LI                                     ulg stored_len, int last) {
860c9083b85SXin LI     send_bits(s, (STORED_BLOCK<<1) + last, 3);  /* send block type */
861c9083b85SXin LI     bi_windup(s);        /* align on byte boundary */
862c9083b85SXin LI     put_short(s, (ush)stored_len);
863c9083b85SXin LI     put_short(s, (ush)~stored_len);
864cd882207SXin LI     if (stored_len)
865c9083b85SXin LI         zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
866c9083b85SXin LI     s->pending += stored_len;
867c9083b85SXin LI #ifdef ZLIB_DEBUG
868c9083b85SXin LI     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
869c9083b85SXin LI     s->compressed_len += (stored_len + 4) << 3;
870c9083b85SXin LI     s->bits_sent += 2*16;
871c9083b85SXin LI     s->bits_sent += stored_len << 3;
872c9083b85SXin LI #endif
873c9083b85SXin LI }
874c9083b85SXin LI 
875c9083b85SXin LI /* ===========================================================================
876c9083b85SXin LI  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
877c9083b85SXin LI  */
_tr_flush_bits(deflate_state * s)8784717628eSXin LI void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) {
879c9083b85SXin LI     bi_flush(s);
880c9083b85SXin LI }
881c9083b85SXin LI 
882c9083b85SXin LI /* ===========================================================================
883c9083b85SXin LI  * Send one empty static block to give enough lookahead for inflate.
884c9083b85SXin LI  * This takes 10 bits, of which 7 may remain in the bit buffer.
885c9083b85SXin LI  */
_tr_align(deflate_state * s)8864717628eSXin LI void ZLIB_INTERNAL _tr_align(deflate_state *s) {
887c9083b85SXin LI     send_bits(s, STATIC_TREES<<1, 3);
888c9083b85SXin LI     send_code(s, END_BLOCK, static_ltree);
889c9083b85SXin LI #ifdef ZLIB_DEBUG
890c9083b85SXin LI     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
891c9083b85SXin LI #endif
892c9083b85SXin LI     bi_flush(s);
893c9083b85SXin LI }
894c9083b85SXin LI 
895c9083b85SXin LI /* ===========================================================================
8964717628eSXin LI  * Send the block data compressed using the given Huffman trees
8974717628eSXin LI  */
compress_block(deflate_state * s,const ct_data * ltree,const ct_data * dtree)8984717628eSXin LI local void compress_block(deflate_state *s, const ct_data *ltree,
8994717628eSXin LI                           const ct_data *dtree) {
9004717628eSXin LI     unsigned dist;      /* distance of matched string */
9014717628eSXin LI     int lc;             /* match length or unmatched char (if dist == 0) */
902*6255c67cSXin LI     unsigned sx = 0;    /* running index in symbol buffers */
9034717628eSXin LI     unsigned code;      /* the code to send */
9044717628eSXin LI     int extra;          /* number of extra bits to send */
9054717628eSXin LI 
9064717628eSXin LI     if (s->sym_next != 0) do {
907*6255c67cSXin LI #ifdef LIT_MEM
908*6255c67cSXin LI         dist = s->d_buf[sx];
909*6255c67cSXin LI         lc = s->l_buf[sx++];
910*6255c67cSXin LI #else
9114717628eSXin LI         dist = s->sym_buf[sx++] & 0xff;
9124717628eSXin LI         dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
9134717628eSXin LI         lc = s->sym_buf[sx++];
914*6255c67cSXin LI #endif
9154717628eSXin LI         if (dist == 0) {
9164717628eSXin LI             send_code(s, lc, ltree); /* send a literal byte */
9174717628eSXin LI             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
9184717628eSXin LI         } else {
9194717628eSXin LI             /* Here, lc is the match length - MIN_MATCH */
9204717628eSXin LI             code = _length_code[lc];
9214717628eSXin LI             send_code(s, code + LITERALS + 1, ltree);   /* send length code */
9224717628eSXin LI             extra = extra_lbits[code];
9234717628eSXin LI             if (extra != 0) {
9244717628eSXin LI                 lc -= base_length[code];
9254717628eSXin LI                 send_bits(s, lc, extra);       /* send the extra length bits */
9264717628eSXin LI             }
9274717628eSXin LI             dist--; /* dist is now the match distance - 1 */
9284717628eSXin LI             code = d_code(dist);
9294717628eSXin LI             Assert (code < D_CODES, "bad d_code");
9304717628eSXin LI 
9314717628eSXin LI             send_code(s, code, dtree);       /* send the distance code */
9324717628eSXin LI             extra = extra_dbits[code];
9334717628eSXin LI             if (extra != 0) {
9344717628eSXin LI                 dist -= (unsigned)base_dist[code];
9354717628eSXin LI                 send_bits(s, dist, extra);   /* send the extra distance bits */
9364717628eSXin LI             }
9374717628eSXin LI         } /* literal or match pair ? */
9384717628eSXin LI 
939*6255c67cSXin LI         /* Check for no overlay of pending_buf on needed symbols */
940*6255c67cSXin LI #ifdef LIT_MEM
941*6255c67cSXin LI         Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow");
942*6255c67cSXin LI #else
9434717628eSXin LI         Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
944*6255c67cSXin LI #endif
9454717628eSXin LI 
9464717628eSXin LI     } while (sx < s->sym_next);
9474717628eSXin LI 
9484717628eSXin LI     send_code(s, END_BLOCK, ltree);
9494717628eSXin LI }
9504717628eSXin LI 
9514717628eSXin LI /* ===========================================================================
9524717628eSXin LI  * Check if the data type is TEXT or BINARY, using the following algorithm:
9534717628eSXin LI  * - TEXT if the two conditions below are satisfied:
9544717628eSXin LI  *    a) There are no non-portable control characters belonging to the
9554717628eSXin LI  *       "block list" (0..6, 14..25, 28..31).
9564717628eSXin LI  *    b) There is at least one printable character belonging to the
9574717628eSXin LI  *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
9584717628eSXin LI  * - BINARY otherwise.
9594717628eSXin LI  * - The following partially-portable control characters form a
9604717628eSXin LI  *   "gray list" that is ignored in this detection algorithm:
9614717628eSXin LI  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
9624717628eSXin LI  * IN assertion: the fields Freq of dyn_ltree are set.
9634717628eSXin LI  */
detect_data_type(deflate_state * s)9644717628eSXin LI local int detect_data_type(deflate_state *s) {
9654717628eSXin LI     /* block_mask is the bit mask of block-listed bytes
9664717628eSXin LI      * set bits 0..6, 14..25, and 28..31
9674717628eSXin LI      * 0xf3ffc07f = binary 11110011111111111100000001111111
9684717628eSXin LI      */
9694717628eSXin LI     unsigned long block_mask = 0xf3ffc07fUL;
9704717628eSXin LI     int n;
9714717628eSXin LI 
9724717628eSXin LI     /* Check for non-textual ("block-listed") bytes. */
9734717628eSXin LI     for (n = 0; n <= 31; n++, block_mask >>= 1)
9744717628eSXin LI         if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
9754717628eSXin LI             return Z_BINARY;
9764717628eSXin LI 
9774717628eSXin LI     /* Check for textual ("allow-listed") bytes. */
9784717628eSXin LI     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
9794717628eSXin LI             || s->dyn_ltree[13].Freq != 0)
9804717628eSXin LI         return Z_TEXT;
9814717628eSXin LI     for (n = 32; n < LITERALS; n++)
9824717628eSXin LI         if (s->dyn_ltree[n].Freq != 0)
9834717628eSXin LI             return Z_TEXT;
9844717628eSXin LI 
9854717628eSXin LI     /* There are no "block-listed" or "allow-listed" bytes:
9864717628eSXin LI      * this stream either is empty or has tolerated ("gray-listed") bytes only.
9874717628eSXin LI      */
9884717628eSXin LI     return Z_BINARY;
9894717628eSXin LI }
9904717628eSXin LI 
9914717628eSXin LI /* ===========================================================================
992c9083b85SXin LI  * Determine the best encoding for the current block: dynamic trees, static
993c9083b85SXin LI  * trees or store, and write out the encoded block.
994c9083b85SXin LI  */
_tr_flush_block(deflate_state * s,charf * buf,ulg stored_len,int last)9954717628eSXin LI void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
9964717628eSXin LI                                    ulg stored_len, int last) {
997c9083b85SXin LI     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
998c9083b85SXin LI     int max_blindex = 0;  /* index of last bit length code of non zero freq */
999c9083b85SXin LI 
1000c9083b85SXin LI     /* Build the Huffman trees unless a stored block is forced */
1001c9083b85SXin LI     if (s->level > 0) {
1002c9083b85SXin LI 
1003c9083b85SXin LI         /* Check if the file is binary or text */
1004c9083b85SXin LI         if (s->strm->data_type == Z_UNKNOWN)
1005c9083b85SXin LI             s->strm->data_type = detect_data_type(s);
1006c9083b85SXin LI 
1007c9083b85SXin LI         /* Construct the literal and distance trees */
1008c9083b85SXin LI         build_tree(s, (tree_desc *)(&(s->l_desc)));
1009c9083b85SXin LI         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
1010c9083b85SXin LI                 s->static_len));
1011c9083b85SXin LI 
1012c9083b85SXin LI         build_tree(s, (tree_desc *)(&(s->d_desc)));
1013c9083b85SXin LI         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
1014c9083b85SXin LI                 s->static_len));
1015c9083b85SXin LI         /* At this point, opt_len and static_len are the total bit lengths of
1016c9083b85SXin LI          * the compressed block data, excluding the tree representations.
1017c9083b85SXin LI          */
1018c9083b85SXin LI 
1019c9083b85SXin LI         /* Build the bit length tree for the above two trees, and get the index
1020c9083b85SXin LI          * in bl_order of the last bit length code to send.
1021c9083b85SXin LI          */
1022c9083b85SXin LI         max_blindex = build_bl_tree(s);
1023c9083b85SXin LI 
1024c9083b85SXin LI         /* Determine the best encoding. Compute the block lengths in bytes. */
1025c9083b85SXin LI         opt_lenb = (s->opt_len + 3 + 7) >> 3;
1026c9083b85SXin LI         static_lenb = (s->static_len + 3 + 7) >> 3;
1027c9083b85SXin LI 
1028c9083b85SXin LI         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
1029c9083b85SXin LI                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
1030cd882207SXin LI                 s->sym_next / 3));
1031c9083b85SXin LI 
1032e37bb444SXin LI #ifndef FORCE_STATIC
1033e37bb444SXin LI         if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
1034e37bb444SXin LI #endif
1035e37bb444SXin LI             opt_lenb = static_lenb;
1036c9083b85SXin LI 
1037c9083b85SXin LI     } else {
1038c9083b85SXin LI         Assert(buf != (char*)0, "lost buf");
1039c9083b85SXin LI         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
1040c9083b85SXin LI     }
1041c9083b85SXin LI 
1042c9083b85SXin LI #ifdef FORCE_STORED
1043c9083b85SXin LI     if (buf != (char*)0) { /* force stored block */
1044c9083b85SXin LI #else
1045c9083b85SXin LI     if (stored_len + 4 <= opt_lenb && buf != (char*)0) {
1046c9083b85SXin LI                        /* 4: two words for the lengths */
1047c9083b85SXin LI #endif
1048c9083b85SXin LI         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1049c9083b85SXin LI          * Otherwise we can't have processed more than WSIZE input bytes since
1050c9083b85SXin LI          * the last block flush, because compression would have been
1051c9083b85SXin LI          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1052c9083b85SXin LI          * transform a block into a stored block.
1053c9083b85SXin LI          */
1054c9083b85SXin LI         _tr_stored_block(s, buf, stored_len, last);
1055c9083b85SXin LI 
1056e37bb444SXin LI     } else if (static_lenb == opt_lenb) {
1057c9083b85SXin LI         send_bits(s, (STATIC_TREES<<1) + last, 3);
1058c9083b85SXin LI         compress_block(s, (const ct_data *)static_ltree,
1059c9083b85SXin LI                        (const ct_data *)static_dtree);
1060c9083b85SXin LI #ifdef ZLIB_DEBUG
1061c9083b85SXin LI         s->compressed_len += 3 + s->static_len;
1062c9083b85SXin LI #endif
1063c9083b85SXin LI     } else {
1064c9083b85SXin LI         send_bits(s, (DYN_TREES<<1) + last, 3);
1065c9083b85SXin LI         send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1,
1066c9083b85SXin LI                        max_blindex + 1);
1067c9083b85SXin LI         compress_block(s, (const ct_data *)s->dyn_ltree,
1068c9083b85SXin LI                        (const ct_data *)s->dyn_dtree);
1069c9083b85SXin LI #ifdef ZLIB_DEBUG
1070c9083b85SXin LI         s->compressed_len += 3 + s->opt_len;
1071c9083b85SXin LI #endif
1072c9083b85SXin LI     }
1073c9083b85SXin LI     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1074c9083b85SXin LI     /* The above check is made mod 2^32, for files larger than 512 MB
1075c9083b85SXin LI      * and uLong implemented on 32 bits.
1076c9083b85SXin LI      */
1077c9083b85SXin LI     init_block(s);
1078c9083b85SXin LI 
1079c9083b85SXin LI     if (last) {
1080c9083b85SXin LI         bi_windup(s);
1081c9083b85SXin LI #ifdef ZLIB_DEBUG
1082c9083b85SXin LI         s->compressed_len += 7;  /* align on byte boundary */
1083c9083b85SXin LI #endif
1084c9083b85SXin LI     }
1085c9083b85SXin LI     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3,
1086c9083b85SXin LI            s->compressed_len - 7*last));
1087c9083b85SXin LI }
1088c9083b85SXin LI 
1089c9083b85SXin LI /* ===========================================================================
1090c9083b85SXin LI  * Save the match info and tally the frequency counts. Return true if
1091c9083b85SXin LI  * the current block must be flushed.
1092c9083b85SXin LI  */
10934717628eSXin LI int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) {
1094*6255c67cSXin LI #ifdef LIT_MEM
1095*6255c67cSXin LI     s->d_buf[s->sym_next] = (ush)dist;
1096*6255c67cSXin LI     s->l_buf[s->sym_next++] = (uch)lc;
1097*6255c67cSXin LI #else
1098e37bb444SXin LI     s->sym_buf[s->sym_next++] = (uch)dist;
1099e37bb444SXin LI     s->sym_buf[s->sym_next++] = (uch)(dist >> 8);
1100e37bb444SXin LI     s->sym_buf[s->sym_next++] = (uch)lc;
1101*6255c67cSXin LI #endif
1102c9083b85SXin LI     if (dist == 0) {
1103c9083b85SXin LI         /* lc is the unmatched char */
1104c9083b85SXin LI         s->dyn_ltree[lc].Freq++;
1105c9083b85SXin LI     } else {
1106c9083b85SXin LI         s->matches++;
1107c9083b85SXin LI         /* Here, lc is the match length - MIN_MATCH */
1108c9083b85SXin LI         dist--;             /* dist = match distance - 1 */
1109c9083b85SXin LI         Assert((ush)dist < (ush)MAX_DIST(s) &&
1110c9083b85SXin LI                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1111c9083b85SXin LI                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1112c9083b85SXin LI 
1113c9083b85SXin LI         s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++;
1114c9083b85SXin LI         s->dyn_dtree[d_code(dist)].Freq++;
1115c9083b85SXin LI     }
1116cd882207SXin LI     return (s->sym_next == s->sym_end);
1117c9083b85SXin LI }
1118