OSDN Git Service

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