117651Speter/* deflate.h -- internal compression state
2313796Sdelphij * Copyright (C) 1995-2016 Jean-loup Gailly
3131377Stjr * For conditions of distribution and use, see copyright notice in zlib.h
417651Speter */
517651Speter
617651Speter/* WARNING: this file should *not* be used by applications. It is
717651Speter   part of the implementation of the compression library and is
817651Speter   subject to change. Applications should only use zlib.h.
917651Speter */
1017651Speter
1133904Ssteve/* @(#) $Id$ */
1217651Speter
13131377Stjr#ifndef DEFLATE_H
14131377Stjr#define DEFLATE_H
1517651Speter
1617651Speter#include "zutil.h"
1717651Speter
18131377Stjr/* define NO_GZIP when compiling if you want to disable gzip header and
19131377Stjr   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
20131377Stjr   the crc code when it is not needed.  For shared libraries, gzip encoding
21131377Stjr   should be left enabled. */
22131377Stjr#ifndef NO_GZIP
23131377Stjr#  define GZIP
24131377Stjr#endif
25131377Stjr
2617651Speter/* ===========================================================================
2717651Speter * Internal compression state.
2817651Speter */
2917651Speter
3017651Speter#define LENGTH_CODES 29
3117651Speter/* number of length codes, not counting the special END_BLOCK code */
3217651Speter
3317651Speter#define LITERALS  256
3417651Speter/* number of literal bytes 0..255 */
3517651Speter
3617651Speter#define L_CODES (LITERALS+1+LENGTH_CODES)
3717651Speter/* number of Literal or Length codes, including the END_BLOCK code */
3817651Speter
3917651Speter#define D_CODES   30
4017651Speter/* number of distance codes */
4117651Speter
4217651Speter#define BL_CODES  19
4317651Speter/* number of codes used to transfer the bit lengths */
4417651Speter
4517651Speter#define HEAP_SIZE (2*L_CODES+1)
4617651Speter/* maximum heap size */
4717651Speter
4817651Speter#define MAX_BITS 15
4917651Speter/* All codes must not exceed MAX_BITS bits */
5017651Speter
51230837Sdelphij#define Buf_size 16
52230837Sdelphij/* size of bit buffer in bi_buf */
53230837Sdelphij
54313796Sdelphij#define INIT_STATE    42    /* zlib header -> BUSY_STATE */
55313796Sdelphij#ifdef GZIP
56313796Sdelphij#  define GZIP_STATE  57    /* gzip header -> BUSY_STATE | EXTRA_STATE */
57313796Sdelphij#endif
58313796Sdelphij#define EXTRA_STATE   69    /* gzip extra block -> NAME_STATE */
59313796Sdelphij#define NAME_STATE    73    /* gzip file name -> COMMENT_STATE */
60313796Sdelphij#define COMMENT_STATE 91    /* gzip comment -> HCRC_STATE */
61313796Sdelphij#define HCRC_STATE   103    /* gzip header CRC -> BUSY_STATE */
62313796Sdelphij#define BUSY_STATE   113    /* deflate -> FINISH_STATE */
63313796Sdelphij#define FINISH_STATE 666    /* stream complete */
6417651Speter/* Stream status */
6517651Speter
6617651Speter
6717651Speter/* Data structure describing a single value and its code string. */
6817651Spetertypedef struct ct_data_s {
6917651Speter    union {
7017651Speter        ush  freq;       /* frequency count */
7117651Speter        ush  code;       /* bit string */
7217651Speter    } fc;
7317651Speter    union {
7417651Speter        ush  dad;        /* father node in Huffman tree */
7517651Speter        ush  len;        /* length of bit string */
7617651Speter    } dl;
7717651Speter} FAR ct_data;
7817651Speter
7917651Speter#define Freq fc.freq
8017651Speter#define Code fc.code
8117651Speter#define Dad  dl.dad
8217651Speter#define Len  dl.len
8317651Speter
8417651Spetertypedef struct static_tree_desc_s  static_tree_desc;
8517651Speter
8617651Spetertypedef struct tree_desc_s {
8717651Speter    ct_data *dyn_tree;           /* the dynamic tree */
8817651Speter    int     max_code;            /* largest code with non zero frequency */
89313796Sdelphij    const static_tree_desc *stat_desc;  /* the corresponding static tree */
9017651Speter} FAR tree_desc;
9117651Speter
9217651Spetertypedef ush Pos;
9317651Spetertypedef Pos FAR Posf;
9417651Spetertypedef unsigned IPos;
9517651Speter
9617651Speter/* A Pos is an index in the character window. We use short instead of int to
9717651Speter * save space in the various tables. IPos is used only for parameter passing.
9817651Speter */
9917651Speter
10017651Spetertypedef struct internal_state {
10117651Speter    z_streamp strm;      /* pointer back to this zlib stream */
10217651Speter    int   status;        /* as the name implies */
10317651Speter    Bytef *pending_buf;  /* output still pending */
10433904Ssteve    ulg   pending_buf_size; /* size of pending_buf */
10517651Speter    Bytef *pending_out;  /* next pending byte to output to the stream */
106313796Sdelphij    ulg   pending;       /* nb of bytes in the pending buffer */
107131377Stjr    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
108157043Sdes    gz_headerp  gzhead;  /* gzip header information to write */
109313796Sdelphij    ulg   gzindex;       /* where in extra, name, or comment */
110250224Sdelphij    Byte  method;        /* can only be DEFLATED */
11117651Speter    int   last_flush;    /* value of flush param for previous deflate call */
11217651Speter
11317651Speter                /* used by deflate.c: */
11417651Speter
11517651Speter    uInt  w_size;        /* LZ77 window size (32K by default) */
11617651Speter    uInt  w_bits;        /* log2(w_size)  (8..16) */
11717651Speter    uInt  w_mask;        /* w_size - 1 */
11817651Speter
11917651Speter    Bytef *window;
12017651Speter    /* Sliding window. Input bytes are read into the second half of the window,
12117651Speter     * and move to the first half later to keep a dictionary of at least wSize
12217651Speter     * bytes. With this organization, matches are limited to a distance of
12317651Speter     * wSize-MAX_MATCH bytes, but this ensures that IO is always
12417651Speter     * performed with a length multiple of the block size. Also, it limits
12517651Speter     * the window size to 64K, which is quite useful on MSDOS.
12617651Speter     * To do: use the user input buffer as sliding window.
12717651Speter     */
12817651Speter
12917651Speter    ulg window_size;
13017651Speter    /* Actual size of window: 2*wSize, except when the user input buffer
13117651Speter     * is directly used as sliding window.
13217651Speter     */
13317651Speter
13417651Speter    Posf *prev;
13517651Speter    /* Link to older string with same hash index. To limit the size of this
13617651Speter     * array to 64K, this link is maintained only for the last 32K strings.
13717651Speter     * An index in this array is thus a window index modulo 32K.
13817651Speter     */
13917651Speter
14017651Speter    Posf *head; /* Heads of the hash chains or NIL. */
14117651Speter
14217651Speter    uInt  ins_h;          /* hash index of string to be inserted */
14317651Speter    uInt  hash_size;      /* number of elements in hash table */
14417651Speter    uInt  hash_bits;      /* log2(hash_size) */
14517651Speter    uInt  hash_mask;      /* hash_size-1 */
14617651Speter
14717651Speter    uInt  hash_shift;
14817651Speter    /* Number of bits by which ins_h must be shifted at each input
14917651Speter     * step. It must be such that after MIN_MATCH steps, the oldest
15017651Speter     * byte no longer takes part in the hash key, that is:
15117651Speter     *   hash_shift * MIN_MATCH >= hash_bits
15217651Speter     */
15317651Speter
15417651Speter    long block_start;
15517651Speter    /* Window position at the beginning of the current output block. Gets
15617651Speter     * negative when the window is moved backwards.
15717651Speter     */
15817651Speter
15917651Speter    uInt match_length;           /* length of best match */
16017651Speter    IPos prev_match;             /* previous match */
16117651Speter    int match_available;         /* set if previous match exists */
16217651Speter    uInt strstart;               /* start of string to insert */
16317651Speter    uInt match_start;            /* start of matching string */
16417651Speter    uInt lookahead;              /* number of valid bytes ahead in window */
16517651Speter
16617651Speter    uInt prev_length;
16717651Speter    /* Length of the best match at previous step. Matches not greater than this
16817651Speter     * are discarded. This is used in the lazy match evaluation.
16917651Speter     */
17017651Speter
17117651Speter    uInt max_chain_length;
17217651Speter    /* To speed up deflation, hash chains are never searched beyond this
17317651Speter     * length.  A higher limit improves compression ratio but degrades the
17417651Speter     * speed.
17517651Speter     */
17617651Speter
17717651Speter    uInt max_lazy_match;
17817651Speter    /* Attempt to find a better match only when the current match is strictly
17917651Speter     * smaller than this value. This mechanism is used only for compression
18017651Speter     * levels >= 4.
18117651Speter     */
18217651Speter#   define max_insert_length  max_lazy_match
18317651Speter    /* Insert new strings in the hash table only if the match length is not
18417651Speter     * greater than this length. This saves time but degrades compression.
18517651Speter     * max_insert_length is used only for compression levels <= 3.
18617651Speter     */
18717651Speter
18817651Speter    int level;    /* compression level (1..9) */
18917651Speter    int strategy; /* favor or force Huffman coding*/
19017651Speter
19117651Speter    uInt good_match;
19217651Speter    /* Use a faster search when the previous match is longer than this */
19317651Speter
19417651Speter    int nice_match; /* Stop searching when current match exceeds this */
19517651Speter
19617651Speter                /* used by trees.c: */
197230837Sdelphij    /* Didn't use ct_data typedef below to suppress compiler warning */
19817651Speter    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
19917651Speter    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
20017651Speter    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
20117651Speter
20217651Speter    struct tree_desc_s l_desc;               /* desc. for literal tree */
20317651Speter    struct tree_desc_s d_desc;               /* desc. for distance tree */
20417651Speter    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
20517651Speter
20617651Speter    ush bl_count[MAX_BITS+1];
20717651Speter    /* number of codes at each bit length for an optimal tree */
20817651Speter
20917651Speter    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
21017651Speter    int heap_len;               /* number of elements in the heap */
21117651Speter    int heap_max;               /* element of largest frequency */
21217651Speter    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
21317651Speter     * The same heap array is used to build all trees.
21417651Speter     */
21517651Speter
21617651Speter    uch depth[2*L_CODES+1];
21717651Speter    /* Depth of each subtree used as tie breaker for trees of equal frequency
21817651Speter     */
21917651Speter
22017651Speter    uchf *l_buf;          /* buffer for literals or lengths */
22117651Speter
22217651Speter    uInt  lit_bufsize;
22317651Speter    /* Size of match buffer for literals/lengths.  There are 4 reasons for
22417651Speter     * limiting lit_bufsize to 64K:
22517651Speter     *   - frequencies can be kept in 16 bit counters
22617651Speter     *   - if compression is not successful for the first block, all input
22717651Speter     *     data is still in the window so we can still emit a stored block even
22817651Speter     *     when input comes from standard input.  (This can also be done for
22917651Speter     *     all blocks if lit_bufsize is not greater than 32K.)
23017651Speter     *   - if compression is not successful for a file smaller than 64K, we can
23117651Speter     *     even emit a stored file instead of a stored block (saving 5 bytes).
23217651Speter     *     This is applicable only for zip (not gzip or zlib).
23317651Speter     *   - creating new Huffman trees less frequently may not provide fast
23417651Speter     *     adaptation to changes in the input data statistics. (Take for
23517651Speter     *     example a binary file with poorly compressible code followed by
23617651Speter     *     a highly compressible string table.) Smaller buffer sizes give
23717651Speter     *     fast adaptation but have of course the overhead of transmitting
23817651Speter     *     trees more frequently.
23917651Speter     *   - I can't count above 4
24017651Speter     */
24117651Speter
24217651Speter    uInt last_lit;      /* running index in l_buf */
24317651Speter
24417651Speter    ushf *d_buf;
24517651Speter    /* Buffer for distances. To simplify the code, d_buf and l_buf have
24617651Speter     * the same number of elements. To use different lengths, an extra flag
24717651Speter     * array would be necessary.
24817651Speter     */
24917651Speter
25017651Speter    ulg opt_len;        /* bit length of current block with optimal trees */
25117651Speter    ulg static_len;     /* bit length of current block with static trees */
25217651Speter    uInt matches;       /* number of string matches in current block */
253230837Sdelphij    uInt insert;        /* bytes at end of window left to insert */
25417651Speter
255313796Sdelphij#ifdef ZLIB_DEBUG
25642468Speter    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
25742468Speter    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
25817651Speter#endif
25917651Speter
26017651Speter    ush bi_buf;
26117651Speter    /* Output buffer. bits are inserted starting at the bottom (least
26217651Speter     * significant bits).
26317651Speter     */
26417651Speter    int bi_valid;
26517651Speter    /* Number of valid bits in bi_buf.  All bits above the last valid bit
26617651Speter     * are always zero.
26717651Speter     */
26817651Speter
269205194Sdelphij    ulg high_water;
270205194Sdelphij    /* High water mark offset in window for initialized bytes -- bytes above
271205194Sdelphij     * this are set to zero in order to avoid memory check warnings when
272205194Sdelphij     * longest match routines access bytes past the input.  This is then
273205194Sdelphij     * updated to the new high water mark.
274205194Sdelphij     */
275205194Sdelphij
27617651Speter} FAR deflate_state;
27717651Speter
27817651Speter/* Output a byte on the stream.
27917651Speter * IN assertion: there is enough room in pending_buf.
28017651Speter */
281313796Sdelphij#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);}
28217651Speter
28317651Speter
28417651Speter#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
28517651Speter/* Minimum amount of lookahead, except at the end of the input file.
28617651Speter * See deflate.c for comments about the MIN_MATCH+1.
28717651Speter */
28817651Speter
28917651Speter#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
29017651Speter/* In order to simplify the code, particularly on 16 bit machines, match
29117651Speter * distances are limited to MAX_DIST instead of WSIZE.
29217651Speter */
29317651Speter
294205194Sdelphij#define WIN_INIT MAX_MATCH
295205194Sdelphij/* Number of bytes after end of data in window to initialize in order to avoid
296205194Sdelphij   memory checker errors from longest match routines */
297205194Sdelphij
29817651Speter        /* in trees.c */
299206905Sdelphijvoid ZLIB_INTERNAL _tr_init OF((deflate_state *s));
300206905Sdelphijint ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
301206905Sdelphijvoid ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
302206905Sdelphij                        ulg stored_len, int last));
303230837Sdelphijvoid ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
304206905Sdelphijvoid ZLIB_INTERNAL _tr_align OF((deflate_state *s));
305206905Sdelphijvoid ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
306206905Sdelphij                        ulg stored_len, int last));
30733904Ssteve
30833904Ssteve#define d_code(dist) \
30933904Ssteve   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
31033904Ssteve/* Mapping from a distance to a distance code. dist is the distance - 1 and
31133904Ssteve * must not have side effects. _dist_code[256] and _dist_code[257] are never
31233904Ssteve * used.
31333904Ssteve */
31433904Ssteve
315313796Sdelphij#ifndef ZLIB_DEBUG
31633904Ssteve/* Inline versions of _tr_tally for speed: */
31733904Ssteve
31833904Ssteve#if defined(GEN_TREES_H) || !defined(STDC)
319206905Sdelphij  extern uch ZLIB_INTERNAL _length_code[];
320206905Sdelphij  extern uch ZLIB_INTERNAL _dist_code[];
32133904Ssteve#else
322206905Sdelphij  extern const uch ZLIB_INTERNAL _length_code[];
323206905Sdelphij  extern const uch ZLIB_INTERNAL _dist_code[];
32417651Speter#endif
32533904Ssteve
32633904Ssteve# define _tr_tally_lit(s, c, flush) \
32733904Ssteve  { uch cc = (c); \
32833904Ssteve    s->d_buf[s->last_lit] = 0; \
32933904Ssteve    s->l_buf[s->last_lit++] = cc; \
33033904Ssteve    s->dyn_ltree[cc].Freq++; \
33133904Ssteve    flush = (s->last_lit == s->lit_bufsize-1); \
33233904Ssteve   }
33333904Ssteve# define _tr_tally_dist(s, distance, length, flush) \
334313796Sdelphij  { uch len = (uch)(length); \
335313796Sdelphij    ush dist = (ush)(distance); \
33633904Ssteve    s->d_buf[s->last_lit] = dist; \
33733904Ssteve    s->l_buf[s->last_lit++] = len; \
33833904Ssteve    dist--; \
33933904Ssteve    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
34033904Ssteve    s->dyn_dtree[d_code(dist)].Freq++; \
34133904Ssteve    flush = (s->last_lit == s->lit_bufsize-1); \
34233904Ssteve  }
34333904Ssteve#else
34433904Ssteve# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
34533904Ssteve# define _tr_tally_dist(s, distance, length, flush) \
346131377Stjr              flush = _tr_tally(s, distance, length)
34733904Ssteve#endif
34833904Ssteve
349131377Stjr#endif /* DEFLATE_H */
350