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