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