trees.c 43 KB

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