📄 trees.c
字号:
/* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */#if (!defined(ASMV) || !defined(RISCOS))local char *out_buf;#elsechar *out_buf;#endif/* Current output buffer. */#if (!defined(ASMV) || !defined(RISCOS))local unsigned out_offset;#elseunsigned out_offset;#endif/* Current offset in output buffer. * On 16 bit machines, the buffer is limited to 64K. */#if !defined(ASMV) || !defined(RISCOS)local unsigned out_size;#elseunsigned out_size;#endif/* Size of current output buffer *//* Output a 16 bit value to the bit stream, lower (oldest) byte first */#define PUTSHORT(w) \{ if (out_offset >= out_size-1) \ flush_outbuf(out_buf, &out_offset); \ out_buf[out_offset++] = (char) ((w) & 0xff); \ out_buf[out_offset++] = (char) ((ush)(w) >> 8); \}#define PUTBYTE(b) \{ if (out_offset >= out_size) \ flush_outbuf(out_buf, &out_offset); \ out_buf[out_offset++] = (char) (b); \}#ifdef DEBUGlocal ulg bits_sent; /* bit length of the compressed data */extern ulg isize; /* byte length of input file */#endifextern long block_start; /* window offset of current block */extern unsigned near strstart; /* window offset of current string *//* =========================================================================== * Local (static) routines in this file. */local void init_block OF((void));local void pqdownheap OF((ct_data near *tree, int k));local void gen_bitlen OF((tree_desc near *desc));local void gen_codes OF((ct_data near *tree, int max_code));local void build_tree OF((tree_desc near *desc));local void scan_tree OF((ct_data near *tree, int max_code));local void send_tree OF((ct_data near *tree, int max_code));local int build_bl_tree OF((void));local void send_all_trees OF((int lcodes, int dcodes, int blcodes));local void compress_block OF((ct_data near *ltree, ct_data near *dtree));local void set_file_type OF((void));#if (!defined(ASMV) || !defined(RISCOS))local void send_bits OF((int value, int length));local unsigned bi_reverse OF((unsigned code, int len));#endiflocal void bi_windup OF((void));local void copy_block OF((char *buf, unsigned len, int header));#ifndef DEBUG# define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len) /* Send a code of the given tree. c and tree must not have side effects */#else /* DEBUG */# define send_code(c, tree) \ { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \ send_bits(tree[c].Code, tree[c].Len); }#endif#define d_code(dist) \ ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])/* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. dist_code[256] and dist_code[257] are never * used. */#define Max(a,b) (a >= b ? a : b)/* the arguments must not have side effects *//* =========================================================================== * Allocate the match buffer, initialize the various tables and save the * location of the internal file attribute (ascii/binary) and method * (DEFLATE/STORE). */void ct_init(attr, method) ush *attr; /* pointer to internal file attribute */ int *method; /* pointer to compression method */{ int n; /* iterates over tree elements */ int bits; /* bit counter */ int length; /* length value */ int code; /* code value */ int dist; /* distance index */ file_type = attr; file_method = method; cmpr_bytelen = cmpr_len_bits = 0L;#ifdef DEBUG input_len = 0L;#endif if (static_dtree[0].Len != 0) return; /* ct_init already called */#ifdef DYN_ALLOC d_buf = (ush far *) zcalloc(DIST_BUFSIZE, sizeof(ush)); l_buf = (uch far *) zcalloc(LIT_BUFSIZE/2, 2); /* Avoid using the value 64K on 16 bit machines */ if (l_buf == NULL || d_buf == NULL) ziperr(ZE_MEM, "ct_init: out of memory");#endif /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { length_code[length++] = (uch)code; } } Assert(length == 256, "ct_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ length_code[length-1] = (uch)code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { dist_code[dist++] = (uch)code; } } Assert(dist == 256, "ct_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { dist_code[256 + dist++] = (uch)code; } } Assert(dist == 256, "ct_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; n = 0; while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes((ct_data near *)static_ltree, L_CODES+1); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n].Len = 5; static_dtree[n].Code = (ush)bi_reverse(n, 5); } /* Initialize the first block of the first file: */ init_block();}/* =========================================================================== * Initialize a new block. */local void init_block(){ int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) bl_tree[n].Freq = 0; dyn_ltree[END_BLOCK].Freq = 1; opt_len = static_len = 0L; last_lit = last_dist = last_flags = 0; flags = 0; flag_bit = 1;}#define SMALLEST 1/* Index within the heap array of least frequent node in the Huffman tree *//* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */#define pqremove(tree, top) \{\ top = heap[SMALLEST]; \ heap[SMALLEST] = heap[heap_len--]; \ pqdownheap(tree, SMALLEST); \}/* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */#define smaller(tree, n, m) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))/* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */local void pqdownheap(tree, k) ct_data near *tree; /* the tree to restore */ int k; /* node to move down */{ int v = heap[k]; int j = k << 1; /* left son of k */ int htemp; /* required because of bug in SASC compiler */ while (j <= heap_len) { /* Set j to the smallest of the two sons: */ if (j < heap_len && smaller(tree, heap[j+1], heap[j])) j++; /* Exit if v is smaller than both sons */ htemp = heap[j]; if (smaller(tree, v, htemp)) break; /* Exchange v with the smallest son */ heap[k] = htemp; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } heap[k] = v;}/* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */local void gen_bitlen(desc) tree_desc near *desc; /* the tree descriptor */{ ct_data near *tree = desc->dyn_tree; int near *extra = desc->extra_bits; int base = desc->extra_base; int max_code = desc->max_code; int max_length = desc->max_length; ct_data near *stree = desc->static_tree; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ ush f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[heap[heap_max]].Len = 0; /* root of the heap */ for (h = heap_max+1; h < HEAP_SIZE; h++) { n = heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (ush)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; opt_len += (ulg)f * (bits + xbits); if (stree) static_len += (ulg)f * (stree[n].Len + xbits); } if (overflow == 0) return; Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (bl_count[bits] == 0) bits--; bl_count[bits]--; /* move one leaf down the tree */ bl_count[bits+1] += (ush)2; /* move one overflow item as its brother */ bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = bl_count[bits]; while (n != 0) { m = heap[--h]; if (m > max_code) continue; if (tree[m].Len != (ush)bits) { Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); opt_len += ((long)bits-(long)tree[m].Len)*(long)tree[m].Freq; tree[m].Len = (ush)bits; } n--; } }}/* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */local void gen_codes (tree, max_code) ct_data near *tree; /* the tree to decorate */ int max_code; /* largest code with non zero frequency */{ ush next_code[MAX_BITS+1]; /* next code value for each bit length */ ush code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (ush)((code + bl_count[bits-1]) << 1); } /* Check that the bit counts in bl_count are consistent. The last code
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -