175fd0b74Schristos /* trees.c -- output deflated data using Huffman coding
2*e992f068Schristos * Copyright (C) 1995-2021 Jean-loup Gailly
375fd0b74Schristos * detect_data_type() function provided freely by Cosmin Truta, 2006
475fd0b74Schristos * For conditions of distribution and use, see copyright notice in zlib.h
575fd0b74Schristos */
675fd0b74Schristos
775fd0b74Schristos /*
875fd0b74Schristos * ALGORITHM
975fd0b74Schristos *
1075fd0b74Schristos * The "deflation" process uses several Huffman trees. The more
1175fd0b74Schristos * common source values are represented by shorter bit sequences.
1275fd0b74Schristos *
1375fd0b74Schristos * Each code tree is stored in a compressed form which is itself
1475fd0b74Schristos * a Huffman encoding of the lengths of all the code strings (in
1575fd0b74Schristos * ascending order by source values). The actual code strings are
1675fd0b74Schristos * reconstructed from the lengths in the inflate process, as described
1775fd0b74Schristos * in the deflate specification.
1875fd0b74Schristos *
1975fd0b74Schristos * REFERENCES
2075fd0b74Schristos *
2175fd0b74Schristos * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
2275fd0b74Schristos * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
2375fd0b74Schristos *
2475fd0b74Schristos * Storer, James A.
2575fd0b74Schristos * Data Compression: Methods and Theory, pp. 49-50.
2675fd0b74Schristos * Computer Science Press, 1988. ISBN 0-7167-8156-5.
2775fd0b74Schristos *
2875fd0b74Schristos * Sedgewick, R.
2975fd0b74Schristos * Algorithms, p290.
3075fd0b74Schristos * Addison-Wesley, 1983. ISBN 0-201-06672-6.
3175fd0b74Schristos */
3275fd0b74Schristos
33*e992f068Schristos /* @(#) Id */
3475fd0b74Schristos
3575fd0b74Schristos /* #define GEN_TREES_H */
3675fd0b74Schristos
3775fd0b74Schristos #include "deflate.h"
3875fd0b74Schristos
39ede78133Schristos #ifdef ZLIB_DEBUG
4075fd0b74Schristos # include <ctype.h>
4175fd0b74Schristos #endif
4275fd0b74Schristos
4375fd0b74Schristos /* ===========================================================================
4475fd0b74Schristos * Constants
4575fd0b74Schristos */
4675fd0b74Schristos
4775fd0b74Schristos #define MAX_BL_BITS 7
4875fd0b74Schristos /* Bit length codes must not exceed MAX_BL_BITS bits */
4975fd0b74Schristos
5075fd0b74Schristos #define END_BLOCK 256
5175fd0b74Schristos /* end of block literal code */
5275fd0b74Schristos
5375fd0b74Schristos #define REP_3_6 16
5475fd0b74Schristos /* repeat previous bit length 3-6 times (2 bits of repeat count) */
5575fd0b74Schristos
5675fd0b74Schristos #define REPZ_3_10 17
5775fd0b74Schristos /* repeat a zero length 3-10 times (3 bits of repeat count) */
5875fd0b74Schristos
5975fd0b74Schristos #define REPZ_11_138 18
6075fd0b74Schristos /* repeat a zero length 11-138 times (7 bits of repeat count) */
6175fd0b74Schristos
6275fd0b74Schristos local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
6375fd0b74Schristos = {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};
6475fd0b74Schristos
6575fd0b74Schristos local const int extra_dbits[D_CODES] /* extra bits for each distance code */
6675fd0b74Schristos = {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};
6775fd0b74Schristos
6875fd0b74Schristos local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
6975fd0b74Schristos = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
7075fd0b74Schristos
7175fd0b74Schristos local const uch bl_order[BL_CODES]
7275fd0b74Schristos = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
7375fd0b74Schristos /* The lengths of the bit length codes are sent in order of decreasing
7475fd0b74Schristos * probability, to avoid transmitting the lengths for unused bit length codes.
7575fd0b74Schristos */
7675fd0b74Schristos
7775fd0b74Schristos /* ===========================================================================
7875fd0b74Schristos * Local data. These are initialized only once.
7975fd0b74Schristos */
8075fd0b74Schristos
8175fd0b74Schristos #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
8275fd0b74Schristos
8375fd0b74Schristos #if defined(GEN_TREES_H) || !defined(STDC)
8475fd0b74Schristos /* non ANSI compilers may not accept trees.h */
8575fd0b74Schristos
8675fd0b74Schristos local ct_data static_ltree[L_CODES+2];
8775fd0b74Schristos /* The static literal tree. Since the bit lengths are imposed, there is no
8875fd0b74Schristos * need for the L_CODES extra codes used during heap construction. However
8975fd0b74Schristos * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
9075fd0b74Schristos * below).
9175fd0b74Schristos */
9275fd0b74Schristos
9375fd0b74Schristos local ct_data static_dtree[D_CODES];
9475fd0b74Schristos /* The static distance tree. (Actually a trivial tree since all codes use
9575fd0b74Schristos * 5 bits.)
9675fd0b74Schristos */
9775fd0b74Schristos
9875fd0b74Schristos uch _dist_code[DIST_CODE_LEN];
9975fd0b74Schristos /* Distance codes. The first 256 values correspond to the distances
10075fd0b74Schristos * 3 .. 258, the last 256 values correspond to the top 8 bits of
10175fd0b74Schristos * the 15 bit distances.
10275fd0b74Schristos */
10375fd0b74Schristos
10475fd0b74Schristos uch _length_code[MAX_MATCH-MIN_MATCH+1];
10575fd0b74Schristos /* length code for each normalized match length (0 == MIN_MATCH) */
10675fd0b74Schristos
10775fd0b74Schristos local int base_length[LENGTH_CODES];
10875fd0b74Schristos /* First normalized length for each code (0 = MIN_MATCH) */
10975fd0b74Schristos
11075fd0b74Schristos local int base_dist[D_CODES];
11175fd0b74Schristos /* First normalized distance for each code (0 = distance of 1) */
11275fd0b74Schristos
11375fd0b74Schristos #else
11475fd0b74Schristos # include "trees.h"
11575fd0b74Schristos #endif /* GEN_TREES_H */
11675fd0b74Schristos
11775fd0b74Schristos struct static_tree_desc_s {
11875fd0b74Schristos const ct_data *static_tree; /* static tree or NULL */
11975fd0b74Schristos const intf *extra_bits; /* extra bits for each code or NULL */
12075fd0b74Schristos int extra_base; /* base index for extra_bits */
12175fd0b74Schristos int elems; /* max number of elements in the tree */
12275fd0b74Schristos int max_length; /* max bit length for the codes */
12375fd0b74Schristos };
12475fd0b74Schristos
125ede78133Schristos local const static_tree_desc static_l_desc =
12675fd0b74Schristos {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
12775fd0b74Schristos
128ede78133Schristos local const static_tree_desc static_d_desc =
12975fd0b74Schristos {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
13075fd0b74Schristos
131ede78133Schristos local const static_tree_desc static_bl_desc =
13275fd0b74Schristos {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
13375fd0b74Schristos
13475fd0b74Schristos /* ===========================================================================
13575fd0b74Schristos * Local (static) routines in this file.
13675fd0b74Schristos */
13775fd0b74Schristos
13875fd0b74Schristos local void tr_static_init OF((void));
13975fd0b74Schristos local void init_block OF((deflate_state *s));
14075fd0b74Schristos local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
14175fd0b74Schristos local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
14275fd0b74Schristos local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
14375fd0b74Schristos local void build_tree OF((deflate_state *s, tree_desc *desc));
14475fd0b74Schristos local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
14575fd0b74Schristos local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
14675fd0b74Schristos local int build_bl_tree OF((deflate_state *s));
14775fd0b74Schristos local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
14875fd0b74Schristos int blcodes));
14975fd0b74Schristos local void compress_block OF((deflate_state *s, const ct_data *ltree,
15075fd0b74Schristos const ct_data *dtree));
15175fd0b74Schristos local int detect_data_type OF((deflate_state *s));
152*e992f068Schristos local unsigned bi_reverse OF((unsigned code, int len));
15375fd0b74Schristos local void bi_windup OF((deflate_state *s));
15475fd0b74Schristos local void bi_flush OF((deflate_state *s));
15575fd0b74Schristos
15675fd0b74Schristos #ifdef GEN_TREES_H
15775fd0b74Schristos local void gen_trees_header OF((void));
15875fd0b74Schristos #endif
15975fd0b74Schristos
160ede78133Schristos #ifndef ZLIB_DEBUG
16175fd0b74Schristos # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
16275fd0b74Schristos /* Send a code of the given tree. c and tree must not have side effects */
16375fd0b74Schristos
164ede78133Schristos #else /* !ZLIB_DEBUG */
16575fd0b74Schristos # define send_code(s, c, tree) \
16675fd0b74Schristos { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
16775fd0b74Schristos send_bits(s, tree[c].Code, tree[c].Len); }
16875fd0b74Schristos #endif
16975fd0b74Schristos
17075fd0b74Schristos /* ===========================================================================
17175fd0b74Schristos * Output a short LSB first on the stream.
17275fd0b74Schristos * IN assertion: there is enough room in pendingBuf.
17375fd0b74Schristos */
17475fd0b74Schristos #define put_short(s, w) { \
17575fd0b74Schristos put_byte(s, (uch)((w) & 0xff)); \
17675fd0b74Schristos put_byte(s, (uch)((ush)(w) >> 8)); \
17775fd0b74Schristos }
17875fd0b74Schristos
17975fd0b74Schristos /* ===========================================================================
18075fd0b74Schristos * Send a value on a given number of bits.
18175fd0b74Schristos * IN assertion: length <= 16 and value fits in length bits.
18275fd0b74Schristos */
183ede78133Schristos #ifdef ZLIB_DEBUG
18475fd0b74Schristos local void send_bits OF((deflate_state *s, int value, int length));
18575fd0b74Schristos
send_bits(s,value,length)18675fd0b74Schristos local void send_bits(s, value, length)
18775fd0b74Schristos deflate_state *s;
18875fd0b74Schristos int value; /* value to send */
18975fd0b74Schristos int length; /* number of bits */
19075fd0b74Schristos {
19175fd0b74Schristos Tracevv((stderr," l %2d v %4x ", length, value));
19275fd0b74Schristos Assert(length > 0 && length <= 15, "invalid length");
19375fd0b74Schristos s->bits_sent += (ulg)length;
19475fd0b74Schristos
19575fd0b74Schristos /* If not enough room in bi_buf, use (valid) bits from bi_buf and
19675fd0b74Schristos * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
19775fd0b74Schristos * unused bits in value.
19875fd0b74Schristos */
19975fd0b74Schristos if (s->bi_valid > (int)Buf_size - length) {
20075fd0b74Schristos s->bi_buf |= (ush)value << s->bi_valid;
20175fd0b74Schristos put_short(s, s->bi_buf);
20275fd0b74Schristos s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
20375fd0b74Schristos s->bi_valid += length - Buf_size;
20475fd0b74Schristos } else {
20575fd0b74Schristos s->bi_buf |= (ush)value << s->bi_valid;
20675fd0b74Schristos s->bi_valid += length;
20775fd0b74Schristos }
20875fd0b74Schristos }
209ede78133Schristos #else /* !ZLIB_DEBUG */
21075fd0b74Schristos
21175fd0b74Schristos #define send_bits(s, value, length) \
21275fd0b74Schristos { int len = length;\
21375fd0b74Schristos if (s->bi_valid > (int)Buf_size - len) {\
214ede78133Schristos int val = (int)value;\
21575fd0b74Schristos s->bi_buf |= (ush)val << s->bi_valid;\
21675fd0b74Schristos put_short(s, s->bi_buf);\
21775fd0b74Schristos s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
21875fd0b74Schristos s->bi_valid += len - Buf_size;\
21975fd0b74Schristos } else {\
22075fd0b74Schristos s->bi_buf |= (ush)(value) << s->bi_valid;\
22175fd0b74Schristos s->bi_valid += len;\
22275fd0b74Schristos }\
22375fd0b74Schristos }
224ede78133Schristos #endif /* ZLIB_DEBUG */
22575fd0b74Schristos
22675fd0b74Schristos
22775fd0b74Schristos /* the arguments must not have side effects */
22875fd0b74Schristos
22975fd0b74Schristos /* ===========================================================================
23075fd0b74Schristos * Initialize the various 'constant' tables.
23175fd0b74Schristos */
tr_static_init()23275fd0b74Schristos local void tr_static_init()
23375fd0b74Schristos {
23475fd0b74Schristos #if defined(GEN_TREES_H) || !defined(STDC)
23575fd0b74Schristos static int static_init_done = 0;
23675fd0b74Schristos int n; /* iterates over tree elements */
23775fd0b74Schristos int bits; /* bit counter */
23875fd0b74Schristos int length; /* length value */
23975fd0b74Schristos int code; /* code value */
24075fd0b74Schristos int dist; /* distance index */
24175fd0b74Schristos ush bl_count[MAX_BITS+1];
24275fd0b74Schristos /* number of codes at each bit length for an optimal tree */
24375fd0b74Schristos
24475fd0b74Schristos if (static_init_done) return;
24575fd0b74Schristos
24675fd0b74Schristos /* For some embedded targets, global variables are not initialized: */
24775fd0b74Schristos #ifdef NO_INIT_GLOBAL_POINTERS
24875fd0b74Schristos static_l_desc.static_tree = static_ltree;
24975fd0b74Schristos static_l_desc.extra_bits = extra_lbits;
25075fd0b74Schristos static_d_desc.static_tree = static_dtree;
25175fd0b74Schristos static_d_desc.extra_bits = extra_dbits;
25275fd0b74Schristos static_bl_desc.extra_bits = extra_blbits;
25375fd0b74Schristos #endif
25475fd0b74Schristos
25575fd0b74Schristos /* Initialize the mapping length (0..255) -> length code (0..28) */
25675fd0b74Schristos length = 0;
25775fd0b74Schristos for (code = 0; code < LENGTH_CODES-1; code++) {
25875fd0b74Schristos base_length[code] = length;
25975fd0b74Schristos for (n = 0; n < (1<<extra_lbits[code]); n++) {
26075fd0b74Schristos _length_code[length++] = (uch)code;
26175fd0b74Schristos }
26275fd0b74Schristos }
26375fd0b74Schristos Assert (length == 256, "tr_static_init: length != 256");
26475fd0b74Schristos /* Note that the length 255 (match length 258) can be represented
26575fd0b74Schristos * in two different ways: code 284 + 5 bits or code 285, so we
26675fd0b74Schristos * overwrite length_code[255] to use the best encoding:
26775fd0b74Schristos */
26875fd0b74Schristos _length_code[length-1] = (uch)code;
26975fd0b74Schristos
27075fd0b74Schristos /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
27175fd0b74Schristos dist = 0;
27275fd0b74Schristos for (code = 0 ; code < 16; code++) {
27375fd0b74Schristos base_dist[code] = dist;
27475fd0b74Schristos for (n = 0; n < (1<<extra_dbits[code]); n++) {
27575fd0b74Schristos _dist_code[dist++] = (uch)code;
27675fd0b74Schristos }
27775fd0b74Schristos }
27875fd0b74Schristos Assert (dist == 256, "tr_static_init: dist != 256");
27975fd0b74Schristos dist >>= 7; /* from now on, all distances are divided by 128 */
28075fd0b74Schristos for ( ; code < D_CODES; code++) {
28175fd0b74Schristos base_dist[code] = dist << 7;
28275fd0b74Schristos for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
28375fd0b74Schristos _dist_code[256 + dist++] = (uch)code;
28475fd0b74Schristos }
28575fd0b74Schristos }
28675fd0b74Schristos Assert (dist == 256, "tr_static_init: 256+dist != 512");
28775fd0b74Schristos
28875fd0b74Schristos /* Construct the codes of the static literal tree */
28975fd0b74Schristos for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
29075fd0b74Schristos n = 0;
29175fd0b74Schristos while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
29275fd0b74Schristos while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
29375fd0b74Schristos while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
29475fd0b74Schristos while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
29575fd0b74Schristos /* Codes 286 and 287 do not exist, but we must include them in the
29675fd0b74Schristos * tree construction to get a canonical Huffman tree (longest code
29775fd0b74Schristos * all ones)
29875fd0b74Schristos */
29975fd0b74Schristos gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
30075fd0b74Schristos
30175fd0b74Schristos /* The static distance tree is trivial: */
30275fd0b74Schristos for (n = 0; n < D_CODES; n++) {
30375fd0b74Schristos static_dtree[n].Len = 5;
30475fd0b74Schristos static_dtree[n].Code = bi_reverse((unsigned)n, 5);
30575fd0b74Schristos }
30675fd0b74Schristos static_init_done = 1;
30775fd0b74Schristos
30875fd0b74Schristos # ifdef GEN_TREES_H
30975fd0b74Schristos gen_trees_header();
31075fd0b74Schristos # endif
31175fd0b74Schristos #endif /* defined(GEN_TREES_H) || !defined(STDC) */
31275fd0b74Schristos }
31375fd0b74Schristos
31475fd0b74Schristos /* ===========================================================================
31575fd0b74Schristos * Genererate the file trees.h describing the static trees.
31675fd0b74Schristos */
31775fd0b74Schristos #ifdef GEN_TREES_H
318ede78133Schristos # ifndef ZLIB_DEBUG
31975fd0b74Schristos # include <stdio.h>
32075fd0b74Schristos # endif
32175fd0b74Schristos
32275fd0b74Schristos # define SEPARATOR(i, last, width) \
32375fd0b74Schristos ((i) == (last)? "\n};\n\n" : \
32475fd0b74Schristos ((i) % (width) == (width)-1 ? ",\n" : ", "))
32575fd0b74Schristos
gen_trees_header()32675fd0b74Schristos void gen_trees_header()
32775fd0b74Schristos {
32875fd0b74Schristos FILE *header = fopen("trees.h", "w");
32975fd0b74Schristos int i;
33075fd0b74Schristos
33175fd0b74Schristos Assert (header != NULL, "Can't open trees.h");
33275fd0b74Schristos fprintf(header,
33375fd0b74Schristos "/* header created automatically with -DGEN_TREES_H */\n\n");
33475fd0b74Schristos
33575fd0b74Schristos fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
33675fd0b74Schristos for (i = 0; i < L_CODES+2; i++) {
33775fd0b74Schristos fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
33875fd0b74Schristos static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
33975fd0b74Schristos }
34075fd0b74Schristos
34175fd0b74Schristos fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
34275fd0b74Schristos for (i = 0; i < D_CODES; i++) {
34375fd0b74Schristos fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
34475fd0b74Schristos static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
34575fd0b74Schristos }
34675fd0b74Schristos
34775fd0b74Schristos fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
34875fd0b74Schristos for (i = 0; i < DIST_CODE_LEN; i++) {
34975fd0b74Schristos fprintf(header, "%2u%s", _dist_code[i],
35075fd0b74Schristos SEPARATOR(i, DIST_CODE_LEN-1, 20));
35175fd0b74Schristos }
35275fd0b74Schristos
35375fd0b74Schristos fprintf(header,
35475fd0b74Schristos "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
35575fd0b74Schristos for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
35675fd0b74Schristos fprintf(header, "%2u%s", _length_code[i],
35775fd0b74Schristos SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
35875fd0b74Schristos }
35975fd0b74Schristos
36075fd0b74Schristos fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
36175fd0b74Schristos for (i = 0; i < LENGTH_CODES; i++) {
36275fd0b74Schristos fprintf(header, "%1u%s", base_length[i],
36375fd0b74Schristos SEPARATOR(i, LENGTH_CODES-1, 20));
36475fd0b74Schristos }
36575fd0b74Schristos
36675fd0b74Schristos fprintf(header, "local const int base_dist[D_CODES] = {\n");
36775fd0b74Schristos for (i = 0; i < D_CODES; i++) {
36875fd0b74Schristos fprintf(header, "%5u%s", base_dist[i],
36975fd0b74Schristos SEPARATOR(i, D_CODES-1, 10));
37075fd0b74Schristos }
37175fd0b74Schristos
37275fd0b74Schristos fclose(header);
37375fd0b74Schristos }
37475fd0b74Schristos #endif /* GEN_TREES_H */
37575fd0b74Schristos
37675fd0b74Schristos /* ===========================================================================
37775fd0b74Schristos * Initialize the tree data structures for a new zlib stream.
37875fd0b74Schristos */
_tr_init(s)37975fd0b74Schristos void ZLIB_INTERNAL _tr_init(s)
38075fd0b74Schristos deflate_state *s;
38175fd0b74Schristos {
38275fd0b74Schristos tr_static_init();
38375fd0b74Schristos
38475fd0b74Schristos s->l_desc.dyn_tree = s->dyn_ltree;
38575fd0b74Schristos s->l_desc.stat_desc = &static_l_desc;
38675fd0b74Schristos
38775fd0b74Schristos s->d_desc.dyn_tree = s->dyn_dtree;
38875fd0b74Schristos s->d_desc.stat_desc = &static_d_desc;
38975fd0b74Schristos
39075fd0b74Schristos s->bl_desc.dyn_tree = s->bl_tree;
39175fd0b74Schristos s->bl_desc.stat_desc = &static_bl_desc;
39275fd0b74Schristos
39375fd0b74Schristos s->bi_buf = 0;
39475fd0b74Schristos s->bi_valid = 0;
395ede78133Schristos #ifdef ZLIB_DEBUG
39675fd0b74Schristos s->compressed_len = 0L;
39775fd0b74Schristos s->bits_sent = 0L;
39875fd0b74Schristos #endif
39975fd0b74Schristos
40075fd0b74Schristos /* Initialize the first block of the first file: */
40175fd0b74Schristos init_block(s);
40275fd0b74Schristos }
40375fd0b74Schristos
40475fd0b74Schristos /* ===========================================================================
40575fd0b74Schristos * Initialize a new block.
40675fd0b74Schristos */
init_block(s)40775fd0b74Schristos local void init_block(s)
40875fd0b74Schristos deflate_state *s;
40975fd0b74Schristos {
41075fd0b74Schristos int n; /* iterates over tree elements */
41175fd0b74Schristos
41275fd0b74Schristos /* Initialize the trees. */
41375fd0b74Schristos for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
41475fd0b74Schristos for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
41575fd0b74Schristos for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
41675fd0b74Schristos
41775fd0b74Schristos s->dyn_ltree[END_BLOCK].Freq = 1;
41875fd0b74Schristos s->opt_len = s->static_len = 0L;
419*e992f068Schristos s->sym_next = s->matches = 0;
42075fd0b74Schristos }
42175fd0b74Schristos
42275fd0b74Schristos #define SMALLEST 1
42375fd0b74Schristos /* Index within the heap array of least frequent node in the Huffman tree */
42475fd0b74Schristos
42575fd0b74Schristos
42675fd0b74Schristos /* ===========================================================================
42775fd0b74Schristos * Remove the smallest element from the heap and recreate the heap with
42875fd0b74Schristos * one less element. Updates heap and heap_len.
42975fd0b74Schristos */
43075fd0b74Schristos #define pqremove(s, tree, top) \
43175fd0b74Schristos {\
43275fd0b74Schristos top = s->heap[SMALLEST]; \
43375fd0b74Schristos s->heap[SMALLEST] = s->heap[s->heap_len--]; \
43475fd0b74Schristos pqdownheap(s, tree, SMALLEST); \
43575fd0b74Schristos }
43675fd0b74Schristos
43775fd0b74Schristos /* ===========================================================================
43875fd0b74Schristos * Compares to subtrees, using the tree depth as tie breaker when
43975fd0b74Schristos * the subtrees have equal frequency. This minimizes the worst case length.
44075fd0b74Schristos */
44175fd0b74Schristos #define smaller(tree, n, m, depth) \
44275fd0b74Schristos (tree[n].Freq < tree[m].Freq || \
44375fd0b74Schristos (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
44475fd0b74Schristos
44575fd0b74Schristos /* ===========================================================================
44675fd0b74Schristos * Restore the heap property by moving down the tree starting at node k,
44775fd0b74Schristos * exchanging a node with the smallest of its two sons if necessary, stopping
44875fd0b74Schristos * when the heap property is re-established (each father smaller than its
44975fd0b74Schristos * two sons).
45075fd0b74Schristos */
pqdownheap(s,tree,k)45175fd0b74Schristos local void pqdownheap(s, tree, k)
45275fd0b74Schristos deflate_state *s;
45375fd0b74Schristos ct_data *tree; /* the tree to restore */
45475fd0b74Schristos int k; /* node to move down */
45575fd0b74Schristos {
45675fd0b74Schristos int v = s->heap[k];
45775fd0b74Schristos int j = k << 1; /* left son of k */
45875fd0b74Schristos while (j <= s->heap_len) {
45975fd0b74Schristos /* Set j to the smallest of the two sons: */
46075fd0b74Schristos if (j < s->heap_len &&
46175fd0b74Schristos smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
46275fd0b74Schristos j++;
46375fd0b74Schristos }
46475fd0b74Schristos /* Exit if v is smaller than both sons */
46575fd0b74Schristos if (smaller(tree, v, s->heap[j], s->depth)) break;
46675fd0b74Schristos
46775fd0b74Schristos /* Exchange v with the smallest son */
46875fd0b74Schristos s->heap[k] = s->heap[j]; k = j;
46975fd0b74Schristos
47075fd0b74Schristos /* And continue down the tree, setting j to the left son of k */
47175fd0b74Schristos j <<= 1;
47275fd0b74Schristos }
47375fd0b74Schristos s->heap[k] = v;
47475fd0b74Schristos }
47575fd0b74Schristos
47675fd0b74Schristos /* ===========================================================================
47775fd0b74Schristos * Compute the optimal bit lengths for a tree and update the total bit length
47875fd0b74Schristos * for the current block.
47975fd0b74Schristos * IN assertion: the fields freq and dad are set, heap[heap_max] and
48075fd0b74Schristos * above are the tree nodes sorted by increasing frequency.
48175fd0b74Schristos * OUT assertions: the field len is set to the optimal bit length, the
48275fd0b74Schristos * array bl_count contains the frequencies for each bit length.
48375fd0b74Schristos * The length opt_len is updated; static_len is also updated if stree is
48475fd0b74Schristos * not null.
48575fd0b74Schristos */
gen_bitlen(s,desc)48675fd0b74Schristos local void gen_bitlen(s, desc)
48775fd0b74Schristos deflate_state *s;
48875fd0b74Schristos tree_desc *desc; /* the tree descriptor */
48975fd0b74Schristos {
49075fd0b74Schristos ct_data *tree = desc->dyn_tree;
49175fd0b74Schristos int max_code = desc->max_code;
49275fd0b74Schristos const ct_data *stree = desc->stat_desc->static_tree;
49375fd0b74Schristos const intf *extra = desc->stat_desc->extra_bits;
49475fd0b74Schristos int base = desc->stat_desc->extra_base;
49575fd0b74Schristos int max_length = desc->stat_desc->max_length;
49675fd0b74Schristos int h; /* heap index */
49775fd0b74Schristos int n, m; /* iterate over the tree elements */
49875fd0b74Schristos int bits; /* bit length */
49975fd0b74Schristos int xbits; /* extra bits */
50075fd0b74Schristos ush f; /* frequency */
50175fd0b74Schristos int overflow = 0; /* number of elements with bit length too large */
50275fd0b74Schristos
50375fd0b74Schristos for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
50475fd0b74Schristos
50575fd0b74Schristos /* In a first pass, compute the optimal bit lengths (which may
50675fd0b74Schristos * overflow in the case of the bit length tree).
50775fd0b74Schristos */
50875fd0b74Schristos tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
50975fd0b74Schristos
51075fd0b74Schristos for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
51175fd0b74Schristos n = s->heap[h];
51275fd0b74Schristos bits = tree[tree[n].Dad].Len + 1;
51375fd0b74Schristos if (bits > max_length) bits = max_length, overflow++;
51475fd0b74Schristos tree[n].Len = (ush)bits;
51575fd0b74Schristos /* We overwrite tree[n].Dad which is no longer needed */
51675fd0b74Schristos
51775fd0b74Schristos if (n > max_code) continue; /* not a leaf node */
51875fd0b74Schristos
51975fd0b74Schristos s->bl_count[bits]++;
52075fd0b74Schristos xbits = 0;
52175fd0b74Schristos if (n >= base) xbits = extra[n-base];
52275fd0b74Schristos f = tree[n].Freq;
523ede78133Schristos s->opt_len += (ulg)f * (unsigned)(bits + xbits);
524ede78133Schristos if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
52575fd0b74Schristos }
52675fd0b74Schristos if (overflow == 0) return;
52775fd0b74Schristos
528ede78133Schristos Tracev((stderr,"\nbit length overflow\n"));
52975fd0b74Schristos /* This happens for example on obj2 and pic of the Calgary corpus */
53075fd0b74Schristos
53175fd0b74Schristos /* Find the first bit length which could increase: */
53275fd0b74Schristos do {
53375fd0b74Schristos bits = max_length-1;
53475fd0b74Schristos while (s->bl_count[bits] == 0) bits--;
53575fd0b74Schristos s->bl_count[bits]--; /* move one leaf down the tree */
53675fd0b74Schristos s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
53775fd0b74Schristos s->bl_count[max_length]--;
53875fd0b74Schristos /* The brother of the overflow item also moves one step up,
53975fd0b74Schristos * but this does not affect bl_count[max_length]
54075fd0b74Schristos */
54175fd0b74Schristos overflow -= 2;
54275fd0b74Schristos } while (overflow > 0);
54375fd0b74Schristos
54475fd0b74Schristos /* Now recompute all bit lengths, scanning in increasing frequency.
54575fd0b74Schristos * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
54675fd0b74Schristos * lengths instead of fixing only the wrong ones. This idea is taken
54775fd0b74Schristos * from 'ar' written by Haruhiko Okumura.)
54875fd0b74Schristos */
54975fd0b74Schristos for (bits = max_length; bits != 0; bits--) {
55075fd0b74Schristos n = s->bl_count[bits];
55175fd0b74Schristos while (n != 0) {
55275fd0b74Schristos m = s->heap[--h];
55375fd0b74Schristos if (m > max_code) continue;
55475fd0b74Schristos if ((unsigned) tree[m].Len != (unsigned) bits) {
555ede78133Schristos Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
556ede78133Schristos s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
55775fd0b74Schristos tree[m].Len = (ush)bits;
55875fd0b74Schristos }
55975fd0b74Schristos n--;
56075fd0b74Schristos }
56175fd0b74Schristos }
56275fd0b74Schristos }
56375fd0b74Schristos
56475fd0b74Schristos /* ===========================================================================
56575fd0b74Schristos * Generate the codes for a given tree and bit counts (which need not be
56675fd0b74Schristos * optimal).
56775fd0b74Schristos * IN assertion: the array bl_count contains the bit length statistics for
56875fd0b74Schristos * the given tree and the field len is set for all tree elements.
56975fd0b74Schristos * OUT assertion: the field code is set for all tree elements of non
57075fd0b74Schristos * zero code length.
57175fd0b74Schristos */
gen_codes(tree,max_code,bl_count)57275fd0b74Schristos local void gen_codes (tree, max_code, bl_count)
57375fd0b74Schristos ct_data *tree; /* the tree to decorate */
57475fd0b74Schristos int max_code; /* largest code with non zero frequency */
57575fd0b74Schristos ushf *bl_count; /* number of codes at each bit length */
57675fd0b74Schristos {
57775fd0b74Schristos ush next_code[MAX_BITS+1]; /* next code value for each bit length */
578ede78133Schristos unsigned code = 0; /* running code value */
57975fd0b74Schristos int bits; /* bit index */
58075fd0b74Schristos int n; /* code index */
58175fd0b74Schristos
58275fd0b74Schristos /* The distribution counts are first used to generate the code values
58375fd0b74Schristos * without bit reversal.
58475fd0b74Schristos */
58575fd0b74Schristos for (bits = 1; bits <= MAX_BITS; bits++) {
586ede78133Schristos code = (code + bl_count[bits-1]) << 1;
587ede78133Schristos next_code[bits] = (ush)code;
58875fd0b74Schristos }
58975fd0b74Schristos /* Check that the bit counts in bl_count are consistent. The last code
59075fd0b74Schristos * must be all ones.
59175fd0b74Schristos */
59275fd0b74Schristos Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
59375fd0b74Schristos "inconsistent bit counts");
59475fd0b74Schristos Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
59575fd0b74Schristos
59675fd0b74Schristos for (n = 0; n <= max_code; n++) {
59775fd0b74Schristos int len = tree[n].Len;
59875fd0b74Schristos if (len == 0) continue;
59975fd0b74Schristos /* Now reverse the bits */
600ede78133Schristos tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
60175fd0b74Schristos
60275fd0b74Schristos Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
60375fd0b74Schristos n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
60475fd0b74Schristos }
60575fd0b74Schristos }
60675fd0b74Schristos
60775fd0b74Schristos /* ===========================================================================
60875fd0b74Schristos * Construct one Huffman tree and assigns the code bit strings and lengths.
60975fd0b74Schristos * Update the total bit length for the current block.
61075fd0b74Schristos * IN assertion: the field freq is set for all tree elements.
61175fd0b74Schristos * OUT assertions: the fields len and code are set to the optimal bit length
61275fd0b74Schristos * and corresponding code. The length opt_len is updated; static_len is
61375fd0b74Schristos * also updated if stree is not null. The field max_code is set.
61475fd0b74Schristos */
build_tree(s,desc)61575fd0b74Schristos local void build_tree(s, desc)
61675fd0b74Schristos deflate_state *s;
61775fd0b74Schristos tree_desc *desc; /* the tree descriptor */
61875fd0b74Schristos {
61975fd0b74Schristos ct_data *tree = desc->dyn_tree;
62075fd0b74Schristos const ct_data *stree = desc->stat_desc->static_tree;
62175fd0b74Schristos int elems = desc->stat_desc->elems;
62275fd0b74Schristos int n, m; /* iterate over heap elements */
62375fd0b74Schristos int max_code = -1; /* largest code with non zero frequency */
62475fd0b74Schristos int node; /* new node being created */
62575fd0b74Schristos
62675fd0b74Schristos /* Construct the initial heap, with least frequent element in
62775fd0b74Schristos * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
62875fd0b74Schristos * heap[0] is not used.
62975fd0b74Schristos */
63075fd0b74Schristos s->heap_len = 0, s->heap_max = HEAP_SIZE;
63175fd0b74Schristos
63275fd0b74Schristos for (n = 0; n < elems; n++) {
63375fd0b74Schristos if (tree[n].Freq != 0) {
63475fd0b74Schristos s->heap[++(s->heap_len)] = max_code = n;
63575fd0b74Schristos s->depth[n] = 0;
63675fd0b74Schristos } else {
63775fd0b74Schristos tree[n].Len = 0;
63875fd0b74Schristos }
63975fd0b74Schristos }
64075fd0b74Schristos
64175fd0b74Schristos /* The pkzip format requires that at least one distance code exists,
64275fd0b74Schristos * and that at least one bit should be sent even if there is only one
64375fd0b74Schristos * possible code. So to avoid special checks later on we force at least
64475fd0b74Schristos * two codes of non zero frequency.
64575fd0b74Schristos */
64675fd0b74Schristos while (s->heap_len < 2) {
64775fd0b74Schristos node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
64875fd0b74Schristos tree[node].Freq = 1;
64975fd0b74Schristos s->depth[node] = 0;
65075fd0b74Schristos s->opt_len--; if (stree) s->static_len -= stree[node].Len;
65175fd0b74Schristos /* node is 0 or 1 so it does not have extra bits */
65275fd0b74Schristos }
65375fd0b74Schristos desc->max_code = max_code;
65475fd0b74Schristos
65575fd0b74Schristos /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
65675fd0b74Schristos * establish sub-heaps of increasing lengths:
65775fd0b74Schristos */
65875fd0b74Schristos for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
65975fd0b74Schristos
66075fd0b74Schristos /* Construct the Huffman tree by repeatedly combining the least two
66175fd0b74Schristos * frequent nodes.
66275fd0b74Schristos */
66375fd0b74Schristos node = elems; /* next internal node of the tree */
66475fd0b74Schristos do {
66575fd0b74Schristos pqremove(s, tree, n); /* n = node of least frequency */
66675fd0b74Schristos m = s->heap[SMALLEST]; /* m = node of next least frequency */
66775fd0b74Schristos
66875fd0b74Schristos s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
66975fd0b74Schristos s->heap[--(s->heap_max)] = m;
67075fd0b74Schristos
67175fd0b74Schristos /* Create a new node father of n and m */
67275fd0b74Schristos tree[node].Freq = tree[n].Freq + tree[m].Freq;
67375fd0b74Schristos s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
67475fd0b74Schristos s->depth[n] : s->depth[m]) + 1);
67575fd0b74Schristos tree[n].Dad = tree[m].Dad = (ush)node;
67675fd0b74Schristos #ifdef DUMP_BL_TREE
67775fd0b74Schristos if (tree == s->bl_tree) {
67875fd0b74Schristos fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
67975fd0b74Schristos node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
68075fd0b74Schristos }
68175fd0b74Schristos #endif
68275fd0b74Schristos /* and insert the new node in the heap */
68375fd0b74Schristos s->heap[SMALLEST] = node++;
68475fd0b74Schristos pqdownheap(s, tree, SMALLEST);
68575fd0b74Schristos
68675fd0b74Schristos } while (s->heap_len >= 2);
68775fd0b74Schristos
68875fd0b74Schristos s->heap[--(s->heap_max)] = s->heap[SMALLEST];
68975fd0b74Schristos
69075fd0b74Schristos /* At this point, the fields freq and dad are set. We can now
69175fd0b74Schristos * generate the bit lengths.
69275fd0b74Schristos */
69375fd0b74Schristos gen_bitlen(s, (tree_desc *)desc);
69475fd0b74Schristos
69575fd0b74Schristos /* The field len is now set, we can generate the bit codes */
69675fd0b74Schristos gen_codes ((ct_data *)tree, max_code, s->bl_count);
69775fd0b74Schristos }
69875fd0b74Schristos
69975fd0b74Schristos /* ===========================================================================
70075fd0b74Schristos * Scan a literal or distance tree to determine the frequencies of the codes
70175fd0b74Schristos * in the bit length tree.
70275fd0b74Schristos */
scan_tree(s,tree,max_code)70375fd0b74Schristos local void scan_tree (s, tree, max_code)
70475fd0b74Schristos deflate_state *s;
70575fd0b74Schristos ct_data *tree; /* the tree to be scanned */
70675fd0b74Schristos int max_code; /* and its largest code of non zero frequency */
70775fd0b74Schristos {
70875fd0b74Schristos int n; /* iterates over all tree elements */
70975fd0b74Schristos int prevlen = -1; /* last emitted length */
71075fd0b74Schristos int curlen; /* length of current code */
71175fd0b74Schristos int nextlen = tree[0].Len; /* length of next code */
71275fd0b74Schristos int count = 0; /* repeat count of the current code */
71375fd0b74Schristos int max_count = 7; /* max repeat count */
71475fd0b74Schristos int min_count = 4; /* min repeat count */
71575fd0b74Schristos
71675fd0b74Schristos if (nextlen == 0) max_count = 138, min_count = 3;
71775fd0b74Schristos tree[max_code+1].Len = (ush)0xffff; /* guard */
71875fd0b74Schristos
71975fd0b74Schristos for (n = 0; n <= max_code; n++) {
72075fd0b74Schristos curlen = nextlen; nextlen = tree[n+1].Len;
72175fd0b74Schristos if (++count < max_count && curlen == nextlen) {
72275fd0b74Schristos continue;
72375fd0b74Schristos } else if (count < min_count) {
72475fd0b74Schristos s->bl_tree[curlen].Freq += count;
72575fd0b74Schristos } else if (curlen != 0) {
72675fd0b74Schristos if (curlen != prevlen) s->bl_tree[curlen].Freq++;
72775fd0b74Schristos s->bl_tree[REP_3_6].Freq++;
72875fd0b74Schristos } else if (count <= 10) {
72975fd0b74Schristos s->bl_tree[REPZ_3_10].Freq++;
73075fd0b74Schristos } else {
73175fd0b74Schristos s->bl_tree[REPZ_11_138].Freq++;
73275fd0b74Schristos }
73375fd0b74Schristos count = 0; prevlen = curlen;
73475fd0b74Schristos if (nextlen == 0) {
73575fd0b74Schristos max_count = 138, min_count = 3;
73675fd0b74Schristos } else if (curlen == nextlen) {
73775fd0b74Schristos max_count = 6, min_count = 3;
73875fd0b74Schristos } else {
73975fd0b74Schristos max_count = 7, min_count = 4;
74075fd0b74Schristos }
74175fd0b74Schristos }
74275fd0b74Schristos }
74375fd0b74Schristos
74475fd0b74Schristos /* ===========================================================================
74575fd0b74Schristos * Send a literal or distance tree in compressed form, using the codes in
74675fd0b74Schristos * bl_tree.
74775fd0b74Schristos */
send_tree(s,tree,max_code)74875fd0b74Schristos local void send_tree (s, tree, max_code)
74975fd0b74Schristos deflate_state *s;
75075fd0b74Schristos ct_data *tree; /* the tree to be scanned */
75175fd0b74Schristos int max_code; /* and its largest code of non zero frequency */
75275fd0b74Schristos {
75375fd0b74Schristos int n; /* iterates over all tree elements */
75475fd0b74Schristos int prevlen = -1; /* last emitted length */
75575fd0b74Schristos int curlen; /* length of current code */
75675fd0b74Schristos int nextlen = tree[0].Len; /* length of next code */
75775fd0b74Schristos int count = 0; /* repeat count of the current code */
75875fd0b74Schristos int max_count = 7; /* max repeat count */
75975fd0b74Schristos int min_count = 4; /* min repeat count */
76075fd0b74Schristos
76175fd0b74Schristos /* tree[max_code+1].Len = -1; */ /* guard already set */
76275fd0b74Schristos if (nextlen == 0) max_count = 138, min_count = 3;
76375fd0b74Schristos
76475fd0b74Schristos for (n = 0; n <= max_code; n++) {
76575fd0b74Schristos curlen = nextlen; nextlen = tree[n+1].Len;
76675fd0b74Schristos if (++count < max_count && curlen == nextlen) {
76775fd0b74Schristos continue;
76875fd0b74Schristos } else if (count < min_count) {
76975fd0b74Schristos do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
77075fd0b74Schristos
77175fd0b74Schristos } else if (curlen != 0) {
77275fd0b74Schristos if (curlen != prevlen) {
77375fd0b74Schristos send_code(s, curlen, s->bl_tree); count--;
77475fd0b74Schristos }
77575fd0b74Schristos Assert(count >= 3 && count <= 6, " 3_6?");
77675fd0b74Schristos send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
77775fd0b74Schristos
77875fd0b74Schristos } else if (count <= 10) {
77975fd0b74Schristos send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
78075fd0b74Schristos
78175fd0b74Schristos } else {
78275fd0b74Schristos send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
78375fd0b74Schristos }
78475fd0b74Schristos count = 0; prevlen = curlen;
78575fd0b74Schristos if (nextlen == 0) {
78675fd0b74Schristos max_count = 138, min_count = 3;
78775fd0b74Schristos } else if (curlen == nextlen) {
78875fd0b74Schristos max_count = 6, min_count = 3;
78975fd0b74Schristos } else {
79075fd0b74Schristos max_count = 7, min_count = 4;
79175fd0b74Schristos }
79275fd0b74Schristos }
79375fd0b74Schristos }
79475fd0b74Schristos
79575fd0b74Schristos /* ===========================================================================
79675fd0b74Schristos * Construct the Huffman tree for the bit lengths and return the index in
79775fd0b74Schristos * bl_order of the last bit length code to send.
79875fd0b74Schristos */
build_bl_tree(s)79975fd0b74Schristos local int build_bl_tree(s)
80075fd0b74Schristos deflate_state *s;
80175fd0b74Schristos {
80275fd0b74Schristos int max_blindex; /* index of last bit length code of non zero freq */
80375fd0b74Schristos
80475fd0b74Schristos /* Determine the bit length frequencies for literal and distance trees */
80575fd0b74Schristos scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
80675fd0b74Schristos scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
80775fd0b74Schristos
80875fd0b74Schristos /* Build the bit length tree: */
80975fd0b74Schristos build_tree(s, (tree_desc *)(&(s->bl_desc)));
81075fd0b74Schristos /* opt_len now includes the length of the tree representations, except
81175fd0b74Schristos * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
81275fd0b74Schristos */
81375fd0b74Schristos
81475fd0b74Schristos /* Determine the number of bit length codes to send. The pkzip format
81575fd0b74Schristos * requires that at least 4 bit length codes be sent. (appnote.txt says
81675fd0b74Schristos * 3 but the actual value used is 4.)
81775fd0b74Schristos */
81875fd0b74Schristos for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
81975fd0b74Schristos if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
82075fd0b74Schristos }
82175fd0b74Schristos /* Update opt_len to include the bit length tree and counts */
822ede78133Schristos s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
82375fd0b74Schristos Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
82475fd0b74Schristos s->opt_len, s->static_len));
82575fd0b74Schristos
82675fd0b74Schristos return max_blindex;
82775fd0b74Schristos }
82875fd0b74Schristos
82975fd0b74Schristos /* ===========================================================================
83075fd0b74Schristos * Send the header for a block using dynamic Huffman trees: the counts, the
83175fd0b74Schristos * lengths of the bit length codes, the literal tree and the distance tree.
83275fd0b74Schristos * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
83375fd0b74Schristos */
send_all_trees(s,lcodes,dcodes,blcodes)83475fd0b74Schristos local void send_all_trees(s, lcodes, dcodes, blcodes)
83575fd0b74Schristos deflate_state *s;
83675fd0b74Schristos int lcodes, dcodes, blcodes; /* number of codes for each tree */
83775fd0b74Schristos {
83875fd0b74Schristos int rank; /* index in bl_order */
83975fd0b74Schristos
84075fd0b74Schristos Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
84175fd0b74Schristos Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
84275fd0b74Schristos "too many codes");
84375fd0b74Schristos Tracev((stderr, "\nbl counts: "));
84475fd0b74Schristos send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
84575fd0b74Schristos send_bits(s, dcodes-1, 5);
84675fd0b74Schristos send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
84775fd0b74Schristos for (rank = 0; rank < blcodes; rank++) {
84875fd0b74Schristos Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
84975fd0b74Schristos send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
85075fd0b74Schristos }
85175fd0b74Schristos Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
85275fd0b74Schristos
85375fd0b74Schristos send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
85475fd0b74Schristos Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
85575fd0b74Schristos
85675fd0b74Schristos send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
85775fd0b74Schristos Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
85875fd0b74Schristos }
85975fd0b74Schristos
86075fd0b74Schristos /* ===========================================================================
86175fd0b74Schristos * Send a stored block
86275fd0b74Schristos */
_tr_stored_block(s,buf,stored_len,last)86375fd0b74Schristos void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
86475fd0b74Schristos deflate_state *s;
86575fd0b74Schristos charf *buf; /* input block */
86675fd0b74Schristos ulg stored_len; /* length of input block */
86775fd0b74Schristos int last; /* one if this is the last block for a file */
86875fd0b74Schristos {
86975fd0b74Schristos send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */
870ede78133Schristos bi_windup(s); /* align on byte boundary */
871ede78133Schristos put_short(s, (ush)stored_len);
872ede78133Schristos put_short(s, (ush)~stored_len);
873*e992f068Schristos if (stored_len)
874ede78133Schristos zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
875ede78133Schristos s->pending += stored_len;
876ede78133Schristos #ifdef ZLIB_DEBUG
87775fd0b74Schristos s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
87875fd0b74Schristos s->compressed_len += (stored_len + 4) << 3;
879ede78133Schristos s->bits_sent += 2*16;
880ede78133Schristos s->bits_sent += stored_len<<3;
88175fd0b74Schristos #endif
88275fd0b74Schristos }
88375fd0b74Schristos
88475fd0b74Schristos /* ===========================================================================
88575fd0b74Schristos * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
88675fd0b74Schristos */
_tr_flush_bits(s)88775fd0b74Schristos void ZLIB_INTERNAL _tr_flush_bits(s)
88875fd0b74Schristos deflate_state *s;
88975fd0b74Schristos {
89075fd0b74Schristos bi_flush(s);
89175fd0b74Schristos }
89275fd0b74Schristos
89375fd0b74Schristos /* ===========================================================================
89475fd0b74Schristos * Send one empty static block to give enough lookahead for inflate.
89575fd0b74Schristos * This takes 10 bits, of which 7 may remain in the bit buffer.
89675fd0b74Schristos */
_tr_align(s)89775fd0b74Schristos void ZLIB_INTERNAL _tr_align(s)
89875fd0b74Schristos deflate_state *s;
89975fd0b74Schristos {
90075fd0b74Schristos send_bits(s, STATIC_TREES<<1, 3);
90175fd0b74Schristos send_code(s, END_BLOCK, static_ltree);
902ede78133Schristos #ifdef ZLIB_DEBUG
90375fd0b74Schristos s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
90475fd0b74Schristos #endif
90575fd0b74Schristos bi_flush(s);
90675fd0b74Schristos }
90775fd0b74Schristos
90875fd0b74Schristos /* ===========================================================================
90975fd0b74Schristos * Determine the best encoding for the current block: dynamic trees, static
910ede78133Schristos * trees or store, and write out the encoded block.
91175fd0b74Schristos */
_tr_flush_block(s,buf,stored_len,last)91275fd0b74Schristos void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
91375fd0b74Schristos deflate_state *s;
91475fd0b74Schristos charf *buf; /* input block, or NULL if too old */
91575fd0b74Schristos ulg stored_len; /* length of input block */
91675fd0b74Schristos int last; /* one if this is the last block for a file */
91775fd0b74Schristos {
91875fd0b74Schristos ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
91975fd0b74Schristos int max_blindex = 0; /* index of last bit length code of non zero freq */
92075fd0b74Schristos
92175fd0b74Schristos /* Build the Huffman trees unless a stored block is forced */
92275fd0b74Schristos if (s->level > 0) {
92375fd0b74Schristos
92475fd0b74Schristos /* Check if the file is binary or text */
92575fd0b74Schristos if (s->strm->data_type == Z_UNKNOWN)
92675fd0b74Schristos s->strm->data_type = detect_data_type(s);
92775fd0b74Schristos
92875fd0b74Schristos /* Construct the literal and distance trees */
92975fd0b74Schristos build_tree(s, (tree_desc *)(&(s->l_desc)));
93075fd0b74Schristos Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
93175fd0b74Schristos s->static_len));
93275fd0b74Schristos
93375fd0b74Schristos build_tree(s, (tree_desc *)(&(s->d_desc)));
93475fd0b74Schristos Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
93575fd0b74Schristos s->static_len));
93675fd0b74Schristos /* At this point, opt_len and static_len are the total bit lengths of
93775fd0b74Schristos * the compressed block data, excluding the tree representations.
93875fd0b74Schristos */
93975fd0b74Schristos
94075fd0b74Schristos /* Build the bit length tree for the above two trees, and get the index
94175fd0b74Schristos * in bl_order of the last bit length code to send.
94275fd0b74Schristos */
94375fd0b74Schristos max_blindex = build_bl_tree(s);
94475fd0b74Schristos
94575fd0b74Schristos /* Determine the best encoding. Compute the block lengths in bytes. */
94675fd0b74Schristos opt_lenb = (s->opt_len+3+7)>>3;
94775fd0b74Schristos static_lenb = (s->static_len+3+7)>>3;
94875fd0b74Schristos
94975fd0b74Schristos Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
95075fd0b74Schristos opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
951*e992f068Schristos s->sym_next / 3));
95275fd0b74Schristos
95375fd0b74Schristos if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
95475fd0b74Schristos
95575fd0b74Schristos } else {
95675fd0b74Schristos Assert(buf != (char*)0, "lost buf");
95775fd0b74Schristos opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
95875fd0b74Schristos }
95975fd0b74Schristos
96075fd0b74Schristos #ifdef FORCE_STORED
96175fd0b74Schristos if (buf != (char*)0) { /* force stored block */
96275fd0b74Schristos #else
96375fd0b74Schristos if (stored_len+4 <= opt_lenb && buf != (char*)0) {
96475fd0b74Schristos /* 4: two words for the lengths */
96575fd0b74Schristos #endif
96675fd0b74Schristos /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
96775fd0b74Schristos * Otherwise we can't have processed more than WSIZE input bytes since
96875fd0b74Schristos * the last block flush, because compression would have been
96975fd0b74Schristos * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
97075fd0b74Schristos * transform a block into a stored block.
97175fd0b74Schristos */
97275fd0b74Schristos _tr_stored_block(s, buf, stored_len, last);
97375fd0b74Schristos
97475fd0b74Schristos #ifdef FORCE_STATIC
97575fd0b74Schristos } else if (static_lenb >= 0) { /* force static trees */
97675fd0b74Schristos #else
97775fd0b74Schristos } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
97875fd0b74Schristos #endif
97975fd0b74Schristos send_bits(s, (STATIC_TREES<<1)+last, 3);
98075fd0b74Schristos compress_block(s, (const ct_data *)static_ltree,
98175fd0b74Schristos (const ct_data *)static_dtree);
982ede78133Schristos #ifdef ZLIB_DEBUG
98375fd0b74Schristos s->compressed_len += 3 + s->static_len;
98475fd0b74Schristos #endif
98575fd0b74Schristos } else {
98675fd0b74Schristos send_bits(s, (DYN_TREES<<1)+last, 3);
98775fd0b74Schristos send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
98875fd0b74Schristos max_blindex+1);
98975fd0b74Schristos compress_block(s, (const ct_data *)s->dyn_ltree,
99075fd0b74Schristos (const ct_data *)s->dyn_dtree);
991ede78133Schristos #ifdef ZLIB_DEBUG
99275fd0b74Schristos s->compressed_len += 3 + s->opt_len;
99375fd0b74Schristos #endif
99475fd0b74Schristos }
99575fd0b74Schristos Assert (s->compressed_len == s->bits_sent, "bad compressed size");
99675fd0b74Schristos /* The above check is made mod 2^32, for files larger than 512 MB
99775fd0b74Schristos * and uLong implemented on 32 bits.
99875fd0b74Schristos */
99975fd0b74Schristos init_block(s);
100075fd0b74Schristos
100175fd0b74Schristos if (last) {
100275fd0b74Schristos bi_windup(s);
1003ede78133Schristos #ifdef ZLIB_DEBUG
100475fd0b74Schristos s->compressed_len += 7; /* align on byte boundary */
100575fd0b74Schristos #endif
100675fd0b74Schristos }
100775fd0b74Schristos Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
100875fd0b74Schristos s->compressed_len-7*last));
100975fd0b74Schristos }
101075fd0b74Schristos
101175fd0b74Schristos /* ===========================================================================
101275fd0b74Schristos * Save the match info and tally the frequency counts. Return true if
101375fd0b74Schristos * the current block must be flushed.
101475fd0b74Schristos */
_tr_tally(s,dist,lc)101575fd0b74Schristos int ZLIB_INTERNAL _tr_tally (s, dist, lc)
101675fd0b74Schristos deflate_state *s;
101775fd0b74Schristos unsigned dist; /* distance of matched string */
101875fd0b74Schristos unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
101975fd0b74Schristos {
1020*e992f068Schristos s->sym_buf[s->sym_next++] = dist;
1021*e992f068Schristos s->sym_buf[s->sym_next++] = dist >> 8;
1022*e992f068Schristos s->sym_buf[s->sym_next++] = lc;
102375fd0b74Schristos if (dist == 0) {
102475fd0b74Schristos /* lc is the unmatched char */
102575fd0b74Schristos s->dyn_ltree[lc].Freq++;
102675fd0b74Schristos } else {
102775fd0b74Schristos s->matches++;
102875fd0b74Schristos /* Here, lc is the match length - MIN_MATCH */
102975fd0b74Schristos dist--; /* dist = match distance - 1 */
103075fd0b74Schristos Assert((ush)dist < (ush)MAX_DIST(s) &&
103175fd0b74Schristos (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
103275fd0b74Schristos (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
103375fd0b74Schristos
103475fd0b74Schristos s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
103575fd0b74Schristos s->dyn_dtree[d_code(dist)].Freq++;
103675fd0b74Schristos }
1037*e992f068Schristos return (s->sym_next == s->sym_end);
103875fd0b74Schristos }
103975fd0b74Schristos
104075fd0b74Schristos /* ===========================================================================
104175fd0b74Schristos * Send the block data compressed using the given Huffman trees
104275fd0b74Schristos */
compress_block(s,ltree,dtree)104375fd0b74Schristos local void compress_block(s, ltree, dtree)
104475fd0b74Schristos deflate_state *s;
104575fd0b74Schristos const ct_data *ltree; /* literal tree */
104675fd0b74Schristos const ct_data *dtree; /* distance tree */
104775fd0b74Schristos {
104875fd0b74Schristos unsigned dist; /* distance of matched string */
104975fd0b74Schristos int lc; /* match length or unmatched char (if dist == 0) */
1050*e992f068Schristos unsigned sx = 0; /* running index in sym_buf */
105175fd0b74Schristos unsigned code; /* the code to send */
105275fd0b74Schristos int extra; /* number of extra bits to send */
105375fd0b74Schristos
1054*e992f068Schristos if (s->sym_next != 0) do {
1055*e992f068Schristos dist = s->sym_buf[sx++] & 0xff;
1056*e992f068Schristos dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
1057*e992f068Schristos lc = s->sym_buf[sx++];
105875fd0b74Schristos if (dist == 0) {
105975fd0b74Schristos send_code(s, lc, ltree); /* send a literal byte */
106075fd0b74Schristos Tracecv(isgraph(lc), (stderr," '%c' ", lc));
106175fd0b74Schristos } else {
106275fd0b74Schristos /* Here, lc is the match length - MIN_MATCH */
106375fd0b74Schristos code = _length_code[lc];
106475fd0b74Schristos send_code(s, code+LITERALS+1, ltree); /* send the length code */
106575fd0b74Schristos extra = extra_lbits[code];
106675fd0b74Schristos if (extra != 0) {
106775fd0b74Schristos lc -= base_length[code];
106875fd0b74Schristos send_bits(s, lc, extra); /* send the extra length bits */
106975fd0b74Schristos }
107075fd0b74Schristos dist--; /* dist is now the match distance - 1 */
107175fd0b74Schristos code = d_code(dist);
107275fd0b74Schristos Assert (code < D_CODES, "bad d_code");
107375fd0b74Schristos
107475fd0b74Schristos send_code(s, code, dtree); /* send the distance code */
107575fd0b74Schristos extra = extra_dbits[code];
107675fd0b74Schristos if (extra != 0) {
1077ede78133Schristos dist -= (unsigned)base_dist[code];
107875fd0b74Schristos send_bits(s, dist, extra); /* send the extra distance bits */
107975fd0b74Schristos }
108075fd0b74Schristos } /* literal or match pair ? */
108175fd0b74Schristos
1082*e992f068Schristos /* Check that the overlay between pending_buf and sym_buf is ok: */
1083*e992f068Schristos Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
108475fd0b74Schristos
1085*e992f068Schristos } while (sx < s->sym_next);
108675fd0b74Schristos
108775fd0b74Schristos send_code(s, END_BLOCK, ltree);
108875fd0b74Schristos }
108975fd0b74Schristos
109075fd0b74Schristos /* ===========================================================================
109175fd0b74Schristos * Check if the data type is TEXT or BINARY, using the following algorithm:
109275fd0b74Schristos * - TEXT if the two conditions below are satisfied:
109375fd0b74Schristos * a) There are no non-portable control characters belonging to the
1094*e992f068Schristos * "block list" (0..6, 14..25, 28..31).
109575fd0b74Schristos * b) There is at least one printable character belonging to the
1096*e992f068Schristos * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
109775fd0b74Schristos * - BINARY otherwise.
109875fd0b74Schristos * - The following partially-portable control characters form a
109975fd0b74Schristos * "gray list" that is ignored in this detection algorithm:
110075fd0b74Schristos * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
110175fd0b74Schristos * IN assertion: the fields Freq of dyn_ltree are set.
110275fd0b74Schristos */
detect_data_type(s)110375fd0b74Schristos local int detect_data_type(s)
110475fd0b74Schristos deflate_state *s;
110575fd0b74Schristos {
1106*e992f068Schristos /* block_mask is the bit mask of block-listed bytes
110775fd0b74Schristos * set bits 0..6, 14..25, and 28..31
110875fd0b74Schristos * 0xf3ffc07f = binary 11110011111111111100000001111111
110975fd0b74Schristos */
1110*e992f068Schristos unsigned long block_mask = 0xf3ffc07fUL;
111175fd0b74Schristos int n;
111275fd0b74Schristos
1113*e992f068Schristos /* Check for non-textual ("block-listed") bytes. */
1114*e992f068Schristos for (n = 0; n <= 31; n++, block_mask >>= 1)
1115*e992f068Schristos if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
111675fd0b74Schristos return Z_BINARY;
111775fd0b74Schristos
1118*e992f068Schristos /* Check for textual ("allow-listed") bytes. */
111975fd0b74Schristos if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
112075fd0b74Schristos || s->dyn_ltree[13].Freq != 0)
112175fd0b74Schristos return Z_TEXT;
112275fd0b74Schristos for (n = 32; n < LITERALS; n++)
112375fd0b74Schristos if (s->dyn_ltree[n].Freq != 0)
112475fd0b74Schristos return Z_TEXT;
112575fd0b74Schristos
1126*e992f068Schristos /* There are no "block-listed" or "allow-listed" bytes:
112775fd0b74Schristos * this stream either is empty or has tolerated ("gray-listed") bytes only.
112875fd0b74Schristos */
112975fd0b74Schristos return Z_BINARY;
113075fd0b74Schristos }
113175fd0b74Schristos
113275fd0b74Schristos /* ===========================================================================
113375fd0b74Schristos * Reverse the first len bits of a code, using straightforward code (a faster
113475fd0b74Schristos * method would use a table)
113575fd0b74Schristos * IN assertion: 1 <= len <= 15
113675fd0b74Schristos */
bi_reverse(code,len)113775fd0b74Schristos local unsigned bi_reverse(code, len)
113875fd0b74Schristos unsigned code; /* the value to invert */
113975fd0b74Schristos int len; /* its bit length */
114075fd0b74Schristos {
114175fd0b74Schristos register unsigned res = 0;
114275fd0b74Schristos do {
114375fd0b74Schristos res |= code & 1;
114475fd0b74Schristos code >>= 1, res <<= 1;
114575fd0b74Schristos } while (--len > 0);
114675fd0b74Schristos return res >> 1;
114775fd0b74Schristos }
114875fd0b74Schristos
114975fd0b74Schristos /* ===========================================================================
115075fd0b74Schristos * Flush the bit buffer, keeping at most 7 bits in it.
115175fd0b74Schristos */
bi_flush(s)115275fd0b74Schristos local void bi_flush(s)
115375fd0b74Schristos deflate_state *s;
115475fd0b74Schristos {
115575fd0b74Schristos if (s->bi_valid == 16) {
115675fd0b74Schristos put_short(s, s->bi_buf);
115775fd0b74Schristos s->bi_buf = 0;
115875fd0b74Schristos s->bi_valid = 0;
115975fd0b74Schristos } else if (s->bi_valid >= 8) {
116075fd0b74Schristos put_byte(s, (Byte)s->bi_buf);
116175fd0b74Schristos s->bi_buf >>= 8;
116275fd0b74Schristos s->bi_valid -= 8;
116375fd0b74Schristos }
116475fd0b74Schristos }
116575fd0b74Schristos
116675fd0b74Schristos /* ===========================================================================
116775fd0b74Schristos * Flush the bit buffer and align the output on a byte boundary
116875fd0b74Schristos */
bi_windup(s)116975fd0b74Schristos local void bi_windup(s)
117075fd0b74Schristos deflate_state *s;
117175fd0b74Schristos {
117275fd0b74Schristos if (s->bi_valid > 8) {
117375fd0b74Schristos put_short(s, s->bi_buf);
117475fd0b74Schristos } else if (s->bi_valid > 0) {
117575fd0b74Schristos put_byte(s, (Byte)s->bi_buf);
117675fd0b74Schristos }
117775fd0b74Schristos s->bi_buf = 0;
117875fd0b74Schristos s->bi_valid = 0;
1179ede78133Schristos #ifdef ZLIB_DEBUG
118075fd0b74Schristos s->bits_sent = (s->bits_sent+7) & ~7;
118175fd0b74Schristos #endif
118275fd0b74Schristos }
1183