deftree.c
上传用户:jlfgdled
上传日期:2013-04-10
资源大小:33168k
文件大小:40k
源码类别:

Linux/Unix编程

开发平台:

Unix_Linux

  1. /* +++ trees.c */
  2. /* trees.c -- output deflated data using Huffman coding
  3.  * Copyright (C) 1995-1996 Jean-loup Gailly
  4.  * For conditions of distribution and use, see copyright notice in zlib.h 
  5.  */
  6. /*
  7.  *  ALGORITHM
  8.  *
  9.  *      The "deflation" process uses several Huffman trees. The more
  10.  *      common source values are represented by shorter bit sequences.
  11.  *
  12.  *      Each code tree is stored in a compressed form which is itself
  13.  * a Huffman encoding of the lengths of all the code strings (in
  14.  * ascending order by source values).  The actual code strings are
  15.  * reconstructed from the lengths in the inflate process, as described
  16.  * in the deflate specification.
  17.  *
  18.  *  REFERENCES
  19.  *
  20.  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  21.  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  22.  *
  23.  *      Storer, James A.
  24.  *          Data Compression:  Methods and Theory, pp. 49-50.
  25.  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  26.  *
  27.  *      Sedgewick, R.
  28.  *          Algorithms, p290.
  29.  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
  30.  */
  31. /* From: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */
  32. /* #include "deflate.h" */
  33. #include <linux/zutil.h>
  34. #include "defutil.h"
  35. #ifdef DEBUG_ZLIB
  36. #  include <ctype.h>
  37. #endif
  38. /* ===========================================================================
  39.  * Constants
  40.  */
  41. #define MAX_BL_BITS 7
  42. /* Bit length codes must not exceed MAX_BL_BITS bits */
  43. #define END_BLOCK 256
  44. /* end of block literal code */
  45. #define REP_3_6      16
  46. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  47. #define REPZ_3_10    17
  48. /* repeat a zero length 3-10 times  (3 bits of repeat count) */
  49. #define REPZ_11_138  18
  50. /* repeat a zero length 11-138 times  (7 bits of repeat count) */
  51. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  52.    = {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};
  53. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  54.    = {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};
  55. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  56.    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  57. local const uch bl_order[BL_CODES]
  58.    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  59. /* The lengths of the bit length codes are sent in order of decreasing
  60.  * probability, to avoid transmitting the lengths for unused bit length codes.
  61.  */
  62. #define Buf_size (8 * 2*sizeof(char))
  63. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  64.  * more than 16 bits on some systems.)
  65.  */
  66. /* ===========================================================================
  67.  * Local data. These are initialized only once.
  68.  */
  69. local ct_data static_ltree[L_CODES+2];
  70. /* The static literal tree. Since the bit lengths are imposed, there is no
  71.  * need for the L_CODES extra codes used during heap construction. However
  72.  * The codes 286 and 287 are needed to build a canonical tree (see zlib_tr_init
  73.  * below).
  74.  */
  75. local ct_data static_dtree[D_CODES];
  76. /* The static distance tree. (Actually a trivial tree since all codes use
  77.  * 5 bits.)
  78.  */
  79. local uch dist_code[512];
  80. /* distance codes. The first 256 values correspond to the distances
  81.  * 3 .. 258, the last 256 values correspond to the top 8 bits of
  82.  * the 15 bit distances.
  83.  */
  84. local uch length_code[MAX_MATCH-MIN_MATCH+1];
  85. /* length code for each normalized match length (0 == MIN_MATCH) */
  86. local int base_length[LENGTH_CODES];
  87. /* First normalized length for each code (0 = MIN_MATCH) */
  88. local int base_dist[D_CODES];
  89. /* First normalized distance for each code (0 = distance of 1) */
  90. struct static_tree_desc_s {
  91.     const ct_data *static_tree;  /* static tree or NULL */
  92.     const intf *extra_bits;      /* extra bits for each code or NULL */
  93.     int     extra_base;          /* base index for extra_bits */
  94.     int     elems;               /* max number of elements in the tree */
  95.     int     max_length;          /* max bit length for the codes */
  96. };
  97. local static_tree_desc  static_l_desc =
  98. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  99. local static_tree_desc  static_d_desc =
  100. {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
  101. local static_tree_desc  static_bl_desc =
  102. {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
  103. /* ===========================================================================
  104.  * Local (static) routines in this file.
  105.  */
  106. local void tr_static_init OF((void));
  107. local void init_block     OF((deflate_state *s));
  108. local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
  109. local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
  110. local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
  111. local void build_tree     OF((deflate_state *s, tree_desc *desc));
  112. local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
  113. local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
  114. local int  build_bl_tree  OF((deflate_state *s));
  115. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  116.                               int blcodes));
  117. local void compress_block OF((deflate_state *s, ct_data *ltree,
  118.                               ct_data *dtree));
  119. local void set_data_type  OF((deflate_state *s));
  120. local unsigned bi_reverse OF((unsigned value, int length));
  121. local void bi_windup      OF((deflate_state *s));
  122. local void bi_flush       OF((deflate_state *s));
  123. local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
  124.                               int header));
  125. #ifndef DEBUG_ZLIB
  126. #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  127.    /* Send a code of the given tree. c and tree must not have side effects */
  128. #else /* DEBUG_ZLIB */
  129. #  define send_code(s, c, tree) 
  130.      { if (z_verbose>2) fprintf(stderr,"ncd %3d ",(c)); 
  131.        send_bits(s, tree[c].Code, tree[c].Len); }
  132. #endif
  133. #define d_code(dist) 
  134.    ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  135. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  136.  * must not have side effects. dist_code[256] and dist_code[257] are never
  137.  * used.
  138.  */
  139. /* ===========================================================================
  140.  * Send a value on a given number of bits.
  141.  * IN assertion: length <= 16 and value fits in length bits.
  142.  */
  143. #ifdef DEBUG_ZLIB
  144. local void send_bits      OF((deflate_state *s, int value, int length));
  145. local void send_bits(s, value, length)
  146.     deflate_state *s;
  147.     int value;  /* value to send */
  148.     int length; /* number of bits */
  149. {
  150.     Tracevv((stderr," l %2d v %4x ", length, value));
  151.     Assert(length > 0 && length <= 15, "invalid length");
  152.     s->bits_sent += (ulg)length;
  153.     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  154.      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  155.      * unused bits in value.
  156.      */
  157.     if (s->bi_valid > (int)Buf_size - length) {
  158.         s->bi_buf |= (value << s->bi_valid);
  159.         put_short(s, s->bi_buf);
  160.         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  161.         s->bi_valid += length - Buf_size;
  162.     } else {
  163.         s->bi_buf |= value << s->bi_valid;
  164.         s->bi_valid += length;
  165.     }
  166. }
  167. #else /* !DEBUG_ZLIB */
  168. #define send_bits(s, value, length) 
  169. { int len = length;
  170.   if (s->bi_valid > (int)Buf_size - len) {
  171.     int val = value;
  172.     s->bi_buf |= (val << s->bi_valid);
  173.     put_short(s, s->bi_buf);
  174.     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);
  175.     s->bi_valid += len - Buf_size;
  176.   } else {
  177.     s->bi_buf |= (value) << s->bi_valid;
  178.     s->bi_valid += len;
  179.   }
  180. }
  181. #endif /* DEBUG_ZLIB */
  182. #define MAX(a,b) (a >= b ? a : b)
  183. /* the arguments must not have side effects */
  184. /* ===========================================================================
  185.  * Initialize the various 'constant' tables. In a multi-threaded environment,
  186.  * this function may be called by two threads concurrently, but this is
  187.  * harmless since both invocations do exactly the same thing.
  188.  */
  189. local void tr_static_init()
  190. {
  191.     static int static_init_done = 0;
  192.     int n;        /* iterates over tree elements */
  193.     int bits;     /* bit counter */
  194.     int length;   /* length value */
  195.     int code;     /* code value */
  196.     int dist;     /* distance index */
  197.     ush bl_count[MAX_BITS+1];
  198.     /* number of codes at each bit length for an optimal tree */
  199.     if (static_init_done) return;
  200.     /* Initialize the mapping length (0..255) -> length code (0..28) */
  201.     length = 0;
  202.     for (code = 0; code < LENGTH_CODES-1; code++) {
  203.         base_length[code] = length;
  204.         for (n = 0; n < (1<<extra_lbits[code]); n++) {
  205.             length_code[length++] = (uch)code;
  206.         }
  207.     }
  208.     Assert (length == 256, "tr_static_init: length != 256");
  209.     /* Note that the length 255 (match length 258) can be represented
  210.      * in two different ways: code 284 + 5 bits or code 285, so we
  211.      * overwrite length_code[255] to use the best encoding:
  212.      */
  213.     length_code[length-1] = (uch)code;
  214.     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  215.     dist = 0;
  216.     for (code = 0 ; code < 16; code++) {
  217.         base_dist[code] = dist;
  218.         for (n = 0; n < (1<<extra_dbits[code]); n++) {
  219.             dist_code[dist++] = (uch)code;
  220.         }
  221.     }
  222.     Assert (dist == 256, "tr_static_init: dist != 256");
  223.     dist >>= 7; /* from now on, all distances are divided by 128 */
  224.     for ( ; code < D_CODES; code++) {
  225.         base_dist[code] = dist << 7;
  226.         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  227.             dist_code[256 + dist++] = (uch)code;
  228.         }
  229.     }
  230.     Assert (dist == 256, "tr_static_init: 256+dist != 512");
  231.     /* Construct the codes of the static literal tree */
  232.     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  233.     n = 0;
  234.     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  235.     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  236.     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  237.     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  238.     /* Codes 286 and 287 do not exist, but we must include them in the
  239.      * tree construction to get a canonical Huffman tree (longest code
  240.      * all ones)
  241.      */
  242.     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  243.     /* The static distance tree is trivial: */
  244.     for (n = 0; n < D_CODES; n++) {
  245.         static_dtree[n].Len = 5;
  246.         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  247.     }
  248.     static_init_done = 1;
  249. }
  250. /* ===========================================================================
  251.  * Initialize the tree data structures for a new zlib stream.
  252.  */
  253. void zlib_tr_init(s)
  254.     deflate_state *s;
  255. {
  256.     tr_static_init();
  257.     s->compressed_len = 0L;
  258.     s->l_desc.dyn_tree = s->dyn_ltree;
  259.     s->l_desc.stat_desc = &static_l_desc;
  260.     s->d_desc.dyn_tree = s->dyn_dtree;
  261.     s->d_desc.stat_desc = &static_d_desc;
  262.     s->bl_desc.dyn_tree = s->bl_tree;
  263.     s->bl_desc.stat_desc = &static_bl_desc;
  264.     s->bi_buf = 0;
  265.     s->bi_valid = 0;
  266.     s->last_eob_len = 8; /* enough lookahead for inflate */
  267. #ifdef DEBUG_ZLIB
  268.     s->bits_sent = 0L;
  269. #endif
  270.     /* Initialize the first block of the first file: */
  271.     init_block(s);
  272. }
  273. /* ===========================================================================
  274.  * Initialize a new block.
  275.  */
  276. local void init_block(s)
  277.     deflate_state *s;
  278. {
  279.     int n; /* iterates over tree elements */
  280.     /* Initialize the trees. */
  281.     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
  282.     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
  283.     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  284.     s->dyn_ltree[END_BLOCK].Freq = 1;
  285.     s->opt_len = s->static_len = 0L;
  286.     s->last_lit = s->matches = 0;
  287. }
  288. #define SMALLEST 1
  289. /* Index within the heap array of least frequent node in the Huffman tree */
  290. /* ===========================================================================
  291.  * Remove the smallest element from the heap and recreate the heap with
  292.  * one less element. Updates heap and heap_len.
  293.  */
  294. #define pqremove(s, tree, top) 
  295. {
  296.     top = s->heap[SMALLEST]; 
  297.     s->heap[SMALLEST] = s->heap[s->heap_len--]; 
  298.     pqdownheap(s, tree, SMALLEST); 
  299. }
  300. /* ===========================================================================
  301.  * Compares to subtrees, using the tree depth as tie breaker when
  302.  * the subtrees have equal frequency. This minimizes the worst case length.
  303.  */
  304. #define smaller(tree, n, m, depth) 
  305.    (tree[n].Freq < tree[m].Freq || 
  306.    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  307. /* ===========================================================================
  308.  * Restore the heap property by moving down the tree starting at node k,
  309.  * exchanging a node with the smallest of its two sons if necessary, stopping
  310.  * when the heap property is re-established (each father smaller than its
  311.  * two sons).
  312.  */
  313. local void pqdownheap(s, tree, k)
  314.     deflate_state *s;
  315.     ct_data *tree;  /* the tree to restore */
  316.     int k;               /* node to move down */
  317. {
  318.     int v = s->heap[k];
  319.     int j = k << 1;  /* left son of k */
  320.     while (j <= s->heap_len) {
  321.         /* Set j to the smallest of the two sons: */
  322.         if (j < s->heap_len &&
  323.             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  324.             j++;
  325.         }
  326.         /* Exit if v is smaller than both sons */
  327.         if (smaller(tree, v, s->heap[j], s->depth)) break;
  328.         /* Exchange v with the smallest son */
  329.         s->heap[k] = s->heap[j];  k = j;
  330.         /* And continue down the tree, setting j to the left son of k */
  331.         j <<= 1;
  332.     }
  333.     s->heap[k] = v;
  334. }
  335. /* ===========================================================================
  336.  * Compute the optimal bit lengths for a tree and update the total bit length
  337.  * for the current block.
  338.  * IN assertion: the fields freq and dad are set, heap[heap_max] and
  339.  *    above are the tree nodes sorted by increasing frequency.
  340.  * OUT assertions: the field len is set to the optimal bit length, the
  341.  *     array bl_count contains the frequencies for each bit length.
  342.  *     The length opt_len is updated; static_len is also updated if stree is
  343.  *     not null.
  344.  */
  345. local void gen_bitlen(s, desc)
  346.     deflate_state *s;
  347.     tree_desc *desc;    /* the tree descriptor */
  348. {
  349.     ct_data *tree        = desc->dyn_tree;
  350.     int max_code         = desc->max_code;
  351.     const ct_data *stree = desc->stat_desc->static_tree;
  352.     const intf *extra    = desc->stat_desc->extra_bits;
  353.     int base             = desc->stat_desc->extra_base;
  354.     int max_length       = desc->stat_desc->max_length;
  355.     int h;              /* heap index */
  356.     int n, m;           /* iterate over the tree elements */
  357.     int bits;           /* bit length */
  358.     int xbits;          /* extra bits */
  359.     ush f;              /* frequency */
  360.     int overflow = 0;   /* number of elements with bit length too large */
  361.     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  362.     /* In a first pass, compute the optimal bit lengths (which may
  363.      * overflow in the case of the bit length tree).
  364.      */
  365.     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  366.     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  367.         n = s->heap[h];
  368.         bits = tree[tree[n].Dad].Len + 1;
  369.         if (bits > max_length) bits = max_length, overflow++;
  370.         tree[n].Len = (ush)bits;
  371.         /* We overwrite tree[n].Dad which is no longer needed */
  372.         if (n > max_code) continue; /* not a leaf node */
  373.         s->bl_count[bits]++;
  374.         xbits = 0;
  375.         if (n >= base) xbits = extra[n-base];
  376.         f = tree[n].Freq;
  377.         s->opt_len += (ulg)f * (bits + xbits);
  378.         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  379.     }
  380.     if (overflow == 0) return;
  381.     Trace((stderr,"nbit length overflown"));
  382.     /* This happens for example on obj2 and pic of the Calgary corpus */
  383.     /* Find the first bit length which could increase: */
  384.     do {
  385.         bits = max_length-1;
  386.         while (s->bl_count[bits] == 0) bits--;
  387.         s->bl_count[bits]--;      /* move one leaf down the tree */
  388.         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  389.         s->bl_count[max_length]--;
  390.         /* The brother of the overflow item also moves one step up,
  391.          * but this does not affect bl_count[max_length]
  392.          */
  393.         overflow -= 2;
  394.     } while (overflow > 0);
  395.     /* Now recompute all bit lengths, scanning in increasing frequency.
  396.      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  397.      * lengths instead of fixing only the wrong ones. This idea is taken
  398.      * from 'ar' written by Haruhiko Okumura.)
  399.      */
  400.     for (bits = max_length; bits != 0; bits--) {
  401.         n = s->bl_count[bits];
  402.         while (n != 0) {
  403.             m = s->heap[--h];
  404.             if (m > max_code) continue;
  405.             if (tree[m].Len != (unsigned) bits) {
  406.                 Trace((stderr,"code %d bits %d->%dn", m, tree[m].Len, bits));
  407.                 s->opt_len += ((long)bits - (long)tree[m].Len)
  408.                               *(long)tree[m].Freq;
  409.                 tree[m].Len = (ush)bits;
  410.             }
  411.             n--;
  412.         }
  413.     }
  414. }
  415. /* ===========================================================================
  416.  * Generate the codes for a given tree and bit counts (which need not be
  417.  * optimal).
  418.  * IN assertion: the array bl_count contains the bit length statistics for
  419.  * the given tree and the field len is set for all tree elements.
  420.  * OUT assertion: the field code is set for all tree elements of non
  421.  *     zero code length.
  422.  */
  423. local void gen_codes (tree, max_code, bl_count)
  424.     ct_data *tree;             /* the tree to decorate */
  425.     int max_code;              /* largest code with non zero frequency */
  426.     ushf *bl_count;            /* number of codes at each bit length */
  427. {
  428.     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  429.     ush code = 0;              /* running code value */
  430.     int bits;                  /* bit index */
  431.     int n;                     /* code index */
  432.     /* The distribution counts are first used to generate the code values
  433.      * without bit reversal.
  434.      */
  435.     for (bits = 1; bits <= MAX_BITS; bits++) {
  436.         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  437.     }
  438.     /* Check that the bit counts in bl_count are consistent. The last code
  439.      * must be all ones.
  440.      */
  441.     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  442.             "inconsistent bit counts");
  443.     Tracev((stderr,"ngen_codes: max_code %d ", max_code));
  444.     for (n = 0;  n <= max_code; n++) {
  445.         int len = tree[n].Len;
  446.         if (len == 0) continue;
  447.         /* Now reverse the bits */
  448.         tree[n].Code = bi_reverse(next_code[len]++, len);
  449.         Tracecv(tree != static_ltree, (stderr,"nn %3d %c l %2d c %4x (%x) ",
  450.              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  451.     }
  452. }
  453. /* ===========================================================================
  454.  * Construct one Huffman tree and assigns the code bit strings and lengths.
  455.  * Update the total bit length for the current block.
  456.  * IN assertion: the field freq is set for all tree elements.
  457.  * OUT assertions: the fields len and code are set to the optimal bit length
  458.  *     and corresponding code. The length opt_len is updated; static_len is
  459.  *     also updated if stree is not null. The field max_code is set.
  460.  */
  461. local void build_tree(s, desc)
  462.     deflate_state *s;
  463.     tree_desc *desc; /* the tree descriptor */
  464. {
  465.     ct_data *tree         = desc->dyn_tree;
  466.     const ct_data *stree  = desc->stat_desc->static_tree;
  467.     int elems             = desc->stat_desc->elems;
  468.     int n, m;          /* iterate over heap elements */
  469.     int max_code = -1; /* largest code with non zero frequency */
  470.     int node;          /* new node being created */
  471.     /* Construct the initial heap, with least frequent element in
  472.      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  473.      * heap[0] is not used.
  474.      */
  475.     s->heap_len = 0, s->heap_max = HEAP_SIZE;
  476.     for (n = 0; n < elems; n++) {
  477.         if (tree[n].Freq != 0) {
  478.             s->heap[++(s->heap_len)] = max_code = n;
  479.             s->depth[n] = 0;
  480.         } else {
  481.             tree[n].Len = 0;
  482.         }
  483.     }
  484.     /* The pkzip format requires that at least one distance code exists,
  485.      * and that at least one bit should be sent even if there is only one
  486.      * possible code. So to avoid special checks later on we force at least
  487.      * two codes of non zero frequency.
  488.      */
  489.     while (s->heap_len < 2) {
  490.         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  491.         tree[node].Freq = 1;
  492.         s->depth[node] = 0;
  493.         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  494.         /* node is 0 or 1 so it does not have extra bits */
  495.     }
  496.     desc->max_code = max_code;
  497.     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  498.      * establish sub-heaps of increasing lengths:
  499.      */
  500.     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  501.     /* Construct the Huffman tree by repeatedly combining the least two
  502.      * frequent nodes.
  503.      */
  504.     node = elems;              /* next internal node of the tree */
  505.     do {
  506.         pqremove(s, tree, n);  /* n = node of least frequency */
  507.         m = s->heap[SMALLEST]; /* m = node of next least frequency */
  508.         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  509.         s->heap[--(s->heap_max)] = m;
  510.         /* Create a new node father of n and m */
  511.         tree[node].Freq = tree[n].Freq + tree[m].Freq;
  512.         s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
  513.         tree[n].Dad = tree[m].Dad = (ush)node;
  514. #ifdef DUMP_BL_TREE
  515.         if (tree == s->bl_tree) {
  516.             fprintf(stderr,"nnode %d(%d), sons %d(%d) %d(%d)",
  517.                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  518.         }
  519. #endif
  520.         /* and insert the new node in the heap */
  521.         s->heap[SMALLEST] = node++;
  522.         pqdownheap(s, tree, SMALLEST);
  523.     } while (s->heap_len >= 2);
  524.     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  525.     /* At this point, the fields freq and dad are set. We can now
  526.      * generate the bit lengths.
  527.      */
  528.     gen_bitlen(s, (tree_desc *)desc);
  529.     /* The field len is now set, we can generate the bit codes */
  530.     gen_codes ((ct_data *)tree, max_code, s->bl_count);
  531. }
  532. /* ===========================================================================
  533.  * Scan a literal or distance tree to determine the frequencies of the codes
  534.  * in the bit length tree.
  535.  */
  536. local void scan_tree (s, tree, max_code)
  537.     deflate_state *s;
  538.     ct_data *tree;   /* the tree to be scanned */
  539.     int max_code;    /* and its largest code of non zero frequency */
  540. {
  541.     int n;                     /* iterates over all tree elements */
  542.     int prevlen = -1;          /* last emitted length */
  543.     int curlen;                /* length of current code */
  544.     int nextlen = tree[0].Len; /* length of next code */
  545.     int count = 0;             /* repeat count of the current code */
  546.     int max_count = 7;         /* max repeat count */
  547.     int min_count = 4;         /* min repeat count */
  548.     if (nextlen == 0) max_count = 138, min_count = 3;
  549.     tree[max_code+1].Len = (ush)0xffff; /* guard */
  550.     for (n = 0; n <= max_code; n++) {
  551.         curlen = nextlen; nextlen = tree[n+1].Len;
  552.         if (++count < max_count && curlen == nextlen) {
  553.             continue;
  554.         } else if (count < min_count) {
  555.             s->bl_tree[curlen].Freq += count;
  556.         } else if (curlen != 0) {
  557.             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  558.             s->bl_tree[REP_3_6].Freq++;
  559.         } else if (count <= 10) {
  560.             s->bl_tree[REPZ_3_10].Freq++;
  561.         } else {
  562.             s->bl_tree[REPZ_11_138].Freq++;
  563.         }
  564.         count = 0; prevlen = curlen;
  565.         if (nextlen == 0) {
  566.             max_count = 138, min_count = 3;
  567.         } else if (curlen == nextlen) {
  568.             max_count = 6, min_count = 3;
  569.         } else {
  570.             max_count = 7, min_count = 4;
  571.         }
  572.     }
  573. }
  574. /* ===========================================================================
  575.  * Send a literal or distance tree in compressed form, using the codes in
  576.  * bl_tree.
  577.  */
  578. local void send_tree (s, tree, max_code)
  579.     deflate_state *s;
  580.     ct_data *tree; /* the tree to be scanned */
  581.     int max_code;       /* and its largest code of non zero frequency */
  582. {
  583.     int n;                     /* iterates over all tree elements */
  584.     int prevlen = -1;          /* last emitted length */
  585.     int curlen;                /* length of current code */
  586.     int nextlen = tree[0].Len; /* length of next code */
  587.     int count = 0;             /* repeat count of the current code */
  588.     int max_count = 7;         /* max repeat count */
  589.     int min_count = 4;         /* min repeat count */
  590.     /* tree[max_code+1].Len = -1; */  /* guard already set */
  591.     if (nextlen == 0) max_count = 138, min_count = 3;
  592.     for (n = 0; n <= max_code; n++) {
  593.         curlen = nextlen; nextlen = tree[n+1].Len;
  594.         if (++count < max_count && curlen == nextlen) {
  595.             continue;
  596.         } else if (count < min_count) {
  597.             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  598.         } else if (curlen != 0) {
  599.             if (curlen != prevlen) {
  600.                 send_code(s, curlen, s->bl_tree); count--;
  601.             }
  602.             Assert(count >= 3 && count <= 6, " 3_6?");
  603.             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  604.         } else if (count <= 10) {
  605.             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  606.         } else {
  607.             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  608.         }
  609.         count = 0; prevlen = curlen;
  610.         if (nextlen == 0) {
  611.             max_count = 138, min_count = 3;
  612.         } else if (curlen == nextlen) {
  613.             max_count = 6, min_count = 3;
  614.         } else {
  615.             max_count = 7, min_count = 4;
  616.         }
  617.     }
  618. }
  619. /* ===========================================================================
  620.  * Construct the Huffman tree for the bit lengths and return the index in
  621.  * bl_order of the last bit length code to send.
  622.  */
  623. local int build_bl_tree(s)
  624.     deflate_state *s;
  625. {
  626.     int max_blindex;  /* index of last bit length code of non zero freq */
  627.     /* Determine the bit length frequencies for literal and distance trees */
  628.     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  629.     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  630.     /* Build the bit length tree: */
  631.     build_tree(s, (tree_desc *)(&(s->bl_desc)));
  632.     /* opt_len now includes the length of the tree representations, except
  633.      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  634.      */
  635.     /* Determine the number of bit length codes to send. The pkzip format
  636.      * requires that at least 4 bit length codes be sent. (appnote.txt says
  637.      * 3 but the actual value used is 4.)
  638.      */
  639.     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  640.         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  641.     }
  642.     /* Update opt_len to include the bit length tree and counts */
  643.     s->opt_len += 3*(max_blindex+1) + 5+5+4;
  644.     Tracev((stderr, "ndyn trees: dyn %ld, stat %ld",
  645.             s->opt_len, s->static_len));
  646.     return max_blindex;
  647. }
  648. /* ===========================================================================
  649.  * Send the header for a block using dynamic Huffman trees: the counts, the
  650.  * lengths of the bit length codes, the literal tree and the distance tree.
  651.  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  652.  */
  653. local void send_all_trees(s, lcodes, dcodes, blcodes)
  654.     deflate_state *s;
  655.     int lcodes, dcodes, blcodes; /* number of codes for each tree */
  656. {
  657.     int rank;                    /* index in bl_order */
  658.     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  659.     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  660.             "too many codes");
  661.     Tracev((stderr, "nbl counts: "));
  662.     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  663.     send_bits(s, dcodes-1,   5);
  664.     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
  665.     for (rank = 0; rank < blcodes; rank++) {
  666.         Tracev((stderr, "nbl code %2d ", bl_order[rank]));
  667.         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  668.     }
  669.     Tracev((stderr, "nbl tree: sent %ld", s->bits_sent));
  670.     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  671.     Tracev((stderr, "nlit tree: sent %ld", s->bits_sent));
  672.     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  673.     Tracev((stderr, "ndist tree: sent %ld", s->bits_sent));
  674. }
  675. /* ===========================================================================
  676.  * Send a stored block
  677.  */
  678. void zlib_tr_stored_block(s, buf, stored_len, eof)
  679.     deflate_state *s;
  680.     charf *buf;       /* input block */
  681.     ulg stored_len;   /* length of input block */
  682.     int eof;          /* true if this is the last block for a file */
  683. {
  684.     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
  685.     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  686.     s->compressed_len += (stored_len + 4) << 3;
  687.     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  688. }
  689. /* Send just the `stored block' type code without any length bytes or data.
  690.  */
  691. void zlib_tr_stored_type_only(s)
  692.     deflate_state *s;
  693. {
  694.     send_bits(s, (STORED_BLOCK << 1), 3);
  695.     bi_windup(s);
  696.     s->compressed_len = (s->compressed_len + 3) & ~7L;
  697. }
  698. /* ===========================================================================
  699.  * Send one empty static block to give enough lookahead for inflate.
  700.  * This takes 10 bits, of which 7 may remain in the bit buffer.
  701.  * The current inflate code requires 9 bits of lookahead. If the
  702.  * last two codes for the previous block (real code plus EOB) were coded
  703.  * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  704.  * the last real code. In this case we send two empty static blocks instead
  705.  * of one. (There are no problems if the previous block is stored or fixed.)
  706.  * To simplify the code, we assume the worst case of last real code encoded
  707.  * on one bit only.
  708.  */
  709. void zlib_tr_align(s)
  710.     deflate_state *s;
  711. {
  712.     send_bits(s, STATIC_TREES<<1, 3);
  713.     send_code(s, END_BLOCK, static_ltree);
  714.     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  715.     bi_flush(s);
  716.     /* Of the 10 bits for the empty block, we have already sent
  717.      * (10 - bi_valid) bits. The lookahead for the last real code (before
  718.      * the EOB of the previous block) was thus at least one plus the length
  719.      * of the EOB plus what we have just sent of the empty static block.
  720.      */
  721.     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  722.         send_bits(s, STATIC_TREES<<1, 3);
  723.         send_code(s, END_BLOCK, static_ltree);
  724.         s->compressed_len += 10L;
  725.         bi_flush(s);
  726.     }
  727.     s->last_eob_len = 7;
  728. }
  729. /* ===========================================================================
  730.  * Determine the best encoding for the current block: dynamic trees, static
  731.  * trees or store, and output the encoded block to the zip file. This function
  732.  * returns the total compressed length for the file so far.
  733.  */
  734. ulg zlib_tr_flush_block(s, buf, stored_len, eof)
  735.     deflate_state *s;
  736.     charf *buf;       /* input block, or NULL if too old */
  737.     ulg stored_len;   /* length of input block */
  738.     int eof;          /* true if this is the last block for a file */
  739. {
  740.     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  741.     int max_blindex = 0;  /* index of last bit length code of non zero freq */
  742.     /* Build the Huffman trees unless a stored block is forced */
  743.     if (s->level > 0) {
  744.  /* Check if the file is ascii or binary */
  745. if (s->data_type == Z_UNKNOWN) set_data_type(s);
  746. /* Construct the literal and distance trees */
  747. build_tree(s, (tree_desc *)(&(s->l_desc)));
  748. Tracev((stderr, "nlit data: dyn %ld, stat %ld", s->opt_len,
  749. s->static_len));
  750. build_tree(s, (tree_desc *)(&(s->d_desc)));
  751. Tracev((stderr, "ndist data: dyn %ld, stat %ld", s->opt_len,
  752. s->static_len));
  753. /* At this point, opt_len and static_len are the total bit lengths of
  754.  * the compressed block data, excluding the tree representations.
  755.  */
  756. /* Build the bit length tree for the above two trees, and get the index
  757.  * in bl_order of the last bit length code to send.
  758.  */
  759. max_blindex = build_bl_tree(s);
  760. /* Determine the best encoding. Compute first the block length in bytes*/
  761. opt_lenb = (s->opt_len+3+7)>>3;
  762. static_lenb = (s->static_len+3+7)>>3;
  763. Tracev((stderr, "nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  764. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  765. s->last_lit));
  766. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  767.     } else {
  768.         Assert(buf != (char*)0, "lost buf");
  769. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  770.     }
  771.     /* If compression failed and this is the first and last block,
  772.      * and if the .zip file can be seeked (to rewrite the local header),
  773.      * the whole file is transformed into a stored file:
  774.      */
  775. #ifdef STORED_FILE_OK
  776. #  ifdef FORCE_STORED_FILE
  777.     if (eof && s->compressed_len == 0L) { /* force stored file */
  778. #  else
  779.     if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable()) {
  780. #  endif
  781.         /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  782.         if (buf == (charf*)0) error ("block vanished");
  783.         copy_block(s, buf, (unsigned)stored_len, 0); /* without header */
  784.         s->compressed_len = stored_len << 3;
  785.         s->method = STORED;
  786.     } else
  787. #endif /* STORED_FILE_OK */
  788. #ifdef FORCE_STORED
  789.     if (buf != (char*)0) { /* force stored block */
  790. #else
  791.     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  792.                        /* 4: two words for the lengths */
  793. #endif
  794.         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  795.          * Otherwise we can't have processed more than WSIZE input bytes since
  796.          * the last block flush, because compression would have been
  797.          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  798.          * transform a block into a stored block.
  799.          */
  800.         zlib_tr_stored_block(s, buf, stored_len, eof);
  801. #ifdef FORCE_STATIC
  802.     } else if (static_lenb >= 0) { /* force static trees */
  803. #else
  804.     } else if (static_lenb == opt_lenb) {
  805. #endif
  806.         send_bits(s, (STATIC_TREES<<1)+eof, 3);
  807.         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  808.         s->compressed_len += 3 + s->static_len;
  809.     } else {
  810.         send_bits(s, (DYN_TREES<<1)+eof, 3);
  811.         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  812.                        max_blindex+1);
  813.         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  814.         s->compressed_len += 3 + s->opt_len;
  815.     }
  816.     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  817.     init_block(s);
  818.     if (eof) {
  819.         bi_windup(s);
  820.         s->compressed_len += 7;  /* align on byte boundary */
  821.     }
  822.     Tracev((stderr,"ncomprlen %lu(%lu) ", s->compressed_len>>3,
  823.            s->compressed_len-7*eof));
  824.     return s->compressed_len >> 3;
  825. }
  826. /* ===========================================================================
  827.  * Save the match info and tally the frequency counts. Return true if
  828.  * the current block must be flushed.
  829.  */
  830. int zlib_tr_tally (s, dist, lc)
  831.     deflate_state *s;
  832.     unsigned dist;  /* distance of matched string */
  833.     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
  834. {
  835.     s->d_buf[s->last_lit] = (ush)dist;
  836.     s->l_buf[s->last_lit++] = (uch)lc;
  837.     if (dist == 0) {
  838.         /* lc is the unmatched char */
  839.         s->dyn_ltree[lc].Freq++;
  840.     } else {
  841.         s->matches++;
  842.         /* Here, lc is the match length - MIN_MATCH */
  843.         dist--;             /* dist = match distance - 1 */
  844.         Assert((ush)dist < (ush)MAX_DIST(s) &&
  845.                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  846.                (ush)d_code(dist) < (ush)D_CODES,  "zlib_tr_tally: bad match");
  847.         s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
  848.         s->dyn_dtree[d_code(dist)].Freq++;
  849.     }
  850.     /* Try to guess if it is profitable to stop the current block here */
  851.     if ((s->last_lit & 0xfff) == 0 && s->level > 2) {
  852.         /* Compute an upper bound for the compressed length */
  853.         ulg out_length = (ulg)s->last_lit*8L;
  854.         ulg in_length = (ulg)((long)s->strstart - s->block_start);
  855.         int dcode;
  856.         for (dcode = 0; dcode < D_CODES; dcode++) {
  857.             out_length += (ulg)s->dyn_dtree[dcode].Freq *
  858.                 (5L+extra_dbits[dcode]);
  859.         }
  860.         out_length >>= 3;
  861.         Tracev((stderr,"nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  862.                s->last_lit, in_length, out_length,
  863.                100L - out_length*100L/in_length));
  864.         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  865.     }
  866.     return (s->last_lit == s->lit_bufsize-1);
  867.     /* We avoid equality with lit_bufsize because of wraparound at 64K
  868.      * on 16 bit machines and because stored blocks are restricted to
  869.      * 64K-1 bytes.
  870.      */
  871. }
  872. /* ===========================================================================
  873.  * Send the block data compressed using the given Huffman trees
  874.  */
  875. local void compress_block(s, ltree, dtree)
  876.     deflate_state *s;
  877.     ct_data *ltree; /* literal tree */
  878.     ct_data *dtree; /* distance tree */
  879. {
  880.     unsigned dist;      /* distance of matched string */
  881.     int lc;             /* match length or unmatched char (if dist == 0) */
  882.     unsigned lx = 0;    /* running index in l_buf */
  883.     unsigned code;      /* the code to send */
  884.     int extra;          /* number of extra bits to send */
  885.     if (s->last_lit != 0) do {
  886.         dist = s->d_buf[lx];
  887.         lc = s->l_buf[lx++];
  888.         if (dist == 0) {
  889.             send_code(s, lc, ltree); /* send a literal byte */
  890.             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  891.         } else {
  892.             /* Here, lc is the match length - MIN_MATCH */
  893.             code = length_code[lc];
  894.             send_code(s, code+LITERALS+1, ltree); /* send the length code */
  895.             extra = extra_lbits[code];
  896.             if (extra != 0) {
  897.                 lc -= base_length[code];
  898.                 send_bits(s, lc, extra);       /* send the extra length bits */
  899.             }
  900.             dist--; /* dist is now the match distance - 1 */
  901.             code = d_code(dist);
  902.             Assert (code < D_CODES, "bad d_code");
  903.             send_code(s, code, dtree);       /* send the distance code */
  904.             extra = extra_dbits[code];
  905.             if (extra != 0) {
  906.                 dist -= base_dist[code];
  907.                 send_bits(s, dist, extra);   /* send the extra distance bits */
  908.             }
  909.         } /* literal or match pair ? */
  910.         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  911.         Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
  912.     } while (lx < s->last_lit);
  913.     send_code(s, END_BLOCK, ltree);
  914.     s->last_eob_len = ltree[END_BLOCK].Len;
  915. }
  916. /* ===========================================================================
  917.  * Set the data type to ASCII or BINARY, using a crude approximation:
  918.  * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  919.  * IN assertion: the fields freq of dyn_ltree are set and the total of all
  920.  * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  921.  */
  922. local void set_data_type(s)
  923.     deflate_state *s;
  924. {
  925.     int n = 0;
  926.     unsigned ascii_freq = 0;
  927.     unsigned bin_freq = 0;
  928.     while (n < 7)        bin_freq += s->dyn_ltree[n++].Freq;
  929.     while (n < 128)    ascii_freq += s->dyn_ltree[n++].Freq;
  930.     while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
  931.     s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
  932. }
  933. /* ===========================================================================
  934.  * Copy a stored block, storing first the length and its
  935.  * one's complement if requested.
  936.  */
  937. local void copy_block(s, buf, len, header)
  938.     deflate_state *s;
  939.     charf    *buf;    /* the input data */
  940.     unsigned len;     /* its length */
  941.     int      header;  /* true if block header must be written */
  942. {
  943.     bi_windup(s);        /* align on byte boundary */
  944.     s->last_eob_len = 8; /* enough lookahead for inflate */
  945.     if (header) {
  946.         put_short(s, (ush)len);   
  947.         put_short(s, (ush)~len);
  948. #ifdef DEBUG_ZLIB
  949.         s->bits_sent += 2*16;
  950. #endif
  951.     }
  952. #ifdef DEBUG_ZLIB
  953.     s->bits_sent += (ulg)len<<3;
  954. #endif
  955.     /* bundle up the put_byte(s, *buf++) calls */
  956.     memcpy(&s->pending_buf[s->pending], buf, len);
  957.     s->pending += len;
  958. }