michael@0: /* trees.c -- output deflated data using Huffman coding michael@0: * Copyright (C) 1995-2012 Jean-loup Gailly michael@0: * detect_data_type() function provided freely by Cosmin Truta, 2006 michael@0: * For conditions of distribution and use, see copyright notice in zlib.h michael@0: */ michael@0: michael@0: /* michael@0: * ALGORITHM michael@0: * michael@0: * The "deflation" process uses several Huffman trees. The more michael@0: * common source values are represented by shorter bit sequences. michael@0: * michael@0: * Each code tree is stored in a compressed form which is itself michael@0: * a Huffman encoding of the lengths of all the code strings (in michael@0: * ascending order by source values). The actual code strings are michael@0: * reconstructed from the lengths in the inflate process, as described michael@0: * in the deflate specification. michael@0: * michael@0: * REFERENCES michael@0: * michael@0: * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". michael@0: * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc michael@0: * michael@0: * Storer, James A. michael@0: * Data Compression: Methods and Theory, pp. 49-50. michael@0: * Computer Science Press, 1988. ISBN 0-7167-8156-5. michael@0: * michael@0: * Sedgewick, R. michael@0: * Algorithms, p290. michael@0: * Addison-Wesley, 1983. ISBN 0-201-06672-6. michael@0: */ michael@0: michael@0: /* @(#) $Id$ */ michael@0: michael@0: /* #define GEN_TREES_H */ michael@0: michael@0: #include "deflate.h" michael@0: michael@0: #ifdef DEBUG michael@0: # include michael@0: #endif michael@0: michael@0: /* =========================================================================== michael@0: * Constants michael@0: */ michael@0: michael@0: #define MAX_BL_BITS 7 michael@0: /* Bit length codes must not exceed MAX_BL_BITS bits */ michael@0: michael@0: #define END_BLOCK 256 michael@0: /* end of block literal code */ michael@0: michael@0: #define REP_3_6 16 michael@0: /* repeat previous bit length 3-6 times (2 bits of repeat count) */ michael@0: michael@0: #define REPZ_3_10 17 michael@0: /* repeat a zero length 3-10 times (3 bits of repeat count) */ michael@0: michael@0: #define REPZ_11_138 18 michael@0: /* repeat a zero length 11-138 times (7 bits of repeat count) */ michael@0: michael@0: local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ michael@0: = {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}; michael@0: michael@0: local const int extra_dbits[D_CODES] /* extra bits for each distance code */ michael@0: = {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}; michael@0: michael@0: local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ michael@0: = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; michael@0: michael@0: local const uch bl_order[BL_CODES] michael@0: = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; michael@0: /* The lengths of the bit length codes are sent in order of decreasing michael@0: * probability, to avoid transmitting the lengths for unused bit length codes. michael@0: */ michael@0: michael@0: /* =========================================================================== michael@0: * Local data. These are initialized only once. michael@0: */ michael@0: michael@0: #define DIST_CODE_LEN 512 /* see definition of array dist_code below */ michael@0: michael@0: #if defined(GEN_TREES_H) || !defined(STDC) michael@0: /* non ANSI compilers may not accept trees.h */ michael@0: michael@0: local ct_data static_ltree[L_CODES+2]; michael@0: /* The static literal tree. Since the bit lengths are imposed, there is no michael@0: * need for the L_CODES extra codes used during heap construction. However michael@0: * The codes 286 and 287 are needed to build a canonical tree (see _tr_init michael@0: * below). michael@0: */ michael@0: michael@0: local ct_data static_dtree[D_CODES]; michael@0: /* The static distance tree. (Actually a trivial tree since all codes use michael@0: * 5 bits.) michael@0: */ michael@0: michael@0: uch _dist_code[DIST_CODE_LEN]; michael@0: /* Distance codes. The first 256 values correspond to the distances michael@0: * 3 .. 258, the last 256 values correspond to the top 8 bits of michael@0: * the 15 bit distances. michael@0: */ michael@0: michael@0: uch _length_code[MAX_MATCH-MIN_MATCH+1]; michael@0: /* length code for each normalized match length (0 == MIN_MATCH) */ michael@0: michael@0: local int base_length[LENGTH_CODES]; michael@0: /* First normalized length for each code (0 = MIN_MATCH) */ michael@0: michael@0: local int base_dist[D_CODES]; michael@0: /* First normalized distance for each code (0 = distance of 1) */ michael@0: michael@0: #else michael@0: # include "trees.h" michael@0: #endif /* GEN_TREES_H */ michael@0: michael@0: struct static_tree_desc_s { michael@0: const ct_data *static_tree; /* static tree or NULL */ michael@0: const intf *extra_bits; /* extra bits for each code or NULL */ michael@0: int extra_base; /* base index for extra_bits */ michael@0: int elems; /* max number of elements in the tree */ michael@0: int max_length; /* max bit length for the codes */ michael@0: }; michael@0: michael@0: local static_tree_desc static_l_desc = michael@0: {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; michael@0: michael@0: local static_tree_desc static_d_desc = michael@0: {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; michael@0: michael@0: local static_tree_desc static_bl_desc = michael@0: {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; michael@0: michael@0: /* =========================================================================== michael@0: * Local (static) routines in this file. michael@0: */ michael@0: michael@0: local void tr_static_init OF((void)); michael@0: local void init_block OF((deflate_state *s)); michael@0: local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); michael@0: local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); michael@0: local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); michael@0: local void build_tree OF((deflate_state *s, tree_desc *desc)); michael@0: local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); michael@0: local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); michael@0: local int build_bl_tree OF((deflate_state *s)); michael@0: local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, michael@0: int blcodes)); michael@0: local void compress_block OF((deflate_state *s, const ct_data *ltree, michael@0: const ct_data *dtree)); michael@0: local int detect_data_type OF((deflate_state *s)); michael@0: local unsigned bi_reverse OF((unsigned value, int length)); michael@0: local void bi_windup OF((deflate_state *s)); michael@0: local void bi_flush OF((deflate_state *s)); michael@0: local void copy_block OF((deflate_state *s, charf *buf, unsigned len, michael@0: int header)); michael@0: michael@0: #ifdef GEN_TREES_H michael@0: local void gen_trees_header OF((void)); michael@0: #endif michael@0: michael@0: #ifndef DEBUG michael@0: # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) michael@0: /* Send a code of the given tree. c and tree must not have side effects */ michael@0: michael@0: #else /* DEBUG */ michael@0: # define send_code(s, c, tree) \ michael@0: { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ michael@0: send_bits(s, tree[c].Code, tree[c].Len); } michael@0: #endif michael@0: michael@0: /* =========================================================================== michael@0: * Output a short LSB first on the stream. michael@0: * IN assertion: there is enough room in pendingBuf. michael@0: */ michael@0: #define put_short(s, w) { \ michael@0: put_byte(s, (uch)((w) & 0xff)); \ michael@0: put_byte(s, (uch)((ush)(w) >> 8)); \ michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Send a value on a given number of bits. michael@0: * IN assertion: length <= 16 and value fits in length bits. michael@0: */ michael@0: #ifdef DEBUG michael@0: local void send_bits OF((deflate_state *s, int value, int length)); michael@0: michael@0: local void send_bits(s, value, length) michael@0: deflate_state *s; michael@0: int value; /* value to send */ michael@0: int length; /* number of bits */ michael@0: { michael@0: Tracevv((stderr," l %2d v %4x ", length, value)); michael@0: Assert(length > 0 && length <= 15, "invalid length"); michael@0: s->bits_sent += (ulg)length; michael@0: michael@0: /* If not enough room in bi_buf, use (valid) bits from bi_buf and michael@0: * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) michael@0: * unused bits in value. michael@0: */ michael@0: if (s->bi_valid > (int)Buf_size - length) { michael@0: s->bi_buf |= (ush)value << s->bi_valid; michael@0: put_short(s, s->bi_buf); michael@0: s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); michael@0: s->bi_valid += length - Buf_size; michael@0: } else { michael@0: s->bi_buf |= (ush)value << s->bi_valid; michael@0: s->bi_valid += length; michael@0: } michael@0: } michael@0: #else /* !DEBUG */ michael@0: michael@0: #define send_bits(s, value, length) \ michael@0: { int len = length;\ michael@0: if (s->bi_valid > (int)Buf_size - len) {\ michael@0: int val = value;\ michael@0: s->bi_buf |= (ush)val << s->bi_valid;\ michael@0: put_short(s, s->bi_buf);\ michael@0: s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ michael@0: s->bi_valid += len - Buf_size;\ michael@0: } else {\ michael@0: s->bi_buf |= (ush)(value) << s->bi_valid;\ michael@0: s->bi_valid += len;\ michael@0: }\ michael@0: } michael@0: #endif /* DEBUG */ michael@0: michael@0: michael@0: /* the arguments must not have side effects */ michael@0: michael@0: /* =========================================================================== michael@0: * Initialize the various 'constant' tables. michael@0: */ michael@0: local void tr_static_init() michael@0: { michael@0: #if defined(GEN_TREES_H) || !defined(STDC) michael@0: static int static_init_done = 0; michael@0: int n; /* iterates over tree elements */ michael@0: int bits; /* bit counter */ michael@0: int length; /* length value */ michael@0: int code; /* code value */ michael@0: int dist; /* distance index */ michael@0: ush bl_count[MAX_BITS+1]; michael@0: /* number of codes at each bit length for an optimal tree */ michael@0: michael@0: if (static_init_done) return; michael@0: michael@0: /* For some embedded targets, global variables are not initialized: */ michael@0: #ifdef NO_INIT_GLOBAL_POINTERS michael@0: static_l_desc.static_tree = static_ltree; michael@0: static_l_desc.extra_bits = extra_lbits; michael@0: static_d_desc.static_tree = static_dtree; michael@0: static_d_desc.extra_bits = extra_dbits; michael@0: static_bl_desc.extra_bits = extra_blbits; michael@0: #endif michael@0: michael@0: /* Initialize the mapping length (0..255) -> length code (0..28) */ michael@0: length = 0; michael@0: for (code = 0; code < LENGTH_CODES-1; code++) { michael@0: base_length[code] = length; michael@0: for (n = 0; n < (1< dist code (0..29) */ michael@0: dist = 0; michael@0: for (code = 0 ; code < 16; code++) { michael@0: base_dist[code] = dist; michael@0: for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ michael@0: for ( ; code < D_CODES; code++) { michael@0: base_dist[code] = dist << 7; michael@0: for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { michael@0: _dist_code[256 + dist++] = (uch)code; michael@0: } michael@0: } michael@0: Assert (dist == 256, "tr_static_init: 256+dist != 512"); michael@0: michael@0: /* Construct the codes of the static literal tree */ michael@0: for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; michael@0: n = 0; michael@0: while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; michael@0: while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; michael@0: while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; michael@0: while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; michael@0: /* Codes 286 and 287 do not exist, but we must include them in the michael@0: * tree construction to get a canonical Huffman tree (longest code michael@0: * all ones) michael@0: */ michael@0: gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); michael@0: michael@0: /* The static distance tree is trivial: */ michael@0: for (n = 0; n < D_CODES; n++) { michael@0: static_dtree[n].Len = 5; michael@0: static_dtree[n].Code = bi_reverse((unsigned)n, 5); michael@0: } michael@0: static_init_done = 1; michael@0: michael@0: # ifdef GEN_TREES_H michael@0: gen_trees_header(); michael@0: # endif michael@0: #endif /* defined(GEN_TREES_H) || !defined(STDC) */ michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Genererate the file trees.h describing the static trees. michael@0: */ michael@0: #ifdef GEN_TREES_H michael@0: # ifndef DEBUG michael@0: # include michael@0: # endif michael@0: michael@0: # define SEPARATOR(i, last, width) \ michael@0: ((i) == (last)? "\n};\n\n" : \ michael@0: ((i) % (width) == (width)-1 ? ",\n" : ", ")) michael@0: michael@0: void gen_trees_header() michael@0: { michael@0: FILE *header = fopen("trees.h", "w"); michael@0: int i; michael@0: michael@0: Assert (header != NULL, "Can't open trees.h"); michael@0: fprintf(header, michael@0: "/* header created automatically with -DGEN_TREES_H */\n\n"); michael@0: michael@0: fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); michael@0: for (i = 0; i < L_CODES+2; i++) { michael@0: fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, michael@0: static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); michael@0: } michael@0: michael@0: fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); michael@0: for (i = 0; i < D_CODES; i++) { michael@0: fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, michael@0: static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); michael@0: } michael@0: michael@0: fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); michael@0: for (i = 0; i < DIST_CODE_LEN; i++) { michael@0: fprintf(header, "%2u%s", _dist_code[i], michael@0: SEPARATOR(i, DIST_CODE_LEN-1, 20)); michael@0: } michael@0: michael@0: fprintf(header, michael@0: "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); michael@0: for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { michael@0: fprintf(header, "%2u%s", _length_code[i], michael@0: SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); michael@0: } michael@0: michael@0: fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); michael@0: for (i = 0; i < LENGTH_CODES; i++) { michael@0: fprintf(header, "%1u%s", base_length[i], michael@0: SEPARATOR(i, LENGTH_CODES-1, 20)); michael@0: } michael@0: michael@0: fprintf(header, "local const int base_dist[D_CODES] = {\n"); michael@0: for (i = 0; i < D_CODES; i++) { michael@0: fprintf(header, "%5u%s", base_dist[i], michael@0: SEPARATOR(i, D_CODES-1, 10)); michael@0: } michael@0: michael@0: fclose(header); michael@0: } michael@0: #endif /* GEN_TREES_H */ michael@0: michael@0: /* =========================================================================== michael@0: * Initialize the tree data structures for a new zlib stream. michael@0: */ michael@0: void ZLIB_INTERNAL _tr_init(s) michael@0: deflate_state *s; michael@0: { michael@0: tr_static_init(); michael@0: michael@0: s->l_desc.dyn_tree = s->dyn_ltree; michael@0: s->l_desc.stat_desc = &static_l_desc; michael@0: michael@0: s->d_desc.dyn_tree = s->dyn_dtree; michael@0: s->d_desc.stat_desc = &static_d_desc; michael@0: michael@0: s->bl_desc.dyn_tree = s->bl_tree; michael@0: s->bl_desc.stat_desc = &static_bl_desc; michael@0: michael@0: s->bi_buf = 0; michael@0: s->bi_valid = 0; michael@0: #ifdef DEBUG michael@0: s->compressed_len = 0L; michael@0: s->bits_sent = 0L; michael@0: #endif michael@0: michael@0: /* Initialize the first block of the first file: */ michael@0: init_block(s); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Initialize a new block. michael@0: */ michael@0: local void init_block(s) michael@0: deflate_state *s; michael@0: { michael@0: int n; /* iterates over tree elements */ michael@0: michael@0: /* Initialize the trees. */ michael@0: for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; michael@0: for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; michael@0: for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; michael@0: michael@0: s->dyn_ltree[END_BLOCK].Freq = 1; michael@0: s->opt_len = s->static_len = 0L; michael@0: s->last_lit = s->matches = 0; michael@0: } michael@0: michael@0: #define SMALLEST 1 michael@0: /* Index within the heap array of least frequent node in the Huffman tree */ michael@0: michael@0: michael@0: /* =========================================================================== michael@0: * Remove the smallest element from the heap and recreate the heap with michael@0: * one less element. Updates heap and heap_len. michael@0: */ michael@0: #define pqremove(s, tree, top) \ michael@0: {\ michael@0: top = s->heap[SMALLEST]; \ michael@0: s->heap[SMALLEST] = s->heap[s->heap_len--]; \ michael@0: pqdownheap(s, tree, SMALLEST); \ michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Compares to subtrees, using the tree depth as tie breaker when michael@0: * the subtrees have equal frequency. This minimizes the worst case length. michael@0: */ michael@0: #define smaller(tree, n, m, depth) \ michael@0: (tree[n].Freq < tree[m].Freq || \ michael@0: (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) michael@0: michael@0: /* =========================================================================== michael@0: * Restore the heap property by moving down the tree starting at node k, michael@0: * exchanging a node with the smallest of its two sons if necessary, stopping michael@0: * when the heap property is re-established (each father smaller than its michael@0: * two sons). michael@0: */ michael@0: local void pqdownheap(s, tree, k) michael@0: deflate_state *s; michael@0: ct_data *tree; /* the tree to restore */ michael@0: int k; /* node to move down */ michael@0: { michael@0: int v = s->heap[k]; michael@0: int j = k << 1; /* left son of k */ michael@0: while (j <= s->heap_len) { michael@0: /* Set j to the smallest of the two sons: */ michael@0: if (j < s->heap_len && michael@0: smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { michael@0: j++; michael@0: } michael@0: /* Exit if v is smaller than both sons */ michael@0: if (smaller(tree, v, s->heap[j], s->depth)) break; michael@0: michael@0: /* Exchange v with the smallest son */ michael@0: s->heap[k] = s->heap[j]; k = j; michael@0: michael@0: /* And continue down the tree, setting j to the left son of k */ michael@0: j <<= 1; michael@0: } michael@0: s->heap[k] = v; michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Compute the optimal bit lengths for a tree and update the total bit length michael@0: * for the current block. michael@0: * IN assertion: the fields freq and dad are set, heap[heap_max] and michael@0: * above are the tree nodes sorted by increasing frequency. michael@0: * OUT assertions: the field len is set to the optimal bit length, the michael@0: * array bl_count contains the frequencies for each bit length. michael@0: * The length opt_len is updated; static_len is also updated if stree is michael@0: * not null. michael@0: */ michael@0: local void gen_bitlen(s, desc) michael@0: deflate_state *s; michael@0: tree_desc *desc; /* the tree descriptor */ michael@0: { michael@0: ct_data *tree = desc->dyn_tree; michael@0: int max_code = desc->max_code; michael@0: const ct_data *stree = desc->stat_desc->static_tree; michael@0: const intf *extra = desc->stat_desc->extra_bits; michael@0: int base = desc->stat_desc->extra_base; michael@0: int max_length = desc->stat_desc->max_length; michael@0: int h; /* heap index */ michael@0: int n, m; /* iterate over the tree elements */ michael@0: int bits; /* bit length */ michael@0: int xbits; /* extra bits */ michael@0: ush f; /* frequency */ michael@0: int overflow = 0; /* number of elements with bit length too large */ michael@0: michael@0: for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; michael@0: michael@0: /* In a first pass, compute the optimal bit lengths (which may michael@0: * overflow in the case of the bit length tree). michael@0: */ michael@0: tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ michael@0: michael@0: for (h = s->heap_max+1; h < HEAP_SIZE; h++) { michael@0: n = s->heap[h]; michael@0: bits = tree[tree[n].Dad].Len + 1; michael@0: if (bits > max_length) bits = max_length, overflow++; michael@0: tree[n].Len = (ush)bits; michael@0: /* We overwrite tree[n].Dad which is no longer needed */ michael@0: michael@0: if (n > max_code) continue; /* not a leaf node */ michael@0: michael@0: s->bl_count[bits]++; michael@0: xbits = 0; michael@0: if (n >= base) xbits = extra[n-base]; michael@0: f = tree[n].Freq; michael@0: s->opt_len += (ulg)f * (bits + xbits); michael@0: if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); michael@0: } michael@0: if (overflow == 0) return; michael@0: michael@0: Trace((stderr,"\nbit length overflow\n")); michael@0: /* This happens for example on obj2 and pic of the Calgary corpus */ michael@0: michael@0: /* Find the first bit length which could increase: */ michael@0: do { michael@0: bits = max_length-1; michael@0: while (s->bl_count[bits] == 0) bits--; michael@0: s->bl_count[bits]--; /* move one leaf down the tree */ michael@0: s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ michael@0: s->bl_count[max_length]--; michael@0: /* The brother of the overflow item also moves one step up, michael@0: * but this does not affect bl_count[max_length] michael@0: */ michael@0: overflow -= 2; michael@0: } while (overflow > 0); michael@0: michael@0: /* Now recompute all bit lengths, scanning in increasing frequency. michael@0: * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all michael@0: * lengths instead of fixing only the wrong ones. This idea is taken michael@0: * from 'ar' written by Haruhiko Okumura.) michael@0: */ michael@0: for (bits = max_length; bits != 0; bits--) { michael@0: n = s->bl_count[bits]; michael@0: while (n != 0) { michael@0: m = s->heap[--h]; michael@0: if (m > max_code) continue; michael@0: if ((unsigned) tree[m].Len != (unsigned) bits) { michael@0: Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); michael@0: s->opt_len += ((long)bits - (long)tree[m].Len) michael@0: *(long)tree[m].Freq; michael@0: tree[m].Len = (ush)bits; michael@0: } michael@0: n--; michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Generate the codes for a given tree and bit counts (which need not be michael@0: * optimal). michael@0: * IN assertion: the array bl_count contains the bit length statistics for michael@0: * the given tree and the field len is set for all tree elements. michael@0: * OUT assertion: the field code is set for all tree elements of non michael@0: * zero code length. michael@0: */ michael@0: local void gen_codes (tree, max_code, bl_count) michael@0: ct_data *tree; /* the tree to decorate */ michael@0: int max_code; /* largest code with non zero frequency */ michael@0: ushf *bl_count; /* number of codes at each bit length */ michael@0: { michael@0: ush next_code[MAX_BITS+1]; /* next code value for each bit length */ michael@0: ush code = 0; /* running code value */ michael@0: int bits; /* bit index */ michael@0: int n; /* code index */ michael@0: michael@0: /* The distribution counts are first used to generate the code values michael@0: * without bit reversal. michael@0: */ michael@0: for (bits = 1; bits <= MAX_BITS; bits++) { michael@0: next_code[bits] = code = (code + bl_count[bits-1]) << 1; michael@0: } michael@0: /* Check that the bit counts in bl_count are consistent. The last code michael@0: * must be all ones. michael@0: */ michael@0: Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; michael@0: const ct_data *stree = desc->stat_desc->static_tree; michael@0: int elems = desc->stat_desc->elems; michael@0: int n, m; /* iterate over heap elements */ michael@0: int max_code = -1; /* largest code with non zero frequency */ michael@0: int node; /* new node being created */ michael@0: michael@0: /* Construct the initial heap, with least frequent element in michael@0: * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. michael@0: * heap[0] is not used. michael@0: */ michael@0: s->heap_len = 0, s->heap_max = HEAP_SIZE; michael@0: michael@0: for (n = 0; n < elems; n++) { michael@0: if (tree[n].Freq != 0) { michael@0: s->heap[++(s->heap_len)] = max_code = n; michael@0: s->depth[n] = 0; michael@0: } else { michael@0: tree[n].Len = 0; michael@0: } michael@0: } michael@0: michael@0: /* The pkzip format requires that at least one distance code exists, michael@0: * and that at least one bit should be sent even if there is only one michael@0: * possible code. So to avoid special checks later on we force at least michael@0: * two codes of non zero frequency. michael@0: */ michael@0: while (s->heap_len < 2) { michael@0: node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); michael@0: tree[node].Freq = 1; michael@0: s->depth[node] = 0; michael@0: s->opt_len--; if (stree) s->static_len -= stree[node].Len; michael@0: /* node is 0 or 1 so it does not have extra bits */ michael@0: } michael@0: desc->max_code = max_code; michael@0: michael@0: /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, michael@0: * establish sub-heaps of increasing lengths: michael@0: */ michael@0: for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); michael@0: michael@0: /* Construct the Huffman tree by repeatedly combining the least two michael@0: * frequent nodes. michael@0: */ michael@0: node = elems; /* next internal node of the tree */ michael@0: do { michael@0: pqremove(s, tree, n); /* n = node of least frequency */ michael@0: m = s->heap[SMALLEST]; /* m = node of next least frequency */ michael@0: michael@0: s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ michael@0: s->heap[--(s->heap_max)] = m; michael@0: michael@0: /* Create a new node father of n and m */ michael@0: tree[node].Freq = tree[n].Freq + tree[m].Freq; michael@0: s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? michael@0: s->depth[n] : s->depth[m]) + 1); michael@0: tree[n].Dad = tree[m].Dad = (ush)node; michael@0: #ifdef DUMP_BL_TREE michael@0: if (tree == s->bl_tree) { michael@0: fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", michael@0: node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); michael@0: } michael@0: #endif michael@0: /* and insert the new node in the heap */ michael@0: s->heap[SMALLEST] = node++; michael@0: pqdownheap(s, tree, SMALLEST); michael@0: michael@0: } while (s->heap_len >= 2); michael@0: michael@0: s->heap[--(s->heap_max)] = s->heap[SMALLEST]; michael@0: michael@0: /* At this point, the fields freq and dad are set. We can now michael@0: * generate the bit lengths. michael@0: */ michael@0: gen_bitlen(s, (tree_desc *)desc); michael@0: michael@0: /* The field len is now set, we can generate the bit codes */ michael@0: gen_codes ((ct_data *)tree, max_code, s->bl_count); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Scan a literal or distance tree to determine the frequencies of the codes michael@0: * in the bit length tree. michael@0: */ michael@0: local void scan_tree (s, tree, max_code) michael@0: deflate_state *s; michael@0: ct_data *tree; /* the tree to be scanned */ michael@0: int max_code; /* and its largest code of non zero frequency */ michael@0: { michael@0: int n; /* iterates over all tree elements */ michael@0: int prevlen = -1; /* last emitted length */ michael@0: int curlen; /* length of current code */ michael@0: int nextlen = tree[0].Len; /* length of next code */ michael@0: int count = 0; /* repeat count of the current code */ michael@0: int max_count = 7; /* max repeat count */ michael@0: int min_count = 4; /* min repeat count */ michael@0: michael@0: if (nextlen == 0) max_count = 138, min_count = 3; michael@0: tree[max_code+1].Len = (ush)0xffff; /* guard */ michael@0: michael@0: for (n = 0; n <= max_code; n++) { michael@0: curlen = nextlen; nextlen = tree[n+1].Len; michael@0: if (++count < max_count && curlen == nextlen) { michael@0: continue; michael@0: } else if (count < min_count) { michael@0: s->bl_tree[curlen].Freq += count; michael@0: } else if (curlen != 0) { michael@0: if (curlen != prevlen) s->bl_tree[curlen].Freq++; michael@0: s->bl_tree[REP_3_6].Freq++; michael@0: } else if (count <= 10) { michael@0: s->bl_tree[REPZ_3_10].Freq++; michael@0: } else { michael@0: s->bl_tree[REPZ_11_138].Freq++; michael@0: } michael@0: count = 0; prevlen = curlen; michael@0: if (nextlen == 0) { michael@0: max_count = 138, min_count = 3; michael@0: } else if (curlen == nextlen) { michael@0: max_count = 6, min_count = 3; michael@0: } else { michael@0: max_count = 7, min_count = 4; michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Send a literal or distance tree in compressed form, using the codes in michael@0: * bl_tree. michael@0: */ michael@0: local void send_tree (s, tree, max_code) michael@0: deflate_state *s; michael@0: ct_data *tree; /* the tree to be scanned */ michael@0: int max_code; /* and its largest code of non zero frequency */ michael@0: { michael@0: int n; /* iterates over all tree elements */ michael@0: int prevlen = -1; /* last emitted length */ michael@0: int curlen; /* length of current code */ michael@0: int nextlen = tree[0].Len; /* length of next code */ michael@0: int count = 0; /* repeat count of the current code */ michael@0: int max_count = 7; /* max repeat count */ michael@0: int min_count = 4; /* min repeat count */ michael@0: michael@0: /* tree[max_code+1].Len = -1; */ /* guard already set */ michael@0: if (nextlen == 0) max_count = 138, min_count = 3; michael@0: michael@0: for (n = 0; n <= max_code; n++) { michael@0: curlen = nextlen; nextlen = tree[n+1].Len; michael@0: if (++count < max_count && curlen == nextlen) { michael@0: continue; michael@0: } else if (count < min_count) { michael@0: do { send_code(s, curlen, s->bl_tree); } while (--count != 0); michael@0: michael@0: } else if (curlen != 0) { michael@0: if (curlen != prevlen) { michael@0: send_code(s, curlen, s->bl_tree); count--; michael@0: } michael@0: Assert(count >= 3 && count <= 6, " 3_6?"); michael@0: send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); michael@0: michael@0: } else if (count <= 10) { michael@0: send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); michael@0: michael@0: } else { michael@0: send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); michael@0: } michael@0: count = 0; prevlen = curlen; michael@0: if (nextlen == 0) { michael@0: max_count = 138, min_count = 3; michael@0: } else if (curlen == nextlen) { michael@0: max_count = 6, min_count = 3; michael@0: } else { michael@0: max_count = 7, min_count = 4; michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Construct the Huffman tree for the bit lengths and return the index in michael@0: * bl_order of the last bit length code to send. michael@0: */ michael@0: local int build_bl_tree(s) michael@0: deflate_state *s; michael@0: { michael@0: int max_blindex; /* index of last bit length code of non zero freq */ michael@0: michael@0: /* Determine the bit length frequencies for literal and distance trees */ michael@0: scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); michael@0: scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); michael@0: michael@0: /* Build the bit length tree: */ michael@0: build_tree(s, (tree_desc *)(&(s->bl_desc))); michael@0: /* opt_len now includes the length of the tree representations, except michael@0: * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. michael@0: */ michael@0: michael@0: /* Determine the number of bit length codes to send. The pkzip format michael@0: * requires that at least 4 bit length codes be sent. (appnote.txt says michael@0: * 3 but the actual value used is 4.) michael@0: */ michael@0: for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { michael@0: if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; michael@0: } michael@0: /* Update opt_len to include the bit length tree and counts */ michael@0: s->opt_len += 3*(max_blindex+1) + 5+5+4; michael@0: Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", michael@0: s->opt_len, s->static_len)); michael@0: michael@0: return max_blindex; michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Send the header for a block using dynamic Huffman trees: the counts, the michael@0: * lengths of the bit length codes, the literal tree and the distance tree. michael@0: * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. michael@0: */ michael@0: local void send_all_trees(s, lcodes, dcodes, blcodes) michael@0: deflate_state *s; michael@0: int lcodes, dcodes, blcodes; /* number of codes for each tree */ michael@0: { michael@0: int rank; /* index in bl_order */ michael@0: michael@0: Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); michael@0: Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, michael@0: "too many codes"); michael@0: Tracev((stderr, "\nbl counts: ")); michael@0: send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ michael@0: send_bits(s, dcodes-1, 5); michael@0: send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ michael@0: for (rank = 0; rank < blcodes; rank++) { michael@0: Tracev((stderr, "\nbl code %2d ", bl_order[rank])); michael@0: send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); michael@0: } michael@0: Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); michael@0: michael@0: send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ michael@0: Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); michael@0: michael@0: send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ michael@0: Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Send a stored block michael@0: */ michael@0: void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) michael@0: deflate_state *s; michael@0: charf *buf; /* input block */ michael@0: ulg stored_len; /* length of input block */ michael@0: int last; /* one if this is the last block for a file */ michael@0: { michael@0: send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ michael@0: #ifdef DEBUG michael@0: s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; michael@0: s->compressed_len += (stored_len + 4) << 3; michael@0: #endif michael@0: copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) michael@0: */ michael@0: void ZLIB_INTERNAL _tr_flush_bits(s) michael@0: deflate_state *s; michael@0: { michael@0: bi_flush(s); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Send one empty static block to give enough lookahead for inflate. michael@0: * This takes 10 bits, of which 7 may remain in the bit buffer. michael@0: */ michael@0: void ZLIB_INTERNAL _tr_align(s) michael@0: deflate_state *s; michael@0: { michael@0: send_bits(s, STATIC_TREES<<1, 3); michael@0: send_code(s, END_BLOCK, static_ltree); michael@0: #ifdef DEBUG michael@0: s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ michael@0: #endif michael@0: bi_flush(s); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Determine the best encoding for the current block: dynamic trees, static michael@0: * trees or store, and output the encoded block to the zip file. michael@0: */ michael@0: void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) michael@0: deflate_state *s; michael@0: charf *buf; /* input block, or NULL if too old */ michael@0: ulg stored_len; /* length of input block */ michael@0: int last; /* one if this is the last block for a file */ michael@0: { michael@0: ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ michael@0: int max_blindex = 0; /* index of last bit length code of non zero freq */ michael@0: michael@0: /* Build the Huffman trees unless a stored block is forced */ michael@0: if (s->level > 0) { michael@0: michael@0: /* Check if the file is binary or text */ michael@0: if (s->strm->data_type == Z_UNKNOWN) michael@0: s->strm->data_type = detect_data_type(s); michael@0: michael@0: /* Construct the literal and distance trees */ michael@0: build_tree(s, (tree_desc *)(&(s->l_desc))); michael@0: Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, michael@0: s->static_len)); michael@0: michael@0: build_tree(s, (tree_desc *)(&(s->d_desc))); michael@0: Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, michael@0: s->static_len)); michael@0: /* At this point, opt_len and static_len are the total bit lengths of michael@0: * the compressed block data, excluding the tree representations. michael@0: */ michael@0: michael@0: /* Build the bit length tree for the above two trees, and get the index michael@0: * in bl_order of the last bit length code to send. michael@0: */ michael@0: max_blindex = build_bl_tree(s); michael@0: michael@0: /* Determine the best encoding. Compute the block lengths in bytes. */ michael@0: opt_lenb = (s->opt_len+3+7)>>3; michael@0: static_lenb = (s->static_len+3+7)>>3; michael@0: michael@0: Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", michael@0: opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, michael@0: s->last_lit)); michael@0: michael@0: if (static_lenb <= opt_lenb) opt_lenb = static_lenb; michael@0: michael@0: } else { michael@0: Assert(buf != (char*)0, "lost buf"); michael@0: opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ michael@0: } michael@0: michael@0: #ifdef FORCE_STORED michael@0: if (buf != (char*)0) { /* force stored block */ michael@0: #else michael@0: if (stored_len+4 <= opt_lenb && buf != (char*)0) { michael@0: /* 4: two words for the lengths */ michael@0: #endif michael@0: /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. michael@0: * Otherwise we can't have processed more than WSIZE input bytes since michael@0: * the last block flush, because compression would have been michael@0: * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to michael@0: * transform a block into a stored block. michael@0: */ michael@0: _tr_stored_block(s, buf, stored_len, last); michael@0: michael@0: #ifdef FORCE_STATIC michael@0: } else if (static_lenb >= 0) { /* force static trees */ michael@0: #else michael@0: } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { michael@0: #endif michael@0: send_bits(s, (STATIC_TREES<<1)+last, 3); michael@0: compress_block(s, (const ct_data *)static_ltree, michael@0: (const ct_data *)static_dtree); michael@0: #ifdef DEBUG michael@0: s->compressed_len += 3 + s->static_len; michael@0: #endif michael@0: } else { michael@0: send_bits(s, (DYN_TREES<<1)+last, 3); michael@0: send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, michael@0: max_blindex+1); michael@0: compress_block(s, (const ct_data *)s->dyn_ltree, michael@0: (const ct_data *)s->dyn_dtree); michael@0: #ifdef DEBUG michael@0: s->compressed_len += 3 + s->opt_len; michael@0: #endif michael@0: } michael@0: Assert (s->compressed_len == s->bits_sent, "bad compressed size"); michael@0: /* The above check is made mod 2^32, for files larger than 512 MB michael@0: * and uLong implemented on 32 bits. michael@0: */ michael@0: init_block(s); michael@0: michael@0: if (last) { michael@0: bi_windup(s); michael@0: #ifdef DEBUG michael@0: s->compressed_len += 7; /* align on byte boundary */ michael@0: #endif michael@0: } michael@0: Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, michael@0: s->compressed_len-7*last)); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Save the match info and tally the frequency counts. Return true if michael@0: * the current block must be flushed. michael@0: */ michael@0: int ZLIB_INTERNAL _tr_tally (s, dist, lc) michael@0: deflate_state *s; michael@0: unsigned dist; /* distance of matched string */ michael@0: unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ michael@0: { michael@0: s->d_buf[s->last_lit] = (ush)dist; michael@0: s->l_buf[s->last_lit++] = (uch)lc; michael@0: if (dist == 0) { michael@0: /* lc is the unmatched char */ michael@0: s->dyn_ltree[lc].Freq++; michael@0: } else { michael@0: s->matches++; michael@0: /* Here, lc is the match length - MIN_MATCH */ michael@0: dist--; /* dist = match distance - 1 */ michael@0: Assert((ush)dist < (ush)MAX_DIST(s) && michael@0: (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && michael@0: (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); michael@0: michael@0: s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; michael@0: s->dyn_dtree[d_code(dist)].Freq++; michael@0: } michael@0: michael@0: #ifdef TRUNCATE_BLOCK michael@0: /* Try to guess if it is profitable to stop the current block here */ michael@0: if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { michael@0: /* Compute an upper bound for the compressed length */ michael@0: ulg out_length = (ulg)s->last_lit*8L; michael@0: ulg in_length = (ulg)((long)s->strstart - s->block_start); michael@0: int dcode; michael@0: for (dcode = 0; dcode < D_CODES; dcode++) { michael@0: out_length += (ulg)s->dyn_dtree[dcode].Freq * michael@0: (5L+extra_dbits[dcode]); michael@0: } michael@0: out_length >>= 3; michael@0: Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", michael@0: s->last_lit, in_length, out_length, michael@0: 100L - out_length*100L/in_length)); michael@0: if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; michael@0: } michael@0: #endif michael@0: return (s->last_lit == s->lit_bufsize-1); michael@0: /* We avoid equality with lit_bufsize because of wraparound at 64K michael@0: * on 16 bit machines and because stored blocks are restricted to michael@0: * 64K-1 bytes. michael@0: */ michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Send the block data compressed using the given Huffman trees michael@0: */ michael@0: local void compress_block(s, ltree, dtree) michael@0: deflate_state *s; michael@0: const ct_data *ltree; /* literal tree */ michael@0: const ct_data *dtree; /* distance tree */ michael@0: { michael@0: unsigned dist; /* distance of matched string */ michael@0: int lc; /* match length or unmatched char (if dist == 0) */ michael@0: unsigned lx = 0; /* running index in l_buf */ michael@0: unsigned code; /* the code to send */ michael@0: int extra; /* number of extra bits to send */ michael@0: michael@0: if (s->last_lit != 0) do { michael@0: dist = s->d_buf[lx]; michael@0: lc = s->l_buf[lx++]; michael@0: if (dist == 0) { michael@0: send_code(s, lc, ltree); /* send a literal byte */ michael@0: Tracecv(isgraph(lc), (stderr," '%c' ", lc)); michael@0: } else { michael@0: /* Here, lc is the match length - MIN_MATCH */ michael@0: code = _length_code[lc]; michael@0: send_code(s, code+LITERALS+1, ltree); /* send the length code */ michael@0: extra = extra_lbits[code]; michael@0: if (extra != 0) { michael@0: lc -= base_length[code]; michael@0: send_bits(s, lc, extra); /* send the extra length bits */ michael@0: } michael@0: dist--; /* dist is now the match distance - 1 */ michael@0: code = d_code(dist); michael@0: Assert (code < D_CODES, "bad d_code"); michael@0: michael@0: send_code(s, code, dtree); /* send the distance code */ michael@0: extra = extra_dbits[code]; michael@0: if (extra != 0) { michael@0: dist -= base_dist[code]; michael@0: send_bits(s, dist, extra); /* send the extra distance bits */ michael@0: } michael@0: } /* literal or match pair ? */ michael@0: michael@0: /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ michael@0: Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, michael@0: "pendingBuf overflow"); michael@0: michael@0: } while (lx < s->last_lit); michael@0: michael@0: send_code(s, END_BLOCK, ltree); michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Check if the data type is TEXT or BINARY, using the following algorithm: michael@0: * - TEXT if the two conditions below are satisfied: michael@0: * a) There are no non-portable control characters belonging to the michael@0: * "black list" (0..6, 14..25, 28..31). michael@0: * b) There is at least one printable character belonging to the michael@0: * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). michael@0: * - BINARY otherwise. michael@0: * - The following partially-portable control characters form a michael@0: * "gray list" that is ignored in this detection algorithm: michael@0: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). michael@0: * IN assertion: the fields Freq of dyn_ltree are set. michael@0: */ michael@0: local int detect_data_type(s) michael@0: deflate_state *s; michael@0: { michael@0: /* black_mask is the bit mask of black-listed bytes michael@0: * set bits 0..6, 14..25, and 28..31 michael@0: * 0xf3ffc07f = binary 11110011111111111100000001111111 michael@0: */ michael@0: unsigned long black_mask = 0xf3ffc07fUL; michael@0: int n; michael@0: michael@0: /* Check for non-textual ("black-listed") bytes. */ michael@0: for (n = 0; n <= 31; n++, black_mask >>= 1) michael@0: if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) michael@0: return Z_BINARY; michael@0: michael@0: /* Check for textual ("white-listed") bytes. */ michael@0: if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 michael@0: || s->dyn_ltree[13].Freq != 0) michael@0: return Z_TEXT; michael@0: for (n = 32; n < LITERALS; n++) michael@0: if (s->dyn_ltree[n].Freq != 0) michael@0: return Z_TEXT; michael@0: michael@0: /* There are no "black-listed" or "white-listed" bytes: michael@0: * this stream either is empty or has tolerated ("gray-listed") bytes only. michael@0: */ michael@0: return Z_BINARY; michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Reverse the first len bits of a code, using straightforward code (a faster michael@0: * method would use a table) michael@0: * IN assertion: 1 <= len <= 15 michael@0: */ michael@0: local unsigned bi_reverse(code, len) michael@0: unsigned code; /* the value to invert */ michael@0: int len; /* its bit length */ michael@0: { michael@0: register unsigned res = 0; michael@0: do { michael@0: res |= code & 1; michael@0: code >>= 1, res <<= 1; michael@0: } while (--len > 0); michael@0: return res >> 1; michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Flush the bit buffer, keeping at most 7 bits in it. michael@0: */ michael@0: local void bi_flush(s) michael@0: deflate_state *s; michael@0: { michael@0: if (s->bi_valid == 16) { michael@0: put_short(s, s->bi_buf); michael@0: s->bi_buf = 0; michael@0: s->bi_valid = 0; michael@0: } else if (s->bi_valid >= 8) { michael@0: put_byte(s, (Byte)s->bi_buf); michael@0: s->bi_buf >>= 8; michael@0: s->bi_valid -= 8; michael@0: } michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Flush the bit buffer and align the output on a byte boundary michael@0: */ michael@0: local void bi_windup(s) michael@0: deflate_state *s; michael@0: { michael@0: if (s->bi_valid > 8) { michael@0: put_short(s, s->bi_buf); michael@0: } else if (s->bi_valid > 0) { michael@0: put_byte(s, (Byte)s->bi_buf); michael@0: } michael@0: s->bi_buf = 0; michael@0: s->bi_valid = 0; michael@0: #ifdef DEBUG michael@0: s->bits_sent = (s->bits_sent+7) & ~7; michael@0: #endif michael@0: } michael@0: michael@0: /* =========================================================================== michael@0: * Copy a stored block, storing first the length and its michael@0: * one's complement if requested. michael@0: */ michael@0: local void copy_block(s, buf, len, header) michael@0: deflate_state *s; michael@0: charf *buf; /* the input data */ michael@0: unsigned len; /* its length */ michael@0: int header; /* true if block header must be written */ michael@0: { michael@0: bi_windup(s); /* align on byte boundary */ michael@0: michael@0: if (header) { michael@0: put_short(s, (ush)len); michael@0: put_short(s, (ush)~len); michael@0: #ifdef DEBUG michael@0: s->bits_sent += 2*16; michael@0: #endif michael@0: } michael@0: #ifdef DEBUG michael@0: s->bits_sent += (ulg)len<<3; michael@0: #endif michael@0: while (len--) { michael@0: put_byte(s, *buf++); michael@0: } michael@0: }