trees.c 43 KB

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