Path: blob/master/src/java.base/share/native/libzip/zlib/trees.c
41153 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324/* trees.c -- output deflated data using Huffman coding25* Copyright (C) 1995-2017 Jean-loup Gailly26* detect_data_type() function provided freely by Cosmin Truta, 200627* For conditions of distribution and use, see copyright notice in zlib.h28*/2930/*31* ALGORITHM32*33* The "deflation" process uses several Huffman trees. The more34* common source values are represented by shorter bit sequences.35*36* Each code tree is stored in a compressed form which is itself37* a Huffman encoding of the lengths of all the code strings (in38* ascending order by source values). The actual code strings are39* reconstructed from the lengths in the inflate process, as described40* in the deflate specification.41*42* REFERENCES43*44* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".45* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc46*47* Storer, James A.48* Data Compression: Methods and Theory, pp. 49-50.49* Computer Science Press, 1988. ISBN 0-7167-8156-5.50*51* Sedgewick, R.52* Algorithms, p290.53* Addison-Wesley, 1983. ISBN 0-201-06672-6.54*/5556/* @(#) $Id$ */5758/* #define GEN_TREES_H */5960#include "deflate.h"6162#ifdef ZLIB_DEBUG63# include <ctype.h>64#endif6566/* ===========================================================================67* Constants68*/6970#define MAX_BL_BITS 771/* Bit length codes must not exceed MAX_BL_BITS bits */7273#define END_BLOCK 25674/* end of block literal code */7576#define REP_3_6 1677/* repeat previous bit length 3-6 times (2 bits of repeat count) */7879#define REPZ_3_10 1780/* repeat a zero length 3-10 times (3 bits of repeat count) */8182#define REPZ_11_138 1883/* repeat a zero length 11-138 times (7 bits of repeat count) */8485local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */86= {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};8788local const int extra_dbits[D_CODES] /* extra bits for each distance code */89= {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};9091local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */92= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};9394local const uch bl_order[BL_CODES]95= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};96/* The lengths of the bit length codes are sent in order of decreasing97* probability, to avoid transmitting the lengths for unused bit length codes.98*/99100/* ===========================================================================101* Local data. These are initialized only once.102*/103104#define DIST_CODE_LEN 512 /* see definition of array dist_code below */105106#if defined(GEN_TREES_H) || !defined(STDC)107/* non ANSI compilers may not accept trees.h */108109local ct_data static_ltree[L_CODES+2];110/* The static literal tree. Since the bit lengths are imposed, there is no111* need for the L_CODES extra codes used during heap construction. However112* The codes 286 and 287 are needed to build a canonical tree (see _tr_init113* below).114*/115116local ct_data static_dtree[D_CODES];117/* The static distance tree. (Actually a trivial tree since all codes use118* 5 bits.)119*/120121uch _dist_code[DIST_CODE_LEN];122/* Distance codes. The first 256 values correspond to the distances123* 3 .. 258, the last 256 values correspond to the top 8 bits of124* the 15 bit distances.125*/126127uch _length_code[MAX_MATCH-MIN_MATCH+1];128/* length code for each normalized match length (0 == MIN_MATCH) */129130local int base_length[LENGTH_CODES];131/* First normalized length for each code (0 = MIN_MATCH) */132133local int base_dist[D_CODES];134/* First normalized distance for each code (0 = distance of 1) */135136#else137# include "trees.h"138#endif /* GEN_TREES_H */139140struct static_tree_desc_s {141const ct_data *static_tree; /* static tree or NULL */142const intf *extra_bits; /* extra bits for each code or NULL */143int extra_base; /* base index for extra_bits */144int elems; /* max number of elements in the tree */145int max_length; /* max bit length for the codes */146};147148local const static_tree_desc static_l_desc =149{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};150151local const static_tree_desc static_d_desc =152{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};153154local const static_tree_desc static_bl_desc =155{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};156157/* ===========================================================================158* Local (static) routines in this file.159*/160161local void tr_static_init OF((void));162local void init_block OF((deflate_state *s));163local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));164local void gen_bitlen OF((deflate_state *s, tree_desc *desc));165local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));166local void build_tree OF((deflate_state *s, tree_desc *desc));167local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));168local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));169local int build_bl_tree OF((deflate_state *s));170local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,171int blcodes));172local void compress_block OF((deflate_state *s, const ct_data *ltree,173const ct_data *dtree));174local int detect_data_type OF((deflate_state *s));175local unsigned bi_reverse OF((unsigned value, int length));176local void bi_windup OF((deflate_state *s));177local void bi_flush OF((deflate_state *s));178179#ifdef GEN_TREES_H180local void gen_trees_header OF((void));181#endif182183#ifndef ZLIB_DEBUG184# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)185/* Send a code of the given tree. c and tree must not have side effects */186187#else /* !ZLIB_DEBUG */188# define send_code(s, c, tree) \189{ if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \190send_bits(s, tree[c].Code, tree[c].Len); }191#endif192193/* ===========================================================================194* Output a short LSB first on the stream.195* IN assertion: there is enough room in pendingBuf.196*/197#define put_short(s, w) { \198put_byte(s, (uch)((w) & 0xff)); \199put_byte(s, (uch)((ush)(w) >> 8)); \200}201202/* ===========================================================================203* Send a value on a given number of bits.204* IN assertion: length <= 16 and value fits in length bits.205*/206#ifdef ZLIB_DEBUG207local void send_bits OF((deflate_state *s, int value, int length));208209local void send_bits(s, value, length)210deflate_state *s;211int value; /* value to send */212int length; /* number of bits */213{214Tracevv((stderr," l %2d v %4x ", length, value));215Assert(length > 0 && length <= 15, "invalid length");216s->bits_sent += (ulg)length;217218/* If not enough room in bi_buf, use (valid) bits from bi_buf and219* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))220* unused bits in value.221*/222if (s->bi_valid > (int)Buf_size - length) {223s->bi_buf |= (ush)value << s->bi_valid;224put_short(s, s->bi_buf);225s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);226s->bi_valid += length - Buf_size;227} else {228s->bi_buf |= (ush)value << s->bi_valid;229s->bi_valid += length;230}231}232#else /* !ZLIB_DEBUG */233234#define send_bits(s, value, length) \235{ int len = length;\236if (s->bi_valid > (int)Buf_size - len) {\237int val = (int)value;\238s->bi_buf |= (ush)val << s->bi_valid;\239put_short(s, s->bi_buf);\240s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\241s->bi_valid += len - Buf_size;\242} else {\243s->bi_buf |= (ush)(value) << s->bi_valid;\244s->bi_valid += len;\245}\246}247#endif /* ZLIB_DEBUG */248249250/* the arguments must not have side effects */251252/* ===========================================================================253* Initialize the various 'constant' tables.254*/255local void tr_static_init()256{257#if defined(GEN_TREES_H) || !defined(STDC)258static int static_init_done = 0;259int n; /* iterates over tree elements */260int bits; /* bit counter */261int length; /* length value */262int code; /* code value */263int dist; /* distance index */264ush bl_count[MAX_BITS+1];265/* number of codes at each bit length for an optimal tree */266267if (static_init_done) return;268269/* For some embedded targets, global variables are not initialized: */270#ifdef NO_INIT_GLOBAL_POINTERS271static_l_desc.static_tree = static_ltree;272static_l_desc.extra_bits = extra_lbits;273static_d_desc.static_tree = static_dtree;274static_d_desc.extra_bits = extra_dbits;275static_bl_desc.extra_bits = extra_blbits;276#endif277278/* Initialize the mapping length (0..255) -> length code (0..28) */279length = 0;280for (code = 0; code < LENGTH_CODES-1; code++) {281base_length[code] = length;282for (n = 0; n < (1<<extra_lbits[code]); n++) {283_length_code[length++] = (uch)code;284}285}286Assert (length == 256, "tr_static_init: length != 256");287/* Note that the length 255 (match length 258) can be represented288* in two different ways: code 284 + 5 bits or code 285, so we289* overwrite length_code[255] to use the best encoding:290*/291_length_code[length-1] = (uch)code;292293/* Initialize the mapping dist (0..32K) -> dist code (0..29) */294dist = 0;295for (code = 0 ; code < 16; code++) {296base_dist[code] = dist;297for (n = 0; n < (1<<extra_dbits[code]); n++) {298_dist_code[dist++] = (uch)code;299}300}301Assert (dist == 256, "tr_static_init: dist != 256");302dist >>= 7; /* from now on, all distances are divided by 128 */303for ( ; code < D_CODES; code++) {304base_dist[code] = dist << 7;305for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {306_dist_code[256 + dist++] = (uch)code;307}308}309Assert (dist == 256, "tr_static_init: 256+dist != 512");310311/* Construct the codes of the static literal tree */312for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;313n = 0;314while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;315while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;316while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;317while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;318/* Codes 286 and 287 do not exist, but we must include them in the319* tree construction to get a canonical Huffman tree (longest code320* all ones)321*/322gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);323324/* The static distance tree is trivial: */325for (n = 0; n < D_CODES; n++) {326static_dtree[n].Len = 5;327static_dtree[n].Code = bi_reverse((unsigned)n, 5);328}329static_init_done = 1;330331# ifdef GEN_TREES_H332gen_trees_header();333# endif334#endif /* defined(GEN_TREES_H) || !defined(STDC) */335}336337/* ===========================================================================338* Genererate the file trees.h describing the static trees.339*/340#ifdef GEN_TREES_H341# ifndef ZLIB_DEBUG342# include <stdio.h>343# endif344345# define SEPARATOR(i, last, width) \346((i) == (last)? "\n};\n\n" : \347((i) % (width) == (width)-1 ? ",\n" : ", "))348349void gen_trees_header()350{351FILE *header = fopen("trees.h", "w");352int i;353354Assert (header != NULL, "Can't open trees.h");355fprintf(header,356"/* header created automatically with -DGEN_TREES_H */\n\n");357358fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");359for (i = 0; i < L_CODES+2; i++) {360fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,361static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));362}363364fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");365for (i = 0; i < D_CODES; i++) {366fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,367static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));368}369370fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");371for (i = 0; i < DIST_CODE_LEN; i++) {372fprintf(header, "%2u%s", _dist_code[i],373SEPARATOR(i, DIST_CODE_LEN-1, 20));374}375376fprintf(header,377"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");378for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {379fprintf(header, "%2u%s", _length_code[i],380SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));381}382383fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");384for (i = 0; i < LENGTH_CODES; i++) {385fprintf(header, "%1u%s", base_length[i],386SEPARATOR(i, LENGTH_CODES-1, 20));387}388389fprintf(header, "local const int base_dist[D_CODES] = {\n");390for (i = 0; i < D_CODES; i++) {391fprintf(header, "%5u%s", base_dist[i],392SEPARATOR(i, D_CODES-1, 10));393}394395fclose(header);396}397#endif /* GEN_TREES_H */398399/* ===========================================================================400* Initialize the tree data structures for a new zlib stream.401*/402void ZLIB_INTERNAL _tr_init(s)403deflate_state *s;404{405tr_static_init();406407s->l_desc.dyn_tree = s->dyn_ltree;408s->l_desc.stat_desc = &static_l_desc;409410s->d_desc.dyn_tree = s->dyn_dtree;411s->d_desc.stat_desc = &static_d_desc;412413s->bl_desc.dyn_tree = s->bl_tree;414s->bl_desc.stat_desc = &static_bl_desc;415416s->bi_buf = 0;417s->bi_valid = 0;418#ifdef ZLIB_DEBUG419s->compressed_len = 0L;420s->bits_sent = 0L;421#endif422423/* Initialize the first block of the first file: */424init_block(s);425}426427/* ===========================================================================428* Initialize a new block.429*/430local void init_block(s)431deflate_state *s;432{433int n; /* iterates over tree elements */434435/* Initialize the trees. */436for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;437for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;438for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;439440s->dyn_ltree[END_BLOCK].Freq = 1;441s->opt_len = s->static_len = 0L;442s->last_lit = s->matches = 0;443}444445#define SMALLEST 1446/* Index within the heap array of least frequent node in the Huffman tree */447448449/* ===========================================================================450* Remove the smallest element from the heap and recreate the heap with451* one less element. Updates heap and heap_len.452*/453#define pqremove(s, tree, top) \454{\455top = s->heap[SMALLEST]; \456s->heap[SMALLEST] = s->heap[s->heap_len--]; \457pqdownheap(s, tree, SMALLEST); \458}459460/* ===========================================================================461* Compares to subtrees, using the tree depth as tie breaker when462* the subtrees have equal frequency. This minimizes the worst case length.463*/464#define smaller(tree, n, m, depth) \465(tree[n].Freq < tree[m].Freq || \466(tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))467468/* ===========================================================================469* Restore the heap property by moving down the tree starting at node k,470* exchanging a node with the smallest of its two sons if necessary, stopping471* when the heap property is re-established (each father smaller than its472* two sons).473*/474local void pqdownheap(s, tree, k)475deflate_state *s;476ct_data *tree; /* the tree to restore */477int k; /* node to move down */478{479int v = s->heap[k];480int j = k << 1; /* left son of k */481while (j <= s->heap_len) {482/* Set j to the smallest of the two sons: */483if (j < s->heap_len &&484smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {485j++;486}487/* Exit if v is smaller than both sons */488if (smaller(tree, v, s->heap[j], s->depth)) break;489490/* Exchange v with the smallest son */491s->heap[k] = s->heap[j]; k = j;492493/* And continue down the tree, setting j to the left son of k */494j <<= 1;495}496s->heap[k] = v;497}498499/* ===========================================================================500* Compute the optimal bit lengths for a tree and update the total bit length501* for the current block.502* IN assertion: the fields freq and dad are set, heap[heap_max] and503* above are the tree nodes sorted by increasing frequency.504* OUT assertions: the field len is set to the optimal bit length, the505* array bl_count contains the frequencies for each bit length.506* The length opt_len is updated; static_len is also updated if stree is507* not null.508*/509local void gen_bitlen(s, desc)510deflate_state *s;511tree_desc *desc; /* the tree descriptor */512{513ct_data *tree = desc->dyn_tree;514int max_code = desc->max_code;515const ct_data *stree = desc->stat_desc->static_tree;516const intf *extra = desc->stat_desc->extra_bits;517int base = desc->stat_desc->extra_base;518int max_length = desc->stat_desc->max_length;519int h; /* heap index */520int n, m; /* iterate over the tree elements */521int bits; /* bit length */522int xbits; /* extra bits */523ush f; /* frequency */524int overflow = 0; /* number of elements with bit length too large */525526for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;527528/* In a first pass, compute the optimal bit lengths (which may529* overflow in the case of the bit length tree).530*/531tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */532533for (h = s->heap_max+1; h < HEAP_SIZE; h++) {534n = s->heap[h];535bits = tree[tree[n].Dad].Len + 1;536if (bits > max_length) bits = max_length, overflow++;537tree[n].Len = (ush)bits;538/* We overwrite tree[n].Dad which is no longer needed */539540if (n > max_code) continue; /* not a leaf node */541542s->bl_count[bits]++;543xbits = 0;544if (n >= base) xbits = extra[n-base];545f = tree[n].Freq;546s->opt_len += (ulg)f * (unsigned)(bits + xbits);547if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);548}549if (overflow == 0) return;550551Tracev((stderr,"\nbit length overflow\n"));552/* This happens for example on obj2 and pic of the Calgary corpus */553554/* Find the first bit length which could increase: */555do {556bits = max_length-1;557while (s->bl_count[bits] == 0) bits--;558s->bl_count[bits]--; /* move one leaf down the tree */559s->bl_count[bits+1] += 2; /* move one overflow item as its brother */560s->bl_count[max_length]--;561/* The brother of the overflow item also moves one step up,562* but this does not affect bl_count[max_length]563*/564overflow -= 2;565} while (overflow > 0);566567/* Now recompute all bit lengths, scanning in increasing frequency.568* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all569* lengths instead of fixing only the wrong ones. This idea is taken570* from 'ar' written by Haruhiko Okumura.)571*/572for (bits = max_length; bits != 0; bits--) {573n = s->bl_count[bits];574while (n != 0) {575m = s->heap[--h];576if (m > max_code) continue;577if ((unsigned) tree[m].Len != (unsigned) bits) {578Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));579s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;580tree[m].Len = (ush)bits;581}582n--;583}584}585}586587/* ===========================================================================588* Generate the codes for a given tree and bit counts (which need not be589* optimal).590* IN assertion: the array bl_count contains the bit length statistics for591* the given tree and the field len is set for all tree elements.592* OUT assertion: the field code is set for all tree elements of non593* zero code length.594*/595local void gen_codes (tree, max_code, bl_count)596ct_data *tree; /* the tree to decorate */597int max_code; /* largest code with non zero frequency */598ushf *bl_count; /* number of codes at each bit length */599{600ush next_code[MAX_BITS+1]; /* next code value for each bit length */601unsigned code = 0; /* running code value */602int bits; /* bit index */603int n; /* code index */604605/* The distribution counts are first used to generate the code values606* without bit reversal.607*/608for (bits = 1; bits <= MAX_BITS; bits++) {609code = (code + bl_count[bits-1]) << 1;610next_code[bits] = (ush)code;611}612/* Check that the bit counts in bl_count are consistent. The last code613* must be all ones.614*/615Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,616"inconsistent bit counts");617Tracev((stderr,"\ngen_codes: max_code %d ", max_code));618619for (n = 0; n <= max_code; n++) {620int len = tree[n].Len;621if (len == 0) continue;622/* Now reverse the bits */623tree[n].Code = (ush)bi_reverse(next_code[len]++, len);624625Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",626n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));627}628}629630/* ===========================================================================631* Construct one Huffman tree and assigns the code bit strings and lengths.632* Update the total bit length for the current block.633* IN assertion: the field freq is set for all tree elements.634* OUT assertions: the fields len and code are set to the optimal bit length635* and corresponding code. The length opt_len is updated; static_len is636* also updated if stree is not null. The field max_code is set.637*/638local void build_tree(s, desc)639deflate_state *s;640tree_desc *desc; /* the tree descriptor */641{642ct_data *tree = desc->dyn_tree;643const ct_data *stree = desc->stat_desc->static_tree;644int elems = desc->stat_desc->elems;645int n, m; /* iterate over heap elements */646int max_code = -1; /* largest code with non zero frequency */647int node; /* new node being created */648649/* Construct the initial heap, with least frequent element in650* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].651* heap[0] is not used.652*/653s->heap_len = 0, s->heap_max = HEAP_SIZE;654655for (n = 0; n < elems; n++) {656if (tree[n].Freq != 0) {657s->heap[++(s->heap_len)] = max_code = n;658s->depth[n] = 0;659} else {660tree[n].Len = 0;661}662}663664/* The pkzip format requires that at least one distance code exists,665* and that at least one bit should be sent even if there is only one666* possible code. So to avoid special checks later on we force at least667* two codes of non zero frequency.668*/669while (s->heap_len < 2) {670node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);671tree[node].Freq = 1;672s->depth[node] = 0;673s->opt_len--; if (stree) s->static_len -= stree[node].Len;674/* node is 0 or 1 so it does not have extra bits */675}676desc->max_code = max_code;677678/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,679* establish sub-heaps of increasing lengths:680*/681for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);682683/* Construct the Huffman tree by repeatedly combining the least two684* frequent nodes.685*/686node = elems; /* next internal node of the tree */687do {688pqremove(s, tree, n); /* n = node of least frequency */689m = s->heap[SMALLEST]; /* m = node of next least frequency */690691s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */692s->heap[--(s->heap_max)] = m;693694/* Create a new node father of n and m */695tree[node].Freq = tree[n].Freq + tree[m].Freq;696s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?697s->depth[n] : s->depth[m]) + 1);698tree[n].Dad = tree[m].Dad = (ush)node;699#ifdef DUMP_BL_TREE700if (tree == s->bl_tree) {701fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",702node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);703}704#endif705/* and insert the new node in the heap */706s->heap[SMALLEST] = node++;707pqdownheap(s, tree, SMALLEST);708709} while (s->heap_len >= 2);710711s->heap[--(s->heap_max)] = s->heap[SMALLEST];712713/* At this point, the fields freq and dad are set. We can now714* generate the bit lengths.715*/716gen_bitlen(s, (tree_desc *)desc);717718/* The field len is now set, we can generate the bit codes */719gen_codes ((ct_data *)tree, max_code, s->bl_count);720}721722/* ===========================================================================723* Scan a literal or distance tree to determine the frequencies of the codes724* in the bit length tree.725*/726local void scan_tree (s, tree, max_code)727deflate_state *s;728ct_data *tree; /* the tree to be scanned */729int max_code; /* and its largest code of non zero frequency */730{731int n; /* iterates over all tree elements */732int prevlen = -1; /* last emitted length */733int curlen; /* length of current code */734int nextlen = tree[0].Len; /* length of next code */735int count = 0; /* repeat count of the current code */736int max_count = 7; /* max repeat count */737int min_count = 4; /* min repeat count */738739if (nextlen == 0) max_count = 138, min_count = 3;740tree[max_code+1].Len = (ush)0xffff; /* guard */741742for (n = 0; n <= max_code; n++) {743curlen = nextlen; nextlen = tree[n+1].Len;744if (++count < max_count && curlen == nextlen) {745continue;746} else if (count < min_count) {747s->bl_tree[curlen].Freq += count;748} else if (curlen != 0) {749if (curlen != prevlen) s->bl_tree[curlen].Freq++;750s->bl_tree[REP_3_6].Freq++;751} else if (count <= 10) {752s->bl_tree[REPZ_3_10].Freq++;753} else {754s->bl_tree[REPZ_11_138].Freq++;755}756count = 0; prevlen = curlen;757if (nextlen == 0) {758max_count = 138, min_count = 3;759} else if (curlen == nextlen) {760max_count = 6, min_count = 3;761} else {762max_count = 7, min_count = 4;763}764}765}766767/* ===========================================================================768* Send a literal or distance tree in compressed form, using the codes in769* bl_tree.770*/771local void send_tree (s, tree, max_code)772deflate_state *s;773ct_data *tree; /* the tree to be scanned */774int max_code; /* and its largest code of non zero frequency */775{776int n; /* iterates over all tree elements */777int prevlen = -1; /* last emitted length */778int curlen; /* length of current code */779int nextlen = tree[0].Len; /* length of next code */780int count = 0; /* repeat count of the current code */781int max_count = 7; /* max repeat count */782int min_count = 4; /* min repeat count */783784/* tree[max_code+1].Len = -1; */ /* guard already set */785if (nextlen == 0) max_count = 138, min_count = 3;786787for (n = 0; n <= max_code; n++) {788curlen = nextlen; nextlen = tree[n+1].Len;789if (++count < max_count && curlen == nextlen) {790continue;791} else if (count < min_count) {792do { send_code(s, curlen, s->bl_tree); } while (--count != 0);793794} else if (curlen != 0) {795if (curlen != prevlen) {796send_code(s, curlen, s->bl_tree); count--;797}798Assert(count >= 3 && count <= 6, " 3_6?");799send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);800801} else if (count <= 10) {802send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);803804} else {805send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);806}807count = 0; prevlen = curlen;808if (nextlen == 0) {809max_count = 138, min_count = 3;810} else if (curlen == nextlen) {811max_count = 6, min_count = 3;812} else {813max_count = 7, min_count = 4;814}815}816}817818/* ===========================================================================819* Construct the Huffman tree for the bit lengths and return the index in820* bl_order of the last bit length code to send.821*/822local int build_bl_tree(s)823deflate_state *s;824{825int max_blindex; /* index of last bit length code of non zero freq */826827/* Determine the bit length frequencies for literal and distance trees */828scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);829scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);830831/* Build the bit length tree: */832build_tree(s, (tree_desc *)(&(s->bl_desc)));833/* opt_len now includes the length of the tree representations, except834* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.835*/836837/* Determine the number of bit length codes to send. The pkzip format838* requires that at least 4 bit length codes be sent. (appnote.txt says839* 3 but the actual value used is 4.)840*/841for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {842if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;843}844/* Update opt_len to include the bit length tree and counts */845s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;846Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",847s->opt_len, s->static_len));848849return max_blindex;850}851852/* ===========================================================================853* Send the header for a block using dynamic Huffman trees: the counts, the854* lengths of the bit length codes, the literal tree and the distance tree.855* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.856*/857local void send_all_trees(s, lcodes, dcodes, blcodes)858deflate_state *s;859int lcodes, dcodes, blcodes; /* number of codes for each tree */860{861int rank; /* index in bl_order */862863Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");864Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,865"too many codes");866Tracev((stderr, "\nbl counts: "));867send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */868send_bits(s, dcodes-1, 5);869send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */870for (rank = 0; rank < blcodes; rank++) {871Tracev((stderr, "\nbl code %2d ", bl_order[rank]));872send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);873}874Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));875876send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */877Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));878879send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */880Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));881}882883/* ===========================================================================884* Send a stored block885*/886void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)887deflate_state *s;888charf *buf; /* input block */889ulg stored_len; /* length of input block */890int last; /* one if this is the last block for a file */891{892send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */893bi_windup(s); /* align on byte boundary */894put_short(s, (ush)stored_len);895put_short(s, (ush)~stored_len);896zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);897s->pending += stored_len;898#ifdef ZLIB_DEBUG899s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;900s->compressed_len += (stored_len + 4) << 3;901s->bits_sent += 2*16;902s->bits_sent += stored_len<<3;903#endif904}905906/* ===========================================================================907* Flush the bits in the bit buffer to pending output (leaves at most 7 bits)908*/909void ZLIB_INTERNAL _tr_flush_bits(s)910deflate_state *s;911{912bi_flush(s);913}914915/* ===========================================================================916* Send one empty static block to give enough lookahead for inflate.917* This takes 10 bits, of which 7 may remain in the bit buffer.918*/919void ZLIB_INTERNAL _tr_align(s)920deflate_state *s;921{922send_bits(s, STATIC_TREES<<1, 3);923send_code(s, END_BLOCK, static_ltree);924#ifdef ZLIB_DEBUG925s->compressed_len += 10L; /* 3 for block type, 7 for EOB */926#endif927bi_flush(s);928}929930/* ===========================================================================931* Determine the best encoding for the current block: dynamic trees, static932* trees or store, and write out the encoded block.933*/934void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)935deflate_state *s;936charf *buf; /* input block, or NULL if too old */937ulg stored_len; /* length of input block */938int last; /* one if this is the last block for a file */939{940ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */941int max_blindex = 0; /* index of last bit length code of non zero freq */942943/* Build the Huffman trees unless a stored block is forced */944if (s->level > 0) {945946/* Check if the file is binary or text */947if (s->strm->data_type == Z_UNKNOWN)948s->strm->data_type = detect_data_type(s);949950/* Construct the literal and distance trees */951build_tree(s, (tree_desc *)(&(s->l_desc)));952Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,953s->static_len));954955build_tree(s, (tree_desc *)(&(s->d_desc)));956Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,957s->static_len));958/* At this point, opt_len and static_len are the total bit lengths of959* the compressed block data, excluding the tree representations.960*/961962/* Build the bit length tree for the above two trees, and get the index963* in bl_order of the last bit length code to send.964*/965max_blindex = build_bl_tree(s);966967/* Determine the best encoding. Compute the block lengths in bytes. */968opt_lenb = (s->opt_len+3+7)>>3;969static_lenb = (s->static_len+3+7)>>3;970971Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",972opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,973s->last_lit));974975if (static_lenb <= opt_lenb) opt_lenb = static_lenb;976977} else {978Assert(buf != (char*)0, "lost buf");979opt_lenb = static_lenb = stored_len + 5; /* force a stored block */980}981982#ifdef FORCE_STORED983if (buf != (char*)0) { /* force stored block */984#else985if (stored_len+4 <= opt_lenb && buf != (char*)0) {986/* 4: two words for the lengths */987#endif988/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.989* Otherwise we can't have processed more than WSIZE input bytes since990* the last block flush, because compression would have been991* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to992* transform a block into a stored block.993*/994_tr_stored_block(s, buf, stored_len, last);995996#ifdef FORCE_STATIC997} else if (static_lenb >= 0) { /* force static trees */998#else999} else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {1000#endif1001send_bits(s, (STATIC_TREES<<1)+last, 3);1002compress_block(s, (const ct_data *)static_ltree,1003(const ct_data *)static_dtree);1004#ifdef ZLIB_DEBUG1005s->compressed_len += 3 + s->static_len;1006#endif1007} else {1008send_bits(s, (DYN_TREES<<1)+last, 3);1009send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,1010max_blindex+1);1011compress_block(s, (const ct_data *)s->dyn_ltree,1012(const ct_data *)s->dyn_dtree);1013#ifdef ZLIB_DEBUG1014s->compressed_len += 3 + s->opt_len;1015#endif1016}1017Assert (s->compressed_len == s->bits_sent, "bad compressed size");1018/* The above check is made mod 2^32, for files larger than 512 MB1019* and uLong implemented on 32 bits.1020*/1021init_block(s);10221023if (last) {1024bi_windup(s);1025#ifdef ZLIB_DEBUG1026s->compressed_len += 7; /* align on byte boundary */1027#endif1028}1029Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,1030s->compressed_len-7*last));1031}10321033/* ===========================================================================1034* Save the match info and tally the frequency counts. Return true if1035* the current block must be flushed.1036*/1037int ZLIB_INTERNAL _tr_tally (s, dist, lc)1038deflate_state *s;1039unsigned dist; /* distance of matched string */1040unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */1041{1042s->d_buf[s->last_lit] = (ush)dist;1043s->l_buf[s->last_lit++] = (uch)lc;1044if (dist == 0) {1045/* lc is the unmatched char */1046s->dyn_ltree[lc].Freq++;1047} else {1048s->matches++;1049/* Here, lc is the match length - MIN_MATCH */1050dist--; /* dist = match distance - 1 */1051Assert((ush)dist < (ush)MAX_DIST(s) &&1052(ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&1053(ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");10541055s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;1056s->dyn_dtree[d_code(dist)].Freq++;1057}10581059#ifdef TRUNCATE_BLOCK1060/* Try to guess if it is profitable to stop the current block here */1061if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {1062/* Compute an upper bound for the compressed length */1063ulg out_length = (ulg)s->last_lit*8L;1064ulg in_length = (ulg)((long)s->strstart - s->block_start);1065int dcode;1066for (dcode = 0; dcode < D_CODES; dcode++) {1067out_length += (ulg)s->dyn_dtree[dcode].Freq *1068(5L+extra_dbits[dcode]);1069}1070out_length >>= 3;1071Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",1072s->last_lit, in_length, out_length,1073100L - out_length*100L/in_length));1074if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;1075}1076#endif1077return (s->last_lit == s->lit_bufsize-1);1078/* We avoid equality with lit_bufsize because of wraparound at 64K1079* on 16 bit machines and because stored blocks are restricted to1080* 64K-1 bytes.1081*/1082}10831084/* ===========================================================================1085* Send the block data compressed using the given Huffman trees1086*/1087local void compress_block(s, ltree, dtree)1088deflate_state *s;1089const ct_data *ltree; /* literal tree */1090const ct_data *dtree; /* distance tree */1091{1092unsigned dist; /* distance of matched string */1093int lc; /* match length or unmatched char (if dist == 0) */1094unsigned lx = 0; /* running index in l_buf */1095unsigned code; /* the code to send */1096int extra; /* number of extra bits to send */10971098if (s->last_lit != 0) do {1099dist = s->d_buf[lx];1100lc = s->l_buf[lx++];1101if (dist == 0) {1102send_code(s, lc, ltree); /* send a literal byte */1103Tracecv(isgraph(lc), (stderr," '%c' ", lc));1104} else {1105/* Here, lc is the match length - MIN_MATCH */1106code = _length_code[lc];1107send_code(s, code+LITERALS+1, ltree); /* send the length code */1108extra = extra_lbits[code];1109if (extra != 0) {1110lc -= base_length[code];1111send_bits(s, lc, extra); /* send the extra length bits */1112}1113dist--; /* dist is now the match distance - 1 */1114code = d_code(dist);1115Assert (code < D_CODES, "bad d_code");11161117send_code(s, code, dtree); /* send the distance code */1118extra = extra_dbits[code];1119if (extra != 0) {1120dist -= (unsigned)base_dist[code];1121send_bits(s, dist, extra); /* send the extra distance bits */1122}1123} /* literal or match pair ? */11241125/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */1126Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,1127"pendingBuf overflow");11281129} while (lx < s->last_lit);11301131send_code(s, END_BLOCK, ltree);1132}11331134/* ===========================================================================1135* Check if the data type is TEXT or BINARY, using the following algorithm:1136* - TEXT if the two conditions below are satisfied:1137* a) There are no non-portable control characters belonging to the1138* "black list" (0..6, 14..25, 28..31).1139* b) There is at least one printable character belonging to the1140* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).1141* - BINARY otherwise.1142* - The following partially-portable control characters form a1143* "gray list" that is ignored in this detection algorithm:1144* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).1145* IN assertion: the fields Freq of dyn_ltree are set.1146*/1147local int detect_data_type(s)1148deflate_state *s;1149{1150/* black_mask is the bit mask of black-listed bytes1151* set bits 0..6, 14..25, and 28..311152* 0xf3ffc07f = binary 111100111111111111000000011111111153*/1154unsigned long black_mask = 0xf3ffc07fUL;1155int n;11561157/* Check for non-textual ("black-listed") bytes. */1158for (n = 0; n <= 31; n++, black_mask >>= 1)1159if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))1160return Z_BINARY;11611162/* Check for textual ("white-listed") bytes. */1163if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 01164|| s->dyn_ltree[13].Freq != 0)1165return Z_TEXT;1166for (n = 32; n < LITERALS; n++)1167if (s->dyn_ltree[n].Freq != 0)1168return Z_TEXT;11691170/* There are no "black-listed" or "white-listed" bytes:1171* this stream either is empty or has tolerated ("gray-listed") bytes only.1172*/1173return Z_BINARY;1174}11751176/* ===========================================================================1177* Reverse the first len bits of a code, using straightforward code (a faster1178* method would use a table)1179* IN assertion: 1 <= len <= 151180*/1181local unsigned bi_reverse(code, len)1182unsigned code; /* the value to invert */1183int len; /* its bit length */1184{1185register unsigned res = 0;1186do {1187res |= code & 1;1188code >>= 1, res <<= 1;1189} while (--len > 0);1190return res >> 1;1191}11921193/* ===========================================================================1194* Flush the bit buffer, keeping at most 7 bits in it.1195*/1196local void bi_flush(s)1197deflate_state *s;1198{1199if (s->bi_valid == 16) {1200put_short(s, s->bi_buf);1201s->bi_buf = 0;1202s->bi_valid = 0;1203} else if (s->bi_valid >= 8) {1204put_byte(s, (Byte)s->bi_buf);1205s->bi_buf >>= 8;1206s->bi_valid -= 8;1207}1208}12091210/* ===========================================================================1211* Flush the bit buffer and align the output on a byte boundary1212*/1213local void bi_windup(s)1214deflate_state *s;1215{1216if (s->bi_valid > 8) {1217put_short(s, s->bi_buf);1218} else if (s->bi_valid > 0) {1219put_byte(s, (Byte)s->bi_buf);1220}1221s->bi_buf = 0;1222s->bi_valid = 0;1223#ifdef ZLIB_DEBUG1224s->bits_sent = (s->bits_sent+7) & ~7;1225#endif1226}122712281229