trees.c 43 KB

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