security/nss/lib/zlib/trees.c

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

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

mercurial