enough.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /* enough.c -- determine the maximum size of inflate's Huffman code tables over
  2. * all possible valid and complete Huffman codes, subject to a length limit.
  3. * Copyright (C) 2007, 2008 Mark Adler
  4. * Version 1.3 17 February 2008 Mark Adler
  5. */
  6. /* Version history:
  7. 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4)
  8. 1.1 4 Jan 2007 Use faster incremental table usage computation
  9. Prune examine() search on previously visited states
  10. 1.2 5 Jan 2007 Comments clean up
  11. As inflate does, decrease root for short codes
  12. Refuse cases where inflate would increase root
  13. 1.3 17 Feb 2008 Add argument for initial root table size
  14. Fix bug for initial root table size == max - 1
  15. Use a macro to compute the history index
  16. */
  17. /*
  18. Examine all possible Huffman codes for a given number of symbols and a
  19. maximum code length in bits to determine the maximum table size for zilb's
  20. inflate. Only complete Huffman codes are counted.
  21. Two codes are considered distinct if the vectors of the number of codes per
  22. length are not identical. So permutations of the symbol assignments result
  23. in the same code for the counting, as do permutations of the assignments of
  24. the bit values to the codes (i.e. only canonical codes are counted).
  25. We build a code from shorter to longer lengths, determining how many symbols
  26. are coded at each length. At each step, we have how many symbols remain to
  27. be coded, what the last code length used was, and how many bit patterns of
  28. that length remain unused. Then we add one to the code length and double the
  29. number of unused patterns to graduate to the next code length. We then
  30. assign all portions of the remaining symbols to that code length that
  31. preserve the properties of a correct and eventually complete code. Those
  32. properties are: we cannot use more bit patterns than are available; and when
  33. all the symbols are used, there are exactly zero possible bit patterns
  34. remaining.
  35. The inflate Huffman decoding algorithm uses two-level lookup tables for
  36. speed. There is a single first-level table to decode codes up to root bits
  37. in length (root == 9 in the current inflate implementation). The table
  38. has 1 << root entries and is indexed by the next root bits of input. Codes
  39. shorter than root bits have replicated table entries, so that the correct
  40. entry is pointed to regardless of the bits that follow the short code. If
  41. the code is longer than root bits, then the table entry points to a second-
  42. level table. The size of that table is determined by the longest code with
  43. that root-bit prefix. If that longest code has length len, then the table
  44. has size 1 << (len - root), to index the remaining bits in that set of
  45. codes. Each subsequent root-bit prefix then has its own sub-table. The
  46. total number of table entries required by the code is calculated
  47. incrementally as the number of codes at each bit length is populated. When
  48. all of the codes are shorter than root bits, then root is reduced to the
  49. longest code length, resulting in a single, smaller, one-level table.
  50. The inflate algorithm also provides for small values of root (relative to
  51. the log2 of the number of symbols), where the shortest code has more bits
  52. than root. In that case, root is increased to the length of the shortest
  53. code. This program, by design, does not handle that case, so it is verified
  54. that the number of symbols is less than 2^(root + 1).
  55. In order to speed up the examination (by about ten orders of magnitude for
  56. the default arguments), the intermediate states in the build-up of a code
  57. are remembered and previously visited branches are pruned. The memory
  58. required for this will increase rapidly with the total number of symbols and
  59. the maximum code length in bits. However this is a very small price to pay
  60. for the vast speedup.
  61. First, all of the possible Huffman codes are counted, and reachable
  62. intermediate states are noted by a non-zero count in a saved-results array.
  63. Second, the intermediate states that lead to (root + 1) bit or longer codes
  64. are used to look at all sub-codes from those junctures for their inflate
  65. memory usage. (The amount of memory used is not affected by the number of
  66. codes of root bits or less in length.) Third, the visited states in the
  67. construction of those sub-codes and the associated calculation of the table
  68. size is recalled in order to avoid recalculating from the same juncture.
  69. Beginning the code examination at (root + 1) bit codes, which is enabled by
  70. identifying the reachable nodes, accounts for about six of the orders of
  71. magnitude of improvement for the default arguments. About another four
  72. orders of magnitude come from not revisiting previous states. Out of
  73. approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes
  74. need to be examined to cover all of the possible table memory usage cases
  75. for the default arguments of 286 symbols limited to 15-bit codes.
  76. Note that an unsigned long long type is used for counting. It is quite easy
  77. to exceed the capacity of an eight-byte integer with a large number of
  78. symbols and a large maximum code length, so multiple-precision arithmetic
  79. would need to replace the unsigned long long arithmetic in that case. This
  80. program will abort if an overflow occurs. The big_t type identifies where
  81. the counting takes place.
  82. An unsigned long long type is also used for calculating the number of
  83. possible codes remaining at the maximum length. This limits the maximum
  84. code length to the number of bits in a long long minus the number of bits
  85. needed to represent the symbols in a flat code. The code_t type identifies
  86. where the bit pattern counting takes place.
  87. */
  88. #include <stdio.h>
  89. #include <stdlib.h>
  90. #include <string.h>
  91. #include <assert.h>
  92. #define local static
  93. /* special data types */
  94. typedef unsigned long long big_t; /* type for code counting */
  95. typedef unsigned long long code_t; /* type for bit pattern counting */
  96. struct tab { /* type for been here check */
  97. size_t len; /* length of bit vector in char's */
  98. char *vec; /* allocated bit vector */
  99. };
  100. /* The array for saving results, num[], is indexed with this triplet:
  101. syms: number of symbols remaining to code
  102. left: number of available bit patterns at length len
  103. len: number of bits in the codes currently being assigned
  104. Those indices are constrained thusly when saving results:
  105. syms: 3..totsym (totsym == total symbols to code)
  106. left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
  107. len: 1..max - 1 (max == maximum code length in bits)
  108. syms == 2 is not saved since that immediately leads to a single code. left
  109. must be even, since it represents the number of available bit patterns at
  110. the current length, which is double the number at the previous length.
  111. left ends at syms-1 since left == syms immediately results in a single code.
  112. (left > sym is not allowed since that would result in an incomplete code.)
  113. len is less than max, since the code completes immediately when len == max.
  114. The offset into the array is calculated for the three indices with the
  115. first one (syms) being outermost, and the last one (len) being innermost.
  116. We build the array with length max-1 lists for the len index, with syms-3
  117. of those for each symbol. There are totsym-2 of those, with each one
  118. varying in length as a function of sym. See the calculation of index in
  119. count() for the index, and the calculation of size in main() for the size
  120. of the array.
  121. For the deflate example of 286 symbols limited to 15-bit codes, the array
  122. has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than
  123. half of the space allocated for saved results is actually used -- not all
  124. possible triplets are reached in the generation of valid Huffman codes.
  125. */
  126. /* The array for tracking visited states, done[], is itself indexed identically
  127. to the num[] array as described above for the (syms, left, len) triplet.
  128. Each element in the array is further indexed by the (mem, rem) doublet,
  129. where mem is the amount of inflate table space used so far, and rem is the
  130. remaining unused entries in the current inflate sub-table. Each indexed
  131. element is simply one bit indicating whether the state has been visited or
  132. not. Since the ranges for mem and rem are not known a priori, each bit
  133. vector is of a variable size, and grows as needed to accommodate the visited
  134. states. mem and rem are used to calculate a single index in a triangular
  135. array. Since the range of mem is expected in the default case to be about
  136. ten times larger than the range of rem, the array is skewed to reduce the
  137. memory usage, with eight times the range for mem than for rem. See the
  138. calculations for offset and bit in beenhere() for the details.
  139. For the deflate example of 286 symbols limited to 15-bit codes, the bit
  140. vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[]
  141. array itself.
  142. */
  143. /* Globals to avoid propagating constants or constant pointers recursively */
  144. local int max; /* maximum allowed bit length for the codes */
  145. local int root; /* size of base code table in bits */
  146. local int large; /* largest code table so far */
  147. local size_t size; /* number of elements in num and done */
  148. local int *code; /* number of symbols assigned to each bit length */
  149. local big_t *num; /* saved results array for code counting */
  150. local struct tab *done; /* states already evaluated array */
  151. /* Index function for num[] and done[] */
  152. #define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1)
  153. /* Free allocated space. Uses globals code, num, and done. */
  154. local void cleanup(void)
  155. {
  156. size_t n;
  157. if (done != NULL) {
  158. for (n = 0; n < size; n++)
  159. if (done[n].len)
  160. free(done[n].vec);
  161. free(done);
  162. }
  163. if (num != NULL)
  164. free(num);
  165. if (code != NULL)
  166. free(code);
  167. }
  168. /* Return the number of possible Huffman codes using bit patterns of lengths
  169. len through max inclusive, coding syms symbols, with left bit patterns of
  170. length len unused -- return -1 if there is an overflow in the counting.
  171. Keep a record of previous results in num to prevent repeating the same
  172. calculation. Uses the globals max and num. */
  173. local big_t count(int syms, int len, int left)
  174. {
  175. big_t sum; /* number of possible codes from this juncture */
  176. big_t got; /* value returned from count() */
  177. int least; /* least number of syms to use at this juncture */
  178. int most; /* most number of syms to use at this juncture */
  179. int use; /* number of bit patterns to use in next call */
  180. size_t index; /* index of this case in *num */
  181. /* see if only one possible code */
  182. if (syms == left)
  183. return 1;
  184. /* note and verify the expected state */
  185. assert(syms > left && left > 0 && len < max);
  186. /* see if we've done this one already */
  187. index = INDEX(syms, left, len);
  188. got = num[index];
  189. if (got)
  190. return got; /* we have -- return the saved result */
  191. /* we need to use at least this many bit patterns so that the code won't be
  192. incomplete at the next length (more bit patterns than symbols) */
  193. least = (left << 1) - syms;
  194. if (least < 0)
  195. least = 0;
  196. /* we can use at most this many bit patterns, lest there not be enough
  197. available for the remaining symbols at the maximum length (if there were
  198. no limit to the code length, this would become: most = left - 1) */
  199. most = (((code_t)left << (max - len)) - syms) /
  200. (((code_t)1 << (max - len)) - 1);
  201. /* count all possible codes from this juncture and add them up */
  202. sum = 0;
  203. for (use = least; use <= most; use++) {
  204. got = count(syms - use, len + 1, (left - use) << 1);
  205. sum += got;
  206. if (got == -1 || sum < got) /* overflow */
  207. return -1;
  208. }
  209. /* verify that all recursive calls are productive */
  210. assert(sum != 0);
  211. /* save the result and return it */
  212. num[index] = sum;
  213. return sum;
  214. }
  215. /* Return true if we've been here before, set to true if not. Set a bit in a
  216. bit vector to indicate visiting this state. Each (syms,len,left) state
  217. has a variable size bit vector indexed by (mem,rem). The bit vector is
  218. lengthened if needed to allow setting the (mem,rem) bit. */
  219. local int beenhere(int syms, int len, int left, int mem, int rem)
  220. {
  221. size_t index; /* index for this state's bit vector */
  222. size_t offset; /* offset in this state's bit vector */
  223. int bit; /* mask for this state's bit */
  224. size_t length; /* length of the bit vector in bytes */
  225. char *vector; /* new or enlarged bit vector */
  226. /* point to vector for (syms,left,len), bit in vector for (mem,rem) */
  227. index = INDEX(syms, left, len);
  228. mem -= 1 << root;
  229. offset = (mem >> 3) + rem;
  230. offset = ((offset * (offset + 1)) >> 1) + rem;
  231. bit = 1 << (mem & 7);
  232. /* see if we've been here */
  233. length = done[index].len;
  234. if (offset < length && (done[index].vec[offset] & bit) != 0)
  235. return 1; /* done this! */
  236. /* we haven't been here before -- set the bit to show we have now */
  237. /* see if we need to lengthen the vector in order to set the bit */
  238. if (length <= offset) {
  239. /* if we have one already, enlarge it, zero out the appended space */
  240. if (length) {
  241. do {
  242. length <<= 1;
  243. } while (length <= offset);
  244. vector = realloc(done[index].vec, length);
  245. if (vector != NULL)
  246. memset(vector + done[index].len, 0, length - done[index].len);
  247. }
  248. /* otherwise we need to make a new vector and zero it out */
  249. else {
  250. length = 1 << (len - root);
  251. while (length <= offset)
  252. length <<= 1;
  253. vector = calloc(length, sizeof(char));
  254. }
  255. /* in either case, bail if we can't get the memory */
  256. if (vector == NULL) {
  257. fputs("abort: unable to allocate enough memory\n", stderr);
  258. cleanup();
  259. exit(1);
  260. }
  261. /* install the new vector */
  262. done[index].len = length;
  263. done[index].vec = vector;
  264. }
  265. /* set the bit */
  266. done[index].vec[offset] |= bit;
  267. return 0;
  268. }
  269. /* Examine all possible codes from the given node (syms, len, left). Compute
  270. the amount of memory required to build inflate's decoding tables, where the
  271. number of code structures used so far is mem, and the number remaining in
  272. the current sub-table is rem. Uses the globals max, code, root, large, and
  273. done. */
  274. local void examine(int syms, int len, int left, int mem, int rem)
  275. {
  276. int least; /* least number of syms to use at this juncture */
  277. int most; /* most number of syms to use at this juncture */
  278. int use; /* number of bit patterns to use in next call */
  279. /* see if we have a complete code */
  280. if (syms == left) {
  281. /* set the last code entry */
  282. code[len] = left;
  283. /* complete computation of memory used by this code */
  284. while (rem < left) {
  285. left -= rem;
  286. rem = 1 << (len - root);
  287. mem += rem;
  288. }
  289. assert(rem == left);
  290. /* if this is a new maximum, show the entries used and the sub-code */
  291. if (mem > large) {
  292. large = mem;
  293. printf("max %d: ", mem);
  294. for (use = root + 1; use <= max; use++)
  295. if (code[use])
  296. printf("%d[%d] ", code[use], use);
  297. putchar('\n');
  298. fflush(stdout);
  299. }
  300. /* remove entries as we drop back down in the recursion */
  301. code[len] = 0;
  302. return;
  303. }
  304. /* prune the tree if we can */
  305. if (beenhere(syms, len, left, mem, rem))
  306. return;
  307. /* we need to use at least this many bit patterns so that the code won't be
  308. incomplete at the next length (more bit patterns than symbols) */
  309. least = (left << 1) - syms;
  310. if (least < 0)
  311. least = 0;
  312. /* we can use at most this many bit patterns, lest there not be enough
  313. available for the remaining symbols at the maximum length (if there were
  314. no limit to the code length, this would become: most = left - 1) */
  315. most = (((code_t)left << (max - len)) - syms) /
  316. (((code_t)1 << (max - len)) - 1);
  317. /* occupy least table spaces, creating new sub-tables as needed */
  318. use = least;
  319. while (rem < use) {
  320. use -= rem;
  321. rem = 1 << (len - root);
  322. mem += rem;
  323. }
  324. rem -= use;
  325. /* examine codes from here, updating table space as we go */
  326. for (use = least; use <= most; use++) {
  327. code[len] = use;
  328. examine(syms - use, len + 1, (left - use) << 1,
  329. mem + (rem ? 1 << (len - root) : 0), rem << 1);
  330. if (rem == 0) {
  331. rem = 1 << (len - root);
  332. mem += rem;
  333. }
  334. rem--;
  335. }
  336. /* remove entries as we drop back down in the recursion */
  337. code[len] = 0;
  338. }
  339. /* Look at all sub-codes starting with root + 1 bits. Look at only the valid
  340. intermediate code states (syms, left, len). For each completed code,
  341. calculate the amount of memory required by inflate to build the decoding
  342. tables. Find the maximum amount of memory required and show the code that
  343. requires that maximum. Uses the globals max, root, and num. */
  344. local void enough(int syms)
  345. {
  346. int n; /* number of remaing symbols for this node */
  347. int left; /* number of unused bit patterns at this length */
  348. size_t index; /* index of this case in *num */
  349. /* clear code */
  350. for (n = 0; n <= max; n++)
  351. code[n] = 0;
  352. /* look at all (root + 1) bit and longer codes */
  353. large = 1 << root; /* base table */
  354. if (root < max) /* otherwise, there's only a base table */
  355. for (n = 3; n <= syms; n++)
  356. for (left = 2; left < n; left += 2)
  357. {
  358. /* look at all reachable (root + 1) bit nodes, and the
  359. resulting codes (complete at root + 2 or more) */
  360. index = INDEX(n, left, root + 1);
  361. if (root + 1 < max && num[index]) /* reachable node */
  362. examine(n, root + 1, left, 1 << root, 0);
  363. /* also look at root bit codes with completions at root + 1
  364. bits (not saved in num, since complete), just in case */
  365. if (num[index - 1] && n <= left << 1)
  366. examine((n - left) << 1, root + 1, (n - left) << 1,
  367. 1 << root, 0);
  368. }
  369. /* done */
  370. printf("done: maximum of %d table entries\n", large);
  371. }
  372. /*
  373. Examine and show the total number of possible Huffman codes for a given
  374. maximum number of symbols, initial root table size, and maximum code length
  375. in bits -- those are the command arguments in that order. The default
  376. values are 286, 9, and 15 respectively, for the deflate literal/length code.
  377. The possible codes are counted for each number of coded symbols from two to
  378. the maximum. The counts for each of those and the total number of codes are
  379. shown. The maximum number of inflate table entires is then calculated
  380. across all possible codes. Each new maximum number of table entries and the
  381. associated sub-code (starting at root + 1 == 10 bits) is shown.
  382. To count and examine Huffman codes that are not length-limited, provide a
  383. maximum length equal to the number of symbols minus one.
  384. For the deflate literal/length code, use "enough". For the deflate distance
  385. code, use "enough 30 6".
  386. This uses the %llu printf format to print big_t numbers, which assumes that
  387. big_t is an unsigned long long. If the big_t type is changed (for example
  388. to a multiple precision type), the method of printing will also need to be
  389. updated.
  390. */
  391. int main(int argc, char **argv)
  392. {
  393. int syms; /* total number of symbols to code */
  394. int n; /* number of symbols to code for this run */
  395. big_t got; /* return value of count() */
  396. big_t sum; /* accumulated number of codes over n */
  397. /* set up globals for cleanup() */
  398. code = NULL;
  399. num = NULL;
  400. done = NULL;
  401. /* get arguments -- default to the deflate literal/length code */
  402. syms = 286;
  403. root = 9;
  404. max = 15;
  405. if (argc > 1) {
  406. syms = atoi(argv[1]);
  407. if (argc > 2) {
  408. root = atoi(argv[2]);
  409. if (argc > 3)
  410. max = atoi(argv[3]);
  411. }
  412. }
  413. if (argc > 4 || syms < 2 || root < 1 || max < 1) {
  414. fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
  415. stderr);
  416. return 1;
  417. }
  418. /* if not restricting the code length, the longest is syms - 1 */
  419. if (max > syms - 1)
  420. max = syms - 1;
  421. /* determine the number of bits in a code_t */
  422. n = 0;
  423. while (((code_t)1 << n) != 0)
  424. n++;
  425. /* make sure that the calculation of most will not overflow */
  426. if (max > n || syms - 2 >= (((code_t)0 - 1) >> (max - 1))) {
  427. fputs("abort: code length too long for internal types\n", stderr);
  428. return 1;
  429. }
  430. /* reject impossible code requests */
  431. if (syms - 1 > ((code_t)1 << max) - 1) {
  432. fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
  433. syms, max);
  434. return 1;
  435. }
  436. /* allocate code vector */
  437. code = calloc(max + 1, sizeof(int));
  438. if (code == NULL) {
  439. fputs("abort: unable to allocate enough memory\n", stderr);
  440. return 1;
  441. }
  442. /* determine size of saved results array, checking for overflows,
  443. allocate and clear the array (set all to zero with calloc()) */
  444. if (syms == 2) /* iff max == 1 */
  445. num = NULL; /* won't be saving any results */
  446. else {
  447. size = syms >> 1;
  448. if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) ||
  449. (size *= n, size > ((size_t)0 - 1) / (n = max - 1)) ||
  450. (size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) ||
  451. (num = calloc(size, sizeof(big_t))) == NULL) {
  452. fputs("abort: unable to allocate enough memory\n", stderr);
  453. cleanup();
  454. return 1;
  455. }
  456. }
  457. /* count possible codes for all numbers of symbols, add up counts */
  458. sum = 0;
  459. for (n = 2; n <= syms; n++) {
  460. got = count(n, 1, 2);
  461. sum += got;
  462. if (got == -1 || sum < got) { /* overflow */
  463. fputs("abort: can't count that high!\n", stderr);
  464. cleanup();
  465. return 1;
  466. }
  467. printf("%llu %d-codes\n", got, n);
  468. }
  469. printf("%llu total codes for 2 to %d symbols", sum, syms);
  470. if (max < syms - 1)
  471. printf(" (%d-bit length limit)\n", max);
  472. else
  473. puts(" (no length limit)");
  474. /* allocate and clear done array for beenhere() */
  475. if (syms == 2)
  476. done = NULL;
  477. else if (size > ((size_t)0 - 1) / sizeof(struct tab) ||
  478. (done = calloc(size, sizeof(struct tab))) == NULL) {
  479. fputs("abort: unable to allocate enough memory\n", stderr);
  480. cleanup();
  481. return 1;
  482. }
  483. /* find and show maximum inflate table usage */
  484. if (root > max) /* reduce root to max length */
  485. root = max;
  486. if (syms < ((code_t)1 << (root + 1)))
  487. enough(syms);
  488. else
  489. puts("cannot handle minimum code lengths > root");
  490. /* done */
  491. cleanup();
  492. return 0;
  493. }