📄 ztrees.cpp
字号:
// ztrees.cpp - modified by Wei Dai from:
// Distributed with Jean-loup Gailly's permission.
/*
The following sorce code is derived from Info-Zip 'zip' 2.01
distribution copyrighted by Mark Adler, Richard B. Wales,
Jean-loup Gailly, Kai Uwe Rommel, Igor Mandrichenko and John Bush.
*/
/*
* trees.c by Jean-loup Gailly
*
* This is a new version of im_ctree.c originally written by Richard B. Wales
* for the defunct implosion method.
*
* PURPOSE
*
* Encode various sets of source values using variable-length
* binary code trees.
*
* DISCUSSION
*
* The PKZIP "deflation" process uses several Huffman trees. The more
* common source values are represented by shorter bit sequences.
*
* Each code tree is stored in the ZIP file in a compressed form
* which is itself a Huffman encoding of the lengths of
* all the code strings (in ascending order by source values).
* The actual code strings are reconstructed from the lengths in
* the UNZIP process, as described in the "application note"
* (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
*
* REFERENCES
*
* Lynch, Thomas J.
* Data Compression: Techniques and Applications, pp. 53-55.
* Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
*
* Storer, James A.
* Data Compression: Methods and Theory, pp. 49-50.
* Computer Science Press, 1988. ISBN 0-7167-8156-5.
*
* Sedgewick, R.
* Algorithms, p290.
* Addison-Wesley, 1983. ISBN 0-201-06672-6.
*
* INTERFACE
*
* int ct_init (void)
* Allocate the match buffer and initialize the various tables.
*
* int ct_tally(int dist, int lc);
* Save the match info and tally the frequency counts.
* Return true if the current block must be flushed.
*
* long flush_block (char *buf, ulg stored_len, int eof)
* Determine the best encoding for the current block: dynamic trees,
* static trees or store, and output the encoded block to the zip
* file. Returns the total compressed length for the file so far.
*/
#include "pch.h"
#include "ztrees.h"
NAMESPACE_BEGIN(CryptoPP)
bool CodeTree::streesBuilt = false;
CodeTree::ct_data CodeTree::static_ltree[CodeTree::L_CODES+2];
CodeTree::ct_data CodeTree::static_dtree[CodeTree::D_CODES];
const int CodeTree::extra_lbits[] /* extra bits for each length code */
= {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};
const int CodeTree::extra_dbits[] /* extra bits for each distance code */
= {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};
const int CodeTree::extra_blbits[]/* extra bits for each bit length code */
= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
const byte CodeTree::bl_order[]
= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
#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 */
#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 */
static unsigned reverse(unsigned int code, int len)
/* Reverse the first len bits of a code. */
{
register unsigned res = 0;
do res = (res << 1) | (code & 1), code>>=1; while (--len);
return res;
}
/* Allocate the match buffer and initialize the various tables. */
CodeTree::CodeTree(int deflate_level, BufferedTransformation &outQ)
: BitOutput(outQ),
deflate_level(deflate_level),
dyn_ltree(HEAP_SIZE), dyn_dtree(2*D_CODES+1),
bl_tree(2*BL_CODES+1),
bl_count(MAX_BITS+1),
l_desc(dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0),
d_desc(dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0),
bl_desc(bl_tree, (ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0),
heap(2*L_CODES+1),
depth(2*L_CODES+1),
length_code(MAX_MATCH-MIN_MATCH+1),
dist_code(512),
base_length(LENGTH_CODES),
base_dist(D_CODES),
l_buf(LIT_BUFSIZE),
d_buf(DIST_BUFSIZE),
flag_buf(LIT_BUFSIZE/8)
{
unsigned int n; /* iterates over tree elements */
int bits; /* bit counter */
int length; /* length value */
register int code; /* code value */
int dist; /* distance index */
compressed_len = input_len = 0L;
/* 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++] = (byte)code;
}
}
assert (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] = (byte)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++] = (byte)code;
}
}
assert (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++] = (byte)code;
}
}
assert (dist == 256);
if (!streesBuilt)
{
/* 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(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 = reverse(n, 5);
}
streesBuilt = true;
}
/* Initialize the first block of the first file: */
init_block();
}
/* Initialize a new block. */
void CodeTree::init_block()
{
register 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).
*/
void CodeTree::pqdownheap(ct_data *tree, int k)
{
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.
*/
void CodeTree::gen_bitlen(tree_desc *desc)
{
ct_data *tree = desc->dyn_tree;
const int *extra = desc->extra_bits;
int base = desc->extra_base;
int max_code = desc->max_code;
int max_length = desc->max_length;
const ct_data *stree = desc->static_tree;
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int xbits; /* extra bits */
word16 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 = 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 += (word32)f * (bits + xbits);
if (stree) static_len += (word32)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] += 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 != (unsigned) 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 = 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.
*/
void CodeTree::gen_codes (ct_data *tree, int max_code)
{
word16 next_code[MAX_BITS+1]; /* next code value for each bit length */
word16 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 = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1);
// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n].Len;
if (len == 0) continue;
/* Now reverse the bits */
tree[n].Code = reverse(next_code[len]++, len);
// Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/*
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
void CodeTree::build_tree(tree_desc *desc)
{
ct_data *tree = desc->dyn_tree;
const ct_data *stree = desc->static_tree;
int elems = desc->elems;
int n, m; /* iterate over heap elements */
int max_code = -1; /* largest code with non zero frequency */
int node = elems; /* next internal node of the tree */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
heap_len = 0, heap_max = HEAP_SIZE;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -