trees.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. /* trees.c -- output deflated data using Huffman coding
  2. * Copyright (C) 1995-2024 Jean-loup Gailly
  3. * detect_data_type() function provided freely by Cosmin Truta, 2006
  4. * For conditions of distribution and use, see copyright notice in zlib.h
  5. */
  6. /*
  7. * ALGORITHM
  8. *
  9. * The "deflation" process uses several Huffman trees. The more
  10. * common source values are represented by shorter bit sequences.
  11. *
  12. * Each code tree is stored in a compressed form which is itself
  13. * a Huffman encoding of the lengths of all the code strings (in
  14. * ascending order by source values). The actual code strings are
  15. * reconstructed from the lengths in the inflate process, as described
  16. * in the deflate specification.
  17. *
  18. * REFERENCES
  19. *
  20. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  21. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  22. *
  23. * Storer, James A.
  24. * Data Compression: Methods and Theory, pp. 49-50.
  25. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  26. *
  27. * Sedgewick, R.
  28. * Algorithms, p290.
  29. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  30. */
  31. #include "zbuild.h"
  32. #include "deflate.h"
  33. #include "trees.h"
  34. #include "trees_emit.h"
  35. #include "trees_tbl.h"
  36. /* The lengths of the bit length codes are sent in order of decreasing
  37. * probability, to avoid transmitting the lengths for unused bit length codes.
  38. */
  39. /* ===========================================================================
  40. * Local data. These are initialized only once.
  41. */
  42. struct static_tree_desc_s {
  43. const ct_data *static_tree; /* static tree or NULL */
  44. const int *extra_bits; /* extra bits for each code or NULL */
  45. int extra_base; /* base index for extra_bits */
  46. int elems; /* max number of elements in the tree */
  47. unsigned int max_length; /* max bit length for the codes */
  48. };
  49. static const static_tree_desc static_l_desc =
  50. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  51. static const static_tree_desc static_d_desc =
  52. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  53. static const static_tree_desc static_bl_desc =
  54. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  55. /* ===========================================================================
  56. * Local (static) routines in this file.
  57. */
  58. static void init_block (deflate_state *s);
  59. static void pqdownheap (deflate_state *s, ct_data *tree, int k);
  60. static void gen_bitlen (deflate_state *s, tree_desc *desc);
  61. static void build_tree (deflate_state *s, tree_desc *desc);
  62. static void scan_tree (deflate_state *s, ct_data *tree, int max_code);
  63. static void send_tree (deflate_state *s, ct_data *tree, int max_code);
  64. static int build_bl_tree (deflate_state *s);
  65. static void send_all_trees (deflate_state *s, int lcodes, int dcodes, int blcodes);
  66. static void compress_block (deflate_state *s, const ct_data *ltree, const ct_data *dtree);
  67. static int detect_data_type (deflate_state *s);
  68. /* ===========================================================================
  69. * Initialize the tree data structures for a new zlib stream.
  70. */
  71. void Z_INTERNAL zng_tr_init(deflate_state *s) {
  72. s->l_desc.dyn_tree = s->dyn_ltree;
  73. s->l_desc.stat_desc = &static_l_desc;
  74. s->d_desc.dyn_tree = s->dyn_dtree;
  75. s->d_desc.stat_desc = &static_d_desc;
  76. s->bl_desc.dyn_tree = s->bl_tree;
  77. s->bl_desc.stat_desc = &static_bl_desc;
  78. s->bi_buf = 0;
  79. s->bi_valid = 0;
  80. #ifdef ZLIB_DEBUG
  81. s->compressed_len = 0L;
  82. s->bits_sent = 0L;
  83. #endif
  84. /* Initialize the first block of the first file: */
  85. init_block(s);
  86. }
  87. /* ===========================================================================
  88. * Initialize a new block.
  89. */
  90. static void init_block(deflate_state *s) {
  91. int n; /* iterates over tree elements */
  92. /* Initialize the trees. */
  93. for (n = 0; n < L_CODES; n++)
  94. s->dyn_ltree[n].Freq = 0;
  95. for (n = 0; n < D_CODES; n++)
  96. s->dyn_dtree[n].Freq = 0;
  97. for (n = 0; n < BL_CODES; n++)
  98. s->bl_tree[n].Freq = 0;
  99. s->dyn_ltree[END_BLOCK].Freq = 1;
  100. s->opt_len = s->static_len = 0L;
  101. s->sym_next = s->matches = 0;
  102. }
  103. #define SMALLEST 1
  104. /* Index within the heap array of least frequent node in the Huffman tree */
  105. /* ===========================================================================
  106. * Remove the smallest element from the heap and recreate the heap with
  107. * one less element. Updates heap and heap_len.
  108. */
  109. #define pqremove(s, tree, top) \
  110. {\
  111. top = s->heap[SMALLEST]; \
  112. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  113. pqdownheap(s, tree, SMALLEST); \
  114. }
  115. /* ===========================================================================
  116. * Compares to subtrees, using the tree depth as tie breaker when
  117. * the subtrees have equal frequency. This minimizes the worst case length.
  118. */
  119. #define smaller(tree, n, m, depth) \
  120. (tree[n].Freq < tree[m].Freq || \
  121. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  122. /* ===========================================================================
  123. * Restore the heap property by moving down the tree starting at node k,
  124. * exchanging a node with the smallest of its two sons if necessary, stopping
  125. * when the heap property is re-established (each father smaller than its
  126. * two sons).
  127. */
  128. static void pqdownheap(deflate_state *s, ct_data *tree, int k) {
  129. /* tree: the tree to restore */
  130. /* k: node to move down */
  131. int v = s->heap[k];
  132. int j = k << 1; /* left son of k */
  133. while (j <= s->heap_len) {
  134. /* Set j to the smallest of the two sons: */
  135. if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  136. j++;
  137. }
  138. /* Exit if v is smaller than both sons */
  139. if (smaller(tree, v, s->heap[j], s->depth))
  140. break;
  141. /* Exchange v with the smallest son */
  142. s->heap[k] = s->heap[j];
  143. k = j;
  144. /* And continue down the tree, setting j to the left son of k */
  145. j <<= 1;
  146. }
  147. s->heap[k] = v;
  148. }
  149. /* ===========================================================================
  150. * Compute the optimal bit lengths for a tree and update the total bit length
  151. * for the current block.
  152. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  153. * above are the tree nodes sorted by increasing frequency.
  154. * OUT assertions: the field len is set to the optimal bit length, the
  155. * array bl_count contains the frequencies for each bit length.
  156. * The length opt_len is updated; static_len is also updated if stree is
  157. * not null.
  158. */
  159. static void gen_bitlen(deflate_state *s, tree_desc *desc) {
  160. /* desc: the tree descriptor */
  161. ct_data *tree = desc->dyn_tree;
  162. int max_code = desc->max_code;
  163. const ct_data *stree = desc->stat_desc->static_tree;
  164. const int *extra = desc->stat_desc->extra_bits;
  165. int base = desc->stat_desc->extra_base;
  166. unsigned int max_length = desc->stat_desc->max_length;
  167. int h; /* heap index */
  168. int n, m; /* iterate over the tree elements */
  169. unsigned int bits; /* bit length */
  170. int xbits; /* extra bits */
  171. uint16_t f; /* frequency */
  172. int overflow = 0; /* number of elements with bit length too large */
  173. for (bits = 0; bits <= MAX_BITS; bits++)
  174. s->bl_count[bits] = 0;
  175. /* In a first pass, compute the optimal bit lengths (which may
  176. * overflow in the case of the bit length tree).
  177. */
  178. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  179. for (h = s->heap_max + 1; h < HEAP_SIZE; h++) {
  180. n = s->heap[h];
  181. bits = tree[tree[n].Dad].Len + 1u;
  182. if (bits > max_length){
  183. bits = max_length;
  184. overflow++;
  185. }
  186. tree[n].Len = (uint16_t)bits;
  187. /* We overwrite tree[n].Dad which is no longer needed */
  188. if (n > max_code) /* not a leaf node */
  189. continue;
  190. s->bl_count[bits]++;
  191. xbits = 0;
  192. if (n >= base)
  193. xbits = extra[n-base];
  194. f = tree[n].Freq;
  195. s->opt_len += (unsigned long)f * (unsigned int)(bits + xbits);
  196. if (stree)
  197. s->static_len += (unsigned long)f * (unsigned int)(stree[n].Len + xbits);
  198. }
  199. if (overflow == 0)
  200. return;
  201. Tracev((stderr, "\nbit length overflow\n"));
  202. /* This happens for example on obj2 and pic of the Calgary corpus */
  203. /* Find the first bit length which could increase: */
  204. do {
  205. bits = max_length - 1;
  206. while (s->bl_count[bits] == 0)
  207. bits--;
  208. s->bl_count[bits]--; /* move one leaf down the tree */
  209. s->bl_count[bits+1] += 2u; /* move one overflow item as its brother */
  210. s->bl_count[max_length]--;
  211. /* The brother of the overflow item also moves one step up,
  212. * but this does not affect bl_count[max_length]
  213. */
  214. overflow -= 2;
  215. } while (overflow > 0);
  216. /* Now recompute all bit lengths, scanning in increasing frequency.
  217. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  218. * lengths instead of fixing only the wrong ones. This idea is taken
  219. * from 'ar' written by Haruhiko Okumura.)
  220. */
  221. for (bits = max_length; bits != 0; bits--) {
  222. n = s->bl_count[bits];
  223. while (n != 0) {
  224. m = s->heap[--h];
  225. if (m > max_code)
  226. continue;
  227. if (tree[m].Len != bits) {
  228. Tracev((stderr, "code %d bits %d->%u\n", m, tree[m].Len, bits));
  229. s->opt_len += (unsigned long)(bits * tree[m].Freq);
  230. s->opt_len -= (unsigned long)(tree[m].Len * tree[m].Freq);
  231. tree[m].Len = (uint16_t)bits;
  232. }
  233. n--;
  234. }
  235. }
  236. }
  237. /* ===========================================================================
  238. * Generate the codes for a given tree and bit counts (which need not be
  239. * optimal).
  240. * IN assertion: the array bl_count contains the bit length statistics for
  241. * the given tree and the field len is set for all tree elements.
  242. * OUT assertion: the field code is set for all tree elements of non
  243. * zero code length.
  244. */
  245. Z_INTERNAL void gen_codes(ct_data *tree, int max_code, uint16_t *bl_count) {
  246. /* tree: the tree to decorate */
  247. /* max_code: largest code with non zero frequency */
  248. /* bl_count: number of codes at each bit length */
  249. uint16_t next_code[MAX_BITS+1]; /* next code value for each bit length */
  250. unsigned int code = 0; /* running code value */
  251. int bits; /* bit index */
  252. int n; /* code index */
  253. /* The distribution counts are first used to generate the code values
  254. * without bit reversal.
  255. */
  256. for (bits = 1; bits <= MAX_BITS; bits++) {
  257. code = (code + bl_count[bits-1]) << 1;
  258. next_code[bits] = (uint16_t)code;
  259. }
  260. /* Check that the bit counts in bl_count are consistent. The last code
  261. * must be all ones.
  262. */
  263. Assert(code + bl_count[MAX_BITS]-1 == (1 << MAX_BITS)-1, "inconsistent bit counts");
  264. Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
  265. for (n = 0; n <= max_code; n++) {
  266. int len = tree[n].Len;
  267. if (len == 0)
  268. continue;
  269. /* Now reverse the bits */
  270. tree[n].Code = PREFIX(bi_reverse)(next_code[len]++, len);
  271. Tracecv(tree != static_ltree, (stderr, "\nn %3d %c l %2d c %4x (%x) ",
  272. n, (isgraph(n & 0xff) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  273. }
  274. }
  275. /* ===========================================================================
  276. * Construct one Huffman tree and assigns the code bit strings and lengths.
  277. * Update the total bit length for the current block.
  278. * IN assertion: the field freq is set for all tree elements.
  279. * OUT assertions: the fields len and code are set to the optimal bit length
  280. * and corresponding code. The length opt_len is updated; static_len is
  281. * also updated if stree is not null. The field max_code is set.
  282. */
  283. static void build_tree(deflate_state *s, tree_desc *desc) {
  284. /* desc: the tree descriptor */
  285. ct_data *tree = desc->dyn_tree;
  286. const ct_data *stree = desc->stat_desc->static_tree;
  287. int elems = desc->stat_desc->elems;
  288. int n, m; /* iterate over heap elements */
  289. int max_code = -1; /* largest code with non zero frequency */
  290. int node; /* new node being created */
  291. /* Construct the initial heap, with least frequent element in
  292. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  293. * heap[0] is not used.
  294. */
  295. s->heap_len = 0;
  296. s->heap_max = HEAP_SIZE;
  297. for (n = 0; n < elems; n++) {
  298. if (tree[n].Freq != 0) {
  299. s->heap[++(s->heap_len)] = max_code = n;
  300. s->depth[n] = 0;
  301. } else {
  302. tree[n].Len = 0;
  303. }
  304. }
  305. /* The pkzip format requires that at least one distance code exists,
  306. * and that at least one bit should be sent even if there is only one
  307. * possible code. So to avoid special checks later on we force at least
  308. * two codes of non zero frequency.
  309. */
  310. while (s->heap_len < 2) {
  311. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  312. tree[node].Freq = 1;
  313. s->depth[node] = 0;
  314. s->opt_len--;
  315. if (stree)
  316. s->static_len -= stree[node].Len;
  317. /* node is 0 or 1 so it does not have extra bits */
  318. }
  319. desc->max_code = max_code;
  320. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  321. * establish sub-heaps of increasing lengths:
  322. */
  323. for (n = s->heap_len/2; n >= 1; n--)
  324. pqdownheap(s, tree, n);
  325. /* Construct the Huffman tree by repeatedly combining the least two
  326. * frequent nodes.
  327. */
  328. node = elems; /* next internal node of the tree */
  329. do {
  330. pqremove(s, tree, n); /* n = node of least frequency */
  331. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  332. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  333. s->heap[--(s->heap_max)] = m;
  334. /* Create a new node father of n and m */
  335. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  336. s->depth[node] = (unsigned char)((s->depth[n] >= s->depth[m] ?
  337. s->depth[n] : s->depth[m]) + 1);
  338. tree[n].Dad = tree[m].Dad = (uint16_t)node;
  339. #ifdef DUMP_BL_TREE
  340. if (tree == s->bl_tree) {
  341. fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)",
  342. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  343. }
  344. #endif
  345. /* and insert the new node in the heap */
  346. s->heap[SMALLEST] = node++;
  347. pqdownheap(s, tree, SMALLEST);
  348. } while (s->heap_len >= 2);
  349. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  350. /* At this point, the fields freq and dad are set. We can now
  351. * generate the bit lengths.
  352. */
  353. gen_bitlen(s, (tree_desc *)desc);
  354. /* The field len is now set, we can generate the bit codes */
  355. gen_codes((ct_data *)tree, max_code, s->bl_count);
  356. }
  357. /* ===========================================================================
  358. * Scan a literal or distance tree to determine the frequencies of the codes
  359. * in the bit length tree.
  360. */
  361. static void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
  362. /* tree: the tree to be scanned */
  363. /* max_code: and its largest code of non zero frequency */
  364. int n; /* iterates over all tree elements */
  365. int prevlen = -1; /* last emitted length */
  366. int curlen; /* length of current code */
  367. int nextlen = tree[0].Len; /* length of next code */
  368. uint16_t count = 0; /* repeat count of the current code */
  369. uint16_t max_count = 7; /* max repeat count */
  370. uint16_t min_count = 4; /* min repeat count */
  371. if (nextlen == 0)
  372. max_count = 138, min_count = 3;
  373. tree[max_code+1].Len = (uint16_t)0xffff; /* guard */
  374. for (n = 0; n <= max_code; n++) {
  375. curlen = nextlen;
  376. nextlen = tree[n+1].Len;
  377. if (++count < max_count && curlen == nextlen) {
  378. continue;
  379. } else if (count < min_count) {
  380. s->bl_tree[curlen].Freq += count;
  381. } else if (curlen != 0) {
  382. if (curlen != prevlen)
  383. s->bl_tree[curlen].Freq++;
  384. s->bl_tree[REP_3_6].Freq++;
  385. } else if (count <= 10) {
  386. s->bl_tree[REPZ_3_10].Freq++;
  387. } else {
  388. s->bl_tree[REPZ_11_138].Freq++;
  389. }
  390. count = 0;
  391. prevlen = curlen;
  392. if (nextlen == 0) {
  393. max_count = 138, min_count = 3;
  394. } else if (curlen == nextlen) {
  395. max_count = 6, min_count = 3;
  396. } else {
  397. max_count = 7, min_count = 4;
  398. }
  399. }
  400. }
  401. /* ===========================================================================
  402. * Send a literal or distance tree in compressed form, using the codes in
  403. * bl_tree.
  404. */
  405. static void send_tree(deflate_state *s, ct_data *tree, int max_code) {
  406. /* tree: the tree to be scanned */
  407. /* max_code and its largest code of non zero frequency */
  408. int n; /* iterates over all tree elements */
  409. int prevlen = -1; /* last emitted length */
  410. int curlen; /* length of current code */
  411. int nextlen = tree[0].Len; /* length of next code */
  412. int count = 0; /* repeat count of the current code */
  413. int max_count = 7; /* max repeat count */
  414. int min_count = 4; /* min repeat count */
  415. /* tree[max_code+1].Len = -1; */ /* guard already set */
  416. if (nextlen == 0)
  417. max_count = 138, min_count = 3;
  418. // Temp local variables
  419. uint32_t bi_valid = s->bi_valid;
  420. uint64_t bi_buf = s->bi_buf;
  421. for (n = 0; n <= max_code; n++) {
  422. curlen = nextlen;
  423. nextlen = tree[n+1].Len;
  424. if (++count < max_count && curlen == nextlen) {
  425. continue;
  426. } else if (count < min_count) {
  427. do {
  428. send_code(s, curlen, s->bl_tree, bi_buf, bi_valid);
  429. } while (--count != 0);
  430. } else if (curlen != 0) {
  431. if (curlen != prevlen) {
  432. send_code(s, curlen, s->bl_tree, bi_buf, bi_valid);
  433. count--;
  434. }
  435. Assert(count >= 3 && count <= 6, " 3_6?");
  436. send_code(s, REP_3_6, s->bl_tree, bi_buf, bi_valid);
  437. send_bits(s, count-3, 2, bi_buf, bi_valid);
  438. } else if (count <= 10) {
  439. send_code(s, REPZ_3_10, s->bl_tree, bi_buf, bi_valid);
  440. send_bits(s, count-3, 3, bi_buf, bi_valid);
  441. } else {
  442. send_code(s, REPZ_11_138, s->bl_tree, bi_buf, bi_valid);
  443. send_bits(s, count-11, 7, bi_buf, bi_valid);
  444. }
  445. count = 0;
  446. prevlen = curlen;
  447. if (nextlen == 0) {
  448. max_count = 138, min_count = 3;
  449. } else if (curlen == nextlen) {
  450. max_count = 6, min_count = 3;
  451. } else {
  452. max_count = 7, min_count = 4;
  453. }
  454. }
  455. // Store back temp variables
  456. s->bi_buf = bi_buf;
  457. s->bi_valid = bi_valid;
  458. }
  459. /* ===========================================================================
  460. * Construct the Huffman tree for the bit lengths and return the index in
  461. * bl_order of the last bit length code to send.
  462. */
  463. static int build_bl_tree(deflate_state *s) {
  464. int max_blindex; /* index of last bit length code of non zero freq */
  465. /* Determine the bit length frequencies for literal and distance trees */
  466. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  467. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  468. /* Build the bit length tree: */
  469. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  470. /* opt_len now includes the length of the tree representations, except
  471. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  472. */
  473. /* Determine the number of bit length codes to send. The pkzip format
  474. * requires that at least 4 bit length codes be sent. (appnote.txt says
  475. * 3 but the actual value used is 4.)
  476. */
  477. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  478. if (s->bl_tree[bl_order[max_blindex]].Len != 0)
  479. break;
  480. }
  481. /* Update opt_len to include the bit length tree and counts */
  482. s->opt_len += 3*((unsigned long)max_blindex+1) + 5+5+4;
  483. Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu", s->opt_len, s->static_len));
  484. return max_blindex;
  485. }
  486. /* ===========================================================================
  487. * Send the header for a block using dynamic Huffman trees: the counts, the
  488. * lengths of the bit length codes, the literal tree and the distance tree.
  489. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  490. */
  491. static void send_all_trees(deflate_state *s, int lcodes, int dcodes, int blcodes) {
  492. int rank; /* index in bl_order */
  493. Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  494. Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes");
  495. // Temp local variables
  496. uint32_t bi_valid = s->bi_valid;
  497. uint64_t bi_buf = s->bi_buf;
  498. Tracev((stderr, "\nbl counts: "));
  499. send_bits(s, lcodes-257, 5, bi_buf, bi_valid); /* not +255 as stated in appnote.txt */
  500. send_bits(s, dcodes-1, 5, bi_buf, bi_valid);
  501. send_bits(s, blcodes-4, 4, bi_buf, bi_valid); /* not -3 as stated in appnote.txt */
  502. for (rank = 0; rank < blcodes; rank++) {
  503. Tracev((stderr, "\nbl code %2u ", bl_order[rank]));
  504. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3, bi_buf, bi_valid);
  505. }
  506. Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent));
  507. // Store back temp variables
  508. s->bi_buf = bi_buf;
  509. s->bi_valid = bi_valid;
  510. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  511. Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent));
  512. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  513. Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent));
  514. }
  515. /* ===========================================================================
  516. * Send a stored block
  517. */
  518. void Z_INTERNAL zng_tr_stored_block(deflate_state *s, char *buf, uint32_t stored_len, int last) {
  519. /* buf: input block */
  520. /* stored_len: length of input block */
  521. /* last: one if this is the last block for a file */
  522. zng_tr_emit_tree(s, STORED_BLOCK, last); /* send block type */
  523. zng_tr_emit_align(s); /* align on byte boundary */
  524. cmpr_bits_align(s);
  525. put_short(s, (uint16_t)stored_len);
  526. put_short(s, (uint16_t)~stored_len);
  527. cmpr_bits_add(s, 32);
  528. sent_bits_add(s, 32);
  529. if (stored_len) {
  530. memcpy(s->pending_buf + s->pending, (unsigned char *)buf, stored_len);
  531. s->pending += stored_len;
  532. cmpr_bits_add(s, stored_len << 3);
  533. sent_bits_add(s, stored_len << 3);
  534. }
  535. }
  536. /* ===========================================================================
  537. * Send one empty static block to give enough lookahead for inflate.
  538. * This takes 10 bits, of which 7 may remain in the bit buffer.
  539. */
  540. void Z_INTERNAL zng_tr_align(deflate_state *s) {
  541. zng_tr_emit_tree(s, STATIC_TREES, 0);
  542. zng_tr_emit_end_block(s, static_ltree, 0);
  543. zng_tr_flush_bits(s);
  544. }
  545. /* ===========================================================================
  546. * Determine the best encoding for the current block: dynamic trees, static
  547. * trees or store, and write out the encoded block.
  548. */
  549. void Z_INTERNAL zng_tr_flush_block(deflate_state *s, char *buf, uint32_t stored_len, int last) {
  550. /* buf: input block, or NULL if too old */
  551. /* stored_len: length of input block */
  552. /* last: one if this is the last block for a file */
  553. unsigned long opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  554. int max_blindex = 0; /* index of last bit length code of non zero freq */
  555. /* Build the Huffman trees unless a stored block is forced */
  556. if (UNLIKELY(s->sym_next == 0)) {
  557. /* Emit an empty static tree block with no codes */
  558. opt_lenb = static_lenb = 0;
  559. s->static_len = 7;
  560. } else if (s->level > 0) {
  561. /* Check if the file is binary or text */
  562. if (s->strm->data_type == Z_UNKNOWN)
  563. s->strm->data_type = detect_data_type(s);
  564. /* Construct the literal and distance trees */
  565. build_tree(s, (tree_desc *)(&(s->l_desc)));
  566. Tracev((stderr, "\nlit data: dyn %lu, stat %lu", s->opt_len, s->static_len));
  567. build_tree(s, (tree_desc *)(&(s->d_desc)));
  568. Tracev((stderr, "\ndist data: dyn %lu, stat %lu", s->opt_len, s->static_len));
  569. /* At this point, opt_len and static_len are the total bit lengths of
  570. * the compressed block data, excluding the tree representations.
  571. */
  572. /* Build the bit length tree for the above two trees, and get the index
  573. * in bl_order of the last bit length code to send.
  574. */
  575. max_blindex = build_bl_tree(s);
  576. /* Determine the best encoding. Compute the block lengths in bytes. */
  577. opt_lenb = (s->opt_len+3+7) >> 3;
  578. static_lenb = (s->static_len+3+7) >> 3;
  579. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %u lit %u ",
  580. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  581. s->sym_next / 3));
  582. if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
  583. opt_lenb = static_lenb;
  584. } else {
  585. Assert(buf != NULL, "lost buf");
  586. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  587. }
  588. if (stored_len+4 <= opt_lenb && buf != NULL) {
  589. /* 4: two words for the lengths
  590. * The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  591. * Otherwise we can't have processed more than WSIZE input bytes since
  592. * the last block flush, because compression would have been
  593. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  594. * transform a block into a stored block.
  595. */
  596. zng_tr_stored_block(s, buf, stored_len, last);
  597. } else if (static_lenb == opt_lenb) {
  598. zng_tr_emit_tree(s, STATIC_TREES, last);
  599. compress_block(s, (const ct_data *)static_ltree, (const ct_data *)static_dtree);
  600. cmpr_bits_add(s, s->static_len);
  601. } else {
  602. zng_tr_emit_tree(s, DYN_TREES, last);
  603. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1);
  604. compress_block(s, (const ct_data *)s->dyn_ltree, (const ct_data *)s->dyn_dtree);
  605. cmpr_bits_add(s, s->opt_len);
  606. }
  607. Assert(s->compressed_len == s->bits_sent, "bad compressed size");
  608. /* The above check is made mod 2^32, for files larger than 512 MB
  609. * and unsigned long implemented on 32 bits.
  610. */
  611. init_block(s);
  612. if (last) {
  613. zng_tr_emit_align(s);
  614. }
  615. Tracev((stderr, "\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last));
  616. }
  617. /* ===========================================================================
  618. * Send the block data compressed using the given Huffman trees
  619. */
  620. static void compress_block(deflate_state *s, const ct_data *ltree, const ct_data *dtree) {
  621. /* ltree: literal tree */
  622. /* dtree: distance tree */
  623. unsigned dist; /* distance of matched string */
  624. int lc; /* match length or unmatched char (if dist == 0) */
  625. unsigned sx = 0; /* running index in symbol buffers */
  626. if (s->sym_next != 0) {
  627. do {
  628. #ifdef LIT_MEM
  629. dist = s->d_buf[sx];
  630. lc = s->l_buf[sx++];
  631. #else
  632. dist = s->sym_buf[sx++] & 0xff;
  633. dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
  634. lc = s->sym_buf[sx++];
  635. #endif
  636. if (dist == 0) {
  637. zng_emit_lit(s, ltree, lc);
  638. } else {
  639. zng_emit_dist(s, ltree, dtree, lc, dist);
  640. } /* literal or match pair ? */
  641. /* Check for no overlay of pending_buf on needed symbols */
  642. #ifdef LIT_MEM
  643. Assert(s->pending < 2 * (s->lit_bufsize + sx), "pending_buf overflow");
  644. #else
  645. Assert(s->pending < s->lit_bufsize + sx, "pending_buf overflow");
  646. #endif
  647. } while (sx < s->sym_next);
  648. }
  649. zng_emit_end_block(s, ltree, 0);
  650. }
  651. /* ===========================================================================
  652. * Check if the data type is TEXT or BINARY, using the following algorithm:
  653. * - TEXT if the two conditions below are satisfied:
  654. * a) There are no non-portable control characters belonging to the
  655. * "black list" (0..6, 14..25, 28..31).
  656. * b) There is at least one printable character belonging to the
  657. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  658. * - BINARY otherwise.
  659. * - The following partially-portable control characters form a
  660. * "gray list" that is ignored in this detection algorithm:
  661. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  662. * IN assertion: the fields Freq of dyn_ltree are set.
  663. */
  664. static int detect_data_type(deflate_state *s) {
  665. /* black_mask is the bit mask of black-listed bytes
  666. * set bits 0..6, 14..25, and 28..31
  667. * 0xf3ffc07f = binary 11110011111111111100000001111111
  668. */
  669. unsigned long black_mask = 0xf3ffc07fUL;
  670. int n;
  671. /* Check for non-textual ("black-listed") bytes. */
  672. for (n = 0; n <= 31; n++, black_mask >>= 1)
  673. if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
  674. return Z_BINARY;
  675. /* Check for textual ("white-listed") bytes. */
  676. if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0)
  677. return Z_TEXT;
  678. for (n = 32; n < LITERALS; n++)
  679. if (s->dyn_ltree[n].Freq != 0)
  680. return Z_TEXT;
  681. /* There are no "black-listed" or "white-listed" bytes:
  682. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  683. */
  684. return Z_BINARY;
  685. }
  686. /* ===========================================================================
  687. * Flush the bit buffer, keeping at most 7 bits in it.
  688. */
  689. void Z_INTERNAL zng_tr_flush_bits(deflate_state *s) {
  690. if (s->bi_valid >= 48) {
  691. put_uint32(s, (uint32_t)s->bi_buf);
  692. put_short(s, (uint16_t)(s->bi_buf >> 32));
  693. s->bi_buf >>= 48;
  694. s->bi_valid -= 48;
  695. } else if (s->bi_valid >= 32) {
  696. put_uint32(s, (uint32_t)s->bi_buf);
  697. s->bi_buf >>= 32;
  698. s->bi_valid -= 32;
  699. }
  700. if (s->bi_valid >= 16) {
  701. put_short(s, (uint16_t)s->bi_buf);
  702. s->bi_buf >>= 16;
  703. s->bi_valid -= 16;
  704. }
  705. if (s->bi_valid >= 8) {
  706. put_byte(s, s->bi_buf);
  707. s->bi_buf >>= 8;
  708. s->bi_valid -= 8;
  709. }
  710. }
  711. /* ===========================================================================
  712. * Reverse the first len bits of a code using bit manipulation
  713. */
  714. Z_INTERNAL uint16_t PREFIX(bi_reverse)(unsigned code, int len) {
  715. /* code: the value to invert */
  716. /* len: its bit length */
  717. Assert(len >= 1 && len <= 15, "code length must be 1-15");
  718. #define bitrev8(b) \
  719. (uint8_t)((((uint8_t)(b) * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32)
  720. return (bitrev8(code >> 8) | (uint16_t)bitrev8(code) << 8) >> (16 - len);
  721. }