home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 March / CMCD0304.ISO / Software / Freeware / Programare / nullsoft / nsis20.exe / Source / zlib / trees.c < prev    next >
C/C++ Source or Header  |  2003-07-12  |  31KB  |  882 lines

  1. /* trees.c -- output deflated data using Huffman coding
  2.  * Copyright (C) 1995-1998 Jean-loup Gailly
  3.  * For conditions of distribution and use, see copyright notice in zlib.h 
  4.  */
  5.  
  6.  
  7. #include "deflate.h"
  8.  
  9. #ifdef DEBUG
  10. #  include <ctype.h>
  11. #endif
  12.  
  13. /* ===========================================================================
  14.  * Constants
  15.  */
  16.  
  17. #define MAX_BL_BITS 7
  18. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19.  
  20. #define END_BLOCK 256
  21. /* end of block literal code */
  22.  
  23. #define REP_3_6      16
  24. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  25.  
  26. #define REPZ_3_10    17
  27. /* repeat a zero length 3-10 times  (3 bits of repeat count) */
  28.  
  29. #define REPZ_11_138  18
  30. /* repeat a zero length 11-138 times  (7 bits of repeat count) */
  31.  
  32. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  33.    = {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};
  34.  
  35. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  36.    = {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};
  37.  
  38. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  39.    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  40.  
  41. local const uch bl_order[BL_CODES]
  42.    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  43. /* The lengths of the bit length codes are sent in order of decreasing
  44.  * probability, to avoid transmitting the lengths for unused bit length codes.
  45.  */
  46.  
  47. #define Buf_size (8 * 2*sizeof(char))
  48.  
  49. #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
  50.  
  51. local ct_data static_ltree[L_CODES+2];
  52.  
  53. local ct_data static_dtree[D_CODES];
  54.  
  55. uch _dist_code[DIST_CODE_LEN];
  56.  
  57. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  58. /* length code for each normalized match length (0 == MIN_MATCH) */
  59.  
  60. local int base_length[LENGTH_CODES];
  61. /* First normalized length for each code (0 = MIN_MATCH) */
  62.  
  63. local int base_dist[D_CODES];
  64. /* First normalized distance for each code (0 = distance of 1) */
  65.  
  66. struct static_tree_desc_s {
  67.     const ct_data *static_tree;  /* static tree or NULL */
  68.     const intf *extra_bits;      /* extra bits for each code or NULL */
  69.     int     extra_base;          /* base index for extra_bits */
  70.     int     elems;               /* max number of elements in the tree */
  71.     int     max_length;          /* max bit length for the codes */
  72. };
  73.  
  74. local static_tree_desc  static_l_desc =
  75. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  76.  
  77. local static_tree_desc  static_d_desc =
  78. {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
  79.  
  80. local static_tree_desc  static_bl_desc =
  81. {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
  82.  
  83. /* ===========================================================================
  84.  * Local (static) routines in this file.
  85.  */
  86.  
  87. local void tr_static_init OF((void));
  88. local void init_block     OF((deflate_state *s));
  89. local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
  90. local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
  91. local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
  92. local void build_tree     OF((deflate_state *s, tree_desc *desc));
  93. local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
  94. local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
  95. local int  build_bl_tree  OF((deflate_state *s));
  96. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  97.                               int blcodes));
  98. local void compress_block OF((deflate_state *s, ct_data *ltree,
  99.                               ct_data *dtree));
  100. local unsigned bi_reverse OF((unsigned value, int length));
  101. local void bi_windup      OF((deflate_state *s));
  102. local void bi_flush       OF((deflate_state *s));
  103. local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
  104.                               int header));
  105.  
  106. #ifdef GEN_TREES_H
  107. local void gen_trees_header OF((void));
  108. #endif
  109.  
  110. #ifndef DEBUG
  111. #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  112.    /* Send a code of the given tree. c and tree must not have side effects */
  113.  
  114. #else /* DEBUG */
  115. #  define send_code(s, c, tree) \
  116.      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  117.        send_bits(s, tree[c].Code, tree[c].Len); }
  118. #endif
  119.  
  120. /* ===========================================================================
  121.  * Output a short LSB first on the stream.
  122.  * IN assertion: there is enough room in pendingBuf.
  123.  */
  124. #define put_short(s, w) { \
  125.     put_byte(s, (uch)((w) & 0xff)); \
  126.     put_byte(s, (uch)((ush)(w) >> 8)); \
  127. }
  128.  
  129. /* ===========================================================================
  130.  * Send a value on a given number of bits.
  131.  * IN assertion: length <= 16 and value fits in length bits.
  132.  */
  133. #ifdef DEBUG
  134. local void send_bits      OF((deflate_state *s, int value, int length));
  135.  
  136. local void send_bits(s, value, length)
  137.     deflate_state *s;
  138.     int value;  /* value to send */
  139.     int length; /* number of bits */
  140. {
  141.     Tracevv((stderr," l %2d v %4x ", length, value));
  142.     Assert(length > 0 && length <= 15, "invalid length");
  143.     s->bits_sent += (ulg)length;
  144.  
  145.     if (s->bi_valid > (int)Buf_size - length) {
  146.         s->bi_buf |= (value << s->bi_valid);
  147.         put_short(s, s->bi_buf);
  148.         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  149.         s->bi_valid += length - Buf_size;
  150.     } else {
  151.         s->bi_buf |= value << s->bi_valid;
  152.         s->bi_valid += length;
  153.     }
  154. }
  155. #else /* !DEBUG */
  156.  
  157. #define send_bits(s, value, length) \
  158. { int len = length;\
  159.   if (s->bi_valid > (int)Buf_size - len) {\
  160.     int val = value;\
  161.     s->bi_buf |= (val << s->bi_valid);\
  162.     put_short(s, s->bi_buf);\
  163.     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  164.     s->bi_valid += len - Buf_size;\
  165.   } else {\
  166.     s->bi_buf |= (value) << s->bi_valid;\
  167.     s->bi_valid += len;\
  168.   }\
  169. }
  170. #endif /* DEBUG */
  171.  
  172.  
  173. #define MAX(a,b) (a >= b ? a : b)
  174. /* the arguments must not have side effects */
  175.  
  176. /* ===========================================================================
  177.  * Initialize the various 'constant' tables.
  178.  */
  179. local void tr_static_init()
  180. {
  181.     static int static_init_done = 0;
  182.     int n;        /* iterates over tree elements */
  183.     int bits;     /* bit counter */
  184.     int length;   /* length value */
  185.     int code;     /* code value */
  186.     int dist;     /* distance index */
  187.     ush bl_count[MAX_BITS+1];
  188.     /* number of codes at each bit length for an optimal tree */
  189.  
  190.     if (static_init_done) return;
  191.  
  192.     /* For some embedded targets, global variables are not initialized: */
  193.     static_l_desc.static_tree = static_ltree;
  194.     static_l_desc.extra_bits = extra_lbits;
  195.     static_d_desc.static_tree = static_dtree;
  196.     static_d_desc.extra_bits = extra_dbits;
  197.     static_bl_desc.extra_bits = extra_blbits;
  198.  
  199.     /* Initialize the mapping length (0..255) -> length code (0..28) */
  200.     length = 0;
  201.     for (code = 0; code < LENGTH_CODES-1; code++) {
  202.         base_length[code] = length;
  203.         for (n = 0; n < (1<<extra_lbits[code]); n++) {
  204.             _length_code[length++] = (uch)code;
  205.         }
  206.     }
  207.     Assert (length == 256, "tr_static_init: length != 256");
  208.     _length_code[length-1] = (uch)code;
  209.  
  210.     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  211.     dist = 0;
  212.     for (code = 0 ; code < 16; code++) {
  213.         base_dist[code] = dist;
  214.         for (n = 0; n < (1<<extra_dbits[code]); n++) {
  215.             _dist_code[dist++] = (uch)code;
  216.         }
  217.     }
  218.     Assert (dist == 256, "tr_static_init: dist != 256");
  219.     dist >>= 7; /* from now on, all distances are divided by 128 */
  220.     for ( ; code < D_CODES; code++) {
  221.         base_dist[code] = dist << 7;
  222.         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  223.             _dist_code[256 + dist++] = (uch)code;
  224.         }
  225.     }
  226.     Assert (dist == 256, "tr_static_init: 256+dist != 512");
  227.  
  228.     /* Construct the codes of the static literal tree */
  229.     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  230.     n = 0;
  231.     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  232.     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  233.     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  234.     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  235.     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  236.  
  237.     /* The static distance tree is trivial: */
  238.     for (n = 0; n < D_CODES; n++) {
  239.         static_dtree[n].Len = 5;
  240.         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  241.     }
  242.     static_init_done = 1;
  243.  
  244. }
  245.  
  246.  
  247. void _tr_init(s)
  248.     deflate_state *s;
  249. {
  250.     tr_static_init();
  251.  
  252.     s->l_desc.dyn_tree = s->dyn_ltree;
  253.     s->l_desc.stat_desc = &static_l_desc;
  254.  
  255.     s->d_desc.dyn_tree = s->dyn_dtree;
  256.     s->d_desc.stat_desc = &static_d_desc;
  257.  
  258.     s->bl_desc.dyn_tree = s->bl_tree;
  259.     s->bl_desc.stat_desc = &static_bl_desc;
  260.  
  261.     s->bi_buf = 0;
  262.     s->bi_valid = 0;
  263.     s->last_eob_len = 8; /* enough lookahead for inflate */
  264. #ifdef DEBUG
  265.     s->compressed_len = 0L;
  266.     s->bits_sent = 0L;
  267. #endif
  268.  
  269.     /* Initialize the first block of the first file: */
  270.     init_block(s);
  271. }
  272.  
  273. local void init_block(s)
  274.     deflate_state *s;
  275. {
  276.     int n; /* iterates over tree elements */
  277.  
  278.     /* Initialize the trees. */
  279.     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
  280.     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
  281.     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  282.  
  283.     s->dyn_ltree[END_BLOCK].Freq = 1;
  284.     s->opt_len = s->static_len = 0L;
  285.     s->last_lit = s->matches = 0;
  286. }
  287.  
  288. #define SMALLEST 1
  289. #define pqremove(s, tree, top) \
  290. {\
  291.     top = s->heap[SMALLEST]; \
  292.     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  293.     pqdownheap(s, tree, SMALLEST); \
  294. }
  295. #define smaller(tree, n, m, depth) \
  296.    (tree[n].Freq < tree[m].Freq || \
  297.    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  298.  
  299. local void pqdownheap(s, tree, k)
  300.     deflate_state *s;
  301.     ct_data *tree;  /* the tree to restore */
  302.     int k;               /* node to move down */
  303. {
  304.     int v = s->heap[k];
  305.     int j = k << 1;  /* left son of k */
  306.     while (j <= s->heap_len) {
  307.         /* Set j to the smallest of the two sons: */
  308.         if (j < s->heap_len &&
  309.             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  310.             j++;
  311.         }
  312.         /* Exit if v is smaller than both sons */
  313.         if (smaller(tree, v, s->heap[j], s->depth)) break;
  314.  
  315.         /* Exchange v with the smallest son */
  316.         s->heap[k] = s->heap[j];  k = j;
  317.  
  318.         /* And continue down the tree, setting j to the left son of k */
  319.         j <<= 1;
  320.     }
  321.     s->heap[k] = v;
  322. }
  323.  
  324. local void gen_bitlen(s, desc)
  325.     deflate_state *s;
  326.     tree_desc *desc;    /* the tree descriptor */
  327. {
  328.     ct_data *tree        = desc->dyn_tree;
  329.     int max_code         = desc->max_code;
  330.     const ct_data *stree = desc->stat_desc->static_tree;
  331.     const intf *extra    = desc->stat_desc->extra_bits;
  332.     int base             = desc->stat_desc->extra_base;
  333.     int max_length       = desc->stat_desc->max_length;
  334.     int h;              /* heap index */
  335.     int n, m;           /* iterate over the tree elements */
  336.     int bits;           /* bit length */
  337.     int xbits;          /* extra bits */
  338.     ush f;              /* frequency */
  339.     int overflow = 0;   /* number of elements with bit length too large */
  340.  
  341.     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  342.  
  343.     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  344.  
  345.     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  346.         n = s->heap[h];
  347.         bits = tree[tree[n].Dad].Len + 1;
  348.         if (bits > max_length) bits = max_length, overflow++;
  349.         tree[n].Len = (ush)bits;
  350.         /* We overwrite tree[n].Dad which is no longer needed */
  351.  
  352.         if (n > max_code) continue; /* not a leaf node */
  353.  
  354.         s->bl_count[bits]++;
  355.         xbits = 0;
  356.         if (n >= base) xbits = extra[n-base];
  357.         f = tree[n].Freq;
  358.         s->opt_len += (ulg)f * (bits + xbits);
  359.         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  360.     }
  361.     if (overflow == 0) return;
  362.  
  363.     Trace((stderr,"\nbit length overflow\n"));
  364.     do {
  365.         bits = max_length-1;
  366.         while (s->bl_count[bits] == 0) bits--;
  367.         s->bl_count[bits]--;      /* move one leaf down the tree */
  368.         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  369.         s->bl_count[max_length]--;
  370.         overflow -= 2;
  371.     } while (overflow > 0);
  372.  
  373.     for (bits = max_length; bits != 0; bits--) {
  374.         n = s->bl_count[bits];
  375.         while (n != 0) {
  376.             m = s->heap[--h];
  377.             if (m > max_code) continue;
  378.             if (tree[m].Len != (unsigned) bits) {
  379.                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  380.                 s->opt_len += ((long)bits - (long)tree[m].Len)
  381.                               *(long)tree[m].Freq;
  382.                 tree[m].Len = (ush)bits;
  383.             }
  384.             n--;
  385.         }
  386.     }
  387. }
  388.  
  389. local void gen_codes (tree, max_code, bl_count)
  390.     ct_data *tree;             /* the tree to decorate */
  391.     int max_code;              /* largest code with non zero frequency */
  392.     ushf *bl_count;            /* number of codes at each bit length */
  393. {
  394.     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  395.     ush code = 0;              /* running code value */
  396.     int bits;                  /* bit index */
  397.     int n;                     /* code index */
  398.  
  399.     for (bits = 1; bits <= MAX_BITS; bits++) {
  400.         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  401.     }
  402.     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  403.             "inconsistent bit counts");
  404.     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  405.  
  406.     for (n = 0;  n <= max_code; n++) {
  407.         int len = tree[n].Len;
  408.         if (len == 0) continue;
  409.         /* Now reverse the bits */
  410.         tree[n].Code = bi_reverse(next_code[len]++, len);
  411.  
  412.         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  413.              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  414.     }
  415. }
  416.  
  417. local void build_tree(s, desc)
  418.     deflate_state *s;
  419.     tree_desc *desc; /* the tree descriptor */
  420. {
  421.     ct_data *tree         = desc->dyn_tree;
  422.     const ct_data *stree  = desc->stat_desc->static_tree;
  423.     int elems             = desc->stat_desc->elems;
  424.     int n, m;          /* iterate over heap elements */
  425.     int max_code = -1; /* largest code with non zero frequency */
  426.     int node;          /* new node being created */
  427.  
  428.     s->heap_len = 0, s->heap_max = HEAP_SIZE;
  429.  
  430.     for (n = 0; n < elems; n++) {
  431.         if (tree[n].Freq != 0) {
  432.             s->heap[++(s->heap_len)] = max_code = n;
  433.             s->depth[n] = 0;
  434.         } else {
  435.             tree[n].Len = 0;
  436.         }
  437.     }
  438.     while (s->heap_len < 2) {
  439.         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  440.         tree[node].Freq = 1;
  441.         s->depth[node] = 0;
  442.         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  443.         /* node is 0 or 1 so it does not have extra bits */
  444.     }
  445.     desc->max_code = max_code;
  446.  
  447.     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  448.  
  449.     node = elems;              /* next internal node of the tree */
  450.     do {
  451.         pqremove(s, tree, n);  /* n = node of least frequency */
  452.         m = s->heap[SMALLEST]; /* m = node of next least frequency */
  453.  
  454.         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  455.         s->heap[--(s->heap_max)] = m;
  456.  
  457.         /* Create a new node father of n and m */
  458.         tree[node].Freq = tree[n].Freq + tree[m].Freq;
  459.         s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
  460.         tree[n].Dad = tree[m].Dad = (ush)node;
  461. #ifdef DUMP_BL_TREE
  462.         if (tree == s->bl_tree) {
  463.             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  464.                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  465.         }
  466. #endif
  467.         /* and insert the new node in the heap */
  468.         s->heap[SMALLEST] = node++;
  469.         pqdownheap(s, tree, SMALLEST);
  470.  
  471.     } while (s->heap_len >= 2);
  472.  
  473.     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  474.  
  475.     gen_bitlen(s, (tree_desc *)desc);
  476.  
  477.     /* The field len is now set, we can generate the bit codes */
  478.     gen_codes ((ct_data *)tree, max_code, s->bl_count);
  479. }
  480.  
  481. local void scan_tree (s, tree, max_code)
  482.     deflate_state *s;
  483.     ct_data *tree;   /* the tree to be scanned */
  484.     int max_code;    /* and its largest code of non zero frequency */
  485. {
  486.     int n;                     /* iterates over all tree elements */
  487.     int prevlen = -1;          /* last emitted length */
  488.     int curlen;                /* length of current code */
  489.     int nextlen = tree[0].Len; /* length of next code */
  490.     int count = 0;             /* repeat count of the current code */
  491.     int max_count = 7;         /* max repeat count */
  492.     int min_count = 4;         /* min repeat count */
  493.  
  494.     if (nextlen == 0) max_count = 138, min_count = 3;
  495.     tree[max_code+1].Len = (ush)0xffff; /* guard */
  496.  
  497.     for (n = 0; n <= max_code; n++) {
  498.         curlen = nextlen; nextlen = tree[n+1].Len;
  499.         if (++count < max_count && curlen == nextlen) {
  500.             continue;
  501.         } else if (count < min_count) {
  502.             s->bl_tree[curlen].Freq += count;
  503.         } else if (curlen != 0) {
  504.             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  505.             s->bl_tree[REP_3_6].Freq++;
  506.         } else if (count <= 10) {
  507.             s->bl_tree[REPZ_3_10].Freq++;
  508.         } else {
  509.             s->bl_tree[REPZ_11_138].Freq++;
  510.         }
  511.         count = 0; prevlen = curlen;
  512.         if (nextlen == 0) {
  513.             max_count = 138, min_count = 3;
  514.         } else if (curlen == nextlen) {
  515.             max_count = 6, min_count = 3;
  516.         } else {
  517.             max_count = 7, min_count = 4;
  518.         }
  519.     }
  520. }
  521.  
  522. local void send_tree (s, tree, max_code)
  523.     deflate_state *s;
  524.     ct_data *tree; /* the tree to be scanned */
  525.     int max_code;       /* and its largest code of non zero frequency */
  526. {
  527.     int n;                     /* iterates over all tree elements */
  528.     int prevlen = -1;          /* last emitted length */
  529.     int curlen;                /* length of current code */
  530.     int nextlen = tree[0].Len; /* length of next code */
  531.     int count = 0;             /* repeat count of the current code */
  532.     int max_count = 7;         /* max repeat count */
  533.     int min_count = 4;         /* min repeat count */
  534.  
  535.     /* tree[max_code+1].Len = -1; */  /* guard already set */
  536.     if (nextlen == 0) max_count = 138, min_count = 3;
  537.  
  538.     for (n = 0; n <= max_code; n++) {
  539.         curlen = nextlen; nextlen = tree[n+1].Len;
  540.         if (++count < max_count && curlen == nextlen) {
  541.             continue;
  542.         } else if (count < min_count) {
  543.             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  544.  
  545.         } else if (curlen != 0) {
  546.             if (curlen != prevlen) {
  547.                 send_code(s, curlen, s->bl_tree); count--;
  548.             }
  549.             Assert(count >= 3 && count <= 6, " 3_6?");
  550.             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  551.  
  552.         } else if (count <= 10) {
  553.             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  554.  
  555.         } else {
  556.             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  557.         }
  558.         count = 0; prevlen = curlen;
  559.         if (nextlen == 0) {
  560.             max_count = 138, min_count = 3;
  561.         } else if (curlen == nextlen) {
  562.             max_count = 6, min_count = 3;
  563.         } else {
  564.             max_count = 7, min_count = 4;
  565.         }
  566.     }
  567. }
  568.  
  569. local int build_bl_tree(s)
  570.     deflate_state *s;
  571. {
  572.     int max_blindex;  /* index of last bit length code of non zero freq */
  573.  
  574.     /* Determine the bit length frequencies for literal and distance trees */
  575.     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  576.     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  577.  
  578.     /* Build the bit length tree: */
  579.     build_tree(s, (tree_desc *)(&(s->bl_desc)));
  580.     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  581.         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  582.     }
  583.     /* Update opt_len to include the bit length tree and counts */
  584.     s->opt_len += 3*(max_blindex+1) + 5+5+4;
  585.     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  586.             s->opt_len, s->static_len));
  587.  
  588.     return max_blindex;
  589. }
  590.  
  591. local void send_all_trees(s, lcodes, dcodes, blcodes)
  592.     deflate_state *s;
  593.     int lcodes, dcodes, blcodes; /* number of codes for each tree */
  594. {
  595.     int rank;                    /* index in bl_order */
  596.  
  597.     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  598.     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  599.             "too many codes");
  600.     Tracev((stderr, "\nbl counts: "));
  601.     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  602.     send_bits(s, dcodes-1,   5);
  603.     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
  604.     for (rank = 0; rank < blcodes; rank++) {
  605.         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  606.         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  607.     }
  608.     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  609.  
  610.     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  611.     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  612.  
  613.     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  614.     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  615. }
  616.  
  617. void _tr_stored_block(s, buf, stored_len, eof)
  618.     deflate_state *s;
  619.     charf *buf;       /* input block */
  620.     ulg stored_len;   /* length of input block */
  621.     int eof;          /* true if this is the last block for a file */
  622. {
  623.     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
  624. #ifdef DEBUG
  625.     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  626.     s->compressed_len += (stored_len + 4) << 3;
  627. #endif
  628.     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  629. }
  630.  
  631. void _tr_align(s)
  632.     deflate_state *s;
  633. {
  634.     send_bits(s, STATIC_TREES<<1, 3);
  635.     send_code(s, END_BLOCK, static_ltree);
  636. #ifdef DEBUG
  637.     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  638. #endif
  639.     bi_flush(s);
  640.     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  641.         send_bits(s, STATIC_TREES<<1, 3);
  642.         send_code(s, END_BLOCK, static_ltree);
  643. #ifdef DEBUG
  644.         s->compressed_len += 10L;
  645. #endif
  646.         bi_flush(s);
  647.     }
  648.     s->last_eob_len = 7;
  649. }
  650.  
  651. void _tr_flush_block(s, buf, stored_len, eof)
  652.     deflate_state *s;
  653.     charf *buf;       /* input block, or NULL if too old */
  654.     ulg stored_len;   /* length of input block */
  655.     int eof;          /* true if this is the last block for a file */
  656. {
  657.     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  658.     int max_blindex = 0;  /* index of last bit length code of non zero freq */
  659.  
  660.     /* Build the Huffman trees unless a stored block is forced */
  661.     if (s->level > 0) {
  662.  
  663.         /* Construct the literal and distance trees */
  664.         build_tree(s, (tree_desc *)(&(s->l_desc)));
  665.         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  666.             s->static_len));
  667.  
  668.         build_tree(s, (tree_desc *)(&(s->d_desc)));
  669.         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  670.             s->static_len));
  671.         max_blindex = build_bl_tree(s);
  672.  
  673.         /* Determine the best encoding. Compute first the block length in bytes*/
  674.         opt_lenb = (s->opt_len+3+7)>>3;
  675.         static_lenb = (s->static_len+3+7)>>3;
  676.  
  677.         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  678.             opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  679.             s->last_lit));
  680.  
  681.         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  682.  
  683.     } else {
  684.         Assert(buf != (char*)0, "lost buf");
  685.         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  686.     }
  687.  
  688. #ifdef FORCE_STORED
  689.     if (buf != (char*)0) { /* force stored block */
  690. #else
  691.     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  692.                        /* 4: two words for the lengths */
  693. #endif
  694.         _tr_stored_block(s, buf, stored_len, eof);
  695.  
  696. #ifdef FORCE_STATIC
  697.     } else if (static_lenb >= 0) { /* force static trees */
  698. #else
  699.     } else if (static_lenb == opt_lenb) {
  700. #endif
  701.         send_bits(s, (STATIC_TREES<<1)+eof, 3);
  702.         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  703. #ifdef DEBUG
  704.         s->compressed_len += 3 + s->static_len;
  705. #endif
  706.     } else {
  707.         send_bits(s, (DYN_TREES<<1)+eof, 3);
  708.         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  709.                        max_blindex+1);
  710.         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  711. #ifdef DEBUG
  712.         s->compressed_len += 3 + s->opt_len;
  713. #endif
  714.     }
  715.     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  716.  
  717.     init_block(s);
  718.  
  719.     if (eof) {
  720.         bi_windup(s);
  721. #ifdef DEBUG
  722.         s->compressed_len += 7;  /* align on byte boundary */
  723. #endif
  724.     }
  725.     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  726.            s->compressed_len-7*eof));
  727. }
  728.  
  729. int _tr_tally (s, dist, lc)
  730.     deflate_state *s;
  731.     unsigned dist;  /* distance of matched string */
  732.     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
  733. {
  734.     s->d_buf[s->last_lit] = (ush)dist;
  735.     s->l_buf[s->last_lit++] = (uch)lc;
  736.     if (dist == 0) {
  737.         /* lc is the unmatched char */
  738.         s->dyn_ltree[lc].Freq++;
  739.     } else {
  740.         s->matches++;
  741.         /* Here, lc is the match length - MIN_MATCH */
  742.         dist--;             /* dist = match distance - 1 */
  743.         Assert((ush)dist < (ush)MAX_DIST(s) &&
  744.                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  745.                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
  746.  
  747.         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  748.         s->dyn_dtree[d_code(dist)].Freq++;
  749.     }
  750.  
  751. #ifdef TRUNCATE_BLOCK
  752.     /* Try to guess if it is profitable to stop the current block here */
  753.     if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  754.         /* Compute an upper bound for the compressed length */
  755.         ulg out_length = (ulg)s->last_lit*8L;
  756.         ulg in_length = (ulg)((long)s->strstart - s->block_start);
  757.         int dcode;
  758.         for (dcode = 0; dcode < D_CODES; dcode++) {
  759.             out_length += (ulg)s->dyn_dtree[dcode].Freq *
  760.                 (5L+extra_dbits[dcode]);
  761.         }
  762.         out_length >>= 3;
  763.         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  764.                s->last_lit, in_length, out_length,
  765.                100L - out_length*100L/in_length));
  766.         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  767.     }
  768. #endif
  769.     return (s->last_lit == s->lit_bufsize-1);
  770. }
  771.  
  772. local void compress_block(s, ltree, dtree)
  773.     deflate_state *s;
  774.     ct_data *ltree; /* literal tree */
  775.     ct_data *dtree; /* distance tree */
  776. {
  777.     unsigned dist;      /* distance of matched string */
  778.     int lc;             /* match length or unmatched char (if dist == 0) */
  779.     unsigned lx = 0;    /* running index in l_buf */
  780.     unsigned code;      /* the code to send */
  781.     int extra;          /* number of extra bits to send */
  782.  
  783.     if (s->last_lit != 0) do {
  784.         dist = s->d_buf[lx];
  785.         lc = s->l_buf[lx++];
  786.         if (dist == 0) {
  787.             send_code(s, lc, ltree); /* send a literal byte */
  788.             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  789.         } else {
  790.             /* Here, lc is the match length - MIN_MATCH */
  791.             code = _length_code[lc];
  792.             send_code(s, code+LITERALS+1, ltree); /* send the length code */
  793.             extra = extra_lbits[code];
  794.             if (extra != 0) {
  795.                 lc -= base_length[code];
  796.                 send_bits(s, lc, extra);       /* send the extra length bits */
  797.             }
  798.             dist--; /* dist is now the match distance - 1 */
  799.             code = d_code(dist);
  800.             Assert (code < D_CODES, "bad d_code");
  801.  
  802.             send_code(s, code, dtree);       /* send the distance code */
  803.             extra = extra_dbits[code];
  804.             if (extra != 0) {
  805.                 dist -= base_dist[code];
  806.                 send_bits(s, dist, extra);   /* send the extra distance bits */
  807.             }
  808.         } /* literal or match pair ? */
  809.  
  810.         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  811.         Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
  812.  
  813.     } while (lx < s->last_lit);
  814.  
  815.     send_code(s, END_BLOCK, ltree);
  816.     s->last_eob_len = ltree[END_BLOCK].Len;
  817. }
  818.  
  819. local unsigned bi_reverse(code, len)
  820.     unsigned code; /* the value to invert */
  821.     int len;       /* its bit length */
  822. {
  823.     register unsigned res = 0;
  824.     do {
  825.         res |= code & 1;
  826.         code >>= 1, res <<= 1;
  827.     } while (--len > 0);
  828.     return res >> 1;
  829. }
  830.  
  831. local void bi_flush(s)
  832.     deflate_state *s;
  833. {
  834.     if (s->bi_valid == 16) {
  835.         put_short(s, s->bi_buf);
  836.         s->bi_buf = 0;
  837.         s->bi_valid = 0;
  838.     } else if (s->bi_valid >= 8) {
  839.         put_byte(s, (Byte)s->bi_buf);
  840.         s->bi_buf >>= 8;
  841.         s->bi_valid -= 8;
  842.     }
  843. }
  844.  
  845. local void bi_windup(s)
  846.     deflate_state *s;
  847. {
  848.     if (s->bi_valid > 8) {
  849.         put_short(s, s->bi_buf);
  850.     } else if (s->bi_valid > 0) {
  851.         put_byte(s, (Byte)s->bi_buf);
  852.     }
  853.     s->bi_buf = 0;
  854.     s->bi_valid = 0;
  855. #ifdef DEBUG
  856.     s->bits_sent = (s->bits_sent+7) & ~7;
  857. #endif
  858. }
  859.  
  860. local void copy_block(s, buf, len, header)
  861.     deflate_state *s;
  862.     charf    *buf;    /* the input data */
  863.     unsigned len;     /* its length */
  864.     int      header;  /* true if block header must be written */
  865. {
  866.     bi_windup(s);        /* align on byte boundary */
  867.     s->last_eob_len = 8; /* enough lookahead for inflate */
  868.  
  869.     if (header) {
  870.         put_short(s, (ush)len);   
  871. #ifdef DEBUG
  872.         s->bits_sent += 2*16;
  873. #endif
  874.     }
  875. #ifdef DEBUG
  876.     s->bits_sent += (ulg)len<<3;
  877. #endif
  878.     while (len--) {
  879.         put_byte(s, *buf++);
  880.     }
  881. }
  882.