You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1798 lines
56 KiB

  1. // Copyright (c) 2006, ComponentAce
  2. // http://www.componentace.com
  3. // All rights reserved.
  4. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  5. // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  6. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  7. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  8. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9. /*
  10. Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
  11. Redistribution and use in source and binary forms, with or without
  12. modification, are permitted provided that the following conditions are met:
  13. 1. Redistributions of source code must retain the above copyright notice,
  14. this list of conditions and the following disclaimer.
  15. 2. Redistributions in binary form must reproduce the above copyright
  16. notice, this list of conditions and the following disclaimer in
  17. the documentation and/or other materials provided with the distribution.
  18. 3. The names of the authors may not be used to endorse or promote products
  19. derived from this software without specific prior written permission.
  20. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  21. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  22. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  23. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  24. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  26. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  29. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. /*
  32. * This program is based on zlib-1.1.3, so all credit should go authors
  33. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  34. * and contributors of zlib.
  35. */
  36. using System;
  37. namespace zlib
  38. {
  39. sealed class Deflate
  40. {
  41. private const int MAX_MEM_LEVEL = 9;
  42. private const int Z_DEFAULT_COMPRESSION = - 1;
  43. private const int MAX_WBITS = 15; // 32K LZ77 window
  44. private const int DEF_MEM_LEVEL = 8;
  45. internal class Config
  46. {
  47. internal int good_length; // reduce lazy search above this match length
  48. internal int max_lazy; // do not perform lazy search above this match length
  49. internal int nice_length; // quit search above this match length
  50. internal int max_chain;
  51. internal int func;
  52. internal Config(int good_length, int max_lazy, int nice_length, int max_chain, int func)
  53. {
  54. this.good_length = good_length;
  55. this.max_lazy = max_lazy;
  56. this.nice_length = nice_length;
  57. this.max_chain = max_chain;
  58. this.func = func;
  59. }
  60. }
  61. private const int STORED = 0;
  62. private const int FAST = 1;
  63. private const int SLOW = 2;
  64. private static Config[] config_table;
  65. private static readonly System.String[] z_errmsg = new System.String[]{"need dictionary", "stream end", "", "file error", "stream error", "data error", "insufficient memory", "buffer error", "incompatible version", ""};
  66. // block not completed, need more input or more output
  67. private const int NeedMore = 0;
  68. // block flush performed
  69. private const int BlockDone = 1;
  70. // finish started, need only more output at next deflate
  71. private const int FinishStarted = 2;
  72. // finish done, accept no more input or output
  73. private const int FinishDone = 3;
  74. // preset dictionary flag in zlib header
  75. private const int PRESET_DICT = 0x20;
  76. private const int Z_FILTERED = 1;
  77. private const int Z_HUFFMAN_ONLY = 2;
  78. private const int Z_DEFAULT_STRATEGY = 0;
  79. private const int Z_NO_FLUSH = 0;
  80. private const int Z_PARTIAL_FLUSH = 1;
  81. private const int Z_SYNC_FLUSH = 2;
  82. private const int Z_FULL_FLUSH = 3;
  83. private const int Z_FINISH = 4;
  84. private const int Z_OK = 0;
  85. private const int Z_STREAM_END = 1;
  86. private const int Z_NEED_DICT = 2;
  87. private const int Z_ERRNO = - 1;
  88. private const int Z_STREAM_ERROR = - 2;
  89. private const int Z_DATA_ERROR = - 3;
  90. private const int Z_MEM_ERROR = - 4;
  91. private const int Z_BUF_ERROR = - 5;
  92. private const int Z_VERSION_ERROR = - 6;
  93. private const int INIT_STATE = 42;
  94. private const int BUSY_STATE = 113;
  95. private const int FINISH_STATE = 666;
  96. // The deflate compression method
  97. private const int Z_DEFLATED = 8;
  98. private const int STORED_BLOCK = 0;
  99. private const int STATIC_TREES = 1;
  100. private const int DYN_TREES = 2;
  101. // The three kinds of block type
  102. private const int Z_BINARY = 0;
  103. private const int Z_ASCII = 1;
  104. private const int Z_UNKNOWN = 2;
  105. private const int Buf_size = 8 * 2;
  106. // repeat previous bit length 3-6 times (2 bits of repeat count)
  107. private const int REP_3_6 = 16;
  108. // repeat a zero length 3-10 times (3 bits of repeat count)
  109. private const int REPZ_3_10 = 17;
  110. // repeat a zero length 11-138 times (7 bits of repeat count)
  111. private const int REPZ_11_138 = 18;
  112. private const int MIN_MATCH = 3;
  113. private const int MAX_MATCH = 258;
  114. private static readonly int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  115. private const int MAX_BITS = 15;
  116. private const int D_CODES = 30;
  117. private const int BL_CODES = 19;
  118. private const int LENGTH_CODES = 29;
  119. private const int LITERALS = 256;
  120. private static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES);
  121. private static readonly int HEAP_SIZE = (2 * L_CODES + 1);
  122. private const int END_BLOCK = 256;
  123. internal ZStream strm; // pointer back to this zlib stream
  124. internal int status; // as the name implies
  125. internal byte[] pending_buf; // output still pending
  126. internal int pending_buf_size; // size of pending_buf
  127. internal int pending_out; // next pending byte to output to the stream
  128. internal int pending; // nb of bytes in the pending buffer
  129. internal int noheader; // suppress zlib header and adler32
  130. internal byte data_type; // UNKNOWN, BINARY or ASCII
  131. internal byte method; // STORED (for zip only) or DEFLATED
  132. internal int last_flush; // value of flush param for previous deflate call
  133. internal int w_size; // LZ77 window size (32K by default)
  134. internal int w_bits; // log2(w_size) (8..16)
  135. internal int w_mask; // w_size - 1
  136. internal byte[] window;
  137. // Sliding window. Input bytes are read into the second half of the window,
  138. // and move to the first half later to keep a dictionary of at least wSize
  139. // bytes. With this organization, matches are limited to a distance of
  140. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  141. // performed with a length multiple of the block size. Also, it limits
  142. // the window size to 64K, which is quite useful on MSDOS.
  143. // To do: use the user input buffer as sliding window.
  144. internal int window_size;
  145. // Actual size of window: 2*wSize, except when the user input buffer
  146. // is directly used as sliding window.
  147. internal short[] prev;
  148. // Link to older string with same hash index. To limit the size of this
  149. // array to 64K, this link is maintained only for the last 32K strings.
  150. // An index in this array is thus a window index modulo 32K.
  151. internal short[] head; // Heads of the hash chains or NIL.
  152. internal int ins_h; // hash index of string to be inserted
  153. internal int hash_size; // number of elements in hash table
  154. internal int hash_bits; // log2(hash_size)
  155. internal int hash_mask; // hash_size-1
  156. // Number of bits by which ins_h must be shifted at each input
  157. // step. It must be such that after MIN_MATCH steps, the oldest
  158. // byte no longer takes part in the hash key, that is:
  159. // hash_shift * MIN_MATCH >= hash_bits
  160. internal int hash_shift;
  161. // Window position at the beginning of the current output block. Gets
  162. // negative when the window is moved backwards.
  163. internal int block_start;
  164. internal int match_length; // length of best match
  165. internal int prev_match; // previous match
  166. internal int match_available; // set if previous match exists
  167. internal int strstart; // start of string to insert
  168. internal int match_start; // start of matching string
  169. internal int lookahead; // number of valid bytes ahead in window
  170. // Length of the best match at previous step. Matches not greater than this
  171. // are discarded. This is used in the lazy match evaluation.
  172. internal int prev_length;
  173. // To speed up deflation, hash chains are never searched beyond this
  174. // length. A higher limit improves compression ratio but degrades the speed.
  175. internal int max_chain_length;
  176. // Attempt to find a better match only when the current match is strictly
  177. // smaller than this value. This mechanism is used only for compression
  178. // levels >= 4.
  179. internal int max_lazy_match;
  180. // Insert new strings in the hash table only if the match length is not
  181. // greater than this length. This saves time but degrades compression.
  182. // max_insert_length is used only for compression levels <= 3.
  183. internal int level; // compression level (1..9)
  184. internal int strategy; // favor or force Huffman coding
  185. // Use a faster search when the previous match is longer than this
  186. internal int good_match;
  187. // Stop searching when current match exceeds this
  188. internal int nice_match;
  189. internal short[] dyn_ltree; // literal and length tree
  190. internal short[] dyn_dtree; // distance tree
  191. internal short[] bl_tree; // Huffman tree for bit lengths
  192. internal Tree l_desc = new Tree(); // desc for literal tree
  193. internal Tree d_desc = new Tree(); // desc for distance tree
  194. internal Tree bl_desc = new Tree(); // desc for bit length tree
  195. // number of codes at each bit length for an optimal tree
  196. internal short[] bl_count = new short[MAX_BITS + 1];
  197. // heap used to build the Huffman trees
  198. internal int[] heap = new int[2 * L_CODES + 1];
  199. internal int heap_len; // number of elements in the heap
  200. internal int heap_max; // element of largest frequency
  201. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  202. // The same heap array is used to build all trees.
  203. // Depth of each subtree used as tie breaker for trees of equal frequency
  204. internal byte[] depth = new byte[2 * L_CODES + 1];
  205. internal int l_buf; // index for literals or lengths */
  206. // Size of match buffer for literals/lengths. There are 4 reasons for
  207. // limiting lit_bufsize to 64K:
  208. // - frequencies can be kept in 16 bit counters
  209. // - if compression is not successful for the first block, all input
  210. // data is still in the window so we can still emit a stored block even
  211. // when input comes from standard input. (This can also be done for
  212. // all blocks if lit_bufsize is not greater than 32K.)
  213. // - if compression is not successful for a file smaller than 64K, we can
  214. // even emit a stored file instead of a stored block (saving 5 bytes).
  215. // This is applicable only for zip (not gzip or zlib).
  216. // - creating new Huffman trees less frequently may not provide fast
  217. // adaptation to changes in the input data statistics. (Take for
  218. // example a binary file with poorly compressible code followed by
  219. // a highly compressible string table.) Smaller buffer sizes give
  220. // fast adaptation but have of course the overhead of transmitting
  221. // trees more frequently.
  222. // - I can't count above 4
  223. internal int lit_bufsize;
  224. internal int last_lit; // running index in l_buf
  225. // Buffer for distances. To simplify the code, d_buf and l_buf have
  226. // the same number of elements. To use different lengths, an extra flag
  227. // array would be necessary.
  228. internal int d_buf; // index of pendig_buf
  229. internal int opt_len; // bit length of current block with optimal trees
  230. internal int static_len; // bit length of current block with static trees
  231. internal int matches; // number of string matches in current block
  232. internal int last_eob_len; // bit length of EOB code for last block
  233. // Output buffer. bits are inserted starting at the bottom (least
  234. // significant bits).
  235. internal short bi_buf;
  236. // Number of valid bits in bi_buf. All bits above the last valid bit
  237. // are always zero.
  238. internal int bi_valid;
  239. internal Deflate()
  240. {
  241. dyn_ltree = new short[HEAP_SIZE * 2];
  242. dyn_dtree = new short[(2 * D_CODES + 1) * 2]; // distance tree
  243. bl_tree = new short[(2 * BL_CODES + 1) * 2]; // Huffman tree for bit lengths
  244. }
  245. internal void lm_init()
  246. {
  247. window_size = 2 * w_size;
  248. head[hash_size - 1] = 0;
  249. for (int i = 0; i < hash_size - 1; i++)
  250. {
  251. head[i] = 0;
  252. }
  253. // Set the default configuration parameters:
  254. max_lazy_match = Deflate.config_table[level].max_lazy;
  255. good_match = Deflate.config_table[level].good_length;
  256. nice_match = Deflate.config_table[level].nice_length;
  257. max_chain_length = Deflate.config_table[level].max_chain;
  258. strstart = 0;
  259. block_start = 0;
  260. lookahead = 0;
  261. match_length = prev_length = MIN_MATCH - 1;
  262. match_available = 0;
  263. ins_h = 0;
  264. }
  265. // Initialize the tree data structures for a new zlib stream.
  266. internal void tr_init()
  267. {
  268. l_desc.dyn_tree = dyn_ltree;
  269. l_desc.stat_desc = StaticTree.static_l_desc;
  270. d_desc.dyn_tree = dyn_dtree;
  271. d_desc.stat_desc = StaticTree.static_d_desc;
  272. bl_desc.dyn_tree = bl_tree;
  273. bl_desc.stat_desc = StaticTree.static_bl_desc;
  274. bi_buf = 0;
  275. bi_valid = 0;
  276. last_eob_len = 8; // enough lookahead for inflate
  277. // Initialize the first block of the first file:
  278. init_block();
  279. }
  280. internal void init_block()
  281. {
  282. // Initialize the trees.
  283. for (int i = 0; i < L_CODES; i++)
  284. dyn_ltree[i * 2] = 0;
  285. for (int i = 0; i < D_CODES; i++)
  286. dyn_dtree[i * 2] = 0;
  287. for (int i = 0; i < BL_CODES; i++)
  288. bl_tree[i * 2] = 0;
  289. dyn_ltree[END_BLOCK * 2] = 1;
  290. opt_len = static_len = 0;
  291. last_lit = matches = 0;
  292. }
  293. // Restore the heap property by moving down the tree starting at node k,
  294. // exchanging a node with the smallest of its two sons if necessary, stopping
  295. // when the heap property is re-established (each father smaller than its
  296. // two sons).
  297. internal void pqdownheap(short[] tree, int k)
  298. {
  299. int v = heap[k];
  300. int j = k << 1; // left son of k
  301. while (j <= heap_len)
  302. {
  303. // Set j to the smallest of the two sons:
  304. if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth))
  305. {
  306. j++;
  307. }
  308. // Exit if v is smaller than both sons
  309. if (smaller(tree, v, heap[j], depth))
  310. break;
  311. // Exchange v with the smallest son
  312. heap[k] = heap[j]; k = j;
  313. // And continue down the tree, setting j to the left son of k
  314. j <<= 1;
  315. }
  316. heap[k] = v;
  317. }
  318. internal static bool smaller(short[] tree, int n, int m, byte[] depth)
  319. {
  320. return (tree[n * 2] < tree[m * 2] || (tree[n * 2] == tree[m * 2] && depth[n] <= depth[m]));
  321. }
  322. // Scan a literal or distance tree to determine the frequencies of the codes
  323. // in the bit length tree.
  324. internal void scan_tree(short[] tree, int max_code)
  325. {
  326. int n; // iterates over all tree elements
  327. int prevlen = - 1; // last emitted length
  328. int curlen; // length of current code
  329. int nextlen = tree[0 * 2 + 1]; // length of next code
  330. int count = 0; // repeat count of the current code
  331. int max_count = 7; // max repeat count
  332. int min_count = 4; // min repeat count
  333. if (nextlen == 0)
  334. {
  335. max_count = 138; min_count = 3;
  336. }
  337. tree[(max_code + 1) * 2 + 1] = (short) SupportClass.Identity(0xffff); // guard
  338. for (n = 0; n <= max_code; n++)
  339. {
  340. curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1];
  341. if (++count < max_count && curlen == nextlen)
  342. {
  343. continue;
  344. }
  345. else if (count < min_count)
  346. {
  347. bl_tree[curlen * 2] = (short) (bl_tree[curlen * 2] + count);
  348. }
  349. else if (curlen != 0)
  350. {
  351. if (curlen != prevlen)
  352. bl_tree[curlen * 2]++;
  353. bl_tree[REP_3_6 * 2]++;
  354. }
  355. else if (count <= 10)
  356. {
  357. bl_tree[REPZ_3_10 * 2]++;
  358. }
  359. else
  360. {
  361. bl_tree[REPZ_11_138 * 2]++;
  362. }
  363. count = 0; prevlen = curlen;
  364. if (nextlen == 0)
  365. {
  366. max_count = 138; min_count = 3;
  367. }
  368. else if (curlen == nextlen)
  369. {
  370. max_count = 6; min_count = 3;
  371. }
  372. else
  373. {
  374. max_count = 7; min_count = 4;
  375. }
  376. }
  377. }
  378. // Construct the Huffman tree for the bit lengths and return the index in
  379. // bl_order of the last bit length code to send.
  380. internal int build_bl_tree()
  381. {
  382. int max_blindex; // index of last bit length code of non zero freq
  383. // Determine the bit length frequencies for literal and distance trees
  384. scan_tree(dyn_ltree, l_desc.max_code);
  385. scan_tree(dyn_dtree, d_desc.max_code);
  386. // Build the bit length tree:
  387. bl_desc.build_tree(this);
  388. // opt_len now includes the length of the tree representations, except
  389. // the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  390. // Determine the number of bit length codes to send. The pkzip format
  391. // requires that at least 4 bit length codes be sent. (appnote.txt says
  392. // 3 but the actual value used is 4.)
  393. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--)
  394. {
  395. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] != 0)
  396. break;
  397. }
  398. // Update opt_len to include the bit length tree and counts
  399. opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  400. return max_blindex;
  401. }
  402. // Send the header for a block using dynamic Huffman trees: the counts, the
  403. // lengths of the bit length codes, the literal tree and the distance tree.
  404. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  405. internal void send_all_trees(int lcodes, int dcodes, int blcodes)
  406. {
  407. int rank; // index in bl_order
  408. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  409. send_bits(dcodes - 1, 5);
  410. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  411. for (rank = 0; rank < blcodes; rank++)
  412. {
  413. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  414. }
  415. send_tree(dyn_ltree, lcodes - 1); // literal tree
  416. send_tree(dyn_dtree, dcodes - 1); // distance tree
  417. }
  418. // Send a literal or distance tree in compressed form, using the codes in
  419. // bl_tree.
  420. internal void send_tree(short[] tree, int max_code)
  421. {
  422. int n; // iterates over all tree elements
  423. int prevlen = - 1; // last emitted length
  424. int curlen; // length of current code
  425. int nextlen = tree[0 * 2 + 1]; // length of next code
  426. int count = 0; // repeat count of the current code
  427. int max_count = 7; // max repeat count
  428. int min_count = 4; // min repeat count
  429. if (nextlen == 0)
  430. {
  431. max_count = 138; min_count = 3;
  432. }
  433. for (n = 0; n <= max_code; n++)
  434. {
  435. curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1];
  436. if (++count < max_count && curlen == nextlen)
  437. {
  438. continue;
  439. }
  440. else if (count < min_count)
  441. {
  442. do
  443. {
  444. send_code(curlen, bl_tree);
  445. }
  446. while (--count != 0);
  447. }
  448. else if (curlen != 0)
  449. {
  450. if (curlen != prevlen)
  451. {
  452. send_code(curlen, bl_tree); count--;
  453. }
  454. send_code(REP_3_6, bl_tree);
  455. send_bits(count - 3, 2);
  456. }
  457. else if (count <= 10)
  458. {
  459. send_code(REPZ_3_10, bl_tree);
  460. send_bits(count - 3, 3);
  461. }
  462. else
  463. {
  464. send_code(REPZ_11_138, bl_tree);
  465. send_bits(count - 11, 7);
  466. }
  467. count = 0; prevlen = curlen;
  468. if (nextlen == 0)
  469. {
  470. max_count = 138; min_count = 3;
  471. }
  472. else if (curlen == nextlen)
  473. {
  474. max_count = 6; min_count = 3;
  475. }
  476. else
  477. {
  478. max_count = 7; min_count = 4;
  479. }
  480. }
  481. }
  482. // Output a byte on the stream.
  483. // IN assertion: there is enough room in pending_buf.
  484. internal void put_byte(byte[] p, int start, int len)
  485. {
  486. Array.Copy(p, start, pending_buf, pending, len);
  487. pending += len;
  488. }
  489. internal void put_byte(byte c)
  490. {
  491. pending_buf[pending++] = c;
  492. }
  493. internal void put_short(int w)
  494. {
  495. put_byte((byte) (w));
  496. put_byte((byte) (SupportClass.URShift(w, 8)));
  497. }
  498. internal void putShortMSB(int b)
  499. {
  500. put_byte((byte) (b >> 8));
  501. put_byte((byte) (b));
  502. }
  503. internal void send_code(int c, short[] tree)
  504. {
  505. send_bits((tree[c * 2] & 0xffff), (tree[c * 2 + 1] & 0xffff));
  506. }
  507. internal void send_bits(int value_Renamed, int length)
  508. {
  509. int len = length;
  510. if (bi_valid > (int) Buf_size - len)
  511. {
  512. int val = value_Renamed;
  513. // bi_buf |= (val << bi_valid);
  514. bi_buf = (short) ((ushort) bi_buf | (ushort) (((val << bi_valid) & 0xffff)));
  515. put_short(bi_buf);
  516. bi_buf = (short) (SupportClass.URShift(val, (Buf_size - bi_valid)));
  517. bi_valid += len - Buf_size;
  518. }
  519. else
  520. {
  521. // bi_buf |= (value) << bi_valid;
  522. bi_buf = (short)((ushort)bi_buf | (ushort)((((value_Renamed) << bi_valid) & 0xffff)));
  523. bi_valid += len;
  524. }
  525. }
  526. // Send one empty static block to give enough lookahead for inflate.
  527. // This takes 10 bits, of which 7 may remain in the bit buffer.
  528. // The current inflate code requires 9 bits of lookahead. If the
  529. // last two codes for the previous block (real code plus EOB) were coded
  530. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  531. // the last real code. In this case we send two empty static blocks instead
  532. // of one. (There are no problems if the previous block is stored or fixed.)
  533. // To simplify the code, we assume the worst case of last real code encoded
  534. // on one bit only.
  535. internal void _tr_align()
  536. {
  537. send_bits(STATIC_TREES << 1, 3);
  538. send_code(END_BLOCK, StaticTree.static_ltree);
  539. bi_flush();
  540. // Of the 10 bits for the empty block, we have already sent
  541. // (10 - bi_valid) bits. The lookahead for the last real code (before
  542. // the EOB of the previous block) was thus at least one plus the length
  543. // of the EOB plus what we have just sent of the empty static block.
  544. if (1 + last_eob_len + 10 - bi_valid < 9)
  545. {
  546. send_bits(STATIC_TREES << 1, 3);
  547. send_code(END_BLOCK, StaticTree.static_ltree);
  548. bi_flush();
  549. }
  550. last_eob_len = 7;
  551. }
  552. // Save the match info and tally the frequency counts. Return true if
  553. // the current block must be flushed.
  554. internal bool _tr_tally(int dist, int lc)
  555. {
  556. pending_buf[d_buf + last_lit * 2] = (byte) (SupportClass.URShift(dist, 8));
  557. pending_buf[d_buf + last_lit * 2 + 1] = (byte) dist;
  558. pending_buf[l_buf + last_lit] = (byte) lc; last_lit++;
  559. if (dist == 0)
  560. {
  561. // lc is the unmatched char
  562. dyn_ltree[lc * 2]++;
  563. }
  564. else
  565. {
  566. matches++;
  567. // Here, lc is the match length - MIN_MATCH
  568. dist--; // dist = match distance - 1
  569. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  570. dyn_dtree[Tree.d_code(dist) * 2]++;
  571. }
  572. if ((last_lit & 0x1fff) == 0 && level > 2)
  573. {
  574. // Compute an upper bound for the compressed length
  575. int out_length = last_lit * 8;
  576. int in_length = strstart - block_start;
  577. int dcode;
  578. for (dcode = 0; dcode < D_CODES; dcode++)
  579. {
  580. out_length = (int) (out_length + (int) dyn_dtree[dcode * 2] * (5L + Tree.extra_dbits[dcode]));
  581. }
  582. out_length = SupportClass.URShift(out_length, 3);
  583. if ((matches < (last_lit / 2)) && out_length < in_length / 2)
  584. return true;
  585. }
  586. return (last_lit == lit_bufsize - 1);
  587. // We avoid equality with lit_bufsize because of wraparound at 64K
  588. // on 16 bit machines and because stored blocks are restricted to
  589. // 64K-1 bytes.
  590. }
  591. // Send the block data compressed using the given Huffman trees
  592. internal void compress_block(short[] ltree, short[] dtree)
  593. {
  594. int dist; // distance of matched string
  595. int lc; // match length or unmatched char (if dist == 0)
  596. int lx = 0; // running index in l_buf
  597. int code; // the code to send
  598. int extra; // number of extra bits to send
  599. if (last_lit != 0)
  600. {
  601. do
  602. {
  603. dist = ((pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (pending_buf[d_buf + lx * 2 + 1] & 0xff);
  604. lc = (pending_buf[l_buf + lx]) & 0xff; lx++;
  605. if (dist == 0)
  606. {
  607. send_code(lc, ltree); // send a literal byte
  608. }
  609. else
  610. {
  611. // Here, lc is the match length - MIN_MATCH
  612. code = Tree._length_code[lc];
  613. send_code(code + LITERALS + 1, ltree); // send the length code
  614. extra = Tree.extra_lbits[code];
  615. if (extra != 0)
  616. {
  617. lc -= Tree.base_length[code];
  618. send_bits(lc, extra); // send the extra length bits
  619. }
  620. dist--; // dist is now the match distance - 1
  621. code = Tree.d_code(dist);
  622. send_code(code, dtree); // send the distance code
  623. extra = Tree.extra_dbits[code];
  624. if (extra != 0)
  625. {
  626. dist -= Tree.base_dist[code];
  627. send_bits(dist, extra); // send the extra distance bits
  628. }
  629. } // literal or match pair ?
  630. // Check that the overlay between pending_buf and d_buf+l_buf is ok:
  631. }
  632. while (lx < last_lit);
  633. }
  634. send_code(END_BLOCK, ltree);
  635. last_eob_len = ltree[END_BLOCK * 2 + 1];
  636. }
  637. // Set the data type to ASCII or BINARY, using a crude approximation:
  638. // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  639. // IN assertion: the fields freq of dyn_ltree are set and the total of all
  640. // frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  641. internal void set_data_type()
  642. {
  643. int n = 0;
  644. int ascii_freq = 0;
  645. int bin_freq = 0;
  646. while (n < 7)
  647. {
  648. bin_freq += dyn_ltree[n * 2]; n++;
  649. }
  650. while (n < 128)
  651. {
  652. ascii_freq += dyn_ltree[n * 2]; n++;
  653. }
  654. while (n < LITERALS)
  655. {
  656. bin_freq += dyn_ltree[n * 2]; n++;
  657. }
  658. data_type = (byte) (bin_freq > (SupportClass.URShift(ascii_freq, 2))?Z_BINARY:Z_ASCII);
  659. }
  660. // Flush the bit buffer, keeping at most 7 bits in it.
  661. internal void bi_flush()
  662. {
  663. if (bi_valid == 16)
  664. {
  665. put_short(bi_buf);
  666. bi_buf = 0;
  667. bi_valid = 0;
  668. }
  669. else if (bi_valid >= 8)
  670. {
  671. put_byte((byte) bi_buf);
  672. bi_buf = (short) (SupportClass.URShift(bi_buf, 8));
  673. bi_valid -= 8;
  674. }
  675. }
  676. // Flush the bit buffer and align the output on a byte boundary
  677. internal void bi_windup()
  678. {
  679. if (bi_valid > 8)
  680. {
  681. put_short(bi_buf);
  682. }
  683. else if (bi_valid > 0)
  684. {
  685. put_byte((byte) bi_buf);
  686. }
  687. bi_buf = 0;
  688. bi_valid = 0;
  689. }
  690. // Copy a stored block, storing first the length and its
  691. // one's complement if requested.
  692. internal void copy_block(int buf, int len, bool header)
  693. {
  694. bi_windup(); // align on byte boundary
  695. last_eob_len = 8; // enough lookahead for inflate
  696. if (header)
  697. {
  698. put_short((short) len);
  699. put_short((short) ~ len);
  700. }
  701. // while(len--!=0) {
  702. // put_byte(window[buf+index]);
  703. // index++;
  704. // }
  705. put_byte(window, buf, len);
  706. }
  707. internal void flush_block_only(bool eof)
  708. {
  709. _tr_flush_block(block_start >= 0?block_start:- 1, strstart - block_start, eof);
  710. block_start = strstart;
  711. strm.flush_pending();
  712. }
  713. // Copy without compression as much as possible from the input stream, return
  714. // the current block state.
  715. // This function does not insert new strings in the dictionary since
  716. // uncompressible data is probably not useful. This function is used
  717. // only for the level=0 compression option.
  718. // NOTE: this function should be optimized to avoid extra copying from
  719. // window to pending_buf.
  720. internal int deflate_stored(int flush)
  721. {
  722. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  723. // to pending_buf_size, and each stored block has a 5 byte header:
  724. int max_block_size = 0xffff;
  725. int max_start;
  726. if (max_block_size > pending_buf_size - 5)
  727. {
  728. max_block_size = pending_buf_size - 5;
  729. }
  730. // Copy as much as possible from input to output:
  731. while (true)
  732. {
  733. // Fill the window as much as possible:
  734. if (lookahead <= 1)
  735. {
  736. fill_window();
  737. if (lookahead == 0 && flush == Z_NO_FLUSH)
  738. return NeedMore;
  739. if (lookahead == 0)
  740. break; // flush the current block
  741. }
  742. strstart += lookahead;
  743. lookahead = 0;
  744. // Emit a stored block if pending_buf will be full:
  745. max_start = block_start + max_block_size;
  746. if (strstart == 0 || strstart >= max_start)
  747. {
  748. // strstart == 0 is possible when wraparound on 16-bit machine
  749. lookahead = (int) (strstart - max_start);
  750. strstart = (int) max_start;
  751. flush_block_only(false);
  752. if (strm.avail_out == 0)
  753. return NeedMore;
  754. }
  755. // Flush if we may have to slide, otherwise block_start may become
  756. // negative and the data will be gone:
  757. if (strstart - block_start >= w_size - MIN_LOOKAHEAD)
  758. {
  759. flush_block_only(false);
  760. if (strm.avail_out == 0)
  761. return NeedMore;
  762. }
  763. }
  764. flush_block_only(flush == Z_FINISH);
  765. if (strm.avail_out == 0)
  766. return (flush == Z_FINISH)?FinishStarted:NeedMore;
  767. return flush == Z_FINISH?FinishDone:BlockDone;
  768. }
  769. // Send a stored block
  770. internal void _tr_stored_block(int buf, int stored_len, bool eof)
  771. {
  772. send_bits((STORED_BLOCK << 1) + (eof?1:0), 3); // send block type
  773. copy_block(buf, stored_len, true); // with header
  774. }
  775. // Determine the best encoding for the current block: dynamic trees, static
  776. // trees or store, and output the encoded block to the zip file.
  777. internal void _tr_flush_block(int buf, int stored_len, bool eof)
  778. {
  779. int opt_lenb, static_lenb; // opt_len and static_len in bytes
  780. int max_blindex = 0; // index of last bit length code of non zero freq
  781. // Build the Huffman trees unless a stored block is forced
  782. if (level > 0)
  783. {
  784. // Check if the file is ascii or binary
  785. if (data_type == Z_UNKNOWN)
  786. set_data_type();
  787. // Construct the literal and distance trees
  788. l_desc.build_tree(this);
  789. d_desc.build_tree(this);
  790. // At this point, opt_len and static_len are the total bit lengths of
  791. // the compressed block data, excluding the tree representations.
  792. // Build the bit length tree for the above two trees, and get the index
  793. // in bl_order of the last bit length code to send.
  794. max_blindex = build_bl_tree();
  795. // Determine the best encoding. Compute first the block length in bytes
  796. opt_lenb = SupportClass.URShift((opt_len + 3 + 7), 3);
  797. static_lenb = SupportClass.URShift((static_len + 3 + 7), 3);
  798. if (static_lenb <= opt_lenb)
  799. opt_lenb = static_lenb;
  800. }
  801. else
  802. {
  803. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  804. }
  805. if (stored_len + 4 <= opt_lenb && buf != - 1)
  806. {
  807. // 4: two words for the lengths
  808. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  809. // Otherwise we can't have processed more than WSIZE input bytes since
  810. // the last block flush, because compression would have been
  811. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  812. // transform a block into a stored block.
  813. _tr_stored_block(buf, stored_len, eof);
  814. }
  815. else if (static_lenb == opt_lenb)
  816. {
  817. send_bits((STATIC_TREES << 1) + (eof?1:0), 3);
  818. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  819. }
  820. else
  821. {
  822. send_bits((DYN_TREES << 1) + (eof?1:0), 3);
  823. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  824. compress_block(dyn_ltree, dyn_dtree);
  825. }
  826. // The above check is made mod 2^32, for files larger than 512 MB
  827. // and uLong implemented on 32 bits.
  828. init_block();
  829. if (eof)
  830. {
  831. bi_windup();
  832. }
  833. }
  834. // Fill the window when the lookahead becomes insufficient.
  835. // Updates strstart and lookahead.
  836. //
  837. // IN assertion: lookahead < MIN_LOOKAHEAD
  838. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  839. // At least one byte has been read, or avail_in == 0; reads are
  840. // performed for at least two bytes (required for the zip translate_eol
  841. // option -- not supported here).
  842. internal void fill_window()
  843. {
  844. int n, m;
  845. int p;
  846. int more; // Amount of free space at the end of the window.
  847. do
  848. {
  849. more = (window_size - lookahead - strstart);
  850. // Deal with !@#$% 64K limit:
  851. if (more == 0 && strstart == 0 && lookahead == 0)
  852. {
  853. more = w_size;
  854. }
  855. else if (more == - 1)
  856. {
  857. // Very unlikely, but possible on 16 bit machine if strstart == 0
  858. // and lookahead == 1 (input done one byte at time)
  859. more--;
  860. // If the window is almost full and there is insufficient lookahead,
  861. // move the upper half to the lower one to make room in the upper half.
  862. }
  863. else if (strstart >= w_size + w_size - MIN_LOOKAHEAD)
  864. {
  865. Array.Copy(window, w_size, window, 0, w_size);
  866. match_start -= w_size;
  867. strstart -= w_size; // we now have strstart >= MAX_DIST
  868. block_start -= w_size;
  869. // Slide the hash table (could be avoided with 32 bit values
  870. // at the expense of memory usage). We slide even when level == 0
  871. // to keep the hash table consistent if we switch back to level > 0
  872. // later. (Using level 0 permanently is not an optimal usage of
  873. // zlib, so we don't care about this pathological case.)
  874. n = hash_size;
  875. p = n;
  876. do
  877. {
  878. m = (head[--p] & 0xffff);
  879. head[p] = (short)(m >= w_size?(m - w_size):0);
  880. //head[p] = (m >= w_size?(short) (m - w_size):0);
  881. }
  882. while (--n != 0);
  883. n = w_size;
  884. p = n;
  885. do
  886. {
  887. m = (prev[--p] & 0xffff);
  888. prev[p] = (short)(m >= w_size?(m - w_size):0);
  889. //prev[p] = (m >= w_size?(short) (m - w_size):0);
  890. // If n is not on any hash chain, prev[n] is garbage but
  891. // its value will never be used.
  892. }
  893. while (--n != 0);
  894. more += w_size;
  895. }
  896. if (strm.avail_in == 0)
  897. return ;
  898. // If there was no sliding:
  899. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  900. // more == window_size - lookahead - strstart
  901. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  902. // => more >= window_size - 2*WSIZE + 2
  903. // In the BIG_MEM or MMAP case (not yet supported),
  904. // window_size == input_size + MIN_LOOKAHEAD &&
  905. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  906. // Otherwise, window_size == 2*WSIZE so more >= 2.
  907. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  908. n = strm.read_buf(window, strstart + lookahead, more);
  909. lookahead += n;
  910. // Initialize the hash value now that we have some input:
  911. if (lookahead >= MIN_MATCH)
  912. {
  913. ins_h = window[strstart] & 0xff;
  914. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  915. }
  916. // If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  917. // but this is not important since only literal bytes will be emitted.
  918. }
  919. while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0);
  920. }
  921. // Compress as much as possible from the input stream, return the current
  922. // block state.
  923. // This function does not perform lazy evaluation of matches and inserts
  924. // new strings in the dictionary only for unmatched strings or for short
  925. // matches. It is used only for the fast compression options.
  926. internal int deflate_fast(int flush)
  927. {
  928. // short hash_head = 0; // head of the hash chain
  929. int hash_head = 0; // head of the hash chain
  930. bool bflush; // set if current block must be flushed
  931. while (true)
  932. {
  933. // Make sure that we always have enough lookahead, except
  934. // at the end of the input file. We need MAX_MATCH bytes
  935. // for the next match, plus MIN_MATCH bytes to insert the
  936. // string following the next match.
  937. if (lookahead < MIN_LOOKAHEAD)
  938. {
  939. fill_window();
  940. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH)
  941. {
  942. return NeedMore;
  943. }
  944. if (lookahead == 0)
  945. break; // flush the current block
  946. }
  947. // Insert the string window[strstart .. strstart+2] in the
  948. // dictionary, and set hash_head to the head of the hash chain:
  949. if (lookahead >= MIN_MATCH)
  950. {
  951. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  952. // prev[strstart&w_mask]=hash_head=head[ins_h];
  953. hash_head = (head[ins_h] & 0xffff);
  954. prev[strstart & w_mask] = head[ins_h];
  955. head[ins_h] = (short) strstart;
  956. }
  957. // Find the longest match, discarding those <= prev_length.
  958. // At this point we have always match_length < MIN_MATCH
  959. if (hash_head != 0L && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD)
  960. {
  961. // To simplify the code, we prevent matches with the string
  962. // of window index 0 (in particular we have to avoid a match
  963. // of the string with itself at the start of the input file).
  964. if (strategy != Z_HUFFMAN_ONLY)
  965. {
  966. match_length = longest_match(hash_head);
  967. }
  968. // longest_match() sets match_start
  969. }
  970. if (match_length >= MIN_MATCH)
  971. {
  972. // check_match(strstart, match_start, match_length);
  973. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  974. lookahead -= match_length;
  975. // Insert new strings in the hash table only if the match length
  976. // is not too large. This saves time but degrades compression.
  977. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH)
  978. {
  979. match_length--; // string at strstart already in hash table
  980. do
  981. {
  982. strstart++;
  983. ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  984. // prev[strstart&w_mask]=hash_head=head[ins_h];
  985. hash_head = (head[ins_h] & 0xffff);
  986. prev[strstart & w_mask] = head[ins_h];
  987. head[ins_h] = (short) strstart;
  988. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  989. // always MIN_MATCH bytes ahead.
  990. }
  991. while (--match_length != 0);
  992. strstart++;
  993. }
  994. else
  995. {
  996. strstart += match_length;
  997. match_length = 0;
  998. ins_h = window[strstart] & 0xff;
  999. ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
  1000. // If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1001. // matter since it will be recomputed at next deflate call.
  1002. }
  1003. }
  1004. else
  1005. {
  1006. // No match, output a literal byte
  1007. bflush = _tr_tally(0, window[strstart] & 0xff);
  1008. lookahead--;
  1009. strstart++;
  1010. }
  1011. if (bflush)
  1012. {
  1013. flush_block_only(false);
  1014. if (strm.avail_out == 0)
  1015. return NeedMore;
  1016. }
  1017. }
  1018. flush_block_only(flush == Z_FINISH);
  1019. if (strm.avail_out == 0)
  1020. {
  1021. if (flush == Z_FINISH)
  1022. return FinishStarted;
  1023. else
  1024. return NeedMore;
  1025. }
  1026. return flush == Z_FINISH?FinishDone:BlockDone;
  1027. }
  1028. // Same as above, but achieves better compression. We use a lazy
  1029. // evaluation for matches: a match is finally adopted only if there is
  1030. // no better match at the next window position.
  1031. internal int deflate_slow(int flush)
  1032. {
  1033. // short hash_head = 0; // head of hash chain
  1034. int hash_head = 0; // head of hash chain
  1035. bool bflush; // set if current block must be flushed
  1036. // Process the input block.
  1037. while (true)
  1038. {
  1039. // Make sure that we always have enough lookahead, except
  1040. // at the end of the input file. We need MAX_MATCH bytes
  1041. // for the next match, plus MIN_MATCH bytes to insert the
  1042. // string following the next match.
  1043. if (lookahead < MIN_LOOKAHEAD)
  1044. {
  1045. fill_window();
  1046. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH)
  1047. {
  1048. return NeedMore;
  1049. }
  1050. if (lookahead == 0)
  1051. break; // flush the current block
  1052. }
  1053. // Insert the string window[strstart .. strstart+2] in the
  1054. // dictionary, and set hash_head to the head of the hash chain:
  1055. if (lookahead >= MIN_MATCH)
  1056. {
  1057. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1058. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1059. hash_head = (head[ins_h] & 0xffff);
  1060. prev[strstart & w_mask] = head[ins_h];
  1061. head[ins_h] = (short) strstart;
  1062. }
  1063. // Find the longest match, discarding those <= prev_length.
  1064. prev_length = match_length; prev_match = match_start;
  1065. match_length = MIN_MATCH - 1;
  1066. if (hash_head != 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD)
  1067. {
  1068. // To simplify the code, we prevent matches with the string
  1069. // of window index 0 (in particular we have to avoid a match
  1070. // of the string with itself at the start of the input file).
  1071. if (strategy != Z_HUFFMAN_ONLY)
  1072. {
  1073. match_length = longest_match(hash_head);
  1074. }
  1075. // longest_match() sets match_start
  1076. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096)))
  1077. {
  1078. // If prev_match is also MIN_MATCH, match_start is garbage
  1079. // but we will ignore the current match anyway.
  1080. match_length = MIN_MATCH - 1;
  1081. }
  1082. }
  1083. // If there was a match at the previous step and the current
  1084. // match is not better, output the previous match:
  1085. if (prev_length >= MIN_MATCH && match_length <= prev_length)
  1086. {
  1087. int max_insert = strstart + lookahead - MIN_MATCH;
  1088. // Do not insert strings in hash table beyond this.
  1089. // check_match(strstart-1, prev_match, prev_length);
  1090. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  1091. // Insert in hash table all strings up to the end of the match.
  1092. // strstart-1 and strstart are already inserted. If there is not
  1093. // enough lookahead, the last two strings are not inserted in
  1094. // the hash table.
  1095. lookahead -= (prev_length - 1);
  1096. prev_length -= 2;
  1097. do
  1098. {
  1099. if (++strstart <= max_insert)
  1100. {
  1101. ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1102. //prev[strstart&w_mask]=hash_head=head[ins_h];
  1103. hash_head = (head[ins_h] & 0xffff);
  1104. prev[strstart & w_mask] = head[ins_h];
  1105. head[ins_h] = (short) strstart;
  1106. }
  1107. }
  1108. while (--prev_length != 0);
  1109. match_available = 0;
  1110. match_length = MIN_MATCH - 1;
  1111. strstart++;
  1112. if (bflush)
  1113. {
  1114. flush_block_only(false);
  1115. if (strm.avail_out == 0)
  1116. return NeedMore;
  1117. }
  1118. }
  1119. else if (match_available != 0)
  1120. {
  1121. // If there was no match at the previous position, output a
  1122. // single literal. If there was a match but the current match
  1123. // is longer, truncate the previous match to a single literal.
  1124. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  1125. if (bflush)
  1126. {
  1127. flush_block_only(false);
  1128. }
  1129. strstart++;
  1130. lookahead--;
  1131. if (strm.avail_out == 0)
  1132. return NeedMore;
  1133. }
  1134. else
  1135. {
  1136. // There is no previous match to compare with, wait for
  1137. // the next step to decide.
  1138. match_available = 1;
  1139. strstart++;
  1140. lookahead--;
  1141. }
  1142. }
  1143. if (match_available != 0)
  1144. {
  1145. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  1146. match_available = 0;
  1147. }
  1148. flush_block_only(flush == Z_FINISH);
  1149. if (strm.avail_out == 0)
  1150. {
  1151. if (flush == Z_FINISH)
  1152. return FinishStarted;
  1153. else
  1154. return NeedMore;
  1155. }
  1156. return flush == Z_FINISH?FinishDone:BlockDone;
  1157. }
  1158. internal int longest_match(int cur_match)
  1159. {
  1160. int chain_length = max_chain_length; // max hash chain length
  1161. int scan = strstart; // current string
  1162. int match; // matched string
  1163. int len; // length of current match
  1164. int best_len = prev_length; // best match length so far
  1165. int limit = strstart > (w_size - MIN_LOOKAHEAD)?strstart - (w_size - MIN_LOOKAHEAD):0;
  1166. int nice_match = this.nice_match;
  1167. // Stop when cur_match becomes <= limit. To simplify the code,
  1168. // we prevent matches with the string of window index 0.
  1169. int wmask = w_mask;
  1170. int strend = strstart + MAX_MATCH;
  1171. byte scan_end1 = window[scan + best_len - 1];
  1172. byte scan_end = window[scan + best_len];
  1173. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1174. // It is easy to get rid of this optimization if necessary.
  1175. // Do not waste too much time if we already have a good match:
  1176. if (prev_length >= good_match)
  1177. {
  1178. chain_length >>= 2;
  1179. }
  1180. // Do not look for matches beyond the end of the input. This is necessary
  1181. // to make deflate deterministic.
  1182. if (nice_match > lookahead)
  1183. nice_match = lookahead;
  1184. do
  1185. {
  1186. match = cur_match;
  1187. // Skip to next match if the match length cannot increase
  1188. // or if the match length is less than 2:
  1189. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan] || window[++match] != window[scan + 1])
  1190. continue;
  1191. // The check at best_len-1 can be removed because it will be made
  1192. // again later. (This heuristic is not always a win.)
  1193. // It is not necessary to compare scan[2] and match[2] since they
  1194. // are always equal when the other bytes match, given that
  1195. // the hash keys are equal and that HASH_BITS >= 8.
  1196. scan += 2; match++;
  1197. // We check for insufficient lookahead only every 8th comparison;
  1198. // the 256th check will be made at strstart+258.
  1199. do
  1200. {
  1201. }
  1202. while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  1203. len = MAX_MATCH - (int) (strend - scan);
  1204. scan = strend - MAX_MATCH;
  1205. if (len > best_len)
  1206. {
  1207. match_start = cur_match;
  1208. best_len = len;
  1209. if (len >= nice_match)
  1210. break;
  1211. scan_end1 = window[scan + best_len - 1];
  1212. scan_end = window[scan + best_len];
  1213. }
  1214. }
  1215. while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length != 0);
  1216. if (best_len <= lookahead)
  1217. return best_len;
  1218. return lookahead;
  1219. }
  1220. internal int deflateInit(ZStream strm, int level, int bits)
  1221. {
  1222. return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  1223. }
  1224. internal int deflateInit(ZStream strm, int level)
  1225. {
  1226. return deflateInit(strm, level, MAX_WBITS);
  1227. }
  1228. internal int deflateInit2(ZStream strm, int level, int method, int windowBits, int memLevel, int strategy)
  1229. {
  1230. int noheader = 0;
  1231. // byte[] my_version=ZLIB_VERSION;
  1232. //
  1233. // if (version == null || version[0] != my_version[0]
  1234. // || stream_size != sizeof(z_stream)) {
  1235. // return Z_VERSION_ERROR;
  1236. // }
  1237. strm.msg = null;
  1238. if (level == Z_DEFAULT_COMPRESSION)
  1239. level = 6;
  1240. if (windowBits < 0)
  1241. {
  1242. // undocumented feature: suppress zlib header
  1243. noheader = 1;
  1244. windowBits = - windowBits;
  1245. }
  1246. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY)
  1247. {
  1248. return Z_STREAM_ERROR;
  1249. }
  1250. strm.dstate = (Deflate) this;
  1251. this.noheader = noheader;
  1252. w_bits = windowBits;
  1253. w_size = 1 << w_bits;
  1254. w_mask = w_size - 1;
  1255. hash_bits = memLevel + 7;
  1256. hash_size = 1 << hash_bits;
  1257. hash_mask = hash_size - 1;
  1258. hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  1259. window = new byte[w_size * 2];
  1260. prev = new short[w_size];
  1261. head = new short[hash_size];
  1262. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  1263. // We overlay pending_buf and d_buf+l_buf. This works since the average
  1264. // output size for (length,distance) codes is <= 24 bits.
  1265. pending_buf = new byte[lit_bufsize * 4];
  1266. pending_buf_size = lit_bufsize * 4;
  1267. d_buf = lit_bufsize / 2;
  1268. l_buf = (1 + 2) * lit_bufsize;
  1269. this.level = level;
  1270. //System.out.println("level="+level);
  1271. this.strategy = strategy;
  1272. this.method = (byte) method;
  1273. return deflateReset(strm);
  1274. }
  1275. internal int deflateReset(ZStream strm)
  1276. {
  1277. strm.total_in = strm.total_out = 0;
  1278. strm.msg = null; //
  1279. strm.data_type = Z_UNKNOWN;
  1280. pending = 0;
  1281. pending_out = 0;
  1282. if (noheader < 0)
  1283. {
  1284. noheader = 0; // was set to -1 by deflate(..., Z_FINISH);
  1285. }
  1286. status = (noheader != 0)?BUSY_STATE:INIT_STATE;
  1287. strm.adler = strm._adler.adler32(0, null, 0, 0);
  1288. last_flush = Z_NO_FLUSH;
  1289. tr_init();
  1290. lm_init();
  1291. return Z_OK;
  1292. }
  1293. internal int deflateEnd()
  1294. {
  1295. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE)
  1296. {
  1297. return Z_STREAM_ERROR;
  1298. }
  1299. // Deallocate in reverse order of allocations:
  1300. pending_buf = null;
  1301. head = null;
  1302. prev = null;
  1303. window = null;
  1304. // free
  1305. // dstate=null;
  1306. return status == BUSY_STATE?Z_DATA_ERROR:Z_OK;
  1307. }
  1308. internal int deflateParams(ZStream strm, int _level, int _strategy)
  1309. {
  1310. int err = Z_OK;
  1311. if (_level == Z_DEFAULT_COMPRESSION)
  1312. {
  1313. _level = 6;
  1314. }
  1315. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY)
  1316. {
  1317. return Z_STREAM_ERROR;
  1318. }
  1319. if (config_table[level].func != config_table[_level].func && strm.total_in != 0)
  1320. {
  1321. // Flush the last buffer:
  1322. err = strm.deflate(Z_PARTIAL_FLUSH);
  1323. }
  1324. if (level != _level)
  1325. {
  1326. level = _level;
  1327. max_lazy_match = config_table[level].max_lazy;
  1328. good_match = config_table[level].good_length;
  1329. nice_match = config_table[level].nice_length;
  1330. max_chain_length = config_table[level].max_chain;
  1331. }
  1332. strategy = _strategy;
  1333. return err;
  1334. }
  1335. internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength)
  1336. {
  1337. int length = dictLength;
  1338. int index = 0;
  1339. if (dictionary == null || status != INIT_STATE)
  1340. return Z_STREAM_ERROR;
  1341. strm.adler = strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
  1342. if (length < MIN_MATCH)
  1343. return Z_OK;
  1344. if (length > w_size - MIN_LOOKAHEAD)
  1345. {
  1346. length = w_size - MIN_LOOKAHEAD;
  1347. index = dictLength - length; // use the tail of the dictionary
  1348. }
  1349. Array.Copy(dictionary, index, window, 0, length);
  1350. strstart = length;
  1351. block_start = length;
  1352. // Insert all strings in the hash table (except for the last two bytes).
  1353. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  1354. // call of fill_window.
  1355. ins_h = window[0] & 0xff;
  1356. ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
  1357. for (int n = 0; n <= length - MIN_MATCH; n++)
  1358. {
  1359. ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1360. prev[n & w_mask] = head[ins_h];
  1361. head[ins_h] = (short) n;
  1362. }
  1363. return Z_OK;
  1364. }
  1365. internal int deflate(ZStream strm, int flush)
  1366. {
  1367. int old_flush;
  1368. if (flush > Z_FINISH || flush < 0)
  1369. {
  1370. return Z_STREAM_ERROR;
  1371. }
  1372. if (strm.next_out == null || (strm.next_in == null && strm.avail_in != 0) || (status == FINISH_STATE && flush != Z_FINISH))
  1373. {
  1374. strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
  1375. return Z_STREAM_ERROR;
  1376. }
  1377. if (strm.avail_out == 0)
  1378. {
  1379. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  1380. return Z_BUF_ERROR;
  1381. }
  1382. this.strm = strm; // just in case
  1383. old_flush = last_flush;
  1384. last_flush = flush;
  1385. // Write the zlib header
  1386. if (status == INIT_STATE)
  1387. {
  1388. int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
  1389. int level_flags = ((level - 1) & 0xff) >> 1;
  1390. if (level_flags > 3)
  1391. level_flags = 3;
  1392. header |= (level_flags << 6);
  1393. if (strstart != 0)
  1394. header |= PRESET_DICT;
  1395. header += 31 - (header % 31);
  1396. status = BUSY_STATE;
  1397. putShortMSB(header);
  1398. // Save the adler32 of the preset dictionary:
  1399. if (strstart != 0)
  1400. {
  1401. putShortMSB((int) (SupportClass.URShift(strm.adler, 16)));
  1402. putShortMSB((int) (strm.adler & 0xffff));
  1403. }
  1404. strm.adler = strm._adler.adler32(0, null, 0, 0);
  1405. }
  1406. // Flush as much pending output as possible
  1407. if (pending != 0)
  1408. {
  1409. strm.flush_pending();
  1410. if (strm.avail_out == 0)
  1411. {
  1412. //System.out.println(" avail_out==0");
  1413. // Since avail_out is 0, deflate will be called again with
  1414. // more output space, but possibly with both pending and
  1415. // avail_in equal to zero. There won't be anything to do,
  1416. // but this is not an error situation so make sure we
  1417. // return OK instead of BUF_ERROR at next call of deflate:
  1418. last_flush = - 1;
  1419. return Z_OK;
  1420. }
  1421. // Make sure there is something to do and avoid duplicate consecutive
  1422. // flushes. For repeated and useless calls with Z_FINISH, we keep
  1423. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  1424. }
  1425. else if (strm.avail_in == 0 && flush <= old_flush && flush != Z_FINISH)
  1426. {
  1427. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  1428. return Z_BUF_ERROR;
  1429. }
  1430. // User must not provide more input after the first FINISH:
  1431. if (status == FINISH_STATE && strm.avail_in != 0)
  1432. {
  1433. strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
  1434. return Z_BUF_ERROR;
  1435. }
  1436. // Start a new block or continue the current one.
  1437. if (strm.avail_in != 0 || lookahead != 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE))
  1438. {
  1439. int bstate = - 1;
  1440. switch (config_table[level].func)
  1441. {
  1442. case STORED:
  1443. bstate = deflate_stored(flush);
  1444. break;
  1445. case FAST:
  1446. bstate = deflate_fast(flush);
  1447. break;
  1448. case SLOW:
  1449. bstate = deflate_slow(flush);
  1450. break;
  1451. default:
  1452. break;
  1453. }
  1454. if (bstate == FinishStarted || bstate == FinishDone)
  1455. {
  1456. status = FINISH_STATE;
  1457. }
  1458. if (bstate == NeedMore || bstate == FinishStarted)
  1459. {
  1460. if (strm.avail_out == 0)
  1461. {
  1462. last_flush = - 1; // avoid BUF_ERROR next call, see above
  1463. }
  1464. return Z_OK;
  1465. // If flush != Z_NO_FLUSH && avail_out == 0, the next call
  1466. // of deflate should use the same flush parameter to make sure
  1467. // that the flush is complete. So we don't have to output an
  1468. // empty block here, this will be done at next call. This also
  1469. // ensures that for a very small output buffer, we emit at most
  1470. // one empty block.
  1471. }
  1472. if (bstate == BlockDone)
  1473. {
  1474. if (flush == Z_PARTIAL_FLUSH)
  1475. {
  1476. _tr_align();
  1477. }
  1478. else
  1479. {
  1480. // FULL_FLUSH or SYNC_FLUSH
  1481. _tr_stored_block(0, 0, false);
  1482. // For a full flush, this empty block will be recognized
  1483. // as a special marker by inflate_sync().
  1484. if (flush == Z_FULL_FLUSH)
  1485. {
  1486. //state.head[s.hash_size-1]=0;
  1487. for (int i = 0; i < hash_size; i++)
  1488. // forget history
  1489. head[i] = 0;
  1490. }
  1491. }
  1492. strm.flush_pending();
  1493. if (strm.avail_out == 0)
  1494. {
  1495. last_flush = - 1; // avoid BUF_ERROR at next call, see above
  1496. return Z_OK;
  1497. }
  1498. }
  1499. }
  1500. if (flush != Z_FINISH)
  1501. return Z_OK;
  1502. if (noheader != 0)
  1503. return Z_STREAM_END;
  1504. // Write the zlib trailer (adler32)
  1505. putShortMSB((int) (SupportClass.URShift(strm.adler, 16)));
  1506. putShortMSB((int) (strm.adler & 0xffff));
  1507. strm.flush_pending();
  1508. // If avail_out is zero, the application will call deflate again
  1509. // to flush the rest.
  1510. noheader = - 1; // write the trailer only once!
  1511. return pending != 0?Z_OK:Z_STREAM_END;
  1512. }
  1513. static Deflate()
  1514. {
  1515. {
  1516. config_table = new Config[10];
  1517. // good lazy nice chain
  1518. config_table[0] = new Config(0, 0, 0, 0, STORED);
  1519. config_table[1] = new Config(4, 4, 8, 4, FAST);
  1520. config_table[2] = new Config(4, 5, 16, 8, FAST);
  1521. config_table[3] = new Config(4, 6, 32, 32, FAST);
  1522. config_table[4] = new Config(4, 4, 16, 16, SLOW);
  1523. config_table[5] = new Config(8, 16, 32, 32, SLOW);
  1524. config_table[6] = new Config(8, 16, 128, 128, SLOW);
  1525. config_table[7] = new Config(8, 32, 128, 256, SLOW);
  1526. config_table[8] = new Config(32, 128, 258, 1024, SLOW);
  1527. config_table[9] = new Config(32, 258, 258, 4096, SLOW);
  1528. }
  1529. }
  1530. }
  1531. }