19573673dSchristos /* trees.c -- output deflated data using Huffman coding
2*4f645668Schristos * Copyright (C) 1995-2021 Jean-loup Gailly
39573673dSchristos * detect_data_type() function provided freely by Cosmin Truta, 2006
49573673dSchristos * For conditions of distribution and use, see copyright notice in zlib.h
59573673dSchristos */
69573673dSchristos
79573673dSchristos /*
89573673dSchristos * ALGORITHM
99573673dSchristos *
109573673dSchristos * The "deflation" process uses several Huffman trees. The more
119573673dSchristos * common source values are represented by shorter bit sequences.
129573673dSchristos *
139573673dSchristos * Each code tree is stored in a compressed form which is itself
149573673dSchristos * a Huffman encoding of the lengths of all the code strings (in
159573673dSchristos * ascending order by source values). The actual code strings are
169573673dSchristos * reconstructed from the lengths in the inflate process, as described
179573673dSchristos * in the deflate specification.
189573673dSchristos *
199573673dSchristos * REFERENCES
209573673dSchristos *
219573673dSchristos * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
229573673dSchristos * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
239573673dSchristos *
249573673dSchristos * Storer, James A.
259573673dSchristos * Data Compression: Methods and Theory, pp. 49-50.
269573673dSchristos * Computer Science Press, 1988. ISBN 0-7167-8156-5.
279573673dSchristos *
289573673dSchristos * Sedgewick, R.
299573673dSchristos * Algorithms, p290.
309573673dSchristos * Addison-Wesley, 1983. ISBN 0-201-06672-6.
319573673dSchristos */
329573673dSchristos
33*4f645668Schristos /* @(#) Id */
349573673dSchristos
359573673dSchristos /* #define GEN_TREES_H */
369573673dSchristos
379573673dSchristos #include "deflate.h"
389573673dSchristos
39fc4f4269Schristos #ifdef ZLIB_DEBUG
409573673dSchristos # include <ctype.h>
419573673dSchristos #endif
429573673dSchristos
439573673dSchristos /* ===========================================================================
449573673dSchristos * Constants
459573673dSchristos */
469573673dSchristos
479573673dSchristos #define MAX_BL_BITS 7
489573673dSchristos /* Bit length codes must not exceed MAX_BL_BITS bits */
499573673dSchristos
509573673dSchristos #define END_BLOCK 256
519573673dSchristos /* end of block literal code */
529573673dSchristos
539573673dSchristos #define REP_3_6 16
549573673dSchristos /* repeat previous bit length 3-6 times (2 bits of repeat count) */
559573673dSchristos
569573673dSchristos #define REPZ_3_10 17
579573673dSchristos /* repeat a zero length 3-10 times (3 bits of repeat count) */
589573673dSchristos
599573673dSchristos #define REPZ_11_138 18
609573673dSchristos /* repeat a zero length 11-138 times (7 bits of repeat count) */
619573673dSchristos
629573673dSchristos local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
639573673dSchristos = {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};
649573673dSchristos
659573673dSchristos local const int extra_dbits[D_CODES] /* extra bits for each distance code */
669573673dSchristos = {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};
679573673dSchristos
689573673dSchristos local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
699573673dSchristos = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
709573673dSchristos
719573673dSchristos local const uch bl_order[BL_CODES]
729573673dSchristos = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
739573673dSchristos /* The lengths of the bit length codes are sent in order of decreasing
749573673dSchristos * probability, to avoid transmitting the lengths for unused bit length codes.
759573673dSchristos */
769573673dSchristos
779573673dSchristos /* ===========================================================================
789573673dSchristos * Local data. These are initialized only once.
799573673dSchristos */
809573673dSchristos
819573673dSchristos #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
829573673dSchristos
839573673dSchristos #if defined(GEN_TREES_H) || !defined(STDC)
849573673dSchristos /* non ANSI compilers may not accept trees.h */
859573673dSchristos
869573673dSchristos local ct_data static_ltree[L_CODES+2];
879573673dSchristos /* The static literal tree. Since the bit lengths are imposed, there is no
889573673dSchristos * need for the L_CODES extra codes used during heap construction. However
899573673dSchristos * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
909573673dSchristos * below).
919573673dSchristos */
929573673dSchristos
939573673dSchristos local ct_data static_dtree[D_CODES];
949573673dSchristos /* The static distance tree. (Actually a trivial tree since all codes use
959573673dSchristos * 5 bits.)
969573673dSchristos */
979573673dSchristos
989573673dSchristos uch _dist_code[DIST_CODE_LEN];
999573673dSchristos /* Distance codes. The first 256 values correspond to the distances
1009573673dSchristos * 3 .. 258, the last 256 values correspond to the top 8 bits of
1019573673dSchristos * the 15 bit distances.
1029573673dSchristos */
1039573673dSchristos
1049573673dSchristos uch _length_code[MAX_MATCH-MIN_MATCH+1];
1059573673dSchristos /* length code for each normalized match length (0 == MIN_MATCH) */
1069573673dSchristos
1079573673dSchristos local int base_length[LENGTH_CODES];
1089573673dSchristos /* First normalized length for each code (0 = MIN_MATCH) */
1099573673dSchristos
1109573673dSchristos local int base_dist[D_CODES];
1119573673dSchristos /* First normalized distance for each code (0 = distance of 1) */
1129573673dSchristos
1139573673dSchristos #else
1149573673dSchristos # include "trees.h"
1159573673dSchristos #endif /* GEN_TREES_H */
1169573673dSchristos
1179573673dSchristos struct static_tree_desc_s {
1189573673dSchristos const ct_data *static_tree; /* static tree or NULL */
1199573673dSchristos const intf *extra_bits; /* extra bits for each code or NULL */
1209573673dSchristos int extra_base; /* base index for extra_bits */
1219573673dSchristos int elems; /* max number of elements in the tree */
1229573673dSchristos int max_length; /* max bit length for the codes */
1239573673dSchristos };
1249573673dSchristos
125fc4f4269Schristos local const static_tree_desc static_l_desc =
1269573673dSchristos {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
1279573673dSchristos
128fc4f4269Schristos local const static_tree_desc static_d_desc =
1299573673dSchristos {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
1309573673dSchristos
131fc4f4269Schristos local const static_tree_desc static_bl_desc =
1329573673dSchristos {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
1339573673dSchristos
1349573673dSchristos /* ===========================================================================
1359573673dSchristos * Local (static) routines in this file.
1369573673dSchristos */
1379573673dSchristos
1389573673dSchristos local void tr_static_init OF((void));
1399573673dSchristos local void init_block OF((deflate_state *s));
1409573673dSchristos local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
1419573673dSchristos local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
1429573673dSchristos local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
1439573673dSchristos local void build_tree OF((deflate_state *s, tree_desc *desc));
1449573673dSchristos local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
1459573673dSchristos local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
1469573673dSchristos local int build_bl_tree OF((deflate_state *s));
1479573673dSchristos local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
1489573673dSchristos int blcodes));
1498cbf5cb7Schristos local void compress_block OF((deflate_state *s, const ct_data *ltree,
1508cbf5cb7Schristos const ct_data *dtree));
1519573673dSchristos local int detect_data_type OF((deflate_state *s));
152*4f645668Schristos local unsigned bi_reverse OF((unsigned code, int len));
1539573673dSchristos local void bi_windup OF((deflate_state *s));
1549573673dSchristos local void bi_flush OF((deflate_state *s));
1559573673dSchristos
1569573673dSchristos #ifdef GEN_TREES_H
1579573673dSchristos local void gen_trees_header OF((void));
1589573673dSchristos #endif
1599573673dSchristos
160fc4f4269Schristos #ifndef ZLIB_DEBUG
1619573673dSchristos # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
1629573673dSchristos /* Send a code of the given tree. c and tree must not have side effects */
1639573673dSchristos
164fc4f4269Schristos #else /* !ZLIB_DEBUG */
1659573673dSchristos # define send_code(s, c, tree) \
1669573673dSchristos { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
1679573673dSchristos send_bits(s, tree[c].Code, tree[c].Len); }
1689573673dSchristos #endif
1699573673dSchristos
1709573673dSchristos /* ===========================================================================
1719573673dSchristos * Output a short LSB first on the stream.
1729573673dSchristos * IN assertion: there is enough room in pendingBuf.
1739573673dSchristos */
1749573673dSchristos #define put_short(s, w) { \
1759573673dSchristos put_byte(s, (uch)((w) & 0xff)); \
1769573673dSchristos put_byte(s, (uch)((ush)(w) >> 8)); \
1779573673dSchristos }
1789573673dSchristos
1799573673dSchristos /* ===========================================================================
1809573673dSchristos * Send a value on a given number of bits.
1819573673dSchristos * IN assertion: length <= 16 and value fits in length bits.
1829573673dSchristos */
183fc4f4269Schristos #ifdef ZLIB_DEBUG
1849573673dSchristos local void send_bits OF((deflate_state *s, int value, int length));
1859573673dSchristos
send_bits(s,value,length)1869573673dSchristos local void send_bits(s, value, length)
1879573673dSchristos deflate_state *s;
1889573673dSchristos int value; /* value to send */
1899573673dSchristos int length; /* number of bits */
1909573673dSchristos {
1919573673dSchristos Tracevv((stderr," l %2d v %4x ", length, value));
1929573673dSchristos Assert(length > 0 && length <= 15, "invalid length");
1939573673dSchristos s->bits_sent += (ulg)length;
1949573673dSchristos
1959573673dSchristos /* If not enough room in bi_buf, use (valid) bits from bi_buf and
1969573673dSchristos * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
1979573673dSchristos * unused bits in value.
1989573673dSchristos */
1999573673dSchristos if (s->bi_valid > (int)Buf_size - length) {
2009573673dSchristos s->bi_buf |= (ush)value << s->bi_valid;
2019573673dSchristos put_short(s, s->bi_buf);
2029573673dSchristos s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
2039573673dSchristos s->bi_valid += length - Buf_size;
2049573673dSchristos } else {
2059573673dSchristos s->bi_buf |= (ush)value << s->bi_valid;
2069573673dSchristos s->bi_valid += length;
2079573673dSchristos }
2089573673dSchristos }
209fc4f4269Schristos #else /* !ZLIB_DEBUG */
2109573673dSchristos
2119573673dSchristos #define send_bits(s, value, length) \
2129573673dSchristos { int len = length;\
2139573673dSchristos if (s->bi_valid > (int)Buf_size - len) {\
214fc4f4269Schristos int val = (int)value;\
2159573673dSchristos s->bi_buf |= (ush)val << s->bi_valid;\
2169573673dSchristos put_short(s, s->bi_buf);\
2179573673dSchristos s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
2189573673dSchristos s->bi_valid += len - Buf_size;\
2199573673dSchristos } else {\
2209573673dSchristos s->bi_buf |= (ush)(value) << s->bi_valid;\
2219573673dSchristos s->bi_valid += len;\
2229573673dSchristos }\
2239573673dSchristos }
224fc4f4269Schristos #endif /* ZLIB_DEBUG */
2259573673dSchristos
2269573673dSchristos
2279573673dSchristos /* the arguments must not have side effects */
2289573673dSchristos
2299573673dSchristos /* ===========================================================================
2309573673dSchristos * Initialize the various 'constant' tables.
2319573673dSchristos */
tr_static_init()2329573673dSchristos local void tr_static_init()
2339573673dSchristos {
2349573673dSchristos #if defined(GEN_TREES_H) || !defined(STDC)
2359573673dSchristos static int static_init_done = 0;
2369573673dSchristos int n; /* iterates over tree elements */
2379573673dSchristos int bits; /* bit counter */
2389573673dSchristos int length; /* length value */
2399573673dSchristos int code; /* code value */
2409573673dSchristos int dist; /* distance index */
2419573673dSchristos ush bl_count[MAX_BITS+1];
2429573673dSchristos /* number of codes at each bit length for an optimal tree */
2439573673dSchristos
2449573673dSchristos if (static_init_done) return;
2459573673dSchristos
2469573673dSchristos /* For some embedded targets, global variables are not initialized: */
2479573673dSchristos #ifdef NO_INIT_GLOBAL_POINTERS
2489573673dSchristos static_l_desc.static_tree = static_ltree;
2499573673dSchristos static_l_desc.extra_bits = extra_lbits;
2509573673dSchristos static_d_desc.static_tree = static_dtree;
2519573673dSchristos static_d_desc.extra_bits = extra_dbits;
2529573673dSchristos static_bl_desc.extra_bits = extra_blbits;
2539573673dSchristos #endif
2549573673dSchristos
2559573673dSchristos /* Initialize the mapping length (0..255) -> length code (0..28) */
2569573673dSchristos length = 0;
2579573673dSchristos for (code = 0; code < LENGTH_CODES-1; code++) {
2589573673dSchristos base_length[code] = length;
2599573673dSchristos for (n = 0; n < (1<<extra_lbits[code]); n++) {
2609573673dSchristos _length_code[length++] = (uch)code;
2619573673dSchristos }
2629573673dSchristos }
2639573673dSchristos Assert (length == 256, "tr_static_init: length != 256");
2649573673dSchristos /* Note that the length 255 (match length 258) can be represented
2659573673dSchristos * in two different ways: code 284 + 5 bits or code 285, so we
2669573673dSchristos * overwrite length_code[255] to use the best encoding:
2679573673dSchristos */
2689573673dSchristos _length_code[length-1] = (uch)code;
2699573673dSchristos
2709573673dSchristos /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
2719573673dSchristos dist = 0;
2729573673dSchristos for (code = 0 ; code < 16; code++) {
2739573673dSchristos base_dist[code] = dist;
2749573673dSchristos for (n = 0; n < (1<<extra_dbits[code]); n++) {
2759573673dSchristos _dist_code[dist++] = (uch)code;
2769573673dSchristos }
2779573673dSchristos }
2789573673dSchristos Assert (dist == 256, "tr_static_init: dist != 256");
2799573673dSchristos dist >>= 7; /* from now on, all distances are divided by 128 */
2809573673dSchristos for ( ; code < D_CODES; code++) {
2819573673dSchristos base_dist[code] = dist << 7;
2829573673dSchristos for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
2839573673dSchristos _dist_code[256 + dist++] = (uch)code;
2849573673dSchristos }
2859573673dSchristos }
2869573673dSchristos Assert (dist == 256, "tr_static_init: 256+dist != 512");
2879573673dSchristos
2889573673dSchristos /* Construct the codes of the static literal tree */
2899573673dSchristos for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
2909573673dSchristos n = 0;
2919573673dSchristos while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
2929573673dSchristos while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
2939573673dSchristos while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
2949573673dSchristos while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
2959573673dSchristos /* Codes 286 and 287 do not exist, but we must include them in the
2969573673dSchristos * tree construction to get a canonical Huffman tree (longest code
2979573673dSchristos * all ones)
2989573673dSchristos */
2999573673dSchristos gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
3009573673dSchristos
3019573673dSchristos /* The static distance tree is trivial: */
3029573673dSchristos for (n = 0; n < D_CODES; n++) {
3039573673dSchristos static_dtree[n].Len = 5;
3049573673dSchristos static_dtree[n].Code = bi_reverse((unsigned)n, 5);
3059573673dSchristos }
3069573673dSchristos static_init_done = 1;
3079573673dSchristos
3089573673dSchristos # ifdef GEN_TREES_H
3099573673dSchristos gen_trees_header();
3109573673dSchristos # endif
3119573673dSchristos #endif /* defined(GEN_TREES_H) || !defined(STDC) */
3129573673dSchristos }
3139573673dSchristos
3149573673dSchristos /* ===========================================================================
3159573673dSchristos * Genererate the file trees.h describing the static trees.
3169573673dSchristos */
3179573673dSchristos #ifdef GEN_TREES_H
318fc4f4269Schristos # ifndef ZLIB_DEBUG
3199573673dSchristos # include <stdio.h>
3209573673dSchristos # endif
3219573673dSchristos
3229573673dSchristos # define SEPARATOR(i, last, width) \
3239573673dSchristos ((i) == (last)? "\n};\n\n" : \
3249573673dSchristos ((i) % (width) == (width)-1 ? ",\n" : ", "))
3259573673dSchristos
gen_trees_header()3269573673dSchristos void gen_trees_header()
3279573673dSchristos {
3289573673dSchristos FILE *header = fopen("trees.h", "w");
3299573673dSchristos int i;
3309573673dSchristos
3319573673dSchristos Assert (header != NULL, "Can't open trees.h");
3329573673dSchristos fprintf(header,
3339573673dSchristos "/* header created automatically with -DGEN_TREES_H */\n\n");
3349573673dSchristos
3359573673dSchristos fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
3369573673dSchristos for (i = 0; i < L_CODES+2; i++) {
3379573673dSchristos fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
3389573673dSchristos static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
3399573673dSchristos }
3409573673dSchristos
3419573673dSchristos fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
3429573673dSchristos for (i = 0; i < D_CODES; i++) {
3439573673dSchristos fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
3449573673dSchristos static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
3459573673dSchristos }
3469573673dSchristos
3479573673dSchristos fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
3489573673dSchristos for (i = 0; i < DIST_CODE_LEN; i++) {
3499573673dSchristos fprintf(header, "%2u%s", _dist_code[i],
3509573673dSchristos SEPARATOR(i, DIST_CODE_LEN-1, 20));
3519573673dSchristos }
3529573673dSchristos
3539573673dSchristos fprintf(header,
3549573673dSchristos "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
3559573673dSchristos for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
3569573673dSchristos fprintf(header, "%2u%s", _length_code[i],
3579573673dSchristos SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
3589573673dSchristos }
3599573673dSchristos
3609573673dSchristos fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
3619573673dSchristos for (i = 0; i < LENGTH_CODES; i++) {
3629573673dSchristos fprintf(header, "%1u%s", base_length[i],
3639573673dSchristos SEPARATOR(i, LENGTH_CODES-1, 20));
3649573673dSchristos }
3659573673dSchristos
3669573673dSchristos fprintf(header, "local const int base_dist[D_CODES] = {\n");
3679573673dSchristos for (i = 0; i < D_CODES; i++) {
3689573673dSchristos fprintf(header, "%5u%s", base_dist[i],
3699573673dSchristos SEPARATOR(i, D_CODES-1, 10));
3709573673dSchristos }
3719573673dSchristos
3729573673dSchristos fclose(header);
3739573673dSchristos }
3749573673dSchristos #endif /* GEN_TREES_H */
3759573673dSchristos
3769573673dSchristos /* ===========================================================================
3779573673dSchristos * Initialize the tree data structures for a new zlib stream.
3789573673dSchristos */
_tr_init(s)3799573673dSchristos void ZLIB_INTERNAL _tr_init(s)
3809573673dSchristos deflate_state *s;
3819573673dSchristos {
3829573673dSchristos tr_static_init();
3839573673dSchristos
3849573673dSchristos s->l_desc.dyn_tree = s->dyn_ltree;
3859573673dSchristos s->l_desc.stat_desc = &static_l_desc;
3869573673dSchristos
3879573673dSchristos s->d_desc.dyn_tree = s->dyn_dtree;
3889573673dSchristos s->d_desc.stat_desc = &static_d_desc;
3899573673dSchristos
3909573673dSchristos s->bl_desc.dyn_tree = s->bl_tree;
3919573673dSchristos s->bl_desc.stat_desc = &static_bl_desc;
3929573673dSchristos
3939573673dSchristos s->bi_buf = 0;
3949573673dSchristos s->bi_valid = 0;
395fc4f4269Schristos #ifdef ZLIB_DEBUG
3969573673dSchristos s->compressed_len = 0L;
3979573673dSchristos s->bits_sent = 0L;
3989573673dSchristos #endif
3999573673dSchristos
4009573673dSchristos /* Initialize the first block of the first file: */
4019573673dSchristos init_block(s);
4029573673dSchristos }
4039573673dSchristos
4049573673dSchristos /* ===========================================================================
4059573673dSchristos * Initialize a new block.
4069573673dSchristos */
init_block(s)4079573673dSchristos local void init_block(s)
4089573673dSchristos deflate_state *s;
4099573673dSchristos {
4109573673dSchristos int n; /* iterates over tree elements */
4119573673dSchristos
4129573673dSchristos /* Initialize the trees. */
4139573673dSchristos for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
4149573673dSchristos for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
4159573673dSchristos for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
4169573673dSchristos
4179573673dSchristos s->dyn_ltree[END_BLOCK].Freq = 1;
4189573673dSchristos s->opt_len = s->static_len = 0L;
419*4f645668Schristos s->sym_next = s->matches = 0;
4209573673dSchristos }
4219573673dSchristos
4229573673dSchristos #define SMALLEST 1
4239573673dSchristos /* Index within the heap array of least frequent node in the Huffman tree */
4249573673dSchristos
4259573673dSchristos
4269573673dSchristos /* ===========================================================================
4279573673dSchristos * Remove the smallest element from the heap and recreate the heap with
4289573673dSchristos * one less element. Updates heap and heap_len.
4299573673dSchristos */
4309573673dSchristos #define pqremove(s, tree, top) \
4319573673dSchristos {\
4329573673dSchristos top = s->heap[SMALLEST]; \
4339573673dSchristos s->heap[SMALLEST] = s->heap[s->heap_len--]; \
4349573673dSchristos pqdownheap(s, tree, SMALLEST); \
4359573673dSchristos }
4369573673dSchristos
4379573673dSchristos /* ===========================================================================
4389573673dSchristos * Compares to subtrees, using the tree depth as tie breaker when
4399573673dSchristos * the subtrees have equal frequency. This minimizes the worst case length.
4409573673dSchristos */
4419573673dSchristos #define smaller(tree, n, m, depth) \
4429573673dSchristos (tree[n].Freq < tree[m].Freq || \
4439573673dSchristos (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
4449573673dSchristos
4459573673dSchristos /* ===========================================================================
4469573673dSchristos * Restore the heap property by moving down the tree starting at node k,
4479573673dSchristos * exchanging a node with the smallest of its two sons if necessary, stopping
4489573673dSchristos * when the heap property is re-established (each father smaller than its
4499573673dSchristos * two sons).
4509573673dSchristos */
pqdownheap(s,tree,k)4519573673dSchristos local void pqdownheap(s, tree, k)
4529573673dSchristos deflate_state *s;
4539573673dSchristos ct_data *tree; /* the tree to restore */
4549573673dSchristos int k; /* node to move down */
4559573673dSchristos {
4569573673dSchristos int v = s->heap[k];
4579573673dSchristos int j = k << 1; /* left son of k */
4589573673dSchristos while (j <= s->heap_len) {
4599573673dSchristos /* Set j to the smallest of the two sons: */
4609573673dSchristos if (j < s->heap_len &&
4619573673dSchristos smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
4629573673dSchristos j++;
4639573673dSchristos }
4649573673dSchristos /* Exit if v is smaller than both sons */
4659573673dSchristos if (smaller(tree, v, s->heap[j], s->depth)) break;
4669573673dSchristos
4679573673dSchristos /* Exchange v with the smallest son */
4689573673dSchristos s->heap[k] = s->heap[j]; k = j;
4699573673dSchristos
4709573673dSchristos /* And continue down the tree, setting j to the left son of k */
4719573673dSchristos j <<= 1;
4729573673dSchristos }
4739573673dSchristos s->heap[k] = v;
4749573673dSchristos }
4759573673dSchristos
4769573673dSchristos /* ===========================================================================
4779573673dSchristos * Compute the optimal bit lengths for a tree and update the total bit length
4789573673dSchristos * for the current block.
4799573673dSchristos * IN assertion: the fields freq and dad are set, heap[heap_max] and
4809573673dSchristos * above are the tree nodes sorted by increasing frequency.
4819573673dSchristos * OUT assertions: the field len is set to the optimal bit length, the
4829573673dSchristos * array bl_count contains the frequencies for each bit length.
4839573673dSchristos * The length opt_len is updated; static_len is also updated if stree is
4849573673dSchristos * not null.
4859573673dSchristos */
gen_bitlen(s,desc)4869573673dSchristos local void gen_bitlen(s, desc)
4879573673dSchristos deflate_state *s;
4889573673dSchristos tree_desc *desc; /* the tree descriptor */
4899573673dSchristos {
4909573673dSchristos ct_data *tree = desc->dyn_tree;
4919573673dSchristos int max_code = desc->max_code;
4929573673dSchristos const ct_data *stree = desc->stat_desc->static_tree;
4939573673dSchristos const intf *extra = desc->stat_desc->extra_bits;
4949573673dSchristos int base = desc->stat_desc->extra_base;
4959573673dSchristos int max_length = desc->stat_desc->max_length;
4969573673dSchristos int h; /* heap index */
4979573673dSchristos int n, m; /* iterate over the tree elements */
4989573673dSchristos int bits; /* bit length */
4999573673dSchristos int xbits; /* extra bits */
5009573673dSchristos ush f; /* frequency */
5019573673dSchristos int overflow = 0; /* number of elements with bit length too large */
5029573673dSchristos
5039573673dSchristos for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
5049573673dSchristos
5059573673dSchristos /* In a first pass, compute the optimal bit lengths (which may
5069573673dSchristos * overflow in the case of the bit length tree).
5079573673dSchristos */
5089573673dSchristos tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
5099573673dSchristos
5109573673dSchristos for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
5119573673dSchristos n = s->heap[h];
5129573673dSchristos bits = tree[tree[n].Dad].Len + 1;
5139573673dSchristos if (bits > max_length) bits = max_length, overflow++;
5149573673dSchristos tree[n].Len = (ush)bits;
5159573673dSchristos /* We overwrite tree[n].Dad which is no longer needed */
5169573673dSchristos
5179573673dSchristos if (n > max_code) continue; /* not a leaf node */
5189573673dSchristos
5199573673dSchristos s->bl_count[bits]++;
5209573673dSchristos xbits = 0;
5219573673dSchristos if (n >= base) xbits = extra[n-base];
5229573673dSchristos f = tree[n].Freq;
523fc4f4269Schristos s->opt_len += (ulg)f * (unsigned)(bits + xbits);
524fc4f4269Schristos if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
5259573673dSchristos }
5269573673dSchristos if (overflow == 0) return;
5279573673dSchristos
528fc4f4269Schristos Tracev((stderr,"\nbit length overflow\n"));
5299573673dSchristos /* This happens for example on obj2 and pic of the Calgary corpus */
5309573673dSchristos
5319573673dSchristos /* Find the first bit length which could increase: */
5329573673dSchristos do {
5339573673dSchristos bits = max_length-1;
5349573673dSchristos while (s->bl_count[bits] == 0) bits--;
5359573673dSchristos s->bl_count[bits]--; /* move one leaf down the tree */
5369573673dSchristos s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
5379573673dSchristos s->bl_count[max_length]--;
5389573673dSchristos /* The brother of the overflow item also moves one step up,
5399573673dSchristos * but this does not affect bl_count[max_length]
5409573673dSchristos */
5419573673dSchristos overflow -= 2;
5429573673dSchristos } while (overflow > 0);
5439573673dSchristos
5449573673dSchristos /* Now recompute all bit lengths, scanning in increasing frequency.
5459573673dSchristos * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
5469573673dSchristos * lengths instead of fixing only the wrong ones. This idea is taken
5479573673dSchristos * from 'ar' written by Haruhiko Okumura.)
5489573673dSchristos */
5499573673dSchristos for (bits = max_length; bits != 0; bits--) {
5509573673dSchristos n = s->bl_count[bits];
5519573673dSchristos while (n != 0) {
5529573673dSchristos m = s->heap[--h];
5539573673dSchristos if (m > max_code) continue;
5549573673dSchristos if ((unsigned) tree[m].Len != (unsigned) bits) {
555fc4f4269Schristos Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
556fc4f4269Schristos s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
5579573673dSchristos tree[m].Len = (ush)bits;
5589573673dSchristos }
5599573673dSchristos n--;
5609573673dSchristos }
5619573673dSchristos }
5629573673dSchristos }
5639573673dSchristos
5649573673dSchristos /* ===========================================================================
5659573673dSchristos * Generate the codes for a given tree and bit counts (which need not be
5669573673dSchristos * optimal).
5679573673dSchristos * IN assertion: the array bl_count contains the bit length statistics for
5689573673dSchristos * the given tree and the field len is set for all tree elements.
5699573673dSchristos * OUT assertion: the field code is set for all tree elements of non
5709573673dSchristos * zero code length.
5719573673dSchristos */
gen_codes(tree,max_code,bl_count)5729573673dSchristos local void gen_codes (tree, max_code, bl_count)
5739573673dSchristos ct_data *tree; /* the tree to decorate */
5749573673dSchristos int max_code; /* largest code with non zero frequency */
5759573673dSchristos ushf *bl_count; /* number of codes at each bit length */
5769573673dSchristos {
5779573673dSchristos ush next_code[MAX_BITS+1]; /* next code value for each bit length */
578fc4f4269Schristos unsigned code = 0; /* running code value */
5799573673dSchristos int bits; /* bit index */
5809573673dSchristos int n; /* code index */
5819573673dSchristos
5829573673dSchristos /* The distribution counts are first used to generate the code values
5839573673dSchristos * without bit reversal.
5849573673dSchristos */
5859573673dSchristos for (bits = 1; bits <= MAX_BITS; bits++) {
586fc4f4269Schristos code = (code + bl_count[bits-1]) << 1;
587fc4f4269Schristos next_code[bits] = (ush)code;
5889573673dSchristos }
5899573673dSchristos /* Check that the bit counts in bl_count are consistent. The last code
5909573673dSchristos * must be all ones.
5919573673dSchristos */
5929573673dSchristos Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
5939573673dSchristos "inconsistent bit counts");
5949573673dSchristos Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
5959573673dSchristos
5969573673dSchristos for (n = 0; n <= max_code; n++) {
5979573673dSchristos int len = tree[n].Len;
5989573673dSchristos if (len == 0) continue;
5999573673dSchristos /* Now reverse the bits */
600fc4f4269Schristos tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
6019573673dSchristos
6029573673dSchristos Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
6039573673dSchristos n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
6049573673dSchristos }
6059573673dSchristos }
6069573673dSchristos
6079573673dSchristos /* ===========================================================================
6089573673dSchristos * Construct one Huffman tree and assigns the code bit strings and lengths.
6099573673dSchristos * Update the total bit length for the current block.
6109573673dSchristos * IN assertion: the field freq is set for all tree elements.
6119573673dSchristos * OUT assertions: the fields len and code are set to the optimal bit length
6129573673dSchristos * and corresponding code. The length opt_len is updated; static_len is
6139573673dSchristos * also updated if stree is not null. The field max_code is set.
6149573673dSchristos */
build_tree(s,desc)6159573673dSchristos local void build_tree(s, desc)
6169573673dSchristos deflate_state *s;
6179573673dSchristos tree_desc *desc; /* the tree descriptor */
6189573673dSchristos {
6199573673dSchristos ct_data *tree = desc->dyn_tree;
6209573673dSchristos const ct_data *stree = desc->stat_desc->static_tree;
6219573673dSchristos int elems = desc->stat_desc->elems;
6229573673dSchristos int n, m; /* iterate over heap elements */
6239573673dSchristos int max_code = -1; /* largest code with non zero frequency */
6249573673dSchristos int node; /* new node being created */
6259573673dSchristos
6269573673dSchristos /* Construct the initial heap, with least frequent element in
6279573673dSchristos * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
6289573673dSchristos * heap[0] is not used.
6299573673dSchristos */
6309573673dSchristos s->heap_len = 0, s->heap_max = HEAP_SIZE;
6319573673dSchristos
6329573673dSchristos for (n = 0; n < elems; n++) {
6339573673dSchristos if (tree[n].Freq != 0) {
6349573673dSchristos s->heap[++(s->heap_len)] = max_code = n;
6359573673dSchristos s->depth[n] = 0;
6369573673dSchristos } else {
6379573673dSchristos tree[n].Len = 0;
6389573673dSchristos }
6399573673dSchristos }
6409573673dSchristos
6419573673dSchristos /* The pkzip format requires that at least one distance code exists,
6429573673dSchristos * and that at least one bit should be sent even if there is only one
6439573673dSchristos * possible code. So to avoid special checks later on we force at least
6449573673dSchristos * two codes of non zero frequency.
6459573673dSchristos */
6469573673dSchristos while (s->heap_len < 2) {
6479573673dSchristos node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
6489573673dSchristos tree[node].Freq = 1;
6499573673dSchristos s->depth[node] = 0;
6509573673dSchristos s->opt_len--; if (stree) s->static_len -= stree[node].Len;
6519573673dSchristos /* node is 0 or 1 so it does not have extra bits */
6529573673dSchristos }
6539573673dSchristos desc->max_code = max_code;
6549573673dSchristos
6559573673dSchristos /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
6569573673dSchristos * establish sub-heaps of increasing lengths:
6579573673dSchristos */
6589573673dSchristos for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
6599573673dSchristos
6609573673dSchristos /* Construct the Huffman tree by repeatedly combining the least two
6619573673dSchristos * frequent nodes.
6629573673dSchristos */
6639573673dSchristos node = elems; /* next internal node of the tree */
6649573673dSchristos do {
6659573673dSchristos pqremove(s, tree, n); /* n = node of least frequency */
6669573673dSchristos m = s->heap[SMALLEST]; /* m = node of next least frequency */
6679573673dSchristos
6689573673dSchristos s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
6699573673dSchristos s->heap[--(s->heap_max)] = m;
6709573673dSchristos
6719573673dSchristos /* Create a new node father of n and m */
6729573673dSchristos tree[node].Freq = tree[n].Freq + tree[m].Freq;
6739573673dSchristos s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
6749573673dSchristos s->depth[n] : s->depth[m]) + 1);
6759573673dSchristos tree[n].Dad = tree[m].Dad = (ush)node;
6769573673dSchristos #ifdef DUMP_BL_TREE
6779573673dSchristos if (tree == s->bl_tree) {
6789573673dSchristos fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
6799573673dSchristos node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
6809573673dSchristos }
6819573673dSchristos #endif
6829573673dSchristos /* and insert the new node in the heap */
6839573673dSchristos s->heap[SMALLEST] = node++;
6849573673dSchristos pqdownheap(s, tree, SMALLEST);
6859573673dSchristos
6869573673dSchristos } while (s->heap_len >= 2);
6879573673dSchristos
6889573673dSchristos s->heap[--(s->heap_max)] = s->heap[SMALLEST];
6899573673dSchristos
6909573673dSchristos /* At this point, the fields freq and dad are set. We can now
6919573673dSchristos * generate the bit lengths.
6929573673dSchristos */
6939573673dSchristos gen_bitlen(s, (tree_desc *)desc);
6949573673dSchristos
6959573673dSchristos /* The field len is now set, we can generate the bit codes */
6969573673dSchristos gen_codes ((ct_data *)tree, max_code, s->bl_count);
6979573673dSchristos }
6989573673dSchristos
6999573673dSchristos /* ===========================================================================
7009573673dSchristos * Scan a literal or distance tree to determine the frequencies of the codes
7019573673dSchristos * in the bit length tree.
7029573673dSchristos */
scan_tree(s,tree,max_code)7039573673dSchristos local void scan_tree (s, tree, max_code)
7049573673dSchristos deflate_state *s;
7059573673dSchristos ct_data *tree; /* the tree to be scanned */
7069573673dSchristos int max_code; /* and its largest code of non zero frequency */
7079573673dSchristos {
7089573673dSchristos int n; /* iterates over all tree elements */
7099573673dSchristos int prevlen = -1; /* last emitted length */
7109573673dSchristos int curlen; /* length of current code */
7119573673dSchristos int nextlen = tree[0].Len; /* length of next code */
7129573673dSchristos int count = 0; /* repeat count of the current code */
7139573673dSchristos int max_count = 7; /* max repeat count */
7149573673dSchristos int min_count = 4; /* min repeat count */
7159573673dSchristos
7169573673dSchristos if (nextlen == 0) max_count = 138, min_count = 3;
7179573673dSchristos tree[max_code+1].Len = (ush)0xffff; /* guard */
7189573673dSchristos
7199573673dSchristos for (n = 0; n <= max_code; n++) {
7209573673dSchristos curlen = nextlen; nextlen = tree[n+1].Len;
7219573673dSchristos if (++count < max_count && curlen == nextlen) {
7229573673dSchristos continue;
7239573673dSchristos } else if (count < min_count) {
7249573673dSchristos s->bl_tree[curlen].Freq += count;
7259573673dSchristos } else if (curlen != 0) {
7269573673dSchristos if (curlen != prevlen) s->bl_tree[curlen].Freq++;
7279573673dSchristos s->bl_tree[REP_3_6].Freq++;
7289573673dSchristos } else if (count <= 10) {
7299573673dSchristos s->bl_tree[REPZ_3_10].Freq++;
7309573673dSchristos } else {
7319573673dSchristos s->bl_tree[REPZ_11_138].Freq++;
7329573673dSchristos }
7339573673dSchristos count = 0; prevlen = curlen;
7349573673dSchristos if (nextlen == 0) {
7359573673dSchristos max_count = 138, min_count = 3;
7369573673dSchristos } else if (curlen == nextlen) {
7379573673dSchristos max_count = 6, min_count = 3;
7389573673dSchristos } else {
7399573673dSchristos max_count = 7, min_count = 4;
7409573673dSchristos }
7419573673dSchristos }
7429573673dSchristos }
7439573673dSchristos
7449573673dSchristos /* ===========================================================================
7459573673dSchristos * Send a literal or distance tree in compressed form, using the codes in
7469573673dSchristos * bl_tree.
7479573673dSchristos */
send_tree(s,tree,max_code)7489573673dSchristos local void send_tree (s, tree, max_code)
7499573673dSchristos deflate_state *s;
7509573673dSchristos ct_data *tree; /* the tree to be scanned */
7519573673dSchristos int max_code; /* and its largest code of non zero frequency */
7529573673dSchristos {
7539573673dSchristos int n; /* iterates over all tree elements */
7549573673dSchristos int prevlen = -1; /* last emitted length */
7559573673dSchristos int curlen; /* length of current code */
7569573673dSchristos int nextlen = tree[0].Len; /* length of next code */
7579573673dSchristos int count = 0; /* repeat count of the current code */
7589573673dSchristos int max_count = 7; /* max repeat count */
7599573673dSchristos int min_count = 4; /* min repeat count */
7609573673dSchristos
7619573673dSchristos /* tree[max_code+1].Len = -1; */ /* guard already set */
7629573673dSchristos if (nextlen == 0) max_count = 138, min_count = 3;
7639573673dSchristos
7649573673dSchristos for (n = 0; n <= max_code; n++) {
7659573673dSchristos curlen = nextlen; nextlen = tree[n+1].Len;
7669573673dSchristos if (++count < max_count && curlen == nextlen) {
7679573673dSchristos continue;
7689573673dSchristos } else if (count < min_count) {
7699573673dSchristos do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
7709573673dSchristos
7719573673dSchristos } else if (curlen != 0) {
7729573673dSchristos if (curlen != prevlen) {
7739573673dSchristos send_code(s, curlen, s->bl_tree); count--;
7749573673dSchristos }
7759573673dSchristos Assert(count >= 3 && count <= 6, " 3_6?");
7769573673dSchristos send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
7779573673dSchristos
7789573673dSchristos } else if (count <= 10) {
7799573673dSchristos send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
7809573673dSchristos
7819573673dSchristos } else {
7829573673dSchristos send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
7839573673dSchristos }
7849573673dSchristos count = 0; prevlen = curlen;
7859573673dSchristos if (nextlen == 0) {
7869573673dSchristos max_count = 138, min_count = 3;
7879573673dSchristos } else if (curlen == nextlen) {
7889573673dSchristos max_count = 6, min_count = 3;
7899573673dSchristos } else {
7909573673dSchristos max_count = 7, min_count = 4;
7919573673dSchristos }
7929573673dSchristos }
7939573673dSchristos }
7949573673dSchristos
7959573673dSchristos /* ===========================================================================
7969573673dSchristos * Construct the Huffman tree for the bit lengths and return the index in
7979573673dSchristos * bl_order of the last bit length code to send.
7989573673dSchristos */
build_bl_tree(s)7999573673dSchristos local int build_bl_tree(s)
8009573673dSchristos deflate_state *s;
8019573673dSchristos {
8029573673dSchristos int max_blindex; /* index of last bit length code of non zero freq */
8039573673dSchristos
8049573673dSchristos /* Determine the bit length frequencies for literal and distance trees */
8059573673dSchristos scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
8069573673dSchristos scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
8079573673dSchristos
8089573673dSchristos /* Build the bit length tree: */
8099573673dSchristos build_tree(s, (tree_desc *)(&(s->bl_desc)));
8109573673dSchristos /* opt_len now includes the length of the tree representations, except
8119573673dSchristos * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
8129573673dSchristos */
8139573673dSchristos
8149573673dSchristos /* Determine the number of bit length codes to send. The pkzip format
8159573673dSchristos * requires that at least 4 bit length codes be sent. (appnote.txt says
8169573673dSchristos * 3 but the actual value used is 4.)
8179573673dSchristos */
8189573673dSchristos for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
8199573673dSchristos if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
8209573673dSchristos }
8219573673dSchristos /* Update opt_len to include the bit length tree and counts */
822fc4f4269Schristos s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
8239573673dSchristos Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
8249573673dSchristos s->opt_len, s->static_len));
8259573673dSchristos
8269573673dSchristos return max_blindex;
8279573673dSchristos }
8289573673dSchristos
8299573673dSchristos /* ===========================================================================
8309573673dSchristos * Send the header for a block using dynamic Huffman trees: the counts, the
8319573673dSchristos * lengths of the bit length codes, the literal tree and the distance tree.
8329573673dSchristos * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
8339573673dSchristos */
send_all_trees(s,lcodes,dcodes,blcodes)8349573673dSchristos local void send_all_trees(s, lcodes, dcodes, blcodes)
8359573673dSchristos deflate_state *s;
8369573673dSchristos int lcodes, dcodes, blcodes; /* number of codes for each tree */
8379573673dSchristos {
8389573673dSchristos int rank; /* index in bl_order */
8399573673dSchristos
8409573673dSchristos Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
8419573673dSchristos Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
8429573673dSchristos "too many codes");
8439573673dSchristos Tracev((stderr, "\nbl counts: "));
8449573673dSchristos send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
8459573673dSchristos send_bits(s, dcodes-1, 5);
8469573673dSchristos send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
8479573673dSchristos for (rank = 0; rank < blcodes; rank++) {
8489573673dSchristos Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
8499573673dSchristos send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
8509573673dSchristos }
8519573673dSchristos Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
8529573673dSchristos
8539573673dSchristos send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
8549573673dSchristos Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
8559573673dSchristos
8569573673dSchristos send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
8579573673dSchristos Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
8589573673dSchristos }
8599573673dSchristos
8609573673dSchristos /* ===========================================================================
8619573673dSchristos * Send a stored block
8629573673dSchristos */
_tr_stored_block(s,buf,stored_len,last)8639573673dSchristos void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
8649573673dSchristos deflate_state *s;
8659573673dSchristos charf *buf; /* input block */
8669573673dSchristos ulg stored_len; /* length of input block */
8679573673dSchristos int last; /* one if this is the last block for a file */
8689573673dSchristos {
8699573673dSchristos send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */
870fc4f4269Schristos bi_windup(s); /* align on byte boundary */
871fc4f4269Schristos put_short(s, (ush)stored_len);
872fc4f4269Schristos put_short(s, (ush)~stored_len);
873*4f645668Schristos if (stored_len)
874fc4f4269Schristos zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
875fc4f4269Schristos s->pending += stored_len;
876fc4f4269Schristos #ifdef ZLIB_DEBUG
8779573673dSchristos s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
8789573673dSchristos s->compressed_len += (stored_len + 4) << 3;
879fc4f4269Schristos s->bits_sent += 2*16;
880fc4f4269Schristos s->bits_sent += stored_len<<3;
8819573673dSchristos #endif
8829573673dSchristos }
8839573673dSchristos
8849573673dSchristos /* ===========================================================================
8859573673dSchristos * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
8869573673dSchristos */
_tr_flush_bits(s)8879573673dSchristos void ZLIB_INTERNAL _tr_flush_bits(s)
8889573673dSchristos deflate_state *s;
8899573673dSchristos {
8909573673dSchristos bi_flush(s);
8919573673dSchristos }
8929573673dSchristos
8939573673dSchristos /* ===========================================================================
8949573673dSchristos * Send one empty static block to give enough lookahead for inflate.
8959573673dSchristos * This takes 10 bits, of which 7 may remain in the bit buffer.
8969573673dSchristos */
_tr_align(s)8979573673dSchristos void ZLIB_INTERNAL _tr_align(s)
8989573673dSchristos deflate_state *s;
8999573673dSchristos {
9009573673dSchristos send_bits(s, STATIC_TREES<<1, 3);
9019573673dSchristos send_code(s, END_BLOCK, static_ltree);
902fc4f4269Schristos #ifdef ZLIB_DEBUG
9039573673dSchristos s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
9049573673dSchristos #endif
9059573673dSchristos bi_flush(s);
9069573673dSchristos }
9079573673dSchristos
9089573673dSchristos /* ===========================================================================
9099573673dSchristos * Determine the best encoding for the current block: dynamic trees, static
910fc4f4269Schristos * trees or store, and write out the encoded block.
9119573673dSchristos */
_tr_flush_block(s,buf,stored_len,last)9129573673dSchristos void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
9139573673dSchristos deflate_state *s;
9149573673dSchristos charf *buf; /* input block, or NULL if too old */
9159573673dSchristos ulg stored_len; /* length of input block */
9169573673dSchristos int last; /* one if this is the last block for a file */
9179573673dSchristos {
9189573673dSchristos ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
9199573673dSchristos int max_blindex = 0; /* index of last bit length code of non zero freq */
9209573673dSchristos
9219573673dSchristos /* Build the Huffman trees unless a stored block is forced */
9229573673dSchristos if (s->level > 0) {
9239573673dSchristos
9249573673dSchristos /* Check if the file is binary or text */
9259573673dSchristos if (s->strm->data_type == Z_UNKNOWN)
9269573673dSchristos s->strm->data_type = detect_data_type(s);
9279573673dSchristos
9289573673dSchristos /* Construct the literal and distance trees */
9299573673dSchristos build_tree(s, (tree_desc *)(&(s->l_desc)));
9309573673dSchristos Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
9319573673dSchristos s->static_len));
9329573673dSchristos
9339573673dSchristos build_tree(s, (tree_desc *)(&(s->d_desc)));
9349573673dSchristos Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
9359573673dSchristos s->static_len));
9369573673dSchristos /* At this point, opt_len and static_len are the total bit lengths of
9379573673dSchristos * the compressed block data, excluding the tree representations.
9389573673dSchristos */
9399573673dSchristos
9409573673dSchristos /* Build the bit length tree for the above two trees, and get the index
9419573673dSchristos * in bl_order of the last bit length code to send.
9429573673dSchristos */
9439573673dSchristos max_blindex = build_bl_tree(s);
9449573673dSchristos
9459573673dSchristos /* Determine the best encoding. Compute the block lengths in bytes. */
9469573673dSchristos opt_lenb = (s->opt_len+3+7)>>3;
9479573673dSchristos static_lenb = (s->static_len+3+7)>>3;
9489573673dSchristos
9499573673dSchristos Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
9509573673dSchristos opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
951*4f645668Schristos s->sym_next / 3));
9529573673dSchristos
9539573673dSchristos if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
9549573673dSchristos
9559573673dSchristos } else {
9569573673dSchristos Assert(buf != (char*)0, "lost buf");
9579573673dSchristos opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
9589573673dSchristos }
9599573673dSchristos
9609573673dSchristos #ifdef FORCE_STORED
9619573673dSchristos if (buf != (char*)0) { /* force stored block */
9629573673dSchristos #else
9639573673dSchristos if (stored_len+4 <= opt_lenb && buf != (char*)0) {
9649573673dSchristos /* 4: two words for the lengths */
9659573673dSchristos #endif
9669573673dSchristos /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
9679573673dSchristos * Otherwise we can't have processed more than WSIZE input bytes since
9689573673dSchristos * the last block flush, because compression would have been
9699573673dSchristos * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
9709573673dSchristos * transform a block into a stored block.
9719573673dSchristos */
9729573673dSchristos _tr_stored_block(s, buf, stored_len, last);
9739573673dSchristos
9749573673dSchristos #ifdef FORCE_STATIC
9759573673dSchristos } else if (static_lenb >= 0) { /* force static trees */
9769573673dSchristos #else
9779573673dSchristos } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
9789573673dSchristos #endif
9799573673dSchristos send_bits(s, (STATIC_TREES<<1)+last, 3);
9808cbf5cb7Schristos compress_block(s, (const ct_data *)static_ltree,
9818cbf5cb7Schristos (const ct_data *)static_dtree);
982fc4f4269Schristos #ifdef ZLIB_DEBUG
9839573673dSchristos s->compressed_len += 3 + s->static_len;
9849573673dSchristos #endif
9859573673dSchristos } else {
9869573673dSchristos send_bits(s, (DYN_TREES<<1)+last, 3);
9879573673dSchristos send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
9889573673dSchristos max_blindex+1);
9898cbf5cb7Schristos compress_block(s, (const ct_data *)s->dyn_ltree,
9908cbf5cb7Schristos (const ct_data *)s->dyn_dtree);
991fc4f4269Schristos #ifdef ZLIB_DEBUG
9929573673dSchristos s->compressed_len += 3 + s->opt_len;
9939573673dSchristos #endif
9949573673dSchristos }
9959573673dSchristos Assert (s->compressed_len == s->bits_sent, "bad compressed size");
9969573673dSchristos /* The above check is made mod 2^32, for files larger than 512 MB
9979573673dSchristos * and uLong implemented on 32 bits.
9989573673dSchristos */
9999573673dSchristos init_block(s);
10009573673dSchristos
10019573673dSchristos if (last) {
10029573673dSchristos bi_windup(s);
1003fc4f4269Schristos #ifdef ZLIB_DEBUG
10049573673dSchristos s->compressed_len += 7; /* align on byte boundary */
10059573673dSchristos #endif
10069573673dSchristos }
10079573673dSchristos Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
10089573673dSchristos s->compressed_len-7*last));
10099573673dSchristos }
10109573673dSchristos
10119573673dSchristos /* ===========================================================================
10129573673dSchristos * Save the match info and tally the frequency counts. Return true if
10139573673dSchristos * the current block must be flushed.
10149573673dSchristos */
_tr_tally(s,dist,lc)10159573673dSchristos int ZLIB_INTERNAL _tr_tally (s, dist, lc)
10169573673dSchristos deflate_state *s;
10179573673dSchristos unsigned dist; /* distance of matched string */
10189573673dSchristos unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
10199573673dSchristos {
1020*4f645668Schristos s->sym_buf[s->sym_next++] = dist;
1021*4f645668Schristos s->sym_buf[s->sym_next++] = dist >> 8;
1022*4f645668Schristos s->sym_buf[s->sym_next++] = lc;
10239573673dSchristos if (dist == 0) {
10249573673dSchristos /* lc is the unmatched char */
10259573673dSchristos s->dyn_ltree[lc].Freq++;
10269573673dSchristos } else {
10279573673dSchristos s->matches++;
10289573673dSchristos /* Here, lc is the match length - MIN_MATCH */
10299573673dSchristos dist--; /* dist = match distance - 1 */
10309573673dSchristos Assert((ush)dist < (ush)MAX_DIST(s) &&
10319573673dSchristos (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
10329573673dSchristos (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
10339573673dSchristos
10349573673dSchristos s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
10359573673dSchristos s->dyn_dtree[d_code(dist)].Freq++;
10369573673dSchristos }
1037*4f645668Schristos return (s->sym_next == s->sym_end);
10389573673dSchristos }
10399573673dSchristos
10409573673dSchristos /* ===========================================================================
10419573673dSchristos * Send the block data compressed using the given Huffman trees
10429573673dSchristos */
compress_block(s,ltree,dtree)10439573673dSchristos local void compress_block(s, ltree, dtree)
10449573673dSchristos deflate_state *s;
10458cbf5cb7Schristos const ct_data *ltree; /* literal tree */
10468cbf5cb7Schristos const ct_data *dtree; /* distance tree */
10479573673dSchristos {
10489573673dSchristos unsigned dist; /* distance of matched string */
10499573673dSchristos int lc; /* match length or unmatched char (if dist == 0) */
1050*4f645668Schristos unsigned sx = 0; /* running index in sym_buf */
10519573673dSchristos unsigned code; /* the code to send */
10529573673dSchristos int extra; /* number of extra bits to send */
10539573673dSchristos
1054*4f645668Schristos if (s->sym_next != 0) do {
1055*4f645668Schristos dist = s->sym_buf[sx++] & 0xff;
1056*4f645668Schristos dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
1057*4f645668Schristos lc = s->sym_buf[sx++];
10589573673dSchristos if (dist == 0) {
10599573673dSchristos send_code(s, lc, ltree); /* send a literal byte */
10609573673dSchristos Tracecv(isgraph(lc), (stderr," '%c' ", lc));
10619573673dSchristos } else {
10629573673dSchristos /* Here, lc is the match length - MIN_MATCH */
10639573673dSchristos code = _length_code[lc];
10649573673dSchristos send_code(s, code+LITERALS+1, ltree); /* send the length code */
10659573673dSchristos extra = extra_lbits[code];
10669573673dSchristos if (extra != 0) {
10679573673dSchristos lc -= base_length[code];
10689573673dSchristos send_bits(s, lc, extra); /* send the extra length bits */
10699573673dSchristos }
10709573673dSchristos dist--; /* dist is now the match distance - 1 */
10719573673dSchristos code = d_code(dist);
10729573673dSchristos Assert (code < D_CODES, "bad d_code");
10739573673dSchristos
10749573673dSchristos send_code(s, code, dtree); /* send the distance code */
10759573673dSchristos extra = extra_dbits[code];
10769573673dSchristos if (extra != 0) {
1077fc4f4269Schristos dist -= (unsigned)base_dist[code];
10789573673dSchristos send_bits(s, dist, extra); /* send the extra distance bits */
10799573673dSchristos }
10809573673dSchristos } /* literal or match pair ? */
10819573673dSchristos
1082*4f645668Schristos /* Check that the overlay between pending_buf and sym_buf is ok: */
1083*4f645668Schristos Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
10849573673dSchristos
1085*4f645668Schristos } while (sx < s->sym_next);
10869573673dSchristos
10879573673dSchristos send_code(s, END_BLOCK, ltree);
10889573673dSchristos }
10899573673dSchristos
10909573673dSchristos /* ===========================================================================
10919573673dSchristos * Check if the data type is TEXT or BINARY, using the following algorithm:
10929573673dSchristos * - TEXT if the two conditions below are satisfied:
10939573673dSchristos * a) There are no non-portable control characters belonging to the
1094*4f645668Schristos * "block list" (0..6, 14..25, 28..31).
10959573673dSchristos * b) There is at least one printable character belonging to the
1096*4f645668Schristos * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
10979573673dSchristos * - BINARY otherwise.
10989573673dSchristos * - The following partially-portable control characters form a
10999573673dSchristos * "gray list" that is ignored in this detection algorithm:
11009573673dSchristos * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
11019573673dSchristos * IN assertion: the fields Freq of dyn_ltree are set.
11029573673dSchristos */
detect_data_type(s)11039573673dSchristos local int detect_data_type(s)
11049573673dSchristos deflate_state *s;
11059573673dSchristos {
1106*4f645668Schristos /* block_mask is the bit mask of block-listed bytes
11079573673dSchristos * set bits 0..6, 14..25, and 28..31
11089573673dSchristos * 0xf3ffc07f = binary 11110011111111111100000001111111
11099573673dSchristos */
1110*4f645668Schristos unsigned long block_mask = 0xf3ffc07fUL;
11119573673dSchristos int n;
11129573673dSchristos
1113*4f645668Schristos /* Check for non-textual ("block-listed") bytes. */
1114*4f645668Schristos for (n = 0; n <= 31; n++, block_mask >>= 1)
1115*4f645668Schristos if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
11169573673dSchristos return Z_BINARY;
11179573673dSchristos
1118*4f645668Schristos /* Check for textual ("allow-listed") bytes. */
11199573673dSchristos if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
11209573673dSchristos || s->dyn_ltree[13].Freq != 0)
11219573673dSchristos return Z_TEXT;
11229573673dSchristos for (n = 32; n < LITERALS; n++)
11239573673dSchristos if (s->dyn_ltree[n].Freq != 0)
11249573673dSchristos return Z_TEXT;
11259573673dSchristos
1126*4f645668Schristos /* There are no "block-listed" or "allow-listed" bytes:
11279573673dSchristos * this stream either is empty or has tolerated ("gray-listed") bytes only.
11289573673dSchristos */
11299573673dSchristos return Z_BINARY;
11309573673dSchristos }
11319573673dSchristos
11329573673dSchristos /* ===========================================================================
11339573673dSchristos * Reverse the first len bits of a code, using straightforward code (a faster
11349573673dSchristos * method would use a table)
11359573673dSchristos * IN assertion: 1 <= len <= 15
11369573673dSchristos */
bi_reverse(code,len)11379573673dSchristos local unsigned bi_reverse(code, len)
11389573673dSchristos unsigned code; /* the value to invert */
11399573673dSchristos int len; /* its bit length */
11409573673dSchristos {
11419573673dSchristos register unsigned res = 0;
11429573673dSchristos do {
11439573673dSchristos res |= code & 1;
11449573673dSchristos code >>= 1, res <<= 1;
11459573673dSchristos } while (--len > 0);
11469573673dSchristos return res >> 1;
11479573673dSchristos }
11489573673dSchristos
11499573673dSchristos /* ===========================================================================
11509573673dSchristos * Flush the bit buffer, keeping at most 7 bits in it.
11519573673dSchristos */
bi_flush(s)11529573673dSchristos local void bi_flush(s)
11539573673dSchristos deflate_state *s;
11549573673dSchristos {
11559573673dSchristos if (s->bi_valid == 16) {
11569573673dSchristos put_short(s, s->bi_buf);
11579573673dSchristos s->bi_buf = 0;
11589573673dSchristos s->bi_valid = 0;
11599573673dSchristos } else if (s->bi_valid >= 8) {
11609573673dSchristos put_byte(s, (Byte)s->bi_buf);
11619573673dSchristos s->bi_buf >>= 8;
11629573673dSchristos s->bi_valid -= 8;
11639573673dSchristos }
11649573673dSchristos }
11659573673dSchristos
11669573673dSchristos /* ===========================================================================
11679573673dSchristos * Flush the bit buffer and align the output on a byte boundary
11689573673dSchristos */
bi_windup(s)11699573673dSchristos local void bi_windup(s)
11709573673dSchristos deflate_state *s;
11719573673dSchristos {
11729573673dSchristos if (s->bi_valid > 8) {
11739573673dSchristos put_short(s, s->bi_buf);
11749573673dSchristos } else if (s->bi_valid > 0) {
11759573673dSchristos put_byte(s, (Byte)s->bi_buf);
11769573673dSchristos }
11779573673dSchristos s->bi_buf = 0;
11789573673dSchristos s->bi_valid = 0;
1179fc4f4269Schristos #ifdef ZLIB_DEBUG
11809573673dSchristos s->bits_sent = (s->bits_sent+7) & ~7;
11819573673dSchristos #endif
11829573673dSchristos }
1183