1/*
2  Copyright (c) 1990-2006 Info-ZIP.  All rights reserved.
3
4  See the accompanying file LICENSE, version 2005-Feb-10 or later
5  (the contents of which are also included in zip.h) for terms of use.
6  If, for some reason, all these files are missing, the Info-ZIP license
7  also may be found at:  ftp://ftp.info-zip.org/pub/infozip/license.html
8*/
9/*
10 *  trees.c by Jean-loup Gailly
11 *
12 *  This is a new version of im_ctree.c originally written by Richard B. Wales
13 *  for the defunct implosion method.
14 *  The low level bit string handling routines from bits.c (originally
15 *  im_bits.c written by Richard B. Wales) have been merged into this version
16 *  of trees.c.
17 *
18 *  PURPOSE
19 *
20 *      Encode various sets of source values using variable-length
21 *      binary code trees.
22 *      Output the resulting variable-length bit strings.
23 *      Compression can be done to a file or to memory.
24 *
25 *  DISCUSSION
26 *
27 *      The PKZIP "deflation" process uses several Huffman trees. The more
28 *      common source values are represented by shorter bit sequences.
29 *
30 *      Each code tree is stored in the ZIP file in a compressed form
31 *      which is itself a Huffman encoding of the lengths of
32 *      all the code strings (in ascending order by source values).
33 *      The actual code strings are reconstructed from the lengths in
34 *      the UNZIP process, as described in the "application note"
35 *      (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
36 *
37 *      The PKZIP "deflate" file format interprets compressed file data
38 *      as a sequence of bits.  Multi-bit strings in the file may cross
39 *      byte boundaries without restriction.
40 *      The first bit of each byte is the low-order bit.
41 *
42 *      The routines in this file allow a variable-length bit value to
43 *      be output right-to-left (useful for literal values). For
44 *      left-to-right output (useful for code strings from the tree routines),
45 *      the bits must have been reversed first with bi_reverse().
46 *
47 *      For in-memory compression, the compressed bit stream goes directly
48 *      into the requested output buffer. The buffer is limited to 64K on
49 *      16 bit machines; flushing of the output buffer during compression
50 *      process is not supported.
51 *      The input data is read in blocks by the (*read_buf)() function.
52 *
53 *      For more details about input to and output from the deflation routines,
54 *      see the actual input functions for (*read_buf)(), flush_outbuf(), and
55 *      the filecompress() resp. memcompress() wrapper functions which handle
56 *      the I/O setup.
57 *
58 *  REFERENCES
59 *
60 *      Lynch, Thomas J.
61 *          Data Compression:  Techniques and Applications, pp. 53-55.
62 *          Lifetime Learning Publications, 1985.  ISBN 0-534-03418-7.
63 *
64 *      Storer, James A.
65 *          Data Compression:  Methods and Theory, pp. 49-50.
66 *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
67 *
68 *      Sedgewick, R.
69 *          Algorithms, p290.
70 *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
71 *
72 *  INTERFACE
73 *
74 *      void ct_init (ush *attr, int *method)
75 *          Allocate the match buffer, initialize the various tables and save
76 *          the location of the internal file attribute (ascii/binary) and
77 *          method (DEFLATE/STORE)
78 *
79 *      void ct_tally (int dist, int lc);
80 *          Save the match info and tally the frequency counts.
81 *
82 *      ulg flush_block (char *buf, ulg stored_len, int eof)
83 *          Determine the best encoding for the current block: dynamic trees,
84 *          static trees or store, and output the encoded block to the zip
85 *          file. Returns the total compressed length for the file so far.
86 *
87 *      void bi_init (char *tgt_buf, unsigned tgt_size, int flsh_allowed)
88 *          Initialize the bit string routines.
89 *
90 *    Most of the bit string output functions are only used internally
91 *    in this source file, they are normally declared as "local" routines:
92 *
93 *      local void send_bits (int value, int length)
94 *          Write out a bit string, taking the source bits right to
95 *          left.
96 *
97 *      local unsigned bi_reverse (unsigned code, int len)
98 *          Reverse the bits of a bit string, taking the source bits left to
99 *          right and emitting them right to left.
100 *
101 *      local void bi_windup (void)
102 *          Write out any remaining bits in an incomplete byte.
103 *
104 *      local void copy_block(char *buf, unsigned len, int header)
105 *          Copy a stored block to the zip file, storing first the length and
106 *          its one's complement if requested.
107 *
108 *    All output that exceeds the bitstring output buffer size (as initialized
109 *    by bi_init() is fed through an externally provided transfer routine
110 *    which flushes the bitstring output buffer on request and resets the
111 *    buffer fill counter:
112 *
113 *      extern void flush_outbuf(char *o_buf, unsigned *o_idx);
114 *
115 */
116#define __TREES_C
117
118#include "zip.h"
119#include <ctype.h>
120
121#ifndef USE_ZLIB
122
123/* ===========================================================================
124 * Constants
125 */
126
127#define MAX_BITS 15
128/* All codes must not exceed MAX_BITS bits */
129
130#define MAX_BL_BITS 7
131/* Bit length codes must not exceed MAX_BL_BITS bits */
132
133#define LENGTH_CODES 29
134/* number of length codes, not counting the special END_BLOCK code */
135
136#define LITERALS  256
137/* number of literal bytes 0..255 */
138
139#define END_BLOCK 256
140/* end of block literal code */
141
142#define L_CODES (LITERALS+1+LENGTH_CODES)
143/* number of Literal or Length codes, including the END_BLOCK code */
144
145#define D_CODES   30
146/* number of distance codes */
147
148#define BL_CODES  19
149/* number of codes used to transfer the bit lengths */
150
151
152local int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */
153   = {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};
154
155local int near extra_dbits[D_CODES] /* extra bits for each distance code */
156   = {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};
157
158local int near extra_blbits[BL_CODES]/* extra bits for each bit length code */
159   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
160
161#define STORED_BLOCK 0
162#define STATIC_TREES 1
163#define DYN_TREES    2
164/* The three kinds of block type */
165
166#ifndef LIT_BUFSIZE
167#  ifdef SMALL_MEM
168#    define LIT_BUFSIZE  0x2000
169#  else
170#  ifdef MEDIUM_MEM
171#    define LIT_BUFSIZE  0x4000
172#  else
173#    define LIT_BUFSIZE  0x8000
174#  endif
175#  endif
176#endif
177#define DIST_BUFSIZE  LIT_BUFSIZE
178/* Sizes of match buffers for literals/lengths and distances.  There are
179 * 4 reasons for limiting LIT_BUFSIZE to 64K:
180 *   - frequencies can be kept in 16 bit counters
181 *   - if compression is not successful for the first block, all input data is
182 *     still in the window so we can still emit a stored block even when input
183 *     comes from standard input.  (This can also be done for all blocks if
184 *     LIT_BUFSIZE is not greater than 32K.)
185 *   - if compression is not successful for a file smaller than 64K, we can
186 *     even emit a stored file instead of a stored block (saving 5 bytes).
187 *   - creating new Huffman trees less frequently may not provide fast
188 *     adaptation to changes in the input data statistics. (Take for
189 *     example a binary file with poorly compressible code followed by
190 *     a highly compressible string table.) Smaller buffer sizes give
191 *     fast adaptation but have of course the overhead of transmitting trees
192 *     more frequently.
193 *   - I can't count above 4
194 * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
195 * memory at the expense of compression). Some optimizations would be possible
196 * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
197 */
198
199#define REP_3_6      16
200/* repeat previous bit length 3-6 times (2 bits of repeat count) */
201
202#define REPZ_3_10    17
203/* repeat a zero length 3-10 times  (3 bits of repeat count) */
204
205#define REPZ_11_138  18
206/* repeat a zero length 11-138 times  (7 bits of repeat count) */
207
208/* ===========================================================================
209 * Local data
210 */
211
212/* Data structure describing a single value and its code string. */
213typedef struct ct_data {
214    union {
215        ush  freq;       /* frequency count */
216        ush  code;       /* bit string */
217    } fc;
218    union {
219        ush  dad;        /* father node in Huffman tree */
220        ush  len;        /* length of bit string */
221    } dl;
222} ct_data;
223
224#define Freq fc.freq
225#define Code fc.code
226#define Dad  dl.dad
227#define Len  dl.len
228
229#define HEAP_SIZE (2*L_CODES+1)
230/* maximum heap size */
231
232local ct_data near dyn_ltree[HEAP_SIZE];   /* literal and length tree */
233local ct_data near dyn_dtree[2*D_CODES+1]; /* distance tree */
234
235local ct_data near static_ltree[L_CODES+2];
236/* The static literal tree. Since the bit lengths are imposed, there is no
237 * need for the L_CODES extra codes used during heap construction. However
238 * The codes 286 and 287 are needed to build a canonical tree (see ct_init
239 * below).
240 */
241
242local ct_data near static_dtree[D_CODES];
243/* The static distance tree. (Actually a trivial tree since all codes use
244 * 5 bits.)
245 */
246
247local ct_data near bl_tree[2*BL_CODES+1];
248/* Huffman tree for the bit lengths */
249
250typedef struct tree_desc {
251    ct_data near *dyn_tree;      /* the dynamic tree */
252    ct_data near *static_tree;   /* corresponding static tree or NULL */
253    int     near *extra_bits;    /* extra bits for each code or NULL */
254    int     extra_base;          /* base index for extra_bits */
255    int     elems;               /* max number of elements in the tree */
256    int     max_length;          /* max bit length for the codes */
257    int     max_code;            /* largest code with non zero frequency */
258} tree_desc;
259
260local tree_desc near l_desc =
261{dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0};
262
263local tree_desc near d_desc =
264{dyn_dtree, static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS, 0};
265
266local tree_desc near bl_desc =
267{bl_tree, NULL,       extra_blbits, 0,         BL_CODES, MAX_BL_BITS, 0};
268
269
270local ush near bl_count[MAX_BITS+1];
271/* number of codes at each bit length for an optimal tree */
272
273local uch near bl_order[BL_CODES]
274   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
275/* The lengths of the bit length codes are sent in order of decreasing
276 * probability, to avoid transmitting the lengths for unused bit length codes.
277 */
278
279local int near heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
280local int heap_len;               /* number of elements in the heap */
281local int heap_max;               /* element of largest frequency */
282/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
283 * The same heap array is used to build all trees.
284 */
285
286local uch near depth[2*L_CODES+1];
287/* Depth of each subtree used as tie breaker for trees of equal frequency */
288
289local uch length_code[MAX_MATCH-MIN_MATCH+1];
290/* length code for each normalized match length (0 == MIN_MATCH) */
291
292local uch dist_code[512];
293/* distance codes. The first 256 values correspond to the distances
294 * 3 .. 258, the last 256 values correspond to the top 8 bits of
295 * the 15 bit distances.
296 */
297
298local int near base_length[LENGTH_CODES];
299/* First normalized length for each code (0 = MIN_MATCH) */
300
301local int near base_dist[D_CODES];
302/* First normalized distance for each code (0 = distance of 1) */
303
304#ifndef DYN_ALLOC
305  local uch far l_buf[LIT_BUFSIZE];  /* buffer for literals/lengths */
306  local ush far d_buf[DIST_BUFSIZE]; /* buffer for distances */
307#else
308  local uch far *l_buf;
309  local ush far *d_buf;
310#endif
311
312local uch near flag_buf[(LIT_BUFSIZE/8)];
313/* flag_buf is a bit array distinguishing literals from lengths in
314 * l_buf, and thus indicating the presence or absence of a distance.
315 */
316
317local unsigned last_lit;    /* running index in l_buf */
318local unsigned last_dist;   /* running index in d_buf */
319local unsigned last_flags;  /* running index in flag_buf */
320local uch flags;            /* current flags not yet saved in flag_buf */
321local uch flag_bit;         /* current bit used in flags */
322/* bits are filled in flags starting at bit 0 (least significant).
323 * Note: these flags are overkill in the current code since we don't
324 * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
325 */
326
327local ulg opt_len;        /* bit length of current block with optimal trees */
328local ulg static_len;     /* bit length of current block with static trees */
329
330local ulg cmpr_bytelen;     /* total byte length of compressed file */
331local ulg cmpr_len_bits;    /* number of bits past 'cmpr_bytelen' */
332
333#ifdef DEBUG
334local ulg input_len;        /* total byte length of input file */
335/* input_len is for debugging only since we can get it by other means. */
336#endif
337
338local ush *file_type;       /* pointer to UNKNOWN, BINARY or ASCII */
339local int *file_method;     /* pointer to DEFLATE or STORE */
340
341/* ===========================================================================
342 * Local data used by the "bit string" routines.
343 */
344
345local int flush_flg;
346
347#if (!defined(ASMV) || !defined(RISCOS))
348local unsigned bi_buf;
349#else
350unsigned bi_buf;
351#endif
352/* Output buffer. bits are inserted starting at the bottom (least significant
353 * bits). The width of bi_buf must be at least 16 bits.
354 */
355
356#define Buf_size (8 * 2*sizeof(char))
357/* Number of bits used within bi_buf. (bi_buf may be implemented on
358 * more than 16 bits on some systems.)
359 */
360
361#if (!defined(ASMV) || !defined(RISCOS))
362local int bi_valid;
363#else
364int bi_valid;
365#endif
366/* Number of valid bits in bi_buf.  All bits above the last valid bit
367 * are always zero.
368 */
369
370#if (!defined(ASMV) || !defined(RISCOS))
371local char *out_buf;
372#else
373char *out_buf;
374#endif
375/* Current output buffer. */
376
377#if (!defined(ASMV) || !defined(RISCOS))
378local unsigned out_offset;
379#else
380unsigned out_offset;
381#endif
382/* Current offset in output buffer.
383 * On 16 bit machines, the buffer is limited to 64K.
384 */
385
386#if !defined(ASMV) || !defined(RISCOS)
387local unsigned out_size;
388#else
389unsigned out_size;
390#endif
391/* Size of current output buffer */
392
393/* Output a 16 bit value to the bit stream, lower (oldest) byte first */
394#define PUTSHORT(w) \
395{ if (out_offset >= out_size-1) \
396    flush_outbuf(out_buf, &out_offset); \
397  out_buf[out_offset++] = (char) ((w) & 0xff); \
398  out_buf[out_offset++] = (char) ((ush)(w) >> 8); \
399}
400
401#define PUTBYTE(b) \
402{ if (out_offset >= out_size) \
403    flush_outbuf(out_buf, &out_offset); \
404  out_buf[out_offset++] = (char) (b); \
405}
406
407#ifdef DEBUG
408local ulg bits_sent;   /* bit length of the compressed data */
409extern ulg isize;      /* byte length of input file */
410#endif
411
412extern long block_start;       /* window offset of current block */
413extern unsigned near strstart; /* window offset of current string */
414
415
416/* ===========================================================================
417 * Local (static) routines in this file.
418 */
419
420local void init_block     OF((void));
421local void pqdownheap     OF((ct_data near *tree, int k));
422local void gen_bitlen     OF((tree_desc near *desc));
423local void gen_codes      OF((ct_data near *tree, int max_code));
424local void build_tree     OF((tree_desc near *desc));
425local void scan_tree      OF((ct_data near *tree, int max_code));
426local void send_tree      OF((ct_data near *tree, int max_code));
427local int  build_bl_tree  OF((void));
428local void send_all_trees OF((int lcodes, int dcodes, int blcodes));
429local void compress_block OF((ct_data near *ltree, ct_data near *dtree));
430local void set_file_type  OF((void));
431#if (!defined(ASMV) || !defined(RISCOS))
432local void send_bits      OF((int value, int length));
433local unsigned bi_reverse OF((unsigned code, int len));
434#endif
435local void bi_windup      OF((void));
436local void copy_block     OF((char *buf, unsigned len, int header));
437
438
439#ifndef DEBUG
440#  define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
441   /* Send a code of the given tree. c and tree must not have side effects */
442
443#else /* DEBUG */
444#  define send_code(c, tree) \
445     { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
446       send_bits(tree[c].Code, tree[c].Len); }
447#endif
448
449#define d_code(dist) \
450   ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
451/* Mapping from a distance to a distance code. dist is the distance - 1 and
452 * must not have side effects. dist_code[256] and dist_code[257] are never
453 * used.
454 */
455
456#define Max(a,b) (a >= b ? a : b)
457/* the arguments must not have side effects */
458
459/* ===========================================================================
460 * Allocate the match buffer, initialize the various tables and save the
461 * location of the internal file attribute (ascii/binary) and method
462 * (DEFLATE/STORE).
463 */
464void ct_init(attr, method)
465    ush  *attr;   /* pointer to internal file attribute */
466    int  *method; /* pointer to compression method */
467{
468    int n;        /* iterates over tree elements */
469    int bits;     /* bit counter */
470    int length;   /* length value */
471    int code;     /* code value */
472    int dist;     /* distance index */
473
474    file_type = attr;
475    file_method = method;
476    cmpr_bytelen = cmpr_len_bits = 0L;
477#ifdef DEBUG
478    input_len = 0L;
479#endif
480
481    if (static_dtree[0].Len != 0) return; /* ct_init already called */
482
483#ifdef DYN_ALLOC
484    d_buf = (ush far *) zcalloc(DIST_BUFSIZE, sizeof(ush));
485    l_buf = (uch far *) zcalloc(LIT_BUFSIZE/2, 2);
486    /* Avoid using the value 64K on 16 bit machines */
487    if (l_buf == NULL || d_buf == NULL)
488        ziperr(ZE_MEM, "ct_init: out of memory");
489#endif
490
491    /* Initialize the mapping length (0..255) -> length code (0..28) */
492    length = 0;
493    for (code = 0; code < LENGTH_CODES-1; code++) {
494        base_length[code] = length;
495        for (n = 0; n < (1<<extra_lbits[code]); n++) {
496            length_code[length++] = (uch)code;
497        }
498    }
499    Assert(length == 256, "ct_init: length != 256");
500    /* Note that the length 255 (match length 258) can be represented
501     * in two different ways: code 284 + 5 bits or code 285, so we
502     * overwrite length_code[255] to use the best encoding:
503     */
504    length_code[length-1] = (uch)code;
505
506    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
507    dist = 0;
508    for (code = 0 ; code < 16; code++) {
509        base_dist[code] = dist;
510        for (n = 0; n < (1<<extra_dbits[code]); n++) {
511            dist_code[dist++] = (uch)code;
512        }
513    }
514    Assert(dist == 256, "ct_init: dist != 256");
515    dist >>= 7; /* from now on, all distances are divided by 128 */
516    for ( ; code < D_CODES; code++) {
517        base_dist[code] = dist << 7;
518        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
519            dist_code[256 + dist++] = (uch)code;
520        }
521    }
522    Assert(dist == 256, "ct_init: 256+dist != 512");
523
524    /* Construct the codes of the static literal tree */
525    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
526    n = 0;
527    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
528    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
529    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
530    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
531    /* Codes 286 and 287 do not exist, but we must include them in the
532     * tree construction to get a canonical Huffman tree (longest code
533     * all ones)
534     */
535    gen_codes((ct_data near *)static_ltree, L_CODES+1);
536
537    /* The static distance tree is trivial: */
538    for (n = 0; n < D_CODES; n++) {
539        static_dtree[n].Len = 5;
540        static_dtree[n].Code = (ush)bi_reverse(n, 5);
541    }
542
543    /* Initialize the first block of the first file: */
544    init_block();
545}
546
547/* ===========================================================================
548 * Initialize a new block.
549 */
550local void init_block()
551{
552    int n; /* iterates over tree elements */
553
554    /* Initialize the trees. */
555    for (n = 0; n < L_CODES;  n++) dyn_ltree[n].Freq = 0;
556    for (n = 0; n < D_CODES;  n++) dyn_dtree[n].Freq = 0;
557    for (n = 0; n < BL_CODES; n++) bl_tree[n].Freq = 0;
558
559    dyn_ltree[END_BLOCK].Freq = 1;
560    opt_len = static_len = 0L;
561    last_lit = last_dist = last_flags = 0;
562    flags = 0; flag_bit = 1;
563}
564
565#define SMALLEST 1
566/* Index within the heap array of least frequent node in the Huffman tree */
567
568
569/* ===========================================================================
570 * Remove the smallest element from the heap and recreate the heap with
571 * one less element. Updates heap and heap_len.
572 */
573#define pqremove(tree, top) \
574{\
575    top = heap[SMALLEST]; \
576    heap[SMALLEST] = heap[heap_len--]; \
577    pqdownheap(tree, SMALLEST); \
578}
579
580/* ===========================================================================
581 * Compares to subtrees, using the tree depth as tie breaker when
582 * the subtrees have equal frequency. This minimizes the worst case length.
583 */
584#define smaller(tree, n, m) \
585   (tree[n].Freq < tree[m].Freq || \
586   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
587
588/* ===========================================================================
589 * Restore the heap property by moving down the tree starting at node k,
590 * exchanging a node with the smallest of its two sons if necessary, stopping
591 * when the heap property is re-established (each father smaller than its
592 * two sons).
593 */
594local void pqdownheap(tree, k)
595    ct_data near *tree;  /* the tree to restore */
596    int k;               /* node to move down */
597{
598    int v = heap[k];
599    int j = k << 1;  /* left son of k */
600    int htemp;       /* required because of bug in SASC compiler */
601
602    while (j <= heap_len) {
603        /* Set j to the smallest of the two sons: */
604        if (j < heap_len && smaller(tree, heap[j+1], heap[j])) j++;
605
606        /* Exit if v is smaller than both sons */
607        htemp = heap[j];
608        if (smaller(tree, v, htemp)) break;
609
610        /* Exchange v with the smallest son */
611        heap[k] = htemp;
612        k = j;
613
614        /* And continue down the tree, setting j to the left son of k */
615        j <<= 1;
616    }
617    heap[k] = v;
618}
619
620/* ===========================================================================
621 * Compute the optimal bit lengths for a tree and update the total bit length
622 * for the current block.
623 * IN assertion: the fields freq and dad are set, heap[heap_max] and
624 *    above are the tree nodes sorted by increasing frequency.
625 * OUT assertions: the field len is set to the optimal bit length, the
626 *     array bl_count contains the frequencies for each bit length.
627 *     The length opt_len is updated; static_len is also updated if stree is
628 *     not null.
629 */
630local void gen_bitlen(desc)
631    tree_desc near *desc; /* the tree descriptor */
632{
633    ct_data near *tree  = desc->dyn_tree;
634    int near *extra     = desc->extra_bits;
635    int base            = desc->extra_base;
636    int max_code        = desc->max_code;
637    int max_length      = desc->max_length;
638    ct_data near *stree = desc->static_tree;
639    int h;              /* heap index */
640    int n, m;           /* iterate over the tree elements */
641    int bits;           /* bit length */
642    int xbits;          /* extra bits */
643    ush f;              /* frequency */
644    int overflow = 0;   /* number of elements with bit length too large */
645
646    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
647
648    /* In a first pass, compute the optimal bit lengths (which may
649     * overflow in the case of the bit length tree).
650     */
651    tree[heap[heap_max]].Len = 0; /* root of the heap */
652
653    for (h = heap_max+1; h < HEAP_SIZE; h++) {
654        n = heap[h];
655        bits = tree[tree[n].Dad].Len + 1;
656        if (bits > max_length) bits = max_length, overflow++;
657        tree[n].Len = (ush)bits;
658        /* We overwrite tree[n].Dad which is no longer needed */
659
660        if (n > max_code) continue; /* not a leaf node */
661
662        bl_count[bits]++;
663        xbits = 0;
664        if (n >= base) xbits = extra[n-base];
665        f = tree[n].Freq;
666        opt_len += (ulg)f * (bits + xbits);
667        if (stree) static_len += (ulg)f * (stree[n].Len + xbits);
668    }
669    if (overflow == 0) return;
670
671    Trace((stderr,"\nbit length overflow\n"));
672    /* This happens for example on obj2 and pic of the Calgary corpus */
673
674    /* Find the first bit length which could increase: */
675    do {
676        bits = max_length-1;
677        while (bl_count[bits] == 0) bits--;
678        bl_count[bits]--;           /* move one leaf down the tree */
679        bl_count[bits+1] += (ush)2; /* move one overflow item as its brother */
680        bl_count[max_length]--;
681        /* The brother of the overflow item also moves one step up,
682         * but this does not affect bl_count[max_length]
683         */
684        overflow -= 2;
685    } while (overflow > 0);
686
687    /* Now recompute all bit lengths, scanning in increasing frequency.
688     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
689     * lengths instead of fixing only the wrong ones. This idea is taken
690     * from 'ar' written by Haruhiko Okumura.)
691     */
692    for (bits = max_length; bits != 0; bits--) {
693        n = bl_count[bits];
694        while (n != 0) {
695            m = heap[--h];
696            if (m > max_code) continue;
697            if (tree[m].Len != (ush)bits) {
698                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
699                opt_len += ((long)bits-(long)tree[m].Len)*(long)tree[m].Freq;
700                tree[m].Len = (ush)bits;
701            }
702            n--;
703        }
704    }
705}
706
707/* ===========================================================================
708 * Generate the codes for a given tree and bit counts (which need not be
709 * optimal).
710 * IN assertion: the array bl_count contains the bit length statistics for
711 * the given tree and the field len is set for all tree elements.
712 * OUT assertion: the field code is set for all tree elements of non
713 *     zero code length.
714 */
715local void gen_codes (tree, max_code)
716    ct_data near *tree;        /* the tree to decorate */
717    int max_code;              /* largest code with non zero frequency */
718{
719    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
720    ush code = 0;              /* running code value */
721    int bits;                  /* bit index */
722    int n;                     /* code index */
723
724    /* The distribution counts are first used to generate the code values
725     * without bit reversal.
726     */
727    for (bits = 1; bits <= MAX_BITS; bits++) {
728        next_code[bits] = code = (ush)((code + bl_count[bits-1]) << 1);
729    }
730    /* Check that the bit counts in bl_count are consistent. The last code
731     * must be all ones.
732     */
733    Assert(code + bl_count[MAX_BITS]-1 == (1<< ((ush) MAX_BITS)) - 1,
734            "inconsistent bit counts");
735    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
736
737    for (n = 0;  n <= max_code; n++) {
738        int len = tree[n].Len;
739        if (len == 0) continue;
740        /* Now reverse the bits */
741        tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
742
743        Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
744             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
745    }
746}
747
748/* ===========================================================================
749 * Construct one Huffman tree and assigns the code bit strings and lengths.
750 * Update the total bit length for the current block.
751 * IN assertion: the field freq is set for all tree elements.
752 * OUT assertions: the fields len and code are set to the optimal bit length
753 *     and corresponding code. The length opt_len is updated; static_len is
754 *     also updated if stree is not null. The field max_code is set.
755 */
756local void build_tree(desc)
757    tree_desc near *desc; /* the tree descriptor */
758{
759    ct_data near *tree   = desc->dyn_tree;
760    ct_data near *stree  = desc->static_tree;
761    int elems            = desc->elems;
762    int n, m;          /* iterate over heap elements */
763    int max_code = -1; /* largest code with non zero frequency */
764    int node = elems;  /* next internal node of the tree */
765
766    /* Construct the initial heap, with least frequent element in
767     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
768     * heap[0] is not used.
769     */
770    heap_len = 0, heap_max = HEAP_SIZE;
771
772    for (n = 0; n < elems; n++) {
773        if (tree[n].Freq != 0) {
774            heap[++heap_len] = max_code = n;
775            depth[n] = 0;
776        } else {
777            tree[n].Len = 0;
778        }
779    }
780
781    /* The pkzip format requires that at least one distance code exists,
782     * and that at least one bit should be sent even if there is only one
783     * possible code. So to avoid special checks later on we force at least
784     * two codes of non zero frequency.
785     */
786    while (heap_len < 2) {
787        int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
788        tree[new].Freq = 1;
789        depth[new] = 0;
790        opt_len--; if (stree) static_len -= stree[new].Len;
791        /* new is 0 or 1 so it does not have extra bits */
792    }
793    desc->max_code = max_code;
794
795    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
796     * establish sub-heaps of increasing lengths:
797     */
798    for (n = heap_len/2; n >= 1; n--) pqdownheap(tree, n);
799
800    /* Construct the Huffman tree by repeatedly combining the least two
801     * frequent nodes.
802     */
803    do {
804        pqremove(tree, n);   /* n = node of least frequency */
805        m = heap[SMALLEST];  /* m = node of next least frequency */
806
807        heap[--heap_max] = n; /* keep the nodes sorted by frequency */
808        heap[--heap_max] = m;
809
810        /* Create a new node father of n and m */
811        tree[node].Freq = (ush)(tree[n].Freq + tree[m].Freq);
812        depth[node] = (uch) (Max(depth[n], depth[m]) + 1);
813        tree[n].Dad = tree[m].Dad = (ush)node;
814#ifdef DUMP_BL_TREE
815        if (tree == bl_tree) {
816            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
817                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
818        }
819#endif
820        /* and insert the new node in the heap */
821        heap[SMALLEST] = node++;
822        pqdownheap(tree, SMALLEST);
823
824    } while (heap_len >= 2);
825
826    heap[--heap_max] = heap[SMALLEST];
827
828    /* At this point, the fields freq and dad are set. We can now
829     * generate the bit lengths.
830     */
831    gen_bitlen((tree_desc near *)desc);
832
833    /* The field len is now set, we can generate the bit codes */
834    gen_codes ((ct_data near *)tree, max_code);
835}
836
837/* ===========================================================================
838 * Scan a literal or distance tree to determine the frequencies of the codes
839 * in the bit length tree. Updates opt_len to take into account the repeat
840 * counts. (The contribution of the bit length codes will be added later
841 * during the construction of bl_tree.)
842 */
843local void scan_tree (tree, max_code)
844    ct_data near *tree; /* the tree to be scanned */
845    int max_code;       /* and its largest code of non zero frequency */
846{
847    int n;                     /* iterates over all tree elements */
848    int prevlen = -1;          /* last emitted length */
849    int curlen;                /* length of current code */
850    int nextlen = tree[0].Len; /* length of next code */
851    int count = 0;             /* repeat count of the current code */
852    int max_count = 7;         /* max repeat count */
853    int min_count = 4;         /* min repeat count */
854
855    if (nextlen == 0) max_count = 138, min_count = 3;
856    tree[max_code+1].Len = (ush)-1; /* guard */
857
858    for (n = 0; n <= max_code; n++) {
859        curlen = nextlen; nextlen = tree[n+1].Len;
860        if (++count < max_count && curlen == nextlen) {
861            continue;
862        } else if (count < min_count) {
863            bl_tree[curlen].Freq += (ush)count;
864        } else if (curlen != 0) {
865            if (curlen != prevlen) bl_tree[curlen].Freq++;
866            bl_tree[REP_3_6].Freq++;
867        } else if (count <= 10) {
868            bl_tree[REPZ_3_10].Freq++;
869        } else {
870            bl_tree[REPZ_11_138].Freq++;
871        }
872        count = 0; prevlen = curlen;
873        if (nextlen == 0) {
874            max_count = 138, min_count = 3;
875        } else if (curlen == nextlen) {
876            max_count = 6, min_count = 3;
877        } else {
878            max_count = 7, min_count = 4;
879        }
880    }
881}
882
883/* ===========================================================================
884 * Send a literal or distance tree in compressed form, using the codes in
885 * bl_tree.
886 */
887local void send_tree (tree, max_code)
888    ct_data near *tree; /* the tree to be scanned */
889    int max_code;       /* and its largest code of non zero frequency */
890{
891    int n;                     /* iterates over all tree elements */
892    int prevlen = -1;          /* last emitted length */
893    int curlen;                /* length of current code */
894    int nextlen = tree[0].Len; /* length of next code */
895    int count = 0;             /* repeat count of the current code */
896    int max_count = 7;         /* max repeat count */
897    int min_count = 4;         /* min repeat count */
898
899    /* tree[max_code+1].Len = -1; */  /* guard already set */
900    if (nextlen == 0) max_count = 138, min_count = 3;
901
902    for (n = 0; n <= max_code; n++) {
903        curlen = nextlen; nextlen = tree[n+1].Len;
904        if (++count < max_count && curlen == nextlen) {
905            continue;
906        } else if (count < min_count) {
907            do { send_code(curlen, bl_tree); } while (--count != 0);
908
909        } else if (curlen != 0) {
910            if (curlen != prevlen) {
911                send_code(curlen, bl_tree); count--;
912            }
913            Assert(count >= 3 && count <= 6, " 3_6?");
914            send_code(REP_3_6, bl_tree); send_bits(count-3, 2);
915
916        } else if (count <= 10) {
917            send_code(REPZ_3_10, bl_tree); send_bits(count-3, 3);
918
919        } else {
920            send_code(REPZ_11_138, bl_tree); send_bits(count-11, 7);
921        }
922        count = 0; prevlen = curlen;
923        if (nextlen == 0) {
924            max_count = 138, min_count = 3;
925        } else if (curlen == nextlen) {
926            max_count = 6, min_count = 3;
927        } else {
928            max_count = 7, min_count = 4;
929        }
930    }
931}
932
933/* ===========================================================================
934 * Construct the Huffman tree for the bit lengths and return the index in
935 * bl_order of the last bit length code to send.
936 */
937local int build_bl_tree()
938{
939    int max_blindex;  /* index of last bit length code of non zero freq */
940
941    /* Determine the bit length frequencies for literal and distance trees */
942    scan_tree((ct_data near *)dyn_ltree, l_desc.max_code);
943    scan_tree((ct_data near *)dyn_dtree, d_desc.max_code);
944
945    /* Build the bit length tree: */
946    build_tree((tree_desc near *)(&bl_desc));
947    /* opt_len now includes the length of the tree representations, except
948     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
949     */
950
951    /* Determine the number of bit length codes to send. The pkzip format
952     * requires that at least 4 bit length codes be sent. (appnote.txt says
953     * 3 but the actual value used is 4.)
954     */
955    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
956        if (bl_tree[bl_order[max_blindex]].Len != 0) break;
957    }
958    /* Update opt_len to include the bit length tree and counts */
959    opt_len += 3*(max_blindex+1) + 5+5+4;
960    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len, static_len));
961
962    return max_blindex;
963}
964
965/* ===========================================================================
966 * Send the header for a block using dynamic Huffman trees: the counts, the
967 * lengths of the bit length codes, the literal tree and the distance tree.
968 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
969 */
970local void send_all_trees(lcodes, dcodes, blcodes)
971    int lcodes, dcodes, blcodes; /* number of codes for each tree */
972{
973    int rank;                    /* index in bl_order */
974
975    Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
976    Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
977            "too many codes");
978    Tracev((stderr, "\nbl counts: "));
979    send_bits(lcodes-257, 5);
980    /* not +255 as stated in appnote.txt 1.93a or -256 in 2.04c */
981    send_bits(dcodes-1,   5);
982    send_bits(blcodes-4,  4); /* not -3 as stated in appnote.txt */
983    for (rank = 0; rank < blcodes; rank++) {
984        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
985        send_bits(bl_tree[bl_order[rank]].Len, 3);
986    }
987    Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
988
989    send_tree((ct_data near *)dyn_ltree, lcodes-1); /* send the literal tree */
990    Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
991
992    send_tree((ct_data near *)dyn_dtree, dcodes-1); /* send the distance tree */
993    Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
994}
995
996/* ===========================================================================
997 * Determine the best encoding for the current block: dynamic trees, static
998 * trees or store, and output the encoded block to the zip file. This function
999 * returns the total compressed length (in bytes) for the file so far.
1000 */
1001ulg flush_block(buf, stored_len, eof)
1002    char *buf;        /* input block, or NULL if too old */
1003    ulg stored_len;   /* length of input block */
1004    int eof;          /* true if this is the last block for a file */
1005{
1006    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
1007    int max_blindex;  /* index of last bit length code of non zero freq */
1008
1009    flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
1010
1011     /* Check if the file is ascii or binary */
1012    if (*file_type == (ush)UNKNOWN) set_file_type();
1013
1014    /* Construct the literal and distance trees */
1015    build_tree((tree_desc near *)(&l_desc));
1016    Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
1017
1018    build_tree((tree_desc near *)(&d_desc));
1019    Tracev((stderr, "\ndist data: dyn %ld, stat %ld", opt_len, static_len));
1020    /* At this point, opt_len and static_len are the total bit lengths of
1021     * the compressed block data, excluding the tree representations.
1022     */
1023
1024    /* Build the bit length tree for the above two trees, and get the index
1025     * in bl_order of the last bit length code to send.
1026     */
1027    max_blindex = build_bl_tree();
1028
1029    /* Determine the best encoding. Compute first the block length in bytes */
1030    opt_lenb = (opt_len+3+7)>>3;
1031    static_lenb = (static_len+3+7)>>3;
1032#ifdef DEBUG
1033    input_len += stored_len; /* for debugging only */
1034#endif
1035
1036    Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
1037            opt_lenb, opt_len, static_lenb, static_len, stored_len,
1038            last_lit, last_dist));
1039
1040    if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
1041
1042#ifndef PGP /* PGP can't handle stored blocks */
1043    /* If compression failed and this is the first and last block,
1044     * the whole file is transformed into a stored file:
1045     */
1046#ifdef FORCE_METHOD
1047    if (level == 1 && eof && file_method != NULL &&
1048        cmpr_bytelen == 0L && cmpr_len_bits == 0L) { /* force stored file */
1049#else
1050    if (stored_len <= opt_lenb && eof && file_method != NULL &&
1051        cmpr_bytelen == 0L && cmpr_len_bits == 0L && seekable()) {
1052#endif
1053        /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
1054        if (buf == NULL) error ("block vanished");
1055
1056        copy_block(buf, (unsigned)stored_len, 0); /* without header */
1057        cmpr_bytelen = stored_len;
1058        *file_method = STORE;
1059    } else
1060#endif /* PGP */
1061
1062#ifdef FORCE_METHOD
1063    if (level <= 2 && buf != (char*)NULL) { /* force stored block */
1064#else
1065    if (stored_len+4 <= opt_lenb && buf != (char*)NULL) {
1066                       /* 4: two words for the lengths */
1067#endif
1068        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1069         * Otherwise we can't have processed more than WSIZE input bytes since
1070         * the last block flush, because compression would have been
1071         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1072         * transform a block into a stored block.
1073         */
1074        send_bits((STORED_BLOCK<<1)+eof, 3);  /* send block type */
1075        cmpr_bytelen += ((cmpr_len_bits + 3 + 7) >> 3) + stored_len + 4;
1076        cmpr_len_bits = 0L;
1077
1078        copy_block(buf, (unsigned)stored_len, 1); /* with header */
1079
1080#ifdef FORCE_METHOD
1081    } else if (level == 3) { /* force static trees */
1082#else
1083    } else if (static_lenb == opt_lenb) {
1084#endif
1085        send_bits((STATIC_TREES<<1)+eof, 3);
1086        compress_block((ct_data near *)static_ltree, (ct_data near *)static_dtree);
1087        cmpr_len_bits += 3 + static_len;
1088        cmpr_bytelen += cmpr_len_bits >> 3;
1089        cmpr_len_bits &= 7L;
1090    } else {
1091        send_bits((DYN_TREES<<1)+eof, 3);
1092        send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
1093        compress_block((ct_data near *)dyn_ltree, (ct_data near *)dyn_dtree);
1094        cmpr_len_bits += 3 + opt_len;
1095        cmpr_bytelen += cmpr_len_bits >> 3;
1096        cmpr_len_bits &= 7L;
1097    }
1098    Assert(((cmpr_bytelen << 3) + cmpr_len_bits) == bits_sent,
1099            "bad compressed size");
1100    init_block();
1101
1102    if (eof) {
1103#if defined(PGP) && !defined(MMAP)
1104        /* Wipe out sensitive data for pgp */
1105# ifdef DYN_ALLOC
1106        extern uch *window;
1107# else
1108        extern uch window[];
1109# endif
1110        memset(window, 0, (unsigned)(2*WSIZE-1)); /* -1 needed if WSIZE=32K */
1111#else /* !PGP */
1112        Assert(input_len == isize, "bad input size");
1113#endif
1114        bi_windup();
1115        cmpr_len_bits += 7;  /* align on byte boundary */
1116    }
1117    Tracev((stderr,"\ncomprlen %lu(%lu) ", cmpr_bytelen + (cmpr_len_bits>>3),
1118           (cmpr_bytelen << 3) + cmpr_len_bits - 7*eof));
1119    Trace((stderr, "\n"));
1120
1121    return cmpr_bytelen + (cmpr_len_bits >> 3);
1122}
1123
1124/* ===========================================================================
1125 * Save the match info and tally the frequency counts. Return true if
1126 * the current block must be flushed.
1127 */
1128int ct_tally (dist, lc)
1129    int dist;  /* distance of matched string */
1130    int lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
1131{
1132    l_buf[last_lit++] = (uch)lc;
1133    if (dist == 0) {
1134        /* lc is the unmatched char */
1135        dyn_ltree[lc].Freq++;
1136    } else {
1137        /* Here, lc is the match length - MIN_MATCH */
1138        dist--;             /* dist = match distance - 1 */
1139        Assert((ush)dist < (ush)MAX_DIST &&
1140               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1141               (ush)d_code(dist) < (ush)D_CODES,  "ct_tally: bad match");
1142
1143        dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
1144        dyn_dtree[d_code(dist)].Freq++;
1145
1146        d_buf[last_dist++] = (ush)dist;
1147        flags |= flag_bit;
1148    }
1149    flag_bit <<= 1;
1150
1151    /* Output the flags if they fill a byte: */
1152    if ((last_lit & 7) == 0) {
1153        flag_buf[last_flags++] = flags;
1154        flags = 0, flag_bit = 1;
1155    }
1156    /* Try to guess if it is profitable to stop the current block here */
1157    if (level > 2 && (last_lit & 0xfff) == 0) {
1158        /* Compute an upper bound for the compressed length */
1159        ulg out_length = (ulg)last_lit*8L;
1160        ulg in_length = (ulg)strstart-block_start;
1161        int dcode;
1162        for (dcode = 0; dcode < D_CODES; dcode++) {
1163            out_length += (ulg)dyn_dtree[dcode].Freq*(5L+extra_dbits[dcode]);
1164        }
1165        out_length >>= 3;
1166        Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
1167               last_lit, last_dist, in_length, out_length,
1168               100L - out_length*100L/in_length));
1169        if (last_dist < last_lit/2 && out_length < in_length/2) return 1;
1170    }
1171    return (last_lit == LIT_BUFSIZE-1 || last_dist == DIST_BUFSIZE);
1172    /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
1173     * on 16 bit machines and because stored blocks are restricted to
1174     * 64K-1 bytes.
1175     */
1176}
1177
1178/* ===========================================================================
1179 * Send the block data compressed using the given Huffman trees
1180 */
1181local void compress_block(ltree, dtree)
1182    ct_data near *ltree; /* literal tree */
1183    ct_data near *dtree; /* distance tree */
1184{
1185    unsigned dist;      /* distance of matched string */
1186    int lc;             /* match length or unmatched char (if dist == 0) */
1187    unsigned lx = 0;    /* running index in l_buf */
1188    unsigned dx = 0;    /* running index in d_buf */
1189    unsigned fx = 0;    /* running index in flag_buf */
1190    uch flag = 0;       /* current flags */
1191    unsigned code;      /* the code to send */
1192    int extra;          /* number of extra bits to send */
1193
1194    if (last_lit != 0) do {
1195        if ((lx & 7) == 0) flag = flag_buf[fx++];
1196        lc = l_buf[lx++];
1197        if ((flag & 1) == 0) {
1198            send_code(lc, ltree); /* send a literal byte */
1199            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1200        } else {
1201            /* Here, lc is the match length - MIN_MATCH */
1202            code = length_code[lc];
1203            send_code(code+LITERALS+1, ltree); /* send the length code */
1204            extra = extra_lbits[code];
1205            if (extra != 0) {
1206                lc -= base_length[code];
1207                send_bits(lc, extra);        /* send the extra length bits */
1208            }
1209            dist = d_buf[dx++];
1210            /* Here, dist is the match distance - 1 */
1211            code = d_code(dist);
1212            Assert(code < D_CODES, "bad d_code");
1213
1214            send_code(code, dtree);       /* send the distance code */
1215            extra = extra_dbits[code];
1216            if (extra != 0) {
1217                dist -= base_dist[code];
1218                send_bits(dist, extra);   /* send the extra distance bits */
1219            }
1220        } /* literal or match pair ? */
1221        flag >>= 1;
1222    } while (lx < last_lit);
1223
1224    send_code(END_BLOCK, ltree);
1225}
1226
1227/* ===========================================================================
1228 * Set the file type to TEXT (ASCII) or BINARY, using following algorithm:
1229 * - TEXT, either ASCII or an ASCII-compatible extension such as ISO-8859,
1230 *   UTF-8, etc., when the following two conditions are satisfied:
1231 *    a) There are no non-portable control characters belonging to the
1232 *       "black list" (0..6, 14..25, 28..31).
1233 *    b) There is at least one printable character belonging to the
1234 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1235 * - BINARY otherwise.
1236 *
1237 * Note that the following partially-portable control characters form a
1238 * "gray list" that is ignored in this detection algorithm:
1239 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
1240 *
1241 * Also note that, unlike in the previous 20% binary detection algorithm,
1242 * any control characters in the black list will set the file type to
1243 * BINARY.  If a text file contains a single accidental black character,
1244 * the file will be flagged as BINARY in the archive.
1245 *
1246 * IN assertion: the fields freq of dyn_ltree are set.
1247 */
1248local void set_file_type()
1249{
1250    /* bit-mask of black-listed bytes
1251     * bit is set if byte is black-listed
1252     * set bits 0..6, 14..25, and 28..31
1253     * 0xf3ffc07f = binary 11110011111111111100000001111111
1254     */
1255    unsigned long mask = 0xf3ffc07fUL;
1256    int n;
1257
1258    /* Check for non-textual ("black-listed") bytes. */
1259    for (n = 0; n <= 31; n++, mask >>= 1)
1260        if ((mask & 1) && (dyn_ltree[n].Freq != 0))
1261        {
1262            *file_type = BINARY;
1263            return;
1264        }
1265
1266    /* Check for textual ("white-listed") bytes. */
1267    *file_type = ASCII;
1268    if (dyn_ltree[9].Freq != 0 || dyn_ltree[10].Freq != 0
1269            || dyn_ltree[13].Freq != 0)
1270        return;
1271    for (n = 32; n < LITERALS; n++)
1272        if (dyn_ltree[n].Freq != 0)
1273            return;
1274
1275    /* This deflate stream is either empty, or
1276     * it has tolerated ("gray-listed") bytes only.
1277     */
1278    *file_type = BINARY;
1279}
1280
1281
1282/* ===========================================================================
1283 * Initialize the bit string routines.
1284 */
1285void bi_init (tgt_buf, tgt_size, flsh_allowed)
1286    char *tgt_buf;
1287    unsigned tgt_size;
1288    int flsh_allowed;
1289{
1290    out_buf = tgt_buf;
1291    out_size = tgt_size;
1292    out_offset = 0;
1293    flush_flg = flsh_allowed;
1294
1295    bi_buf = 0;
1296    bi_valid = 0;
1297#ifdef DEBUG
1298    bits_sent = 0L;
1299#endif
1300}
1301
1302#if (!defined(ASMV) || !defined(RISCOS))
1303/* ===========================================================================
1304 * Send a value on a given number of bits.
1305 * IN assertion: length <= 16 and value fits in length bits.
1306 */
1307local void send_bits(value, length)
1308    int value;  /* value to send */
1309    int length; /* number of bits */
1310{
1311#ifdef DEBUG
1312    Tracevv((stderr," l %2d v %4x ", length, value));
1313    Assert(length > 0 && length <= 15, "invalid length");
1314    bits_sent += (ulg)length;
1315#endif
1316    /* If not enough room in bi_buf, use (bi_valid) bits from bi_buf and
1317     * (Buf_size - bi_valid) bits from value to flush the filled bi_buf,
1318     * then fill in the rest of (value), leaving (length - (Buf_size-bi_valid))
1319     * unused bits in bi_buf.
1320     */
1321    bi_buf |= (value << bi_valid);
1322    bi_valid += length;
1323    if (bi_valid > (int)Buf_size) {
1324        PUTSHORT(bi_buf);
1325        bi_valid -= Buf_size;
1326        bi_buf = (unsigned)value >> (length - bi_valid);
1327    }
1328}
1329
1330/* ===========================================================================
1331 * Reverse the first len bits of a code, using straightforward code (a faster
1332 * method would use a table)
1333 * IN assertion: 1 <= len <= 15
1334 */
1335local unsigned bi_reverse(code, len)
1336    unsigned code; /* the value to invert */
1337    int len;       /* its bit length */
1338{
1339    register unsigned res = 0;
1340    do {
1341        res |= code & 1;
1342        code >>= 1, res <<= 1;
1343    } while (--len > 0);
1344    return res >> 1;
1345}
1346#endif /* !ASMV || !RISCOS */
1347
1348/* ===========================================================================
1349 * Write out any remaining bits in an incomplete byte.
1350 */
1351local void bi_windup()
1352{
1353    if (bi_valid > 8) {
1354        PUTSHORT(bi_buf);
1355    } else if (bi_valid > 0) {
1356        PUTBYTE(bi_buf);
1357    }
1358    if (flush_flg) {
1359        flush_outbuf(out_buf, &out_offset);
1360    }
1361    bi_buf = 0;
1362    bi_valid = 0;
1363#ifdef DEBUG
1364    bits_sent = (bits_sent+7) & ~7;
1365#endif
1366}
1367
1368/* ===========================================================================
1369 * Copy a stored block to the zip file, storing first the length and its
1370 * one's complement if requested.
1371 *
1372 * Buffer Overwrite fix
1373 *
1374 * A buffer flush has been added to fix a bug when encrypting deflated files
1375 * with embedded "copied blocks".  When encrypting, the flush_out() routine
1376 * modifies its data buffer because encryption is done "in-place" in
1377 * zfwrite(), whereas without encryption, the flush_out() data buffer is
1378 * left unaltered.  This can be a problem as noted below by the submitter.
1379 *
1380 * "But an exception comes when a block of stored data (data that could not
1381 * be compressed) is being encrypted. In this case, the data that is passed
1382 * to zfwrite (and is therefore encrypted-in-place) is actually a block of
1383 * data from within the sliding input window that is being managed by
1384 * deflate.c.
1385 *
1386 * "Since part of the sliding input window has now been overwritten by
1387 * encrypted (and essentially random) data, deflate.c's search for previous
1388 * text that matches the current text will usually fail but on rare
1389 * occasions will find a match with something in the encrypted data. This
1390 * incorrect match then causes incorrect information to be placed in the
1391 * ZIP file."
1392 *
1393 * The problem results in the zip file having bad data and so a bad CRC.
1394 * This does not happen often and to recreate the problem a large file
1395 * with non-compressable data is needed so that deflate chooses to store the
1396 * data.  A test file of 400 MB seems large enough to recreate the problem
1397 * using a command such as
1398 *     zip -1 -e crcerror.zip testfile.dat
1399 * maybe half the time.
1400 *
1401 * This problem has been fixed by copying the data into the deflate output
1402 * buffer before calling flush_outbuf(), when encryption is enabled.
1403 *
1404 * Thanks to the nice people at WinZip for identifying the problem and
1405 * passing it on.  Also see Changes.
1406 *
1407 * 2006-03-05 EG, CS
1408 */
1409local void copy_block(block, len, header)
1410    char *block;  /* the input data */
1411    unsigned len; /* its length */
1412    int header;   /* true if block header must be written */
1413{
1414    bi_windup();              /* align on byte boundary */
1415
1416    if (header) {
1417        PUTSHORT((ush)len);
1418        PUTSHORT((ush)~len);
1419#ifdef DEBUG
1420        bits_sent += 2*16;
1421#endif
1422    }
1423    if (flush_flg) {
1424        flush_outbuf(out_buf, &out_offset);
1425        if (key != (char *)NULL) {  /* key is the global password pointer */
1426            /* Encryption modifies the data in the output buffer. But the
1427             * copied input data must remain intact for further deflate
1428             * string matching lookups.  Therefore, the input data is
1429             * copied into the compression output buffer for flushing
1430             * to the compressed/encrypted output stream.
1431             */
1432            while(len > 0) {
1433                out_offset = (len < out_size ? len : out_size);
1434                memcpy(out_buf, block, out_offset);
1435                block += out_offset;
1436                len -= out_offset;
1437                flush_outbuf(out_buf, &out_offset);
1438            }
1439        } else {
1440            /* Without encryption, the output routines do not touch the
1441             * written data, so there is no need for an additional copy
1442             * operation.
1443             */
1444            out_offset = len;
1445            flush_outbuf(block, &out_offset);
1446        }
1447    } else if (out_offset + len > out_size) {
1448        error("output buffer too small for in-memory compression");
1449    } else {
1450        memcpy(out_buf + out_offset, block, len);
1451        out_offset += len;
1452    }
1453#ifdef DEBUG
1454    bits_sent += (ulg)len<<3;
1455#endif
1456}
1457
1458#endif /* !USE_ZLIB */
1459