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