trees.c
上传用户:zlh9724
上传日期:2007-01-04
资源大小:1991k
文件大小:40k
源码类别:

浏览器

开发平台:

Unix_Linux

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