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


pcl
Author(s): Open Perception
autogenerated on Wed Aug 26 2015 15:37:05