- Main Page
- Namespaces
- Classes
- Files
- Directories

- File List
- File Members

# trees.c

    00001 /* trees.c -- output deflated data using Huffman coding
    00002  * Copyright (C) 1995-2002 Jean-loup Gailly
    00003  * For conditions of distribution and use, see copyright notice in zlib.h
    00004  */
    00005
    00006 /*
    00007  *  ALGORITHM
    00008  *
    00009  *      The "deflation" process uses several Huffman trees. The more
    00010  *      common source values are represented by shorter bit sequences.
    00011  *
    00012  *      Each code tree is stored in a compressed form which is itself
    00013  * a Huffman encoding of the lengths of all the code strings (in
    00014  * ascending order by source values).  The actual code strings are
    00015  * reconstructed from the lengths in the inflate process, as described
    00016  * in the deflate specification.
    00017  *
    00018  *  REFERENCES
    00019  *
    00020  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
    00021  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
    00022  *
    00023  *      Storer, James A.
    00024  *          Data Compression:  Methods and Theory, pp. 49-50.
    00025  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
    00026  *
    00027  *      Sedgewick, R.
    00028  *          Algorithms, p290.
    00029  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
    00030  */
    00031
    00032 /* @(#) $Id: trees.c,v 1.1 2003/11/09 01:37:56 gabest Exp $ */
    00033
    00034 /* #define GEN_TREES_H */
    00035
    00036 #include "deflate.h"
    00037
    00038 #ifdef DEBUG
    00039 #  include <ctype.h>
    00040 #endif
    00041
    00042 /* ===========================================================================
    00043  * Constants
    00044  */
    00045
    00046 #define MAX_BL_BITS 7
    00047 /* Bit length codes must not exceed MAX_BL_BITS bits */
    00048
    00049 #define END_BLOCK 256
    00050 /* end of block literal code */
    00051
    00052 #define REP_3_6      16
    00053 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
    00054
    00055 #define REPZ_3_10    17
    00056 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
    00057
    00058 #define REPZ_11_138  18
    00059 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
    00060
    00061 local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
    00062    = {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};
    00063
    00064 local const int extra_dbits[D_CODES] /* extra bits for each distance code */
    00065    = {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};
    00066
    00067 local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
    00068    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
    00069
    00070 local const uch bl_order[BL_CODES]
    00071    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
    00072 /* The lengths of the bit length codes are sent in order of decreasing
    00073  * probability, to avoid transmitting the lengths for unused bit length codes.
    00074  */
    00075
    00076 #define Buf_size (8 * 2*sizeof(char))
    00077 /* Number of bits used within bi_buf. (bi_buf might be implemented on
    00078  * more than 16 bits on some systems.)
    00079  */
    00080
    00081 /* ===========================================================================
    00082  * Local data. These are initialized only once.
    00083  */
    00084
    00085 #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
    00086
    00087 #if defined(GEN_TREES_H) || !defined(STDC)
    00088 /* non ANSI compilers may not accept trees.h */
    00089
    00090 local ct_data static_ltree[L_CODES+2];
    00091 /* The static literal tree. Since the bit lengths are imposed, there is no
    00092  * need for the L_CODES extra codes used during heap construction. However
    00093  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
    00094  * below).
    00095  */
    00096
    00097 local ct_data static_dtree[D_CODES];
    00098 /* The static distance tree. (Actually a trivial tree since all codes use
    00099  * 5 bits.)
    00100  */
    00101
    00102 uch _dist_code[DIST_CODE_LEN];
    00103 /* Distance codes. The first 256 values correspond to the distances
    00104  * 3 .. 258, the last 256 values correspond to the top 8 bits of
    00105  * the 15 bit distances.
    00106  */
    00107
    00108 uch _length_code[MAX_MATCH-MIN_MATCH+1];
    00109 /* length code for each normalized match length (0 == MIN_MATCH) */
    00110
    00111 local int base_length[LENGTH_CODES];
    00112 /* First normalized length for each code (0 = MIN_MATCH) */
    00113
    00114 local int base_dist[D_CODES];
    00115 /* First normalized distance for each code (0 = distance of 1) */
    00116
    00117 #else
    00118 #  include "trees.h"
    00119 #endif /* GEN_TREES_H */
    00120
    00121 struct static_tree_desc_s {
    00122     const ct_data *static_tree;  /* static tree or NULL */
    00123     const intf *extra_bits;      /* extra bits for each code or NULL */
    00124     int     extra_base;          /* base index for extra_bits */
    00125     int     elems;               /* max number of elements in the tree */
    00126     int     max_length;          /* max bit length for the codes */
    00127 };
    00128
    00129 local static_tree_desc  static_l_desc =
    00130 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
    00131
    00132 local static_tree_desc  static_d_desc =
    00133 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
    00134
    00135 local static_tree_desc  static_bl_desc =
    00136 {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
    00137
    00138 /* ===========================================================================
    00139  * Local (static) routines in this file.
    00140  */
    00141
    00142 local void tr_static_init OF((void));
    00143 local void init_block     OF((deflate_state *s));
    00144 local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
    00145 local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
    00146 local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
    00147 local void build_tree     OF((deflate_state *s, tree_desc *desc));
    00148 local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
    00149 local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
    00150 local int  build_bl_tree  OF((deflate_state *s));
    00151 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
    00152                               int blcodes));
    00153 local void compress_block OF((deflate_state *s, ct_data *ltree,
    00154                               ct_data *dtree));
    00155 local void set_data_type  OF((deflate_state *s));
    00156 local unsigned bi_reverse OF((unsigned value, int length));
    00157 local void bi_windup      OF((deflate_state *s));
    00158 local void bi_flush       OF((deflate_state *s));
    00159 local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
    00160                               int header));
    00161
    00162 #ifdef GEN_TREES_H
    00163 local void gen_trees_header OF((void));
    00164 #endif
    00165
    00166 #ifndef DEBUG
    00167 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
    00168    /* Send a code of the given tree. c and tree must not have side effects */
    00169
    00170 #else /* DEBUG */
    00171 #  define send_code(s, c, tree) \
    00172      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
    00173        send_bits(s, tree[c].Code, tree[c].Len); }
    00174 #endif
    00175
    00176 /* ===========================================================================
    00177  * Output a short LSB first on the stream.
    00178  * IN assertion: there is enough room in pendingBuf.
    00179  */
    00180 #define put_short(s, w) { \
    00181     put_byte(s, (uch)((w) & 0xff)); \
    00182     put_byte(s, (uch)((ush)(w) >> 8)); \
    00183 }
    00184
    00185 /* ===========================================================================
    00186  * Send a value on a given number of bits.
    00187  * IN assertion: length <= 16 and value fits in length bits.
    00188  */
    00189 #ifdef DEBUG
    00190 local void send_bits      OF((deflate_state *s, int value, int length));
    00191
    00192 local void send_bits(s, value, length)
    00193     deflate_state *s;
    00194     int value;  /* value to send */
    00195     int length; /* number of bits */
    00196 {
    00197     Tracevv((stderr," l %2d v %4x ", length, value));
    00198     Assert(length > 0 && length <= 15, "invalid length");
    00199     s->bits_sent += (ulg)length;
    00200
    00201     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
    00202      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
    00203      * unused bits in value.
    00204      */
    00205     if (s->bi_valid > (int)Buf_size - length) {
    00206         s->bi_buf |= (value << s->bi_valid);
    00207         put_short(s, s->bi_buf);
    00208         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
    00209         s->bi_valid += length - Buf_size;
    00210     } else {
    00211         s->bi_buf |= value << s->bi_valid;
    00212         s->bi_valid += length;
    00213     }
    00214 }
    00215 #else /* !DEBUG */
    00216
    00217 #define send_bits(s, value, length) \
    00218 { int len = length;\
    00219   if (s->bi_valid > (int)Buf_size - len) {\
    00220     int val = value;\
    00221     s->bi_buf |= (val << s->bi_valid);\
    00222     put_short(s, s->bi_buf);\
    00223     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
    00224     s->bi_valid += len - Buf_size;\
    00225   } else {\
    00226     s->bi_buf |= (value) << s->bi_valid;\
    00227     s->bi_valid += len;\
    00228   }\
    00229 }
    00230 #endif /* DEBUG */
    00231
    00232
    00233 #define MAX(a,b) (a >= b ? a : b)
    00234 /* the arguments must not have side effects */
    00235
    00236 /* ===========================================================================
    00237  * Initialize the various 'constant' tables.
    00238  */
    00239 local void tr_static_init()
    00240 {
    00241 #if defined(GEN_TREES_H) || !defined(STDC)
    00242     static int static_init_done = 0;
    00243     int n;        /* iterates over tree elements */
    00244     int bits;     /* bit counter */
    00245     int length;   /* length value */
    00246     int code;     /* code value */
    00247     int dist;     /* distance index */
    00248     ush bl_count[MAX_BITS+1];
    00249     /* number of codes at each bit length for an optimal tree */
    00250
    00251     if (static_init_done) return;
    00252
    00253     /* For some embedded targets, global variables are not initialized: */
    00254     static_l_desc.static_tree = static_ltree;
    00255     static_l_desc.extra_bits = extra_lbits;
    00256     static_d_desc.static_tree = static_dtree;
    00257     static_d_desc.extra_bits = extra_dbits;
    00258     static_bl_desc.extra_bits = extra_blbits;
    00259
    00260     /* Initialize the mapping length (0..255) -> length code (0..28) */
    00261     length = 0;
    00262     for (code = 0; code < LENGTH_CODES-1; code++) {
    00263         base_length[code] = length;
    00264         for (n = 0; n < (1<<extra_lbits[code]); n++) {
    00265             _length_code[length++] = (uch)code;
    00266         }
    00267     }
    00268     Assert (length == 256, "tr_static_init: length != 256");
    00269     /* Note that the length 255 (match length 258) can be represented
    00270      * in two different ways: code 284 + 5 bits or code 285, so we
    00271      * overwrite length_code[255] to use the best encoding:
    00272      */
    00273     _length_code[length-1] = (uch)code;
    00274
    00275     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
    00276     dist = 0;
    00277     for (code = 0 ; code < 16; code++) {
    00278         base_dist[code] = dist;
    00279         for (n = 0; n < (1<<extra_dbits[code]); n++) {
    00280             _dist_code[dist++] = (uch)code;
    00281         }
    00282     }
    00283     Assert (dist == 256, "tr_static_init: dist != 256");
    00284     dist >>= 7; /* from now on, all distances are divided by 128 */
    00285     for ( ; code < D_CODES; code++) {
    00286         base_dist[code] = dist << 7;
    00287         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
    00288             _dist_code[256 + dist++] = (uch)code;
    00289         }
    00290     }
    00291     Assert (dist == 256, "tr_static_init: 256+dist != 512");
    00292
    00293     /* Construct the codes of the static literal tree */
    00294     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
    00295     n = 0;
    00296     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
    00297     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
    00298     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
    00299     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
    00300     /* Codes 286 and 287 do not exist, but we must include them in the
    00301      * tree construction to get a canonical Huffman tree (longest code
    00302      * all ones)
    00303      */
    00304     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
    00305
    00306     /* The static distance tree is trivial: */
    00307     for (n = 0; n < D_CODES; n++) {
    00308         static_dtree[n].Len = 5;
    00309         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
    00310     }
    00311     static_init_done = 1;
    00312
    00313 #  ifdef GEN_TREES_H
    00314     gen_trees_header();
    00315 #  endif
    00316 #endif /* defined(GEN_TREES_H) || !defined(STDC) */
    00317 }
    00318
    00319 /* ===========================================================================
    00320  * Genererate the file trees.h describing the static trees.
    00321  */
    00322 #ifdef GEN_TREES_H
    00323 #  ifndef DEBUG
    00324 #    include <stdio.h>
    00325 #  endif
    00326
    00327 #  define SEPARATOR(i, last, width) \
    00328       ((i) == (last)? "\n};\n\n" :    \
    00329        ((i) % (width) == (width)-1 ? ",\n" : ", "))
    00330
    00331 void gen_trees_header()
    00332 {
    00333     FILE *header = fopen("trees.h", "w");
    00334     int i;
    00335
    00336     Assert (header != NULL, "Can't open trees.h");
    00337     fprintf(header,
    00338             "/* header created automatically with -DGEN_TREES_H */\n\n");
    00339
    00340     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
    00341     for (i = 0; i < L_CODES+2; i++) {
    00342         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
    00343                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
    00344     }
    00345
    00346     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
    00347     for (i = 0; i < D_CODES; i++) {
    00348         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
    00349                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
    00350     }
    00351
    00352     fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
    00353     for (i = 0; i < DIST_CODE_LEN; i++) {
    00354         fprintf(header, "%2u%s", _dist_code[i],
    00355                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
    00356     }
    00357
    00358     fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
    00359     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
    00360         fprintf(header, "%2u%s", _length_code[i],
    00361                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
    00362     }
    00363
    00364     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
    00365     for (i = 0; i < LENGTH_CODES; i++) {
    00366         fprintf(header, "%1u%s", base_length[i],
    00367                 SEPARATOR(i, LENGTH_CODES-1, 20));
    00368     }
    00369
    00370     fprintf(header, "local const int base_dist[D_CODES] = {\n");
    00371     for (i = 0; i < D_CODES; i++) {
    00372         fprintf(header, "%5u%s", base_dist[i],
    00373                 SEPARATOR(i, D_CODES-1, 10));
    00374     }
    00375
    00376     fclose(header);
    00377 }
    00378 #endif /* GEN_TREES_H */
    00379
    00380 /* ===========================================================================
    00381  * Initialize the tree data structures for a new zlib stream.
    00382  */
    00383 void _tr_init(s)
    00384     deflate_state *s;
    00385 {
    00386     tr_static_init();
    00387
    00388     s->l_desc.dyn_tree = s->dyn_ltree;
    00389     s->l_desc.stat_desc = &static_l_desc;
    00390
    00391     s->d_desc.dyn_tree = s->dyn_dtree;
    00392     s->d_desc.stat_desc = &static_d_desc;
    00393
    00394     s->bl_desc.dyn_tree = s->bl_tree;
    00395     s->bl_desc.stat_desc = &static_bl_desc;
    00396
    00397     s->bi_buf = 0;
    00398     s->bi_valid = 0;
    00399     s->last_eob_len = 8; /* enough lookahead for inflate */
    00400 #ifdef DEBUG
    00401     s->compressed_len = 0L;
    00402     s->bits_sent = 0L;
    00403 #endif
    00404
    00405     /* Initialize the first block of the first file: */
    00406     init_block(s);
    00407 }
    00408
    00409 /* ===========================================================================
    00410  * Initialize a new block.
    00411  */
    00412 local void init_block(s)
    00413     deflate_state *s;
    00414 {
    00415     int n; /* iterates over tree elements */
    00416
    00417     /* Initialize the trees. */
    00418     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
    00419     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
    00420     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
    00421
    00422     s->dyn_ltree[END_BLOCK].Freq = 1;
    00423     s->opt_len = s->static_len = 0L;
    00424     s->last_lit = s->matches = 0;
    00425 }
    00426
    00427 #define SMALLEST 1
    00428 /* Index within the heap array of least frequent node in the Huffman tree */
    00429
    00430
    00431 /* ===========================================================================
    00432  * Remove the smallest element from the heap and recreate the heap with
    00433  * one less element. Updates heap and heap_len.
    00434  */
    00435 #define pqremove(s, tree, top) \
    00436 {\
    00437     top = s->heap[SMALLEST]; \
    00438     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
    00439     pqdownheap(s, tree, SMALLEST); \
    00440 }
    00441
    00442 /* ===========================================================================
    00443  * Compares to subtrees, using the tree depth as tie breaker when
    00444  * the subtrees have equal frequency. This minimizes the worst case length.
    00445  */
    00446 #define smaller(tree, n, m, depth) \
    00447    (tree[n].Freq < tree[m].Freq || \
    00448    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
    00449
    00450 /* ===========================================================================
    00451  * Restore the heap property by moving down the tree starting at node k,
    00452  * exchanging a node with the smallest of its two sons if necessary, stopping
    00453  * when the heap property is re-established (each father smaller than its
    00454  * two sons).
    00455  */
    00456 local void pqdownheap(s, tree, k)
    00457     deflate_state *s;
    00458     ct_data *tree;  /* the tree to restore */
    00459     int k;               /* node to move down */
    00460 {
    00461     int v = s->heap[k];
    00462     int j = k << 1;  /* left son of k */
    00463     while (j <= s->heap_len) {
    00464         /* Set j to the smallest of the two sons: */
    00465         if (j < s->heap_len &&
    00466             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
    00467             j++;
    00468         }
    00469         /* Exit if v is smaller than both sons */
    00470         if (smaller(tree, v, s->heap[j], s->depth)) break;
    00471
    00472         /* Exchange v with the smallest son */
    00473         s->heap[k] = s->heap[j];  k = j;
    00474
    00475         /* And continue down the tree, setting j to the left son of k */
    00476         j <<= 1;
    00477     }
    00478     s->heap[k] = v;
    00479 }
    00480
    00481 /* ===========================================================================
    00482  * Compute the optimal bit lengths for a tree and update the total bit length
    00483  * for the current block.
    00484  * IN assertion: the fields freq and dad are set, heap[heap_max] and
    00485  *    above are the tree nodes sorted by increasing frequency.
    00486  * OUT assertions: the field len is set to the optimal bit length, the
    00487  *     array bl_count contains the frequencies for each bit length.
    00488  *     The length opt_len is updated; static_len is also updated if stree is
    00489  *     not null.
    00490  */
    00491 local void gen_bitlen(s, desc)
    00492     deflate_state *s;
    00493     tree_desc *desc;    /* the tree descriptor */
    00494 {
    00495     ct_data *tree        = desc->dyn_tree;
    00496     int max_code         = desc->max_code;
    00497     const ct_data *stree = desc->stat_desc->static_tree;
    00498     const intf *extra    = desc->stat_desc->extra_bits;
    00499     int base             = desc->stat_desc->extra_base;
    00500     int max_length       = desc->stat_desc->max_length;
    00501     int h;              /* heap index */
    00502     int n, m;           /* iterate over the tree elements */
    00503     int bits;           /* bit length */
    00504     int xbits;          /* extra bits */
    00505     ush f;              /* frequency */
    00506     int overflow = 0;   /* number of elements with bit length too large */
    00507
    00508     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
    00509
    00510     /* In a first pass, compute the optimal bit lengths (which may
    00511      * overflow in the case of the bit length tree).
    00512      */
    00513     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
    00514
    00515     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
    00516         n = s->heap[h];
    00517         bits = tree[tree[n].Dad].Len + 1;
    00518         if (bits > max_length) bits = max_length, overflow++;
    00519         tree[n].Len = (ush)bits;
    00520         /* We overwrite tree[n].Dad which is no longer needed */
    00521
    00522         if (n > max_code) continue; /* not a leaf node */
    00523
    00524         s->bl_count[bits]++;
    00525         xbits = 0;
    00526         if (n >= base) xbits = extra[n-base];
    00527         f = tree[n].Freq;
    00528         s->opt_len += (ulg)f * (bits + xbits);
    00529         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
    00530     }
    00531     if (overflow == 0) return;
    00532
    00533     Trace((stderr,"\nbit length overflow\n"));
    00534     /* This happens for example on obj2 and pic of the Calgary corpus */
    00535
    00536     /* Find the first bit length which could increase: */
    00537     do {
    00538         bits = max_length-1;
    00539         while (s->bl_count[bits] == 0) bits--;
    00540         s->bl_count[bits]--;      /* move one leaf down the tree */
    00541         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
    00542         s->bl_count[max_length]--;
    00543         /* The brother of the overflow item also moves one step up,
    00544          * but this does not affect bl_count[max_length]
    00545          */
    00546         overflow -= 2;
    00547     } while (overflow > 0);
    00548
    00549     /* Now recompute all bit lengths, scanning in increasing frequency.
    00550      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
    00551      * lengths instead of fixing only the wrong ones. This idea is taken
    00552      * from 'ar' written by Haruhiko Okumura.)
    00553      */
    00554     for (bits = max_length; bits != 0; bits--) {
    00555         n = s->bl_count[bits];
    00556         while (n != 0) {
    00557             m = s->heap[--h];
    00558             if (m > max_code) continue;
    00559             if (tree[m].Len != (unsigned) bits) {
    00560                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
    00561                 s->opt_len += ((long)bits - (long)tree[m].Len)
    00562                               *(long)tree[m].Freq;
    00563                 tree[m].Len = (ush)bits;
    00564             }
    00565             n--;
    00566         }
    00567     }
    00568 }
    00569
    00570 /* ===========================================================================
    00571  * Generate the codes for a given tree and bit counts (which need not be
    00572  * optimal).
    00573  * IN assertion: the array bl_count contains the bit length statistics for
    00574  * the given tree and the field len is set for all tree elements.
    00575  * OUT assertion: the field code is set for all tree elements of non
    00576  *     zero code length.
    00577  */
    00578 local void gen_codes (tree, max_code, bl_count)
    00579     ct_data *tree;             /* the tree to decorate */
    00580     int max_code;              /* largest code with non zero frequency */
    00581     ushf *bl_count;            /* number of codes at each bit length */
    00582 {
    00583     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
    00584     ush code = 0;              /* running code value */
    00585     int bits;                  /* bit index */
    00586     int n;                     /* code index */
    00587
    00588     /* The distribution counts are first used to generate the code values
    00589      * without bit reversal.
    00590      */
    00591     for (bits = 1; bits <= MAX_BITS; bits++) {
    00592         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
    00593     }
    00594     /* Check that the bit counts in bl_count are consistent. The last code
    00595      * must be all ones.
    00596      */
    00597     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
    00598             "inconsistent bit counts");
    00599     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
    00600
    00601     for (n = 0;  n <= max_code; n++) {
    00602         int len = tree[n].Len;
    00603         if (len == 0) continue;
    00604         /* Now reverse the bits */
    00605         tree[n].Code = bi_reverse(next_code[len]++, len);
    00606
    00607         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
    00608              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
    00609     }
    00610 }
    00611
    00612 /* ===========================================================================
    00613  * Construct one Huffman tree and assigns the code bit strings and lengths.
    00614  * Update the total bit length for the current block.
    00615  * IN assertion: the field freq is set for all tree elements.
    00616  * OUT assertions: the fields len and code are set to the optimal bit length
    00617  *     and corresponding code. The length opt_len is updated; static_len is
    00618  *     also updated if stree is not null. The field max_code is set.
    00619  */
    00620 local void build_tree(s, desc)
    00621     deflate_state *s;
    00622     tree_desc *desc; /* the tree descriptor */
    00623 {
    00624     ct_data *tree         = desc->dyn_tree;
    00625     const ct_data *stree  = desc->stat_desc->static_tree;
    00626     int elems             = desc->stat_desc->elems;
    00627     int n, m;          /* iterate over heap elements */
    00628     int max_code = -1; /* largest code with non zero frequency */
    00629     int node;          /* new node being created */
    00630
    00631     /* Construct the initial heap, with least frequent element in
    00632      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
    00633      * heap[0] is not used.
    00634      */
    00635     s->heap_len = 0, s->heap_max = HEAP_SIZE;
    00636
    00637     for (n = 0; n < elems; n++) {
    00638         if (tree[n].Freq != 0) {
    00639             s->heap[++(s->heap_len)] = max_code = n;
    00640             s->depth[n] = 0;
    00641         } else {
    00642             tree[n].Len = 0;
    00643         }
    00644     }
    00645
    00646     /* The pkzip format requires that at least one distance code exists,
    00647      * and that at least one bit should be sent even if there is only one
    00648      * possible code. So to avoid special checks later on we force at least
    00649      * two codes of non zero frequency.
    00650      */
    00651     while (s->heap_len < 2) {
    00652         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
    00653         tree[node].Freq = 1;
    00654         s->depth[node] = 0;
    00655         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
    00656         /* node is 0 or 1 so it does not have extra bits */
    00657     }
    00658     desc->max_code = max_code;
    00659
    00660     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
    00661      * establish sub-heaps of increasing lengths:
    00662      */
    00663     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
    00664
    00665     /* Construct the Huffman tree by repeatedly combining the least two
    00666      * frequent nodes.
    00667      */
    00668     node = elems;              /* next internal node of the tree */
    00669     do {
    00670         pqremove(s, tree, n);  /* n = node of least frequency */
    00671         m = s->heap[SMALLEST]; /* m = node of next least frequency */
    00672
    00673         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
    00674         s->heap[--(s->heap_max)] = m;
    00675
    00676         /* Create a new node father of n and m */
    00677         tree[node].Freq = tree[n].Freq + tree[m].Freq;
    00678         s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
    00679         tree[n].Dad = tree[m].Dad = (ush)node;
    00680 #ifdef DUMP_BL_TREE
    00681         if (tree == s->bl_tree) {
    00682             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
    00683                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
    00684         }
    00685 #endif
    00686         /* and insert the new node in the heap */
    00687         s->heap[SMALLEST] = node++;
    00688         pqdownheap(s, tree, SMALLEST);
    00689
    00690     } while (s->heap_len >= 2);
    00691
    00692     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
    00693
    00694     /* At this point, the fields freq and dad are set. We can now
    00695      * generate the bit lengths.
    00696      */
    00697     gen_bitlen(s, (tree_desc *)desc);
    00698
    00699     /* The field len is now set, we can generate the bit codes */
    00700     gen_codes ((ct_data *)tree, max_code, s->bl_count);
    00701 }
    00702
    00703 /* ===========================================================================
    00704  * Scan a literal or distance tree to determine the frequencies of the codes
    00705  * in the bit length tree.
    00706  */
    00707 local void scan_tree (s, tree, max_code)
    00708     deflate_state *s;
    00709     ct_data *tree;   /* the tree to be scanned */
    00710     int max_code;    /* and its largest code of non zero frequency */
    00711 {
    00712     int n;                     /* iterates over all tree elements */
    00713     int prevlen = -1;          /* last emitted length */
    00714     int curlen;                /* length of current code */
    00715     int nextlen = tree[0].Len; /* length of next code */
    00716     int count = 0;             /* repeat count of the current code */
    00717     int max_count = 7;         /* max repeat count */
    00718     int min_count = 4;         /* min repeat count */
    00719
    00720     if (nextlen == 0) max_count = 138, min_count = 3;
    00721     tree[max_code+1].Len = (ush)0xffff; /* guard */
    00722
    00723     for (n = 0; n <= max_code; n++) {
    00724         curlen = nextlen; nextlen = tree[n+1].Len;
    00725         if (++count < max_count && curlen == nextlen) {
    00726             continue;
    00727         } else if (count < min_count) {
    00728             s->bl_tree[curlen].Freq += count;
    00729         } else if (curlen != 0) {
    00730             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
    00731             s->bl_tree[REP_3_6].Freq++;
    00732         } else if (count <= 10) {
    00733             s->bl_tree[REPZ_3_10].Freq++;
    00734         } else {
    00735             s->bl_tree[REPZ_11_138].Freq++;
    00736         }
    00737         count = 0; prevlen = curlen;
    00738         if (nextlen == 0) {
    00739             max_count = 138, min_count = 3;
    00740         } else if (curlen == nextlen) {
    00741             max_count = 6, min_count = 3;
    00742         } else {
    00743             max_count = 7, min_count = 4;
    00744         }
    00745     }
    00746 }
    00747
    00748 /* ===========================================================================
    00749  * Send a literal or distance tree in compressed form, using the codes in
    00750  * bl_tree.
    00751  */
    00752 local void send_tree (s, tree, max_code)
    00753     deflate_state *s;
    00754     ct_data *tree; /* the tree to be scanned */
    00755     int max_code;       /* and its largest code of non zero frequency */
    00756 {
    00757     int n;                     /* iterates over all tree elements */
    00758     int prevlen = -1;          /* last emitted length */
    00759     int curlen;                /* length of current code */
    00760     int nextlen = tree[0].Len; /* length of next code */
    00761     int count = 0;             /* repeat count of the current code */
    00762     int max_count = 7;         /* max repeat count */
    00763     int min_count = 4;         /* min repeat count */
    00764
    00765     /* tree[max_code+1].Len = -1; */  /* guard already set */
    00766     if (nextlen == 0) max_count = 138, min_count = 3;
    00767
    00768     for (n = 0; n <= max_code; n++) {
    00769         curlen = nextlen; nextlen = tree[n+1].Len;
    00770         if (++count < max_count && curlen == nextlen) {
    00771             continue;
    00772         } else if (count < min_count) {
    00773             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
    00774
    00775         } else if (curlen != 0) {
    00776             if (curlen != prevlen) {
    00777                 send_code(s, curlen, s->bl_tree); count--;
    00778             }
    00779             Assert(count >= 3 && count <= 6, " 3_6?");
    00780             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
    00781
    00782         } else if (count <= 10) {
    00783             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
    00784
    00785         } else {
    00786             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
    00787         }
    00788         count = 0; prevlen = curlen;
    00789         if (nextlen == 0) {
    00790             max_count = 138, min_count = 3;
    00791         } else if (curlen == nextlen) {
    00792             max_count = 6, min_count = 3;
    00793         } else {
    00794             max_count = 7, min_count = 4;
    00795         }
    00796     }
    00797 }
    00798
    00799 /* ===========================================================================
    00800  * Construct the Huffman tree for the bit lengths and return the index in
    00801  * bl_order of the last bit length code to send.
    00802  */
    00803 local int build_bl_tree(s)
    00804     deflate_state *s;
    00805 {
    00806     int max_blindex;  /* index of last bit length code of non zero freq */
    00807
    00808     /* Determine the bit length frequencies for literal and distance trees */
    00809     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
    00810     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
    00811
    00812     /* Build the bit length tree: */
    00813     build_tree(s, (tree_desc *)(&(s->bl_desc)));
    00814     /* opt_len now includes the length of the tree representations, except
    00815      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
    00816      */
    00817
    00818     /* Determine the number of bit length codes to send. The pkzip format
    00819      * requires that at least 4 bit length codes be sent. (appnote.txt says
    00820      * 3 but the actual value used is 4.)
    00821      */
    00822     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
    00823         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
    00824     }
    00825     /* Update opt_len to include the bit length tree and counts */
    00826     s->opt_len += 3*(max_blindex+1) + 5+5+4;
    00827     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
    00828             s->opt_len, s->static_len));
    00829
    00830     return max_blindex;
    00831 }
    00832
    00833 /* ===========================================================================
    00834  * Send the header for a block using dynamic Huffman trees: the counts, the
    00835  * lengths of the bit length codes, the literal tree and the distance tree.
    00836  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
    00837  */
    00838 local void send_all_trees(s, lcodes, dcodes, blcodes)
    00839     deflate_state *s;
    00840     int lcodes, dcodes, blcodes; /* number of codes for each tree */
    00841 {
    00842     int rank;                    /* index in bl_order */
    00843
    00844     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
    00845     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
    00846             "too many codes");
    00847     Tracev((stderr, "\nbl counts: "));
    00848     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
    00849     send_bits(s, dcodes-1,   5);
    00850     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
    00851     for (rank = 0; rank < blcodes; rank++) {
    00852         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
    00853         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
    00854     }
    00855     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
    00856
    00857     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
    00858     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
    00859
    00860     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
    00861     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
    00862 }
    00863
    00864 /* ===========================================================================
    00865  * Send a stored block
    00866  */
    00867 void _tr_stored_block(s, buf, stored_len, eof)
    00868     deflate_state *s;
    00869     charf *buf;       /* input block */
    00870     ulg stored_len;   /* length of input block */
    00871     int eof;          /* true if this is the last block for a file */
    00872 {
    00873     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
    00874 #ifdef DEBUG
    00875     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
    00876     s->compressed_len += (stored_len + 4) << 3;
    00877 #endif
    00878     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
    00879 }
    00880
    00881 /* ===========================================================================
    00882  * Send one empty static block to give enough lookahead for inflate.
    00883  * This takes 10 bits, of which 7 may remain in the bit buffer.
    00884  * The current inflate code requires 9 bits of lookahead. If the
    00885  * last two codes for the previous block (real code plus EOB) were coded
    00886  * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
    00887  * the last real code. In this case we send two empty static blocks instead
    00888  * of one. (There are no problems if the previous block is stored or fixed.)
    00889  * To simplify the code, we assume the worst case of last real code encoded
    00890  * on one bit only.
    00891  */
    00892 void _tr_align(s)
    00893     deflate_state *s;
    00894 {
    00895     send_bits(s, STATIC_TREES<<1, 3);
    00896     send_code(s, END_BLOCK, static_ltree);
    00897 #ifdef DEBUG
    00898     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
    00899 #endif
    00900     bi_flush(s);
    00901     /* Of the 10 bits for the empty block, we have already sent
    00902      * (10 - bi_valid) bits. The lookahead for the last real code (before
    00903      * the EOB of the previous block) was thus at least one plus the length
    00904      * of the EOB plus what we have just sent of the empty static block.
    00905      */
    00906     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
    00907         send_bits(s, STATIC_TREES<<1, 3);
    00908         send_code(s, END_BLOCK, static_ltree);
    00909 #ifdef DEBUG
    00910         s->compressed_len += 10L;
    00911 #endif
    00912         bi_flush(s);
    00913     }
    00914     s->last_eob_len = 7;
    00915 }
    00916
    00917 /* ===========================================================================
    00918  * Determine the best encoding for the current block: dynamic trees, static
    00919  * trees or store, and output the encoded block to the zip file.
    00920  */
    00921 void _tr_flush_block(s, buf, stored_len, eof)
    00922     deflate_state *s;
    00923     charf *buf;       /* input block, or NULL if too old */
    00924     ulg stored_len;   /* length of input block */
    00925     int eof;          /* true if this is the last block for a file */
    00926 {
    00927     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
    00928     int max_blindex = 0;  /* index of last bit length code of non zero freq */
    00929
    00930     /* Build the Huffman trees unless a stored block is forced */
    00931     if (s->level > 0) {
    00932
    00933          /* Check if the file is ascii or binary */
    00934         if (s->data_type == Z_UNKNOWN) set_data_type(s);
    00935
    00936         /* Construct the literal and distance trees */
    00937         build_tree(s, (tree_desc *)(&(s->l_desc)));
    00938         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
    00939                 s->static_len));
    00940
    00941         build_tree(s, (tree_desc *)(&(s->d_desc)));
    00942         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
    00943                 s->static_len));
    00944         /* At this point, opt_len and static_len are the total bit lengths of
    00945          * the compressed block data, excluding the tree representations.
    00946          */
    00947
    00948         /* Build the bit length tree for the above two trees, and get the index
    00949          * in bl_order of the last bit length code to send.
    00950          */
    00951         max_blindex = build_bl_tree(s);
    00952
    00953         /* Determine the best encoding. Compute first the block length in bytes*/
    00954         opt_lenb = (s->opt_len+3+7)>>3;
    00955         static_lenb = (s->static_len+3+7)>>3;
    00956
    00957         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
    00958                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
    00959                 s->last_lit));
    00960
    00961         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
    00962
    00963     } else {
    00964         Assert(buf != (char*)0, "lost buf");
    00965         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
    00966     }
    00967
    00968 #ifdef FORCE_STORED
    00969     if (buf != (char*)0) { /* force stored block */
    00970 #else
    00971     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
    00972                        /* 4: two words for the lengths */
    00973 #endif
    00974         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
    00975          * Otherwise we can't have processed more than WSIZE input bytes since
    00976          * the last block flush, because compression would have been
    00977          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
    00978          * transform a block into a stored block.
    00979          */
    00980         _tr_stored_block(s, buf, stored_len, eof);
    00981
    00982 #ifdef FORCE_STATIC
    00983     } else if (static_lenb >= 0) { /* force static trees */
    00984 #else
    00985     } else if (static_lenb == opt_lenb) {
    00986 #endif
    00987         send_bits(s, (STATIC_TREES<<1)+eof, 3);
    00988         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
    00989 #ifdef DEBUG
    00990         s->compressed_len += 3 + s->static_len;
    00991 #endif
    00992     } else {
    00993         send_bits(s, (DYN_TREES<<1)+eof, 3);
    00994         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
    00995                        max_blindex+1);
    00996         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
    00997 #ifdef DEBUG
    00998         s->compressed_len += 3 + s->opt_len;
    00999 #endif
    01000     }
    01001     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
    01002     /* The above check is made mod 2^32, for files larger than 512 MB
    01003      * and uLong implemented on 32 bits.
    01004      */
    01005     init_block(s);
    01006
    01007     if (eof) {
    01008         bi_windup(s);
    01009 #ifdef DEBUG
    01010         s->compressed_len += 7;  /* align on byte boundary */
    01011 #endif
    01012     }
    01013     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
    01014            s->compressed_len-7*eof));
    01015 }
    01016
    01017 /* ===========================================================================
    01018  * Save the match info and tally the frequency counts. Return true if
    01019  * the current block must be flushed.
    01020  */
    01021 int _tr_tally (s, dist, lc)
    01022     deflate_state *s;
    01023     unsigned dist;  /* distance of matched string */
    01024     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
    01025 {
    01026     s->d_buf[s->last_lit] = (ush)dist;
    01027     s->l_buf[s->last_lit++] = (uch)lc;
    01028     if (dist == 0) {
    01029         /* lc is the unmatched char */
    01030         s->dyn_ltree[lc].Freq++;
    01031     } else {
    01032         s->matches++;
    01033         /* Here, lc is the match length - MIN_MATCH */
    01034         dist--;             /* dist = match distance - 1 */
    01035         Assert((ush)dist < (ush)MAX_DIST(s) &&
    01036                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
    01037                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
    01038
    01039         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
    01040         s->dyn_dtree[d_code(dist)].Freq++;
    01041     }
    01042
    01043 #ifdef TRUNCATE_BLOCK
    01044     /* Try to guess if it is profitable to stop the current block here */
    01045     if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
    01046         /* Compute an upper bound for the compressed length */
    01047         ulg out_length = (ulg)s->last_lit*8L;
    01048         ulg in_length = (ulg)((long)s->strstart - s->block_start);
    01049         int dcode;
    01050         for (dcode = 0; dcode < D_CODES; dcode++) {
    01051             out_length += (ulg)s->dyn_dtree[dcode].Freq *
    01052                 (5L+extra_dbits[dcode]);
    01053         }
    01054         out_length >>= 3;
    01055         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
    01056                s->last_lit, in_length, out_length,
    01057                100L - out_length*100L/in_length));
    01058         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
    01059     }
    01060 #endif
    01061     return (s->last_lit == s->lit_bufsize-1);
    01062     /* We avoid equality with lit_bufsize because of wraparound at 64K
    01063      * on 16 bit machines and because stored blocks are restricted to
    01064      * 64K-1 bytes.
    01065      */
    01066 }
    01067
    01068 /* ===========================================================================
    01069  * Send the block data compressed using the given Huffman trees
    01070  */
    01071 local void compress_block(s, ltree, dtree)
    01072     deflate_state *s;
    01073     ct_data *ltree; /* literal tree */
    01074     ct_data *dtree; /* distance tree */
    01075 {
    01076     unsigned dist;      /* distance of matched string */
    01077     int lc;             /* match length or unmatched char (if dist == 0) */
    01078     unsigned lx = 0;    /* running index in l_buf */
    01079     unsigned code;      /* the code to send */
    01080     int extra;          /* number of extra bits to send */
    01081
    01082     if (s->last_lit != 0) do {
    01083         dist = s->d_buf[lx];
    01084         lc = s->l_buf[lx++];
    01085         if (dist == 0) {
    01086             send_code(s, lc, ltree); /* send a literal byte */
    01087             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
    01088         } else {
    01089             /* Here, lc is the match length - MIN_MATCH */
    01090             code = _length_code[lc];
    01091             send_code(s, code+LITERALS+1, ltree); /* send the length code */
    01092             extra = extra_lbits[code];
    01093             if (extra != 0) {
    01094                 lc -= base_length[code];
    01095                 send_bits(s, lc, extra);       /* send the extra length bits */
    01096             }
    01097             dist--; /* dist is now the match distance - 1 */
    01098             code = d_code(dist);
    01099             Assert (code < D_CODES, "bad d_code");
    01100
    01101             send_code(s, code, dtree);       /* send the distance code */
    01102             extra = extra_dbits[code];
    01103             if (extra != 0) {
    01104                 dist -= base_dist[code];
    01105                 send_bits(s, dist, extra);   /* send the extra distance bits */
    01106             }
    01107         } /* literal or match pair ? */
    01108
    01109         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
    01110         Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
    01111
    01112     } while (lx < s->last_lit);
    01113
    01114     send_code(s, END_BLOCK, ltree);
    01115     s->last_eob_len = ltree[END_BLOCK].Len;
    01116 }
    01117
    01118 /* ===========================================================================
    01119  * Set the data type to ASCII or BINARY, using a crude approximation:
    01120  * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
    01121  * IN assertion: the fields freq of dyn_ltree are set and the total of all
    01122  * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
    01123  */
    01124 local void set_data_type(s)
    01125     deflate_state *s;
    01126 {
    01127     int n = 0;
    01128     unsigned ascii_freq = 0;
    01129     unsigned bin_freq = 0;
    01130     while (n < 7)        bin_freq += s->dyn_ltree[n++].Freq;
    01131     while (n < 128)    ascii_freq += s->dyn_ltree[n++].Freq;
    01132     while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
    01133     s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
    01134 }
    01135
    01136 /* ===========================================================================
    01137  * Reverse the first len bits of a code, using straightforward code (a faster
    01138  * method would use a table)
    01139  * IN assertion: 1 <= len <= 15
    01140  */
    01141 local unsigned bi_reverse(code, len)
    01142     unsigned code; /* the value to invert */
    01143     int len;       /* its bit length */
    01144 {
    01145     register unsigned res = 0;
    01146     do {
    01147         res |= code & 1;
    01148         code >>= 1, res <<= 1;
    01149     } while (--len > 0);
    01150     return res >> 1;
    01151 }
    01152
    01153 /* ===========================================================================
    01154  * Flush the bit buffer, keeping at most 7 bits in it.
    01155  */
    01156 local void bi_flush(s)
    01157     deflate_state *s;
    01158 {
    01159     if (s->bi_valid == 16) {
    01160         put_short(s, s->bi_buf);
    01161         s->bi_buf = 0;
    01162         s->bi_valid = 0;
    01163     } else if (s->bi_valid >= 8) {
    01164         put_byte(s, (Byte)s->bi_buf);
    01165         s->bi_buf >>= 8;
    01166         s->bi_valid -= 8;
    01167     }
    01168 }
    01169
    01170 /* ===========================================================================
    01171  * Flush the bit buffer and align the output on a byte boundary
    01172  */
    01173 local void bi_windup(s)
    01174     deflate_state *s;
    01175 {
    01176     if (s->bi_valid > 8) {
    01177         put_short(s, s->bi_buf);
    01178     } else if (s->bi_valid > 0) {
    01179         put_byte(s, (Byte)s->bi_buf);
    01180     }
    01181     s->bi_buf = 0;
    01182     s->bi_valid = 0;
    01183 #ifdef DEBUG
    01184     s->bits_sent = (s->bits_sent+7) & ~7;
    01185 #endif
    01186 }
    01187
    01188 /* ===========================================================================
    01189  * Copy a stored block, storing first the length and its
    01190  * one's complement if requested.
    01191  */
    01192 local void copy_block(s, buf, len, header)
    01193     deflate_state *s;
    01194     charf    *buf;    /* the input data */
    01195     unsigned len;     /* its length */
    01196     int      header;  /* true if block header must be written */
    01197 {
    01198     bi_windup(s);        /* align on byte boundary */
    01199     s->last_eob_len = 8; /* enough lookahead for inflate */
    01200
    01201     if (header) {
    01202         put_short(s, (ush)len);
    01203         put_short(s, (ush)~len);
    01204 #ifdef DEBUG
    01205         s->bits_sent += 2*16;
    01206 #endif
    01207     }
    01208 #ifdef DEBUG
    01209     s->bits_sent += (ulg)len<<3;
    01210 #endif
    01211     while (len--) {
    01212         put_byte(s, *buf++);
    01213     }
    01214 }