trees.c 44 KB

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