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