trees.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. /* trees.c -- output deflated data using Huffman coding
  2. * Copyright (C) 1995-2010 Jean-loup Gailly
  3. * detect_data_type() function provided freely by Cosmin Truta, 2006
  4. * For conditions of distribution and use, see copyright notice in zlib.h
  5. */
  6. /*
  7. * ALGORITHM
  8. *
  9. * The "deflation" process uses several Huffman trees. The more
  10. * common source values are represented by shorter bit sequences.
  11. *
  12. * Each code tree is stored in a compressed form which is itself
  13. * a Huffman encoding of the lengths of all the code strings (in
  14. * ascending order by source values). The actual code strings are
  15. * reconstructed from the lengths in the inflate process, as described
  16. * in the deflate specification.
  17. *
  18. * REFERENCES
  19. *
  20. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  21. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  22. *
  23. * Storer, James A.
  24. * Data Compression: Methods and Theory, pp. 49-50.
  25. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  26. *
  27. * Sedgewick, R.
  28. * Algorithms, p290.
  29. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  30. */
  31. /* @(#) $Id$ */
  32. /* #define GEN_TREES_H */
  33. #include "deflate.h"
  34. #ifdef DEBUG
  35. # include <ctype.h>
  36. #endif
  37. /* ===========================================================================
  38. * Constants
  39. */
  40. #define MAX_BL_BITS 7
  41. /* Bit length codes must not exceed MAX_BL_BITS bits */
  42. #define END_BLOCK 256
  43. /* end of block literal code */
  44. #define REP_3_6 16
  45. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  46. #define REPZ_3_10 17
  47. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  48. #define REPZ_11_138 18
  49. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  50. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  51. = {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};
  52. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  53. = {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};
  54. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  55. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  56. local const uch bl_order[BL_CODES]
  57. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  58. /* The lengths of the bit length codes are sent in order of decreasing
  59. * probability, to avoid transmitting the lengths for unused bit length codes.
  60. */
  61. #define Buf_size (8 * 2*sizeof(char))
  62. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  63. * more than 16 bits on some systems.)
  64. */
  65. /* ===========================================================================
  66. * Local data. These are initialized only once.
  67. */
  68. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  69. #if defined(GEN_TREES_H) || !defined(STDC)
  70. /* non ANSI compilers may not accept trees.h */
  71. local ct_data static_ltree[L_CODES+2];
  72. /* The static literal tree. Since the bit lengths are imposed, there is no
  73. * need for the L_CODES extra codes used during heap construction. However
  74. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  75. * below).
  76. */
  77. local ct_data static_dtree[D_CODES];
  78. /* The static distance tree. (Actually a trivial tree since all codes use
  79. * 5 bits.)
  80. */
  81. uch _dist_code[DIST_CODE_LEN];
  82. /* Distance codes. The first 256 values correspond to the distances
  83. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84. * the 15 bit distances.
  85. */
  86. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  87. /* length code for each normalized match length (0 == MIN_MATCH) */
  88. local int base_length[LENGTH_CODES];
  89. /* First normalized length for each code (0 = MIN_MATCH) */
  90. local int base_dist[D_CODES];
  91. /* First normalized distance for each code (0 = distance of 1) */
  92. #else
  93. # include "trees.h"
  94. #endif /* GEN_TREES_H */
  95. struct static_tree_desc_s {
  96. const ct_data *static_tree; /* static tree or NULL */
  97. const intf *extra_bits; /* extra bits for each code or NULL */
  98. int extra_base; /* base index for extra_bits */
  99. int elems; /* max number of elements in the tree */
  100. int max_length; /* max bit length for the codes */
  101. };
  102. local static_tree_desc static_l_desc =
  103. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  104. local static_tree_desc static_d_desc =
  105. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  106. local static_tree_desc static_bl_desc =
  107. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  108. /* ===========================================================================
  109. * Local (static) routines in this file.
  110. */
  111. local void tr_static_init OF((void));
  112. local void init_block OF((deflate_state *s));
  113. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  114. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  115. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  116. local void build_tree OF((deflate_state *s, tree_desc *desc));
  117. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  118. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  119. local int build_bl_tree OF((deflate_state *s));
  120. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  121. int blcodes));
  122. local void compress_block OF((deflate_state *s, ct_data *ltree,
  123. ct_data *dtree));
  124. local int detect_data_type OF((deflate_state *s));
  125. local unsigned bi_reverse OF((unsigned value, int length));
  126. local void bi_windup OF((deflate_state *s));
  127. local void bi_flush OF((deflate_state *s));
  128. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  129. int header));
  130. #ifdef GEN_TREES_H
  131. local void gen_trees_header OF((void));
  132. #endif
  133. #ifndef DEBUG
  134. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  135. /* Send a code of the given tree. c and tree must not have side effects */
  136. #else /* DEBUG */
  137. # define send_code(s, c, tree) \
  138. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  139. send_bits(s, tree[c].Code, tree[c].Len); }
  140. #endif
  141. /* ===========================================================================
  142. * Output a short LSB first on the stream.
  143. * IN assertion: there is enough room in pendingBuf.
  144. */
  145. #define put_short(s, w) { \
  146. put_byte(s, (uch)((w) & 0xff)); \
  147. put_byte(s, (uch)((ush)(w) >> 8)); \
  148. }
  149. /* ===========================================================================
  150. * Send a value on a given number of bits.
  151. * IN assertion: length <= 16 and value fits in length bits.
  152. */
  153. #ifdef DEBUG
  154. local void send_bits OF((deflate_state *s, int value, int length));
  155. local void send_bits(s, value, length)
  156. deflate_state *s;
  157. int value; /* value to send */
  158. int length; /* number of bits */
  159. {
  160. Tracevv((stderr," l %2d v %4x ", length, value));
  161. Assert(length > 0 && length <= 15, "invalid length");
  162. s->bits_sent += (ulg)length;
  163. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  164. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  165. * unused bits in value.
  166. */
  167. if (s->bi_valid > (int)Buf_size - length) {
  168. s->bi_buf |= (ush)value << s->bi_valid;
  169. put_short(s, s->bi_buf);
  170. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  171. s->bi_valid += length - Buf_size;
  172. } else {
  173. s->bi_buf |= (ush)value << s->bi_valid;
  174. s->bi_valid += length;
  175. }
  176. }
  177. #else /* !DEBUG */
  178. #define send_bits(s, value, length) \
  179. { int len = length;\
  180. if (s->bi_valid > (int)Buf_size - len) {\
  181. int val = value;\
  182. s->bi_buf |= (ush)val << s->bi_valid;\
  183. put_short(s, s->bi_buf);\
  184. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  185. s->bi_valid += len - Buf_size;\
  186. } else {\
  187. s->bi_buf |= (ush)(value) << s->bi_valid;\
  188. s->bi_valid += len;\
  189. }\
  190. }
  191. #endif /* DEBUG */
  192. /* the arguments must not have side effects */
  193. /* ===========================================================================
  194. * Initialize the various 'constant' tables.
  195. */
  196. local void tr_static_init()
  197. {
  198. #if defined(GEN_TREES_H) || !defined(STDC)
  199. static int static_init_done = 0;
  200. int n; /* iterates over tree elements */
  201. int bits; /* bit counter */
  202. int length; /* length value */
  203. int code; /* code value */
  204. int dist; /* distance index */
  205. ush bl_count[MAX_BITS+1];
  206. /* number of codes at each bit length for an optimal tree */
  207. if (static_init_done) return;
  208. /* For some embedded targets, global variables are not initialized: */
  209. #ifdef NO_INIT_GLOBAL_POINTERS
  210. static_l_desc.static_tree = static_ltree;
  211. static_l_desc.extra_bits = extra_lbits;
  212. static_d_desc.static_tree = static_dtree;
  213. static_d_desc.extra_bits = extra_dbits;
  214. static_bl_desc.extra_bits = extra_blbits;
  215. #endif
  216. /* Initialize the mapping length (0..255) -> length code (0..28) */
  217. length = 0;
  218. for (code = 0; code < LENGTH_CODES-1; code++) {
  219. base_length[code] = length;
  220. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  221. _length_code[length++] = (uch)code;
  222. }
  223. }
  224. Assert (length == 256, "tr_static_init: length != 256");
  225. /* Note that the length 255 (match length 258) can be represented
  226. * in two different ways: code 284 + 5 bits or code 285, so we
  227. * overwrite length_code[255] to use the best encoding:
  228. */
  229. _length_code[length-1] = (uch)code;
  230. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  231. dist = 0;
  232. for (code = 0 ; code < 16; code++) {
  233. base_dist[code] = dist;
  234. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  235. _dist_code[dist++] = (uch)code;
  236. }
  237. }
  238. Assert (dist == 256, "tr_static_init: dist != 256");
  239. dist >>= 7; /* from now on, all distances are divided by 128 */
  240. for ( ; code < D_CODES; code++) {
  241. base_dist[code] = dist << 7;
  242. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  243. _dist_code[256 + dist++] = (uch)code;
  244. }
  245. }
  246. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  247. /* Construct the codes of the static literal tree */
  248. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  249. n = 0;
  250. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  251. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  252. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  253. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  254. /* Codes 286 and 287 do not exist, but we must include them in the
  255. * tree construction to get a canonical Huffman tree (longest code
  256. * all ones)
  257. */
  258. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  259. /* The static distance tree is trivial: */
  260. for (n = 0; n < D_CODES; n++) {
  261. static_dtree[n].Len = 5;
  262. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  263. }
  264. static_init_done = 1;
  265. # ifdef GEN_TREES_H
  266. gen_trees_header();
  267. # endif
  268. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  269. }
  270. /* ===========================================================================
  271. * Genererate the file trees.h describing the static trees.
  272. */
  273. #ifdef GEN_TREES_H
  274. # ifndef DEBUG
  275. # include <stdio.h>
  276. # endif
  277. # define SEPARATOR(i, last, width) \
  278. ((i) == (last)? "\n};\n\n" : \
  279. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  280. void gen_trees_header()
  281. {
  282. FILE *header = fopen("trees.h", "w");
  283. int i;
  284. Assert (header != NULL, "Can't open trees.h");
  285. fprintf(header,
  286. "/* header created automatically with -DGEN_TREES_H */\n\n");
  287. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  288. for (i = 0; i < L_CODES+2; i++) {
  289. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  290. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  291. }
  292. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  293. for (i = 0; i < D_CODES; i++) {
  294. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  295. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  296. }
  297. fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
  298. for (i = 0; i < DIST_CODE_LEN; i++) {
  299. fprintf(header, "%2u%s", _dist_code[i],
  300. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  301. }
  302. fprintf(header,
  303. "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  304. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  305. fprintf(header, "%2u%s", _length_code[i],
  306. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  307. }
  308. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  309. for (i = 0; i < LENGTH_CODES; i++) {
  310. fprintf(header, "%1u%s", base_length[i],
  311. SEPARATOR(i, LENGTH_CODES-1, 20));
  312. }
  313. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  314. for (i = 0; i < D_CODES; i++) {
  315. fprintf(header, "%5u%s", base_dist[i],
  316. SEPARATOR(i, D_CODES-1, 10));
  317. }
  318. fclose(header);
  319. }
  320. #endif /* GEN_TREES_H */
  321. /* ===========================================================================
  322. * Initialize the tree data structures for a new zlib stream.
  323. */
  324. void ZLIB_INTERNAL _tr_init(s)
  325. deflate_state *s;
  326. {
  327. tr_static_init();
  328. s->l_desc.dyn_tree = s->dyn_ltree;
  329. s->l_desc.stat_desc = &static_l_desc;
  330. s->d_desc.dyn_tree = s->dyn_dtree;
  331. s->d_desc.stat_desc = &static_d_desc;
  332. s->bl_desc.dyn_tree = s->bl_tree;
  333. s->bl_desc.stat_desc = &static_bl_desc;
  334. s->bi_buf = 0;
  335. s->bi_valid = 0;
  336. s->last_eob_len = 8; /* enough lookahead for inflate */
  337. #ifdef DEBUG
  338. s->compressed_len = 0L;
  339. s->bits_sent = 0L;
  340. #endif
  341. /* Initialize the first block of the first file: */
  342. init_block(s);
  343. }
  344. /* ===========================================================================
  345. * Initialize a new block.
  346. */
  347. local void init_block(s)
  348. deflate_state *s;
  349. {
  350. int n; /* iterates over tree elements */
  351. /* Initialize the trees. */
  352. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  353. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  354. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  355. s->dyn_ltree[END_BLOCK].Freq = 1;
  356. s->opt_len = s->static_len = 0L;
  357. s->last_lit = s->matches = 0;
  358. }
  359. #define SMALLEST 1
  360. /* Index within the heap array of least frequent node in the Huffman tree */
  361. /* ===========================================================================
  362. * Remove the smallest element from the heap and recreate the heap with
  363. * one less element. Updates heap and heap_len.
  364. */
  365. #define pqremove(s, tree, top) \
  366. {\
  367. top = s->heap[SMALLEST]; \
  368. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  369. pqdownheap(s, tree, SMALLEST); \
  370. }
  371. /* ===========================================================================
  372. * Compares to subtrees, using the tree depth as tie breaker when
  373. * the subtrees have equal frequency. This minimizes the worst case length.
  374. */
  375. #define smaller(tree, n, m, depth) \
  376. (tree[n].Freq < tree[m].Freq || \
  377. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  378. /* ===========================================================================
  379. * Restore the heap property by moving down the tree starting at node k,
  380. * exchanging a node with the smallest of its two sons if necessary, stopping
  381. * when the heap property is re-established (each father smaller than its
  382. * two sons).
  383. */
  384. local void pqdownheap(s, tree, k)
  385. deflate_state *s;
  386. ct_data *tree; /* the tree to restore */
  387. int k; /* node to move down */
  388. {
  389. int v = s->heap[k];
  390. int j = k << 1; /* left son of k */
  391. while (j <= s->heap_len) {
  392. /* Set j to the smallest of the two sons: */
  393. if (j < s->heap_len &&
  394. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  395. j++;
  396. }
  397. /* Exit if v is smaller than both sons */
  398. if (smaller(tree, v, s->heap[j], s->depth)) break;
  399. /* Exchange v with the smallest son */
  400. s->heap[k] = s->heap[j]; k = j;
  401. /* And continue down the tree, setting j to the left son of k */
  402. j <<= 1;
  403. }
  404. s->heap[k] = v;
  405. }
  406. /* ===========================================================================
  407. * Compute the optimal bit lengths for a tree and update the total bit length
  408. * for the current block.
  409. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  410. * above are the tree nodes sorted by increasing frequency.
  411. * OUT assertions: the field len is set to the optimal bit length, the
  412. * array bl_count contains the frequencies for each bit length.
  413. * The length opt_len is updated; static_len is also updated if stree is
  414. * not null.
  415. */
  416. local void gen_bitlen(s, desc)
  417. deflate_state *s;
  418. tree_desc *desc; /* the tree descriptor */
  419. {
  420. ct_data *tree = desc->dyn_tree;
  421. int max_code = desc->max_code;
  422. const ct_data *stree = desc->stat_desc->static_tree;
  423. const intf *extra = desc->stat_desc->extra_bits;
  424. int base = desc->stat_desc->extra_base;
  425. int max_length = desc->stat_desc->max_length;
  426. int h; /* heap index */
  427. int n, m; /* iterate over the tree elements */
  428. int bits; /* bit length */
  429. int xbits; /* extra bits */
  430. ush f; /* frequency */
  431. int overflow = 0; /* number of elements with bit length too large */
  432. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  433. /* In a first pass, compute the optimal bit lengths (which may
  434. * overflow in the case of the bit length tree).
  435. */
  436. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  437. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  438. n = s->heap[h];
  439. bits = tree[tree[n].Dad].Len + 1;
  440. if (bits > max_length) bits = max_length, overflow++;
  441. tree[n].Len = (ush)bits;
  442. /* We overwrite tree[n].Dad which is no longer needed */
  443. if (n > max_code) continue; /* not a leaf node */
  444. s->bl_count[bits]++;
  445. xbits = 0;
  446. if (n >= base) xbits = extra[n-base];
  447. f = tree[n].Freq;
  448. s->opt_len += (ulg)f * (bits + xbits);
  449. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  450. }
  451. if (overflow == 0) return;
  452. Trace((stderr,"\nbit length overflow\n"));
  453. /* This happens for example on obj2 and pic of the Calgary corpus */
  454. /* Find the first bit length which could increase: */
  455. do {
  456. bits = max_length-1;
  457. while (s->bl_count[bits] == 0) bits--;
  458. s->bl_count[bits]--; /* move one leaf down the tree */
  459. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  460. s->bl_count[max_length]--;
  461. /* The brother of the overflow item also moves one step up,
  462. * but this does not affect bl_count[max_length]
  463. */
  464. overflow -= 2;
  465. } while (overflow > 0);
  466. /* Now recompute all bit lengths, scanning in increasing frequency.
  467. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  468. * lengths instead of fixing only the wrong ones. This idea is taken
  469. * from 'ar' written by Haruhiko Okumura.)
  470. */
  471. for (bits = max_length; bits != 0; bits--) {
  472. n = s->bl_count[bits];
  473. while (n != 0) {
  474. m = s->heap[--h];
  475. if (m > max_code) continue;
  476. if ((unsigned) tree[m].Len != (unsigned) bits) {
  477. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  478. s->opt_len += ((long)bits - (long)tree[m].Len)
  479. *(long)tree[m].Freq;
  480. tree[m].Len = (ush)bits;
  481. }
  482. n--;
  483. }
  484. }
  485. }
  486. /* ===========================================================================
  487. * Generate the codes for a given tree and bit counts (which need not be
  488. * optimal).
  489. * IN assertion: the array bl_count contains the bit length statistics for
  490. * the given tree and the field len is set for all tree elements.
  491. * OUT assertion: the field code is set for all tree elements of non
  492. * zero code length.
  493. */
  494. local void gen_codes (tree, max_code, bl_count)
  495. ct_data *tree; /* the tree to decorate */
  496. int max_code; /* largest code with non zero frequency */
  497. ushf *bl_count; /* number of codes at each bit length */
  498. {
  499. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  500. ush code = 0; /* running code value */
  501. int bits; /* bit index */
  502. int n; /* code index */
  503. /* The distribution counts are first used to generate the code values
  504. * without bit reversal.
  505. */
  506. for (bits = 1; bits <= MAX_BITS; bits++) {
  507. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  508. }
  509. /* Check that the bit counts in bl_count are consistent. The last code
  510. * must be all ones.
  511. */
  512. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  513. "inconsistent bit counts");
  514. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  515. for (n = 0; n <= max_code; n++) {
  516. int len = tree[n].Len;
  517. if (len == 0) continue;
  518. /* Now reverse the bits */
  519. tree[n].Code = bi_reverse(next_code[len]++, len);
  520. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  521. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  522. }
  523. }
  524. /* ===========================================================================
  525. * Construct one Huffman tree and assigns the code bit strings and lengths.
  526. * Update the total bit length for the current block.
  527. * IN assertion: the field freq is set for all tree elements.
  528. * OUT assertions: the fields len and code are set to the optimal bit length
  529. * and corresponding code. The length opt_len is updated; static_len is
  530. * also updated if stree is not null. The field max_code is set.
  531. */
  532. local void build_tree(s, desc)
  533. deflate_state *s;
  534. tree_desc *desc; /* the tree descriptor */
  535. {
  536. ct_data *tree = desc->dyn_tree;
  537. const ct_data *stree = desc->stat_desc->static_tree;
  538. int elems = desc->stat_desc->elems;
  539. int n, m; /* iterate over heap elements */
  540. int max_code = -1; /* largest code with non zero frequency */
  541. int node; /* new node being created */
  542. /* Construct the initial heap, with least frequent element in
  543. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  544. * heap[0] is not used.
  545. */
  546. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  547. for (n = 0; n < elems; n++) {
  548. if (tree[n].Freq != 0) {
  549. s->heap[++(s->heap_len)] = max_code = n;
  550. s->depth[n] = 0;
  551. } else {
  552. tree[n].Len = 0;
  553. }
  554. }
  555. /* The pkzip format requires that at least one distance code exists,
  556. * and that at least one bit should be sent even if there is only one
  557. * possible code. So to avoid special checks later on we force at least
  558. * two codes of non zero frequency.
  559. */
  560. while (s->heap_len < 2) {
  561. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  562. tree[node].Freq = 1;
  563. s->depth[node] = 0;
  564. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  565. /* node is 0 or 1 so it does not have extra bits */
  566. }
  567. desc->max_code = max_code;
  568. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  569. * establish sub-heaps of increasing lengths:
  570. */
  571. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  572. /* Construct the Huffman tree by repeatedly combining the least two
  573. * frequent nodes.
  574. */
  575. node = elems; /* next internal node of the tree */
  576. do {
  577. pqremove(s, tree, n); /* n = node of least frequency */
  578. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  579. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  580. s->heap[--(s->heap_max)] = m;
  581. /* Create a new node father of n and m */
  582. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  583. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  584. s->depth[n] : s->depth[m]) + 1);
  585. tree[n].Dad = tree[m].Dad = (ush)node;
  586. #ifdef DUMP_BL_TREE
  587. if (tree == s->bl_tree) {
  588. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  589. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  590. }
  591. #endif
  592. /* and insert the new node in the heap */
  593. s->heap[SMALLEST] = node++;
  594. pqdownheap(s, tree, SMALLEST);
  595. } while (s->heap_len >= 2);
  596. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  597. /* At this point, the fields freq and dad are set. We can now
  598. * generate the bit lengths.
  599. */
  600. gen_bitlen(s, (tree_desc *)desc);
  601. /* The field len is now set, we can generate the bit codes */
  602. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  603. }
  604. /* ===========================================================================
  605. * Scan a literal or distance tree to determine the frequencies of the codes
  606. * in the bit length tree.
  607. */
  608. local void scan_tree (s, tree, max_code)
  609. deflate_state *s;
  610. ct_data *tree; /* the tree to be scanned */
  611. int max_code; /* and its largest code of non zero frequency */
  612. {
  613. int n; /* iterates over all tree elements */
  614. int prevlen = -1; /* last emitted length */
  615. int curlen; /* length of current code */
  616. int nextlen = tree[0].Len; /* length of next code */
  617. int count = 0; /* repeat count of the current code */
  618. int max_count = 7; /* max repeat count */
  619. int min_count = 4; /* min repeat count */
  620. if (nextlen == 0) max_count = 138, min_count = 3;
  621. tree[max_code+1].Len = (ush)0xffff; /* guard */
  622. for (n = 0; n <= max_code; n++) {
  623. curlen = nextlen; nextlen = tree[n+1].Len;
  624. if (++count < max_count && curlen == nextlen) {
  625. continue;
  626. } else if (count < min_count) {
  627. s->bl_tree[curlen].Freq += count;
  628. } else if (curlen != 0) {
  629. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  630. s->bl_tree[REP_3_6].Freq++;
  631. } else if (count <= 10) {
  632. s->bl_tree[REPZ_3_10].Freq++;
  633. } else {
  634. s->bl_tree[REPZ_11_138].Freq++;
  635. }
  636. count = 0; prevlen = curlen;
  637. if (nextlen == 0) {
  638. max_count = 138, min_count = 3;
  639. } else if (curlen == nextlen) {
  640. max_count = 6, min_count = 3;
  641. } else {
  642. max_count = 7, min_count = 4;
  643. }
  644. }
  645. }
  646. /* ===========================================================================
  647. * Send a literal or distance tree in compressed form, using the codes in
  648. * bl_tree.
  649. */
  650. local void send_tree (s, tree, max_code)
  651. deflate_state *s;
  652. ct_data *tree; /* the tree to be scanned */
  653. int max_code; /* and its largest code of non zero frequency */
  654. {
  655. int n; /* iterates over all tree elements */
  656. int prevlen = -1; /* last emitted length */
  657. int curlen; /* length of current code */
  658. int nextlen = tree[0].Len; /* length of next code */
  659. int count = 0; /* repeat count of the current code */
  660. int max_count = 7; /* max repeat count */
  661. int min_count = 4; /* min repeat count */
  662. /* tree[max_code+1].Len = -1; */ /* guard already set */
  663. if (nextlen == 0) max_count = 138, min_count = 3;
  664. for (n = 0; n <= max_code; n++) {
  665. curlen = nextlen; nextlen = tree[n+1].Len;
  666. if (++count < max_count && curlen == nextlen) {
  667. continue;
  668. } else if (count < min_count) {
  669. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  670. } else if (curlen != 0) {
  671. if (curlen != prevlen) {
  672. send_code(s, curlen, s->bl_tree); count--;
  673. }
  674. Assert(count >= 3 && count <= 6, " 3_6?");
  675. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  676. } else if (count <= 10) {
  677. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  678. } else {
  679. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  680. }
  681. count = 0; prevlen = curlen;
  682. if (nextlen == 0) {
  683. max_count = 138, min_count = 3;
  684. } else if (curlen == nextlen) {
  685. max_count = 6, min_count = 3;
  686. } else {
  687. max_count = 7, min_count = 4;
  688. }
  689. }
  690. }
  691. /* ===========================================================================
  692. * Construct the Huffman tree for the bit lengths and return the index in
  693. * bl_order of the last bit length code to send.
  694. */
  695. local int build_bl_tree(s)
  696. deflate_state *s;
  697. {
  698. int max_blindex; /* index of last bit length code of non zero freq */
  699. /* Determine the bit length frequencies for literal and distance trees */
  700. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  701. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  702. /* Build the bit length tree: */
  703. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  704. /* opt_len now includes the length of the tree representations, except
  705. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  706. */
  707. /* Determine the number of bit length codes to send. The pkzip format
  708. * requires that at least 4 bit length codes be sent. (appnote.txt says
  709. * 3 but the actual value used is 4.)
  710. */
  711. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  712. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  713. }
  714. /* Update opt_len to include the bit length tree and counts */
  715. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  716. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  717. s->opt_len, s->static_len));
  718. return max_blindex;
  719. }
  720. /* ===========================================================================
  721. * Send the header for a block using dynamic Huffman trees: the counts, the
  722. * lengths of the bit length codes, the literal tree and the distance tree.
  723. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  724. */
  725. local void send_all_trees(s, lcodes, dcodes, blcodes)
  726. deflate_state *s;
  727. int lcodes, dcodes, blcodes; /* number of codes for each tree */
  728. {
  729. int rank; /* index in bl_order */
  730. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  731. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  732. "too many codes");
  733. Tracev((stderr, "\nbl counts: "));
  734. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  735. send_bits(s, dcodes-1, 5);
  736. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  737. for (rank = 0; rank < blcodes; rank++) {
  738. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  739. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  740. }
  741. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  742. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  743. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  744. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  745. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  746. }
  747. /* ===========================================================================
  748. * Send a stored block
  749. */
  750. void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
  751. deflate_state *s;
  752. charf *buf; /* input block */
  753. ulg stored_len; /* length of input block */
  754. int last; /* one if this is the last block for a file */
  755. {
  756. send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */
  757. #ifdef DEBUG
  758. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  759. s->compressed_len += (stored_len + 4) << 3;
  760. #endif
  761. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  762. }
  763. /* ===========================================================================
  764. * Send one empty static block to give enough lookahead for inflate.
  765. * This takes 10 bits, of which 7 may remain in the bit buffer.
  766. * The current inflate code requires 9 bits of lookahead. If the
  767. * last two codes for the previous block (real code plus EOB) were coded
  768. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  769. * the last real code. In this case we send two empty static blocks instead
  770. * of one. (There are no problems if the previous block is stored or fixed.)
  771. * To simplify the code, we assume the worst case of last real code encoded
  772. * on one bit only.
  773. */
  774. void ZLIB_INTERNAL _tr_align(s)
  775. deflate_state *s;
  776. {
  777. send_bits(s, STATIC_TREES<<1, 3);
  778. send_code(s, END_BLOCK, static_ltree);
  779. #ifdef DEBUG
  780. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  781. #endif
  782. bi_flush(s);
  783. /* Of the 10 bits for the empty block, we have already sent
  784. * (10 - bi_valid) bits. The lookahead for the last real code (before
  785. * the EOB of the previous block) was thus at least one plus the length
  786. * of the EOB plus what we have just sent of the empty static block.
  787. */
  788. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  789. send_bits(s, STATIC_TREES<<1, 3);
  790. send_code(s, END_BLOCK, static_ltree);
  791. #ifdef DEBUG
  792. s->compressed_len += 10L;
  793. #endif
  794. bi_flush(s);
  795. }
  796. s->last_eob_len = 7;
  797. }
  798. /* ===========================================================================
  799. * Determine the best encoding for the current block: dynamic trees, static
  800. * trees or store, and output the encoded block to the zip file.
  801. */
  802. void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
  803. deflate_state *s;
  804. charf *buf; /* input block, or NULL if too old */
  805. ulg stored_len; /* length of input block */
  806. int last; /* one if this is the last block for a file */
  807. {
  808. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  809. int max_blindex = 0; /* index of last bit length code of non zero freq */
  810. /* Build the Huffman trees unless a stored block is forced */
  811. if (s->level > 0) {
  812. /* Check if the file is binary or text */
  813. if (s->strm->data_type == Z_UNKNOWN)
  814. s->strm->data_type = detect_data_type(s);
  815. /* Construct the literal and distance trees */
  816. build_tree(s, (tree_desc *)(&(s->l_desc)));
  817. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  818. s->static_len));
  819. build_tree(s, (tree_desc *)(&(s->d_desc)));
  820. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  821. s->static_len));
  822. /* At this point, opt_len and static_len are the total bit lengths of
  823. * the compressed block data, excluding the tree representations.
  824. */
  825. /* Build the bit length tree for the above two trees, and get the index
  826. * in bl_order of the last bit length code to send.
  827. */
  828. max_blindex = build_bl_tree(s);
  829. /* Determine the best encoding. Compute the block lengths in bytes. */
  830. opt_lenb = (s->opt_len+3+7)>>3;
  831. static_lenb = (s->static_len+3+7)>>3;
  832. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  833. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  834. s->last_lit));
  835. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  836. } else {
  837. Assert(buf != (char*)0, "lost buf");
  838. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  839. }
  840. #ifdef FORCE_STORED
  841. if (buf != (char*)0) { /* force stored block */
  842. #else
  843. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  844. /* 4: two words for the lengths */
  845. #endif
  846. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  847. * Otherwise we can't have processed more than WSIZE input bytes since
  848. * the last block flush, because compression would have been
  849. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  850. * transform a block into a stored block.
  851. */
  852. _tr_stored_block(s, buf, stored_len, last);
  853. #ifdef FORCE_STATIC
  854. } else if (static_lenb >= 0) { /* force static trees */
  855. #else
  856. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  857. #endif
  858. send_bits(s, (STATIC_TREES<<1)+last, 3);
  859. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  860. #ifdef DEBUG
  861. s->compressed_len += 3 + s->static_len;
  862. #endif
  863. } else {
  864. send_bits(s, (DYN_TREES<<1)+last, 3);
  865. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  866. max_blindex+1);
  867. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  868. #ifdef DEBUG
  869. s->compressed_len += 3 + s->opt_len;
  870. #endif
  871. }
  872. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  873. /* The above check is made mod 2^32, for files larger than 512 MB
  874. * and uLong implemented on 32 bits.
  875. */
  876. init_block(s);
  877. if (last) {
  878. bi_windup(s);
  879. #ifdef DEBUG
  880. s->compressed_len += 7; /* align on byte boundary */
  881. #endif
  882. }
  883. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  884. s->compressed_len-7*last));
  885. }
  886. /* ===========================================================================
  887. * Save the match info and tally the frequency counts. Return true if
  888. * the current block must be flushed.
  889. */
  890. int ZLIB_INTERNAL _tr_tally (s, dist, lc)
  891. deflate_state *s;
  892. unsigned dist; /* distance of matched string */
  893. unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  894. {
  895. s->d_buf[s->last_lit] = (ush)dist;
  896. s->l_buf[s->last_lit++] = (uch)lc;
  897. if (dist == 0) {
  898. /* lc is the unmatched char */
  899. s->dyn_ltree[lc].Freq++;
  900. } else {
  901. s->matches++;
  902. /* Here, lc is the match length - MIN_MATCH */
  903. dist--; /* dist = match distance - 1 */
  904. Assert((ush)dist < (ush)MAX_DIST(s) &&
  905. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  906. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  907. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  908. s->dyn_dtree[d_code(dist)].Freq++;
  909. }
  910. #ifdef TRUNCATE_BLOCK
  911. /* Try to guess if it is profitable to stop the current block here */
  912. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  913. /* Compute an upper bound for the compressed length */
  914. ulg out_length = (ulg)s->last_lit*8L;
  915. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  916. int dcode;
  917. for (dcode = 0; dcode < D_CODES; dcode++) {
  918. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  919. (5L+extra_dbits[dcode]);
  920. }
  921. out_length >>= 3;
  922. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  923. s->last_lit, in_length, out_length,
  924. 100L - out_length*100L/in_length));
  925. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  926. }
  927. #endif
  928. return (s->last_lit == s->lit_bufsize-1);
  929. /* We avoid equality with lit_bufsize because of wraparound at 64K
  930. * on 16 bit machines and because stored blocks are restricted to
  931. * 64K-1 bytes.
  932. */
  933. }
  934. /* ===========================================================================
  935. * Send the block data compressed using the given Huffman trees
  936. */
  937. local void compress_block(s, ltree, dtree)
  938. deflate_state *s;
  939. ct_data *ltree; /* literal tree */
  940. ct_data *dtree; /* distance tree */
  941. {
  942. unsigned dist; /* distance of matched string */
  943. int lc; /* match length or unmatched char (if dist == 0) */
  944. unsigned lx = 0; /* running index in l_buf */
  945. unsigned code; /* the code to send */
  946. int extra; /* number of extra bits to send */
  947. if (s->last_lit != 0) do {
  948. dist = s->d_buf[lx];
  949. lc = s->l_buf[lx++];
  950. if (dist == 0) {
  951. send_code(s, lc, ltree); /* send a literal byte */
  952. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  953. } else {
  954. /* Here, lc is the match length - MIN_MATCH */
  955. code = _length_code[lc];
  956. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  957. extra = extra_lbits[code];
  958. if (extra != 0) {
  959. lc -= base_length[code];
  960. send_bits(s, lc, extra); /* send the extra length bits */
  961. }
  962. dist--; /* dist is now the match distance - 1 */
  963. code = d_code(dist);
  964. Assert (code < D_CODES, "bad d_code");
  965. send_code(s, code, dtree); /* send the distance code */
  966. extra = extra_dbits[code];
  967. if (extra != 0) {
  968. dist -= base_dist[code];
  969. send_bits(s, dist, extra); /* send the extra distance bits */
  970. }
  971. } /* literal or match pair ? */
  972. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  973. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  974. "pendingBuf overflow");
  975. } while (lx < s->last_lit);
  976. send_code(s, END_BLOCK, ltree);
  977. s->last_eob_len = ltree[END_BLOCK].Len;
  978. }
  979. /* ===========================================================================
  980. * Check if the data type is TEXT or BINARY, using the following algorithm:
  981. * - TEXT if the two conditions below are satisfied:
  982. * a) There are no non-portable control characters belonging to the
  983. * "black list" (0..6, 14..25, 28..31).
  984. * b) There is at least one printable character belonging to the
  985. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  986. * - BINARY otherwise.
  987. * - The following partially-portable control characters form a
  988. * "gray list" that is ignored in this detection algorithm:
  989. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  990. * IN assertion: the fields Freq of dyn_ltree are set.
  991. */
  992. local int detect_data_type(s)
  993. deflate_state *s;
  994. {
  995. /* black_mask is the bit mask of black-listed bytes
  996. * set bits 0..6, 14..25, and 28..31
  997. * 0xf3ffc07f = binary 11110011111111111100000001111111
  998. */
  999. unsigned long black_mask = 0xf3ffc07fUL;
  1000. int n;
  1001. /* Check for non-textual ("black-listed") bytes. */
  1002. for (n = 0; n <= 31; n++, black_mask >>= 1)
  1003. if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
  1004. return Z_BINARY;
  1005. /* Check for textual ("white-listed") bytes. */
  1006. if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
  1007. || s->dyn_ltree[13].Freq != 0)
  1008. return Z_TEXT;
  1009. for (n = 32; n < LITERALS; n++)
  1010. if (s->dyn_ltree[n].Freq != 0)
  1011. return Z_TEXT;
  1012. /* There are no "black-listed" or "white-listed" bytes:
  1013. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  1014. */
  1015. return Z_BINARY;
  1016. }
  1017. /* ===========================================================================
  1018. * Reverse the first len bits of a code, using straightforward code (a faster
  1019. * method would use a table)
  1020. * IN assertion: 1 <= len <= 15
  1021. */
  1022. local unsigned bi_reverse(code, len)
  1023. unsigned code; /* the value to invert */
  1024. int len; /* its bit length */
  1025. {
  1026. register unsigned res = 0;
  1027. do {
  1028. res |= code & 1;
  1029. code >>= 1, res <<= 1;
  1030. } while (--len > 0);
  1031. return res >> 1;
  1032. }
  1033. /* ===========================================================================
  1034. * Flush the bit buffer, keeping at most 7 bits in it.
  1035. */
  1036. local void bi_flush(s)
  1037. deflate_state *s;
  1038. {
  1039. if (s->bi_valid == 16) {
  1040. put_short(s, s->bi_buf);
  1041. s->bi_buf = 0;
  1042. s->bi_valid = 0;
  1043. } else if (s->bi_valid >= 8) {
  1044. put_byte(s, (Byte)s->bi_buf);
  1045. s->bi_buf >>= 8;
  1046. s->bi_valid -= 8;
  1047. }
  1048. }
  1049. /* ===========================================================================
  1050. * Flush the bit buffer and align the output on a byte boundary
  1051. */
  1052. local void bi_windup(s)
  1053. deflate_state *s;
  1054. {
  1055. if (s->bi_valid > 8) {
  1056. put_short(s, s->bi_buf);
  1057. } else if (s->bi_valid > 0) {
  1058. put_byte(s, (Byte)s->bi_buf);
  1059. }
  1060. s->bi_buf = 0;
  1061. s->bi_valid = 0;
  1062. #ifdef DEBUG
  1063. s->bits_sent = (s->bits_sent+7) & ~7;
  1064. #endif
  1065. }
  1066. /* ===========================================================================
  1067. * Copy a stored block, storing first the length and its
  1068. * one's complement if requested.
  1069. */
  1070. local void copy_block(s, buf, len, header)
  1071. deflate_state *s;
  1072. charf *buf; /* the input data */
  1073. unsigned len; /* its length */
  1074. int header; /* true if block header must be written */
  1075. {
  1076. bi_windup(s); /* align on byte boundary */
  1077. s->last_eob_len = 8; /* enough lookahead for inflate */
  1078. if (header) {
  1079. put_short(s, (ush)len);
  1080. put_short(s, (ush)~len);
  1081. #ifdef DEBUG
  1082. s->bits_sent += 2*16;
  1083. #endif
  1084. }
  1085. #ifdef DEBUG
  1086. s->bits_sent += (ulg)len<<3;
  1087. #endif
  1088. while (len--) {
  1089. put_byte(s, *buf++);
  1090. }
  1091. }