16141cf33Sderaadt /* trees.c -- output deflated data using Huffman coding 2f0633749Stb * Copyright (C) 1995-2024 Jean-loup Gailly 336f395ceStb * detect_data_type() function provided freely by Cosmin Truta, 2006 46141cf33Sderaadt * For conditions of distribution and use, see copyright notice in zlib.h 56141cf33Sderaadt */ 66141cf33Sderaadt 76141cf33Sderaadt /* 86141cf33Sderaadt * ALGORITHM 96141cf33Sderaadt * 106141cf33Sderaadt * The "deflation" process uses several Huffman trees. The more 116141cf33Sderaadt * common source values are represented by shorter bit sequences. 126141cf33Sderaadt * 136141cf33Sderaadt * Each code tree is stored in a compressed form which is itself 146141cf33Sderaadt * a Huffman encoding of the lengths of all the code strings (in 156141cf33Sderaadt * ascending order by source values). The actual code strings are 166141cf33Sderaadt * reconstructed from the lengths in the inflate process, as described 176141cf33Sderaadt * in the deflate specification. 186141cf33Sderaadt * 196141cf33Sderaadt * REFERENCES 206141cf33Sderaadt * 216141cf33Sderaadt * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". 226141cf33Sderaadt * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc 236141cf33Sderaadt * 246141cf33Sderaadt * Storer, James A. 256141cf33Sderaadt * Data Compression: Methods and Theory, pp. 49-50. 266141cf33Sderaadt * Computer Science Press, 1988. ISBN 0-7167-8156-5. 276141cf33Sderaadt * 286141cf33Sderaadt * Sedgewick, R. 296141cf33Sderaadt * Algorithms, p290. 306141cf33Sderaadt * Addison-Wesley, 1983. ISBN 0-201-06672-6. 316141cf33Sderaadt */ 326141cf33Sderaadt 336141cf33Sderaadt /* #define GEN_TREES_H */ 346141cf33Sderaadt 356141cf33Sderaadt #include "deflate.h" 366141cf33Sderaadt 3736f395ceStb #ifdef ZLIB_DEBUG 386141cf33Sderaadt # include <ctype.h> 396141cf33Sderaadt #endif 406141cf33Sderaadt 416141cf33Sderaadt /* =========================================================================== 426141cf33Sderaadt * Constants 436141cf33Sderaadt */ 446141cf33Sderaadt 456141cf33Sderaadt #define MAX_BL_BITS 7 466141cf33Sderaadt /* Bit length codes must not exceed MAX_BL_BITS bits */ 476141cf33Sderaadt 486141cf33Sderaadt #define END_BLOCK 256 496141cf33Sderaadt /* end of block literal code */ 506141cf33Sderaadt 516141cf33Sderaadt #define REP_3_6 16 526141cf33Sderaadt /* repeat previous bit length 3-6 times (2 bits of repeat count) */ 536141cf33Sderaadt 546141cf33Sderaadt #define REPZ_3_10 17 556141cf33Sderaadt /* repeat a zero length 3-10 times (3 bits of repeat count) */ 566141cf33Sderaadt 576141cf33Sderaadt #define REPZ_11_138 18 586141cf33Sderaadt /* repeat a zero length 11-138 times (7 bits of repeat count) */ 596141cf33Sderaadt 606141cf33Sderaadt local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ 616141cf33Sderaadt = {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}; 626141cf33Sderaadt 636141cf33Sderaadt local const int extra_dbits[D_CODES] /* extra bits for each distance code */ 646141cf33Sderaadt = {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}; 656141cf33Sderaadt 666141cf33Sderaadt local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ 676141cf33Sderaadt = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; 686141cf33Sderaadt 696141cf33Sderaadt local const uch bl_order[BL_CODES] 706141cf33Sderaadt = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; 716141cf33Sderaadt /* The lengths of the bit length codes are sent in order of decreasing 726141cf33Sderaadt * probability, to avoid transmitting the lengths for unused bit length codes. 736141cf33Sderaadt */ 746141cf33Sderaadt 756141cf33Sderaadt /* =========================================================================== 766141cf33Sderaadt * Local data. These are initialized only once. 776141cf33Sderaadt */ 786141cf33Sderaadt 796141cf33Sderaadt #define DIST_CODE_LEN 512 /* see definition of array dist_code below */ 806141cf33Sderaadt 816141cf33Sderaadt #if defined(GEN_TREES_H) || !defined(STDC) 826141cf33Sderaadt /* non ANSI compilers may not accept trees.h */ 836141cf33Sderaadt 846141cf33Sderaadt local ct_data static_ltree[L_CODES+2]; 856141cf33Sderaadt /* The static literal tree. Since the bit lengths are imposed, there is no 866141cf33Sderaadt * need for the L_CODES extra codes used during heap construction. However 876141cf33Sderaadt * The codes 286 and 287 are needed to build a canonical tree (see _tr_init 886141cf33Sderaadt * below). 896141cf33Sderaadt */ 906141cf33Sderaadt 916141cf33Sderaadt local ct_data static_dtree[D_CODES]; 926141cf33Sderaadt /* The static distance tree. (Actually a trivial tree since all codes use 936141cf33Sderaadt * 5 bits.) 946141cf33Sderaadt */ 956141cf33Sderaadt 966141cf33Sderaadt uch _dist_code[DIST_CODE_LEN]; 976141cf33Sderaadt /* Distance codes. The first 256 values correspond to the distances 986141cf33Sderaadt * 3 .. 258, the last 256 values correspond to the top 8 bits of 996141cf33Sderaadt * the 15 bit distances. 1006141cf33Sderaadt */ 1016141cf33Sderaadt 1026141cf33Sderaadt uch _length_code[MAX_MATCH-MIN_MATCH+1]; 1036141cf33Sderaadt /* length code for each normalized match length (0 == MIN_MATCH) */ 1046141cf33Sderaadt 1056141cf33Sderaadt local int base_length[LENGTH_CODES]; 1066141cf33Sderaadt /* First normalized length for each code (0 = MIN_MATCH) */ 1076141cf33Sderaadt 1086141cf33Sderaadt local int base_dist[D_CODES]; 1096141cf33Sderaadt /* First normalized distance for each code (0 = distance of 1) */ 1106141cf33Sderaadt 1116141cf33Sderaadt #else 1126141cf33Sderaadt # include "trees.h" 1136141cf33Sderaadt #endif /* GEN_TREES_H */ 1146141cf33Sderaadt 1156141cf33Sderaadt struct static_tree_desc_s { 1166141cf33Sderaadt const ct_data *static_tree; /* static tree or NULL */ 1176141cf33Sderaadt const intf *extra_bits; /* extra bits for each code or NULL */ 1186141cf33Sderaadt int extra_base; /* base index for extra_bits */ 1196141cf33Sderaadt int elems; /* max number of elements in the tree */ 1206141cf33Sderaadt int max_length; /* max bit length for the codes */ 1216141cf33Sderaadt }; 1226141cf33Sderaadt 123cfac609cStb #ifdef NO_INIT_GLOBAL_POINTERS 124cfac609cStb # define TCONST 125cfac609cStb #else 126cfac609cStb # define TCONST const 127cfac609cStb #endif 128cfac609cStb 129cfac609cStb local TCONST static_tree_desc static_l_desc = 1306141cf33Sderaadt {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; 1316141cf33Sderaadt 132cfac609cStb local TCONST static_tree_desc static_d_desc = 1336141cf33Sderaadt {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; 1346141cf33Sderaadt 135cfac609cStb local TCONST static_tree_desc static_bl_desc = 1366141cf33Sderaadt {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; 1376141cf33Sderaadt 1386141cf33Sderaadt /* =========================================================================== 139cfac609cStb * Output a short LSB first on the stream. 140cfac609cStb * IN assertion: there is enough room in pendingBuf. 1416141cf33Sderaadt */ 142cfac609cStb #define put_short(s, w) { \ 143cfac609cStb put_byte(s, (uch)((w) & 0xff)); \ 144cfac609cStb put_byte(s, (uch)((ush)(w) >> 8)); \ 145cfac609cStb } 1466141cf33Sderaadt 147cfac609cStb /* =========================================================================== 148cfac609cStb * Reverse the first len bits of a code, using straightforward code (a faster 149cfac609cStb * method would use a table) 150cfac609cStb * IN assertion: 1 <= len <= 15 151cfac609cStb */ 152cfac609cStb local unsigned bi_reverse(unsigned code, int len) { 153cfac609cStb register unsigned res = 0; 154cfac609cStb do { 155cfac609cStb res |= code & 1; 156cfac609cStb code >>= 1, res <<= 1; 157cfac609cStb } while (--len > 0); 158cfac609cStb return res >> 1; 159cfac609cStb } 160cfac609cStb 161cfac609cStb /* =========================================================================== 162cfac609cStb * Flush the bit buffer, keeping at most 7 bits in it. 163cfac609cStb */ 164cfac609cStb local void bi_flush(deflate_state *s) { 165cfac609cStb if (s->bi_valid == 16) { 166cfac609cStb put_short(s, s->bi_buf); 167cfac609cStb s->bi_buf = 0; 168cfac609cStb s->bi_valid = 0; 169cfac609cStb } else if (s->bi_valid >= 8) { 170cfac609cStb put_byte(s, (Byte)s->bi_buf); 171cfac609cStb s->bi_buf >>= 8; 172cfac609cStb s->bi_valid -= 8; 173cfac609cStb } 174cfac609cStb } 175cfac609cStb 176cfac609cStb /* =========================================================================== 177cfac609cStb * Flush the bit buffer and align the output on a byte boundary 178cfac609cStb */ 179cfac609cStb local void bi_windup(deflate_state *s) { 180cfac609cStb if (s->bi_valid > 8) { 181cfac609cStb put_short(s, s->bi_buf); 182cfac609cStb } else if (s->bi_valid > 0) { 183cfac609cStb put_byte(s, (Byte)s->bi_buf); 184cfac609cStb } 185*0a218225Stb s->bi_used = ((s->bi_valid - 1) & 7) + 1; 186cfac609cStb s->bi_buf = 0; 187cfac609cStb s->bi_valid = 0; 188cfac609cStb #ifdef ZLIB_DEBUG 189cfac609cStb s->bits_sent = (s->bits_sent + 7) & ~7; 190cfac609cStb #endif 191cfac609cStb } 192cfac609cStb 193cfac609cStb /* =========================================================================== 194cfac609cStb * Generate the codes for a given tree and bit counts (which need not be 195cfac609cStb * optimal). 196cfac609cStb * IN assertion: the array bl_count contains the bit length statistics for 197cfac609cStb * the given tree and the field len is set for all tree elements. 198cfac609cStb * OUT assertion: the field code is set for all tree elements of non 199cfac609cStb * zero code length. 200cfac609cStb */ 201cfac609cStb local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) { 202cfac609cStb ush next_code[MAX_BITS+1]; /* next code value for each bit length */ 203cfac609cStb unsigned code = 0; /* running code value */ 204cfac609cStb int bits; /* bit index */ 205cfac609cStb int n; /* code index */ 206cfac609cStb 207cfac609cStb /* The distribution counts are first used to generate the code values 208cfac609cStb * without bit reversal. 209cfac609cStb */ 210cfac609cStb for (bits = 1; bits <= MAX_BITS; bits++) { 211cfac609cStb code = (code + bl_count[bits - 1]) << 1; 212cfac609cStb next_code[bits] = (ush)code; 213cfac609cStb } 214cfac609cStb /* Check that the bit counts in bl_count are consistent. The last code 215cfac609cStb * must be all ones. 216cfac609cStb */ 217cfac609cStb Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1, 218cfac609cStb "inconsistent bit counts"); 219cfac609cStb Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); 220cfac609cStb 221cfac609cStb for (n = 0; n <= max_code; n++) { 222cfac609cStb int len = tree[n].Len; 223cfac609cStb if (len == 0) continue; 224cfac609cStb /* Now reverse the bits */ 225cfac609cStb tree[n].Code = (ush)bi_reverse(next_code[len]++, len); 226cfac609cStb 227cfac609cStb Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", 228cfac609cStb n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); 229cfac609cStb } 230cfac609cStb } 2316141cf33Sderaadt 2326141cf33Sderaadt #ifdef GEN_TREES_H 233cfac609cStb local void gen_trees_header(void); 2346141cf33Sderaadt #endif 2356141cf33Sderaadt 23636f395ceStb #ifndef ZLIB_DEBUG 2376141cf33Sderaadt # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) 2386141cf33Sderaadt /* Send a code of the given tree. c and tree must not have side effects */ 2396141cf33Sderaadt 24036f395ceStb #else /* !ZLIB_DEBUG */ 2416141cf33Sderaadt # define send_code(s, c, tree) \ 2426141cf33Sderaadt { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ 2436141cf33Sderaadt send_bits(s, tree[c].Code, tree[c].Len); } 2446141cf33Sderaadt #endif 2456141cf33Sderaadt 2466141cf33Sderaadt /* =========================================================================== 2476141cf33Sderaadt * Send a value on a given number of bits. 2486141cf33Sderaadt * IN assertion: length <= 16 and value fits in length bits. 2496141cf33Sderaadt */ 25036f395ceStb #ifdef ZLIB_DEBUG 251cfac609cStb local void send_bits(deflate_state *s, int value, int length) { 2526141cf33Sderaadt Tracevv((stderr," l %2d v %4x ", length, value)); 2536141cf33Sderaadt Assert(length > 0 && length <= 15, "invalid length"); 2546141cf33Sderaadt s->bits_sent += (ulg)length; 2556141cf33Sderaadt 2566141cf33Sderaadt /* If not enough room in bi_buf, use (valid) bits from bi_buf and 2576141cf33Sderaadt * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid)) 2586141cf33Sderaadt * unused bits in value. 2596141cf33Sderaadt */ 2606141cf33Sderaadt if (s->bi_valid > (int)Buf_size - length) { 26136f395ceStb s->bi_buf |= (ush)value << s->bi_valid; 2626141cf33Sderaadt put_short(s, s->bi_buf); 2636141cf33Sderaadt s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); 2646141cf33Sderaadt s->bi_valid += length - Buf_size; 2656141cf33Sderaadt } else { 26636f395ceStb s->bi_buf |= (ush)value << s->bi_valid; 2676141cf33Sderaadt s->bi_valid += length; 2686141cf33Sderaadt } 2696141cf33Sderaadt } 27036f395ceStb #else /* !ZLIB_DEBUG */ 2716141cf33Sderaadt 2726141cf33Sderaadt #define send_bits(s, value, length) \ 2736141cf33Sderaadt { int len = length;\ 2746141cf33Sderaadt if (s->bi_valid > (int)Buf_size - len) {\ 27536f395ceStb int val = (int)value;\ 27636f395ceStb s->bi_buf |= (ush)val << s->bi_valid;\ 2776141cf33Sderaadt put_short(s, s->bi_buf);\ 2786141cf33Sderaadt s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ 2796141cf33Sderaadt s->bi_valid += len - Buf_size;\ 2806141cf33Sderaadt } else {\ 28136f395ceStb s->bi_buf |= (ush)(value) << s->bi_valid;\ 2826141cf33Sderaadt s->bi_valid += len;\ 2836141cf33Sderaadt }\ 2846141cf33Sderaadt } 28536f395ceStb #endif /* ZLIB_DEBUG */ 2866141cf33Sderaadt 2876141cf33Sderaadt 2886141cf33Sderaadt /* the arguments must not have side effects */ 2896141cf33Sderaadt 2906141cf33Sderaadt /* =========================================================================== 2916141cf33Sderaadt * Initialize the various 'constant' tables. 2926141cf33Sderaadt */ 293cfac609cStb local void tr_static_init(void) { 2946141cf33Sderaadt #if defined(GEN_TREES_H) || !defined(STDC) 2956141cf33Sderaadt static int static_init_done = 0; 2966141cf33Sderaadt int n; /* iterates over tree elements */ 2976141cf33Sderaadt int bits; /* bit counter */ 2986141cf33Sderaadt int length; /* length value */ 2996141cf33Sderaadt int code; /* code value */ 3006141cf33Sderaadt int dist; /* distance index */ 3016141cf33Sderaadt ush bl_count[MAX_BITS+1]; 3026141cf33Sderaadt /* number of codes at each bit length for an optimal tree */ 3036141cf33Sderaadt 3046141cf33Sderaadt if (static_init_done) return; 3056141cf33Sderaadt 3066141cf33Sderaadt /* For some embedded targets, global variables are not initialized: */ 30736f395ceStb #ifdef NO_INIT_GLOBAL_POINTERS 3086141cf33Sderaadt static_l_desc.static_tree = static_ltree; 3096141cf33Sderaadt static_l_desc.extra_bits = extra_lbits; 3106141cf33Sderaadt static_d_desc.static_tree = static_dtree; 3116141cf33Sderaadt static_d_desc.extra_bits = extra_dbits; 3126141cf33Sderaadt static_bl_desc.extra_bits = extra_blbits; 31336f395ceStb #endif 3146141cf33Sderaadt 3156141cf33Sderaadt /* Initialize the mapping length (0..255) -> length code (0..28) */ 3166141cf33Sderaadt length = 0; 3176141cf33Sderaadt for (code = 0; code < LENGTH_CODES-1; code++) { 3186141cf33Sderaadt base_length[code] = length; 3196141cf33Sderaadt for (n = 0; n < (1 << extra_lbits[code]); n++) { 3206141cf33Sderaadt _length_code[length++] = (uch)code; 3216141cf33Sderaadt } 3226141cf33Sderaadt } 3236141cf33Sderaadt Assert (length == 256, "tr_static_init: length != 256"); 3246141cf33Sderaadt /* Note that the length 255 (match length 258) can be represented 3256141cf33Sderaadt * in two different ways: code 284 + 5 bits or code 285, so we 3266141cf33Sderaadt * overwrite length_code[255] to use the best encoding: 3276141cf33Sderaadt */ 3286141cf33Sderaadt _length_code[length - 1] = (uch)code; 3296141cf33Sderaadt 3306141cf33Sderaadt /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ 3316141cf33Sderaadt dist = 0; 3326141cf33Sderaadt for (code = 0 ; code < 16; code++) { 3336141cf33Sderaadt base_dist[code] = dist; 3346141cf33Sderaadt for (n = 0; n < (1 << extra_dbits[code]); n++) { 3356141cf33Sderaadt _dist_code[dist++] = (uch)code; 3366141cf33Sderaadt } 3376141cf33Sderaadt } 3386141cf33Sderaadt Assert (dist == 256, "tr_static_init: dist != 256"); 3396141cf33Sderaadt dist >>= 7; /* from now on, all distances are divided by 128 */ 3406141cf33Sderaadt for ( ; code < D_CODES; code++) { 3416141cf33Sderaadt base_dist[code] = dist << 7; 3426141cf33Sderaadt for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { 3436141cf33Sderaadt _dist_code[256 + dist++] = (uch)code; 3446141cf33Sderaadt } 3456141cf33Sderaadt } 3466141cf33Sderaadt Assert (dist == 256, "tr_static_init: 256 + dist != 512"); 3476141cf33Sderaadt 3486141cf33Sderaadt /* Construct the codes of the static literal tree */ 3496141cf33Sderaadt for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; 3506141cf33Sderaadt n = 0; 3516141cf33Sderaadt while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; 3526141cf33Sderaadt while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; 3536141cf33Sderaadt while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; 3546141cf33Sderaadt while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; 3556141cf33Sderaadt /* Codes 286 and 287 do not exist, but we must include them in the 3566141cf33Sderaadt * tree construction to get a canonical Huffman tree (longest code 3576141cf33Sderaadt * all ones) 3586141cf33Sderaadt */ 3596141cf33Sderaadt gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); 3606141cf33Sderaadt 3616141cf33Sderaadt /* The static distance tree is trivial: */ 3626141cf33Sderaadt for (n = 0; n < D_CODES; n++) { 3636141cf33Sderaadt static_dtree[n].Len = 5; 3646141cf33Sderaadt static_dtree[n].Code = bi_reverse((unsigned)n, 5); 3656141cf33Sderaadt } 3666141cf33Sderaadt static_init_done = 1; 3676141cf33Sderaadt 3686141cf33Sderaadt # ifdef GEN_TREES_H 3696141cf33Sderaadt gen_trees_header(); 3706141cf33Sderaadt # endif 3716141cf33Sderaadt #endif /* defined(GEN_TREES_H) || !defined(STDC) */ 3726141cf33Sderaadt } 3736141cf33Sderaadt 3746141cf33Sderaadt /* =========================================================================== 375ddf65acdStb * Generate the file trees.h describing the static trees. 3766141cf33Sderaadt */ 3776141cf33Sderaadt #ifdef GEN_TREES_H 37836f395ceStb # ifndef ZLIB_DEBUG 3796141cf33Sderaadt # include <stdio.h> 3806141cf33Sderaadt # endif 3816141cf33Sderaadt 3826141cf33Sderaadt # define SEPARATOR(i, last, width) \ 3836141cf33Sderaadt ((i) == (last)? "\n};\n\n" : \ 3846141cf33Sderaadt ((i) % (width) == (width) - 1 ? ",\n" : ", ")) 3856141cf33Sderaadt 386cfac609cStb void gen_trees_header(void) { 3876141cf33Sderaadt FILE *header = fopen("trees.h", "w"); 3886141cf33Sderaadt int i; 3896141cf33Sderaadt 3906141cf33Sderaadt Assert (header != NULL, "Can't open trees.h"); 3916141cf33Sderaadt fprintf(header, 3926141cf33Sderaadt "/* header created automatically with -DGEN_TREES_H */\n\n"); 3936141cf33Sderaadt 3946141cf33Sderaadt fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); 3956141cf33Sderaadt for (i = 0; i < L_CODES+2; i++) { 3966141cf33Sderaadt fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, 3976141cf33Sderaadt static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); 3986141cf33Sderaadt } 3996141cf33Sderaadt 4006141cf33Sderaadt fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); 4016141cf33Sderaadt for (i = 0; i < D_CODES; i++) { 4026141cf33Sderaadt fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, 4036141cf33Sderaadt static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); 4046141cf33Sderaadt } 4056141cf33Sderaadt 40636f395ceStb fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); 4076141cf33Sderaadt for (i = 0; i < DIST_CODE_LEN; i++) { 4086141cf33Sderaadt fprintf(header, "%2u%s", _dist_code[i], 4096141cf33Sderaadt SEPARATOR(i, DIST_CODE_LEN-1, 20)); 4106141cf33Sderaadt } 4116141cf33Sderaadt 41236f395ceStb fprintf(header, 41336f395ceStb "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); 4146141cf33Sderaadt for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { 4156141cf33Sderaadt fprintf(header, "%2u%s", _length_code[i], 4166141cf33Sderaadt SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); 4176141cf33Sderaadt } 4186141cf33Sderaadt 4196141cf33Sderaadt fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); 4206141cf33Sderaadt for (i = 0; i < LENGTH_CODES; i++) { 4216141cf33Sderaadt fprintf(header, "%1u%s", base_length[i], 4226141cf33Sderaadt SEPARATOR(i, LENGTH_CODES-1, 20)); 4236141cf33Sderaadt } 4246141cf33Sderaadt 4256141cf33Sderaadt fprintf(header, "local const int base_dist[D_CODES] = {\n"); 4266141cf33Sderaadt for (i = 0; i < D_CODES; i++) { 4276141cf33Sderaadt fprintf(header, "%5u%s", base_dist[i], 4286141cf33Sderaadt SEPARATOR(i, D_CODES-1, 10)); 4296141cf33Sderaadt } 4306141cf33Sderaadt 4316141cf33Sderaadt fclose(header); 4326141cf33Sderaadt } 4336141cf33Sderaadt #endif /* GEN_TREES_H */ 4346141cf33Sderaadt 4356141cf33Sderaadt /* =========================================================================== 436cfac609cStb * Initialize a new block. 437cfac609cStb */ 438cfac609cStb local void init_block(deflate_state *s) { 439cfac609cStb int n; /* iterates over tree elements */ 440cfac609cStb 441cfac609cStb /* Initialize the trees. */ 442cfac609cStb for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; 443cfac609cStb for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; 444cfac609cStb for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; 445cfac609cStb 446cfac609cStb s->dyn_ltree[END_BLOCK].Freq = 1; 447cfac609cStb s->opt_len = s->static_len = 0L; 448cfac609cStb s->sym_next = s->matches = 0; 449cfac609cStb } 450cfac609cStb 451cfac609cStb /* =========================================================================== 4526141cf33Sderaadt * Initialize the tree data structures for a new zlib stream. 4536141cf33Sderaadt */ 454cfac609cStb void ZLIB_INTERNAL _tr_init(deflate_state *s) { 4556141cf33Sderaadt tr_static_init(); 4566141cf33Sderaadt 4576141cf33Sderaadt s->l_desc.dyn_tree = s->dyn_ltree; 4586141cf33Sderaadt s->l_desc.stat_desc = &static_l_desc; 4596141cf33Sderaadt 4606141cf33Sderaadt s->d_desc.dyn_tree = s->dyn_dtree; 4616141cf33Sderaadt s->d_desc.stat_desc = &static_d_desc; 4626141cf33Sderaadt 4636141cf33Sderaadt s->bl_desc.dyn_tree = s->bl_tree; 4646141cf33Sderaadt s->bl_desc.stat_desc = &static_bl_desc; 4656141cf33Sderaadt 4666141cf33Sderaadt s->bi_buf = 0; 4676141cf33Sderaadt s->bi_valid = 0; 468*0a218225Stb s->bi_used = 0; 46936f395ceStb #ifdef ZLIB_DEBUG 4706141cf33Sderaadt s->compressed_len = 0L; 4716141cf33Sderaadt s->bits_sent = 0L; 4726141cf33Sderaadt #endif 4736141cf33Sderaadt 4746141cf33Sderaadt /* Initialize the first block of the first file: */ 4756141cf33Sderaadt init_block(s); 4766141cf33Sderaadt } 4776141cf33Sderaadt 4786141cf33Sderaadt #define SMALLEST 1 4796141cf33Sderaadt /* Index within the heap array of least frequent node in the Huffman tree */ 4806141cf33Sderaadt 4816141cf33Sderaadt 4826141cf33Sderaadt /* =========================================================================== 4836141cf33Sderaadt * Remove the smallest element from the heap and recreate the heap with 4846141cf33Sderaadt * one less element. Updates heap and heap_len. 4856141cf33Sderaadt */ 4866141cf33Sderaadt #define pqremove(s, tree, top) \ 4876141cf33Sderaadt {\ 4886141cf33Sderaadt top = s->heap[SMALLEST]; \ 4896141cf33Sderaadt s->heap[SMALLEST] = s->heap[s->heap_len--]; \ 4906141cf33Sderaadt pqdownheap(s, tree, SMALLEST); \ 4916141cf33Sderaadt } 4926141cf33Sderaadt 4936141cf33Sderaadt /* =========================================================================== 4946141cf33Sderaadt * Compares to subtrees, using the tree depth as tie breaker when 4956141cf33Sderaadt * the subtrees have equal frequency. This minimizes the worst case length. 4966141cf33Sderaadt */ 4976141cf33Sderaadt #define smaller(tree, n, m, depth) \ 4986141cf33Sderaadt (tree[n].Freq < tree[m].Freq || \ 4996141cf33Sderaadt (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) 5006141cf33Sderaadt 5016141cf33Sderaadt /* =========================================================================== 5026141cf33Sderaadt * Restore the heap property by moving down the tree starting at node k, 5036141cf33Sderaadt * exchanging a node with the smallest of its two sons if necessary, stopping 5046141cf33Sderaadt * when the heap property is re-established (each father smaller than its 5056141cf33Sderaadt * two sons). 5066141cf33Sderaadt */ 507cfac609cStb local void pqdownheap(deflate_state *s, ct_data *tree, int k) { 5086141cf33Sderaadt int v = s->heap[k]; 5096141cf33Sderaadt int j = k << 1; /* left son of k */ 5106141cf33Sderaadt while (j <= s->heap_len) { 5116141cf33Sderaadt /* Set j to the smallest of the two sons: */ 5126141cf33Sderaadt if (j < s->heap_len && 5136141cf33Sderaadt smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) { 5146141cf33Sderaadt j++; 5156141cf33Sderaadt } 5166141cf33Sderaadt /* Exit if v is smaller than both sons */ 5176141cf33Sderaadt if (smaller(tree, v, s->heap[j], s->depth)) break; 5186141cf33Sderaadt 5196141cf33Sderaadt /* Exchange v with the smallest son */ 5206141cf33Sderaadt s->heap[k] = s->heap[j]; k = j; 5216141cf33Sderaadt 5226141cf33Sderaadt /* And continue down the tree, setting j to the left son of k */ 5236141cf33Sderaadt j <<= 1; 5246141cf33Sderaadt } 5256141cf33Sderaadt s->heap[k] = v; 5266141cf33Sderaadt } 5276141cf33Sderaadt 5286141cf33Sderaadt /* =========================================================================== 5296141cf33Sderaadt * Compute the optimal bit lengths for a tree and update the total bit length 5306141cf33Sderaadt * for the current block. 5316141cf33Sderaadt * IN assertion: the fields freq and dad are set, heap[heap_max] and 5326141cf33Sderaadt * above are the tree nodes sorted by increasing frequency. 5336141cf33Sderaadt * OUT assertions: the field len is set to the optimal bit length, the 5346141cf33Sderaadt * array bl_count contains the frequencies for each bit length. 5356141cf33Sderaadt * The length opt_len is updated; static_len is also updated if stree is 5366141cf33Sderaadt * not null. 5376141cf33Sderaadt */ 538cfac609cStb local void gen_bitlen(deflate_state *s, tree_desc *desc) { 5396141cf33Sderaadt ct_data *tree = desc->dyn_tree; 5406141cf33Sderaadt int max_code = desc->max_code; 5416141cf33Sderaadt const ct_data *stree = desc->stat_desc->static_tree; 5426141cf33Sderaadt const intf *extra = desc->stat_desc->extra_bits; 5436141cf33Sderaadt int base = desc->stat_desc->extra_base; 5446141cf33Sderaadt int max_length = desc->stat_desc->max_length; 5456141cf33Sderaadt int h; /* heap index */ 5466141cf33Sderaadt int n, m; /* iterate over the tree elements */ 5476141cf33Sderaadt int bits; /* bit length */ 5486141cf33Sderaadt int xbits; /* extra bits */ 5496141cf33Sderaadt ush f; /* frequency */ 5506141cf33Sderaadt int overflow = 0; /* number of elements with bit length too large */ 5516141cf33Sderaadt 5526141cf33Sderaadt for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; 5536141cf33Sderaadt 5546141cf33Sderaadt /* In a first pass, compute the optimal bit lengths (which may 5556141cf33Sderaadt * overflow in the case of the bit length tree). 5566141cf33Sderaadt */ 5576141cf33Sderaadt tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ 5586141cf33Sderaadt 5596141cf33Sderaadt for (h = s->heap_max + 1; h < HEAP_SIZE; h++) { 5606141cf33Sderaadt n = s->heap[h]; 5616141cf33Sderaadt bits = tree[tree[n].Dad].Len + 1; 5626141cf33Sderaadt if (bits > max_length) bits = max_length, overflow++; 5636141cf33Sderaadt tree[n].Len = (ush)bits; 5646141cf33Sderaadt /* We overwrite tree[n].Dad which is no longer needed */ 5656141cf33Sderaadt 5666141cf33Sderaadt if (n > max_code) continue; /* not a leaf node */ 5676141cf33Sderaadt 5686141cf33Sderaadt s->bl_count[bits]++; 5696141cf33Sderaadt xbits = 0; 5706141cf33Sderaadt if (n >= base) xbits = extra[n - base]; 5716141cf33Sderaadt f = tree[n].Freq; 57236f395ceStb s->opt_len += (ulg)f * (unsigned)(bits + xbits); 57336f395ceStb if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); 5746141cf33Sderaadt } 5756141cf33Sderaadt if (overflow == 0) return; 5766141cf33Sderaadt 57736f395ceStb Tracev((stderr,"\nbit length overflow\n")); 5786141cf33Sderaadt /* This happens for example on obj2 and pic of the Calgary corpus */ 5796141cf33Sderaadt 5806141cf33Sderaadt /* Find the first bit length which could increase: */ 5816141cf33Sderaadt do { 5826141cf33Sderaadt bits = max_length - 1; 5836141cf33Sderaadt while (s->bl_count[bits] == 0) bits--; 5846141cf33Sderaadt s->bl_count[bits]--; /* move one leaf down the tree */ 5856141cf33Sderaadt s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */ 5866141cf33Sderaadt s->bl_count[max_length]--; 5876141cf33Sderaadt /* The brother of the overflow item also moves one step up, 5886141cf33Sderaadt * but this does not affect bl_count[max_length] 5896141cf33Sderaadt */ 5906141cf33Sderaadt overflow -= 2; 5916141cf33Sderaadt } while (overflow > 0); 5926141cf33Sderaadt 5936141cf33Sderaadt /* Now recompute all bit lengths, scanning in increasing frequency. 5946141cf33Sderaadt * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all 5956141cf33Sderaadt * lengths instead of fixing only the wrong ones. This idea is taken 5966141cf33Sderaadt * from 'ar' written by Haruhiko Okumura.) 5976141cf33Sderaadt */ 5986141cf33Sderaadt for (bits = max_length; bits != 0; bits--) { 5996141cf33Sderaadt n = s->bl_count[bits]; 6006141cf33Sderaadt while (n != 0) { 6016141cf33Sderaadt m = s->heap[--h]; 6026141cf33Sderaadt if (m > max_code) continue; 6036141cf33Sderaadt if ((unsigned) tree[m].Len != (unsigned) bits) { 60436f395ceStb Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); 60536f395ceStb s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; 6066141cf33Sderaadt tree[m].Len = (ush)bits; 6076141cf33Sderaadt } 6086141cf33Sderaadt n--; 6096141cf33Sderaadt } 6106141cf33Sderaadt } 6116141cf33Sderaadt } 6126141cf33Sderaadt 613cfac609cStb #ifdef DUMP_BL_TREE 614cfac609cStb # include <stdio.h> 615cfac609cStb #endif 6166141cf33Sderaadt 6176141cf33Sderaadt /* =========================================================================== 6186141cf33Sderaadt * Construct one Huffman tree and assigns the code bit strings and lengths. 6196141cf33Sderaadt * Update the total bit length for the current block. 6206141cf33Sderaadt * IN assertion: the field freq is set for all tree elements. 6216141cf33Sderaadt * OUT assertions: the fields len and code are set to the optimal bit length 6226141cf33Sderaadt * and corresponding code. The length opt_len is updated; static_len is 6236141cf33Sderaadt * also updated if stree is not null. The field max_code is set. 6246141cf33Sderaadt */ 625cfac609cStb local void build_tree(deflate_state *s, tree_desc *desc) { 6266141cf33Sderaadt ct_data *tree = desc->dyn_tree; 6276141cf33Sderaadt const ct_data *stree = desc->stat_desc->static_tree; 6286141cf33Sderaadt int elems = desc->stat_desc->elems; 6296141cf33Sderaadt int n, m; /* iterate over heap elements */ 6306141cf33Sderaadt int max_code = -1; /* largest code with non zero frequency */ 6316141cf33Sderaadt int node; /* new node being created */ 6326141cf33Sderaadt 6336141cf33Sderaadt /* Construct the initial heap, with least frequent element in 6346141cf33Sderaadt * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1]. 6356141cf33Sderaadt * heap[0] is not used. 6366141cf33Sderaadt */ 6376141cf33Sderaadt s->heap_len = 0, s->heap_max = HEAP_SIZE; 6386141cf33Sderaadt 6396141cf33Sderaadt for (n = 0; n < elems; n++) { 6406141cf33Sderaadt if (tree[n].Freq != 0) { 6416141cf33Sderaadt s->heap[++(s->heap_len)] = max_code = n; 6426141cf33Sderaadt s->depth[n] = 0; 6436141cf33Sderaadt } else { 6446141cf33Sderaadt tree[n].Len = 0; 6456141cf33Sderaadt } 6466141cf33Sderaadt } 6476141cf33Sderaadt 6486141cf33Sderaadt /* The pkzip format requires that at least one distance code exists, 6496141cf33Sderaadt * and that at least one bit should be sent even if there is only one 6506141cf33Sderaadt * possible code. So to avoid special checks later on we force at least 6516141cf33Sderaadt * two codes of non zero frequency. 6526141cf33Sderaadt */ 6536141cf33Sderaadt while (s->heap_len < 2) { 6546141cf33Sderaadt node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); 6556141cf33Sderaadt tree[node].Freq = 1; 6566141cf33Sderaadt s->depth[node] = 0; 6576141cf33Sderaadt s->opt_len--; if (stree) s->static_len -= stree[node].Len; 6586141cf33Sderaadt /* node is 0 or 1 so it does not have extra bits */ 6596141cf33Sderaadt } 6606141cf33Sderaadt desc->max_code = max_code; 6616141cf33Sderaadt 6626141cf33Sderaadt /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree, 6636141cf33Sderaadt * establish sub-heaps of increasing lengths: 6646141cf33Sderaadt */ 6656141cf33Sderaadt for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); 6666141cf33Sderaadt 6676141cf33Sderaadt /* Construct the Huffman tree by repeatedly combining the least two 6686141cf33Sderaadt * frequent nodes. 6696141cf33Sderaadt */ 6706141cf33Sderaadt node = elems; /* next internal node of the tree */ 6716141cf33Sderaadt do { 6726141cf33Sderaadt pqremove(s, tree, n); /* n = node of least frequency */ 6736141cf33Sderaadt m = s->heap[SMALLEST]; /* m = node of next least frequency */ 6746141cf33Sderaadt 6756141cf33Sderaadt s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ 6766141cf33Sderaadt s->heap[--(s->heap_max)] = m; 6776141cf33Sderaadt 6786141cf33Sderaadt /* Create a new node father of n and m */ 6796141cf33Sderaadt tree[node].Freq = tree[n].Freq + tree[m].Freq; 6806141cf33Sderaadt s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? 6816141cf33Sderaadt s->depth[n] : s->depth[m]) + 1); 6826141cf33Sderaadt tree[n].Dad = tree[m].Dad = (ush)node; 6836141cf33Sderaadt #ifdef DUMP_BL_TREE 6846141cf33Sderaadt if (tree == s->bl_tree) { 6856141cf33Sderaadt fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", 6866141cf33Sderaadt node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); 6876141cf33Sderaadt } 6886141cf33Sderaadt #endif 6896141cf33Sderaadt /* and insert the new node in the heap */ 6906141cf33Sderaadt s->heap[SMALLEST] = node++; 6916141cf33Sderaadt pqdownheap(s, tree, SMALLEST); 6926141cf33Sderaadt 6936141cf33Sderaadt } while (s->heap_len >= 2); 6946141cf33Sderaadt 6956141cf33Sderaadt s->heap[--(s->heap_max)] = s->heap[SMALLEST]; 6966141cf33Sderaadt 6976141cf33Sderaadt /* At this point, the fields freq and dad are set. We can now 6986141cf33Sderaadt * generate the bit lengths. 6996141cf33Sderaadt */ 7006141cf33Sderaadt gen_bitlen(s, (tree_desc *)desc); 7016141cf33Sderaadt 7026141cf33Sderaadt /* The field len is now set, we can generate the bit codes */ 7036141cf33Sderaadt gen_codes ((ct_data *)tree, max_code, s->bl_count); 7046141cf33Sderaadt } 7056141cf33Sderaadt 7066141cf33Sderaadt /* =========================================================================== 7076141cf33Sderaadt * Scan a literal or distance tree to determine the frequencies of the codes 7086141cf33Sderaadt * in the bit length tree. 7096141cf33Sderaadt */ 710cfac609cStb local void scan_tree(deflate_state *s, ct_data *tree, int max_code) { 7116141cf33Sderaadt int n; /* iterates over all tree elements */ 7126141cf33Sderaadt int prevlen = -1; /* last emitted length */ 7136141cf33Sderaadt int curlen; /* length of current code */ 7146141cf33Sderaadt int nextlen = tree[0].Len; /* length of next code */ 7156141cf33Sderaadt int count = 0; /* repeat count of the current code */ 7166141cf33Sderaadt int max_count = 7; /* max repeat count */ 7176141cf33Sderaadt int min_count = 4; /* min repeat count */ 7186141cf33Sderaadt 7196141cf33Sderaadt if (nextlen == 0) max_count = 138, min_count = 3; 7206141cf33Sderaadt tree[max_code + 1].Len = (ush)0xffff; /* guard */ 7216141cf33Sderaadt 7226141cf33Sderaadt for (n = 0; n <= max_code; n++) { 7236141cf33Sderaadt curlen = nextlen; nextlen = tree[n + 1].Len; 7246141cf33Sderaadt if (++count < max_count && curlen == nextlen) { 7256141cf33Sderaadt continue; 7266141cf33Sderaadt } else if (count < min_count) { 72776eaddfcStb s->bl_tree[curlen].Freq += (ush)count; 7286141cf33Sderaadt } else if (curlen != 0) { 7296141cf33Sderaadt if (curlen != prevlen) s->bl_tree[curlen].Freq++; 7306141cf33Sderaadt s->bl_tree[REP_3_6].Freq++; 7316141cf33Sderaadt } else if (count <= 10) { 7326141cf33Sderaadt s->bl_tree[REPZ_3_10].Freq++; 7336141cf33Sderaadt } else { 7346141cf33Sderaadt s->bl_tree[REPZ_11_138].Freq++; 7356141cf33Sderaadt } 7366141cf33Sderaadt count = 0; prevlen = curlen; 7376141cf33Sderaadt if (nextlen == 0) { 7386141cf33Sderaadt max_count = 138, min_count = 3; 7396141cf33Sderaadt } else if (curlen == nextlen) { 7406141cf33Sderaadt max_count = 6, min_count = 3; 7416141cf33Sderaadt } else { 7426141cf33Sderaadt max_count = 7, min_count = 4; 7436141cf33Sderaadt } 7446141cf33Sderaadt } 7456141cf33Sderaadt } 7466141cf33Sderaadt 7476141cf33Sderaadt /* =========================================================================== 7486141cf33Sderaadt * Send a literal or distance tree in compressed form, using the codes in 7496141cf33Sderaadt * bl_tree. 7506141cf33Sderaadt */ 751cfac609cStb local void send_tree(deflate_state *s, ct_data *tree, int max_code) { 7526141cf33Sderaadt int n; /* iterates over all tree elements */ 7536141cf33Sderaadt int prevlen = -1; /* last emitted length */ 7546141cf33Sderaadt int curlen; /* length of current code */ 7556141cf33Sderaadt int nextlen = tree[0].Len; /* length of next code */ 7566141cf33Sderaadt int count = 0; /* repeat count of the current code */ 7576141cf33Sderaadt int max_count = 7; /* max repeat count */ 7586141cf33Sderaadt int min_count = 4; /* min repeat count */ 7596141cf33Sderaadt 7606141cf33Sderaadt /* tree[max_code + 1].Len = -1; */ /* guard already set */ 7616141cf33Sderaadt if (nextlen == 0) max_count = 138, min_count = 3; 7626141cf33Sderaadt 7636141cf33Sderaadt for (n = 0; n <= max_code; n++) { 7646141cf33Sderaadt curlen = nextlen; nextlen = tree[n + 1].Len; 7656141cf33Sderaadt if (++count < max_count && curlen == nextlen) { 7666141cf33Sderaadt continue; 7676141cf33Sderaadt } else if (count < min_count) { 7686141cf33Sderaadt do { send_code(s, curlen, s->bl_tree); } while (--count != 0); 7696141cf33Sderaadt 7706141cf33Sderaadt } else if (curlen != 0) { 7716141cf33Sderaadt if (curlen != prevlen) { 7726141cf33Sderaadt send_code(s, curlen, s->bl_tree); count--; 7736141cf33Sderaadt } 7746141cf33Sderaadt Assert(count >= 3 && count <= 6, " 3_6?"); 7756141cf33Sderaadt send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2); 7766141cf33Sderaadt 7776141cf33Sderaadt } else if (count <= 10) { 7786141cf33Sderaadt send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3); 7796141cf33Sderaadt 7806141cf33Sderaadt } else { 7816141cf33Sderaadt send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7); 7826141cf33Sderaadt } 7836141cf33Sderaadt count = 0; prevlen = curlen; 7846141cf33Sderaadt if (nextlen == 0) { 7856141cf33Sderaadt max_count = 138, min_count = 3; 7866141cf33Sderaadt } else if (curlen == nextlen) { 7876141cf33Sderaadt max_count = 6, min_count = 3; 7886141cf33Sderaadt } else { 7896141cf33Sderaadt max_count = 7, min_count = 4; 7906141cf33Sderaadt } 7916141cf33Sderaadt } 7926141cf33Sderaadt } 7936141cf33Sderaadt 7946141cf33Sderaadt /* =========================================================================== 7956141cf33Sderaadt * Construct the Huffman tree for the bit lengths and return the index in 7966141cf33Sderaadt * bl_order of the last bit length code to send. 7976141cf33Sderaadt */ 798cfac609cStb local int build_bl_tree(deflate_state *s) { 7996141cf33Sderaadt int max_blindex; /* index of last bit length code of non zero freq */ 8006141cf33Sderaadt 8016141cf33Sderaadt /* Determine the bit length frequencies for literal and distance trees */ 8026141cf33Sderaadt scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); 8036141cf33Sderaadt scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); 8046141cf33Sderaadt 8056141cf33Sderaadt /* Build the bit length tree: */ 8066141cf33Sderaadt build_tree(s, (tree_desc *)(&(s->bl_desc))); 807ddf65acdStb /* opt_len now includes the length of the tree representations, except the 808ddf65acdStb * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts. 8096141cf33Sderaadt */ 8106141cf33Sderaadt 8116141cf33Sderaadt /* Determine the number of bit length codes to send. The pkzip format 8126141cf33Sderaadt * requires that at least 4 bit length codes be sent. (appnote.txt says 8136141cf33Sderaadt * 3 but the actual value used is 4.) 8146141cf33Sderaadt */ 8156141cf33Sderaadt for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { 8166141cf33Sderaadt if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; 8176141cf33Sderaadt } 8186141cf33Sderaadt /* Update opt_len to include the bit length tree and counts */ 81936f395ceStb s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4; 8206141cf33Sderaadt Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", 8216141cf33Sderaadt s->opt_len, s->static_len)); 8226141cf33Sderaadt 8236141cf33Sderaadt return max_blindex; 8246141cf33Sderaadt } 8256141cf33Sderaadt 8266141cf33Sderaadt /* =========================================================================== 8276141cf33Sderaadt * Send the header for a block using dynamic Huffman trees: the counts, the 8286141cf33Sderaadt * lengths of the bit length codes, the literal tree and the distance tree. 8296141cf33Sderaadt * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. 8306141cf33Sderaadt */ 831cfac609cStb local void send_all_trees(deflate_state *s, int lcodes, int dcodes, 832cfac609cStb int blcodes) { 8336141cf33Sderaadt int rank; /* index in bl_order */ 8346141cf33Sderaadt 8356141cf33Sderaadt Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); 8366141cf33Sderaadt Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, 8376141cf33Sderaadt "too many codes"); 8386141cf33Sderaadt Tracev((stderr, "\nbl counts: ")); 8396141cf33Sderaadt send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ 8406141cf33Sderaadt send_bits(s, dcodes - 1, 5); 8416141cf33Sderaadt send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ 8426141cf33Sderaadt for (rank = 0; rank < blcodes; rank++) { 8436141cf33Sderaadt Tracev((stderr, "\nbl code %2d ", bl_order[rank])); 8446141cf33Sderaadt send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); 8456141cf33Sderaadt } 8466141cf33Sderaadt Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); 8476141cf33Sderaadt 8486141cf33Sderaadt send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1); /* literal tree */ 8496141cf33Sderaadt Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); 8506141cf33Sderaadt 8516141cf33Sderaadt send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1); /* distance tree */ 8526141cf33Sderaadt Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); 8536141cf33Sderaadt } 8546141cf33Sderaadt 8556141cf33Sderaadt /* =========================================================================== 8566141cf33Sderaadt * Send a stored block 8576141cf33Sderaadt */ 858cfac609cStb void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, 859cfac609cStb ulg stored_len, int last) { 86036f395ceStb send_bits(s, (STORED_BLOCK<<1) + last, 3); /* send block type */ 86136f395ceStb bi_windup(s); /* align on byte boundary */ 86236f395ceStb put_short(s, (ush)stored_len); 86336f395ceStb put_short(s, (ush)~stored_len); 864a6530658Stb if (stored_len) 86536f395ceStb zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); 86636f395ceStb s->pending += stored_len; 86736f395ceStb #ifdef ZLIB_DEBUG 8686141cf33Sderaadt s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; 8696141cf33Sderaadt s->compressed_len += (stored_len + 4) << 3; 87036f395ceStb s->bits_sent += 2*16; 87136f395ceStb s->bits_sent += stored_len << 3; 8726141cf33Sderaadt #endif 87336f395ceStb } 87436f395ceStb 87536f395ceStb /* =========================================================================== 87636f395ceStb * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) 87736f395ceStb */ 878cfac609cStb void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) { 87936f395ceStb bi_flush(s); 8806141cf33Sderaadt } 8816141cf33Sderaadt 8826141cf33Sderaadt /* =========================================================================== 8836141cf33Sderaadt * Send one empty static block to give enough lookahead for inflate. 8846141cf33Sderaadt * This takes 10 bits, of which 7 may remain in the bit buffer. 8856141cf33Sderaadt */ 886cfac609cStb void ZLIB_INTERNAL _tr_align(deflate_state *s) { 8876141cf33Sderaadt send_bits(s, STATIC_TREES<<1, 3); 8886141cf33Sderaadt send_code(s, END_BLOCK, static_ltree); 88936f395ceStb #ifdef ZLIB_DEBUG 8906141cf33Sderaadt s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ 8916141cf33Sderaadt #endif 8926141cf33Sderaadt bi_flush(s); 8936141cf33Sderaadt } 8946141cf33Sderaadt 8956141cf33Sderaadt /* =========================================================================== 896cfac609cStb * Send the block data compressed using the given Huffman trees 897cfac609cStb */ 898cfac609cStb local void compress_block(deflate_state *s, const ct_data *ltree, 899cfac609cStb const ct_data *dtree) { 900cfac609cStb unsigned dist; /* distance of matched string */ 901cfac609cStb int lc; /* match length or unmatched char (if dist == 0) */ 90285d95931Stb unsigned sx = 0; /* running index in symbol buffers */ 903cfac609cStb unsigned code; /* the code to send */ 904cfac609cStb int extra; /* number of extra bits to send */ 905cfac609cStb 906cfac609cStb if (s->sym_next != 0) do { 90785d95931Stb #ifdef LIT_MEM 90885d95931Stb dist = s->d_buf[sx]; 90985d95931Stb lc = s->l_buf[sx++]; 91085d95931Stb #else 911cfac609cStb dist = s->sym_buf[sx++] & 0xff; 912cfac609cStb dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; 913cfac609cStb lc = s->sym_buf[sx++]; 91485d95931Stb #endif 915cfac609cStb if (dist == 0) { 916cfac609cStb send_code(s, lc, ltree); /* send a literal byte */ 917cfac609cStb Tracecv(isgraph(lc), (stderr," '%c' ", lc)); 918cfac609cStb } else { 919cfac609cStb /* Here, lc is the match length - MIN_MATCH */ 920cfac609cStb code = _length_code[lc]; 921cfac609cStb send_code(s, code + LITERALS + 1, ltree); /* send length code */ 922cfac609cStb extra = extra_lbits[code]; 923cfac609cStb if (extra != 0) { 924cfac609cStb lc -= base_length[code]; 925cfac609cStb send_bits(s, lc, extra); /* send the extra length bits */ 926cfac609cStb } 927cfac609cStb dist--; /* dist is now the match distance - 1 */ 928cfac609cStb code = d_code(dist); 929cfac609cStb Assert (code < D_CODES, "bad d_code"); 930cfac609cStb 931cfac609cStb send_code(s, code, dtree); /* send the distance code */ 932cfac609cStb extra = extra_dbits[code]; 933cfac609cStb if (extra != 0) { 934cfac609cStb dist -= (unsigned)base_dist[code]; 935cfac609cStb send_bits(s, dist, extra); /* send the extra distance bits */ 936cfac609cStb } 937cfac609cStb } /* literal or match pair ? */ 938cfac609cStb 93985d95931Stb /* Check for no overlay of pending_buf on needed symbols */ 94085d95931Stb #ifdef LIT_MEM 941555b046eStb Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow"); 94285d95931Stb #else 943cfac609cStb Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); 94485d95931Stb #endif 945cfac609cStb 946cfac609cStb } while (sx < s->sym_next); 947cfac609cStb 948cfac609cStb send_code(s, END_BLOCK, ltree); 949cfac609cStb } 950cfac609cStb 951cfac609cStb /* =========================================================================== 952cfac609cStb * Check if the data type is TEXT or BINARY, using the following algorithm: 953cfac609cStb * - TEXT if the two conditions below are satisfied: 954cfac609cStb * a) There are no non-portable control characters belonging to the 955cfac609cStb * "block list" (0..6, 14..25, 28..31). 956cfac609cStb * b) There is at least one printable character belonging to the 957cfac609cStb * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). 958cfac609cStb * - BINARY otherwise. 959cfac609cStb * - The following partially-portable control characters form a 960cfac609cStb * "gray list" that is ignored in this detection algorithm: 961cfac609cStb * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). 962cfac609cStb * IN assertion: the fields Freq of dyn_ltree are set. 963cfac609cStb */ 964cfac609cStb local int detect_data_type(deflate_state *s) { 965cfac609cStb /* block_mask is the bit mask of block-listed bytes 966cfac609cStb * set bits 0..6, 14..25, and 28..31 967cfac609cStb * 0xf3ffc07f = binary 11110011111111111100000001111111 968cfac609cStb */ 969cfac609cStb unsigned long block_mask = 0xf3ffc07fUL; 970cfac609cStb int n; 971cfac609cStb 972cfac609cStb /* Check for non-textual ("block-listed") bytes. */ 973cfac609cStb for (n = 0; n <= 31; n++, block_mask >>= 1) 974cfac609cStb if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0)) 975cfac609cStb return Z_BINARY; 976cfac609cStb 977cfac609cStb /* Check for textual ("allow-listed") bytes. */ 978cfac609cStb if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 979cfac609cStb || s->dyn_ltree[13].Freq != 0) 980cfac609cStb return Z_TEXT; 981cfac609cStb for (n = 32; n < LITERALS; n++) 982cfac609cStb if (s->dyn_ltree[n].Freq != 0) 983cfac609cStb return Z_TEXT; 984cfac609cStb 985cfac609cStb /* There are no "block-listed" or "allow-listed" bytes: 986cfac609cStb * this stream either is empty or has tolerated ("gray-listed") bytes only. 987cfac609cStb */ 988cfac609cStb return Z_BINARY; 989cfac609cStb } 990cfac609cStb 991cfac609cStb /* =========================================================================== 9926141cf33Sderaadt * Determine the best encoding for the current block: dynamic trees, static 99336f395ceStb * trees or store, and write out the encoded block. 9946141cf33Sderaadt */ 995cfac609cStb void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf, 996cfac609cStb ulg stored_len, int last) { 9976141cf33Sderaadt ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ 9986141cf33Sderaadt int max_blindex = 0; /* index of last bit length code of non zero freq */ 9996141cf33Sderaadt 10006141cf33Sderaadt /* Build the Huffman trees unless a stored block is forced */ 10016141cf33Sderaadt if (s->level > 0) { 10026141cf33Sderaadt 10036141cf33Sderaadt /* Check if the file is binary or text */ 100436f395ceStb if (s->strm->data_type == Z_UNKNOWN) 100536f395ceStb s->strm->data_type = detect_data_type(s); 10066141cf33Sderaadt 10076141cf33Sderaadt /* Construct the literal and distance trees */ 10086141cf33Sderaadt build_tree(s, (tree_desc *)(&(s->l_desc))); 10096141cf33Sderaadt Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, 10106141cf33Sderaadt s->static_len)); 10116141cf33Sderaadt 10126141cf33Sderaadt build_tree(s, (tree_desc *)(&(s->d_desc))); 10136141cf33Sderaadt Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, 10146141cf33Sderaadt s->static_len)); 10156141cf33Sderaadt /* At this point, opt_len and static_len are the total bit lengths of 10166141cf33Sderaadt * the compressed block data, excluding the tree representations. 10176141cf33Sderaadt */ 10186141cf33Sderaadt 10196141cf33Sderaadt /* Build the bit length tree for the above two trees, and get the index 10206141cf33Sderaadt * in bl_order of the last bit length code to send. 10216141cf33Sderaadt */ 10226141cf33Sderaadt max_blindex = build_bl_tree(s); 10236141cf33Sderaadt 10246141cf33Sderaadt /* Determine the best encoding. Compute the block lengths in bytes. */ 10256141cf33Sderaadt opt_lenb = (s->opt_len + 3 + 7) >> 3; 10266141cf33Sderaadt static_lenb = (s->static_len + 3 + 7) >> 3; 10276141cf33Sderaadt 10286141cf33Sderaadt Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", 10296141cf33Sderaadt opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, 103056e03632Stb s->sym_next / 3)); 10316141cf33Sderaadt 1032ddf65acdStb #ifndef FORCE_STATIC 1033ddf65acdStb if (static_lenb <= opt_lenb || s->strategy == Z_FIXED) 1034ddf65acdStb #endif 1035ddf65acdStb opt_lenb = static_lenb; 10366141cf33Sderaadt 10376141cf33Sderaadt } else { 103836f395ceStb Assert(buf != (char*)0, "lost buf"); 10396141cf33Sderaadt opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ 10406141cf33Sderaadt } 10416141cf33Sderaadt 10426141cf33Sderaadt #ifdef FORCE_STORED 104336f395ceStb if (buf != (char*)0) { /* force stored block */ 10446141cf33Sderaadt #else 104536f395ceStb if (stored_len + 4 <= opt_lenb && buf != (char*)0) { 10466141cf33Sderaadt /* 4: two words for the lengths */ 10476141cf33Sderaadt #endif 10486141cf33Sderaadt /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. 10496141cf33Sderaadt * Otherwise we can't have processed more than WSIZE input bytes since 10506141cf33Sderaadt * the last block flush, because compression would have been 10516141cf33Sderaadt * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to 10526141cf33Sderaadt * transform a block into a stored block. 10536141cf33Sderaadt */ 105436f395ceStb _tr_stored_block(s, buf, stored_len, last); 10556141cf33Sderaadt 1056ddf65acdStb } else if (static_lenb == opt_lenb) { 105736f395ceStb send_bits(s, (STATIC_TREES<<1) + last, 3); 105836f395ceStb compress_block(s, (const ct_data *)static_ltree, 105936f395ceStb (const ct_data *)static_dtree); 106036f395ceStb #ifdef ZLIB_DEBUG 10616141cf33Sderaadt s->compressed_len += 3 + s->static_len; 10626141cf33Sderaadt #endif 10636141cf33Sderaadt } else { 106436f395ceStb send_bits(s, (DYN_TREES<<1) + last, 3); 10656141cf33Sderaadt send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1, 10666141cf33Sderaadt max_blindex + 1); 106736f395ceStb compress_block(s, (const ct_data *)s->dyn_ltree, 106836f395ceStb (const ct_data *)s->dyn_dtree); 106936f395ceStb #ifdef ZLIB_DEBUG 10706141cf33Sderaadt s->compressed_len += 3 + s->opt_len; 10716141cf33Sderaadt #endif 10726141cf33Sderaadt } 10736141cf33Sderaadt Assert (s->compressed_len == s->bits_sent, "bad compressed size"); 10746141cf33Sderaadt /* The above check is made mod 2^32, for files larger than 512 MB 10756141cf33Sderaadt * and uLong implemented on 32 bits. 10766141cf33Sderaadt */ 10776141cf33Sderaadt init_block(s); 10786141cf33Sderaadt 107936f395ceStb if (last) { 10806141cf33Sderaadt bi_windup(s); 108136f395ceStb #ifdef ZLIB_DEBUG 10826141cf33Sderaadt s->compressed_len += 7; /* align on byte boundary */ 10836141cf33Sderaadt #endif 10846141cf33Sderaadt } 10856141cf33Sderaadt Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3, 108636f395ceStb s->compressed_len - 7*last)); 10876141cf33Sderaadt } 10886141cf33Sderaadt 10896141cf33Sderaadt /* =========================================================================== 10906141cf33Sderaadt * Save the match info and tally the frequency counts. Return true if 10916141cf33Sderaadt * the current block must be flushed. 10926141cf33Sderaadt */ 1093cfac609cStb int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) { 109485d95931Stb #ifdef LIT_MEM 109585d95931Stb s->d_buf[s->sym_next] = (ush)dist; 109685d95931Stb s->l_buf[s->sym_next++] = (uch)lc; 109785d95931Stb #else 1098ddf65acdStb s->sym_buf[s->sym_next++] = (uch)dist; 1099ddf65acdStb s->sym_buf[s->sym_next++] = (uch)(dist >> 8); 1100ddf65acdStb s->sym_buf[s->sym_next++] = (uch)lc; 110185d95931Stb #endif 11026141cf33Sderaadt if (dist == 0) { 11036141cf33Sderaadt /* lc is the unmatched char */ 11046141cf33Sderaadt s->dyn_ltree[lc].Freq++; 11056141cf33Sderaadt } else { 11066141cf33Sderaadt s->matches++; 11076141cf33Sderaadt /* Here, lc is the match length - MIN_MATCH */ 11086141cf33Sderaadt dist--; /* dist = match distance - 1 */ 11096141cf33Sderaadt Assert((ush)dist < (ush)MAX_DIST(s) && 11106141cf33Sderaadt (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && 11116141cf33Sderaadt (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); 11126141cf33Sderaadt 11136141cf33Sderaadt s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++; 11146141cf33Sderaadt s->dyn_dtree[d_code(dist)].Freq++; 11156141cf33Sderaadt } 111656e03632Stb return (s->sym_next == s->sym_end); 11176141cf33Sderaadt } 1118