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