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