/* trees.c -- output deflated data using Huffman coding1* Copyright (C) 1995-2017 Jean-loup Gailly2* detect_data_type() function provided freely by Cosmin Truta, 20063* For conditions of distribution and use, see copyright notice in zlib.h4*/56/*7* ALGORITHM8*9* The "deflation" process uses several Huffman trees. The more10* common source values are represented by shorter bit sequences.11*12* Each code tree is stored in a compressed form which is itself13* a Huffman encoding of the lengths of all the code strings (in14* ascending order by source values). The actual code strings are15* reconstructed from the lengths in the inflate process, as described16* in the deflate specification.17*18* REFERENCES19*20* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".21* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc22*23* Storer, James A.24* Data Compression: Methods and Theory, pp. 49-50.25* Computer Science Press, 1988. ISBN 0-7167-8156-5.26*27* Sedgewick, R.28* Algorithms, p290.29* Addison-Wesley, 1983. ISBN 0-201-06672-6.30*/3132/* @(#) $Id$ */3334/* #define GEN_TREES_H */3536#include "deflate.h"3738#ifdef ZLIB_DEBUG39# include <ctype.h>40#endif4142/* ===========================================================================43* Constants44*/4546#define MAX_BL_BITS 747/* Bit length codes must not exceed MAX_BL_BITS bits */4849#define END_BLOCK 25650/* end of block literal code */5152#define REP_3_6 1653/* repeat previous bit length 3-6 times (2 bits of repeat count) */5455#define REPZ_3_10 1756/* repeat a zero length 3-10 times (3 bits of repeat count) */5758#define REPZ_11_138 1859/* repeat a zero length 11-138 times (7 bits of repeat count) */6061local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */62= {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};6364local const int extra_dbits[D_CODES] /* extra bits for each distance code */65= {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};6667local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */68= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};6970local const uch bl_order[BL_CODES]71= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};72/* The lengths of the bit length codes are sent in order of decreasing73* probability, to avoid transmitting the lengths for unused bit length codes.74*/7576/* ===========================================================================77* Local data. These are initialized only once.78*/7980#define DIST_CODE_LEN 512 /* see definition of array dist_code below */8182#if defined(GEN_TREES_H) || !defined(STDC)83/* non ANSI compilers may not accept trees.h */8485local ct_data static_ltree[L_CODES+2];86/* The static literal tree. Since the bit lengths are imposed, there is no87* need for the L_CODES extra codes used during heap construction. However88* The codes 286 and 287 are needed to build a canonical tree (see _tr_init89* below).90*/9192local ct_data static_dtree[D_CODES];93/* The static distance tree. (Actually a trivial tree since all codes use94* 5 bits.)95*/9697uch _dist_code[DIST_CODE_LEN];98/* Distance codes. The first 256 values correspond to the distances99* 3 .. 258, the last 256 values correspond to the top 8 bits of100* the 15 bit distances.101*/102103uch _length_code[MAX_MATCH-MIN_MATCH+1];104/* length code for each normalized match length (0 == MIN_MATCH) */105106local int base_length[LENGTH_CODES];107/* First normalized length for each code (0 = MIN_MATCH) */108109local int base_dist[D_CODES];110/* First normalized distance for each code (0 = distance of 1) */111112#else113# include "trees.h"114#endif /* GEN_TREES_H */115116struct static_tree_desc_s {117const ct_data *static_tree; /* static tree or NULL */118const intf *extra_bits; /* extra bits for each code or NULL */119int extra_base; /* base index for extra_bits */120int elems; /* max number of elements in the tree */121int max_length; /* max bit length for the codes */122};123124local const static_tree_desc static_l_desc =125{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};126127local const static_tree_desc static_d_desc =128{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};129130local const static_tree_desc static_bl_desc =131{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};132133/* ===========================================================================134* Local (static) routines in this file.135*/136137local void tr_static_init OF((void));138local void init_block OF((deflate_state *s));139local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));140local void gen_bitlen OF((deflate_state *s, tree_desc *desc));141local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));142local void build_tree OF((deflate_state *s, tree_desc *desc));143local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));144local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));145local int build_bl_tree OF((deflate_state *s));146local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,147int blcodes));148local void compress_block OF((deflate_state *s, const ct_data *ltree,149const ct_data *dtree));150local int detect_data_type OF((deflate_state *s));151local unsigned bi_reverse OF((unsigned value, int length));152local void bi_windup OF((deflate_state *s));153local void bi_flush OF((deflate_state *s));154155#ifdef GEN_TREES_H156local void gen_trees_header OF((void));157#endif158159#ifndef ZLIB_DEBUG160# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)161/* Send a code of the given tree. c and tree must not have side effects */162163#else /* !ZLIB_DEBUG */164# define send_code(s, c, tree) \165{ if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \166send_bits(s, tree[c].Code, tree[c].Len); }167#endif168169/* ===========================================================================170* Output a short LSB first on the stream.171* IN assertion: there is enough room in pendingBuf.172*/173#define put_short(s, w) { \174put_byte(s, (uch)((w) & 0xff)); \175put_byte(s, (uch)((ush)(w) >> 8)); \176}177178/* ===========================================================================179* Send a value on a given number of bits.180* IN assertion: length <= 16 and value fits in length bits.181*/182#ifdef ZLIB_DEBUG183local void send_bits OF((deflate_state *s, int value, int length));184185local void send_bits(s, value, length)186deflate_state *s;187int value; /* value to send */188int length; /* number of bits */189{190Tracevv((stderr," l %2d v %4x ", length, value));191Assert(length > 0 && length <= 15, "invalid length");192s->bits_sent += (ulg)length;193194/* If not enough room in bi_buf, use (valid) bits from bi_buf and195* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))196* unused bits in value.197*/198if (s->bi_valid > (int)Buf_size - length) {199s->bi_buf |= (ush)value << s->bi_valid;200put_short(s, s->bi_buf);201s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);202s->bi_valid += length - Buf_size;203} else {204s->bi_buf |= (ush)value << s->bi_valid;205s->bi_valid += length;206}207}208#else /* !ZLIB_DEBUG */209210#define send_bits(s, value, length) \211{ int len = length;\212if (s->bi_valid > (int)Buf_size - len) {\213int val = (int)value;\214s->bi_buf |= (ush)val << s->bi_valid;\215put_short(s, s->bi_buf);\216s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\217s->bi_valid += len - Buf_size;\218} else {\219s->bi_buf |= (ush)(value) << s->bi_valid;\220s->bi_valid += len;\221}\222}223#endif /* ZLIB_DEBUG */224225226/* the arguments must not have side effects */227228/* ===========================================================================229* Initialize the various 'constant' tables.230*/231local void tr_static_init()232{233#if defined(GEN_TREES_H) || !defined(STDC)234static int static_init_done = 0;235int n; /* iterates over tree elements */236int bits; /* bit counter */237int length; /* length value */238int code; /* code value */239int dist; /* distance index */240ush bl_count[MAX_BITS+1];241/* number of codes at each bit length for an optimal tree */242243if (static_init_done) return;244245/* For some embedded targets, global variables are not initialized: */246#ifdef NO_INIT_GLOBAL_POINTERS247static_l_desc.static_tree = static_ltree;248static_l_desc.extra_bits = extra_lbits;249static_d_desc.static_tree = static_dtree;250static_d_desc.extra_bits = extra_dbits;251static_bl_desc.extra_bits = extra_blbits;252#endif253254/* Initialize the mapping length (0..255) -> length code (0..28) */255length = 0;256for (code = 0; code < LENGTH_CODES-1; code++) {257base_length[code] = length;258for (n = 0; n < (1<<extra_lbits[code]); n++) {259_length_code[length++] = (uch)code;260}261}262Assert (length == 256, "tr_static_init: length != 256");263/* Note that the length 255 (match length 258) can be represented264* in two different ways: code 284 + 5 bits or code 285, so we265* overwrite length_code[255] to use the best encoding:266*/267_length_code[length-1] = (uch)code;268269/* Initialize the mapping dist (0..32K) -> dist code (0..29) */270dist = 0;271for (code = 0 ; code < 16; code++) {272base_dist[code] = dist;273for (n = 0; n < (1<<extra_dbits[code]); n++) {274_dist_code[dist++] = (uch)code;275}276}277Assert (dist == 256, "tr_static_init: dist != 256");278dist >>= 7; /* from now on, all distances are divided by 128 */279for ( ; code < D_CODES; code++) {280base_dist[code] = dist << 7;281for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {282_dist_code[256 + dist++] = (uch)code;283}284}285Assert (dist == 256, "tr_static_init: 256+dist != 512");286287/* Construct the codes of the static literal tree */288for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;289n = 0;290while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;291while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;292while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;293while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;294/* Codes 286 and 287 do not exist, but we must include them in the295* tree construction to get a canonical Huffman tree (longest code296* all ones)297*/298gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);299300/* The static distance tree is trivial: */301for (n = 0; n < D_CODES; n++) {302static_dtree[n].Len = 5;303static_dtree[n].Code = bi_reverse((unsigned)n, 5);304}305static_init_done = 1;306307# ifdef GEN_TREES_H308gen_trees_header();309# endif310#endif /* defined(GEN_TREES_H) || !defined(STDC) */311}312313/* ===========================================================================314* Genererate the file trees.h describing the static trees.315*/316#ifdef GEN_TREES_H317# ifndef ZLIB_DEBUG318# include <stdio.h>319# endif320321# define SEPARATOR(i, last, width) \322((i) == (last)? "\n};\n\n" : \323((i) % (width) == (width)-1 ? ",\n" : ", "))324325void gen_trees_header()326{327FILE *header = fopen("trees.h", "w");328int i;329330Assert (header != NULL, "Can't open trees.h");331fprintf(header,332"/* header created automatically with -DGEN_TREES_H */\n\n");333334fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");335for (i = 0; i < L_CODES+2; i++) {336fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,337static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));338}339340fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");341for (i = 0; i < D_CODES; i++) {342fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,343static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));344}345346fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");347for (i = 0; i < DIST_CODE_LEN; i++) {348fprintf(header, "%2u%s", _dist_code[i],349SEPARATOR(i, DIST_CODE_LEN-1, 20));350}351352fprintf(header,353"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");354for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {355fprintf(header, "%2u%s", _length_code[i],356SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));357}358359fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");360for (i = 0; i < LENGTH_CODES; i++) {361fprintf(header, "%1u%s", base_length[i],362SEPARATOR(i, LENGTH_CODES-1, 20));363}364365fprintf(header, "local const int base_dist[D_CODES] = {\n");366for (i = 0; i < D_CODES; i++) {367fprintf(header, "%5u%s", base_dist[i],368SEPARATOR(i, D_CODES-1, 10));369}370371fclose(header);372}373#endif /* GEN_TREES_H */374375/* ===========================================================================376* Initialize the tree data structures for a new zlib stream.377*/378void ZLIB_INTERNAL _tr_init(s)379deflate_state *s;380{381tr_static_init();382383s->l_desc.dyn_tree = s->dyn_ltree;384s->l_desc.stat_desc = &static_l_desc;385386s->d_desc.dyn_tree = s->dyn_dtree;387s->d_desc.stat_desc = &static_d_desc;388389s->bl_desc.dyn_tree = s->bl_tree;390s->bl_desc.stat_desc = &static_bl_desc;391392s->bi_buf = 0;393s->bi_valid = 0;394#ifdef ZLIB_DEBUG395s->compressed_len = 0L;396s->bits_sent = 0L;397#endif398399/* Initialize the first block of the first file: */400init_block(s);401}402403/* ===========================================================================404* Initialize a new block.405*/406local void init_block(s)407deflate_state *s;408{409int n; /* iterates over tree elements */410411/* Initialize the trees. */412for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;413for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;414for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;415416s->dyn_ltree[END_BLOCK].Freq = 1;417s->opt_len = s->static_len = 0L;418s->last_lit = s->matches = 0;419}420421#define SMALLEST 1422/* Index within the heap array of least frequent node in the Huffman tree */423424425/* ===========================================================================426* Remove the smallest element from the heap and recreate the heap with427* one less element. Updates heap and heap_len.428*/429#define pqremove(s, tree, top) \430{\431top = s->heap[SMALLEST]; \432s->heap[SMALLEST] = s->heap[s->heap_len--]; \433pqdownheap(s, tree, SMALLEST); \434}435436/* ===========================================================================437* Compares to subtrees, using the tree depth as tie breaker when438* the subtrees have equal frequency. This minimizes the worst case length.439*/440#define smaller(tree, n, m, depth) \441(tree[n].Freq < tree[m].Freq || \442(tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))443444/* ===========================================================================445* Restore the heap property by moving down the tree starting at node k,446* exchanging a node with the smallest of its two sons if necessary, stopping447* when the heap property is re-established (each father smaller than its448* two sons).449*/450local void pqdownheap(s, tree, k)451deflate_state *s;452ct_data *tree; /* the tree to restore */453int k; /* node to move down */454{455int v = s->heap[k];456int j = k << 1; /* left son of k */457while (j <= s->heap_len) {458/* Set j to the smallest of the two sons: */459if (j < s->heap_len &&460smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {461j++;462}463/* Exit if v is smaller than both sons */464if (smaller(tree, v, s->heap[j], s->depth)) break;465466/* Exchange v with the smallest son */467s->heap[k] = s->heap[j]; k = j;468469/* And continue down the tree, setting j to the left son of k */470j <<= 1;471}472s->heap[k] = v;473}474475/* ===========================================================================476* Compute the optimal bit lengths for a tree and update the total bit length477* for the current block.478* IN assertion: the fields freq and dad are set, heap[heap_max] and479* above are the tree nodes sorted by increasing frequency.480* OUT assertions: the field len is set to the optimal bit length, the481* array bl_count contains the frequencies for each bit length.482* The length opt_len is updated; static_len is also updated if stree is483* not null.484*/485local void gen_bitlen(s, desc)486deflate_state *s;487tree_desc *desc; /* the tree descriptor */488{489ct_data *tree = desc->dyn_tree;490int max_code = desc->max_code;491const ct_data *stree = desc->stat_desc->static_tree;492const intf *extra = desc->stat_desc->extra_bits;493int base = desc->stat_desc->extra_base;494int max_length = desc->stat_desc->max_length;495int h; /* heap index */496int n, m; /* iterate over the tree elements */497int bits; /* bit length */498int xbits; /* extra bits */499ush f; /* frequency */500int overflow = 0; /* number of elements with bit length too large */501502for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;503504/* In a first pass, compute the optimal bit lengths (which may505* overflow in the case of the bit length tree).506*/507tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */508509for (h = s->heap_max+1; h < HEAP_SIZE; h++) {510n = s->heap[h];511bits = tree[tree[n].Dad].Len + 1;512if (bits > max_length) bits = max_length, overflow++;513tree[n].Len = (ush)bits;514/* We overwrite tree[n].Dad which is no longer needed */515516if (n > max_code) continue; /* not a leaf node */517518s->bl_count[bits]++;519xbits = 0;520if (n >= base) xbits = extra[n-base];521f = tree[n].Freq;522s->opt_len += (ulg)f * (unsigned)(bits + xbits);523if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);524}525if (overflow == 0) return;526527Tracev((stderr,"\nbit length overflow\n"));528/* This happens for example on obj2 and pic of the Calgary corpus */529530/* Find the first bit length which could increase: */531do {532bits = max_length-1;533while (s->bl_count[bits] == 0) bits--;534s->bl_count[bits]--; /* move one leaf down the tree */535s->bl_count[bits+1] += 2; /* move one overflow item as its brother */536s->bl_count[max_length]--;537/* The brother of the overflow item also moves one step up,538* but this does not affect bl_count[max_length]539*/540overflow -= 2;541} while (overflow > 0);542543/* Now recompute all bit lengths, scanning in increasing frequency.544* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all545* lengths instead of fixing only the wrong ones. This idea is taken546* from 'ar' written by Haruhiko Okumura.)547*/548for (bits = max_length; bits != 0; bits--) {549n = s->bl_count[bits];550while (n != 0) {551m = s->heap[--h];552if (m > max_code) continue;553if ((unsigned) tree[m].Len != (unsigned) bits) {554Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));555s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;556tree[m].Len = (ush)bits;557}558n--;559}560}561}562563/* ===========================================================================564* Generate the codes for a given tree and bit counts (which need not be565* optimal).566* IN assertion: the array bl_count contains the bit length statistics for567* the given tree and the field len is set for all tree elements.568* OUT assertion: the field code is set for all tree elements of non569* zero code length.570*/571local void gen_codes (tree, max_code, bl_count)572ct_data *tree; /* the tree to decorate */573int max_code; /* largest code with non zero frequency */574ushf *bl_count; /* number of codes at each bit length */575{576ush next_code[MAX_BITS+1]; /* next code value for each bit length */577unsigned code = 0; /* running code value */578int bits; /* bit index */579int n; /* code index */580581/* The distribution counts are first used to generate the code values582* without bit reversal.583*/584for (bits = 1; bits <= MAX_BITS; bits++) {585code = (code + bl_count[bits-1]) << 1;586next_code[bits] = (ush)code;587}588/* Check that the bit counts in bl_count are consistent. The last code589* must be all ones.590*/591Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,592"inconsistent bit counts");593Tracev((stderr,"\ngen_codes: max_code %d ", max_code));594595for (n = 0; n <= max_code; n++) {596int len = tree[n].Len;597if (len == 0) continue;598/* Now reverse the bits */599tree[n].Code = (ush)bi_reverse(next_code[len]++, len);600601Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",602n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));603}604}605606/* ===========================================================================607* Construct one Huffman tree and assigns the code bit strings and lengths.608* Update the total bit length for the current block.609* IN assertion: the field freq is set for all tree elements.610* OUT assertions: the fields len and code are set to the optimal bit length611* and corresponding code. The length opt_len is updated; static_len is612* also updated if stree is not null. The field max_code is set.613*/614local void build_tree(s, desc)615deflate_state *s;616tree_desc *desc; /* the tree descriptor */617{618ct_data *tree = desc->dyn_tree;619const ct_data *stree = desc->stat_desc->static_tree;620int elems = desc->stat_desc->elems;621int n, m; /* iterate over heap elements */622int max_code = -1; /* largest code with non zero frequency */623int node; /* new node being created */624625/* Construct the initial heap, with least frequent element in626* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].627* heap[0] is not used.628*/629s->heap_len = 0, s->heap_max = HEAP_SIZE;630631for (n = 0; n < elems; n++) {632if (tree[n].Freq != 0) {633s->heap[++(s->heap_len)] = max_code = n;634s->depth[n] = 0;635} else {636tree[n].Len = 0;637}638}639640/* The pkzip format requires that at least one distance code exists,641* and that at least one bit should be sent even if there is only one642* possible code. So to avoid special checks later on we force at least643* two codes of non zero frequency.644*/645while (s->heap_len < 2) {646node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);647tree[node].Freq = 1;648s->depth[node] = 0;649s->opt_len--; if (stree) s->static_len -= stree[node].Len;650/* node is 0 or 1 so it does not have extra bits */651}652desc->max_code = max_code;653654/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,655* establish sub-heaps of increasing lengths:656*/657for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);658659/* Construct the Huffman tree by repeatedly combining the least two660* frequent nodes.661*/662node = elems; /* next internal node of the tree */663do {664pqremove(s, tree, n); /* n = node of least frequency */665m = s->heap[SMALLEST]; /* m = node of next least frequency */666667s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */668s->heap[--(s->heap_max)] = m;669670/* Create a new node father of n and m */671tree[node].Freq = tree[n].Freq + tree[m].Freq;672s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?673s->depth[n] : s->depth[m]) + 1);674tree[n].Dad = tree[m].Dad = (ush)node;675#ifdef DUMP_BL_TREE676if (tree == s->bl_tree) {677fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",678node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);679}680#endif681/* and insert the new node in the heap */682s->heap[SMALLEST] = node++;683pqdownheap(s, tree, SMALLEST);684685} while (s->heap_len >= 2);686687s->heap[--(s->heap_max)] = s->heap[SMALLEST];688689/* At this point, the fields freq and dad are set. We can now690* generate the bit lengths.691*/692gen_bitlen(s, (tree_desc *)desc);693694/* The field len is now set, we can generate the bit codes */695gen_codes ((ct_data *)tree, max_code, s->bl_count);696}697698/* ===========================================================================699* Scan a literal or distance tree to determine the frequencies of the codes700* in the bit length tree.701*/702local void scan_tree (s, tree, max_code)703deflate_state *s;704ct_data *tree; /* the tree to be scanned */705int max_code; /* and its largest code of non zero frequency */706{707int n; /* iterates over all tree elements */708int prevlen = -1; /* last emitted length */709int curlen; /* length of current code */710int nextlen = tree[0].Len; /* length of next code */711int count = 0; /* repeat count of the current code */712int max_count = 7; /* max repeat count */713int min_count = 4; /* min repeat count */714715if (nextlen == 0) max_count = 138, min_count = 3;716tree[max_code+1].Len = (ush)0xffff; /* guard */717718for (n = 0; n <= max_code; n++) {719curlen = nextlen; nextlen = tree[n+1].Len;720if (++count < max_count && curlen == nextlen) {721continue;722} else if (count < min_count) {723s->bl_tree[curlen].Freq += count;724} else if (curlen != 0) {725if (curlen != prevlen) s->bl_tree[curlen].Freq++;726s->bl_tree[REP_3_6].Freq++;727} else if (count <= 10) {728s->bl_tree[REPZ_3_10].Freq++;729} else {730s->bl_tree[REPZ_11_138].Freq++;731}732count = 0; prevlen = curlen;733if (nextlen == 0) {734max_count = 138, min_count = 3;735} else if (curlen == nextlen) {736max_count = 6, min_count = 3;737} else {738max_count = 7, min_count = 4;739}740}741}742743/* ===========================================================================744* Send a literal or distance tree in compressed form, using the codes in745* bl_tree.746*/747local void send_tree (s, tree, max_code)748deflate_state *s;749ct_data *tree; /* the tree to be scanned */750int max_code; /* and its largest code of non zero frequency */751{752int n; /* iterates over all tree elements */753int prevlen = -1; /* last emitted length */754int curlen; /* length of current code */755int nextlen = tree[0].Len; /* length of next code */756int count = 0; /* repeat count of the current code */757int max_count = 7; /* max repeat count */758int min_count = 4; /* min repeat count */759760/* tree[max_code+1].Len = -1; */ /* guard already set */761if (nextlen == 0) max_count = 138, min_count = 3;762763for (n = 0; n <= max_code; n++) {764curlen = nextlen; nextlen = tree[n+1].Len;765if (++count < max_count && curlen == nextlen) {766continue;767} else if (count < min_count) {768do { send_code(s, curlen, s->bl_tree); } while (--count != 0);769770} else if (curlen != 0) {771if (curlen != prevlen) {772send_code(s, curlen, s->bl_tree); count--;773}774Assert(count >= 3 && count <= 6, " 3_6?");775send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);776777} else if (count <= 10) {778send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);779780} else {781send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);782}783count = 0; prevlen = curlen;784if (nextlen == 0) {785max_count = 138, min_count = 3;786} else if (curlen == nextlen) {787max_count = 6, min_count = 3;788} else {789max_count = 7, min_count = 4;790}791}792}793794/* ===========================================================================795* Construct the Huffman tree for the bit lengths and return the index in796* bl_order of the last bit length code to send.797*/798local int build_bl_tree(s)799deflate_state *s;800{801int max_blindex; /* index of last bit length code of non zero freq */802803/* Determine the bit length frequencies for literal and distance trees */804scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);805scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);806807/* Build the bit length tree: */808build_tree(s, (tree_desc *)(&(s->bl_desc)));809/* opt_len now includes the length of the tree representations, except810* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.811*/812813/* Determine the number of bit length codes to send. The pkzip format814* requires that at least 4 bit length codes be sent. (appnote.txt says815* 3 but the actual value used is 4.)816*/817for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {818if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;819}820/* Update opt_len to include the bit length tree and counts */821s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;822Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",823s->opt_len, s->static_len));824825return max_blindex;826}827828/* ===========================================================================829* Send the header for a block using dynamic Huffman trees: the counts, the830* lengths of the bit length codes, the literal tree and the distance tree.831* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.832*/833local void send_all_trees(s, lcodes, dcodes, blcodes)834deflate_state *s;835int lcodes, dcodes, blcodes; /* number of codes for each tree */836{837int rank; /* index in bl_order */838839Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");840Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,841"too many codes");842Tracev((stderr, "\nbl counts: "));843send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */844send_bits(s, dcodes-1, 5);845send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */846for (rank = 0; rank < blcodes; rank++) {847Tracev((stderr, "\nbl code %2d ", bl_order[rank]));848send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);849}850Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));851852send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */853Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));854855send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */856Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));857}858859/* ===========================================================================860* Send a stored block861*/862void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)863deflate_state *s;864charf *buf; /* input block */865ulg stored_len; /* length of input block */866int last; /* one if this is the last block for a file */867{868send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */869bi_windup(s); /* align on byte boundary */870put_short(s, (ush)stored_len);871put_short(s, (ush)~stored_len);872zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);873s->pending += stored_len;874#ifdef ZLIB_DEBUG875s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;876s->compressed_len += (stored_len + 4) << 3;877s->bits_sent += 2*16;878s->bits_sent += stored_len<<3;879#endif880}881882/* ===========================================================================883* Flush the bits in the bit buffer to pending output (leaves at most 7 bits)884*/885void ZLIB_INTERNAL _tr_flush_bits(s)886deflate_state *s;887{888bi_flush(s);889}890891/* ===========================================================================892* Send one empty static block to give enough lookahead for inflate.893* This takes 10 bits, of which 7 may remain in the bit buffer.894*/895void ZLIB_INTERNAL _tr_align(s)896deflate_state *s;897{898send_bits(s, STATIC_TREES<<1, 3);899send_code(s, END_BLOCK, static_ltree);900#ifdef ZLIB_DEBUG901s->compressed_len += 10L; /* 3 for block type, 7 for EOB */902#endif903bi_flush(s);904}905906/* ===========================================================================907* Determine the best encoding for the current block: dynamic trees, static908* trees or store, and write out the encoded block.909*/910void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)911deflate_state *s;912charf *buf; /* input block, or NULL if too old */913ulg stored_len; /* length of input block */914int last; /* one if this is the last block for a file */915{916ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */917int max_blindex = 0; /* index of last bit length code of non zero freq */918919/* Build the Huffman trees unless a stored block is forced */920if (s->level > 0) {921922/* Check if the file is binary or text */923if (s->strm->data_type == Z_UNKNOWN)924s->strm->data_type = detect_data_type(s);925926/* Construct the literal and distance trees */927build_tree(s, (tree_desc *)(&(s->l_desc)));928Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,929s->static_len));930931build_tree(s, (tree_desc *)(&(s->d_desc)));932Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,933s->static_len));934/* At this point, opt_len and static_len are the total bit lengths of935* the compressed block data, excluding the tree representations.936*/937938/* Build the bit length tree for the above two trees, and get the index939* in bl_order of the last bit length code to send.940*/941max_blindex = build_bl_tree(s);942943/* Determine the best encoding. Compute the block lengths in bytes. */944opt_lenb = (s->opt_len+3+7)>>3;945static_lenb = (s->static_len+3+7)>>3;946947Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",948opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,949s->last_lit));950951if (static_lenb <= opt_lenb) opt_lenb = static_lenb;952953} else {954Assert(buf != (char*)0, "lost buf");955opt_lenb = static_lenb = stored_len + 5; /* force a stored block */956}957958#ifdef FORCE_STORED959if (buf != (char*)0) { /* force stored block */960#else961if (stored_len+4 <= opt_lenb && buf != (char*)0) {962/* 4: two words for the lengths */963#endif964/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.965* Otherwise we can't have processed more than WSIZE input bytes since966* the last block flush, because compression would have been967* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to968* transform a block into a stored block.969*/970_tr_stored_block(s, buf, stored_len, last);971972#ifdef FORCE_STATIC973} else if (static_lenb >= 0) { /* force static trees */974#else975} else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {976#endif977send_bits(s, (STATIC_TREES<<1)+last, 3);978compress_block(s, (const ct_data *)static_ltree,979(const ct_data *)static_dtree);980#ifdef ZLIB_DEBUG981s->compressed_len += 3 + s->static_len;982#endif983} else {984send_bits(s, (DYN_TREES<<1)+last, 3);985send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,986max_blindex+1);987compress_block(s, (const ct_data *)s->dyn_ltree,988(const ct_data *)s->dyn_dtree);989#ifdef ZLIB_DEBUG990s->compressed_len += 3 + s->opt_len;991#endif992}993Assert (s->compressed_len == s->bits_sent, "bad compressed size");994/* The above check is made mod 2^32, for files larger than 512 MB995* and uLong implemented on 32 bits.996*/997init_block(s);998999if (last) {1000bi_windup(s);1001#ifdef ZLIB_DEBUG1002s->compressed_len += 7; /* align on byte boundary */1003#endif1004}1005Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,1006s->compressed_len-7*last));1007}10081009/* ===========================================================================1010* Save the match info and tally the frequency counts. Return true if1011* the current block must be flushed.1012*/1013int ZLIB_INTERNAL _tr_tally (s, dist, lc)1014deflate_state *s;1015unsigned dist; /* distance of matched string */1016unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */1017{1018s->d_buf[s->last_lit] = (ush)dist;1019s->l_buf[s->last_lit++] = (uch)lc;1020if (dist == 0) {1021/* lc is the unmatched char */1022s->dyn_ltree[lc].Freq++;1023} else {1024s->matches++;1025/* Here, lc is the match length - MIN_MATCH */1026dist--; /* dist = match distance - 1 */1027Assert((ush)dist < (ush)MAX_DIST(s) &&1028(ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&1029(ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");10301031s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;1032s->dyn_dtree[d_code(dist)].Freq++;1033}10341035#ifdef TRUNCATE_BLOCK1036/* Try to guess if it is profitable to stop the current block here */1037if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {1038/* Compute an upper bound for the compressed length */1039ulg out_length = (ulg)s->last_lit*8L;1040ulg in_length = (ulg)((long)s->strstart - s->block_start);1041int dcode;1042for (dcode = 0; dcode < D_CODES; dcode++) {1043out_length += (ulg)s->dyn_dtree[dcode].Freq *1044(5L+extra_dbits[dcode]);1045}1046out_length >>= 3;1047Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",1048s->last_lit, in_length, out_length,1049100L - out_length*100L/in_length));1050if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;1051}1052#endif1053return (s->last_lit == s->lit_bufsize-1);1054/* We avoid equality with lit_bufsize because of wraparound at 64K1055* on 16 bit machines and because stored blocks are restricted to1056* 64K-1 bytes.1057*/1058}10591060/* ===========================================================================1061* Send the block data compressed using the given Huffman trees1062*/1063local void compress_block(s, ltree, dtree)1064deflate_state *s;1065const ct_data *ltree; /* literal tree */1066const ct_data *dtree; /* distance tree */1067{1068unsigned dist; /* distance of matched string */1069int lc; /* match length or unmatched char (if dist == 0) */1070unsigned lx = 0; /* running index in l_buf */1071unsigned code; /* the code to send */1072int extra; /* number of extra bits to send */10731074if (s->last_lit != 0) do {1075dist = s->d_buf[lx];1076lc = s->l_buf[lx++];1077if (dist == 0) {1078send_code(s, lc, ltree); /* send a literal byte */1079Tracecv(isgraph(lc), (stderr," '%c' ", lc));1080} else {1081/* Here, lc is the match length - MIN_MATCH */1082code = _length_code[lc];1083send_code(s, code+LITERALS+1, ltree); /* send the length code */1084extra = extra_lbits[code];1085if (extra != 0) {1086lc -= base_length[code];1087send_bits(s, lc, extra); /* send the extra length bits */1088}1089dist--; /* dist is now the match distance - 1 */1090code = d_code(dist);1091Assert (code < D_CODES, "bad d_code");10921093send_code(s, code, dtree); /* send the distance code */1094extra = extra_dbits[code];1095if (extra != 0) {1096dist -= (unsigned)base_dist[code];1097send_bits(s, dist, extra); /* send the extra distance bits */1098}1099} /* literal or match pair ? */11001101/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */1102Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,1103"pendingBuf overflow");11041105} while (lx < s->last_lit);11061107send_code(s, END_BLOCK, ltree);1108}11091110/* ===========================================================================1111* Check if the data type is TEXT or BINARY, using the following algorithm:1112* - TEXT if the two conditions below are satisfied:1113* a) There are no non-portable control characters belonging to the1114* "black list" (0..6, 14..25, 28..31).1115* b) There is at least one printable character belonging to the1116* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).1117* - BINARY otherwise.1118* - The following partially-portable control characters form a1119* "gray list" that is ignored in this detection algorithm:1120* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).1121* IN assertion: the fields Freq of dyn_ltree are set.1122*/1123local int detect_data_type(s)1124deflate_state *s;1125{1126/* black_mask is the bit mask of black-listed bytes1127* set bits 0..6, 14..25, and 28..311128* 0xf3ffc07f = binary 111100111111111111000000011111111129*/1130unsigned long black_mask = 0xf3ffc07fUL;1131int n;11321133/* Check for non-textual ("black-listed") bytes. */1134for (n = 0; n <= 31; n++, black_mask >>= 1)1135if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))1136return Z_BINARY;11371138/* Check for textual ("white-listed") bytes. */1139if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 01140|| s->dyn_ltree[13].Freq != 0)1141return Z_TEXT;1142for (n = 32; n < LITERALS; n++)1143if (s->dyn_ltree[n].Freq != 0)1144return Z_TEXT;11451146/* There are no "black-listed" or "white-listed" bytes:1147* this stream either is empty or has tolerated ("gray-listed") bytes only.1148*/1149return Z_BINARY;1150}11511152/* ===========================================================================1153* Reverse the first len bits of a code, using straightforward code (a faster1154* method would use a table)1155* IN assertion: 1 <= len <= 151156*/1157local unsigned bi_reverse(code, len)1158unsigned code; /* the value to invert */1159int len; /* its bit length */1160{1161register unsigned res = 0;1162do {1163res |= code & 1;1164code >>= 1, res <<= 1;1165} while (--len > 0);1166return res >> 1;1167}11681169/* ===========================================================================1170* Flush the bit buffer, keeping at most 7 bits in it.1171*/1172local void bi_flush(s)1173deflate_state *s;1174{1175if (s->bi_valid == 16) {1176put_short(s, s->bi_buf);1177s->bi_buf = 0;1178s->bi_valid = 0;1179} else if (s->bi_valid >= 8) {1180put_byte(s, (Byte)s->bi_buf);1181s->bi_buf >>= 8;1182s->bi_valid -= 8;1183}1184}11851186/* ===========================================================================1187* Flush the bit buffer and align the output on a byte boundary1188*/1189local void bi_windup(s)1190deflate_state *s;1191{1192if (s->bi_valid > 8) {1193put_short(s, s->bi_buf);1194} else if (s->bi_valid > 0) {1195put_byte(s, (Byte)s->bi_buf);1196}1197s->bi_buf = 0;1198s->bi_valid = 0;1199#ifdef ZLIB_DEBUG1200s->bits_sent = (s->bits_sent+7) & ~7;1201#endif1202}120312041205