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