xref: /openbsd-src/gnu/usr.bin/perl/cpan/Compress-Raw-Zlib/zlib-src/trees.c (revision 3d61058aa5c692477b6d18acfbbdb653a9930ff9)
1b39c5158Smillert /* trees.c -- output deflated data using Huffman coding
2*3d61058aSafresh1  * Copyright (C) 1995-2024 Jean-loup Gailly
348950c12Ssthen  * detect_data_type() function provided freely by Cosmin Truta, 2006
4b39c5158Smillert  * For conditions of distribution and use, see copyright notice in zlib.h
5b39c5158Smillert  */
6b39c5158Smillert 
7b39c5158Smillert /*
8b39c5158Smillert  *  ALGORITHM
9b39c5158Smillert  *
10b39c5158Smillert  *      The "deflation" process uses several Huffman trees. The more
11b39c5158Smillert  *      common source values are represented by shorter bit sequences.
12b39c5158Smillert  *
13b39c5158Smillert  *      Each code tree is stored in a compressed form which is itself
14b39c5158Smillert  * a Huffman encoding of the lengths of all the code strings (in
15b39c5158Smillert  * ascending order by source values).  The actual code strings are
16b39c5158Smillert  * reconstructed from the lengths in the inflate process, as described
17b39c5158Smillert  * in the deflate specification.
18b39c5158Smillert  *
19b39c5158Smillert  *  REFERENCES
20b39c5158Smillert  *
21b39c5158Smillert  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
22b39c5158Smillert  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
23b39c5158Smillert  *
24b39c5158Smillert  *      Storer, James A.
25b39c5158Smillert  *          Data Compression:  Methods and Theory, pp. 49-50.
26b39c5158Smillert  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
27b39c5158Smillert  *
28b39c5158Smillert  *      Sedgewick, R.
29b39c5158Smillert  *          Algorithms, p290.
30b39c5158Smillert  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
31b39c5158Smillert  */
32b39c5158Smillert 
33b39c5158Smillert /* @(#) $Id$ */
34b39c5158Smillert 
35b39c5158Smillert /* #define GEN_TREES_H */
36b39c5158Smillert 
37b39c5158Smillert #include "deflate.h"
38b39c5158Smillert 
399f11ffb7Safresh1 #ifdef ZLIB_DEBUG
40b39c5158Smillert #  include <ctype.h>
41b39c5158Smillert #endif
42b39c5158Smillert 
43b39c5158Smillert /* ===========================================================================
44b39c5158Smillert  * Constants
45b39c5158Smillert  */
46b39c5158Smillert 
47b39c5158Smillert #define MAX_BL_BITS 7
48b39c5158Smillert /* Bit length codes must not exceed MAX_BL_BITS bits */
49b39c5158Smillert 
50b39c5158Smillert #define END_BLOCK 256
51b39c5158Smillert /* end of block literal code */
52b39c5158Smillert 
53b39c5158Smillert #define REP_3_6      16
54b39c5158Smillert /* repeat previous bit length 3-6 times (2 bits of repeat count) */
55b39c5158Smillert 
56b39c5158Smillert #define REPZ_3_10    17
57b39c5158Smillert /* repeat a zero length 3-10 times  (3 bits of repeat count) */
58b39c5158Smillert 
59b39c5158Smillert #define REPZ_11_138  18
60b39c5158Smillert /* repeat a zero length 11-138 times  (7 bits of repeat count) */
61b39c5158Smillert 
62b39c5158Smillert local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
63b39c5158Smillert    = {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};
64b39c5158Smillert 
65b39c5158Smillert local const int extra_dbits[D_CODES] /* extra bits for each distance code */
66b39c5158Smillert    = {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};
67b39c5158Smillert 
68b39c5158Smillert local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
69b39c5158Smillert    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
70b39c5158Smillert 
71b39c5158Smillert local const uch bl_order[BL_CODES]
72b39c5158Smillert    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
73b39c5158Smillert /* The lengths of the bit length codes are sent in order of decreasing
74b39c5158Smillert  * probability, to avoid transmitting the lengths for unused bit length codes.
75b39c5158Smillert  */
76b39c5158Smillert 
77b39c5158Smillert /* ===========================================================================
78b39c5158Smillert  * Local data. These are initialized only once.
79b39c5158Smillert  */
80b39c5158Smillert 
81b39c5158Smillert #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
82b39c5158Smillert 
83b39c5158Smillert #if defined(GEN_TREES_H) || !defined(STDC)
84b39c5158Smillert /* non ANSI compilers may not accept trees.h */
85b39c5158Smillert 
86b39c5158Smillert local ct_data static_ltree[L_CODES+2];
87b39c5158Smillert /* The static literal tree. Since the bit lengths are imposed, there is no
88b39c5158Smillert  * need for the L_CODES extra codes used during heap construction. However
89b39c5158Smillert  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
90b39c5158Smillert  * below).
91b39c5158Smillert  */
92b39c5158Smillert 
93b39c5158Smillert local ct_data static_dtree[D_CODES];
94b39c5158Smillert /* The static distance tree. (Actually a trivial tree since all codes use
95b39c5158Smillert  * 5 bits.)
96b39c5158Smillert  */
97b39c5158Smillert 
98b39c5158Smillert uch _dist_code[DIST_CODE_LEN];
99b39c5158Smillert /* Distance codes. The first 256 values correspond to the distances
100b39c5158Smillert  * 3 .. 258, the last 256 values correspond to the top 8 bits of
101b39c5158Smillert  * the 15 bit distances.
102b39c5158Smillert  */
103b39c5158Smillert 
104b39c5158Smillert uch _length_code[MAX_MATCH-MIN_MATCH+1];
105b39c5158Smillert /* length code for each normalized match length (0 == MIN_MATCH) */
106b39c5158Smillert 
107b39c5158Smillert local int base_length[LENGTH_CODES];
108b39c5158Smillert /* First normalized length for each code (0 = MIN_MATCH) */
109b39c5158Smillert 
110b39c5158Smillert local int base_dist[D_CODES];
111b39c5158Smillert /* First normalized distance for each code (0 = distance of 1) */
112b39c5158Smillert 
113b39c5158Smillert #else
114b39c5158Smillert #  include "trees.h"
115b39c5158Smillert #endif /* GEN_TREES_H */
116b39c5158Smillert 
117b39c5158Smillert struct static_tree_desc_s {
118b39c5158Smillert     const ct_data *static_tree;  /* static tree or NULL */
119b39c5158Smillert     const intf *extra_bits;      /* extra bits for each code or NULL */
120b39c5158Smillert     int     extra_base;          /* base index for extra_bits */
121b39c5158Smillert     int     elems;               /* max number of elements in the tree */
122b39c5158Smillert     int     max_length;          /* max bit length for the codes */
123b39c5158Smillert };
124b39c5158Smillert 
125*3d61058aSafresh1 #ifdef NO_INIT_GLOBAL_POINTERS
126*3d61058aSafresh1 #  define TCONST
127*3d61058aSafresh1 #else
128*3d61058aSafresh1 #  define TCONST const
129*3d61058aSafresh1 #endif
130*3d61058aSafresh1 
131*3d61058aSafresh1 local TCONST static_tree_desc static_l_desc =
132b39c5158Smillert {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
133b39c5158Smillert 
134*3d61058aSafresh1 local TCONST static_tree_desc static_d_desc =
135b39c5158Smillert {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
136b39c5158Smillert 
137*3d61058aSafresh1 local TCONST static_tree_desc static_bl_desc =
138b39c5158Smillert {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
139b39c5158Smillert 
140b39c5158Smillert /* ===========================================================================
141*3d61058aSafresh1  * Output a short LSB first on the stream.
142*3d61058aSafresh1  * IN assertion: there is enough room in pendingBuf.
143b39c5158Smillert  */
144*3d61058aSafresh1 #define put_short(s, w) { \
145*3d61058aSafresh1     put_byte(s, (uch)((w) & 0xff)); \
146*3d61058aSafresh1     put_byte(s, (uch)((ush)(w) >> 8)); \
147*3d61058aSafresh1 }
148b39c5158Smillert 
149*3d61058aSafresh1 /* ===========================================================================
150*3d61058aSafresh1  * Reverse the first len bits of a code, using straightforward code (a faster
151*3d61058aSafresh1  * method would use a table)
152*3d61058aSafresh1  * IN assertion: 1 <= len <= 15
153*3d61058aSafresh1  */
154*3d61058aSafresh1 local unsigned bi_reverse(unsigned code, int len) {
155*3d61058aSafresh1     register unsigned res = 0;
156*3d61058aSafresh1     do {
157*3d61058aSafresh1         res |= code & 1;
158*3d61058aSafresh1         code >>= 1, res <<= 1;
159*3d61058aSafresh1     } while (--len > 0);
160*3d61058aSafresh1     return res >> 1;
161*3d61058aSafresh1 }
162*3d61058aSafresh1 
163*3d61058aSafresh1 /* ===========================================================================
164*3d61058aSafresh1  * Flush the bit buffer, keeping at most 7 bits in it.
165*3d61058aSafresh1  */
166*3d61058aSafresh1 local void bi_flush(deflate_state *s) {
167*3d61058aSafresh1     if (s->bi_valid == 16) {
168*3d61058aSafresh1         put_short(s, s->bi_buf);
169*3d61058aSafresh1         s->bi_buf = 0;
170*3d61058aSafresh1         s->bi_valid = 0;
171*3d61058aSafresh1     } else if (s->bi_valid >= 8) {
172*3d61058aSafresh1         put_byte(s, (Byte)s->bi_buf);
173*3d61058aSafresh1         s->bi_buf >>= 8;
174*3d61058aSafresh1         s->bi_valid -= 8;
175*3d61058aSafresh1     }
176*3d61058aSafresh1 }
177*3d61058aSafresh1 
178*3d61058aSafresh1 /* ===========================================================================
179*3d61058aSafresh1  * Flush the bit buffer and align the output on a byte boundary
180*3d61058aSafresh1  */
181*3d61058aSafresh1 local void bi_windup(deflate_state *s) {
182*3d61058aSafresh1     if (s->bi_valid > 8) {
183*3d61058aSafresh1         put_short(s, s->bi_buf);
184*3d61058aSafresh1     } else if (s->bi_valid > 0) {
185*3d61058aSafresh1         put_byte(s, (Byte)s->bi_buf);
186*3d61058aSafresh1     }
187*3d61058aSafresh1     s->bi_buf = 0;
188*3d61058aSafresh1     s->bi_valid = 0;
189*3d61058aSafresh1 #ifdef ZLIB_DEBUG
190*3d61058aSafresh1     s->bits_sent = (s->bits_sent + 7) & ~7;
191*3d61058aSafresh1 #endif
192*3d61058aSafresh1 }
193*3d61058aSafresh1 
194*3d61058aSafresh1 /* ===========================================================================
195*3d61058aSafresh1  * Generate the codes for a given tree and bit counts (which need not be
196*3d61058aSafresh1  * optimal).
197*3d61058aSafresh1  * IN assertion: the array bl_count contains the bit length statistics for
198*3d61058aSafresh1  * the given tree and the field len is set for all tree elements.
199*3d61058aSafresh1  * OUT assertion: the field code is set for all tree elements of non
200*3d61058aSafresh1  *     zero code length.
201*3d61058aSafresh1  */
202*3d61058aSafresh1 local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) {
203*3d61058aSafresh1     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
204*3d61058aSafresh1     unsigned code = 0;         /* running code value */
205*3d61058aSafresh1     int bits;                  /* bit index */
206*3d61058aSafresh1     int n;                     /* code index */
207*3d61058aSafresh1 
208*3d61058aSafresh1     /* The distribution counts are first used to generate the code values
209*3d61058aSafresh1      * without bit reversal.
210*3d61058aSafresh1      */
211*3d61058aSafresh1     for (bits = 1; bits <= MAX_BITS; bits++) {
212*3d61058aSafresh1         code = (code + bl_count[bits - 1]) << 1;
213*3d61058aSafresh1         next_code[bits] = (ush)code;
214*3d61058aSafresh1     }
215*3d61058aSafresh1     /* Check that the bit counts in bl_count are consistent. The last code
216*3d61058aSafresh1      * must be all ones.
217*3d61058aSafresh1      */
218*3d61058aSafresh1     Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
219*3d61058aSafresh1             "inconsistent bit counts");
220*3d61058aSafresh1     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
221*3d61058aSafresh1 
222*3d61058aSafresh1     for (n = 0;  n <= max_code; n++) {
223*3d61058aSafresh1         int len = tree[n].Len;
224*3d61058aSafresh1         if (len == 0) continue;
225*3d61058aSafresh1         /* Now reverse the bits */
226*3d61058aSafresh1         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
227*3d61058aSafresh1 
228*3d61058aSafresh1         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
229*3d61058aSafresh1             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1));
230*3d61058aSafresh1     }
231*3d61058aSafresh1 }
232b39c5158Smillert 
233b39c5158Smillert #ifdef GEN_TREES_H
234*3d61058aSafresh1 local void gen_trees_header(void);
235b39c5158Smillert #endif
236b39c5158Smillert 
2379f11ffb7Safresh1 #ifndef ZLIB_DEBUG
238b39c5158Smillert #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
239b39c5158Smillert    /* Send a code of the given tree. c and tree must not have side effects */
240b39c5158Smillert 
2419f11ffb7Safresh1 #else /* !ZLIB_DEBUG */
242b39c5158Smillert #  define send_code(s, c, tree) \
243b39c5158Smillert      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
244b39c5158Smillert        send_bits(s, tree[c].Code, tree[c].Len); }
245b39c5158Smillert #endif
246b39c5158Smillert 
247b39c5158Smillert /* ===========================================================================
248b39c5158Smillert  * Send a value on a given number of bits.
249b39c5158Smillert  * IN assertion: length <= 16 and value fits in length bits.
250b39c5158Smillert  */
2519f11ffb7Safresh1 #ifdef ZLIB_DEBUG
252*3d61058aSafresh1 local void send_bits(deflate_state *s, int value, int length) {
253b39c5158Smillert     Tracevv((stderr," l %2d v %4x ", length, value));
254b39c5158Smillert     Assert(length > 0 && length <= 15, "invalid length");
255b39c5158Smillert     s->bits_sent += (ulg)length;
256b39c5158Smillert 
257b39c5158Smillert     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
258b39c5158Smillert      * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid))
259b39c5158Smillert      * unused bits in value.
260b39c5158Smillert      */
261b39c5158Smillert     if (s->bi_valid > (int)Buf_size - length) {
26248950c12Ssthen         s->bi_buf |= (ush)value << s->bi_valid;
263b39c5158Smillert         put_short(s, s->bi_buf);
264b39c5158Smillert         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
265b39c5158Smillert         s->bi_valid += length - Buf_size;
266b39c5158Smillert     } else {
26748950c12Ssthen         s->bi_buf |= (ush)value << s->bi_valid;
268b39c5158Smillert         s->bi_valid += length;
269b39c5158Smillert     }
270b39c5158Smillert }
2719f11ffb7Safresh1 #else /* !ZLIB_DEBUG */
272b39c5158Smillert 
273b39c5158Smillert #define send_bits(s, value, length) \
274b39c5158Smillert { int len = length;\
275b39c5158Smillert   if (s->bi_valid > (int)Buf_size - len) {\
2769f11ffb7Safresh1     int val = (int)value;\
27748950c12Ssthen     s->bi_buf |= (ush)val << s->bi_valid;\
278b39c5158Smillert     put_short(s, s->bi_buf);\
279b39c5158Smillert     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
280b39c5158Smillert     s->bi_valid += len - Buf_size;\
281b39c5158Smillert   } else {\
28248950c12Ssthen     s->bi_buf |= (ush)(value) << s->bi_valid;\
283b39c5158Smillert     s->bi_valid += len;\
284b39c5158Smillert   }\
285b39c5158Smillert }
2869f11ffb7Safresh1 #endif /* ZLIB_DEBUG */
287b39c5158Smillert 
288b39c5158Smillert 
289b39c5158Smillert /* the arguments must not have side effects */
290b39c5158Smillert 
291b39c5158Smillert /* ===========================================================================
292b39c5158Smillert  * Initialize the various 'constant' tables.
293b39c5158Smillert  */
294*3d61058aSafresh1 local void tr_static_init(void) {
295b39c5158Smillert #if defined(GEN_TREES_H) || !defined(STDC)
296b39c5158Smillert     static int static_init_done = 0;
297b39c5158Smillert     int n;        /* iterates over tree elements */
298b39c5158Smillert     int bits;     /* bit counter */
299b39c5158Smillert     int length;   /* length value */
300b39c5158Smillert     int code;     /* code value */
301b39c5158Smillert     int dist;     /* distance index */
302b39c5158Smillert     ush bl_count[MAX_BITS+1];
303b39c5158Smillert     /* number of codes at each bit length for an optimal tree */
304b39c5158Smillert 
305b39c5158Smillert     if (static_init_done) return;
306b39c5158Smillert 
307b39c5158Smillert     /* For some embedded targets, global variables are not initialized: */
30848950c12Ssthen #ifdef NO_INIT_GLOBAL_POINTERS
309b39c5158Smillert     static_l_desc.static_tree = static_ltree;
310b39c5158Smillert     static_l_desc.extra_bits = extra_lbits;
311b39c5158Smillert     static_d_desc.static_tree = static_dtree;
312b39c5158Smillert     static_d_desc.extra_bits = extra_dbits;
313b39c5158Smillert     static_bl_desc.extra_bits = extra_blbits;
31448950c12Ssthen #endif
315b39c5158Smillert 
316b39c5158Smillert     /* Initialize the mapping length (0..255) -> length code (0..28) */
317b39c5158Smillert     length = 0;
318b39c5158Smillert     for (code = 0; code < LENGTH_CODES-1; code++) {
319b39c5158Smillert         base_length[code] = length;
320b39c5158Smillert         for (n = 0; n < (1 << extra_lbits[code]); n++) {
321b39c5158Smillert             _length_code[length++] = (uch)code;
322b39c5158Smillert         }
323b39c5158Smillert     }
324b39c5158Smillert     Assert (length == 256, "tr_static_init: length != 256");
325b39c5158Smillert     /* Note that the length 255 (match length 258) can be represented
326b39c5158Smillert      * in two different ways: code 284 + 5 bits or code 285, so we
327b39c5158Smillert      * overwrite length_code[255] to use the best encoding:
328b39c5158Smillert      */
329b39c5158Smillert     _length_code[length - 1] = (uch)code;
330b39c5158Smillert 
331b39c5158Smillert     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
332b39c5158Smillert     dist = 0;
333b39c5158Smillert     for (code = 0 ; code < 16; code++) {
334b39c5158Smillert         base_dist[code] = dist;
335b39c5158Smillert         for (n = 0; n < (1 << extra_dbits[code]); n++) {
336b39c5158Smillert             _dist_code[dist++] = (uch)code;
337b39c5158Smillert         }
338b39c5158Smillert     }
339b39c5158Smillert     Assert (dist == 256, "tr_static_init: dist != 256");
340b39c5158Smillert     dist >>= 7; /* from now on, all distances are divided by 128 */
341b39c5158Smillert     for ( ; code < D_CODES; code++) {
342b39c5158Smillert         base_dist[code] = dist << 7;
343b39c5158Smillert         for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
344b39c5158Smillert             _dist_code[256 + dist++] = (uch)code;
345b39c5158Smillert         }
346b39c5158Smillert     }
347b39c5158Smillert     Assert (dist == 256, "tr_static_init: 256 + dist != 512");
348b39c5158Smillert 
349b39c5158Smillert     /* Construct the codes of the static literal tree */
350b39c5158Smillert     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
351b39c5158Smillert     n = 0;
352b39c5158Smillert     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
353b39c5158Smillert     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
354b39c5158Smillert     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
355b39c5158Smillert     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
356b39c5158Smillert     /* Codes 286 and 287 do not exist, but we must include them in the
357b39c5158Smillert      * tree construction to get a canonical Huffman tree (longest code
358b39c5158Smillert      * all ones)
359b39c5158Smillert      */
360b39c5158Smillert     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
361b39c5158Smillert 
362b39c5158Smillert     /* The static distance tree is trivial: */
363b39c5158Smillert     for (n = 0; n < D_CODES; n++) {
364b39c5158Smillert         static_dtree[n].Len = 5;
365b39c5158Smillert         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
366b39c5158Smillert     }
367b39c5158Smillert     static_init_done = 1;
368b39c5158Smillert 
369b39c5158Smillert #  ifdef GEN_TREES_H
370b39c5158Smillert     gen_trees_header();
371b39c5158Smillert #  endif
372b39c5158Smillert #endif /* defined(GEN_TREES_H) || !defined(STDC) */
373b39c5158Smillert }
374b39c5158Smillert 
375b39c5158Smillert /* ===========================================================================
376e0680481Safresh1  * Generate the file trees.h describing the static trees.
377b39c5158Smillert  */
378b39c5158Smillert #ifdef GEN_TREES_H
3799f11ffb7Safresh1 #  ifndef ZLIB_DEBUG
380b39c5158Smillert #    include <stdio.h>
381b39c5158Smillert #  endif
382b39c5158Smillert 
383b39c5158Smillert #  define SEPARATOR(i, last, width) \
384b39c5158Smillert       ((i) == (last)? "\n};\n\n" :    \
385b39c5158Smillert        ((i) % (width) == (width) - 1 ? ",\n" : ", "))
386b39c5158Smillert 
387*3d61058aSafresh1 void gen_trees_header(void) {
388b39c5158Smillert     FILE *header = fopen("trees.h", "w");
389b39c5158Smillert     int i;
390b39c5158Smillert 
391b39c5158Smillert     Assert (header != NULL, "Can't open trees.h");
392b39c5158Smillert     fprintf(header,
393b39c5158Smillert             "/* header created automatically with -DGEN_TREES_H */\n\n");
394b39c5158Smillert 
395b39c5158Smillert     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
396b39c5158Smillert     for (i = 0; i < L_CODES+2; i++) {
397b39c5158Smillert         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
398b39c5158Smillert                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
399b39c5158Smillert     }
400b39c5158Smillert 
401b39c5158Smillert     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
402b39c5158Smillert     for (i = 0; i < D_CODES; i++) {
403b39c5158Smillert         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
404b39c5158Smillert                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
405b39c5158Smillert     }
406b39c5158Smillert 
40748950c12Ssthen     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
408b39c5158Smillert     for (i = 0; i < DIST_CODE_LEN; i++) {
409b39c5158Smillert         fprintf(header, "%2u%s", _dist_code[i],
410b39c5158Smillert                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
411b39c5158Smillert     }
412b39c5158Smillert 
41348950c12Ssthen     fprintf(header,
41448950c12Ssthen         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
415b39c5158Smillert     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
416b39c5158Smillert         fprintf(header, "%2u%s", _length_code[i],
417b39c5158Smillert                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
418b39c5158Smillert     }
419b39c5158Smillert 
420b39c5158Smillert     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
421b39c5158Smillert     for (i = 0; i < LENGTH_CODES; i++) {
422b39c5158Smillert         fprintf(header, "%1u%s", base_length[i],
423b39c5158Smillert                 SEPARATOR(i, LENGTH_CODES-1, 20));
424b39c5158Smillert     }
425b39c5158Smillert 
426b39c5158Smillert     fprintf(header, "local const int base_dist[D_CODES] = {\n");
427b39c5158Smillert     for (i = 0; i < D_CODES; i++) {
428b39c5158Smillert         fprintf(header, "%5u%s", base_dist[i],
429b39c5158Smillert                 SEPARATOR(i, D_CODES-1, 10));
430b39c5158Smillert     }
431b39c5158Smillert 
432b39c5158Smillert     fclose(header);
433b39c5158Smillert }
434b39c5158Smillert #endif /* GEN_TREES_H */
435b39c5158Smillert 
436b39c5158Smillert /* ===========================================================================
437*3d61058aSafresh1  * Initialize a new block.
438*3d61058aSafresh1  */
439*3d61058aSafresh1 local void init_block(deflate_state *s) {
440*3d61058aSafresh1     int n; /* iterates over tree elements */
441*3d61058aSafresh1 
442*3d61058aSafresh1     /* Initialize the trees. */
443*3d61058aSafresh1     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
444*3d61058aSafresh1     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
445*3d61058aSafresh1     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
446*3d61058aSafresh1 
447*3d61058aSafresh1     s->dyn_ltree[END_BLOCK].Freq = 1;
448*3d61058aSafresh1     s->opt_len = s->static_len = 0L;
449*3d61058aSafresh1     s->sym_next = s->matches = 0;
450*3d61058aSafresh1 }
451*3d61058aSafresh1 
452*3d61058aSafresh1 /* ===========================================================================
453b39c5158Smillert  * Initialize the tree data structures for a new zlib stream.
454b39c5158Smillert  */
455*3d61058aSafresh1 void ZLIB_INTERNAL _tr_init(deflate_state *s) {
456b39c5158Smillert     tr_static_init();
457b39c5158Smillert 
458b39c5158Smillert     s->l_desc.dyn_tree = s->dyn_ltree;
459b39c5158Smillert     s->l_desc.stat_desc = &static_l_desc;
460b39c5158Smillert 
461b39c5158Smillert     s->d_desc.dyn_tree = s->dyn_dtree;
462b39c5158Smillert     s->d_desc.stat_desc = &static_d_desc;
463b39c5158Smillert 
464b39c5158Smillert     s->bl_desc.dyn_tree = s->bl_tree;
465b39c5158Smillert     s->bl_desc.stat_desc = &static_bl_desc;
466b39c5158Smillert 
467b39c5158Smillert     s->bi_buf = 0;
468b39c5158Smillert     s->bi_valid = 0;
4699f11ffb7Safresh1 #ifdef ZLIB_DEBUG
470b39c5158Smillert     s->compressed_len = 0L;
471b39c5158Smillert     s->bits_sent = 0L;
472b39c5158Smillert #endif
473b39c5158Smillert 
474b39c5158Smillert     /* Initialize the first block of the first file: */
475b39c5158Smillert     init_block(s);
476b39c5158Smillert }
477b39c5158Smillert 
478b39c5158Smillert #define SMALLEST 1
479b39c5158Smillert /* Index within the heap array of least frequent node in the Huffman tree */
480b39c5158Smillert 
481b39c5158Smillert 
482b39c5158Smillert /* ===========================================================================
483b39c5158Smillert  * Remove the smallest element from the heap and recreate the heap with
484b39c5158Smillert  * one less element. Updates heap and heap_len.
485b39c5158Smillert  */
486b39c5158Smillert #define pqremove(s, tree, top) \
487b39c5158Smillert {\
488b39c5158Smillert     top = s->heap[SMALLEST]; \
489b39c5158Smillert     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
490b39c5158Smillert     pqdownheap(s, tree, SMALLEST); \
491b39c5158Smillert }
492b39c5158Smillert 
493b39c5158Smillert /* ===========================================================================
494b39c5158Smillert  * Compares to subtrees, using the tree depth as tie breaker when
495b39c5158Smillert  * the subtrees have equal frequency. This minimizes the worst case length.
496b39c5158Smillert  */
497b39c5158Smillert #define smaller(tree, n, m, depth) \
498b39c5158Smillert    (tree[n].Freq < tree[m].Freq || \
499b39c5158Smillert    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
500b39c5158Smillert 
501b39c5158Smillert /* ===========================================================================
502b39c5158Smillert  * Restore the heap property by moving down the tree starting at node k,
503b39c5158Smillert  * exchanging a node with the smallest of its two sons if necessary, stopping
504b39c5158Smillert  * when the heap property is re-established (each father smaller than its
505b39c5158Smillert  * two sons).
506b39c5158Smillert  */
507*3d61058aSafresh1 local void pqdownheap(deflate_state *s, ct_data *tree, int k) {
508b39c5158Smillert     int v = s->heap[k];
509b39c5158Smillert     int j = k << 1;  /* left son of k */
510b39c5158Smillert     while (j <= s->heap_len) {
511b39c5158Smillert         /* Set j to the smallest of the two sons: */
512b39c5158Smillert         if (j < s->heap_len &&
513b39c5158Smillert             smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) {
514b39c5158Smillert             j++;
515b39c5158Smillert         }
516b39c5158Smillert         /* Exit if v is smaller than both sons */
517b39c5158Smillert         if (smaller(tree, v, s->heap[j], s->depth)) break;
518b39c5158Smillert 
519b39c5158Smillert         /* Exchange v with the smallest son */
520b39c5158Smillert         s->heap[k] = s->heap[j];  k = j;
521b39c5158Smillert 
522b39c5158Smillert         /* And continue down the tree, setting j to the left son of k */
523b39c5158Smillert         j <<= 1;
524b39c5158Smillert     }
525b39c5158Smillert     s->heap[k] = v;
526b39c5158Smillert }
527b39c5158Smillert 
528b39c5158Smillert /* ===========================================================================
529b39c5158Smillert  * Compute the optimal bit lengths for a tree and update the total bit length
530b39c5158Smillert  * for the current block.
531b39c5158Smillert  * IN assertion: the fields freq and dad are set, heap[heap_max] and
532b39c5158Smillert  *    above are the tree nodes sorted by increasing frequency.
533b39c5158Smillert  * OUT assertions: the field len is set to the optimal bit length, the
534b39c5158Smillert  *     array bl_count contains the frequencies for each bit length.
535b39c5158Smillert  *     The length opt_len is updated; static_len is also updated if stree is
536b39c5158Smillert  *     not null.
537b39c5158Smillert  */
538*3d61058aSafresh1 local void gen_bitlen(deflate_state *s, tree_desc *desc) {
539b39c5158Smillert     ct_data *tree        = desc->dyn_tree;
540b39c5158Smillert     int max_code         = desc->max_code;
541b39c5158Smillert     const ct_data *stree = desc->stat_desc->static_tree;
542b39c5158Smillert     const intf *extra    = desc->stat_desc->extra_bits;
543b39c5158Smillert     int base             = desc->stat_desc->extra_base;
544b39c5158Smillert     int max_length       = desc->stat_desc->max_length;
545b39c5158Smillert     int h;              /* heap index */
546b39c5158Smillert     int n, m;           /* iterate over the tree elements */
547b39c5158Smillert     int bits;           /* bit length */
548b39c5158Smillert     int xbits;          /* extra bits */
549b39c5158Smillert     ush f;              /* frequency */
550b39c5158Smillert     int overflow = 0;   /* number of elements with bit length too large */
551b39c5158Smillert 
552b39c5158Smillert     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
553b39c5158Smillert 
554b39c5158Smillert     /* In a first pass, compute the optimal bit lengths (which may
555b39c5158Smillert      * overflow in the case of the bit length tree).
556b39c5158Smillert      */
557b39c5158Smillert     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
558b39c5158Smillert 
559b39c5158Smillert     for (h = s->heap_max + 1; h < HEAP_SIZE; h++) {
560b39c5158Smillert         n = s->heap[h];
561b39c5158Smillert         bits = tree[tree[n].Dad].Len + 1;
562b39c5158Smillert         if (bits > max_length) bits = max_length, overflow++;
563b39c5158Smillert         tree[n].Len = (ush)bits;
564b39c5158Smillert         /* We overwrite tree[n].Dad which is no longer needed */
565b39c5158Smillert 
566b39c5158Smillert         if (n > max_code) continue; /* not a leaf node */
567b39c5158Smillert 
568b39c5158Smillert         s->bl_count[bits]++;
569b39c5158Smillert         xbits = 0;
570b39c5158Smillert         if (n >= base) xbits = extra[n - base];
571b39c5158Smillert         f = tree[n].Freq;
5729f11ffb7Safresh1         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
5739f11ffb7Safresh1         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
574b39c5158Smillert     }
575b39c5158Smillert     if (overflow == 0) return;
576b39c5158Smillert 
5779f11ffb7Safresh1     Tracev((stderr,"\nbit length overflow\n"));
578b39c5158Smillert     /* This happens for example on obj2 and pic of the Calgary corpus */
579b39c5158Smillert 
580b39c5158Smillert     /* Find the first bit length which could increase: */
581b39c5158Smillert     do {
582b39c5158Smillert         bits = max_length - 1;
583b39c5158Smillert         while (s->bl_count[bits] == 0) bits--;
584b39c5158Smillert         s->bl_count[bits]--;        /* move one leaf down the tree */
585b39c5158Smillert         s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */
586b39c5158Smillert         s->bl_count[max_length]--;
587b39c5158Smillert         /* The brother of the overflow item also moves one step up,
588b39c5158Smillert          * but this does not affect bl_count[max_length]
589b39c5158Smillert          */
590b39c5158Smillert         overflow -= 2;
591b39c5158Smillert     } while (overflow > 0);
592b39c5158Smillert 
593b39c5158Smillert     /* Now recompute all bit lengths, scanning in increasing frequency.
594b39c5158Smillert      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
595b39c5158Smillert      * lengths instead of fixing only the wrong ones. This idea is taken
596b39c5158Smillert      * from 'ar' written by Haruhiko Okumura.)
597b39c5158Smillert      */
598b39c5158Smillert     for (bits = max_length; bits != 0; bits--) {
599b39c5158Smillert         n = s->bl_count[bits];
600b39c5158Smillert         while (n != 0) {
601b39c5158Smillert             m = s->heap[--h];
602b39c5158Smillert             if (m > max_code) continue;
603b39c5158Smillert             if ((unsigned) tree[m].Len != (unsigned) bits) {
6049f11ffb7Safresh1                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
6059f11ffb7Safresh1                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
606b39c5158Smillert                 tree[m].Len = (ush)bits;
607b39c5158Smillert             }
608b39c5158Smillert             n--;
609b39c5158Smillert         }
610b39c5158Smillert     }
611b39c5158Smillert }
612b39c5158Smillert 
613*3d61058aSafresh1 #ifdef DUMP_BL_TREE
614*3d61058aSafresh1 #  include <stdio.h>
615*3d61058aSafresh1 #endif
616b39c5158Smillert 
617b39c5158Smillert /* ===========================================================================
618b39c5158Smillert  * Construct one Huffman tree and assigns the code bit strings and lengths.
619b39c5158Smillert  * Update the total bit length for the current block.
620b39c5158Smillert  * IN assertion: the field freq is set for all tree elements.
621b39c5158Smillert  * OUT assertions: the fields len and code are set to the optimal bit length
622b39c5158Smillert  *     and corresponding code. The length opt_len is updated; static_len is
623b39c5158Smillert  *     also updated if stree is not null. The field max_code is set.
624b39c5158Smillert  */
625*3d61058aSafresh1 local void build_tree(deflate_state *s, tree_desc *desc) {
626b39c5158Smillert     ct_data *tree         = desc->dyn_tree;
627b39c5158Smillert     const ct_data *stree  = desc->stat_desc->static_tree;
628b39c5158Smillert     int elems             = desc->stat_desc->elems;
629b39c5158Smillert     int n, m;          /* iterate over heap elements */
630b39c5158Smillert     int max_code = -1; /* largest code with non zero frequency */
631b39c5158Smillert     int node;          /* new node being created */
632b39c5158Smillert 
633b39c5158Smillert     /* Construct the initial heap, with least frequent element in
634b39c5158Smillert      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1].
635b39c5158Smillert      * heap[0] is not used.
636b39c5158Smillert      */
637b39c5158Smillert     s->heap_len = 0, s->heap_max = HEAP_SIZE;
638b39c5158Smillert 
639b39c5158Smillert     for (n = 0; n < elems; n++) {
640b39c5158Smillert         if (tree[n].Freq != 0) {
641b39c5158Smillert             s->heap[++(s->heap_len)] = max_code = n;
642b39c5158Smillert             s->depth[n] = 0;
643b39c5158Smillert         } else {
644b39c5158Smillert             tree[n].Len = 0;
645b39c5158Smillert         }
646b39c5158Smillert     }
647b39c5158Smillert 
648b39c5158Smillert     /* The pkzip format requires that at least one distance code exists,
649b39c5158Smillert      * and that at least one bit should be sent even if there is only one
650b39c5158Smillert      * possible code. So to avoid special checks later on we force at least
651b39c5158Smillert      * two codes of non zero frequency.
652b39c5158Smillert      */
653b39c5158Smillert     while (s->heap_len < 2) {
654b39c5158Smillert         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
655b39c5158Smillert         tree[node].Freq = 1;
656b39c5158Smillert         s->depth[node] = 0;
657b39c5158Smillert         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
658b39c5158Smillert         /* node is 0 or 1 so it does not have extra bits */
659b39c5158Smillert     }
660b39c5158Smillert     desc->max_code = max_code;
661b39c5158Smillert 
662b39c5158Smillert     /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree,
663b39c5158Smillert      * establish sub-heaps of increasing lengths:
664b39c5158Smillert      */
665b39c5158Smillert     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
666b39c5158Smillert 
667b39c5158Smillert     /* Construct the Huffman tree by repeatedly combining the least two
668b39c5158Smillert      * frequent nodes.
669b39c5158Smillert      */
670b39c5158Smillert     node = elems;              /* next internal node of the tree */
671b39c5158Smillert     do {
672b39c5158Smillert         pqremove(s, tree, n);  /* n = node of least frequency */
673b39c5158Smillert         m = s->heap[SMALLEST]; /* m = node of next least frequency */
674b39c5158Smillert 
675b39c5158Smillert         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
676b39c5158Smillert         s->heap[--(s->heap_max)] = m;
677b39c5158Smillert 
678b39c5158Smillert         /* Create a new node father of n and m */
679b39c5158Smillert         tree[node].Freq = tree[n].Freq + tree[m].Freq;
680b39c5158Smillert         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
681b39c5158Smillert                                 s->depth[n] : s->depth[m]) + 1);
682b39c5158Smillert         tree[n].Dad = tree[m].Dad = (ush)node;
683b39c5158Smillert #ifdef DUMP_BL_TREE
684b39c5158Smillert         if (tree == s->bl_tree) {
685b39c5158Smillert             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
686b39c5158Smillert                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
687b39c5158Smillert         }
688b39c5158Smillert #endif
689b39c5158Smillert         /* and insert the new node in the heap */
690b39c5158Smillert         s->heap[SMALLEST] = node++;
691b39c5158Smillert         pqdownheap(s, tree, SMALLEST);
692b39c5158Smillert 
693b39c5158Smillert     } while (s->heap_len >= 2);
694b39c5158Smillert 
695b39c5158Smillert     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
696b39c5158Smillert 
697b39c5158Smillert     /* At this point, the fields freq and dad are set. We can now
698b39c5158Smillert      * generate the bit lengths.
699b39c5158Smillert      */
700b39c5158Smillert     gen_bitlen(s, (tree_desc *)desc);
701b39c5158Smillert 
702b39c5158Smillert     /* The field len is now set, we can generate the bit codes */
703b39c5158Smillert     gen_codes ((ct_data *)tree, max_code, s->bl_count);
704b39c5158Smillert }
705b39c5158Smillert 
706b39c5158Smillert /* ===========================================================================
707b39c5158Smillert  * Scan a literal or distance tree to determine the frequencies of the codes
708b39c5158Smillert  * in the bit length tree.
709b39c5158Smillert  */
710*3d61058aSafresh1 local void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
711b39c5158Smillert     int n;                     /* iterates over all tree elements */
712b39c5158Smillert     int prevlen = -1;          /* last emitted length */
713b39c5158Smillert     int curlen;                /* length of current code */
714b39c5158Smillert     int nextlen = tree[0].Len; /* length of next code */
715b39c5158Smillert     int count = 0;             /* repeat count of the current code */
716b39c5158Smillert     int max_count = 7;         /* max repeat count */
717b39c5158Smillert     int min_count = 4;         /* min repeat count */
718b39c5158Smillert 
719b39c5158Smillert     if (nextlen == 0) max_count = 138, min_count = 3;
720b39c5158Smillert     tree[max_code + 1].Len = (ush)0xffff; /* guard */
721b39c5158Smillert 
722b39c5158Smillert     for (n = 0; n <= max_code; n++) {
723b39c5158Smillert         curlen = nextlen; nextlen = tree[n + 1].Len;
724b39c5158Smillert         if (++count < max_count && curlen == nextlen) {
725b39c5158Smillert             continue;
726b39c5158Smillert         } else if (count < min_count) {
727b39c5158Smillert             s->bl_tree[curlen].Freq += count;
728b39c5158Smillert         } else if (curlen != 0) {
729b39c5158Smillert             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
730b39c5158Smillert             s->bl_tree[REP_3_6].Freq++;
731b39c5158Smillert         } else if (count <= 10) {
732b39c5158Smillert             s->bl_tree[REPZ_3_10].Freq++;
733b39c5158Smillert         } else {
734b39c5158Smillert             s->bl_tree[REPZ_11_138].Freq++;
735b39c5158Smillert         }
736b39c5158Smillert         count = 0; prevlen = curlen;
737b39c5158Smillert         if (nextlen == 0) {
738b39c5158Smillert             max_count = 138, min_count = 3;
739b39c5158Smillert         } else if (curlen == nextlen) {
740b39c5158Smillert             max_count = 6, min_count = 3;
741b39c5158Smillert         } else {
742b39c5158Smillert             max_count = 7, min_count = 4;
743b39c5158Smillert         }
744b39c5158Smillert     }
745b39c5158Smillert }
746b39c5158Smillert 
747b39c5158Smillert /* ===========================================================================
748b39c5158Smillert  * Send a literal or distance tree in compressed form, using the codes in
749b39c5158Smillert  * bl_tree.
750b39c5158Smillert  */
751*3d61058aSafresh1 local void send_tree(deflate_state *s, ct_data *tree, int max_code) {
752b39c5158Smillert     int n;                     /* iterates over all tree elements */
753b39c5158Smillert     int prevlen = -1;          /* last emitted length */
754b39c5158Smillert     int curlen;                /* length of current code */
755b39c5158Smillert     int nextlen = tree[0].Len; /* length of next code */
756b39c5158Smillert     int count = 0;             /* repeat count of the current code */
757b39c5158Smillert     int max_count = 7;         /* max repeat count */
758b39c5158Smillert     int min_count = 4;         /* min repeat count */
759b39c5158Smillert 
760b39c5158Smillert     /* tree[max_code + 1].Len = -1; */  /* guard already set */
761b39c5158Smillert     if (nextlen == 0) max_count = 138, min_count = 3;
762b39c5158Smillert 
763b39c5158Smillert     for (n = 0; n <= max_code; n++) {
764b39c5158Smillert         curlen = nextlen; nextlen = tree[n + 1].Len;
765b39c5158Smillert         if (++count < max_count && curlen == nextlen) {
766b39c5158Smillert             continue;
767b39c5158Smillert         } else if (count < min_count) {
768b39c5158Smillert             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
769b39c5158Smillert 
770b39c5158Smillert         } else if (curlen != 0) {
771b39c5158Smillert             if (curlen != prevlen) {
772b39c5158Smillert                 send_code(s, curlen, s->bl_tree); count--;
773b39c5158Smillert             }
774b39c5158Smillert             Assert(count >= 3 && count <= 6, " 3_6?");
775b39c5158Smillert             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2);
776b39c5158Smillert 
777b39c5158Smillert         } else if (count <= 10) {
778b39c5158Smillert             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3);
779b39c5158Smillert 
780b39c5158Smillert         } else {
781b39c5158Smillert             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7);
782b39c5158Smillert         }
783b39c5158Smillert         count = 0; prevlen = curlen;
784b39c5158Smillert         if (nextlen == 0) {
785b39c5158Smillert             max_count = 138, min_count = 3;
786b39c5158Smillert         } else if (curlen == nextlen) {
787b39c5158Smillert             max_count = 6, min_count = 3;
788b39c5158Smillert         } else {
789b39c5158Smillert             max_count = 7, min_count = 4;
790b39c5158Smillert         }
791b39c5158Smillert     }
792b39c5158Smillert }
793b39c5158Smillert 
794b39c5158Smillert /* ===========================================================================
795b39c5158Smillert  * Construct the Huffman tree for the bit lengths and return the index in
796b39c5158Smillert  * bl_order of the last bit length code to send.
797b39c5158Smillert  */
798*3d61058aSafresh1 local int build_bl_tree(deflate_state *s) {
799b39c5158Smillert     int max_blindex;  /* index of last bit length code of non zero freq */
800b39c5158Smillert 
801b39c5158Smillert     /* Determine the bit length frequencies for literal and distance trees */
802b39c5158Smillert     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
803b39c5158Smillert     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
804b39c5158Smillert 
805b39c5158Smillert     /* Build the bit length tree: */
806b39c5158Smillert     build_tree(s, (tree_desc *)(&(s->bl_desc)));
807e0680481Safresh1     /* opt_len now includes the length of the tree representations, except the
808e0680481Safresh1      * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts.
809b39c5158Smillert      */
810b39c5158Smillert 
811b39c5158Smillert     /* Determine the number of bit length codes to send. The pkzip format
812b39c5158Smillert      * requires that at least 4 bit length codes be sent. (appnote.txt says
813b39c5158Smillert      * 3 but the actual value used is 4.)
814b39c5158Smillert      */
815b39c5158Smillert     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
816b39c5158Smillert         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
817b39c5158Smillert     }
818b39c5158Smillert     /* Update opt_len to include the bit length tree and counts */
8199f11ffb7Safresh1     s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4;
820b39c5158Smillert     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
821b39c5158Smillert             s->opt_len, s->static_len));
822b39c5158Smillert 
823b39c5158Smillert     return max_blindex;
824b39c5158Smillert }
825b39c5158Smillert 
826b39c5158Smillert /* ===========================================================================
827b39c5158Smillert  * Send the header for a block using dynamic Huffman trees: the counts, the
828b39c5158Smillert  * lengths of the bit length codes, the literal tree and the distance tree.
829b39c5158Smillert  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
830b39c5158Smillert  */
831*3d61058aSafresh1 local void send_all_trees(deflate_state *s, int lcodes, int dcodes,
832*3d61058aSafresh1                           int blcodes) {
833b39c5158Smillert     int rank;                    /* index in bl_order */
834b39c5158Smillert 
835b39c5158Smillert     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
836b39c5158Smillert     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
837b39c5158Smillert             "too many codes");
838b39c5158Smillert     Tracev((stderr, "\nbl counts: "));
839b39c5158Smillert     send_bits(s, lcodes - 257, 5);  /* not +255 as stated in appnote.txt */
840b39c5158Smillert     send_bits(s, dcodes - 1,   5);
841b39c5158Smillert     send_bits(s, blcodes - 4,  4);  /* not -3 as stated in appnote.txt */
842b39c5158Smillert     for (rank = 0; rank < blcodes; rank++) {
843b39c5158Smillert         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
844b39c5158Smillert         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
845b39c5158Smillert     }
846b39c5158Smillert     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
847b39c5158Smillert 
848b39c5158Smillert     send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1);  /* literal tree */
849b39c5158Smillert     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
850b39c5158Smillert 
851b39c5158Smillert     send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1);  /* distance tree */
852b39c5158Smillert     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
853b39c5158Smillert }
854b39c5158Smillert 
855b39c5158Smillert /* ===========================================================================
856b39c5158Smillert  * Send a stored block
857b39c5158Smillert  */
858*3d61058aSafresh1 void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf,
859*3d61058aSafresh1                                     ulg stored_len, int last) {
86048950c12Ssthen     send_bits(s, (STORED_BLOCK<<1) + last, 3);  /* send block type */
8619f11ffb7Safresh1     bi_windup(s);        /* align on byte boundary */
8629f11ffb7Safresh1     put_short(s, (ush)stored_len);
8639f11ffb7Safresh1     put_short(s, (ush)~stored_len);
864eac174f2Safresh1     if (stored_len)
8659f11ffb7Safresh1         zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
8669f11ffb7Safresh1     s->pending += stored_len;
8679f11ffb7Safresh1 #ifdef ZLIB_DEBUG
868b39c5158Smillert     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
869b39c5158Smillert     s->compressed_len += (stored_len + 4) << 3;
8709f11ffb7Safresh1     s->bits_sent += 2*16;
8719f11ffb7Safresh1     s->bits_sent += stored_len << 3;
872b39c5158Smillert #endif
873b39c5158Smillert }
874b39c5158Smillert 
875b39c5158Smillert /* ===========================================================================
876e9ce3842Safresh1  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
877e9ce3842Safresh1  */
878*3d61058aSafresh1 void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) {
879e9ce3842Safresh1     bi_flush(s);
880e9ce3842Safresh1 }
881e9ce3842Safresh1 
882e9ce3842Safresh1 /* ===========================================================================
883b39c5158Smillert  * Send one empty static block to give enough lookahead for inflate.
884b39c5158Smillert  * This takes 10 bits, of which 7 may remain in the bit buffer.
885b39c5158Smillert  */
886*3d61058aSafresh1 void ZLIB_INTERNAL _tr_align(deflate_state *s) {
887b39c5158Smillert     send_bits(s, STATIC_TREES<<1, 3);
888b39c5158Smillert     send_code(s, END_BLOCK, static_ltree);
8899f11ffb7Safresh1 #ifdef ZLIB_DEBUG
890b39c5158Smillert     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
891b39c5158Smillert #endif
892b39c5158Smillert     bi_flush(s);
893b39c5158Smillert }
894b39c5158Smillert 
895b39c5158Smillert /* ===========================================================================
896*3d61058aSafresh1  * Send the block data compressed using the given Huffman trees
897*3d61058aSafresh1  */
898*3d61058aSafresh1 local void compress_block(deflate_state *s, const ct_data *ltree,
899*3d61058aSafresh1                           const ct_data *dtree) {
900*3d61058aSafresh1     unsigned dist;      /* distance of matched string */
901*3d61058aSafresh1     int lc;             /* match length or unmatched char (if dist == 0) */
902*3d61058aSafresh1     unsigned sx = 0;    /* running index in symbol buffers */
903*3d61058aSafresh1     unsigned code;      /* the code to send */
904*3d61058aSafresh1     int extra;          /* number of extra bits to send */
905*3d61058aSafresh1 
906*3d61058aSafresh1     if (s->sym_next != 0) do {
907*3d61058aSafresh1 #ifdef LIT_MEM
908*3d61058aSafresh1         dist = s->d_buf[sx];
909*3d61058aSafresh1         lc = s->l_buf[sx++];
910*3d61058aSafresh1 #else
911*3d61058aSafresh1         dist = s->sym_buf[sx++] & 0xff;
912*3d61058aSafresh1         dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
913*3d61058aSafresh1         lc = s->sym_buf[sx++];
914*3d61058aSafresh1 #endif
915*3d61058aSafresh1         if (dist == 0) {
916*3d61058aSafresh1             send_code(s, lc, ltree); /* send a literal byte */
917*3d61058aSafresh1             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
918*3d61058aSafresh1         } else {
919*3d61058aSafresh1             /* Here, lc is the match length - MIN_MATCH */
920*3d61058aSafresh1             code = _length_code[lc];
921*3d61058aSafresh1             send_code(s, code + LITERALS + 1, ltree);   /* send length code */
922*3d61058aSafresh1             extra = extra_lbits[code];
923*3d61058aSafresh1             if (extra != 0) {
924*3d61058aSafresh1                 lc -= base_length[code];
925*3d61058aSafresh1                 send_bits(s, lc, extra);       /* send the extra length bits */
926*3d61058aSafresh1             }
927*3d61058aSafresh1             dist--; /* dist is now the match distance - 1 */
928*3d61058aSafresh1             code = d_code(dist);
929*3d61058aSafresh1             Assert (code < D_CODES, "bad d_code");
930*3d61058aSafresh1 
931*3d61058aSafresh1             send_code(s, code, dtree);       /* send the distance code */
932*3d61058aSafresh1             extra = extra_dbits[code];
933*3d61058aSafresh1             if (extra != 0) {
934*3d61058aSafresh1                 dist -= (unsigned)base_dist[code];
935*3d61058aSafresh1                 send_bits(s, dist, extra);   /* send the extra distance bits */
936*3d61058aSafresh1             }
937*3d61058aSafresh1         } /* literal or match pair ? */
938*3d61058aSafresh1 
939*3d61058aSafresh1         /* Check for no overlay of pending_buf on needed symbols */
940*3d61058aSafresh1 #ifdef LIT_MEM
941*3d61058aSafresh1         Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow");
942*3d61058aSafresh1 #else
943*3d61058aSafresh1         Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
944*3d61058aSafresh1 #endif
945*3d61058aSafresh1 
946*3d61058aSafresh1     } while (sx < s->sym_next);
947*3d61058aSafresh1 
948*3d61058aSafresh1     send_code(s, END_BLOCK, ltree);
949*3d61058aSafresh1 }
950*3d61058aSafresh1 
951*3d61058aSafresh1 /* ===========================================================================
952*3d61058aSafresh1  * Check if the data type is TEXT or BINARY, using the following algorithm:
953*3d61058aSafresh1  * - TEXT if the two conditions below are satisfied:
954*3d61058aSafresh1  *    a) There are no non-portable control characters belonging to the
955*3d61058aSafresh1  *       "block list" (0..6, 14..25, 28..31).
956*3d61058aSafresh1  *    b) There is at least one printable character belonging to the
957*3d61058aSafresh1  *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
958*3d61058aSafresh1  * - BINARY otherwise.
959*3d61058aSafresh1  * - The following partially-portable control characters form a
960*3d61058aSafresh1  *   "gray list" that is ignored in this detection algorithm:
961*3d61058aSafresh1  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
962*3d61058aSafresh1  * IN assertion: the fields Freq of dyn_ltree are set.
963*3d61058aSafresh1  */
964*3d61058aSafresh1 local int detect_data_type(deflate_state *s) {
965*3d61058aSafresh1     /* block_mask is the bit mask of block-listed bytes
966*3d61058aSafresh1      * set bits 0..6, 14..25, and 28..31
967*3d61058aSafresh1      * 0xf3ffc07f = binary 11110011111111111100000001111111
968*3d61058aSafresh1      */
969*3d61058aSafresh1     unsigned long block_mask = 0xf3ffc07fUL;
970*3d61058aSafresh1     int n;
971*3d61058aSafresh1 
972*3d61058aSafresh1     /* Check for non-textual ("block-listed") bytes. */
973*3d61058aSafresh1     for (n = 0; n <= 31; n++, block_mask >>= 1)
974*3d61058aSafresh1         if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
975*3d61058aSafresh1             return Z_BINARY;
976*3d61058aSafresh1 
977*3d61058aSafresh1     /* Check for textual ("allow-listed") bytes. */
978*3d61058aSafresh1     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
979*3d61058aSafresh1             || s->dyn_ltree[13].Freq != 0)
980*3d61058aSafresh1         return Z_TEXT;
981*3d61058aSafresh1     for (n = 32; n < LITERALS; n++)
982*3d61058aSafresh1         if (s->dyn_ltree[n].Freq != 0)
983*3d61058aSafresh1             return Z_TEXT;
984*3d61058aSafresh1 
985*3d61058aSafresh1     /* There are no "block-listed" or "allow-listed" bytes:
986*3d61058aSafresh1      * this stream either is empty or has tolerated ("gray-listed") bytes only.
987*3d61058aSafresh1      */
988*3d61058aSafresh1     return Z_BINARY;
989*3d61058aSafresh1 }
990*3d61058aSafresh1 
991*3d61058aSafresh1 /* ===========================================================================
992b39c5158Smillert  * Determine the best encoding for the current block: dynamic trees, static
9939f11ffb7Safresh1  * trees or store, and write out the encoded block.
994b39c5158Smillert  */
995*3d61058aSafresh1 void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
996*3d61058aSafresh1                                    ulg stored_len, int last) {
997b39c5158Smillert     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
998b39c5158Smillert     int max_blindex = 0;  /* index of last bit length code of non zero freq */
999b39c5158Smillert 
1000b39c5158Smillert     /* Build the Huffman trees unless a stored block is forced */
1001b39c5158Smillert     if (s->level > 0) {
1002b39c5158Smillert 
1003b39c5158Smillert         /* Check if the file is binary or text */
100448950c12Ssthen         if (s->strm->data_type == Z_UNKNOWN)
100548950c12Ssthen             s->strm->data_type = detect_data_type(s);
1006b39c5158Smillert 
1007b39c5158Smillert         /* Construct the literal and distance trees */
1008b39c5158Smillert         build_tree(s, (tree_desc *)(&(s->l_desc)));
1009b39c5158Smillert         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
1010b39c5158Smillert                 s->static_len));
1011b39c5158Smillert 
1012b39c5158Smillert         build_tree(s, (tree_desc *)(&(s->d_desc)));
1013b39c5158Smillert         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
1014b39c5158Smillert                 s->static_len));
1015b39c5158Smillert         /* At this point, opt_len and static_len are the total bit lengths of
1016b39c5158Smillert          * the compressed block data, excluding the tree representations.
1017b39c5158Smillert          */
1018b39c5158Smillert 
1019b39c5158Smillert         /* Build the bit length tree for the above two trees, and get the index
1020b39c5158Smillert          * in bl_order of the last bit length code to send.
1021b39c5158Smillert          */
1022b39c5158Smillert         max_blindex = build_bl_tree(s);
1023b39c5158Smillert 
1024b39c5158Smillert         /* Determine the best encoding. Compute the block lengths in bytes. */
1025b39c5158Smillert         opt_lenb = (s->opt_len + 3 + 7) >> 3;
1026b39c5158Smillert         static_lenb = (s->static_len + 3 + 7) >> 3;
1027b39c5158Smillert 
1028b39c5158Smillert         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
1029b39c5158Smillert                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
1030fc2b99ebSbluhm                 s->sym_next / 3));
1031b39c5158Smillert 
1032e0680481Safresh1 #ifndef FORCE_STATIC
1033e0680481Safresh1         if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
1034e0680481Safresh1 #endif
1035e0680481Safresh1             opt_lenb = static_lenb;
1036b39c5158Smillert 
1037b39c5158Smillert     } else {
1038b39c5158Smillert         Assert(buf != (char*)0, "lost buf");
1039b39c5158Smillert         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
1040b39c5158Smillert     }
1041b39c5158Smillert 
1042b39c5158Smillert #ifdef FORCE_STORED
1043b39c5158Smillert     if (buf != (char*)0) { /* force stored block */
1044b39c5158Smillert #else
1045b39c5158Smillert     if (stored_len + 4 <= opt_lenb && buf != (char*)0) {
1046b39c5158Smillert                        /* 4: two words for the lengths */
1047b39c5158Smillert #endif
1048b39c5158Smillert         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1049b39c5158Smillert          * Otherwise we can't have processed more than WSIZE input bytes since
1050b39c5158Smillert          * the last block flush, because compression would have been
1051b39c5158Smillert          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1052b39c5158Smillert          * transform a block into a stored block.
1053b39c5158Smillert          */
105448950c12Ssthen         _tr_stored_block(s, buf, stored_len, last);
1055b39c5158Smillert 
1056e0680481Safresh1     } else if (static_lenb == opt_lenb) {
105748950c12Ssthen         send_bits(s, (STATIC_TREES<<1) + last, 3);
1058e5157e49Safresh1         compress_block(s, (const ct_data *)static_ltree,
1059e5157e49Safresh1                        (const ct_data *)static_dtree);
10609f11ffb7Safresh1 #ifdef ZLIB_DEBUG
1061b39c5158Smillert         s->compressed_len += 3 + s->static_len;
1062b39c5158Smillert #endif
1063b39c5158Smillert     } else {
106448950c12Ssthen         send_bits(s, (DYN_TREES<<1) + last, 3);
1065b39c5158Smillert         send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1,
1066b39c5158Smillert                        max_blindex + 1);
1067e5157e49Safresh1         compress_block(s, (const ct_data *)s->dyn_ltree,
1068e5157e49Safresh1                        (const ct_data *)s->dyn_dtree);
10699f11ffb7Safresh1 #ifdef ZLIB_DEBUG
1070b39c5158Smillert         s->compressed_len += 3 + s->opt_len;
1071b39c5158Smillert #endif
1072b39c5158Smillert     }
1073b39c5158Smillert     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1074b39c5158Smillert     /* The above check is made mod 2^32, for files larger than 512 MB
1075b39c5158Smillert      * and uLong implemented on 32 bits.
1076b39c5158Smillert      */
1077b39c5158Smillert     init_block(s);
1078b39c5158Smillert 
107948950c12Ssthen     if (last) {
1080b39c5158Smillert         bi_windup(s);
10819f11ffb7Safresh1 #ifdef ZLIB_DEBUG
1082b39c5158Smillert         s->compressed_len += 7;  /* align on byte boundary */
1083b39c5158Smillert #endif
1084b39c5158Smillert     }
1085b39c5158Smillert     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3,
108648950c12Ssthen            s->compressed_len - 7*last));
1087b39c5158Smillert }
1088b39c5158Smillert 
1089b39c5158Smillert /* ===========================================================================
1090b39c5158Smillert  * Save the match info and tally the frequency counts. Return true if
1091b39c5158Smillert  * the current block must be flushed.
1092b39c5158Smillert  */
1093*3d61058aSafresh1 int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) {
1094*3d61058aSafresh1 #ifdef LIT_MEM
1095*3d61058aSafresh1     s->d_buf[s->sym_next] = (ush)dist;
1096*3d61058aSafresh1     s->l_buf[s->sym_next++] = (uch)lc;
1097*3d61058aSafresh1 #else
1098e0680481Safresh1     s->sym_buf[s->sym_next++] = (uch)dist;
1099e0680481Safresh1     s->sym_buf[s->sym_next++] = (uch)(dist >> 8);
1100e0680481Safresh1     s->sym_buf[s->sym_next++] = (uch)lc;
1101*3d61058aSafresh1 #endif
1102b39c5158Smillert     if (dist == 0) {
1103b39c5158Smillert         /* lc is the unmatched char */
1104b39c5158Smillert         s->dyn_ltree[lc].Freq++;
1105b39c5158Smillert     } else {
1106b39c5158Smillert         s->matches++;
1107b39c5158Smillert         /* Here, lc is the match length - MIN_MATCH */
1108b39c5158Smillert         dist--;             /* dist = match distance - 1 */
1109b39c5158Smillert         Assert((ush)dist < (ush)MAX_DIST(s) &&
1110b39c5158Smillert                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1111b39c5158Smillert                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1112b39c5158Smillert 
1113b39c5158Smillert         s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++;
1114b39c5158Smillert         s->dyn_dtree[d_code(dist)].Freq++;
1115b39c5158Smillert     }
1116fc2b99ebSbluhm     return (s->sym_next == s->sym_end);
1117b39c5158Smillert }
1118