annotate src/zlib-1.2.7/trees.c @ 44:9894b839b0cb

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