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