trees.c 43 KB

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