deflate.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. #ifndef DEFLATE_H_
  2. #define DEFLATE_H_
  3. /* deflate.h -- internal compression state
  4. * Copyright (C) 1995-2016 Jean-loup Gailly
  5. * For conditions of distribution and use, see copyright notice in zlib.h
  6. */
  7. /* WARNING: this file should *not* be used by applications. It is
  8. part of the implementation of the compression library and is
  9. subject to change. Applications should only use zlib.h.
  10. */
  11. #include "zutil.h"
  12. #include "zendian.h"
  13. #include "crc32.h"
  14. #ifdef S390_DFLTCC_DEFLATE
  15. # include "arch/s390/dfltcc_common.h"
  16. # define HAVE_ARCH_DEFLATE_STATE
  17. #endif
  18. /* define NO_GZIP when compiling if you want to disable gzip header and
  19. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  20. the crc code when it is not needed. For shared libraries, gzip encoding
  21. should be left enabled. */
  22. #ifndef NO_GZIP
  23. # define GZIP
  24. #endif
  25. /* define LIT_MEM to slightly increase the speed of deflate (order 1% to 2%) at
  26. the cost of a larger memory footprint */
  27. #ifndef NO_LIT_MEM
  28. # define LIT_MEM
  29. #endif
  30. /* ===========================================================================
  31. * Internal compression state.
  32. */
  33. #define LENGTH_CODES 29
  34. /* number of length codes, not counting the special END_BLOCK code */
  35. #define LITERALS 256
  36. /* number of literal bytes 0..255 */
  37. #define L_CODES (LITERALS+1+LENGTH_CODES)
  38. /* number of Literal or Length codes, including the END_BLOCK code */
  39. #define D_CODES 30
  40. /* number of distance codes */
  41. #define BL_CODES 19
  42. /* number of codes used to transfer the bit lengths */
  43. #define HEAP_SIZE (2*L_CODES+1)
  44. /* maximum heap size */
  45. #define BIT_BUF_SIZE 64
  46. /* size of bit buffer in bi_buf */
  47. #define END_BLOCK 256
  48. /* end of block literal code */
  49. #define INIT_STATE 1 /* zlib header -> BUSY_STATE */
  50. #ifdef GZIP
  51. # define GZIP_STATE 4 /* gzip header -> BUSY_STATE | EXTRA_STATE */
  52. # define EXTRA_STATE 5 /* gzip extra block -> NAME_STATE */
  53. # define NAME_STATE 6 /* gzip file name -> COMMENT_STATE */
  54. # define COMMENT_STATE 7 /* gzip comment -> HCRC_STATE */
  55. # define HCRC_STATE 8 /* gzip header CRC -> BUSY_STATE */
  56. #endif
  57. #define BUSY_STATE 2 /* deflate -> FINISH_STATE */
  58. #define FINISH_STATE 3 /* stream complete */
  59. #ifdef GZIP
  60. # define MAX_STATE HCRC_STATE
  61. #else
  62. # define MAX_STATE FINISH_STATE
  63. #endif
  64. /* Stream status */
  65. #define HASH_BITS 16u /* log2(HASH_SIZE) */
  66. #ifndef HASH_SIZE
  67. # define HASH_SIZE 65536u /* number of elements in hash table */
  68. #endif
  69. #define HASH_MASK (HASH_SIZE - 1u) /* HASH_SIZE-1 */
  70. /* Data structure describing a single value and its code string. */
  71. typedef struct ct_data_s {
  72. union {
  73. uint16_t freq; /* frequency count */
  74. uint16_t code; /* bit string */
  75. } fc;
  76. union {
  77. uint16_t dad; /* father node in Huffman tree */
  78. uint16_t len; /* length of bit string */
  79. } dl;
  80. } ct_data;
  81. #define Freq fc.freq
  82. #define Code fc.code
  83. #define Dad dl.dad
  84. #define Len dl.len
  85. typedef struct static_tree_desc_s static_tree_desc;
  86. typedef struct tree_desc_s {
  87. ct_data *dyn_tree; /* the dynamic tree */
  88. int max_code; /* largest code with non zero frequency */
  89. const static_tree_desc *stat_desc; /* the corresponding static tree */
  90. } tree_desc;
  91. typedef uint16_t Pos;
  92. /* A Pos is an index in the character window. We use short instead of int to
  93. * save space in the various tables.
  94. */
  95. /* Type definitions for hash callbacks */
  96. typedef struct internal_state deflate_state;
  97. typedef uint32_t (* update_hash_cb) (uint32_t h, uint32_t val);
  98. typedef void (* insert_string_cb) (deflate_state *const s, uint32_t str, uint32_t count);
  99. typedef Pos (* quick_insert_string_cb)(deflate_state *const s, uint32_t str);
  100. uint32_t update_hash (uint32_t h, uint32_t val);
  101. void insert_string (deflate_state *const s, uint32_t str, uint32_t count);
  102. Pos quick_insert_string (deflate_state *const s, uint32_t str);
  103. uint32_t update_hash_roll (uint32_t h, uint32_t val);
  104. void insert_string_roll (deflate_state *const s, uint32_t str, uint32_t count);
  105. Pos quick_insert_string_roll(deflate_state *const s, uint32_t str);
  106. /* Struct for memory allocation handling */
  107. typedef struct deflate_allocs_s {
  108. char *buf_start;
  109. free_func zfree;
  110. deflate_state *state;
  111. unsigned char *window;
  112. unsigned char *pending_buf;
  113. Pos *prev;
  114. Pos *head;
  115. } deflate_allocs;
  116. struct ALIGNED_(64) internal_state {
  117. PREFIX3(stream) *strm; /* pointer back to this zlib stream */
  118. unsigned char *pending_buf; /* output still pending */
  119. unsigned char *pending_out; /* next pending byte to output to the stream */
  120. uint32_t pending_buf_size; /* size of pending_buf */
  121. uint32_t pending; /* nb of bytes in the pending buffer */
  122. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  123. uint32_t gzindex; /* where in extra, name, or comment */
  124. PREFIX(gz_headerp) gzhead; /* gzip header information to write */
  125. int status; /* as the name implies */
  126. int last_flush; /* value of flush param for previous deflate call */
  127. int reproducible; /* Whether reproducible compression results are required. */
  128. int block_open;
  129. /* Whether or not a block is currently open for the QUICK deflation scheme.
  130. * This is set to 1 if there is an active block, or 0 if the block was just closed.
  131. */
  132. /* used by deflate.c: */
  133. unsigned int w_size; /* LZ77 window size (32K by default) */
  134. unsigned int w_bits; /* log2(w_size) (8..16) */
  135. unsigned int w_mask; /* w_size - 1 */
  136. unsigned int lookahead; /* number of valid bytes ahead in window */
  137. unsigned int high_water;
  138. /* High water mark offset in window for initialized bytes -- bytes above
  139. * this are set to zero in order to avoid memory check warnings when
  140. * longest match routines access bytes past the input. This is then
  141. * updated to the new high water mark.
  142. */
  143. unsigned int window_size;
  144. /* Actual size of window: 2*wSize, except when the user input buffer
  145. * is directly used as sliding window.
  146. */
  147. unsigned char *window;
  148. /* Sliding window. Input bytes are read into the second half of the window,
  149. * and move to the first half later to keep a dictionary of at least wSize
  150. * bytes. With this organization, matches are limited to a distance of
  151. * wSize-STD_MAX_MATCH bytes, but this ensures that IO is always
  152. * performed with a length multiple of the block size. Also, it limits
  153. * the window size to 64K, which is quite useful on MSDOS.
  154. * To do: use the user input buffer as sliding window.
  155. */
  156. Pos *prev;
  157. /* Link to older string with same hash index. To limit the size of this
  158. * array to 64K, this link is maintained only for the last 32K strings.
  159. * An index in this array is thus a window index modulo 32K.
  160. */
  161. Pos *head; /* Heads of the hash chains or 0. */
  162. uint32_t ins_h; /* hash index of string to be inserted */
  163. int block_start;
  164. /* Window position at the beginning of the current output block. Gets
  165. * negative when the window is moved backwards.
  166. */
  167. unsigned int match_length; /* length of best match */
  168. Pos prev_match; /* previous match */
  169. int match_available; /* set if previous match exists */
  170. unsigned int strstart; /* start of string to insert */
  171. unsigned int match_start; /* start of matching string */
  172. unsigned int prev_length;
  173. /* Length of the best match at previous step. Matches not greater than this
  174. * are discarded. This is used in the lazy match evaluation.
  175. */
  176. unsigned int max_chain_length;
  177. /* To speed up deflation, hash chains are never searched beyond this length.
  178. * A higher limit improves compression ratio but degrades the speed.
  179. */
  180. unsigned int max_lazy_match;
  181. /* Attempt to find a better match only when the current match is strictly smaller
  182. * than this value. This mechanism is used only for compression levels >= 4.
  183. */
  184. # define max_insert_length max_lazy_match
  185. /* Insert new strings in the hash table only if the match length is not
  186. * greater than this length. This saves time but degrades compression.
  187. * max_insert_length is used only for compression levels <= 3.
  188. */
  189. update_hash_cb update_hash;
  190. insert_string_cb insert_string;
  191. quick_insert_string_cb quick_insert_string;
  192. /* Hash function callbacks that can be configured depending on the deflate
  193. * algorithm being used */
  194. int level; /* compression level (1..9) */
  195. int strategy; /* favor or force Huffman coding*/
  196. unsigned int good_match;
  197. /* Use a faster search when the previous match is longer than this */
  198. int nice_match; /* Stop searching when current match exceeds this */
  199. struct crc32_fold_s ALIGNED_(16) crc_fold;
  200. /* used by trees.c: */
  201. /* Didn't use ct_data typedef below to suppress compiler warning */
  202. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  203. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  204. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  205. struct tree_desc_s l_desc; /* desc. for literal tree */
  206. struct tree_desc_s d_desc; /* desc. for distance tree */
  207. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  208. uint16_t bl_count[MAX_BITS+1];
  209. /* number of codes at each bit length for an optimal tree */
  210. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  211. int heap_len; /* number of elements in the heap */
  212. int heap_max; /* element of largest frequency */
  213. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  214. * The same heap array is used to build all trees.
  215. */
  216. unsigned char depth[2*L_CODES+1];
  217. /* Depth of each subtree used as tie breaker for trees of equal frequency
  218. */
  219. unsigned int lit_bufsize;
  220. /* Size of match buffer for literals/lengths. There are 4 reasons for
  221. * limiting lit_bufsize to 64K:
  222. * - frequencies can be kept in 16 bit counters
  223. * - if compression is not successful for the first block, all input
  224. * data is still in the window so we can still emit a stored block even
  225. * when input comes from standard input. (This can also be done for
  226. * all blocks if lit_bufsize is not greater than 32K.)
  227. * - if compression is not successful for a file smaller than 64K, we can
  228. * even emit a stored file instead of a stored block (saving 5 bytes).
  229. * This is applicable only for zip (not gzip or zlib).
  230. * - creating new Huffman trees less frequently may not provide fast
  231. * adaptation to changes in the input data statistics. (Take for
  232. * example a binary file with poorly compressible code followed by
  233. * a highly compressible string table.) Smaller buffer sizes give
  234. * fast adaptation but have of course the overhead of transmitting
  235. * trees more frequently.
  236. * - I can't count above 4
  237. */
  238. #ifdef LIT_MEM
  239. # define LIT_BUFS 5
  240. uint16_t *d_buf; /* buffer for distances */
  241. unsigned char *l_buf; /* buffer for literals/lengths */
  242. #else
  243. # define LIT_BUFS 4
  244. unsigned char *sym_buf; /* buffer for distances and literals/lengths */
  245. #endif
  246. unsigned int sym_next; /* running index in symbol buffer */
  247. unsigned int sym_end; /* symbol table full when sym_next reaches this */
  248. unsigned long opt_len; /* bit length of current block with optimal trees */
  249. unsigned long static_len; /* bit length of current block with static trees */
  250. unsigned int matches; /* number of string matches in current block */
  251. unsigned int insert; /* bytes at end of window left to insert */
  252. /* compressed_len and bits_sent are only used if ZLIB_DEBUG is defined */
  253. unsigned long compressed_len; /* total bit length of compressed file mod 2^32 */
  254. unsigned long bits_sent; /* bit length of compressed data sent mod 2^32 */
  255. deflate_allocs *alloc_bufs;
  256. #ifdef HAVE_ARCH_DEFLATE_STATE
  257. arch_deflate_state arch; /* architecture-specific extensions */
  258. #endif
  259. uint64_t bi_buf;
  260. /* Output buffer. bits are inserted starting at the bottom (least significant bits). */
  261. int32_t bi_valid;
  262. /* Number of valid bits in bi_buf. All bits above the last valid bit are always zero. */
  263. /* Reserved for future use and alignment purposes */
  264. int32_t reserved[11];
  265. };
  266. typedef enum {
  267. need_more, /* block not completed, need more input or more output */
  268. block_done, /* block flush performed */
  269. finish_started, /* finish started, need only more output at next deflate */
  270. finish_done /* finish done, accept no more input or output */
  271. } block_state;
  272. /* Output a byte on the stream.
  273. * IN assertion: there is enough room in pending_buf.
  274. */
  275. #define put_byte(s, c) { \
  276. s->pending_buf[s->pending++] = (unsigned char)(c); \
  277. }
  278. /* ===========================================================================
  279. * Output a short LSB first on the stream.
  280. * IN assertion: there is enough room in pending_buf.
  281. */
  282. static inline void put_short(deflate_state *s, uint16_t w) {
  283. #if BYTE_ORDER == BIG_ENDIAN
  284. w = ZSWAP16(w);
  285. #endif
  286. memcpy(&s->pending_buf[s->pending], &w, sizeof(w));
  287. s->pending += 2;
  288. }
  289. /* ===========================================================================
  290. * Output a short MSB first on the stream.
  291. * IN assertion: there is enough room in pending_buf.
  292. */
  293. static inline void put_short_msb(deflate_state *s, uint16_t w) {
  294. #if BYTE_ORDER == LITTLE_ENDIAN
  295. w = ZSWAP16(w);
  296. #endif
  297. memcpy(&s->pending_buf[s->pending], &w, sizeof(w));
  298. s->pending += 2;
  299. }
  300. /* ===========================================================================
  301. * Output a 32-bit unsigned int LSB first on the stream.
  302. * IN assertion: there is enough room in pending_buf.
  303. */
  304. static inline void put_uint32(deflate_state *s, uint32_t dw) {
  305. #if BYTE_ORDER == BIG_ENDIAN
  306. dw = ZSWAP32(dw);
  307. #endif
  308. memcpy(&s->pending_buf[s->pending], &dw, sizeof(dw));
  309. s->pending += 4;
  310. }
  311. /* ===========================================================================
  312. * Output a 32-bit unsigned int MSB first on the stream.
  313. * IN assertion: there is enough room in pending_buf.
  314. */
  315. static inline void put_uint32_msb(deflate_state *s, uint32_t dw) {
  316. #if BYTE_ORDER == LITTLE_ENDIAN
  317. dw = ZSWAP32(dw);
  318. #endif
  319. memcpy(&s->pending_buf[s->pending], &dw, sizeof(dw));
  320. s->pending += 4;
  321. }
  322. /* ===========================================================================
  323. * Output a 64-bit unsigned int LSB first on the stream.
  324. * IN assertion: there is enough room in pending_buf.
  325. */
  326. static inline void put_uint64(deflate_state *s, uint64_t lld) {
  327. #if BYTE_ORDER == BIG_ENDIAN
  328. lld = ZSWAP64(lld);
  329. #endif
  330. memcpy(&s->pending_buf[s->pending], &lld, sizeof(lld));
  331. s->pending += 8;
  332. }
  333. #define MIN_LOOKAHEAD (STD_MAX_MATCH + STD_MIN_MATCH + 1)
  334. /* Minimum amount of lookahead, except at the end of the input file.
  335. * See deflate.c for comments about the STD_MIN_MATCH+1.
  336. */
  337. #define MAX_DIST(s) ((s)->w_size - MIN_LOOKAHEAD)
  338. /* In order to simplify the code, particularly on 16 bit machines, match
  339. * distances are limited to MAX_DIST instead of WSIZE.
  340. */
  341. #define WIN_INIT STD_MAX_MATCH
  342. /* Number of bytes after end of data in window to initialize in order to avoid
  343. memory checker errors from longest match routines */
  344. void Z_INTERNAL PREFIX(fill_window)(deflate_state *s);
  345. void Z_INTERNAL slide_hash_c(deflate_state *s);
  346. /* in trees.c */
  347. void Z_INTERNAL zng_tr_init(deflate_state *s);
  348. void Z_INTERNAL zng_tr_flush_block(deflate_state *s, char *buf, uint32_t stored_len, int last);
  349. void Z_INTERNAL zng_tr_flush_bits(deflate_state *s);
  350. void Z_INTERNAL zng_tr_align(deflate_state *s);
  351. void Z_INTERNAL zng_tr_stored_block(deflate_state *s, char *buf, uint32_t stored_len, int last);
  352. uint16_t Z_INTERNAL PREFIX(bi_reverse)(unsigned code, int len);
  353. void Z_INTERNAL PREFIX(flush_pending)(PREFIX3(streamp) strm);
  354. #define d_code(dist) ((dist) < 256 ? zng_dist_code[dist] : zng_dist_code[256+((dist)>>7)])
  355. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  356. * must not have side effects. zng_dist_code[256] and zng_dist_code[257] are never
  357. * used.
  358. */
  359. /* Bit buffer and compress bits calculation debugging */
  360. #ifdef ZLIB_DEBUG
  361. # define cmpr_bits_add(s, len) s->compressed_len += (len)
  362. # define cmpr_bits_align(s) s->compressed_len = (s->compressed_len + 7) & ~7L
  363. # define sent_bits_add(s, bits) s->bits_sent += (bits)
  364. # define sent_bits_align(s) s->bits_sent = (s->bits_sent + 7) & ~7L
  365. #else
  366. # define cmpr_bits_add(s, len) Z_UNUSED(len)
  367. # define cmpr_bits_align(s)
  368. # define sent_bits_add(s, bits) Z_UNUSED(bits)
  369. # define sent_bits_align(s)
  370. #endif
  371. #endif /* DEFLATE_H_ */