annotate src/zlib-1.2.8/trees.c @ 169:223a55898ab9 tip default

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