Deflate.cs 68 KB

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