/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-2005 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* ALGORITHM
*
* The "deflation" process uses several Huffman trees. The more
* common source values are represented by shorter bit sequences.
*
* Each code tree is stored 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 inflate process, as described
* in the deflate specification.
*
* REFERENCES
*
* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
*
* 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.
*/
/* @(#) $Id$ */
/* #define GEN_TREES_H */
#include "deflate.h"
#ifdef DEBUG
# include <ctype.h>
#endif
/* ===========================================================================
* Constants
*/
/* Bit length codes must not exceed MAX_BL_BITS bits */
/* end of block literal code */
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
/* repeat a zero length 3-10 times (3 bits of repeat count) */
/* repeat a zero length 11-138 times (7 bits of repeat count) */
= {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};
= {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};
= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
= {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.
*/
/* Number of bits used within bi_buf. (bi_buf might be implemented on
* more than 16 bits on some systems.)
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
#if defined(GEN_TREES_H) || !defined(STDC)
/* non ANSI compilers may not accept trees.h */
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
/* length code for each normalized match length (0 == MIN_MATCH) */
/* First normalized length for each code (0 = MIN_MATCH) */
/* First normalized distance for each code (0 = distance of 1) */
#else
# include "trees.h"
#endif /* GEN_TREES_H */
struct static_tree_desc_s {
};
/* ===========================================================================
* Local (static) routines in this file.
*/
int blcodes));
int header));
#ifdef GEN_TREES_H
#endif
#ifndef DEBUG
/* Send a code of the given tree. c and tree must not have side effects */
#else /* DEBUG */
#endif
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
#define put_short(s, w) { \
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
#ifdef DEBUG
deflate_state *s;
int value; /* value to send */
int length; /* number of bits */
{
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
} else {
}
}
#else /* !DEBUG */
} else {\
}\
}
#endif /* DEBUG */
/* the arguments must not have side effects */
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
{
#if defined(GEN_TREES_H) || !defined(STDC)
static int static_init_done = 0;
int n; /* iterates over tree elements */
/* number of codes at each bit length for an optimal tree */
if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
}
}
/* 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:
*/
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
}
}
}
}
/* Construct the codes of the static literal tree */
n = 0;
/* 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)
*/
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
}
static_init_done = 1;
# ifdef GEN_TREES_H
# endif
#endif /* defined(GEN_TREES_H) || !defined(STDC) */
}
/* ===========================================================================
* Genererate the file trees.h describing the static trees.
*/
#ifdef GEN_TREES_H
# ifndef DEBUG
# include <stdio.h>
# endif
((i) == (last)? "\n};\n\n" : \
void gen_trees_header()
{
int i;
"/* header created automatically with -DGEN_TREES_H */\n\n");
for (i = 0; i < L_CODES+2; i++) {
}
for (i = 0; i < D_CODES; i++) {
}
for (i = 0; i < DIST_CODE_LEN; i++) {
}
}
for (i = 0; i < LENGTH_CODES; i++) {
}
for (i = 0; i < D_CODES; i++) {
}
}
#endif /* GEN_TREES_H */
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
void _tr_init(s)
deflate_state *s;
{
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
s->compressed_len = 0L;
s->bits_sent = 0L;
#endif
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Initialize a new block.
*/
deflate_state *s;
{
int n; /* iterates over tree elements */
/* Initialize the trees. */
s->opt_len = s->static_len = 0L;
}
/* 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.
*/
{\
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
/* ===========================================================================
* 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).
*/
deflate_state *s;
int k; /* node to move down */
{
int v = s->heap[k];
int j = k << 1; /* left son of k */
while (j <= s->heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s->heap_len &&
j++;
}
/* Exit if v is smaller than both sons */
/* Exchange v with the smallest son */
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s->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.
*/
deflate_state *s;
{
int h; /* heap index */
int n, m; /* iterate over the tree elements */
ush f; /* frequency */
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
n = s->heap[h];
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) continue; /* not a leaf node */
xbits = 0;
}
if (overflow == 0) return;
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
s->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.)
*/
while (n != 0) {
m = s->heap[--h];
if (m > max_code) continue;
}
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.
*/
int max_code; /* largest code with non zero frequency */
{
int n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
"inconsistent bit counts");
for (n = 0; n <= max_code; n++) {
if (len == 0) continue;
/* Now reverse the bits */
}
}
/* ===========================================================================
* 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.
*/
deflate_state *s;
{
int n, m; /* iterate over heap elements */
/* 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.
*/
for (n = 0; n < elems; n++) {
s->depth[n] = 0;
} else {
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s->heap_len < 2) {
/* node is 0 or 1 so it does not have extra bits */
}
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
/* Create a new node father of n and m */
#ifdef DUMP_BL_TREE
}
#endif
/* and insert the new node in the heap */
} while (s->heap_len >= 2);
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
/* The field len is now set, we can generate the bit codes */
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
deflate_state *s;
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
for (n = 0; n <= max_code; n++) {
continue;
} else if (curlen != 0) {
} else if (count <= 10) {
} else {
}
if (nextlen == 0) {
} else {
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
deflate_state *s;
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
/* tree[max_code+1].Len = -1; */ /* guard already set */
for (n = 0; n <= max_code; n++) {
continue;
} else if (curlen != 0) {
}
} else if (count <= 10) {
} else {
}
if (nextlen == 0) {
} else {
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
deflate_state *s;
{
/* Determine the bit length frequencies for literal and distance trees */
/* Build the bit length tree: */
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
}
/* Update opt_len to include the bit length tree and counts */
s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
deflate_state *s;
{
"too many codes");
}
}
/* ===========================================================================
* Send a stored block
*/
deflate_state *s;
int eof; /* true if this is the last block for a file */
{
#ifdef DEBUG
#endif
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
* The current inflate code requires 9 bits of lookahead. If the
* last two codes for the previous block (real code plus EOB) were coded
* on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
* the last real code. In this case we send two empty static blocks instead
* of one. (There are no problems if the previous block is stored or fixed.)
* To simplify the code, we assume the worst case of last real code encoded
* on one bit only.
*/
void _tr_align(s)
deflate_state *s;
{
#ifdef DEBUG
#endif
bi_flush(s);
/* Of the 10 bits for the empty block, we have already sent
* (10 - bi_valid) bits. The lookahead for the last real code (before
* the EOB of the previous block) was thus at least one plus the length
* of the EOB plus what we have just sent of the empty static block.
*/
#ifdef DEBUG
s->compressed_len += 10L;
#endif
bi_flush(s);
}
s->last_eob_len = 7;
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
deflate_state *s;
int eof; /* true if this is the last block for a file */
{
/* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) {
/* Check if the file is binary or text */
set_data_type(s);
/* Construct the literal and distance trees */
s->static_len));
s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
s->last_lit));
} else {
}
#ifdef FORCE_STORED
if (buf != (char*)0) { /* force stored block */
#else
/* 4: two words for the lengths */
#endif
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
#ifdef FORCE_STATIC
} else if (static_lenb >= 0) { /* force static trees */
#else
#endif
#ifdef DEBUG
#endif
} else {
max_blindex+1);
#ifdef DEBUG
#endif
}
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (eof) {
bi_windup(s);
#ifdef DEBUG
#endif
}
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
deflate_state *s;
unsigned dist; /* distance of matched string */
unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
if (dist == 0) {
/* lc is the unmatched char */
} else {
s->matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
}
#ifdef TRUNCATE_BLOCK
/* Try to guess if it is profitable to stop the current block here */
/* Compute an upper bound for the compressed length */
int dcode;
}
out_length >>= 3;
}
#endif
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
deflate_state *s;
{
if (s->last_lit != 0) do {
if (dist == 0) {
} else {
/* Here, lc is the match length - MIN_MATCH */
if (extra != 0) {
}
dist--; /* dist is now the match distance - 1 */
if (extra != 0) {
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
"pendingBuf overflow");
}
/* ===========================================================================
* Set the data type to BINARY or TEXT, using a crude approximation:
* set it to Z_TEXT if all symbols are either printable characters (33 to 255)
* or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
* IN assertion: the fields Freq of dyn_ltree are set.
*/
deflate_state *s;
{
int n;
for (n = 0; n < 9; n++)
break;
if (n == 9)
for (n = 14; n < 32; n++)
break;
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
unsigned code; /* the value to invert */
int len; /* its bit length */
{
register unsigned res = 0;
do {
} while (--len > 0);
return res >> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
deflate_state *s;
{
if (s->bi_valid == 16) {
s->bi_buf = 0;
s->bi_valid = 0;
} else if (s->bi_valid >= 8) {
s->bi_buf >>= 8;
s->bi_valid -= 8;
}
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
deflate_state *s;
{
if (s->bi_valid > 8) {
} else if (s->bi_valid > 0) {
}
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
#endif
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
deflate_state *s;
unsigned len; /* its length */
int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
#ifdef DEBUG
#endif
}
#ifdef DEBUG
#endif
while (len--) {
}
}