deflate.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  1. /* Copyright (C) 1999 Masanao Izumo <[email protected]>
  2. * Version: 1.0.1
  3. * LastModified: Dec 25 1999
  4. */
  5. /* Interface:
  6. * data = deflate(src);
  7. */
  8. const deflate = (function () {
  9. /* constant parameters */
  10. var zip_WSIZE = 32768; // Sliding Window size
  11. var zip_STORED_BLOCK = 0;
  12. var zip_STATIC_TREES = 1;
  13. var zip_DYN_TREES = 2;
  14. /* for deflate */
  15. var zip_DEFAULT_LEVEL = 6;
  16. var zip_FULL_SEARCH = true;
  17. var zip_INBUFSIZ = 32768; // Input buffer size
  18. var zip_INBUF_EXTRA = 64; // Extra buffer
  19. var zip_OUTBUFSIZ = 1024 * 8;
  20. var zip_window_size = 2 * zip_WSIZE;
  21. var zip_MIN_MATCH = 3;
  22. var zip_MAX_MATCH = 258;
  23. var zip_BITS = 16;
  24. // for SMALL_MEM
  25. var zip_LIT_BUFSIZE = 0x2000;
  26. var zip_HASH_BITS = 13;
  27. // for MEDIUM_MEM
  28. // var zip_LIT_BUFSIZE = 0x4000;
  29. // var zip_HASH_BITS = 14;
  30. // for BIG_MEM
  31. // var zip_LIT_BUFSIZE = 0x8000;
  32. // var zip_HASH_BITS = 15;
  33. //if(zip_LIT_BUFSIZE > zip_INBUFSIZ)
  34. // alert("error: zip_INBUFSIZ is too small");
  35. //if((zip_WSIZE<<1) > (1<<zip_BITS))
  36. // alert("error: zip_WSIZE is too large");
  37. //if(zip_HASH_BITS > zip_BITS-1)
  38. // alert("error: zip_HASH_BITS is too large");
  39. //if(zip_HASH_BITS < 8 || zip_MAX_MATCH != 258)
  40. // alert("error: Code too clever");
  41. var zip_DIST_BUFSIZE = zip_LIT_BUFSIZE;
  42. var zip_HASH_SIZE = 1 << zip_HASH_BITS;
  43. var zip_HASH_MASK = zip_HASH_SIZE - 1;
  44. var zip_WMASK = zip_WSIZE - 1;
  45. var zip_NIL = 0; // Tail of hash chains
  46. var zip_TOO_FAR = 4096;
  47. var zip_MIN_LOOKAHEAD = zip_MAX_MATCH + zip_MIN_MATCH + 1;
  48. var zip_MAX_DIST = zip_WSIZE - zip_MIN_LOOKAHEAD;
  49. var zip_SMALLEST = 1;
  50. var zip_MAX_BITS = 15;
  51. var zip_MAX_BL_BITS = 7;
  52. var zip_LENGTH_CODES = 29;
  53. var zip_LITERALS = 256;
  54. var zip_END_BLOCK = 256;
  55. var zip_L_CODES = zip_LITERALS + 1 + zip_LENGTH_CODES;
  56. var zip_D_CODES = 30;
  57. var zip_BL_CODES = 19;
  58. var zip_REP_3_6 = 16;
  59. var zip_REPZ_3_10 = 17;
  60. var zip_REPZ_11_138 = 18;
  61. var zip_HEAP_SIZE = 2 * zip_L_CODES + 1;
  62. var zip_H_SHIFT = parseInt((zip_HASH_BITS + zip_MIN_MATCH - 1) /
  63. zip_MIN_MATCH);
  64. /* variables */
  65. var zip_free_queue;
  66. var zip_qhead, zip_qtail;
  67. var zip_initflag;
  68. var zip_outbuf = null;
  69. var zip_outcnt, zip_outoff;
  70. var zip_complete;
  71. var zip_window;
  72. var zip_d_buf;
  73. var zip_l_buf;
  74. var zip_prev;
  75. var zip_bi_buf;
  76. var zip_bi_valid;
  77. var zip_block_start;
  78. var zip_ins_h;
  79. var zip_hash_head;
  80. var zip_prev_match;
  81. var zip_match_available;
  82. var zip_match_length;
  83. var zip_prev_length;
  84. var zip_strstart;
  85. var zip_match_start;
  86. var zip_eofile;
  87. var zip_lookahead;
  88. var zip_max_chain_length;
  89. var zip_max_lazy_match;
  90. var zip_compr_level;
  91. var zip_good_match;
  92. var zip_nice_match;
  93. var zip_dyn_ltree;
  94. var zip_dyn_dtree;
  95. var zip_static_ltree;
  96. var zip_static_dtree;
  97. var zip_bl_tree;
  98. var zip_l_desc;
  99. var zip_d_desc;
  100. var zip_bl_desc;
  101. var zip_bl_count;
  102. var zip_heap;
  103. var zip_heap_len;
  104. var zip_heap_max;
  105. var zip_depth;
  106. var zip_length_code;
  107. var zip_dist_code;
  108. var zip_base_length;
  109. var zip_base_dist;
  110. var zip_flag_buf;
  111. var zip_last_lit;
  112. var zip_last_dist;
  113. var zip_last_flags;
  114. var zip_flags;
  115. var zip_flag_bit;
  116. var zip_opt_len;
  117. var zip_static_len;
  118. var zip_deflate_data;
  119. var zip_deflate_pos;
  120. /* objects (deflate) */
  121. function zip_DeflateCT() {
  122. this.fc = 0; // frequency count or bit string
  123. this.dl = 0; // father node in Huffman tree or length of bit string
  124. }
  125. function zip_DeflateTreeDesc() {
  126. this.dyn_tree = null; // the dynamic tree
  127. this.static_tree = null; // corresponding static tree or NULL
  128. this.extra_bits = null; // extra bits for each code or NULL
  129. this.extra_base = 0; // base index for extra_bits
  130. this.elems = 0; // max number of elements in the tree
  131. this.max_length = 0; // max bit length for the codes
  132. this.max_code = 0; // largest code with non zero frequency
  133. }
  134. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  135. * the desired pack level (0..9). The values given below have been tuned to
  136. * exclude worst case performance for pathological files. Better values may be
  137. * found for specific files.
  138. */
  139. function zip_DeflateConfiguration(a, b, c, d) {
  140. this.good_length = a; // reduce lazy search above this match length
  141. this.max_lazy = b; // do not perform lazy search above this match length
  142. this.nice_length = c; // quit search above this match length
  143. this.max_chain = d;
  144. }
  145. function zip_DeflateBuffer() {
  146. this.next = null;
  147. this.len = 0;
  148. this.ptr = new Array(zip_OUTBUFSIZ);
  149. this.off = 0;
  150. }
  151. /* constant tables */
  152. var zip_extra_lbits = [
  153. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
  154. var zip_extra_dbits = [
  155. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
  156. var zip_extra_blbits = [
  157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
  158. var zip_bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  159. var zip_configuration_table = [
  160. new zip_DeflateConfiguration(0, 0, 0, 0),
  161. new zip_DeflateConfiguration(4, 4, 8, 4),
  162. new zip_DeflateConfiguration(4, 5, 16, 8),
  163. new zip_DeflateConfiguration(4, 6, 32, 32),
  164. new zip_DeflateConfiguration(4, 4, 16, 16),
  165. new zip_DeflateConfiguration(8, 16, 32, 32),
  166. new zip_DeflateConfiguration(8, 16, 128, 128),
  167. new zip_DeflateConfiguration(8, 32, 128, 256),
  168. new zip_DeflateConfiguration(32, 128, 258, 1024),
  169. new zip_DeflateConfiguration(32, 258, 258, 4096)];
  170. /* routines (deflate) */
  171. function zip_deflate_start(level) {
  172. var i;
  173. if (!level)
  174. level = zip_DEFAULT_LEVEL;
  175. else if (level < 1)
  176. level = 1;
  177. else if (level > 9)
  178. level = 9;
  179. zip_compr_level = level;
  180. zip_initflag = false;
  181. zip_eofile = false;
  182. if (zip_outbuf != null)
  183. return;
  184. zip_free_queue = zip_qhead = zip_qtail = null;
  185. zip_outbuf = new Array(zip_OUTBUFSIZ);
  186. zip_window = new Array(zip_window_size);
  187. zip_d_buf = new Array(zip_DIST_BUFSIZE);
  188. zip_l_buf = new Array(zip_INBUFSIZ + zip_INBUF_EXTRA);
  189. zip_prev = new Array(1 << zip_BITS);
  190. zip_dyn_ltree = new Array(zip_HEAP_SIZE);
  191. for (i = 0; i < zip_HEAP_SIZE; i++)
  192. zip_dyn_ltree[i] = new zip_DeflateCT();
  193. zip_dyn_dtree = new Array(2 * zip_D_CODES + 1);
  194. for (i = 0; i < 2 * zip_D_CODES + 1; i++)
  195. zip_dyn_dtree[i] = new zip_DeflateCT();
  196. zip_static_ltree = new Array(zip_L_CODES + 2);
  197. for (i = 0; i < zip_L_CODES + 2; i++)
  198. zip_static_ltree[i] = new zip_DeflateCT();
  199. zip_static_dtree = new Array(zip_D_CODES);
  200. for (i = 0; i < zip_D_CODES; i++)
  201. zip_static_dtree[i] = new zip_DeflateCT();
  202. zip_bl_tree = new Array(2 * zip_BL_CODES + 1);
  203. for (i = 0; i < 2 * zip_BL_CODES + 1; i++)
  204. zip_bl_tree[i] = new zip_DeflateCT();
  205. zip_l_desc = new zip_DeflateTreeDesc();
  206. zip_d_desc = new zip_DeflateTreeDesc();
  207. zip_bl_desc = new zip_DeflateTreeDesc();
  208. zip_bl_count = new Array(zip_MAX_BITS + 1);
  209. zip_heap = new Array(2 * zip_L_CODES + 1);
  210. zip_depth = new Array(2 * zip_L_CODES + 1);
  211. zip_length_code = new Array(zip_MAX_MATCH - zip_MIN_MATCH + 1);
  212. zip_dist_code = new Array(512);
  213. zip_base_length = new Array(zip_LENGTH_CODES);
  214. zip_base_dist = new Array(zip_D_CODES);
  215. zip_flag_buf = new Array(parseInt(zip_LIT_BUFSIZE / 8));
  216. }
  217. function zip_deflate_end() {
  218. zip_free_queue = zip_qhead = zip_qtail = null;
  219. zip_outbuf = null;
  220. zip_window = null;
  221. zip_d_buf = null;
  222. zip_l_buf = null;
  223. zip_prev = null;
  224. zip_dyn_ltree = null;
  225. zip_dyn_dtree = null;
  226. zip_static_ltree = null;
  227. zip_static_dtree = null;
  228. zip_bl_tree = null;
  229. zip_l_desc = null;
  230. zip_d_desc = null;
  231. zip_bl_desc = null;
  232. zip_bl_count = null;
  233. zip_heap = null;
  234. zip_depth = null;
  235. zip_length_code = null;
  236. zip_dist_code = null;
  237. zip_base_length = null;
  238. zip_base_dist = null;
  239. zip_flag_buf = null;
  240. }
  241. function zip_reuse_queue(p) {
  242. p.next = zip_free_queue;
  243. zip_free_queue = p;
  244. }
  245. function zip_new_queue() {
  246. var p;
  247. if (zip_free_queue != null) {
  248. p = zip_free_queue;
  249. zip_free_queue = zip_free_queue.next;
  250. }
  251. else
  252. p = new zip_DeflateBuffer();
  253. p.next = null;
  254. p.len = p.off = 0;
  255. return p;
  256. }
  257. function zip_head1(i) {
  258. return zip_prev[zip_WSIZE + i];
  259. }
  260. function zip_head2(i, val) {
  261. return zip_prev[zip_WSIZE + i] = val;
  262. }
  263. /* put_byte is used for the compressed output, put_ubyte for the
  264. * uncompressed output. However unlzw() uses window for its
  265. * suffix table instead of its output buffer, so it does not use put_ubyte
  266. * (to be cleaned up).
  267. */
  268. function zip_put_byte(c) {
  269. zip_outbuf[zip_outoff + zip_outcnt++] = c;
  270. if (zip_outoff + zip_outcnt == zip_OUTBUFSIZ)
  271. zip_qoutbuf();
  272. }
  273. /* Output a 16 bit value, lsb first */
  274. function zip_put_short(w) {
  275. w &= 0xffff;
  276. if (zip_outoff + zip_outcnt < zip_OUTBUFSIZ - 2) {
  277. zip_outbuf[zip_outoff + zip_outcnt++] = (w & 0xff);
  278. zip_outbuf[zip_outoff + zip_outcnt++] = (w >>> 8);
  279. } else {
  280. zip_put_byte(w & 0xff);
  281. zip_put_byte(w >>> 8);
  282. }
  283. }
  284. /* ==========================================================================
  285. * Insert string s in the dictionary and set match_head to the previous head
  286. * of the hash chain (the most recent string with same hash key). Return
  287. * the previous length of the hash chain.
  288. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  289. * input characters and the first MIN_MATCH bytes of s are valid
  290. * (except for the last MIN_MATCH-1 bytes of the input file).
  291. */
  292. function zip_INSERT_STRING() {
  293. zip_ins_h = ((zip_ins_h << zip_H_SHIFT)
  294. ^ (zip_window[zip_strstart + zip_MIN_MATCH - 1] & 0xff))
  295. & zip_HASH_MASK;
  296. zip_hash_head = zip_head1(zip_ins_h);
  297. zip_prev[zip_strstart & zip_WMASK] = zip_hash_head;
  298. zip_head2(zip_ins_h, zip_strstart);
  299. }
  300. /* Send a code of the given tree. c and tree must not have side effects */
  301. function zip_SEND_CODE(c, tree) {
  302. zip_send_bits(tree[c].fc, tree[c].dl);
  303. }
  304. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  305. * must not have side effects. dist_code[256] and dist_code[257] are never
  306. * used.
  307. */
  308. function zip_D_CODE(dist) {
  309. return (dist < 256 ? zip_dist_code[dist]
  310. : zip_dist_code[256 + (dist >> 7)]) & 0xff;
  311. }
  312. /* ==========================================================================
  313. * Compares to subtrees, using the tree depth as tie breaker when
  314. * the subtrees have equal frequency. This minimizes the worst case length.
  315. */
  316. function zip_SMALLER(tree, n, m) {
  317. return tree[n].fc < tree[m].fc ||
  318. (tree[n].fc == tree[m].fc && zip_depth[n] <= zip_depth[m]);
  319. }
  320. /* ==========================================================================
  321. * read string data
  322. */
  323. function zip_read_buff(buff, offset, n) {
  324. var i;
  325. for (i = 0; i < n && zip_deflate_pos < zip_deflate_data.length; i++)
  326. buff[offset + i] =
  327. zip_deflate_data.charCodeAt(zip_deflate_pos++) & 0xff;
  328. return i;
  329. }
  330. /* ==========================================================================
  331. * Initialize the "longest match" routines for a new file
  332. */
  333. function zip_lm_init() {
  334. var j;
  335. /* Initialize the hash table. */
  336. for (j = 0; j < zip_HASH_SIZE; j++)
  337. // zip_head2(j, zip_NIL);
  338. zip_prev[zip_WSIZE + j] = 0;
  339. /* prev will be initialized on the fly */
  340. /* Set the default configuration parameters:
  341. */
  342. zip_max_lazy_match = zip_configuration_table[zip_compr_level].max_lazy;
  343. zip_good_match = zip_configuration_table[zip_compr_level].good_length;
  344. if (!zip_FULL_SEARCH)
  345. zip_nice_match = zip_configuration_table[zip_compr_level].nice_length;
  346. zip_max_chain_length = zip_configuration_table[zip_compr_level].max_chain;
  347. zip_strstart = 0;
  348. zip_block_start = 0;
  349. zip_lookahead = zip_read_buff(zip_window, 0, 2 * zip_WSIZE);
  350. if (zip_lookahead <= 0) {
  351. zip_eofile = true;
  352. zip_lookahead = 0;
  353. return;
  354. }
  355. zip_eofile = false;
  356. /* Make sure that we always have enough lookahead. This is important
  357. * if input comes from a device such as a tty.
  358. */
  359. while (zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
  360. zip_fill_window();
  361. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  362. * not important since only literal bytes will be emitted.
  363. */
  364. zip_ins_h = 0;
  365. for (j = 0; j < zip_MIN_MATCH - 1; j++) {
  366. // UPDATE_HASH(ins_h, window[j]);
  367. zip_ins_h = ((zip_ins_h << zip_H_SHIFT) ^ (zip_window[j] & 0xff)) & zip_HASH_MASK;
  368. }
  369. }
  370. /* ==========================================================================
  371. * Set match_start to the longest match starting at the given string and
  372. * return its length. Matches shorter or equal to prev_length are discarded,
  373. * in which case the result is equal to prev_length and match_start is
  374. * garbage.
  375. * IN assertions: cur_match is the head of the hash chain for the current
  376. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  377. */
  378. function zip_longest_match(cur_match) {
  379. var chain_length = zip_max_chain_length; // max hash chain length
  380. var scanp = zip_strstart; // current string
  381. var matchp; // matched string
  382. var len; // length of current match
  383. var best_len = zip_prev_length; // best match length so far
  384. /* Stop when cur_match becomes <= limit. To simplify the code,
  385. * we prevent matches with the string of window index 0.
  386. */
  387. var limit = (zip_strstart > zip_MAX_DIST ? zip_strstart - zip_MAX_DIST : zip_NIL);
  388. var strendp = zip_strstart + zip_MAX_MATCH;
  389. var scan_end1 = zip_window[scanp + best_len - 1];
  390. var scan_end = zip_window[scanp + best_len];
  391. /* Do not waste too much time if we already have a good match: */
  392. if (zip_prev_length >= zip_good_match)
  393. chain_length >>= 2;
  394. // Assert(encoder->strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  395. do {
  396. // Assert(cur_match < encoder->strstart, "no future");
  397. matchp = cur_match;
  398. /* Skip to next match if the match length cannot increase
  399. * or if the match length is less than 2:
  400. */
  401. if (zip_window[matchp + best_len] != scan_end ||
  402. zip_window[matchp + best_len - 1] != scan_end1 ||
  403. zip_window[matchp] != zip_window[scanp] ||
  404. zip_window[++matchp] != zip_window[scanp + 1]) {
  405. continue;
  406. }
  407. /* The check at best_len-1 can be removed because it will be made
  408. * again later. (This heuristic is not always a win.)
  409. * It is not necessary to compare scan[2] and match[2] since they
  410. * are always equal when the other bytes match, given that
  411. * the hash keys are equal and that HASH_BITS >= 8.
  412. */
  413. scanp += 2;
  414. matchp++;
  415. /* We check for insufficient lookahead only every 8th comparison;
  416. * the 256th check will be made at strstart+258.
  417. */
  418. do {
  419. } while (zip_window[++scanp] == zip_window[++matchp] &&
  420. zip_window[++scanp] == zip_window[++matchp] &&
  421. zip_window[++scanp] == zip_window[++matchp] &&
  422. zip_window[++scanp] == zip_window[++matchp] &&
  423. zip_window[++scanp] == zip_window[++matchp] &&
  424. zip_window[++scanp] == zip_window[++matchp] &&
  425. zip_window[++scanp] == zip_window[++matchp] &&
  426. zip_window[++scanp] == zip_window[++matchp] &&
  427. scanp < strendp);
  428. len = zip_MAX_MATCH - (strendp - scanp);
  429. scanp = strendp - zip_MAX_MATCH;
  430. if (len > best_len) {
  431. zip_match_start = cur_match;
  432. best_len = len;
  433. if (zip_FULL_SEARCH) {
  434. if (len >= zip_MAX_MATCH) break;
  435. } else {
  436. if (len >= zip_nice_match) break;
  437. }
  438. scan_end1 = zip_window[scanp + best_len - 1];
  439. scan_end = zip_window[scanp + best_len];
  440. }
  441. } while ((cur_match = zip_prev[cur_match & zip_WMASK]) > limit
  442. && --chain_length != 0);
  443. return best_len;
  444. }
  445. /* ==========================================================================
  446. * Fill the window when the lookahead becomes insufficient.
  447. * Updates strstart and lookahead, and sets eofile if end of input file.
  448. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  449. * OUT assertions: at least one byte has been read, or eofile is set;
  450. * file reads are performed for at least two bytes (required for the
  451. * translate_eol option).
  452. */
  453. function zip_fill_window() {
  454. var n, m;
  455. // Amount of free space at the end of the window.
  456. var more = zip_window_size - zip_lookahead - zip_strstart;
  457. /* If the window is almost full and there is insufficient lookahead,
  458. * move the upper half to the lower one to make room in the upper half.
  459. */
  460. if (more == -1) {
  461. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  462. * and lookahead == 1 (input done one byte at time)
  463. */
  464. more--;
  465. } else if (zip_strstart >= zip_WSIZE + zip_MAX_DIST) {
  466. /* By the IN assertion, the window is not empty so we can't confuse
  467. * more == 0 with more == 64K on a 16 bit machine.
  468. */
  469. // Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
  470. // System.arraycopy(window, WSIZE, window, 0, WSIZE);
  471. for (n = 0; n < zip_WSIZE; n++)
  472. zip_window[n] = zip_window[n + zip_WSIZE];
  473. zip_match_start -= zip_WSIZE;
  474. zip_strstart -= zip_WSIZE; /* we now have strstart >= MAX_DIST: */
  475. zip_block_start -= zip_WSIZE;
  476. for (n = 0; n < zip_HASH_SIZE; n++) {
  477. m = zip_head1(n);
  478. zip_head2(n, m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
  479. }
  480. for (n = 0; n < zip_WSIZE; n++) {
  481. /* If n is not on any hash chain, prev[n] is garbage but
  482. * its value will never be used.
  483. */
  484. m = zip_prev[n];
  485. zip_prev[n] = (m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
  486. }
  487. more += zip_WSIZE;
  488. }
  489. // At this point, more >= 2
  490. if (!zip_eofile) {
  491. n = zip_read_buff(zip_window, zip_strstart + zip_lookahead, more);
  492. if (n <= 0)
  493. zip_eofile = true;
  494. else
  495. zip_lookahead += n;
  496. }
  497. }
  498. /* ==========================================================================
  499. * Processes a new input file and return its compressed length. This
  500. * function does not perform lazy evaluationof matches and inserts
  501. * new strings in the dictionary only for unmatched strings or for short
  502. * matches. It is used only for the fast compression options.
  503. */
  504. function zip_deflate_fast() {
  505. while (zip_lookahead != 0 && zip_qhead == null) {
  506. var flush; // set if current block must be flushed
  507. /* Insert the string window[strstart .. strstart+2] in the
  508. * dictionary, and set hash_head to the head of the hash chain:
  509. */
  510. zip_INSERT_STRING();
  511. /* Find the longest match, discarding those <= prev_length.
  512. * At this point we have always match_length < MIN_MATCH
  513. */
  514. if (zip_hash_head != zip_NIL &&
  515. zip_strstart - zip_hash_head <= zip_MAX_DIST) {
  516. /* To simplify the code, we prevent matches with the string
  517. * of window index 0 (in particular we have to avoid a match
  518. * of the string with itself at the start of the input file).
  519. */
  520. zip_match_length = zip_longest_match(zip_hash_head);
  521. /* longest_match() sets match_start */
  522. if (zip_match_length > zip_lookahead)
  523. zip_match_length = zip_lookahead;
  524. }
  525. if (zip_match_length >= zip_MIN_MATCH) {
  526. // check_match(strstart, match_start, match_length);
  527. flush = zip_ct_tally(zip_strstart - zip_match_start,
  528. zip_match_length - zip_MIN_MATCH);
  529. zip_lookahead -= zip_match_length;
  530. /* Insert new strings in the hash table only if the match length
  531. * is not too large. This saves time but degrades compression.
  532. */
  533. if (zip_match_length <= zip_max_lazy_match) {
  534. zip_match_length--; // string at strstart already in hash table
  535. do {
  536. zip_strstart++;
  537. zip_INSERT_STRING();
  538. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  539. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  540. * these bytes are garbage, but it does not matter since
  541. * the next lookahead bytes will be emitted as literals.
  542. */
  543. } while (--zip_match_length != 0);
  544. zip_strstart++;
  545. } else {
  546. zip_strstart += zip_match_length;
  547. zip_match_length = 0;
  548. zip_ins_h = zip_window[zip_strstart] & 0xff;
  549. // UPDATE_HASH(ins_h, window[strstart + 1]);
  550. zip_ins_h = ((zip_ins_h << zip_H_SHIFT) ^ (zip_window[zip_strstart + 1] & 0xff)) & zip_HASH_MASK;
  551. //#if MIN_MATCH != 3
  552. // Call UPDATE_HASH() MIN_MATCH-3 more times
  553. //#endif
  554. }
  555. } else {
  556. /* No match, output a literal byte */
  557. flush = zip_ct_tally(0, zip_window[zip_strstart] & 0xff);
  558. zip_lookahead--;
  559. zip_strstart++;
  560. }
  561. if (flush) {
  562. zip_flush_block(0);
  563. zip_block_start = zip_strstart;
  564. }
  565. /* Make sure that we always have enough lookahead, except
  566. * at the end of the input file. We need MAX_MATCH bytes
  567. * for the next match, plus MIN_MATCH bytes to insert the
  568. * string following the next match.
  569. */
  570. while (zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
  571. zip_fill_window();
  572. }
  573. }
  574. function zip_deflate_better() {
  575. /* Process the input block. */
  576. while (zip_lookahead != 0 && zip_qhead == null) {
  577. /* Insert the string window[strstart .. strstart+2] in the
  578. * dictionary, and set hash_head to the head of the hash chain:
  579. */
  580. zip_INSERT_STRING();
  581. /* Find the longest match, discarding those <= prev_length.
  582. */
  583. zip_prev_length = zip_match_length;
  584. zip_prev_match = zip_match_start;
  585. zip_match_length = zip_MIN_MATCH - 1;
  586. if (zip_hash_head != zip_NIL &&
  587. zip_prev_length < zip_max_lazy_match &&
  588. zip_strstart - zip_hash_head <= zip_MAX_DIST) {
  589. /* To simplify the code, we prevent matches with the string
  590. * of window index 0 (in particular we have to avoid a match
  591. * of the string with itself at the start of the input file).
  592. */
  593. zip_match_length = zip_longest_match(zip_hash_head);
  594. /* longest_match() sets match_start */
  595. if (zip_match_length > zip_lookahead)
  596. zip_match_length = zip_lookahead;
  597. /* Ignore a length 3 match if it is too distant: */
  598. if (zip_match_length == zip_MIN_MATCH &&
  599. zip_strstart - zip_match_start > zip_TOO_FAR) {
  600. /* If prev_match is also MIN_MATCH, match_start is garbage
  601. * but we will ignore the current match anyway.
  602. */
  603. zip_match_length--;
  604. }
  605. }
  606. /* If there was a match at the previous step and the current
  607. * match is not better, output the previous match:
  608. */
  609. if (zip_prev_length >= zip_MIN_MATCH &&
  610. zip_match_length <= zip_prev_length) {
  611. var flush; // set if current block must be flushed
  612. // check_match(strstart - 1, prev_match, prev_length);
  613. flush = zip_ct_tally(zip_strstart - 1 - zip_prev_match,
  614. zip_prev_length - zip_MIN_MATCH);
  615. /* Insert in hash table all strings up to the end of the match.
  616. * strstart-1 and strstart are already inserted.
  617. */
  618. zip_lookahead -= zip_prev_length - 1;
  619. zip_prev_length -= 2;
  620. do {
  621. zip_strstart++;
  622. zip_INSERT_STRING();
  623. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  624. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  625. * these bytes are garbage, but it does not matter since the
  626. * next lookahead bytes will always be emitted as literals.
  627. */
  628. } while (--zip_prev_length != 0);
  629. zip_match_available = 0;
  630. zip_match_length = zip_MIN_MATCH - 1;
  631. zip_strstart++;
  632. if (flush) {
  633. zip_flush_block(0);
  634. zip_block_start = zip_strstart;
  635. }
  636. } else if (zip_match_available != 0) {
  637. /* If there was no match at the previous position, output a
  638. * single literal. If there was a match but the current match
  639. * is longer, truncate the previous match to a single literal.
  640. */
  641. if (zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff)) {
  642. zip_flush_block(0);
  643. zip_block_start = zip_strstart;
  644. }
  645. zip_strstart++;
  646. zip_lookahead--;
  647. } else {
  648. /* There is no previous match to compare with, wait for
  649. * the next step to decide.
  650. */
  651. zip_match_available = 1;
  652. zip_strstart++;
  653. zip_lookahead--;
  654. }
  655. /* Make sure that we always have enough lookahead, except
  656. * at the end of the input file. We need MAX_MATCH bytes
  657. * for the next match, plus MIN_MATCH bytes to insert the
  658. * string following the next match.
  659. */
  660. while (zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
  661. zip_fill_window();
  662. }
  663. }
  664. function zip_init_deflate() {
  665. if (zip_eofile)
  666. return;
  667. zip_bi_buf = 0;
  668. zip_bi_valid = 0;
  669. zip_ct_init();
  670. zip_lm_init();
  671. zip_qhead = null;
  672. zip_outcnt = 0;
  673. zip_outoff = 0;
  674. if (zip_compr_level <= 3) {
  675. zip_prev_length = zip_MIN_MATCH - 1;
  676. zip_match_length = 0;
  677. }
  678. else {
  679. zip_match_length = zip_MIN_MATCH - 1;
  680. zip_match_available = 0;
  681. }
  682. zip_complete = false;
  683. }
  684. /* ==========================================================================
  685. * Same as above, but achieves better compression. We use a lazy
  686. * evaluation for matches: a match is finally adopted only if there is
  687. * no better match at the next window position.
  688. */
  689. function zip_deflate_internal(buff, off, buff_size) {
  690. var n;
  691. if (!zip_initflag) {
  692. zip_init_deflate();
  693. zip_initflag = true;
  694. if (zip_lookahead == 0) { // empty
  695. zip_complete = true;
  696. return 0;
  697. }
  698. }
  699. if ((n = zip_qcopy(buff, off, buff_size)) == buff_size)
  700. return buff_size;
  701. if (zip_complete)
  702. return n;
  703. if (zip_compr_level <= 3) // optimized for speed
  704. zip_deflate_fast();
  705. else
  706. zip_deflate_better();
  707. if (zip_lookahead == 0) {
  708. if (zip_match_available != 0)
  709. zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff);
  710. zip_flush_block(1);
  711. zip_complete = true;
  712. }
  713. return n + zip_qcopy(buff, n + off, buff_size - n);
  714. }
  715. function zip_qcopy(buff, off, buff_size) {
  716. var n, i, j;
  717. n = 0;
  718. while (zip_qhead != null && n < buff_size) {
  719. i = buff_size - n;
  720. if (i > zip_qhead.len)
  721. i = zip_qhead.len;
  722. // System.arraycopy(qhead.ptr, qhead.off, buff, off + n, i);
  723. for (j = 0; j < i; j++)
  724. buff[off + n + j] = zip_qhead.ptr[zip_qhead.off + j];
  725. zip_qhead.off += i;
  726. zip_qhead.len -= i;
  727. n += i;
  728. if (zip_qhead.len == 0) {
  729. var p;
  730. p = zip_qhead;
  731. zip_qhead = zip_qhead.next;
  732. zip_reuse_queue(p);
  733. }
  734. }
  735. if (n == buff_size)
  736. return n;
  737. if (zip_outoff < zip_outcnt) {
  738. i = buff_size - n;
  739. if (i > zip_outcnt - zip_outoff)
  740. i = zip_outcnt - zip_outoff;
  741. // System.arraycopy(outbuf, outoff, buff, off + n, i);
  742. for (j = 0; j < i; j++)
  743. buff[off + n + j] = zip_outbuf[zip_outoff + j];
  744. zip_outoff += i;
  745. n += i;
  746. if (zip_outcnt == zip_outoff)
  747. zip_outcnt = zip_outoff = 0;
  748. }
  749. return n;
  750. }
  751. /* ==========================================================================
  752. * Allocate the match buffer, initialize the various tables and save the
  753. * location of the internal file attribute (ascii/binary) and method
  754. * (DEFLATE/STORE).
  755. */
  756. function zip_ct_init() {
  757. var n; // iterates over tree elements
  758. var bits; // bit counter
  759. var length; // length value
  760. var code; // code value
  761. var dist; // distance index
  762. if (zip_static_dtree[0].dl != 0) return; // ct_init already called
  763. zip_l_desc.dyn_tree = zip_dyn_ltree;
  764. zip_l_desc.static_tree = zip_static_ltree;
  765. zip_l_desc.extra_bits = zip_extra_lbits;
  766. zip_l_desc.extra_base = zip_LITERALS + 1;
  767. zip_l_desc.elems = zip_L_CODES;
  768. zip_l_desc.max_length = zip_MAX_BITS;
  769. zip_l_desc.max_code = 0;
  770. zip_d_desc.dyn_tree = zip_dyn_dtree;
  771. zip_d_desc.static_tree = zip_static_dtree;
  772. zip_d_desc.extra_bits = zip_extra_dbits;
  773. zip_d_desc.extra_base = 0;
  774. zip_d_desc.elems = zip_D_CODES;
  775. zip_d_desc.max_length = zip_MAX_BITS;
  776. zip_d_desc.max_code = 0;
  777. zip_bl_desc.dyn_tree = zip_bl_tree;
  778. zip_bl_desc.static_tree = null;
  779. zip_bl_desc.extra_bits = zip_extra_blbits;
  780. zip_bl_desc.extra_base = 0;
  781. zip_bl_desc.elems = zip_BL_CODES;
  782. zip_bl_desc.max_length = zip_MAX_BL_BITS;
  783. zip_bl_desc.max_code = 0;
  784. // Initialize the mapping length (0..255) -> length code (0..28)
  785. length = 0;
  786. for (code = 0; code < zip_LENGTH_CODES - 1; code++) {
  787. zip_base_length[code] = length;
  788. for (n = 0; n < (1 << zip_extra_lbits[code]); n++)
  789. zip_length_code[length++] = code;
  790. }
  791. // Assert (length == 256, "ct_init: length != 256");
  792. /* Note that the length 255 (match length 258) can be represented
  793. * in two different ways: code 284 + 5 bits or code 285, so we
  794. * overwrite length_code[255] to use the best encoding:
  795. */
  796. zip_length_code[length - 1] = code;
  797. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  798. dist = 0;
  799. for (code = 0; code < 16; code++) {
  800. zip_base_dist[code] = dist;
  801. for (n = 0; n < (1 << zip_extra_dbits[code]); n++) {
  802. zip_dist_code[dist++] = code;
  803. }
  804. }
  805. // Assert (dist == 256, "ct_init: dist != 256");
  806. dist >>= 7; // from now on, all distances are divided by 128
  807. for (; code < zip_D_CODES; code++) {
  808. zip_base_dist[code] = dist << 7;
  809. for (n = 0; n < (1 << (zip_extra_dbits[code] - 7)); n++)
  810. zip_dist_code[256 + dist++] = code;
  811. }
  812. // Assert (dist == 256, "ct_init: 256+dist != 512");
  813. // Construct the codes of the static literal tree
  814. for (bits = 0; bits <= zip_MAX_BITS; bits++)
  815. zip_bl_count[bits] = 0;
  816. n = 0;
  817. while (n <= 143) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; }
  818. while (n <= 255) { zip_static_ltree[n++].dl = 9; zip_bl_count[9]++; }
  819. while (n <= 279) { zip_static_ltree[n++].dl = 7; zip_bl_count[7]++; }
  820. while (n <= 287) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; }
  821. /* Codes 286 and 287 do not exist, but we must include them in the
  822. * tree construction to get a canonical Huffman tree (longest code
  823. * all ones)
  824. */
  825. zip_gen_codes(zip_static_ltree, zip_L_CODES + 1);
  826. /* The static distance tree is trivial: */
  827. for (n = 0; n < zip_D_CODES; n++) {
  828. zip_static_dtree[n].dl = 5;
  829. zip_static_dtree[n].fc = zip_bi_reverse(n, 5);
  830. }
  831. // Initialize the first block of the first file:
  832. zip_init_block();
  833. }
  834. /* ==========================================================================
  835. * Initialize a new block.
  836. */
  837. function zip_init_block() {
  838. var n; // iterates over tree elements
  839. // Initialize the trees.
  840. for (n = 0; n < zip_L_CODES; n++) zip_dyn_ltree[n].fc = 0;
  841. for (n = 0; n < zip_D_CODES; n++) zip_dyn_dtree[n].fc = 0;
  842. for (n = 0; n < zip_BL_CODES; n++) zip_bl_tree[n].fc = 0;
  843. zip_dyn_ltree[zip_END_BLOCK].fc = 1;
  844. zip_opt_len = zip_static_len = 0;
  845. zip_last_lit = zip_last_dist = zip_last_flags = 0;
  846. zip_flags = 0;
  847. zip_flag_bit = 1;
  848. }
  849. /* ==========================================================================
  850. * Restore the heap property by moving down the tree starting at node k,
  851. * exchanging a node with the smallest of its two sons if necessary, stopping
  852. * when the heap property is re-established (each father smaller than its
  853. * two sons).
  854. */
  855. function zip_pqdownheap(
  856. tree, // the tree to restore
  857. k) { // node to move down
  858. var v = zip_heap[k];
  859. var j = k << 1; // left son of k
  860. while (j <= zip_heap_len) {
  861. // Set j to the smallest of the two sons:
  862. if (j < zip_heap_len &&
  863. zip_SMALLER(tree, zip_heap[j + 1], zip_heap[j]))
  864. j++;
  865. // Exit if v is smaller than both sons
  866. if (zip_SMALLER(tree, v, zip_heap[j]))
  867. break;
  868. // Exchange v with the smallest son
  869. zip_heap[k] = zip_heap[j];
  870. k = j;
  871. // And continue down the tree, setting j to the left son of k
  872. j <<= 1;
  873. }
  874. zip_heap[k] = v;
  875. }
  876. /* ==========================================================================
  877. * Compute the optimal bit lengths for a tree and update the total bit length
  878. * for the current block.
  879. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  880. * above are the tree nodes sorted by increasing frequency.
  881. * OUT assertions: the field len is set to the optimal bit length, the
  882. * array bl_count contains the frequencies for each bit length.
  883. * The length opt_len is updated; static_len is also updated if stree is
  884. * not null.
  885. */
  886. function zip_gen_bitlen(desc) { // the tree descriptor
  887. var tree = desc.dyn_tree;
  888. var extra = desc.extra_bits;
  889. var base = desc.extra_base;
  890. var max_code = desc.max_code;
  891. var max_length = desc.max_length;
  892. var stree = desc.static_tree;
  893. var h; // heap index
  894. var n, m; // iterate over the tree elements
  895. var bits; // bit length
  896. var xbits; // extra bits
  897. var f; // frequency
  898. var overflow = 0; // number of elements with bit length too large
  899. for (bits = 0; bits <= zip_MAX_BITS; bits++)
  900. zip_bl_count[bits] = 0;
  901. /* In a first pass, compute the optimal bit lengths (which may
  902. * overflow in the case of the bit length tree).
  903. */
  904. tree[zip_heap[zip_heap_max]].dl = 0; // root of the heap
  905. for (h = zip_heap_max + 1; h < zip_HEAP_SIZE; h++) {
  906. n = zip_heap[h];
  907. bits = tree[tree[n].dl].dl + 1;
  908. if (bits > max_length) {
  909. bits = max_length;
  910. overflow++;
  911. }
  912. tree[n].dl = bits;
  913. // We overwrite tree[n].dl which is no longer needed
  914. if (n > max_code)
  915. continue; // not a leaf node
  916. zip_bl_count[bits]++;
  917. xbits = 0;
  918. if (n >= base)
  919. xbits = extra[n - base];
  920. f = tree[n].fc;
  921. zip_opt_len += f * (bits + xbits);
  922. if (stree != null)
  923. zip_static_len += f * (stree[n].dl + xbits);
  924. }
  925. if (overflow == 0)
  926. return;
  927. // This happens for example on obj2 and pic of the Calgary corpus
  928. // Find the first bit length which could increase:
  929. do {
  930. bits = max_length - 1;
  931. while (zip_bl_count[bits] == 0)
  932. bits--;
  933. zip_bl_count[bits]--; // move one leaf down the tree
  934. zip_bl_count[bits + 1] += 2; // move one overflow item as its brother
  935. zip_bl_count[max_length]--;
  936. /* The brother of the overflow item also moves one step up,
  937. * but this does not affect bl_count[max_length]
  938. */
  939. overflow -= 2;
  940. } while (overflow > 0);
  941. /* Now recompute all bit lengths, scanning in increasing frequency.
  942. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  943. * lengths instead of fixing only the wrong ones. This idea is taken
  944. * from 'ar' written by Haruhiko Okumura.)
  945. */
  946. for (bits = max_length; bits != 0; bits--) {
  947. n = zip_bl_count[bits];
  948. while (n != 0) {
  949. m = zip_heap[--h];
  950. if (m > max_code)
  951. continue;
  952. if (tree[m].dl != bits) {
  953. zip_opt_len += (bits - tree[m].dl) * tree[m].fc;
  954. tree[m].fc = bits;
  955. }
  956. n--;
  957. }
  958. }
  959. }
  960. /* ==========================================================================
  961. * Generate the codes for a given tree and bit counts (which need not be
  962. * optimal).
  963. * IN assertion: the array bl_count contains the bit length statistics for
  964. * the given tree and the field len is set for all tree elements.
  965. * OUT assertion: the field code is set for all tree elements of non
  966. * zero code length.
  967. */
  968. function zip_gen_codes(tree, // the tree to decorate
  969. max_code) { // largest code with non zero frequency
  970. var next_code = new Array(zip_MAX_BITS + 1); // next code value for each bit length
  971. var code = 0; // running code value
  972. var bits; // bit index
  973. var n; // code index
  974. /* The distribution counts are first used to generate the code values
  975. * without bit reversal.
  976. */
  977. for (bits = 1; bits <= zip_MAX_BITS; bits++) {
  978. code = ((code + zip_bl_count[bits - 1]) << 1);
  979. next_code[bits] = code;
  980. }
  981. /* Check that the bit counts in bl_count are consistent. The last code
  982. * must be all ones.
  983. */
  984. // Assert (code + encoder->bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  985. // "inconsistent bit counts");
  986. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  987. for (n = 0; n <= max_code; n++) {
  988. var len = tree[n].dl;
  989. if (len == 0)
  990. continue;
  991. // Now reverse the bits
  992. tree[n].fc = zip_bi_reverse(next_code[len]++, len);
  993. // Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  994. // n, (isgraph(n) ? n : ' '), len, tree[n].fc, next_code[len]-1));
  995. }
  996. }
  997. /* ==========================================================================
  998. * Construct one Huffman tree and assigns the code bit strings and lengths.
  999. * Update the total bit length for the current block.
  1000. * IN assertion: the field freq is set for all tree elements.
  1001. * OUT assertions: the fields len and code are set to the optimal bit length
  1002. * and corresponding code. The length opt_len is updated; static_len is
  1003. * also updated if stree is not null. The field max_code is set.
  1004. */
  1005. function zip_build_tree(desc) { // the tree descriptor
  1006. var tree = desc.dyn_tree;
  1007. var stree = desc.static_tree;
  1008. var elems = desc.elems;
  1009. var n, m; // iterate over heap elements
  1010. var max_code = -1; // largest code with non zero frequency
  1011. var node = elems; // next internal node of the tree
  1012. /* Construct the initial heap, with least frequent element in
  1013. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  1014. * heap[0] is not used.
  1015. */
  1016. zip_heap_len = 0;
  1017. zip_heap_max = zip_HEAP_SIZE;
  1018. for (n = 0; n < elems; n++) {
  1019. if (tree[n].fc != 0) {
  1020. zip_heap[++zip_heap_len] = max_code = n;
  1021. zip_depth[n] = 0;
  1022. } else
  1023. tree[n].dl = 0;
  1024. }
  1025. /* The pkzip format requires that at least one distance code exists,
  1026. * and that at least one bit should be sent even if there is only one
  1027. * possible code. So to avoid special checks later on we force at least
  1028. * two codes of non zero frequency.
  1029. */
  1030. while (zip_heap_len < 2) {
  1031. var xnew = zip_heap[++zip_heap_len] = (max_code < 2 ? ++max_code : 0);
  1032. tree[xnew].fc = 1;
  1033. zip_depth[xnew] = 0;
  1034. zip_opt_len--;
  1035. if (stree != null)
  1036. zip_static_len -= stree[xnew].dl;
  1037. // new is 0 or 1 so it does not have extra bits
  1038. }
  1039. desc.max_code = max_code;
  1040. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  1041. * establish sub-heaps of increasing lengths:
  1042. */
  1043. for (n = zip_heap_len >> 1; n >= 1; n--)
  1044. zip_pqdownheap(tree, n);
  1045. /* Construct the Huffman tree by repeatedly combining the least two
  1046. * frequent nodes.
  1047. */
  1048. do {
  1049. n = zip_heap[zip_SMALLEST];
  1050. zip_heap[zip_SMALLEST] = zip_heap[zip_heap_len--];
  1051. zip_pqdownheap(tree, zip_SMALLEST);
  1052. m = zip_heap[zip_SMALLEST]; // m = node of next least frequency
  1053. // keep the nodes sorted by frequency
  1054. zip_heap[--zip_heap_max] = n;
  1055. zip_heap[--zip_heap_max] = m;
  1056. // Create a new node father of n and m
  1057. tree[node].fc = tree[n].fc + tree[m].fc;
  1058. // depth[node] = (char)(MAX(depth[n], depth[m]) + 1);
  1059. if (zip_depth[n] > zip_depth[m] + 1)
  1060. zip_depth[node] = zip_depth[n];
  1061. else
  1062. zip_depth[node] = zip_depth[m] + 1;
  1063. tree[n].dl = tree[m].dl = node;
  1064. // and insert the new node in the heap
  1065. zip_heap[zip_SMALLEST] = node++;
  1066. zip_pqdownheap(tree, zip_SMALLEST);
  1067. } while (zip_heap_len >= 2);
  1068. zip_heap[--zip_heap_max] = zip_heap[zip_SMALLEST];
  1069. /* At this point, the fields freq and dad are set. We can now
  1070. * generate the bit lengths.
  1071. */
  1072. zip_gen_bitlen(desc);
  1073. // The field len is now set, we can generate the bit codes
  1074. zip_gen_codes(tree, max_code);
  1075. }
  1076. /* ==========================================================================
  1077. * Scan a literal or distance tree to determine the frequencies of the codes
  1078. * in the bit length tree. Updates opt_len to take into account the repeat
  1079. * counts. (The contribution of the bit length codes will be added later
  1080. * during the construction of bl_tree.)
  1081. */
  1082. function zip_scan_tree(tree,// the tree to be scanned
  1083. max_code) { // and its largest code of non zero frequency
  1084. var n; // iterates over all tree elements
  1085. var prevlen = -1; // last emitted length
  1086. var curlen; // length of current code
  1087. var nextlen = tree[0].dl; // length of next code
  1088. var count = 0; // repeat count of the current code
  1089. var max_count = 7; // max repeat count
  1090. var min_count = 4; // min repeat count
  1091. if (nextlen == 0) {
  1092. max_count = 138;
  1093. min_count = 3;
  1094. }
  1095. tree[max_code + 1].dl = 0xffff; // guard
  1096. for (n = 0; n <= max_code; n++) {
  1097. curlen = nextlen;
  1098. nextlen = tree[n + 1].dl;
  1099. if (++count < max_count && curlen == nextlen)
  1100. continue;
  1101. else if (count < min_count)
  1102. zip_bl_tree[curlen].fc += count;
  1103. else if (curlen != 0) {
  1104. if (curlen != prevlen)
  1105. zip_bl_tree[curlen].fc++;
  1106. zip_bl_tree[zip_REP_3_6].fc++;
  1107. } else if (count <= 10)
  1108. zip_bl_tree[zip_REPZ_3_10].fc++;
  1109. else
  1110. zip_bl_tree[zip_REPZ_11_138].fc++;
  1111. count = 0; prevlen = curlen;
  1112. if (nextlen == 0) {
  1113. max_count = 138;
  1114. min_count = 3;
  1115. } else if (curlen == nextlen) {
  1116. max_count = 6;
  1117. min_count = 3;
  1118. } else {
  1119. max_count = 7;
  1120. min_count = 4;
  1121. }
  1122. }
  1123. }
  1124. /* ==========================================================================
  1125. * Send a literal or distance tree in compressed form, using the codes in
  1126. * bl_tree.
  1127. */
  1128. function zip_send_tree(tree, // the tree to be scanned
  1129. max_code) { // and its largest code of non zero frequency
  1130. var n; // iterates over all tree elements
  1131. var prevlen = -1; // last emitted length
  1132. var curlen; // length of current code
  1133. var nextlen = tree[0].dl; // length of next code
  1134. var count = 0; // repeat count of the current code
  1135. var max_count = 7; // max repeat count
  1136. var min_count = 4; // min repeat count
  1137. /* tree[max_code+1].dl = -1; */ /* guard already set */
  1138. if (nextlen == 0) {
  1139. max_count = 138;
  1140. min_count = 3;
  1141. }
  1142. for (n = 0; n <= max_code; n++) {
  1143. curlen = nextlen;
  1144. nextlen = tree[n + 1].dl;
  1145. if (++count < max_count && curlen == nextlen) {
  1146. continue;
  1147. } else if (count < min_count) {
  1148. do { zip_SEND_CODE(curlen, zip_bl_tree); } while (--count != 0);
  1149. } else if (curlen != 0) {
  1150. if (curlen != prevlen) {
  1151. zip_SEND_CODE(curlen, zip_bl_tree);
  1152. count--;
  1153. }
  1154. // Assert(count >= 3 && count <= 6, " 3_6?");
  1155. zip_SEND_CODE(zip_REP_3_6, zip_bl_tree);
  1156. zip_send_bits(count - 3, 2);
  1157. } else if (count <= 10) {
  1158. zip_SEND_CODE(zip_REPZ_3_10, zip_bl_tree);
  1159. zip_send_bits(count - 3, 3);
  1160. } else {
  1161. zip_SEND_CODE(zip_REPZ_11_138, zip_bl_tree);
  1162. zip_send_bits(count - 11, 7);
  1163. }
  1164. count = 0;
  1165. prevlen = curlen;
  1166. if (nextlen == 0) {
  1167. max_count = 138;
  1168. min_count = 3;
  1169. } else if (curlen == nextlen) {
  1170. max_count = 6;
  1171. min_count = 3;
  1172. } else {
  1173. max_count = 7;
  1174. min_count = 4;
  1175. }
  1176. }
  1177. }
  1178. /* ==========================================================================
  1179. * Construct the Huffman tree for the bit lengths and return the index in
  1180. * bl_order of the last bit length code to send.
  1181. */
  1182. function zip_build_bl_tree() {
  1183. var max_blindex; // index of last bit length code of non zero freq
  1184. // Determine the bit length frequencies for literal and distance trees
  1185. zip_scan_tree(zip_dyn_ltree, zip_l_desc.max_code);
  1186. zip_scan_tree(zip_dyn_dtree, zip_d_desc.max_code);
  1187. // Build the bit length tree:
  1188. zip_build_tree(zip_bl_desc);
  1189. /* opt_len now includes the length of the tree representations, except
  1190. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1191. */
  1192. /* Determine the number of bit length codes to send. The pkzip format
  1193. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1194. * 3 but the actual value used is 4.)
  1195. */
  1196. for (max_blindex = zip_BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  1197. if (zip_bl_tree[zip_bl_order[max_blindex]].dl != 0) break;
  1198. }
  1199. /* Update opt_len to include the bit length tree and counts */
  1200. zip_opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  1201. // Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  1202. // encoder->opt_len, encoder->static_len));
  1203. return max_blindex;
  1204. }
  1205. /* ==========================================================================
  1206. * Send the header for a block using dynamic Huffman trees: the counts, the
  1207. * lengths of the bit length codes, the literal tree and the distance tree.
  1208. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  1209. */
  1210. function zip_send_all_trees(lcodes, dcodes, blcodes) { // number of codes for each tree
  1211. var rank; // index in bl_order
  1212. // Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  1213. // Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  1214. // "too many codes");
  1215. // Tracev((stderr, "\nbl counts: "));
  1216. zip_send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  1217. zip_send_bits(dcodes - 1, 5);
  1218. zip_send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  1219. for (rank = 0; rank < blcodes; rank++) {
  1220. // Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  1221. zip_send_bits(zip_bl_tree[zip_bl_order[rank]].dl, 3);
  1222. }
  1223. // send the literal tree
  1224. zip_send_tree(zip_dyn_ltree, lcodes - 1);
  1225. // send the distance tree
  1226. zip_send_tree(zip_dyn_dtree, dcodes - 1);
  1227. }
  1228. /* ==========================================================================
  1229. * Determine the best encoding for the current block: dynamic trees, static
  1230. * trees or store, and output the encoded block to the zip file.
  1231. */
  1232. function zip_flush_block(eof) { // true if this is the last block for a file
  1233. var opt_lenb, static_lenb; // opt_len and static_len in bytes
  1234. var max_blindex; // index of last bit length code of non zero freq
  1235. var stored_len; // length of input block
  1236. stored_len = zip_strstart - zip_block_start;
  1237. zip_flag_buf[zip_last_flags] = zip_flags; // Save the flags for the last 8 items
  1238. // Construct the literal and distance trees
  1239. zip_build_tree(zip_l_desc);
  1240. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld",
  1241. // encoder->opt_len, encoder->static_len));
  1242. zip_build_tree(zip_d_desc);
  1243. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld",
  1244. // encoder->opt_len, encoder->static_len));
  1245. /* At this point, opt_len and static_len are the total bit lengths of
  1246. * the compressed block data, excluding the tree representations.
  1247. */
  1248. /* Build the bit length tree for the above two trees, and get the index
  1249. * in bl_order of the last bit length code to send.
  1250. */
  1251. max_blindex = zip_build_bl_tree();
  1252. // Determine the best encoding. Compute first the block length in bytes
  1253. opt_lenb = (zip_opt_len + 3 + 7) >> 3;
  1254. static_lenb = (zip_static_len + 3 + 7) >> 3;
  1255. // Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  1256. // opt_lenb, encoder->opt_len,
  1257. // static_lenb, encoder->static_len, stored_len,
  1258. // encoder->last_lit, encoder->last_dist));
  1259. if (static_lenb <= opt_lenb)
  1260. opt_lenb = static_lenb;
  1261. if (stored_len + 4 <= opt_lenb // 4: two words for the lengths
  1262. && zip_block_start >= 0) {
  1263. var i;
  1264. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1265. * Otherwise we can't have processed more than WSIZE input bytes since
  1266. * the last block flush, because compression would have been
  1267. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1268. * transform a block into a stored block.
  1269. */
  1270. zip_send_bits((zip_STORED_BLOCK << 1) + eof, 3); /* send block type */
  1271. zip_bi_windup(); /* align on byte boundary */
  1272. zip_put_short(stored_len);
  1273. zip_put_short(~stored_len);
  1274. // copy block
  1275. /*
  1276. p = &window[block_start];
  1277. for(i = 0; i < stored_len; i++)
  1278. put_byte(p[i]);
  1279. */
  1280. for (i = 0; i < stored_len; i++)
  1281. zip_put_byte(zip_window[zip_block_start + i]);
  1282. } else if (static_lenb == opt_lenb) {
  1283. zip_send_bits((zip_STATIC_TREES << 1) + eof, 3);
  1284. zip_compress_block(zip_static_ltree, zip_static_dtree);
  1285. } else {
  1286. zip_send_bits((zip_DYN_TREES << 1) + eof, 3);
  1287. zip_send_all_trees(zip_l_desc.max_code + 1,
  1288. zip_d_desc.max_code + 1,
  1289. max_blindex + 1);
  1290. zip_compress_block(zip_dyn_ltree, zip_dyn_dtree);
  1291. }
  1292. zip_init_block();
  1293. if (eof != 0)
  1294. zip_bi_windup();
  1295. }
  1296. /* ==========================================================================
  1297. * Save the match info and tally the frequency counts. Return true if
  1298. * the current block must be flushed.
  1299. */
  1300. function zip_ct_tally(
  1301. dist, // distance of matched string
  1302. lc) { // match length-MIN_MATCH or unmatched char (if dist==0)
  1303. zip_l_buf[zip_last_lit++] = lc;
  1304. if (dist == 0) {
  1305. // lc is the unmatched char
  1306. zip_dyn_ltree[lc].fc++;
  1307. } else {
  1308. // Here, lc is the match length - MIN_MATCH
  1309. dist--; // dist = match distance - 1
  1310. // Assert((ush)dist < (ush)MAX_DIST &&
  1311. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  1312. // (ush)D_CODE(dist) < (ush)D_CODES, "ct_tally: bad match");
  1313. zip_dyn_ltree[zip_length_code[lc] + zip_LITERALS + 1].fc++;
  1314. zip_dyn_dtree[zip_D_CODE(dist)].fc++;
  1315. zip_d_buf[zip_last_dist++] = dist;
  1316. zip_flags |= zip_flag_bit;
  1317. }
  1318. zip_flag_bit <<= 1;
  1319. // Output the flags if they fill a byte
  1320. if ((zip_last_lit & 7) == 0) {
  1321. zip_flag_buf[zip_last_flags++] = zip_flags;
  1322. zip_flags = 0;
  1323. zip_flag_bit = 1;
  1324. }
  1325. // Try to guess if it is profitable to stop the current block here
  1326. if (zip_compr_level > 2 && (zip_last_lit & 0xfff) == 0) {
  1327. // Compute an upper bound for the compressed length
  1328. var out_length = zip_last_lit * 8;
  1329. var in_length = zip_strstart - zip_block_start;
  1330. var dcode;
  1331. for (dcode = 0; dcode < zip_D_CODES; dcode++) {
  1332. out_length += zip_dyn_dtree[dcode].fc * (5 + zip_extra_dbits[dcode]);
  1333. }
  1334. out_length >>= 3;
  1335. // Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  1336. // encoder->last_lit, encoder->last_dist, in_length, out_length,
  1337. // 100L - out_length*100L/in_length));
  1338. if (zip_last_dist < parseInt(zip_last_lit / 2) &&
  1339. out_length < parseInt(in_length / 2))
  1340. return true;
  1341. }
  1342. return (zip_last_lit == zip_LIT_BUFSIZE - 1 ||
  1343. zip_last_dist == zip_DIST_BUFSIZE);
  1344. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  1345. * on 16 bit machines and because stored blocks are restricted to
  1346. * 64K-1 bytes.
  1347. */
  1348. }
  1349. /* ==========================================================================
  1350. * Send the block data compressed using the given Huffman trees
  1351. */
  1352. function zip_compress_block(
  1353. ltree, // literal tree
  1354. dtree) { // distance tree
  1355. var dist; // distance of matched string
  1356. var lc; // match length or unmatched char (if dist == 0)
  1357. var lx = 0; // running index in l_buf
  1358. var dx = 0; // running index in d_buf
  1359. var fx = 0; // running index in flag_buf
  1360. var flag = 0; // current flags
  1361. var code; // the code to send
  1362. var extra; // number of extra bits to send
  1363. if (zip_last_lit != 0) do {
  1364. if ((lx & 7) == 0)
  1365. flag = zip_flag_buf[fx++];
  1366. lc = zip_l_buf[lx++] & 0xff;
  1367. if ((flag & 1) == 0) {
  1368. zip_SEND_CODE(lc, ltree); /* send a literal byte */
  1369. // Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  1370. } else {
  1371. // Here, lc is the match length - MIN_MATCH
  1372. code = zip_length_code[lc];
  1373. zip_SEND_CODE(code + zip_LITERALS + 1, ltree); // send the length code
  1374. extra = zip_extra_lbits[code];
  1375. if (extra != 0) {
  1376. lc -= zip_base_length[code];
  1377. zip_send_bits(lc, extra); // send the extra length bits
  1378. }
  1379. dist = zip_d_buf[dx++];
  1380. // Here, dist is the match distance - 1
  1381. code = zip_D_CODE(dist);
  1382. // Assert (code < D_CODES, "bad d_code");
  1383. zip_SEND_CODE(code, dtree); // send the distance code
  1384. extra = zip_extra_dbits[code];
  1385. if (extra != 0) {
  1386. dist -= zip_base_dist[code];
  1387. zip_send_bits(dist, extra); // send the extra distance bits
  1388. }
  1389. } // literal or match pair ?
  1390. flag >>= 1;
  1391. } while (lx < zip_last_lit);
  1392. zip_SEND_CODE(zip_END_BLOCK, ltree);
  1393. }
  1394. /* ==========================================================================
  1395. * Send a value on a given number of bits.
  1396. * IN assertion: length <= 16 and value fits in length bits.
  1397. */
  1398. var zip_Buf_size = 16; // bit size of bi_buf
  1399. function zip_send_bits(
  1400. value, // value to send
  1401. length) { // number of bits
  1402. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  1403. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  1404. * unused bits in value.
  1405. */
  1406. if (zip_bi_valid > zip_Buf_size - length) {
  1407. zip_bi_buf |= (value << zip_bi_valid);
  1408. zip_put_short(zip_bi_buf);
  1409. zip_bi_buf = (value >> (zip_Buf_size - zip_bi_valid));
  1410. zip_bi_valid += length - zip_Buf_size;
  1411. } else {
  1412. zip_bi_buf |= value << zip_bi_valid;
  1413. zip_bi_valid += length;
  1414. }
  1415. }
  1416. /* ==========================================================================
  1417. * Reverse the first len bits of a code, using straightforward code (a faster
  1418. * method would use a table)
  1419. * IN assertion: 1 <= len <= 15
  1420. */
  1421. function zip_bi_reverse(
  1422. code, // the value to invert
  1423. len) { // its bit length
  1424. var res = 0;
  1425. do {
  1426. res |= code & 1;
  1427. code >>= 1;
  1428. res <<= 1;
  1429. } while (--len > 0);
  1430. return res >> 1;
  1431. }
  1432. /* ==========================================================================
  1433. * Write out any remaining bits in an incomplete byte.
  1434. */
  1435. function zip_bi_windup() {
  1436. if (zip_bi_valid > 8) {
  1437. zip_put_short(zip_bi_buf);
  1438. } else if (zip_bi_valid > 0) {
  1439. zip_put_byte(zip_bi_buf);
  1440. }
  1441. zip_bi_buf = 0;
  1442. zip_bi_valid = 0;
  1443. }
  1444. function zip_qoutbuf() {
  1445. if (zip_outcnt != 0) {
  1446. var q, i;
  1447. q = zip_new_queue();
  1448. if (zip_qhead == null)
  1449. zip_qhead = zip_qtail = q;
  1450. else
  1451. zip_qtail = zip_qtail.next = q;
  1452. q.len = zip_outcnt - zip_outoff;
  1453. // System.arraycopy(zip_outbuf, zip_outoff, q.ptr, 0, q.len);
  1454. for (i = 0; i < q.len; i++)
  1455. q.ptr[i] = zip_outbuf[zip_outoff + i];
  1456. zip_outcnt = zip_outoff = 0;
  1457. }
  1458. }
  1459. return function deflate(str, level) {
  1460. var i, j;
  1461. zip_deflate_data = str;
  1462. zip_deflate_pos = 0;
  1463. if (typeof level == "undefined")
  1464. level = zip_DEFAULT_LEVEL;
  1465. zip_deflate_start(level);
  1466. var buff = new Array(1024);
  1467. var aout = [];
  1468. while ((i = zip_deflate_internal(buff, 0, buff.length)) > 0) {
  1469. var cbuf = new Array(i);
  1470. for (j = 0; j < i; j++) {
  1471. cbuf[j] = String.fromCharCode(buff[j]);
  1472. }
  1473. aout[aout.length] = cbuf.join("");
  1474. }
  1475. zip_deflate_data = null; // G.C.
  1476. return aout.join("");
  1477. };
  1478. })();