external/zlib-1.2.11/trees.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 21 Oct 2017 21:05:43 -0700
changeset 521 9ed2f7d4a251
permissions -rw-r--r--
Added pristine code for zlib-1.2.11
slouken@521
     1
/* trees.c -- output deflated data using Huffman coding
slouken@521
     2
 * Copyright (C) 1995-2017 Jean-loup Gailly
slouken@521
     3
 * detect_data_type() function provided freely by Cosmin Truta, 2006
slouken@521
     4
 * For conditions of distribution and use, see copyright notice in zlib.h
slouken@521
     5
 */
slouken@521
     6
slouken@521
     7
/*
slouken@521
     8
 *  ALGORITHM
slouken@521
     9
 *
slouken@521
    10
 *      The "deflation" process uses several Huffman trees. The more
slouken@521
    11
 *      common source values are represented by shorter bit sequences.
slouken@521
    12
 *
slouken@521
    13
 *      Each code tree is stored in a compressed form which is itself
slouken@521
    14
 * a Huffman encoding of the lengths of all the code strings (in
slouken@521
    15
 * ascending order by source values).  The actual code strings are
slouken@521
    16
 * reconstructed from the lengths in the inflate process, as described
slouken@521
    17
 * in the deflate specification.
slouken@521
    18
 *
slouken@521
    19
 *  REFERENCES
slouken@521
    20
 *
slouken@521
    21
 *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
slouken@521
    22
 *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
slouken@521
    23
 *
slouken@521
    24
 *      Storer, James A.
slouken@521
    25
 *          Data Compression:  Methods and Theory, pp. 49-50.
slouken@521
    26
 *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
slouken@521
    27
 *
slouken@521
    28
 *      Sedgewick, R.
slouken@521
    29
 *          Algorithms, p290.
slouken@521
    30
 *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
slouken@521
    31
 */
slouken@521
    32
slouken@521
    33
/* @(#) $Id$ */
slouken@521
    34
slouken@521
    35
/* #define GEN_TREES_H */
slouken@521
    36
slouken@521
    37
#include "deflate.h"
slouken@521
    38
slouken@521
    39
#ifdef ZLIB_DEBUG
slouken@521
    40
#  include <ctype.h>
slouken@521
    41
#endif
slouken@521
    42
slouken@521
    43
/* ===========================================================================
slouken@521
    44
 * Constants
slouken@521
    45
 */
slouken@521
    46
slouken@521
    47
#define MAX_BL_BITS 7
slouken@521
    48
/* Bit length codes must not exceed MAX_BL_BITS bits */
slouken@521
    49
slouken@521
    50
#define END_BLOCK 256
slouken@521
    51
/* end of block literal code */
slouken@521
    52
slouken@521
    53
#define REP_3_6      16
slouken@521
    54
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
slouken@521
    55
slouken@521
    56
#define REPZ_3_10    17
slouken@521
    57
/* repeat a zero length 3-10 times  (3 bits of repeat count) */
slouken@521
    58
slouken@521
    59
#define REPZ_11_138  18
slouken@521
    60
/* repeat a zero length 11-138 times  (7 bits of repeat count) */
slouken@521
    61
slouken@521
    62
local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
slouken@521
    63
   = {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};
slouken@521
    64
slouken@521
    65
local const int extra_dbits[D_CODES] /* extra bits for each distance code */
slouken@521
    66
   = {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};
slouken@521
    67
slouken@521
    68
local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
slouken@521
    69
   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
slouken@521
    70
slouken@521
    71
local const uch bl_order[BL_CODES]
slouken@521
    72
   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
slouken@521
    73
/* The lengths of the bit length codes are sent in order of decreasing
slouken@521
    74
 * probability, to avoid transmitting the lengths for unused bit length codes.
slouken@521
    75
 */
slouken@521
    76
slouken@521
    77
/* ===========================================================================
slouken@521
    78
 * Local data. These are initialized only once.
slouken@521
    79
 */
slouken@521
    80
slouken@521
    81
#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
slouken@521
    82
slouken@521
    83
#if defined(GEN_TREES_H) || !defined(STDC)
slouken@521
    84
/* non ANSI compilers may not accept trees.h */
slouken@521
    85
slouken@521
    86
local ct_data static_ltree[L_CODES+2];
slouken@521
    87
/* The static literal tree. Since the bit lengths are imposed, there is no
slouken@521
    88
 * need for the L_CODES extra codes used during heap construction. However
slouken@521
    89
 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
slouken@521
    90
 * below).
slouken@521
    91
 */
slouken@521
    92
slouken@521
    93
local ct_data static_dtree[D_CODES];
slouken@521
    94
/* The static distance tree. (Actually a trivial tree since all codes use
slouken@521
    95
 * 5 bits.)
slouken@521
    96
 */
slouken@521
    97
slouken@521
    98
uch _dist_code[DIST_CODE_LEN];
slouken@521
    99
/* Distance codes. The first 256 values correspond to the distances
slouken@521
   100
 * 3 .. 258, the last 256 values correspond to the top 8 bits of
slouken@521
   101
 * the 15 bit distances.
slouken@521
   102
 */
slouken@521
   103
slouken@521
   104
uch _length_code[MAX_MATCH-MIN_MATCH+1];
slouken@521
   105
/* length code for each normalized match length (0 == MIN_MATCH) */
slouken@521
   106
slouken@521
   107
local int base_length[LENGTH_CODES];
slouken@521
   108
/* First normalized length for each code (0 = MIN_MATCH) */
slouken@521
   109
slouken@521
   110
local int base_dist[D_CODES];
slouken@521
   111
/* First normalized distance for each code (0 = distance of 1) */
slouken@521
   112
slouken@521
   113
#else
slouken@521
   114
#  include "trees.h"
slouken@521
   115
#endif /* GEN_TREES_H */
slouken@521
   116
slouken@521
   117
struct static_tree_desc_s {
slouken@521
   118
    const ct_data *static_tree;  /* static tree or NULL */
slouken@521
   119
    const intf *extra_bits;      /* extra bits for each code or NULL */
slouken@521
   120
    int     extra_base;          /* base index for extra_bits */
slouken@521
   121
    int     elems;               /* max number of elements in the tree */
slouken@521
   122
    int     max_length;          /* max bit length for the codes */
slouken@521
   123
};
slouken@521
   124
slouken@521
   125
local const static_tree_desc  static_l_desc =
slouken@521
   126
{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
slouken@521
   127
slouken@521
   128
local const static_tree_desc  static_d_desc =
slouken@521
   129
{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
slouken@521
   130
slouken@521
   131
local const static_tree_desc  static_bl_desc =
slouken@521
   132
{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
slouken@521
   133
slouken@521
   134
/* ===========================================================================
slouken@521
   135
 * Local (static) routines in this file.
slouken@521
   136
 */
slouken@521
   137
slouken@521
   138
local void tr_static_init OF((void));
slouken@521
   139
local void init_block     OF((deflate_state *s));
slouken@521
   140
local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
slouken@521
   141
local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
slouken@521
   142
local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
slouken@521
   143
local void build_tree     OF((deflate_state *s, tree_desc *desc));
slouken@521
   144
local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
slouken@521
   145
local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
slouken@521
   146
local int  build_bl_tree  OF((deflate_state *s));
slouken@521
   147
local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
slouken@521
   148
                              int blcodes));
slouken@521
   149
local void compress_block OF((deflate_state *s, const ct_data *ltree,
slouken@521
   150
                              const ct_data *dtree));
slouken@521
   151
local int  detect_data_type OF((deflate_state *s));
slouken@521
   152
local unsigned bi_reverse OF((unsigned value, int length));
slouken@521
   153
local void bi_windup      OF((deflate_state *s));
slouken@521
   154
local void bi_flush       OF((deflate_state *s));
slouken@521
   155
slouken@521
   156
#ifdef GEN_TREES_H
slouken@521
   157
local void gen_trees_header OF((void));
slouken@521
   158
#endif
slouken@521
   159
slouken@521
   160
#ifndef ZLIB_DEBUG
slouken@521
   161
#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
slouken@521
   162
   /* Send a code of the given tree. c and tree must not have side effects */
slouken@521
   163
slouken@521
   164
#else /* !ZLIB_DEBUG */
slouken@521
   165
#  define send_code(s, c, tree) \
slouken@521
   166
     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
slouken@521
   167
       send_bits(s, tree[c].Code, tree[c].Len); }
slouken@521
   168
#endif
slouken@521
   169
slouken@521
   170
/* ===========================================================================
slouken@521
   171
 * Output a short LSB first on the stream.
slouken@521
   172
 * IN assertion: there is enough room in pendingBuf.
slouken@521
   173
 */
slouken@521
   174
#define put_short(s, w) { \
slouken@521
   175
    put_byte(s, (uch)((w) & 0xff)); \
slouken@521
   176
    put_byte(s, (uch)((ush)(w) >> 8)); \
slouken@521
   177
}
slouken@521
   178
slouken@521
   179
/* ===========================================================================
slouken@521
   180
 * Send a value on a given number of bits.
slouken@521
   181
 * IN assertion: length <= 16 and value fits in length bits.
slouken@521
   182
 */
slouken@521
   183
#ifdef ZLIB_DEBUG
slouken@521
   184
local void send_bits      OF((deflate_state *s, int value, int length));
slouken@521
   185
slouken@521
   186
local void send_bits(s, value, length)
slouken@521
   187
    deflate_state *s;
slouken@521
   188
    int value;  /* value to send */
slouken@521
   189
    int length; /* number of bits */
slouken@521
   190
{
slouken@521
   191
    Tracevv((stderr," l %2d v %4x ", length, value));
slouken@521
   192
    Assert(length > 0 && length <= 15, "invalid length");
slouken@521
   193
    s->bits_sent += (ulg)length;
slouken@521
   194
slouken@521
   195
    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
slouken@521
   196
     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
slouken@521
   197
     * unused bits in value.
slouken@521
   198
     */
slouken@521
   199
    if (s->bi_valid > (int)Buf_size - length) {
slouken@521
   200
        s->bi_buf |= (ush)value << s->bi_valid;
slouken@521
   201
        put_short(s, s->bi_buf);
slouken@521
   202
        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
slouken@521
   203
        s->bi_valid += length - Buf_size;
slouken@521
   204
    } else {
slouken@521
   205
        s->bi_buf |= (ush)value << s->bi_valid;
slouken@521
   206
        s->bi_valid += length;
slouken@521
   207
    }
slouken@521
   208
}
slouken@521
   209
#else /* !ZLIB_DEBUG */
slouken@521
   210
slouken@521
   211
#define send_bits(s, value, length) \
slouken@521
   212
{ int len = length;\
slouken@521
   213
  if (s->bi_valid > (int)Buf_size - len) {\
slouken@521
   214
    int val = (int)value;\
slouken@521
   215
    s->bi_buf |= (ush)val << s->bi_valid;\
slouken@521
   216
    put_short(s, s->bi_buf);\
slouken@521
   217
    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
slouken@521
   218
    s->bi_valid += len - Buf_size;\
slouken@521
   219
  } else {\
slouken@521
   220
    s->bi_buf |= (ush)(value) << s->bi_valid;\
slouken@521
   221
    s->bi_valid += len;\
slouken@521
   222
  }\
slouken@521
   223
}
slouken@521
   224
#endif /* ZLIB_DEBUG */
slouken@521
   225
slouken@521
   226
slouken@521
   227
/* the arguments must not have side effects */
slouken@521
   228
slouken@521
   229
/* ===========================================================================
slouken@521
   230
 * Initialize the various 'constant' tables.
slouken@521
   231
 */
slouken@521
   232
local void tr_static_init()
slouken@521
   233
{
slouken@521
   234
#if defined(GEN_TREES_H) || !defined(STDC)
slouken@521
   235
    static int static_init_done = 0;
slouken@521
   236
    int n;        /* iterates over tree elements */
slouken@521
   237
    int bits;     /* bit counter */
slouken@521
   238
    int length;   /* length value */
slouken@521
   239
    int code;     /* code value */
slouken@521
   240
    int dist;     /* distance index */
slouken@521
   241
    ush bl_count[MAX_BITS+1];
slouken@521
   242
    /* number of codes at each bit length for an optimal tree */
slouken@521
   243
slouken@521
   244
    if (static_init_done) return;
slouken@521
   245
slouken@521
   246
    /* For some embedded targets, global variables are not initialized: */
slouken@521
   247
#ifdef NO_INIT_GLOBAL_POINTERS
slouken@521
   248
    static_l_desc.static_tree = static_ltree;
slouken@521
   249
    static_l_desc.extra_bits = extra_lbits;
slouken@521
   250
    static_d_desc.static_tree = static_dtree;
slouken@521
   251
    static_d_desc.extra_bits = extra_dbits;
slouken@521
   252
    static_bl_desc.extra_bits = extra_blbits;
slouken@521
   253
#endif
slouken@521
   254
slouken@521
   255
    /* Initialize the mapping length (0..255) -> length code (0..28) */
slouken@521
   256
    length = 0;
slouken@521
   257
    for (code = 0; code < LENGTH_CODES-1; code++) {
slouken@521
   258
        base_length[code] = length;
slouken@521
   259
        for (n = 0; n < (1<<extra_lbits[code]); n++) {
slouken@521
   260
            _length_code[length++] = (uch)code;
slouken@521
   261
        }
slouken@521
   262
    }
slouken@521
   263
    Assert (length == 256, "tr_static_init: length != 256");
slouken@521
   264
    /* Note that the length 255 (match length 258) can be represented
slouken@521
   265
     * in two different ways: code 284 + 5 bits or code 285, so we
slouken@521
   266
     * overwrite length_code[255] to use the best encoding:
slouken@521
   267
     */
slouken@521
   268
    _length_code[length-1] = (uch)code;
slouken@521
   269
slouken@521
   270
    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
slouken@521
   271
    dist = 0;
slouken@521
   272
    for (code = 0 ; code < 16; code++) {
slouken@521
   273
        base_dist[code] = dist;
slouken@521
   274
        for (n = 0; n < (1<<extra_dbits[code]); n++) {
slouken@521
   275
            _dist_code[dist++] = (uch)code;
slouken@521
   276
        }
slouken@521
   277
    }
slouken@521
   278
    Assert (dist == 256, "tr_static_init: dist != 256");
slouken@521
   279
    dist >>= 7; /* from now on, all distances are divided by 128 */
slouken@521
   280
    for ( ; code < D_CODES; code++) {
slouken@521
   281
        base_dist[code] = dist << 7;
slouken@521
   282
        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
slouken@521
   283
            _dist_code[256 + dist++] = (uch)code;
slouken@521
   284
        }
slouken@521
   285
    }
slouken@521
   286
    Assert (dist == 256, "tr_static_init: 256+dist != 512");
slouken@521
   287
slouken@521
   288
    /* Construct the codes of the static literal tree */
slouken@521
   289
    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
slouken@521
   290
    n = 0;
slouken@521
   291
    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
slouken@521
   292
    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
slouken@521
   293
    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
slouken@521
   294
    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
slouken@521
   295
    /* Codes 286 and 287 do not exist, but we must include them in the
slouken@521
   296
     * tree construction to get a canonical Huffman tree (longest code
slouken@521
   297
     * all ones)
slouken@521
   298
     */
slouken@521
   299
    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
slouken@521
   300
slouken@521
   301
    /* The static distance tree is trivial: */
slouken@521
   302
    for (n = 0; n < D_CODES; n++) {
slouken@521
   303
        static_dtree[n].Len = 5;
slouken@521
   304
        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
slouken@521
   305
    }
slouken@521
   306
    static_init_done = 1;
slouken@521
   307
slouken@521
   308
#  ifdef GEN_TREES_H
slouken@521
   309
    gen_trees_header();
slouken@521
   310
#  endif
slouken@521
   311
#endif /* defined(GEN_TREES_H) || !defined(STDC) */
slouken@521
   312
}
slouken@521
   313
slouken@521
   314
/* ===========================================================================
slouken@521
   315
 * Genererate the file trees.h describing the static trees.
slouken@521
   316
 */
slouken@521
   317
#ifdef GEN_TREES_H
slouken@521
   318
#  ifndef ZLIB_DEBUG
slouken@521
   319
#    include <stdio.h>
slouken@521
   320
#  endif
slouken@521
   321
slouken@521
   322
#  define SEPARATOR(i, last, width) \
slouken@521
   323
      ((i) == (last)? "\n};\n\n" :    \
slouken@521
   324
       ((i) % (width) == (width)-1 ? ",\n" : ", "))
slouken@521
   325
slouken@521
   326
void gen_trees_header()
slouken@521
   327
{
slouken@521
   328
    FILE *header = fopen("trees.h", "w");
slouken@521
   329
    int i;
slouken@521
   330
slouken@521
   331
    Assert (header != NULL, "Can't open trees.h");
slouken@521
   332
    fprintf(header,
slouken@521
   333
            "/* header created automatically with -DGEN_TREES_H */\n\n");
slouken@521
   334
slouken@521
   335
    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
slouken@521
   336
    for (i = 0; i < L_CODES+2; i++) {
slouken@521
   337
        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
slouken@521
   338
                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
slouken@521
   339
    }
slouken@521
   340
slouken@521
   341
    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
slouken@521
   342
    for (i = 0; i < D_CODES; i++) {
slouken@521
   343
        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
slouken@521
   344
                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
slouken@521
   345
    }
slouken@521
   346
slouken@521
   347
    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
slouken@521
   348
    for (i = 0; i < DIST_CODE_LEN; i++) {
slouken@521
   349
        fprintf(header, "%2u%s", _dist_code[i],
slouken@521
   350
                SEPARATOR(i, DIST_CODE_LEN-1, 20));
slouken@521
   351
    }
slouken@521
   352
slouken@521
   353
    fprintf(header,
slouken@521
   354
        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
slouken@521
   355
    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
slouken@521
   356
        fprintf(header, "%2u%s", _length_code[i],
slouken@521
   357
                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
slouken@521
   358
    }
slouken@521
   359
slouken@521
   360
    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
slouken@521
   361
    for (i = 0; i < LENGTH_CODES; i++) {
slouken@521
   362
        fprintf(header, "%1u%s", base_length[i],
slouken@521
   363
                SEPARATOR(i, LENGTH_CODES-1, 20));
slouken@521
   364
    }
slouken@521
   365
slouken@521
   366
    fprintf(header, "local const int base_dist[D_CODES] = {\n");
slouken@521
   367
    for (i = 0; i < D_CODES; i++) {
slouken@521
   368
        fprintf(header, "%5u%s", base_dist[i],
slouken@521
   369
                SEPARATOR(i, D_CODES-1, 10));
slouken@521
   370
    }
slouken@521
   371
slouken@521
   372
    fclose(header);
slouken@521
   373
}
slouken@521
   374
#endif /* GEN_TREES_H */
slouken@521
   375
slouken@521
   376
/* ===========================================================================
slouken@521
   377
 * Initialize the tree data structures for a new zlib stream.
slouken@521
   378
 */
slouken@521
   379
void ZLIB_INTERNAL _tr_init(s)
slouken@521
   380
    deflate_state *s;
slouken@521
   381
{
slouken@521
   382
    tr_static_init();
slouken@521
   383
slouken@521
   384
    s->l_desc.dyn_tree = s->dyn_ltree;
slouken@521
   385
    s->l_desc.stat_desc = &static_l_desc;
slouken@521
   386
slouken@521
   387
    s->d_desc.dyn_tree = s->dyn_dtree;
slouken@521
   388
    s->d_desc.stat_desc = &static_d_desc;
slouken@521
   389
slouken@521
   390
    s->bl_desc.dyn_tree = s->bl_tree;
slouken@521
   391
    s->bl_desc.stat_desc = &static_bl_desc;
slouken@521
   392
slouken@521
   393
    s->bi_buf = 0;
slouken@521
   394
    s->bi_valid = 0;
slouken@521
   395
#ifdef ZLIB_DEBUG
slouken@521
   396
    s->compressed_len = 0L;
slouken@521
   397
    s->bits_sent = 0L;
slouken@521
   398
#endif
slouken@521
   399
slouken@521
   400
    /* Initialize the first block of the first file: */
slouken@521
   401
    init_block(s);
slouken@521
   402
}
slouken@521
   403
slouken@521
   404
/* ===========================================================================
slouken@521
   405
 * Initialize a new block.
slouken@521
   406
 */
slouken@521
   407
local void init_block(s)
slouken@521
   408
    deflate_state *s;
slouken@521
   409
{
slouken@521
   410
    int n; /* iterates over tree elements */
slouken@521
   411
slouken@521
   412
    /* Initialize the trees. */
slouken@521
   413
    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
slouken@521
   414
    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
slouken@521
   415
    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
slouken@521
   416
slouken@521
   417
    s->dyn_ltree[END_BLOCK].Freq = 1;
slouken@521
   418
    s->opt_len = s->static_len = 0L;
slouken@521
   419
    s->last_lit = s->matches = 0;
slouken@521
   420
}
slouken@521
   421
slouken@521
   422
#define SMALLEST 1
slouken@521
   423
/* Index within the heap array of least frequent node in the Huffman tree */
slouken@521
   424
slouken@521
   425
slouken@521
   426
/* ===========================================================================
slouken@521
   427
 * Remove the smallest element from the heap and recreate the heap with
slouken@521
   428
 * one less element. Updates heap and heap_len.
slouken@521
   429
 */
slouken@521
   430
#define pqremove(s, tree, top) \
slouken@521
   431
{\
slouken@521
   432
    top = s->heap[SMALLEST]; \
slouken@521
   433
    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
slouken@521
   434
    pqdownheap(s, tree, SMALLEST); \
slouken@521
   435
}
slouken@521
   436
slouken@521
   437
/* ===========================================================================
slouken@521
   438
 * Compares to subtrees, using the tree depth as tie breaker when
slouken@521
   439
 * the subtrees have equal frequency. This minimizes the worst case length.
slouken@521
   440
 */
slouken@521
   441
#define smaller(tree, n, m, depth) \
slouken@521
   442
   (tree[n].Freq < tree[m].Freq || \
slouken@521
   443
   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
slouken@521
   444
slouken@521
   445
/* ===========================================================================
slouken@521
   446
 * Restore the heap property by moving down the tree starting at node k,
slouken@521
   447
 * exchanging a node with the smallest of its two sons if necessary, stopping
slouken@521
   448
 * when the heap property is re-established (each father smaller than its
slouken@521
   449
 * two sons).
slouken@521
   450
 */
slouken@521
   451
local void pqdownheap(s, tree, k)
slouken@521
   452
    deflate_state *s;
slouken@521
   453
    ct_data *tree;  /* the tree to restore */
slouken@521
   454
    int k;               /* node to move down */
slouken@521
   455
{
slouken@521
   456
    int v = s->heap[k];
slouken@521
   457
    int j = k << 1;  /* left son of k */
slouken@521
   458
    while (j <= s->heap_len) {
slouken@521
   459
        /* Set j to the smallest of the two sons: */
slouken@521
   460
        if (j < s->heap_len &&
slouken@521
   461
            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
slouken@521
   462
            j++;
slouken@521
   463
        }
slouken@521
   464
        /* Exit if v is smaller than both sons */
slouken@521
   465
        if (smaller(tree, v, s->heap[j], s->depth)) break;
slouken@521
   466
slouken@521
   467
        /* Exchange v with the smallest son */
slouken@521
   468
        s->heap[k] = s->heap[j];  k = j;
slouken@521
   469
slouken@521
   470
        /* And continue down the tree, setting j to the left son of k */
slouken@521
   471
        j <<= 1;
slouken@521
   472
    }
slouken@521
   473
    s->heap[k] = v;
slouken@521
   474
}
slouken@521
   475
slouken@521
   476
/* ===========================================================================
slouken@521
   477
 * Compute the optimal bit lengths for a tree and update the total bit length
slouken@521
   478
 * for the current block.
slouken@521
   479
 * IN assertion: the fields freq and dad are set, heap[heap_max] and
slouken@521
   480
 *    above are the tree nodes sorted by increasing frequency.
slouken@521
   481
 * OUT assertions: the field len is set to the optimal bit length, the
slouken@521
   482
 *     array bl_count contains the frequencies for each bit length.
slouken@521
   483
 *     The length opt_len is updated; static_len is also updated if stree is
slouken@521
   484
 *     not null.
slouken@521
   485
 */
slouken@521
   486
local void gen_bitlen(s, desc)
slouken@521
   487
    deflate_state *s;
slouken@521
   488
    tree_desc *desc;    /* the tree descriptor */
slouken@521
   489
{
slouken@521
   490
    ct_data *tree        = desc->dyn_tree;
slouken@521
   491
    int max_code         = desc->max_code;
slouken@521
   492
    const ct_data *stree = desc->stat_desc->static_tree;
slouken@521
   493
    const intf *extra    = desc->stat_desc->extra_bits;
slouken@521
   494
    int base             = desc->stat_desc->extra_base;
slouken@521
   495
    int max_length       = desc->stat_desc->max_length;
slouken@521
   496
    int h;              /* heap index */
slouken@521
   497
    int n, m;           /* iterate over the tree elements */
slouken@521
   498
    int bits;           /* bit length */
slouken@521
   499
    int xbits;          /* extra bits */
slouken@521
   500
    ush f;              /* frequency */
slouken@521
   501
    int overflow = 0;   /* number of elements with bit length too large */
slouken@521
   502
slouken@521
   503
    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
slouken@521
   504
slouken@521
   505
    /* In a first pass, compute the optimal bit lengths (which may
slouken@521
   506
     * overflow in the case of the bit length tree).
slouken@521
   507
     */
slouken@521
   508
    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
slouken@521
   509
slouken@521
   510
    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
slouken@521
   511
        n = s->heap[h];
slouken@521
   512
        bits = tree[tree[n].Dad].Len + 1;
slouken@521
   513
        if (bits > max_length) bits = max_length, overflow++;
slouken@521
   514
        tree[n].Len = (ush)bits;
slouken@521
   515
        /* We overwrite tree[n].Dad which is no longer needed */
slouken@521
   516
slouken@521
   517
        if (n > max_code) continue; /* not a leaf node */
slouken@521
   518
slouken@521
   519
        s->bl_count[bits]++;
slouken@521
   520
        xbits = 0;
slouken@521
   521
        if (n >= base) xbits = extra[n-base];
slouken@521
   522
        f = tree[n].Freq;
slouken@521
   523
        s->opt_len += (ulg)f * (unsigned)(bits + xbits);
slouken@521
   524
        if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
slouken@521
   525
    }
slouken@521
   526
    if (overflow == 0) return;
slouken@521
   527
slouken@521
   528
    Tracev((stderr,"\nbit length overflow\n"));
slouken@521
   529
    /* This happens for example on obj2 and pic of the Calgary corpus */
slouken@521
   530
slouken@521
   531
    /* Find the first bit length which could increase: */
slouken@521
   532
    do {
slouken@521
   533
        bits = max_length-1;
slouken@521
   534
        while (s->bl_count[bits] == 0) bits--;
slouken@521
   535
        s->bl_count[bits]--;      /* move one leaf down the tree */
slouken@521
   536
        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
slouken@521
   537
        s->bl_count[max_length]--;
slouken@521
   538
        /* The brother of the overflow item also moves one step up,
slouken@521
   539
         * but this does not affect bl_count[max_length]
slouken@521
   540
         */
slouken@521
   541
        overflow -= 2;
slouken@521
   542
    } while (overflow > 0);
slouken@521
   543
slouken@521
   544
    /* Now recompute all bit lengths, scanning in increasing frequency.
slouken@521
   545
     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
slouken@521
   546
     * lengths instead of fixing only the wrong ones. This idea is taken
slouken@521
   547
     * from 'ar' written by Haruhiko Okumura.)
slouken@521
   548
     */
slouken@521
   549
    for (bits = max_length; bits != 0; bits--) {
slouken@521
   550
        n = s->bl_count[bits];
slouken@521
   551
        while (n != 0) {
slouken@521
   552
            m = s->heap[--h];
slouken@521
   553
            if (m > max_code) continue;
slouken@521
   554
            if ((unsigned) tree[m].Len != (unsigned) bits) {
slouken@521
   555
                Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
slouken@521
   556
                s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
slouken@521
   557
                tree[m].Len = (ush)bits;
slouken@521
   558
            }
slouken@521
   559
            n--;
slouken@521
   560
        }
slouken@521
   561
    }
slouken@521
   562
}
slouken@521
   563
slouken@521
   564
/* ===========================================================================
slouken@521
   565
 * Generate the codes for a given tree and bit counts (which need not be
slouken@521
   566
 * optimal).
slouken@521
   567
 * IN assertion: the array bl_count contains the bit length statistics for
slouken@521
   568
 * the given tree and the field len is set for all tree elements.
slouken@521
   569
 * OUT assertion: the field code is set for all tree elements of non
slouken@521
   570
 *     zero code length.
slouken@521
   571
 */
slouken@521
   572
local void gen_codes (tree, max_code, bl_count)
slouken@521
   573
    ct_data *tree;             /* the tree to decorate */
slouken@521
   574
    int max_code;              /* largest code with non zero frequency */
slouken@521
   575
    ushf *bl_count;            /* number of codes at each bit length */
slouken@521
   576
{
slouken@521
   577
    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
slouken@521
   578
    unsigned code = 0;         /* running code value */
slouken@521
   579
    int bits;                  /* bit index */
slouken@521
   580
    int n;                     /* code index */
slouken@521
   581
slouken@521
   582
    /* The distribution counts are first used to generate the code values
slouken@521
   583
     * without bit reversal.
slouken@521
   584
     */
slouken@521
   585
    for (bits = 1; bits <= MAX_BITS; bits++) {
slouken@521
   586
        code = (code + bl_count[bits-1]) << 1;
slouken@521
   587
        next_code[bits] = (ush)code;
slouken@521
   588
    }
slouken@521
   589
    /* Check that the bit counts in bl_count are consistent. The last code
slouken@521
   590
     * must be all ones.
slouken@521
   591
     */
slouken@521
   592
    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
slouken@521
   593
            "inconsistent bit counts");
slouken@521
   594
    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
slouken@521
   595
slouken@521
   596
    for (n = 0;  n <= max_code; n++) {
slouken@521
   597
        int len = tree[n].Len;
slouken@521
   598
        if (len == 0) continue;
slouken@521
   599
        /* Now reverse the bits */
slouken@521
   600
        tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
slouken@521
   601
slouken@521
   602
        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
slouken@521
   603
             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
slouken@521
   604
    }
slouken@521
   605
}
slouken@521
   606
slouken@521
   607
/* ===========================================================================
slouken@521
   608
 * Construct one Huffman tree and assigns the code bit strings and lengths.
slouken@521
   609
 * Update the total bit length for the current block.
slouken@521
   610
 * IN assertion: the field freq is set for all tree elements.
slouken@521
   611
 * OUT assertions: the fields len and code are set to the optimal bit length
slouken@521
   612
 *     and corresponding code. The length opt_len is updated; static_len is
slouken@521
   613
 *     also updated if stree is not null. The field max_code is set.
slouken@521
   614
 */
slouken@521
   615
local void build_tree(s, desc)
slouken@521
   616
    deflate_state *s;
slouken@521
   617
    tree_desc *desc; /* the tree descriptor */
slouken@521
   618
{
slouken@521
   619
    ct_data *tree         = desc->dyn_tree;
slouken@521
   620
    const ct_data *stree  = desc->stat_desc->static_tree;
slouken@521
   621
    int elems             = desc->stat_desc->elems;
slouken@521
   622
    int n, m;          /* iterate over heap elements */
slouken@521
   623
    int max_code = -1; /* largest code with non zero frequency */
slouken@521
   624
    int node;          /* new node being created */
slouken@521
   625
slouken@521
   626
    /* Construct the initial heap, with least frequent element in
slouken@521
   627
     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
slouken@521
   628
     * heap[0] is not used.
slouken@521
   629
     */
slouken@521
   630
    s->heap_len = 0, s->heap_max = HEAP_SIZE;
slouken@521
   631
slouken@521
   632
    for (n = 0; n < elems; n++) {
slouken@521
   633
        if (tree[n].Freq != 0) {
slouken@521
   634
            s->heap[++(s->heap_len)] = max_code = n;
slouken@521
   635
            s->depth[n] = 0;
slouken@521
   636
        } else {
slouken@521
   637
            tree[n].Len = 0;
slouken@521
   638
        }
slouken@521
   639
    }
slouken@521
   640
slouken@521
   641
    /* The pkzip format requires that at least one distance code exists,
slouken@521
   642
     * and that at least one bit should be sent even if there is only one
slouken@521
   643
     * possible code. So to avoid special checks later on we force at least
slouken@521
   644
     * two codes of non zero frequency.
slouken@521
   645
     */
slouken@521
   646
    while (s->heap_len < 2) {
slouken@521
   647
        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
slouken@521
   648
        tree[node].Freq = 1;
slouken@521
   649
        s->depth[node] = 0;
slouken@521
   650
        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
slouken@521
   651
        /* node is 0 or 1 so it does not have extra bits */
slouken@521
   652
    }
slouken@521
   653
    desc->max_code = max_code;
slouken@521
   654
slouken@521
   655
    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
slouken@521
   656
     * establish sub-heaps of increasing lengths:
slouken@521
   657
     */
slouken@521
   658
    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
slouken@521
   659
slouken@521
   660
    /* Construct the Huffman tree by repeatedly combining the least two
slouken@521
   661
     * frequent nodes.
slouken@521
   662
     */
slouken@521
   663
    node = elems;              /* next internal node of the tree */
slouken@521
   664
    do {
slouken@521
   665
        pqremove(s, tree, n);  /* n = node of least frequency */
slouken@521
   666
        m = s->heap[SMALLEST]; /* m = node of next least frequency */
slouken@521
   667
slouken@521
   668
        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
slouken@521
   669
        s->heap[--(s->heap_max)] = m;
slouken@521
   670
slouken@521
   671
        /* Create a new node father of n and m */
slouken@521
   672
        tree[node].Freq = tree[n].Freq + tree[m].Freq;
slouken@521
   673
        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
slouken@521
   674
                                s->depth[n] : s->depth[m]) + 1);
slouken@521
   675
        tree[n].Dad = tree[m].Dad = (ush)node;
slouken@521
   676
#ifdef DUMP_BL_TREE
slouken@521
   677
        if (tree == s->bl_tree) {
slouken@521
   678
            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
slouken@521
   679
                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
slouken@521
   680
        }
slouken@521
   681
#endif
slouken@521
   682
        /* and insert the new node in the heap */
slouken@521
   683
        s->heap[SMALLEST] = node++;
slouken@521
   684
        pqdownheap(s, tree, SMALLEST);
slouken@521
   685
slouken@521
   686
    } while (s->heap_len >= 2);
slouken@521
   687
slouken@521
   688
    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
slouken@521
   689
slouken@521
   690
    /* At this point, the fields freq and dad are set. We can now
slouken@521
   691
     * generate the bit lengths.
slouken@521
   692
     */
slouken@521
   693
    gen_bitlen(s, (tree_desc *)desc);
slouken@521
   694
slouken@521
   695
    /* The field len is now set, we can generate the bit codes */
slouken@521
   696
    gen_codes ((ct_data *)tree, max_code, s->bl_count);
slouken@521
   697
}
slouken@521
   698
slouken@521
   699
/* ===========================================================================
slouken@521
   700
 * Scan a literal or distance tree to determine the frequencies of the codes
slouken@521
   701
 * in the bit length tree.
slouken@521
   702
 */
slouken@521
   703
local void scan_tree (s, tree, max_code)
slouken@521
   704
    deflate_state *s;
slouken@521
   705
    ct_data *tree;   /* the tree to be scanned */
slouken@521
   706
    int max_code;    /* and its largest code of non zero frequency */
slouken@521
   707
{
slouken@521
   708
    int n;                     /* iterates over all tree elements */
slouken@521
   709
    int prevlen = -1;          /* last emitted length */
slouken@521
   710
    int curlen;                /* length of current code */
slouken@521
   711
    int nextlen = tree[0].Len; /* length of next code */
slouken@521
   712
    int count = 0;             /* repeat count of the current code */
slouken@521
   713
    int max_count = 7;         /* max repeat count */
slouken@521
   714
    int min_count = 4;         /* min repeat count */
slouken@521
   715
slouken@521
   716
    if (nextlen == 0) max_count = 138, min_count = 3;
slouken@521
   717
    tree[max_code+1].Len = (ush)0xffff; /* guard */
slouken@521
   718
slouken@521
   719
    for (n = 0; n <= max_code; n++) {
slouken@521
   720
        curlen = nextlen; nextlen = tree[n+1].Len;
slouken@521
   721
        if (++count < max_count && curlen == nextlen) {
slouken@521
   722
            continue;
slouken@521
   723
        } else if (count < min_count) {
slouken@521
   724
            s->bl_tree[curlen].Freq += count;
slouken@521
   725
        } else if (curlen != 0) {
slouken@521
   726
            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
slouken@521
   727
            s->bl_tree[REP_3_6].Freq++;
slouken@521
   728
        } else if (count <= 10) {
slouken@521
   729
            s->bl_tree[REPZ_3_10].Freq++;
slouken@521
   730
        } else {
slouken@521
   731
            s->bl_tree[REPZ_11_138].Freq++;
slouken@521
   732
        }
slouken@521
   733
        count = 0; prevlen = curlen;
slouken@521
   734
        if (nextlen == 0) {
slouken@521
   735
            max_count = 138, min_count = 3;
slouken@521
   736
        } else if (curlen == nextlen) {
slouken@521
   737
            max_count = 6, min_count = 3;
slouken@521
   738
        } else {
slouken@521
   739
            max_count = 7, min_count = 4;
slouken@521
   740
        }
slouken@521
   741
    }
slouken@521
   742
}
slouken@521
   743
slouken@521
   744
/* ===========================================================================
slouken@521
   745
 * Send a literal or distance tree in compressed form, using the codes in
slouken@521
   746
 * bl_tree.
slouken@521
   747
 */
slouken@521
   748
local void send_tree (s, tree, max_code)
slouken@521
   749
    deflate_state *s;
slouken@521
   750
    ct_data *tree; /* the tree to be scanned */
slouken@521
   751
    int max_code;       /* and its largest code of non zero frequency */
slouken@521
   752
{
slouken@521
   753
    int n;                     /* iterates over all tree elements */
slouken@521
   754
    int prevlen = -1;          /* last emitted length */
slouken@521
   755
    int curlen;                /* length of current code */
slouken@521
   756
    int nextlen = tree[0].Len; /* length of next code */
slouken@521
   757
    int count = 0;             /* repeat count of the current code */
slouken@521
   758
    int max_count = 7;         /* max repeat count */
slouken@521
   759
    int min_count = 4;         /* min repeat count */
slouken@521
   760
slouken@521
   761
    /* tree[max_code+1].Len = -1; */  /* guard already set */
slouken@521
   762
    if (nextlen == 0) max_count = 138, min_count = 3;
slouken@521
   763
slouken@521
   764
    for (n = 0; n <= max_code; n++) {
slouken@521
   765
        curlen = nextlen; nextlen = tree[n+1].Len;
slouken@521
   766
        if (++count < max_count && curlen == nextlen) {
slouken@521
   767
            continue;
slouken@521
   768
        } else if (count < min_count) {
slouken@521
   769
            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
slouken@521
   770
slouken@521
   771
        } else if (curlen != 0) {
slouken@521
   772
            if (curlen != prevlen) {
slouken@521
   773
                send_code(s, curlen, s->bl_tree); count--;
slouken@521
   774
            }
slouken@521
   775
            Assert(count >= 3 && count <= 6, " 3_6?");
slouken@521
   776
            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
slouken@521
   777
slouken@521
   778
        } else if (count <= 10) {
slouken@521
   779
            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
slouken@521
   780
slouken@521
   781
        } else {
slouken@521
   782
            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
slouken@521
   783
        }
slouken@521
   784
        count = 0; prevlen = curlen;
slouken@521
   785
        if (nextlen == 0) {
slouken@521
   786
            max_count = 138, min_count = 3;
slouken@521
   787
        } else if (curlen == nextlen) {
slouken@521
   788
            max_count = 6, min_count = 3;
slouken@521
   789
        } else {
slouken@521
   790
            max_count = 7, min_count = 4;
slouken@521
   791
        }
slouken@521
   792
    }
slouken@521
   793
}
slouken@521
   794
slouken@521
   795
/* ===========================================================================
slouken@521
   796
 * Construct the Huffman tree for the bit lengths and return the index in
slouken@521
   797
 * bl_order of the last bit length code to send.
slouken@521
   798
 */
slouken@521
   799
local int build_bl_tree(s)
slouken@521
   800
    deflate_state *s;
slouken@521
   801
{
slouken@521
   802
    int max_blindex;  /* index of last bit length code of non zero freq */
slouken@521
   803
slouken@521
   804
    /* Determine the bit length frequencies for literal and distance trees */
slouken@521
   805
    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
slouken@521
   806
    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
slouken@521
   807
slouken@521
   808
    /* Build the bit length tree: */
slouken@521
   809
    build_tree(s, (tree_desc *)(&(s->bl_desc)));
slouken@521
   810
    /* opt_len now includes the length of the tree representations, except
slouken@521
   811
     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
slouken@521
   812
     */
slouken@521
   813
slouken@521
   814
    /* Determine the number of bit length codes to send. The pkzip format
slouken@521
   815
     * requires that at least 4 bit length codes be sent. (appnote.txt says
slouken@521
   816
     * 3 but the actual value used is 4.)
slouken@521
   817
     */
slouken@521
   818
    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
slouken@521
   819
        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
slouken@521
   820
    }
slouken@521
   821
    /* Update opt_len to include the bit length tree and counts */
slouken@521
   822
    s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
slouken@521
   823
    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
slouken@521
   824
            s->opt_len, s->static_len));
slouken@521
   825
slouken@521
   826
    return max_blindex;
slouken@521
   827
}
slouken@521
   828
slouken@521
   829
/* ===========================================================================
slouken@521
   830
 * Send the header for a block using dynamic Huffman trees: the counts, the
slouken@521
   831
 * lengths of the bit length codes, the literal tree and the distance tree.
slouken@521
   832
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
slouken@521
   833
 */
slouken@521
   834
local void send_all_trees(s, lcodes, dcodes, blcodes)
slouken@521
   835
    deflate_state *s;
slouken@521
   836
    int lcodes, dcodes, blcodes; /* number of codes for each tree */
slouken@521
   837
{
slouken@521
   838
    int rank;                    /* index in bl_order */
slouken@521
   839
slouken@521
   840
    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
slouken@521
   841
    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
slouken@521
   842
            "too many codes");
slouken@521
   843
    Tracev((stderr, "\nbl counts: "));
slouken@521
   844
    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
slouken@521
   845
    send_bits(s, dcodes-1,   5);
slouken@521
   846
    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
slouken@521
   847
    for (rank = 0; rank < blcodes; rank++) {
slouken@521
   848
        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
slouken@521
   849
        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
slouken@521
   850
    }
slouken@521
   851
    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
slouken@521
   852
slouken@521
   853
    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
slouken@521
   854
    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
slouken@521
   855
slouken@521
   856
    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
slouken@521
   857
    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
slouken@521
   858
}
slouken@521
   859
slouken@521
   860
/* ===========================================================================
slouken@521
   861
 * Send a stored block
slouken@521
   862
 */
slouken@521
   863
void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
slouken@521
   864
    deflate_state *s;
slouken@521
   865
    charf *buf;       /* input block */
slouken@521
   866
    ulg stored_len;   /* length of input block */
slouken@521
   867
    int last;         /* one if this is the last block for a file */
slouken@521
   868
{
slouken@521
   869
    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
slouken@521
   870
    bi_windup(s);        /* align on byte boundary */
slouken@521
   871
    put_short(s, (ush)stored_len);
slouken@521
   872
    put_short(s, (ush)~stored_len);
slouken@521
   873
    zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
slouken@521
   874
    s->pending += stored_len;
slouken@521
   875
#ifdef ZLIB_DEBUG
slouken@521
   876
    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
slouken@521
   877
    s->compressed_len += (stored_len + 4) << 3;
slouken@521
   878
    s->bits_sent += 2*16;
slouken@521
   879
    s->bits_sent += stored_len<<3;
slouken@521
   880
#endif
slouken@521
   881
}
slouken@521
   882
slouken@521
   883
/* ===========================================================================
slouken@521
   884
 * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
slouken@521
   885
 */
slouken@521
   886
void ZLIB_INTERNAL _tr_flush_bits(s)
slouken@521
   887
    deflate_state *s;
slouken@521
   888
{
slouken@521
   889
    bi_flush(s);
slouken@521
   890
}
slouken@521
   891
slouken@521
   892
/* ===========================================================================
slouken@521
   893
 * Send one empty static block to give enough lookahead for inflate.
slouken@521
   894
 * This takes 10 bits, of which 7 may remain in the bit buffer.
slouken@521
   895
 */
slouken@521
   896
void ZLIB_INTERNAL _tr_align(s)
slouken@521
   897
    deflate_state *s;
slouken@521
   898
{
slouken@521
   899
    send_bits(s, STATIC_TREES<<1, 3);
slouken@521
   900
    send_code(s, END_BLOCK, static_ltree);
slouken@521
   901
#ifdef ZLIB_DEBUG
slouken@521
   902
    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
slouken@521
   903
#endif
slouken@521
   904
    bi_flush(s);
slouken@521
   905
}
slouken@521
   906
slouken@521
   907
/* ===========================================================================
slouken@521
   908
 * Determine the best encoding for the current block: dynamic trees, static
slouken@521
   909
 * trees or store, and write out the encoded block.
slouken@521
   910
 */
slouken@521
   911
void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
slouken@521
   912
    deflate_state *s;
slouken@521
   913
    charf *buf;       /* input block, or NULL if too old */
slouken@521
   914
    ulg stored_len;   /* length of input block */
slouken@521
   915
    int last;         /* one if this is the last block for a file */
slouken@521
   916
{
slouken@521
   917
    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
slouken@521
   918
    int max_blindex = 0;  /* index of last bit length code of non zero freq */
slouken@521
   919
slouken@521
   920
    /* Build the Huffman trees unless a stored block is forced */
slouken@521
   921
    if (s->level > 0) {
slouken@521
   922
slouken@521
   923
        /* Check if the file is binary or text */
slouken@521
   924
        if (s->strm->data_type == Z_UNKNOWN)
slouken@521
   925
            s->strm->data_type = detect_data_type(s);
slouken@521
   926
slouken@521
   927
        /* Construct the literal and distance trees */
slouken@521
   928
        build_tree(s, (tree_desc *)(&(s->l_desc)));
slouken@521
   929
        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
slouken@521
   930
                s->static_len));
slouken@521
   931
slouken@521
   932
        build_tree(s, (tree_desc *)(&(s->d_desc)));
slouken@521
   933
        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
slouken@521
   934
                s->static_len));
slouken@521
   935
        /* At this point, opt_len and static_len are the total bit lengths of
slouken@521
   936
         * the compressed block data, excluding the tree representations.
slouken@521
   937
         */
slouken@521
   938
slouken@521
   939
        /* Build the bit length tree for the above two trees, and get the index
slouken@521
   940
         * in bl_order of the last bit length code to send.
slouken@521
   941
         */
slouken@521
   942
        max_blindex = build_bl_tree(s);
slouken@521
   943
slouken@521
   944
        /* Determine the best encoding. Compute the block lengths in bytes. */
slouken@521
   945
        opt_lenb = (s->opt_len+3+7)>>3;
slouken@521
   946
        static_lenb = (s->static_len+3+7)>>3;
slouken@521
   947
slouken@521
   948
        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
slouken@521
   949
                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
slouken@521
   950
                s->last_lit));
slouken@521
   951
slouken@521
   952
        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
slouken@521
   953
slouken@521
   954
    } else {
slouken@521
   955
        Assert(buf != (char*)0, "lost buf");
slouken@521
   956
        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
slouken@521
   957
    }
slouken@521
   958
slouken@521
   959
#ifdef FORCE_STORED
slouken@521
   960
    if (buf != (char*)0) { /* force stored block */
slouken@521
   961
#else
slouken@521
   962
    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
slouken@521
   963
                       /* 4: two words for the lengths */
slouken@521
   964
#endif
slouken@521
   965
        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
slouken@521
   966
         * Otherwise we can't have processed more than WSIZE input bytes since
slouken@521
   967
         * the last block flush, because compression would have been
slouken@521
   968
         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
slouken@521
   969
         * transform a block into a stored block.
slouken@521
   970
         */
slouken@521
   971
        _tr_stored_block(s, buf, stored_len, last);
slouken@521
   972
slouken@521
   973
#ifdef FORCE_STATIC
slouken@521
   974
    } else if (static_lenb >= 0) { /* force static trees */
slouken@521
   975
#else
slouken@521
   976
    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
slouken@521
   977
#endif
slouken@521
   978
        send_bits(s, (STATIC_TREES<<1)+last, 3);
slouken@521
   979
        compress_block(s, (const ct_data *)static_ltree,
slouken@521
   980
                       (const ct_data *)static_dtree);
slouken@521
   981
#ifdef ZLIB_DEBUG
slouken@521
   982
        s->compressed_len += 3 + s->static_len;
slouken@521
   983
#endif
slouken@521
   984
    } else {
slouken@521
   985
        send_bits(s, (DYN_TREES<<1)+last, 3);
slouken@521
   986
        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
slouken@521
   987
                       max_blindex+1);
slouken@521
   988
        compress_block(s, (const ct_data *)s->dyn_ltree,
slouken@521
   989
                       (const ct_data *)s->dyn_dtree);
slouken@521
   990
#ifdef ZLIB_DEBUG
slouken@521
   991
        s->compressed_len += 3 + s->opt_len;
slouken@521
   992
#endif
slouken@521
   993
    }
slouken@521
   994
    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
slouken@521
   995
    /* The above check is made mod 2^32, for files larger than 512 MB
slouken@521
   996
     * and uLong implemented on 32 bits.
slouken@521
   997
     */
slouken@521
   998
    init_block(s);
slouken@521
   999
slouken@521
  1000
    if (last) {
slouken@521
  1001
        bi_windup(s);
slouken@521
  1002
#ifdef ZLIB_DEBUG
slouken@521
  1003
        s->compressed_len += 7;  /* align on byte boundary */
slouken@521
  1004
#endif
slouken@521
  1005
    }
slouken@521
  1006
    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
slouken@521
  1007
           s->compressed_len-7*last));
slouken@521
  1008
}
slouken@521
  1009
slouken@521
  1010
/* ===========================================================================
slouken@521
  1011
 * Save the match info and tally the frequency counts. Return true if
slouken@521
  1012
 * the current block must be flushed.
slouken@521
  1013
 */
slouken@521
  1014
int ZLIB_INTERNAL _tr_tally (s, dist, lc)
slouken@521
  1015
    deflate_state *s;
slouken@521
  1016
    unsigned dist;  /* distance of matched string */
slouken@521
  1017
    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
slouken@521
  1018
{
slouken@521
  1019
    s->d_buf[s->last_lit] = (ush)dist;
slouken@521
  1020
    s->l_buf[s->last_lit++] = (uch)lc;
slouken@521
  1021
    if (dist == 0) {
slouken@521
  1022
        /* lc is the unmatched char */
slouken@521
  1023
        s->dyn_ltree[lc].Freq++;
slouken@521
  1024
    } else {
slouken@521
  1025
        s->matches++;
slouken@521
  1026
        /* Here, lc is the match length - MIN_MATCH */
slouken@521
  1027
        dist--;             /* dist = match distance - 1 */
slouken@521
  1028
        Assert((ush)dist < (ush)MAX_DIST(s) &&
slouken@521
  1029
               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
slouken@521
  1030
               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
slouken@521
  1031
slouken@521
  1032
        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
slouken@521
  1033
        s->dyn_dtree[d_code(dist)].Freq++;
slouken@521
  1034
    }
slouken@521
  1035
slouken@521
  1036
#ifdef TRUNCATE_BLOCK
slouken@521
  1037
    /* Try to guess if it is profitable to stop the current block here */
slouken@521
  1038
    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
slouken@521
  1039
        /* Compute an upper bound for the compressed length */
slouken@521
  1040
        ulg out_length = (ulg)s->last_lit*8L;
slouken@521
  1041
        ulg in_length = (ulg)((long)s->strstart - s->block_start);
slouken@521
  1042
        int dcode;
slouken@521
  1043
        for (dcode = 0; dcode < D_CODES; dcode++) {
slouken@521
  1044
            out_length += (ulg)s->dyn_dtree[dcode].Freq *
slouken@521
  1045
                (5L+extra_dbits[dcode]);
slouken@521
  1046
        }
slouken@521
  1047
        out_length >>= 3;
slouken@521
  1048
        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
slouken@521
  1049
               s->last_lit, in_length, out_length,
slouken@521
  1050
               100L - out_length*100L/in_length));
slouken@521
  1051
        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
slouken@521
  1052
    }
slouken@521
  1053
#endif
slouken@521
  1054
    return (s->last_lit == s->lit_bufsize-1);
slouken@521
  1055
    /* We avoid equality with lit_bufsize because of wraparound at 64K
slouken@521
  1056
     * on 16 bit machines and because stored blocks are restricted to
slouken@521
  1057
     * 64K-1 bytes.
slouken@521
  1058
     */
slouken@521
  1059
}
slouken@521
  1060
slouken@521
  1061
/* ===========================================================================
slouken@521
  1062
 * Send the block data compressed using the given Huffman trees
slouken@521
  1063
 */
slouken@521
  1064
local void compress_block(s, ltree, dtree)
slouken@521
  1065
    deflate_state *s;
slouken@521
  1066
    const ct_data *ltree; /* literal tree */
slouken@521
  1067
    const ct_data *dtree; /* distance tree */
slouken@521
  1068
{
slouken@521
  1069
    unsigned dist;      /* distance of matched string */
slouken@521
  1070
    int lc;             /* match length or unmatched char (if dist == 0) */
slouken@521
  1071
    unsigned lx = 0;    /* running index in l_buf */
slouken@521
  1072
    unsigned code;      /* the code to send */
slouken@521
  1073
    int extra;          /* number of extra bits to send */
slouken@521
  1074
slouken@521
  1075
    if (s->last_lit != 0) do {
slouken@521
  1076
        dist = s->d_buf[lx];
slouken@521
  1077
        lc = s->l_buf[lx++];
slouken@521
  1078
        if (dist == 0) {
slouken@521
  1079
            send_code(s, lc, ltree); /* send a literal byte */
slouken@521
  1080
            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
slouken@521
  1081
        } else {
slouken@521
  1082
            /* Here, lc is the match length - MIN_MATCH */
slouken@521
  1083
            code = _length_code[lc];
slouken@521
  1084
            send_code(s, code+LITERALS+1, ltree); /* send the length code */
slouken@521
  1085
            extra = extra_lbits[code];
slouken@521
  1086
            if (extra != 0) {
slouken@521
  1087
                lc -= base_length[code];
slouken@521
  1088
                send_bits(s, lc, extra);       /* send the extra length bits */
slouken@521
  1089
            }
slouken@521
  1090
            dist--; /* dist is now the match distance - 1 */
slouken@521
  1091
            code = d_code(dist);
slouken@521
  1092
            Assert (code < D_CODES, "bad d_code");
slouken@521
  1093
slouken@521
  1094
            send_code(s, code, dtree);       /* send the distance code */
slouken@521
  1095
            extra = extra_dbits[code];
slouken@521
  1096
            if (extra != 0) {
slouken@521
  1097
                dist -= (unsigned)base_dist[code];
slouken@521
  1098
                send_bits(s, dist, extra);   /* send the extra distance bits */
slouken@521
  1099
            }
slouken@521
  1100
        } /* literal or match pair ? */
slouken@521
  1101
slouken@521
  1102
        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
slouken@521
  1103
        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
slouken@521
  1104
               "pendingBuf overflow");
slouken@521
  1105
slouken@521
  1106
    } while (lx < s->last_lit);
slouken@521
  1107
slouken@521
  1108
    send_code(s, END_BLOCK, ltree);
slouken@521
  1109
}
slouken@521
  1110
slouken@521
  1111
/* ===========================================================================
slouken@521
  1112
 * Check if the data type is TEXT or BINARY, using the following algorithm:
slouken@521
  1113
 * - TEXT if the two conditions below are satisfied:
slouken@521
  1114
 *    a) There are no non-portable control characters belonging to the
slouken@521
  1115
 *       "black list" (0..6, 14..25, 28..31).
slouken@521
  1116
 *    b) There is at least one printable character belonging to the
slouken@521
  1117
 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
slouken@521
  1118
 * - BINARY otherwise.
slouken@521
  1119
 * - The following partially-portable control characters form a
slouken@521
  1120
 *   "gray list" that is ignored in this detection algorithm:
slouken@521
  1121
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
slouken@521
  1122
 * IN assertion: the fields Freq of dyn_ltree are set.
slouken@521
  1123
 */
slouken@521
  1124
local int detect_data_type(s)
slouken@521
  1125
    deflate_state *s;
slouken@521
  1126
{
slouken@521
  1127
    /* black_mask is the bit mask of black-listed bytes
slouken@521
  1128
     * set bits 0..6, 14..25, and 28..31
slouken@521
  1129
     * 0xf3ffc07f = binary 11110011111111111100000001111111
slouken@521
  1130
     */
slouken@521
  1131
    unsigned long black_mask = 0xf3ffc07fUL;
slouken@521
  1132
    int n;
slouken@521
  1133
slouken@521
  1134
    /* Check for non-textual ("black-listed") bytes. */
slouken@521
  1135
    for (n = 0; n <= 31; n++, black_mask >>= 1)
slouken@521
  1136
        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
slouken@521
  1137
            return Z_BINARY;
slouken@521
  1138
slouken@521
  1139
    /* Check for textual ("white-listed") bytes. */
slouken@521
  1140
    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
slouken@521
  1141
            || s->dyn_ltree[13].Freq != 0)
slouken@521
  1142
        return Z_TEXT;
slouken@521
  1143
    for (n = 32; n < LITERALS; n++)
slouken@521
  1144
        if (s->dyn_ltree[n].Freq != 0)
slouken@521
  1145
            return Z_TEXT;
slouken@521
  1146
slouken@521
  1147
    /* There are no "black-listed" or "white-listed" bytes:
slouken@521
  1148
     * this stream either is empty or has tolerated ("gray-listed") bytes only.
slouken@521
  1149
     */
slouken@521
  1150
    return Z_BINARY;
slouken@521
  1151
}
slouken@521
  1152
slouken@521
  1153
/* ===========================================================================
slouken@521
  1154
 * Reverse the first len bits of a code, using straightforward code (a faster
slouken@521
  1155
 * method would use a table)
slouken@521
  1156
 * IN assertion: 1 <= len <= 15
slouken@521
  1157
 */
slouken@521
  1158
local unsigned bi_reverse(code, len)
slouken@521
  1159
    unsigned code; /* the value to invert */
slouken@521
  1160
    int len;       /* its bit length */
slouken@521
  1161
{
slouken@521
  1162
    register unsigned res = 0;
slouken@521
  1163
    do {
slouken@521
  1164
        res |= code & 1;
slouken@521
  1165
        code >>= 1, res <<= 1;
slouken@521
  1166
    } while (--len > 0);
slouken@521
  1167
    return res >> 1;
slouken@521
  1168
}
slouken@521
  1169
slouken@521
  1170
/* ===========================================================================
slouken@521
  1171
 * Flush the bit buffer, keeping at most 7 bits in it.
slouken@521
  1172
 */
slouken@521
  1173
local void bi_flush(s)
slouken@521
  1174
    deflate_state *s;
slouken@521
  1175
{
slouken@521
  1176
    if (s->bi_valid == 16) {
slouken@521
  1177
        put_short(s, s->bi_buf);
slouken@521
  1178
        s->bi_buf = 0;
slouken@521
  1179
        s->bi_valid = 0;
slouken@521
  1180
    } else if (s->bi_valid >= 8) {
slouken@521
  1181
        put_byte(s, (Byte)s->bi_buf);
slouken@521
  1182
        s->bi_buf >>= 8;
slouken@521
  1183
        s->bi_valid -= 8;
slouken@521
  1184
    }
slouken@521
  1185
}
slouken@521
  1186
slouken@521
  1187
/* ===========================================================================
slouken@521
  1188
 * Flush the bit buffer and align the output on a byte boundary
slouken@521
  1189
 */
slouken@521
  1190
local void bi_windup(s)
slouken@521
  1191
    deflate_state *s;
slouken@521
  1192
{
slouken@521
  1193
    if (s->bi_valid > 8) {
slouken@521
  1194
        put_short(s, s->bi_buf);
slouken@521
  1195
    } else if (s->bi_valid > 0) {
slouken@521
  1196
        put_byte(s, (Byte)s->bi_buf);
slouken@521
  1197
    }
slouken@521
  1198
    s->bi_buf = 0;
slouken@521
  1199
    s->bi_valid = 0;
slouken@521
  1200
#ifdef ZLIB_DEBUG
slouken@521
  1201
    s->bits_sent = (s->bits_sent+7) & ~7;
slouken@521
  1202
#endif
slouken@521
  1203
}