decompress_common.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * decompress_common.c - Code shared by the XPRESS and LZX decompressors
  4. *
  5. * Copyright (C) 2015 Eric Biggers
  6. */
  7. #include "decompress_common.h"
  8. /*
  9. * make_huffman_decode_table() -
  10. *
  11. * Build a decoding table for a canonical prefix code, or "Huffman code".
  12. *
  13. * This is an internal function, not part of the library API!
  14. *
  15. * This takes as input the length of the codeword for each symbol in the
  16. * alphabet and produces as output a table that can be used for fast
  17. * decoding of prefix-encoded symbols using read_huffsym().
  18. *
  19. * Strictly speaking, a canonical prefix code might not be a Huffman
  20. * code. But this algorithm will work either way; and in fact, since
  21. * Huffman codes are defined in terms of symbol frequencies, there is no
  22. * way for the decompressor to know whether the code is a true Huffman
  23. * code or not until all symbols have been decoded.
  24. *
  25. * Because the prefix code is assumed to be "canonical", it can be
  26. * reconstructed directly from the codeword lengths. A prefix code is
  27. * canonical if and only if a longer codeword never lexicographically
  28. * precedes a shorter codeword, and the lexicographic ordering of
  29. * codewords of the same length is the same as the lexicographic ordering
  30. * of the corresponding symbols. Consequently, we can sort the symbols
  31. * primarily by codeword length and secondarily by symbol value, then
  32. * reconstruct the prefix code by generating codewords lexicographically
  33. * in that order.
  34. *
  35. * This function does not, however, generate the prefix code explicitly.
  36. * Instead, it directly builds a table for decoding symbols using the
  37. * code. The basic idea is this: given the next 'max_codeword_len' bits
  38. * in the input, we can look up the decoded symbol by indexing a table
  39. * containing 2**max_codeword_len entries. A codeword with length
  40. * 'max_codeword_len' will have exactly one entry in this table, whereas
  41. * a codeword shorter than 'max_codeword_len' will have multiple entries
  42. * in this table. Precisely, a codeword of length n will be represented
  43. * by 2**(max_codeword_len - n) entries in this table. The 0-based index
  44. * of each such entry will contain the corresponding codeword as a prefix
  45. * when zero-padded on the left to 'max_codeword_len' binary digits.
  46. *
  47. * That's the basic idea, but we implement two optimizations regarding
  48. * the format of the decode table itself:
  49. *
  50. * - For many compression formats, the maximum codeword length is too
  51. * long for it to be efficient to build the full decoding table
  52. * whenever a new prefix code is used. Instead, we can build the table
  53. * using only 2**table_bits entries, where 'table_bits' is some number
  54. * less than or equal to 'max_codeword_len'. Then, only codewords of
  55. * length 'table_bits' and shorter can be directly looked up. For
  56. * longer codewords, the direct lookup instead produces the root of a
  57. * binary tree. Using this tree, the decoder can do traditional
  58. * bit-by-bit decoding of the remainder of the codeword. Child nodes
  59. * are allocated in extra entries at the end of the table; leaf nodes
  60. * contain symbols. Note that the long-codeword case is, in general,
  61. * not performance critical, since in Huffman codes the most frequently
  62. * used symbols are assigned the shortest codeword lengths.
  63. *
  64. * - When we decode a symbol using a direct lookup of the table, we still
  65. * need to know its length so that the bitstream can be advanced by the
  66. * appropriate number of bits. The simple solution is to simply retain
  67. * the 'lens' array and use the decoded symbol as an index into it.
  68. * However, this requires two separate array accesses in the fast path.
  69. * The optimization is to store the length directly in the decode
  70. * table. We use the bottom 11 bits for the symbol and the top 5 bits
  71. * for the length. In addition, to combine this optimization with the
  72. * previous one, we introduce a special case where the top 2 bits of
  73. * the length are both set if the entry is actually the root of a
  74. * binary tree.
  75. *
  76. * @decode_table:
  77. * The array in which to create the decoding table. This must have
  78. * a length of at least ((2**table_bits) + 2 * num_syms) entries.
  79. *
  80. * @num_syms:
  81. * The number of symbols in the alphabet; also, the length of the
  82. * 'lens' array. Must be less than or equal to 2048.
  83. *
  84. * @table_bits:
  85. * The order of the decode table size, as explained above. Must be
  86. * less than or equal to 13.
  87. *
  88. * @lens:
  89. * An array of length @num_syms, indexable by symbol, that gives the
  90. * length of the codeword, in bits, for that symbol. The length can
  91. * be 0, which means that the symbol does not have a codeword
  92. * assigned.
  93. *
  94. * @max_codeword_len:
  95. * The longest codeword length allowed in the compression format.
  96. * All entries in 'lens' must be less than or equal to this value.
  97. * This must be less than or equal to 23.
  98. *
  99. * @working_space
  100. * A temporary array of length '2 * (max_codeword_len + 1) +
  101. * num_syms'.
  102. *
  103. * Returns 0 on success, or -1 if the lengths do not form a valid prefix
  104. * code.
  105. */
  106. int make_huffman_decode_table(u16 decode_table[], const u32 num_syms,
  107. const u32 table_bits, const u8 lens[],
  108. const u32 max_codeword_len,
  109. u16 working_space[])
  110. {
  111. const u32 table_num_entries = 1 << table_bits;
  112. u16 * const len_counts = &working_space[0];
  113. u16 * const offsets = &working_space[1 * (max_codeword_len + 1)];
  114. u16 * const sorted_syms = &working_space[2 * (max_codeword_len + 1)];
  115. int left;
  116. void *decode_table_ptr;
  117. u32 sym_idx;
  118. u32 codeword_len;
  119. u32 stores_per_loop;
  120. u32 decode_table_pos;
  121. u32 len;
  122. u32 sym;
  123. /* Count how many symbols have each possible codeword length.
  124. * Note that a length of 0 indicates the corresponding symbol is not
  125. * used in the code and therefore does not have a codeword.
  126. */
  127. for (len = 0; len <= max_codeword_len; len++)
  128. len_counts[len] = 0;
  129. for (sym = 0; sym < num_syms; sym++)
  130. len_counts[lens[sym]]++;
  131. /* We can assume all lengths are <= max_codeword_len, but we
  132. * cannot assume they form a valid prefix code. A codeword of
  133. * length n should require a proportion of the codespace equaling
  134. * (1/2)^n. The code is valid if and only if the codespace is
  135. * exactly filled by the lengths, by this measure.
  136. */
  137. left = 1;
  138. for (len = 1; len <= max_codeword_len; len++) {
  139. left <<= 1;
  140. left -= len_counts[len];
  141. if (left < 0) {
  142. /* The lengths overflow the codespace; that is, the code
  143. * is over-subscribed.
  144. */
  145. return -1;
  146. }
  147. }
  148. if (left) {
  149. /* The lengths do not fill the codespace; that is, they form an
  150. * incomplete set.
  151. */
  152. if (left == (1 << max_codeword_len)) {
  153. /* The code is completely empty. This is arguably
  154. * invalid, but in fact it is valid in LZX and XPRESS,
  155. * so we must allow it. By definition, no symbols can
  156. * be decoded with an empty code. Consequently, we
  157. * technically don't even need to fill in the decode
  158. * table. However, to avoid accessing uninitialized
  159. * memory if the algorithm nevertheless attempts to
  160. * decode symbols using such a code, we zero out the
  161. * decode table.
  162. */
  163. memset(decode_table, 0,
  164. table_num_entries * sizeof(decode_table[0]));
  165. return 0;
  166. }
  167. return -1;
  168. }
  169. /* Sort the symbols primarily by length and secondarily by symbol order.
  170. */
  171. /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
  172. * max_codeword_len is the number of codewords shorter than 'len' bits.
  173. */
  174. offsets[1] = 0;
  175. for (len = 1; len < max_codeword_len; len++)
  176. offsets[len + 1] = offsets[len] + len_counts[len];
  177. /* Use the 'offsets' array to sort the symbols. Note that we do not
  178. * include symbols that are not used in the code. Consequently, fewer
  179. * than 'num_syms' entries in 'sorted_syms' may be filled.
  180. */
  181. for (sym = 0; sym < num_syms; sym++)
  182. if (lens[sym])
  183. sorted_syms[offsets[lens[sym]]++] = sym;
  184. /* Fill entries for codewords with length <= table_bits
  185. * --- that is, those short enough for a direct mapping.
  186. *
  187. * The table will start with entries for the shortest codeword(s), which
  188. * have the most entries. From there, the number of entries per
  189. * codeword will decrease.
  190. */
  191. decode_table_ptr = decode_table;
  192. sym_idx = 0;
  193. codeword_len = 1;
  194. stores_per_loop = (1 << (table_bits - codeword_len));
  195. for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
  196. u32 end_sym_idx = sym_idx + len_counts[codeword_len];
  197. for (; sym_idx < end_sym_idx; sym_idx++) {
  198. u16 entry;
  199. u16 *p;
  200. u32 n;
  201. entry = ((u32)codeword_len << 11) | sorted_syms[sym_idx];
  202. p = (u16 *)decode_table_ptr;
  203. n = stores_per_loop;
  204. do {
  205. *p++ = entry;
  206. } while (--n);
  207. decode_table_ptr = p;
  208. }
  209. }
  210. /* If we've filled in the entire table, we are done. Otherwise,
  211. * there are codewords longer than table_bits for which we must
  212. * generate binary trees.
  213. */
  214. decode_table_pos = (u16 *)decode_table_ptr - decode_table;
  215. if (decode_table_pos != table_num_entries) {
  216. u32 j;
  217. u32 next_free_tree_slot;
  218. u32 cur_codeword;
  219. /* First, zero out the remaining entries. This is
  220. * necessary so that these entries appear as
  221. * "unallocated" in the next part. Each of these entries
  222. * will eventually be filled with the representation of
  223. * the root node of a binary tree.
  224. */
  225. j = decode_table_pos;
  226. do {
  227. decode_table[j] = 0;
  228. } while (++j != table_num_entries);
  229. /* We allocate child nodes starting at the end of the
  230. * direct lookup table. Note that there should be
  231. * 2*num_syms extra entries for this purpose, although
  232. * fewer than this may actually be needed.
  233. */
  234. next_free_tree_slot = table_num_entries;
  235. /* Iterate through each codeword with length greater than
  236. * 'table_bits', primarily in order of codeword length
  237. * and secondarily in order of symbol.
  238. */
  239. for (cur_codeword = decode_table_pos << 1;
  240. codeword_len <= max_codeword_len;
  241. codeword_len++, cur_codeword <<= 1) {
  242. u32 end_sym_idx = sym_idx + len_counts[codeword_len];
  243. for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++) {
  244. /* 'sorted_sym' is the symbol represented by the
  245. * codeword.
  246. */
  247. u32 sorted_sym = sorted_syms[sym_idx];
  248. u32 extra_bits = codeword_len - table_bits;
  249. u32 node_idx = cur_codeword >> extra_bits;
  250. /* Go through each bit of the current codeword
  251. * beyond the prefix of length @table_bits and
  252. * walk the appropriate binary tree, allocating
  253. * any slots that have not yet been allocated.
  254. *
  255. * Note that the 'pointer' entry to the binary
  256. * tree, which is stored in the direct lookup
  257. * portion of the table, is represented
  258. * identically to other internal (non-leaf)
  259. * nodes of the binary tree; it can be thought
  260. * of as simply the root of the tree. The
  261. * representation of these internal nodes is
  262. * simply the index of the left child combined
  263. * with the special bits 0xC000 to distinguish
  264. * the entry from direct mapping and leaf node
  265. * entries.
  266. */
  267. do {
  268. /* At least one bit remains in the
  269. * codeword, but the current node is an
  270. * unallocated leaf. Change it to an
  271. * internal node.
  272. */
  273. if (decode_table[node_idx] == 0) {
  274. decode_table[node_idx] =
  275. next_free_tree_slot | 0xC000;
  276. decode_table[next_free_tree_slot++] = 0;
  277. decode_table[next_free_tree_slot++] = 0;
  278. }
  279. /* Go to the left child if the next bit
  280. * in the codeword is 0; otherwise go to
  281. * the right child.
  282. */
  283. node_idx = decode_table[node_idx] & 0x3FFF;
  284. --extra_bits;
  285. node_idx += (cur_codeword >> extra_bits) & 1;
  286. } while (extra_bits != 0);
  287. /* We've traversed the tree using the entire
  288. * codeword, and we're now at the entry where
  289. * the actual symbol will be stored. This is
  290. * distinguished from internal nodes by not
  291. * having its high two bits set.
  292. */
  293. decode_table[node_idx] = sorted_sym;
  294. }
  295. }
  296. }
  297. return 0;
  298. }