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