xref: /openbsd-src/lib/libz/trees.c (revision a225ed82339557610307f4ad61f79271a8594b78)
12af503bcStholo /* trees.c -- output deflated data using Huffman coding
2d5e7bdb5Stb  * Copyright (C) 1995-2024 Jean-loup Gailly
336f395ceStb  * detect_data_type() function provided freely by Cosmin Truta, 2006
42af503bcStholo  * For conditions of distribution and use, see copyright notice in zlib.h
52af503bcStholo  */
62af503bcStholo 
72af503bcStholo /*
82af503bcStholo  *  ALGORITHM
92af503bcStholo  *
102af503bcStholo  *      The "deflation" process uses several Huffman trees. The more
112af503bcStholo  *      common source values are represented by shorter bit sequences.
122af503bcStholo  *
132af503bcStholo  *      Each code tree is stored in a compressed form which is itself
142af503bcStholo  * a Huffman encoding of the lengths of all the code strings (in
152af503bcStholo  * ascending order by source values).  The actual code strings are
162af503bcStholo  * reconstructed from the lengths in the inflate process, as described
172af503bcStholo  * in the deflate specification.
182af503bcStholo  *
192af503bcStholo  *  REFERENCES
202af503bcStholo  *
212af503bcStholo  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
222af503bcStholo  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
232af503bcStholo  *
242af503bcStholo  *      Storer, James A.
252af503bcStholo  *          Data Compression:  Methods and Theory, pp. 49-50.
262af503bcStholo  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
272af503bcStholo  *
282af503bcStholo  *      Sedgewick, R.
292af503bcStholo  *          Algorithms, p290.
302af503bcStholo  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
312af503bcStholo  */
322af503bcStholo 
3315ce0796Smillert /* #define GEN_TREES_H */
342af503bcStholo 
352af503bcStholo #include "deflate.h"
362af503bcStholo 
3736f395ceStb #ifdef ZLIB_DEBUG
382af503bcStholo #  include <ctype.h>
392af503bcStholo #endif
402af503bcStholo 
412af503bcStholo /* ===========================================================================
422af503bcStholo  * Constants
432af503bcStholo  */
442af503bcStholo 
452af503bcStholo #define MAX_BL_BITS 7
462af503bcStholo /* Bit length codes must not exceed MAX_BL_BITS bits */
472af503bcStholo 
482af503bcStholo #define END_BLOCK 256
492af503bcStholo /* end of block literal code */
502af503bcStholo 
512af503bcStholo #define REP_3_6      16
522af503bcStholo /* repeat previous bit length 3-6 times (2 bits of repeat count) */
532af503bcStholo 
542af503bcStholo #define REPZ_3_10    17
552af503bcStholo /* repeat a zero length 3-10 times  (3 bits of repeat count) */
562af503bcStholo 
572af503bcStholo #define REPZ_11_138  18
582af503bcStholo /* repeat a zero length 11-138 times  (7 bits of repeat count) */
592af503bcStholo 
6015ce0796Smillert local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
612af503bcStholo    = {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};
622af503bcStholo 
6315ce0796Smillert local const int extra_dbits[D_CODES] /* extra bits for each distance code */
642af503bcStholo    = {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};
652af503bcStholo 
6615ce0796Smillert local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
672af503bcStholo    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
682af503bcStholo 
6915ce0796Smillert local const uch bl_order[BL_CODES]
702af503bcStholo    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
712af503bcStholo /* The lengths of the bit length codes are sent in order of decreasing
722af503bcStholo  * probability, to avoid transmitting the lengths for unused bit length codes.
732af503bcStholo  */
742af503bcStholo 
752af503bcStholo /* ===========================================================================
762af503bcStholo  * Local data. These are initialized only once.
772af503bcStholo  */
782af503bcStholo 
7915ce0796Smillert #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
8015ce0796Smillert 
8115ce0796Smillert #if defined(GEN_TREES_H) || !defined(STDC)
8215ce0796Smillert /* non ANSI compilers may not accept trees.h */
8315ce0796Smillert 
842af503bcStholo local ct_data static_ltree[L_CODES+2];
852af503bcStholo /* The static literal tree. Since the bit lengths are imposed, there is no
862af503bcStholo  * need for the L_CODES extra codes used during heap construction. However
872af503bcStholo  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
882af503bcStholo  * below).
892af503bcStholo  */
902af503bcStholo 
912af503bcStholo local ct_data static_dtree[D_CODES];
922af503bcStholo /* The static distance tree. (Actually a trivial tree since all codes use
932af503bcStholo  * 5 bits.)
942af503bcStholo  */
952af503bcStholo 
9615ce0796Smillert uch _dist_code[DIST_CODE_LEN];
9715ce0796Smillert /* Distance codes. The first 256 values correspond to the distances
982af503bcStholo  * 3 .. 258, the last 256 values correspond to the top 8 bits of
992af503bcStholo  * the 15 bit distances.
1002af503bcStholo  */
1012af503bcStholo 
10215ce0796Smillert uch _length_code[MAX_MATCH-MIN_MATCH+1];
1032af503bcStholo /* length code for each normalized match length (0 == MIN_MATCH) */
1042af503bcStholo 
1052af503bcStholo local int base_length[LENGTH_CODES];
1062af503bcStholo /* First normalized length for each code (0 = MIN_MATCH) */
1072af503bcStholo 
1082af503bcStholo local int base_dist[D_CODES];
1092af503bcStholo /* First normalized distance for each code (0 = distance of 1) */
1102af503bcStholo 
11115ce0796Smillert #else
11215ce0796Smillert #  include "trees.h"
11315ce0796Smillert #endif /* GEN_TREES_H */
11415ce0796Smillert 
1152af503bcStholo struct static_tree_desc_s {
11615ce0796Smillert     const ct_data *static_tree;  /* static tree or NULL */
11715ce0796Smillert     const intf *extra_bits;      /* extra bits for each code or NULL */
1182af503bcStholo     int     extra_base;          /* base index for extra_bits */
1192af503bcStholo     int     elems;               /* max number of elements in the tree */
1202af503bcStholo     int     max_length;          /* max bit length for the codes */
1212af503bcStholo };
1222af503bcStholo 
123a04ea15dStb #ifdef NO_INIT_GLOBAL_POINTERS
124a04ea15dStb #  define TCONST
125a04ea15dStb #else
126a04ea15dStb #  define TCONST const
127a04ea15dStb #endif
128a04ea15dStb 
129a04ea15dStb local TCONST static_tree_desc static_l_desc =
1302af503bcStholo {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
1312af503bcStholo 
132a04ea15dStb local TCONST static_tree_desc static_d_desc =
1332af503bcStholo {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
1342af503bcStholo 
135a04ea15dStb local TCONST static_tree_desc static_bl_desc =
13615ce0796Smillert {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
1372af503bcStholo 
1382af503bcStholo /* ===========================================================================
139a04ea15dStb  * Output a short LSB first on the stream.
140a04ea15dStb  * IN assertion: there is enough room in pendingBuf.
1412af503bcStholo  */
142a04ea15dStb #define put_short(s, w) { \
143a04ea15dStb     put_byte(s, (uch)((w) & 0xff)); \
144a04ea15dStb     put_byte(s, (uch)((ush)(w) >> 8)); \
145a04ea15dStb }
1462af503bcStholo 
147a04ea15dStb /* ===========================================================================
148a04ea15dStb  * Reverse the first len bits of a code, using straightforward code (a faster
149a04ea15dStb  * method would use a table)
150a04ea15dStb  * IN assertion: 1 <= len <= 15
151a04ea15dStb  */
152a04ea15dStb local unsigned bi_reverse(unsigned code, int len) {
153a04ea15dStb     register unsigned res = 0;
154a04ea15dStb     do {
155a04ea15dStb         res |= code & 1;
156a04ea15dStb         code >>= 1, res <<= 1;
157a04ea15dStb     } while (--len > 0);
158a04ea15dStb     return res >> 1;
159a04ea15dStb }
160a04ea15dStb 
161a04ea15dStb /* ===========================================================================
162a04ea15dStb  * Flush the bit buffer, keeping at most 7 bits in it.
163a04ea15dStb  */
164a04ea15dStb local void bi_flush(deflate_state *s) {
165a04ea15dStb     if (s->bi_valid == 16) {
166a04ea15dStb         put_short(s, s->bi_buf);
167a04ea15dStb         s->bi_buf = 0;
168a04ea15dStb         s->bi_valid = 0;
169a04ea15dStb     } else if (s->bi_valid >= 8) {
170a04ea15dStb         put_byte(s, (Byte)s->bi_buf);
171a04ea15dStb         s->bi_buf >>= 8;
172a04ea15dStb         s->bi_valid -= 8;
173a04ea15dStb     }
174a04ea15dStb }
175a04ea15dStb 
176a04ea15dStb /* ===========================================================================
177a04ea15dStb  * Flush the bit buffer and align the output on a byte boundary
178a04ea15dStb  */
179a04ea15dStb local void bi_windup(deflate_state *s) {
180a04ea15dStb     if (s->bi_valid > 8) {
181a04ea15dStb         put_short(s, s->bi_buf);
182a04ea15dStb     } else if (s->bi_valid > 0) {
183a04ea15dStb         put_byte(s, (Byte)s->bi_buf);
184a04ea15dStb     }
185*a225ed82Stb     s->bi_used = ((s->bi_valid - 1) & 7) + 1;
186a04ea15dStb     s->bi_buf = 0;
187a04ea15dStb     s->bi_valid = 0;
188a04ea15dStb #ifdef ZLIB_DEBUG
189a04ea15dStb     s->bits_sent = (s->bits_sent + 7) & ~7;
190a04ea15dStb #endif
191a04ea15dStb }
192a04ea15dStb 
193a04ea15dStb /* ===========================================================================
194a04ea15dStb  * Generate the codes for a given tree and bit counts (which need not be
195a04ea15dStb  * optimal).
196a04ea15dStb  * IN assertion: the array bl_count contains the bit length statistics for
197a04ea15dStb  * the given tree and the field len is set for all tree elements.
198a04ea15dStb  * OUT assertion: the field code is set for all tree elements of non
199a04ea15dStb  *     zero code length.
200a04ea15dStb  */
201a04ea15dStb local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) {
202a04ea15dStb     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
203a04ea15dStb     unsigned code = 0;         /* running code value */
204a04ea15dStb     int bits;                  /* bit index */
205a04ea15dStb     int n;                     /* code index */
206a04ea15dStb 
207a04ea15dStb     /* The distribution counts are first used to generate the code values
208a04ea15dStb      * without bit reversal.
209a04ea15dStb      */
210a04ea15dStb     for (bits = 1; bits <= MAX_BITS; bits++) {
211a04ea15dStb         code = (code + bl_count[bits - 1]) << 1;
212a04ea15dStb         next_code[bits] = (ush)code;
213a04ea15dStb     }
214a04ea15dStb     /* Check that the bit counts in bl_count are consistent. The last code
215a04ea15dStb      * must be all ones.
216a04ea15dStb      */
217a04ea15dStb     Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
218a04ea15dStb             "inconsistent bit counts");
219a04ea15dStb     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
220a04ea15dStb 
221a04ea15dStb     for (n = 0;  n <= max_code; n++) {
222a04ea15dStb         int len = tree[n].Len;
223a04ea15dStb         if (len == 0) continue;
224a04ea15dStb         /* Now reverse the bits */
225a04ea15dStb         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
226a04ea15dStb 
227a04ea15dStb         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
228a04ea15dStb             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1));
229a04ea15dStb     }
230a04ea15dStb }
2312af503bcStholo 
23215ce0796Smillert #ifdef GEN_TREES_H
233a04ea15dStb local void gen_trees_header(void);
23415ce0796Smillert #endif
23515ce0796Smillert 
23636f395ceStb #ifndef ZLIB_DEBUG
2372af503bcStholo #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
2382af503bcStholo    /* Send a code of the given tree. c and tree must not have side effects */
2392af503bcStholo 
24036f395ceStb #else /* !ZLIB_DEBUG */
2412af503bcStholo #  define send_code(s, c, tree) \
24215ce0796Smillert      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
2432af503bcStholo        send_bits(s, tree[c].Code, tree[c].Len); }
2442af503bcStholo #endif
2452af503bcStholo 
2462af503bcStholo /* ===========================================================================
2472af503bcStholo  * Send a value on a given number of bits.
2482af503bcStholo  * IN assertion: length <= 16 and value fits in length bits.
2492af503bcStholo  */
25036f395ceStb #ifdef ZLIB_DEBUG
251a04ea15dStb local void send_bits(deflate_state *s, int value, int length) {
2522af503bcStholo     Tracevv((stderr," l %2d v %4x ", length, value));
2532af503bcStholo     Assert(length > 0 && length <= 15, "invalid length");
2542af503bcStholo     s->bits_sent += (ulg)length;
2552af503bcStholo 
2562af503bcStholo     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
2572af503bcStholo      * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid))
2582af503bcStholo      * unused bits in value.
2592af503bcStholo      */
2602af503bcStholo     if (s->bi_valid > (int)Buf_size - length) {
26136f395ceStb         s->bi_buf |= (ush)value << s->bi_valid;
2622af503bcStholo         put_short(s, s->bi_buf);
2632af503bcStholo         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
2642af503bcStholo         s->bi_valid += length - Buf_size;
2652af503bcStholo     } else {
26636f395ceStb         s->bi_buf |= (ush)value << s->bi_valid;
2672af503bcStholo         s->bi_valid += length;
2682af503bcStholo     }
2692af503bcStholo }
27036f395ceStb #else /* !ZLIB_DEBUG */
2712af503bcStholo 
2722af503bcStholo #define send_bits(s, value, length) \
2732af503bcStholo { int len = length;\
2742af503bcStholo   if (s->bi_valid > (int)Buf_size - len) {\
27536f395ceStb     int val = (int)value;\
27636f395ceStb     s->bi_buf |= (ush)val << s->bi_valid;\
2772af503bcStholo     put_short(s, s->bi_buf);\
2782af503bcStholo     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
2792af503bcStholo     s->bi_valid += len - Buf_size;\
2802af503bcStholo   } else {\
28136f395ceStb     s->bi_buf |= (ush)(value) << s->bi_valid;\
2822af503bcStholo     s->bi_valid += len;\
2832af503bcStholo   }\
2842af503bcStholo }
28536f395ceStb #endif /* ZLIB_DEBUG */
2862af503bcStholo 
2872af503bcStholo 
2882af503bcStholo /* the arguments must not have side effects */
2892af503bcStholo 
2902af503bcStholo /* ===========================================================================
29115ce0796Smillert  * Initialize the various 'constant' tables.
2922af503bcStholo  */
293a04ea15dStb local void tr_static_init(void) {
29415ce0796Smillert #if defined(GEN_TREES_H) || !defined(STDC)
2952af503bcStholo     static int static_init_done = 0;
2962af503bcStholo     int n;        /* iterates over tree elements */
2972af503bcStholo     int bits;     /* bit counter */
2982af503bcStholo     int length;   /* length value */
2992af503bcStholo     int code;     /* code value */
3002af503bcStholo     int dist;     /* distance index */
3012af503bcStholo     ush bl_count[MAX_BITS+1];
3022af503bcStholo     /* number of codes at each bit length for an optimal tree */
3032af503bcStholo 
3042af503bcStholo     if (static_init_done) return;
3052af503bcStholo 
30615ce0796Smillert     /* For some embedded targets, global variables are not initialized: */
30736f395ceStb #ifdef NO_INIT_GLOBAL_POINTERS
30815ce0796Smillert     static_l_desc.static_tree = static_ltree;
30915ce0796Smillert     static_l_desc.extra_bits = extra_lbits;
31015ce0796Smillert     static_d_desc.static_tree = static_dtree;
31115ce0796Smillert     static_d_desc.extra_bits = extra_dbits;
31215ce0796Smillert     static_bl_desc.extra_bits = extra_blbits;
31336f395ceStb #endif
31415ce0796Smillert 
3152af503bcStholo     /* Initialize the mapping length (0..255) -> length code (0..28) */
3162af503bcStholo     length = 0;
3172af503bcStholo     for (code = 0; code < LENGTH_CODES-1; code++) {
3182af503bcStholo         base_length[code] = length;
3192af503bcStholo         for (n = 0; n < (1 << extra_lbits[code]); n++) {
32015ce0796Smillert             _length_code[length++] = (uch)code;
3212af503bcStholo         }
3222af503bcStholo     }
3232af503bcStholo     Assert (length == 256, "tr_static_init: length != 256");
3242af503bcStholo     /* Note that the length 255 (match length 258) can be represented
3252af503bcStholo      * in two different ways: code 284 + 5 bits or code 285, so we
3262af503bcStholo      * overwrite length_code[255] to use the best encoding:
3272af503bcStholo      */
32815ce0796Smillert     _length_code[length - 1] = (uch)code;
3292af503bcStholo 
3302af503bcStholo     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
3312af503bcStholo     dist = 0;
3322af503bcStholo     for (code = 0 ; code < 16; code++) {
3332af503bcStholo         base_dist[code] = dist;
3342af503bcStholo         for (n = 0; n < (1 << extra_dbits[code]); n++) {
33515ce0796Smillert             _dist_code[dist++] = (uch)code;
3362af503bcStholo         }
3372af503bcStholo     }
3382af503bcStholo     Assert (dist == 256, "tr_static_init: dist != 256");
3392af503bcStholo     dist >>= 7; /* from now on, all distances are divided by 128 */
3402af503bcStholo     for ( ; code < D_CODES; code++) {
3412af503bcStholo         base_dist[code] = dist << 7;
3422af503bcStholo         for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
34315ce0796Smillert             _dist_code[256 + dist++] = (uch)code;
3442af503bcStholo         }
3452af503bcStholo     }
3462af503bcStholo     Assert (dist == 256, "tr_static_init: 256 + dist != 512");
3472af503bcStholo 
3482af503bcStholo     /* Construct the codes of the static literal tree */
3492af503bcStholo     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
3502af503bcStholo     n = 0;
3512af503bcStholo     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
3522af503bcStholo     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
3532af503bcStholo     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
3542af503bcStholo     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
3552af503bcStholo     /* Codes 286 and 287 do not exist, but we must include them in the
3562af503bcStholo      * tree construction to get a canonical Huffman tree (longest code
3572af503bcStholo      * all ones)
3582af503bcStholo      */
3592af503bcStholo     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
3602af503bcStholo 
3612af503bcStholo     /* The static distance tree is trivial: */
3622af503bcStholo     for (n = 0; n < D_CODES; n++) {
3632af503bcStholo         static_dtree[n].Len = 5;
3642af503bcStholo         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
3652af503bcStholo     }
3662af503bcStholo     static_init_done = 1;
36715ce0796Smillert 
36815ce0796Smillert #  ifdef GEN_TREES_H
36915ce0796Smillert     gen_trees_header();
37015ce0796Smillert #  endif
37115ce0796Smillert #endif /* defined(GEN_TREES_H) || !defined(STDC) */
3722af503bcStholo }
3732af503bcStholo 
3742af503bcStholo /* ===========================================================================
3758bda5813Stb  * Generate the file trees.h describing the static trees.
37615ce0796Smillert  */
37715ce0796Smillert #ifdef GEN_TREES_H
37836f395ceStb #  ifndef ZLIB_DEBUG
37915ce0796Smillert #    include <stdio.h>
38015ce0796Smillert #  endif
38115ce0796Smillert 
38215ce0796Smillert #  define SEPARATOR(i, last, width) \
38315ce0796Smillert       ((i) == (last)? "\n};\n\n" :    \
38415ce0796Smillert        ((i) % (width) == (width) - 1 ? ",\n" : ", "))
38515ce0796Smillert 
386a04ea15dStb void gen_trees_header(void) {
38715ce0796Smillert     FILE *header = fopen("trees.h", "w");
38815ce0796Smillert     int i;
38915ce0796Smillert 
39015ce0796Smillert     Assert (header != NULL, "Can't open trees.h");
39115ce0796Smillert     fprintf(header,
39215ce0796Smillert             "/* header created automatically with -DGEN_TREES_H */\n\n");
39315ce0796Smillert 
39415ce0796Smillert     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
39515ce0796Smillert     for (i = 0; i < L_CODES+2; i++) {
39615ce0796Smillert         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
39715ce0796Smillert                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
39815ce0796Smillert     }
39915ce0796Smillert 
40015ce0796Smillert     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
40115ce0796Smillert     for (i = 0; i < D_CODES; i++) {
40215ce0796Smillert         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
40315ce0796Smillert                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
40415ce0796Smillert     }
40515ce0796Smillert 
40636f395ceStb     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
40715ce0796Smillert     for (i = 0; i < DIST_CODE_LEN; i++) {
40815ce0796Smillert         fprintf(header, "%2u%s", _dist_code[i],
40915ce0796Smillert                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
41015ce0796Smillert     }
41115ce0796Smillert 
41236f395ceStb     fprintf(header,
41336f395ceStb         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
41415ce0796Smillert     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
41515ce0796Smillert         fprintf(header, "%2u%s", _length_code[i],
41615ce0796Smillert                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
41715ce0796Smillert     }
41815ce0796Smillert 
41915ce0796Smillert     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
42015ce0796Smillert     for (i = 0; i < LENGTH_CODES; i++) {
42115ce0796Smillert         fprintf(header, "%1u%s", base_length[i],
42215ce0796Smillert                 SEPARATOR(i, LENGTH_CODES-1, 20));
42315ce0796Smillert     }
42415ce0796Smillert 
42515ce0796Smillert     fprintf(header, "local const int base_dist[D_CODES] = {\n");
42615ce0796Smillert     for (i = 0; i < D_CODES; i++) {
42715ce0796Smillert         fprintf(header, "%5u%s", base_dist[i],
42815ce0796Smillert                 SEPARATOR(i, D_CODES-1, 10));
42915ce0796Smillert     }
43015ce0796Smillert 
43115ce0796Smillert     fclose(header);
43215ce0796Smillert }
43315ce0796Smillert #endif /* GEN_TREES_H */
43415ce0796Smillert 
43515ce0796Smillert /* ===========================================================================
436a04ea15dStb  * Initialize a new block.
437a04ea15dStb  */
438a04ea15dStb local void init_block(deflate_state *s) {
439a04ea15dStb     int n; /* iterates over tree elements */
440a04ea15dStb 
441a04ea15dStb     /* Initialize the trees. */
442a04ea15dStb     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
443a04ea15dStb     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
444a04ea15dStb     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
445a04ea15dStb 
446a04ea15dStb     s->dyn_ltree[END_BLOCK].Freq = 1;
447a04ea15dStb     s->opt_len = s->static_len = 0L;
448a04ea15dStb     s->sym_next = s->matches = 0;
449a04ea15dStb }
450a04ea15dStb 
451a04ea15dStb /* ===========================================================================
4522af503bcStholo  * Initialize the tree data structures for a new zlib stream.
4532af503bcStholo  */
454a04ea15dStb void ZLIB_INTERNAL _tr_init(deflate_state *s) {
4552af503bcStholo     tr_static_init();
4562af503bcStholo 
4572af503bcStholo     s->l_desc.dyn_tree = s->dyn_ltree;
4582af503bcStholo     s->l_desc.stat_desc = &static_l_desc;
4592af503bcStholo 
4602af503bcStholo     s->d_desc.dyn_tree = s->dyn_dtree;
4612af503bcStholo     s->d_desc.stat_desc = &static_d_desc;
4622af503bcStholo 
4632af503bcStholo     s->bl_desc.dyn_tree = s->bl_tree;
4642af503bcStholo     s->bl_desc.stat_desc = &static_bl_desc;
4652af503bcStholo 
4662af503bcStholo     s->bi_buf = 0;
4672af503bcStholo     s->bi_valid = 0;
468*a225ed82Stb     s->bi_used = 0;
46936f395ceStb #ifdef ZLIB_DEBUG
47015ce0796Smillert     s->compressed_len = 0L;
4712af503bcStholo     s->bits_sent = 0L;
4722af503bcStholo #endif
4732af503bcStholo 
4742af503bcStholo     /* Initialize the first block of the first file: */
4752af503bcStholo     init_block(s);
4762af503bcStholo }
4772af503bcStholo 
4782af503bcStholo #define SMALLEST 1
4792af503bcStholo /* Index within the heap array of least frequent node in the Huffman tree */
4802af503bcStholo 
4812af503bcStholo 
4822af503bcStholo /* ===========================================================================
4832af503bcStholo  * Remove the smallest element from the heap and recreate the heap with
4842af503bcStholo  * one less element. Updates heap and heap_len.
4852af503bcStholo  */
4862af503bcStholo #define pqremove(s, tree, top) \
4872af503bcStholo {\
4882af503bcStholo     top = s->heap[SMALLEST]; \
4892af503bcStholo     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
4902af503bcStholo     pqdownheap(s, tree, SMALLEST); \
4912af503bcStholo }
4922af503bcStholo 
4932af503bcStholo /* ===========================================================================
4942af503bcStholo  * Compares to subtrees, using the tree depth as tie breaker when
4952af503bcStholo  * the subtrees have equal frequency. This minimizes the worst case length.
4962af503bcStholo  */
4972af503bcStholo #define smaller(tree, n, m, depth) \
4982af503bcStholo    (tree[n].Freq < tree[m].Freq || \
4992af503bcStholo    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
5002af503bcStholo 
5012af503bcStholo /* ===========================================================================
5022af503bcStholo  * Restore the heap property by moving down the tree starting at node k,
5032af503bcStholo  * exchanging a node with the smallest of its two sons if necessary, stopping
5042af503bcStholo  * when the heap property is re-established (each father smaller than its
5052af503bcStholo  * two sons).
5062af503bcStholo  */
507a04ea15dStb local void pqdownheap(deflate_state *s, ct_data *tree, int k) {
5082af503bcStholo     int v = s->heap[k];
5092af503bcStholo     int j = k << 1;  /* left son of k */
5102af503bcStholo     while (j <= s->heap_len) {
5112af503bcStholo         /* Set j to the smallest of the two sons: */
5122af503bcStholo         if (j < s->heap_len &&
5132af503bcStholo             smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) {
5142af503bcStholo             j++;
5152af503bcStholo         }
5162af503bcStholo         /* Exit if v is smaller than both sons */
5172af503bcStholo         if (smaller(tree, v, s->heap[j], s->depth)) break;
5182af503bcStholo 
5192af503bcStholo         /* Exchange v with the smallest son */
5202af503bcStholo         s->heap[k] = s->heap[j];  k = j;
5212af503bcStholo 
5222af503bcStholo         /* And continue down the tree, setting j to the left son of k */
5232af503bcStholo         j <<= 1;
5242af503bcStholo     }
5252af503bcStholo     s->heap[k] = v;
5262af503bcStholo }
5272af503bcStholo 
5282af503bcStholo /* ===========================================================================
5292af503bcStholo  * Compute the optimal bit lengths for a tree and update the total bit length
5302af503bcStholo  * for the current block.
5312af503bcStholo  * IN assertion: the fields freq and dad are set, heap[heap_max] and
5322af503bcStholo  *    above are the tree nodes sorted by increasing frequency.
5332af503bcStholo  * OUT assertions: the field len is set to the optimal bit length, the
5342af503bcStholo  *     array bl_count contains the frequencies for each bit length.
5352af503bcStholo  *     The length opt_len is updated; static_len is also updated if stree is
5362af503bcStholo  *     not null.
5372af503bcStholo  */
538a04ea15dStb local void gen_bitlen(deflate_state *s, tree_desc *desc) {
5392af503bcStholo     ct_data *tree        = desc->dyn_tree;
5402af503bcStholo     int max_code         = desc->max_code;
54115ce0796Smillert     const ct_data *stree = desc->stat_desc->static_tree;
54215ce0796Smillert     const intf *extra    = desc->stat_desc->extra_bits;
5432af503bcStholo     int base             = desc->stat_desc->extra_base;
5442af503bcStholo     int max_length       = desc->stat_desc->max_length;
5452af503bcStholo     int h;              /* heap index */
5462af503bcStholo     int n, m;           /* iterate over the tree elements */
5472af503bcStholo     int bits;           /* bit length */
5482af503bcStholo     int xbits;          /* extra bits */
5492af503bcStholo     ush f;              /* frequency */
5502af503bcStholo     int overflow = 0;   /* number of elements with bit length too large */
5512af503bcStholo 
5522af503bcStholo     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
5532af503bcStholo 
5542af503bcStholo     /* In a first pass, compute the optimal bit lengths (which may
5552af503bcStholo      * overflow in the case of the bit length tree).
5562af503bcStholo      */
5572af503bcStholo     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
5582af503bcStholo 
5592af503bcStholo     for (h = s->heap_max + 1; h < HEAP_SIZE; h++) {
5602af503bcStholo         n = s->heap[h];
5612af503bcStholo         bits = tree[tree[n].Dad].Len + 1;
5622af503bcStholo         if (bits > max_length) bits = max_length, overflow++;
5632af503bcStholo         tree[n].Len = (ush)bits;
5642af503bcStholo         /* We overwrite tree[n].Dad which is no longer needed */
5652af503bcStholo 
5662af503bcStholo         if (n > max_code) continue; /* not a leaf node */
5672af503bcStholo 
5682af503bcStholo         s->bl_count[bits]++;
5692af503bcStholo         xbits = 0;
5702af503bcStholo         if (n >= base) xbits = extra[n - base];
5712af503bcStholo         f = tree[n].Freq;
57236f395ceStb         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
57336f395ceStb         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
5742af503bcStholo     }
5752af503bcStholo     if (overflow == 0) return;
5762af503bcStholo 
57736f395ceStb     Tracev((stderr,"\nbit length overflow\n"));
5782af503bcStholo     /* This happens for example on obj2 and pic of the Calgary corpus */
5792af503bcStholo 
5802af503bcStholo     /* Find the first bit length which could increase: */
5812af503bcStholo     do {
5822af503bcStholo         bits = max_length - 1;
5832af503bcStholo         while (s->bl_count[bits] == 0) bits--;
5842af503bcStholo         s->bl_count[bits]--;        /* move one leaf down the tree */
5852af503bcStholo         s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */
5862af503bcStholo         s->bl_count[max_length]--;
5872af503bcStholo         /* The brother of the overflow item also moves one step up,
5882af503bcStholo          * but this does not affect bl_count[max_length]
5892af503bcStholo          */
5902af503bcStholo         overflow -= 2;
5912af503bcStholo     } while (overflow > 0);
5922af503bcStholo 
5932af503bcStholo     /* Now recompute all bit lengths, scanning in increasing frequency.
5942af503bcStholo      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
5952af503bcStholo      * lengths instead of fixing only the wrong ones. This idea is taken
5962af503bcStholo      * from 'ar' written by Haruhiko Okumura.)
5972af503bcStholo      */
5982af503bcStholo     for (bits = max_length; bits != 0; bits--) {
5992af503bcStholo         n = s->bl_count[bits];
6002af503bcStholo         while (n != 0) {
6012af503bcStholo             m = s->heap[--h];
6022af503bcStholo             if (m > max_code) continue;
603d76b9bfaSmillert             if ((unsigned) tree[m].Len != (unsigned) bits) {
60436f395ceStb                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
60536f395ceStb                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
6062af503bcStholo                 tree[m].Len = (ush)bits;
6072af503bcStholo             }
6082af503bcStholo             n--;
6092af503bcStholo         }
6102af503bcStholo     }
6112af503bcStholo }
6122af503bcStholo 
613a04ea15dStb #ifdef DUMP_BL_TREE
614a04ea15dStb #  include <stdio.h>
615a04ea15dStb #endif
6162af503bcStholo 
6172af503bcStholo /* ===========================================================================
6182af503bcStholo  * Construct one Huffman tree and assigns the code bit strings and lengths.
6192af503bcStholo  * Update the total bit length for the current block.
6202af503bcStholo  * IN assertion: the field freq is set for all tree elements.
6212af503bcStholo  * OUT assertions: the fields len and code are set to the optimal bit length
6222af503bcStholo  *     and corresponding code. The length opt_len is updated; static_len is
6232af503bcStholo  *     also updated if stree is not null. The field max_code is set.
6242af503bcStholo  */
625a04ea15dStb local void build_tree(deflate_state *s, tree_desc *desc) {
6262af503bcStholo     ct_data *tree         = desc->dyn_tree;
62715ce0796Smillert     const ct_data *stree  = desc->stat_desc->static_tree;
6282af503bcStholo     int elems             = desc->stat_desc->elems;
6292af503bcStholo     int n, m;          /* iterate over heap elements */
6302af503bcStholo     int max_code = -1; /* largest code with non zero frequency */
6312af503bcStholo     int node;          /* new node being created */
6322af503bcStholo 
6332af503bcStholo     /* Construct the initial heap, with least frequent element in
6342af503bcStholo      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1].
6352af503bcStholo      * heap[0] is not used.
6362af503bcStholo      */
6372af503bcStholo     s->heap_len = 0, s->heap_max = HEAP_SIZE;
6382af503bcStholo 
6392af503bcStholo     for (n = 0; n < elems; n++) {
6402af503bcStholo         if (tree[n].Freq != 0) {
6412af503bcStholo             s->heap[++(s->heap_len)] = max_code = n;
6422af503bcStholo             s->depth[n] = 0;
6432af503bcStholo         } else {
6442af503bcStholo             tree[n].Len = 0;
6452af503bcStholo         }
6462af503bcStholo     }
6472af503bcStholo 
6482af503bcStholo     /* The pkzip format requires that at least one distance code exists,
6492af503bcStholo      * and that at least one bit should be sent even if there is only one
6502af503bcStholo      * possible code. So to avoid special checks later on we force at least
6512af503bcStholo      * two codes of non zero frequency.
6522af503bcStholo      */
6532af503bcStholo     while (s->heap_len < 2) {
6542af503bcStholo         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
6552af503bcStholo         tree[node].Freq = 1;
6562af503bcStholo         s->depth[node] = 0;
6572af503bcStholo         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
6582af503bcStholo         /* node is 0 or 1 so it does not have extra bits */
6592af503bcStholo     }
6602af503bcStholo     desc->max_code = max_code;
6612af503bcStholo 
6622af503bcStholo     /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree,
6632af503bcStholo      * establish sub-heaps of increasing lengths:
6642af503bcStholo      */
6652af503bcStholo     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
6662af503bcStholo 
6672af503bcStholo     /* Construct the Huffman tree by repeatedly combining the least two
6682af503bcStholo      * frequent nodes.
6692af503bcStholo      */
6702af503bcStholo     node = elems;              /* next internal node of the tree */
6712af503bcStholo     do {
6722af503bcStholo         pqremove(s, tree, n);  /* n = node of least frequency */
6732af503bcStholo         m = s->heap[SMALLEST]; /* m = node of next least frequency */
6742af503bcStholo 
6752af503bcStholo         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
6762af503bcStholo         s->heap[--(s->heap_max)] = m;
6772af503bcStholo 
6782af503bcStholo         /* Create a new node father of n and m */
6792af503bcStholo         tree[node].Freq = tree[n].Freq + tree[m].Freq;
68085c48e79Shenning         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
68185c48e79Shenning                                 s->depth[n] : s->depth[m]) + 1);
6822af503bcStholo         tree[n].Dad = tree[m].Dad = (ush)node;
6832af503bcStholo #ifdef DUMP_BL_TREE
6842af503bcStholo         if (tree == s->bl_tree) {
6852af503bcStholo             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
6862af503bcStholo                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
6872af503bcStholo         }
6882af503bcStholo #endif
6892af503bcStholo         /* and insert the new node in the heap */
6902af503bcStholo         s->heap[SMALLEST] = node++;
6912af503bcStholo         pqdownheap(s, tree, SMALLEST);
6922af503bcStholo 
6932af503bcStholo     } while (s->heap_len >= 2);
6942af503bcStholo 
6952af503bcStholo     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
6962af503bcStholo 
6972af503bcStholo     /* At this point, the fields freq and dad are set. We can now
6982af503bcStholo      * generate the bit lengths.
6992af503bcStholo      */
7002af503bcStholo     gen_bitlen(s, (tree_desc *)desc);
7012af503bcStholo 
7022af503bcStholo     /* The field len is now set, we can generate the bit codes */
7032af503bcStholo     gen_codes ((ct_data *)tree, max_code, s->bl_count);
7042af503bcStholo }
7052af503bcStholo 
7062af503bcStholo /* ===========================================================================
7072af503bcStholo  * Scan a literal or distance tree to determine the frequencies of the codes
7082af503bcStholo  * in the bit length tree.
7092af503bcStholo  */
710a04ea15dStb local void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
7112af503bcStholo     int n;                     /* iterates over all tree elements */
7122af503bcStholo     int prevlen = -1;          /* last emitted length */
7132af503bcStholo     int curlen;                /* length of current code */
7142af503bcStholo     int nextlen = tree[0].Len; /* length of next code */
7152af503bcStholo     int count = 0;             /* repeat count of the current code */
7162af503bcStholo     int max_count = 7;         /* max repeat count */
7172af503bcStholo     int min_count = 4;         /* min repeat count */
7182af503bcStholo 
7192af503bcStholo     if (nextlen == 0) max_count = 138, min_count = 3;
7202af503bcStholo     tree[max_code + 1].Len = (ush)0xffff; /* guard */
7212af503bcStholo 
7222af503bcStholo     for (n = 0; n <= max_code; n++) {
7232af503bcStholo         curlen = nextlen; nextlen = tree[n + 1].Len;
7242af503bcStholo         if (++count < max_count && curlen == nextlen) {
7252af503bcStholo             continue;
7262af503bcStholo         } else if (count < min_count) {
72741a6a251Stb             s->bl_tree[curlen].Freq += (ush)count;
7282af503bcStholo         } else if (curlen != 0) {
7292af503bcStholo             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
7302af503bcStholo             s->bl_tree[REP_3_6].Freq++;
7312af503bcStholo         } else if (count <= 10) {
7322af503bcStholo             s->bl_tree[REPZ_3_10].Freq++;
7332af503bcStholo         } else {
7342af503bcStholo             s->bl_tree[REPZ_11_138].Freq++;
7352af503bcStholo         }
7362af503bcStholo         count = 0; prevlen = curlen;
7372af503bcStholo         if (nextlen == 0) {
7382af503bcStholo             max_count = 138, min_count = 3;
7392af503bcStholo         } else if (curlen == nextlen) {
7402af503bcStholo             max_count = 6, min_count = 3;
7412af503bcStholo         } else {
7422af503bcStholo             max_count = 7, min_count = 4;
7432af503bcStholo         }
7442af503bcStholo     }
7452af503bcStholo }
7462af503bcStholo 
7472af503bcStholo /* ===========================================================================
7482af503bcStholo  * Send a literal or distance tree in compressed form, using the codes in
7492af503bcStholo  * bl_tree.
7502af503bcStholo  */
751a04ea15dStb local void send_tree(deflate_state *s, ct_data *tree, int max_code) {
7522af503bcStholo     int n;                     /* iterates over all tree elements */
7532af503bcStholo     int prevlen = -1;          /* last emitted length */
7542af503bcStholo     int curlen;                /* length of current code */
7552af503bcStholo     int nextlen = tree[0].Len; /* length of next code */
7562af503bcStholo     int count = 0;             /* repeat count of the current code */
7572af503bcStholo     int max_count = 7;         /* max repeat count */
7582af503bcStholo     int min_count = 4;         /* min repeat count */
7592af503bcStholo 
7602af503bcStholo     /* tree[max_code + 1].Len = -1; */  /* guard already set */
7612af503bcStholo     if (nextlen == 0) max_count = 138, min_count = 3;
7622af503bcStholo 
7632af503bcStholo     for (n = 0; n <= max_code; n++) {
7642af503bcStholo         curlen = nextlen; nextlen = tree[n + 1].Len;
7652af503bcStholo         if (++count < max_count && curlen == nextlen) {
7662af503bcStholo             continue;
7672af503bcStholo         } else if (count < min_count) {
7682af503bcStholo             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
7692af503bcStholo 
7702af503bcStholo         } else if (curlen != 0) {
7712af503bcStholo             if (curlen != prevlen) {
7722af503bcStholo                 send_code(s, curlen, s->bl_tree); count--;
7732af503bcStholo             }
7742af503bcStholo             Assert(count >= 3 && count <= 6, " 3_6?");
7752af503bcStholo             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2);
7762af503bcStholo 
7772af503bcStholo         } else if (count <= 10) {
7782af503bcStholo             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3);
7792af503bcStholo 
7802af503bcStholo         } else {
7812af503bcStholo             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7);
7822af503bcStholo         }
7832af503bcStholo         count = 0; prevlen = curlen;
7842af503bcStholo         if (nextlen == 0) {
7852af503bcStholo             max_count = 138, min_count = 3;
7862af503bcStholo         } else if (curlen == nextlen) {
7872af503bcStholo             max_count = 6, min_count = 3;
7882af503bcStholo         } else {
7892af503bcStholo             max_count = 7, min_count = 4;
7902af503bcStholo         }
7912af503bcStholo     }
7922af503bcStholo }
7932af503bcStholo 
7942af503bcStholo /* ===========================================================================
7952af503bcStholo  * Construct the Huffman tree for the bit lengths and return the index in
7962af503bcStholo  * bl_order of the last bit length code to send.
7972af503bcStholo  */
798a04ea15dStb local int build_bl_tree(deflate_state *s) {
7992af503bcStholo     int max_blindex;  /* index of last bit length code of non zero freq */
8002af503bcStholo 
8012af503bcStholo     /* Determine the bit length frequencies for literal and distance trees */
8022af503bcStholo     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
8032af503bcStholo     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
8042af503bcStholo 
8052af503bcStholo     /* Build the bit length tree: */
8062af503bcStholo     build_tree(s, (tree_desc *)(&(s->bl_desc)));
8078bda5813Stb     /* opt_len now includes the length of the tree representations, except the
8088bda5813Stb      * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts.
8092af503bcStholo      */
8102af503bcStholo 
8112af503bcStholo     /* Determine the number of bit length codes to send. The pkzip format
8122af503bcStholo      * requires that at least 4 bit length codes be sent. (appnote.txt says
8132af503bcStholo      * 3 but the actual value used is 4.)
8142af503bcStholo      */
8152af503bcStholo     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
8162af503bcStholo         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
8172af503bcStholo     }
8182af503bcStholo     /* Update opt_len to include the bit length tree and counts */
81936f395ceStb     s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4;
8202af503bcStholo     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
8212af503bcStholo             s->opt_len, s->static_len));
8222af503bcStholo 
8232af503bcStholo     return max_blindex;
8242af503bcStholo }
8252af503bcStholo 
8262af503bcStholo /* ===========================================================================
8272af503bcStholo  * Send the header for a block using dynamic Huffman trees: the counts, the
8282af503bcStholo  * lengths of the bit length codes, the literal tree and the distance tree.
8292af503bcStholo  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
8302af503bcStholo  */
831a04ea15dStb local void send_all_trees(deflate_state *s, int lcodes, int dcodes,
832a04ea15dStb                           int blcodes) {
8332af503bcStholo     int rank;                    /* index in bl_order */
8342af503bcStholo 
8352af503bcStholo     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
8362af503bcStholo     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
8372af503bcStholo             "too many codes");
8382af503bcStholo     Tracev((stderr, "\nbl counts: "));
8392af503bcStholo     send_bits(s, lcodes - 257, 5);  /* not +255 as stated in appnote.txt */
8402af503bcStholo     send_bits(s, dcodes - 1,   5);
8412af503bcStholo     send_bits(s, blcodes - 4,  4);  /* not -3 as stated in appnote.txt */
8422af503bcStholo     for (rank = 0; rank < blcodes; rank++) {
8432af503bcStholo         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
8442af503bcStholo         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
8452af503bcStholo     }
8462af503bcStholo     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
8472af503bcStholo 
8482af503bcStholo     send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1);  /* literal tree */
8492af503bcStholo     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
8502af503bcStholo 
8512af503bcStholo     send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1);  /* distance tree */
8522af503bcStholo     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
8532af503bcStholo }
8542af503bcStholo 
8552af503bcStholo /* ===========================================================================
8562af503bcStholo  * Send a stored block
8572af503bcStholo  */
858a04ea15dStb void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf,
859a04ea15dStb                                     ulg stored_len, int last) {
86036f395ceStb     send_bits(s, (STORED_BLOCK<<1) + last, 3);  /* send block type */
86136f395ceStb     bi_windup(s);        /* align on byte boundary */
86236f395ceStb     put_short(s, (ush)stored_len);
86336f395ceStb     put_short(s, (ush)~stored_len);
864703d4924Stb     if (stored_len)
86536f395ceStb         zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
86636f395ceStb     s->pending += stored_len;
86736f395ceStb #ifdef ZLIB_DEBUG
8682af503bcStholo     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
8692af503bcStholo     s->compressed_len += (stored_len + 4) << 3;
87036f395ceStb     s->bits_sent += 2*16;
87136f395ceStb     s->bits_sent += stored_len << 3;
87215ce0796Smillert #endif
87336f395ceStb }
87436f395ceStb 
87536f395ceStb /* ===========================================================================
87636f395ceStb  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
87736f395ceStb  */
878a04ea15dStb void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) {
87936f395ceStb     bi_flush(s);
8802af503bcStholo }
8812af503bcStholo 
8822af503bcStholo /* ===========================================================================
8832af503bcStholo  * Send one empty static block to give enough lookahead for inflate.
8842af503bcStholo  * This takes 10 bits, of which 7 may remain in the bit buffer.
8852af503bcStholo  */
886a04ea15dStb void ZLIB_INTERNAL _tr_align(deflate_state *s) {
8872af503bcStholo     send_bits(s, STATIC_TREES<<1, 3);
8882af503bcStholo     send_code(s, END_BLOCK, static_ltree);
88936f395ceStb #ifdef ZLIB_DEBUG
8902af503bcStholo     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
89115ce0796Smillert #endif
8922af503bcStholo     bi_flush(s);
8932af503bcStholo }
8942af503bcStholo 
8952af503bcStholo /* ===========================================================================
896a04ea15dStb  * Send the block data compressed using the given Huffman trees
897a04ea15dStb  */
898a04ea15dStb local void compress_block(deflate_state *s, const ct_data *ltree,
899a04ea15dStb                           const ct_data *dtree) {
900a04ea15dStb     unsigned dist;      /* distance of matched string */
901a04ea15dStb     int lc;             /* match length or unmatched char (if dist == 0) */
90262a6fda7Stb     unsigned sx = 0;    /* running index in symbol buffers */
903a04ea15dStb     unsigned code;      /* the code to send */
904a04ea15dStb     int extra;          /* number of extra bits to send */
905a04ea15dStb 
906a04ea15dStb     if (s->sym_next != 0) do {
90762a6fda7Stb #ifdef LIT_MEM
90862a6fda7Stb         dist = s->d_buf[sx];
90962a6fda7Stb         lc = s->l_buf[sx++];
91062a6fda7Stb #else
911a04ea15dStb         dist = s->sym_buf[sx++] & 0xff;
912a04ea15dStb         dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
913a04ea15dStb         lc = s->sym_buf[sx++];
91462a6fda7Stb #endif
915a04ea15dStb         if (dist == 0) {
916a04ea15dStb             send_code(s, lc, ltree); /* send a literal byte */
917a04ea15dStb             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
918a04ea15dStb         } else {
919a04ea15dStb             /* Here, lc is the match length - MIN_MATCH */
920a04ea15dStb             code = _length_code[lc];
921a04ea15dStb             send_code(s, code + LITERALS + 1, ltree);   /* send length code */
922a04ea15dStb             extra = extra_lbits[code];
923a04ea15dStb             if (extra != 0) {
924a04ea15dStb                 lc -= base_length[code];
925a04ea15dStb                 send_bits(s, lc, extra);       /* send the extra length bits */
926a04ea15dStb             }
927a04ea15dStb             dist--; /* dist is now the match distance - 1 */
928a04ea15dStb             code = d_code(dist);
929a04ea15dStb             Assert (code < D_CODES, "bad d_code");
930a04ea15dStb 
931a04ea15dStb             send_code(s, code, dtree);       /* send the distance code */
932a04ea15dStb             extra = extra_dbits[code];
933a04ea15dStb             if (extra != 0) {
934a04ea15dStb                 dist -= (unsigned)base_dist[code];
935a04ea15dStb                 send_bits(s, dist, extra);   /* send the extra distance bits */
936a04ea15dStb             }
937a04ea15dStb         } /* literal or match pair ? */
938a04ea15dStb 
93962a6fda7Stb         /* Check for no overlay of pending_buf on needed symbols */
94062a6fda7Stb #ifdef LIT_MEM
941f5252e2dStb         Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow");
94262a6fda7Stb #else
943a04ea15dStb         Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
94462a6fda7Stb #endif
945a04ea15dStb 
946a04ea15dStb     } while (sx < s->sym_next);
947a04ea15dStb 
948a04ea15dStb     send_code(s, END_BLOCK, ltree);
949a04ea15dStb }
950a04ea15dStb 
951a04ea15dStb /* ===========================================================================
952a04ea15dStb  * Check if the data type is TEXT or BINARY, using the following algorithm:
953a04ea15dStb  * - TEXT if the two conditions below are satisfied:
954a04ea15dStb  *    a) There are no non-portable control characters belonging to the
955a04ea15dStb  *       "block list" (0..6, 14..25, 28..31).
956a04ea15dStb  *    b) There is at least one printable character belonging to the
957a04ea15dStb  *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
958a04ea15dStb  * - BINARY otherwise.
959a04ea15dStb  * - The following partially-portable control characters form a
960a04ea15dStb  *   "gray list" that is ignored in this detection algorithm:
961a04ea15dStb  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
962a04ea15dStb  * IN assertion: the fields Freq of dyn_ltree are set.
963a04ea15dStb  */
964a04ea15dStb local int detect_data_type(deflate_state *s) {
965a04ea15dStb     /* block_mask is the bit mask of block-listed bytes
966a04ea15dStb      * set bits 0..6, 14..25, and 28..31
967a04ea15dStb      * 0xf3ffc07f = binary 11110011111111111100000001111111
968a04ea15dStb      */
969a04ea15dStb     unsigned long block_mask = 0xf3ffc07fUL;
970a04ea15dStb     int n;
971a04ea15dStb 
972a04ea15dStb     /* Check for non-textual ("block-listed") bytes. */
973a04ea15dStb     for (n = 0; n <= 31; n++, block_mask >>= 1)
974a04ea15dStb         if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
975a04ea15dStb             return Z_BINARY;
976a04ea15dStb 
977a04ea15dStb     /* Check for textual ("allow-listed") bytes. */
978a04ea15dStb     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
979a04ea15dStb             || s->dyn_ltree[13].Freq != 0)
980a04ea15dStb         return Z_TEXT;
981a04ea15dStb     for (n = 32; n < LITERALS; n++)
982a04ea15dStb         if (s->dyn_ltree[n].Freq != 0)
983a04ea15dStb             return Z_TEXT;
984a04ea15dStb 
985a04ea15dStb     /* There are no "block-listed" or "allow-listed" bytes:
986a04ea15dStb      * this stream either is empty or has tolerated ("gray-listed") bytes only.
987a04ea15dStb      */
988a04ea15dStb     return Z_BINARY;
989a04ea15dStb }
990a04ea15dStb 
991a04ea15dStb /* ===========================================================================
9922af503bcStholo  * Determine the best encoding for the current block: dynamic trees, static
99336f395ceStb  * trees or store, and write out the encoded block.
9942af503bcStholo  */
995a04ea15dStb void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
996a04ea15dStb                                    ulg stored_len, int last) {
9972af503bcStholo     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
9982af503bcStholo     int max_blindex = 0;  /* index of last bit length code of non zero freq */
9992af503bcStholo 
10002af503bcStholo     /* Build the Huffman trees unless a stored block is forced */
10012af503bcStholo     if (s->level > 0) {
10022af503bcStholo 
1003d76b9bfaSmillert         /* Check if the file is binary or text */
100436f395ceStb         if (s->strm->data_type == Z_UNKNOWN)
100536f395ceStb             s->strm->data_type = detect_data_type(s);
10062af503bcStholo 
10072af503bcStholo         /* Construct the literal and distance trees */
10082af503bcStholo         build_tree(s, (tree_desc *)(&(s->l_desc)));
10092af503bcStholo         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
10102af503bcStholo                 s->static_len));
10112af503bcStholo 
10122af503bcStholo         build_tree(s, (tree_desc *)(&(s->d_desc)));
10132af503bcStholo         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
10142af503bcStholo                 s->static_len));
10152af503bcStholo         /* At this point, opt_len and static_len are the total bit lengths of
10162af503bcStholo          * the compressed block data, excluding the tree representations.
10172af503bcStholo          */
10182af503bcStholo 
10192af503bcStholo         /* Build the bit length tree for the above two trees, and get the index
10202af503bcStholo          * in bl_order of the last bit length code to send.
10212af503bcStholo          */
10222af503bcStholo         max_blindex = build_bl_tree(s);
10232af503bcStholo 
102485c48e79Shenning         /* Determine the best encoding. Compute the block lengths in bytes. */
10252af503bcStholo         opt_lenb = (s->opt_len + 3 + 7) >> 3;
10262af503bcStholo         static_lenb = (s->static_len + 3 + 7) >> 3;
10272af503bcStholo 
10282af503bcStholo         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
10292af503bcStholo                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
1030f0c342b3Stb                 s->sym_next / 3));
10312af503bcStholo 
10328bda5813Stb #ifndef FORCE_STATIC
10338bda5813Stb         if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
10348bda5813Stb #endif
10358bda5813Stb             opt_lenb = static_lenb;
10362af503bcStholo 
10372af503bcStholo     } else {
10382af503bcStholo         Assert(buf != (char*)0, "lost buf");
10392af503bcStholo         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
10402af503bcStholo     }
10412af503bcStholo 
10422af503bcStholo #ifdef FORCE_STORED
10432af503bcStholo     if (buf != (char*)0) { /* force stored block */
10442af503bcStholo #else
10452af503bcStholo     if (stored_len + 4 <= opt_lenb && buf != (char*)0) {
10462af503bcStholo                        /* 4: two words for the lengths */
10472af503bcStholo #endif
10482af503bcStholo         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
10492af503bcStholo          * Otherwise we can't have processed more than WSIZE input bytes since
10502af503bcStholo          * the last block flush, because compression would have been
10512af503bcStholo          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
10522af503bcStholo          * transform a block into a stored block.
10532af503bcStholo          */
105436f395ceStb         _tr_stored_block(s, buf, stored_len, last);
10552af503bcStholo 
10568bda5813Stb     } else if (static_lenb == opt_lenb) {
105736f395ceStb         send_bits(s, (STATIC_TREES<<1) + last, 3);
105836f395ceStb         compress_block(s, (const ct_data *)static_ltree,
105936f395ceStb                        (const ct_data *)static_dtree);
106036f395ceStb #ifdef ZLIB_DEBUG
10612af503bcStholo         s->compressed_len += 3 + s->static_len;
106215ce0796Smillert #endif
10632af503bcStholo     } else {
106436f395ceStb         send_bits(s, (DYN_TREES<<1) + last, 3);
10652af503bcStholo         send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1,
10662af503bcStholo                        max_blindex + 1);
106736f395ceStb         compress_block(s, (const ct_data *)s->dyn_ltree,
106836f395ceStb                        (const ct_data *)s->dyn_dtree);
106936f395ceStb #ifdef ZLIB_DEBUG
10702af503bcStholo         s->compressed_len += 3 + s->opt_len;
107115ce0796Smillert #endif
10722af503bcStholo     }
10732af503bcStholo     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
107415ce0796Smillert     /* The above check is made mod 2^32, for files larger than 512 MB
107515ce0796Smillert      * and uLong implemented on 32 bits.
107615ce0796Smillert      */
10772af503bcStholo     init_block(s);
10782af503bcStholo 
107936f395ceStb     if (last) {
10802af503bcStholo         bi_windup(s);
108136f395ceStb #ifdef ZLIB_DEBUG
10822af503bcStholo         s->compressed_len += 7;  /* align on byte boundary */
108315ce0796Smillert #endif
10842af503bcStholo     }
10852af503bcStholo     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3,
108636f395ceStb            s->compressed_len - 7*last));
10872af503bcStholo }
10882af503bcStholo 
10892af503bcStholo /* ===========================================================================
10902af503bcStholo  * Save the match info and tally the frequency counts. Return true if
10912af503bcStholo  * the current block must be flushed.
10922af503bcStholo  */
1093a04ea15dStb int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) {
109462a6fda7Stb #ifdef LIT_MEM
109562a6fda7Stb     s->d_buf[s->sym_next] = (ush)dist;
109662a6fda7Stb     s->l_buf[s->sym_next++] = (uch)lc;
109762a6fda7Stb #else
10988bda5813Stb     s->sym_buf[s->sym_next++] = (uch)dist;
10998bda5813Stb     s->sym_buf[s->sym_next++] = (uch)(dist >> 8);
11008bda5813Stb     s->sym_buf[s->sym_next++] = (uch)lc;
110162a6fda7Stb #endif
11022af503bcStholo     if (dist == 0) {
11032af503bcStholo         /* lc is the unmatched char */
11042af503bcStholo         s->dyn_ltree[lc].Freq++;
11052af503bcStholo     } else {
11062af503bcStholo         s->matches++;
11072af503bcStholo         /* Here, lc is the match length - MIN_MATCH */
11082af503bcStholo         dist--;             /* dist = match distance - 1 */
11092af503bcStholo         Assert((ush)dist < (ush)MAX_DIST(s) &&
11102af503bcStholo                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
11112af503bcStholo                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
11122af503bcStholo 
111315ce0796Smillert         s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++;
11142af503bcStholo         s->dyn_dtree[d_code(dist)].Freq++;
11152af503bcStholo     }
1116f0c342b3Stb     return (s->sym_next == s->sym_end);
11172af503bcStholo }
1118