trees.c 44 KB

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