deftree.c 40 KB

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