Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * decompress_common.c - Code shared by the XPRESS and LZX decompressors
0004  *
0005  * Copyright (C) 2015 Eric Biggers
0006  */
0007 
0008 #include "decompress_common.h"
0009 
0010 /*
0011  * make_huffman_decode_table() -
0012  *
0013  * Build a decoding table for a canonical prefix code, or "Huffman code".
0014  *
0015  * This is an internal function, not part of the library API!
0016  *
0017  * This takes as input the length of the codeword for each symbol in the
0018  * alphabet and produces as output a table that can be used for fast
0019  * decoding of prefix-encoded symbols using read_huffsym().
0020  *
0021  * Strictly speaking, a canonical prefix code might not be a Huffman
0022  * code.  But this algorithm will work either way; and in fact, since
0023  * Huffman codes are defined in terms of symbol frequencies, there is no
0024  * way for the decompressor to know whether the code is a true Huffman
0025  * code or not until all symbols have been decoded.
0026  *
0027  * Because the prefix code is assumed to be "canonical", it can be
0028  * reconstructed directly from the codeword lengths.  A prefix code is
0029  * canonical if and only if a longer codeword never lexicographically
0030  * precedes a shorter codeword, and the lexicographic ordering of
0031  * codewords of the same length is the same as the lexicographic ordering
0032  * of the corresponding symbols.  Consequently, we can sort the symbols
0033  * primarily by codeword length and secondarily by symbol value, then
0034  * reconstruct the prefix code by generating codewords lexicographically
0035  * in that order.
0036  *
0037  * This function does not, however, generate the prefix code explicitly.
0038  * Instead, it directly builds a table for decoding symbols using the
0039  * code.  The basic idea is this: given the next 'max_codeword_len' bits
0040  * in the input, we can look up the decoded symbol by indexing a table
0041  * containing 2**max_codeword_len entries.  A codeword with length
0042  * 'max_codeword_len' will have exactly one entry in this table, whereas
0043  * a codeword shorter than 'max_codeword_len' will have multiple entries
0044  * in this table.  Precisely, a codeword of length n will be represented
0045  * by 2**(max_codeword_len - n) entries in this table.  The 0-based index
0046  * of each such entry will contain the corresponding codeword as a prefix
0047  * when zero-padded on the left to 'max_codeword_len' binary digits.
0048  *
0049  * That's the basic idea, but we implement two optimizations regarding
0050  * the format of the decode table itself:
0051  *
0052  * - For many compression formats, the maximum codeword length is too
0053  *   long for it to be efficient to build the full decoding table
0054  *   whenever a new prefix code is used.  Instead, we can build the table
0055  *   using only 2**table_bits entries, where 'table_bits' is some number
0056  *   less than or equal to 'max_codeword_len'.  Then, only codewords of
0057  *   length 'table_bits' and shorter can be directly looked up.  For
0058  *   longer codewords, the direct lookup instead produces the root of a
0059  *   binary tree.  Using this tree, the decoder can do traditional
0060  *   bit-by-bit decoding of the remainder of the codeword.  Child nodes
0061  *   are allocated in extra entries at the end of the table; leaf nodes
0062  *   contain symbols.  Note that the long-codeword case is, in general,
0063  *   not performance critical, since in Huffman codes the most frequently
0064  *   used symbols are assigned the shortest codeword lengths.
0065  *
0066  * - When we decode a symbol using a direct lookup of the table, we still
0067  *   need to know its length so that the bitstream can be advanced by the
0068  *   appropriate number of bits.  The simple solution is to simply retain
0069  *   the 'lens' array and use the decoded symbol as an index into it.
0070  *   However, this requires two separate array accesses in the fast path.
0071  *   The optimization is to store the length directly in the decode
0072  *   table.  We use the bottom 11 bits for the symbol and the top 5 bits
0073  *   for the length.  In addition, to combine this optimization with the
0074  *   previous one, we introduce a special case where the top 2 bits of
0075  *   the length are both set if the entry is actually the root of a
0076  *   binary tree.
0077  *
0078  * @decode_table:
0079  *  The array in which to create the decoding table.  This must have
0080  *  a length of at least ((2**table_bits) + 2 * num_syms) entries.
0081  *
0082  * @num_syms:
0083  *  The number of symbols in the alphabet; also, the length of the
0084  *  'lens' array.  Must be less than or equal to 2048.
0085  *
0086  * @table_bits:
0087  *  The order of the decode table size, as explained above.  Must be
0088  *  less than or equal to 13.
0089  *
0090  * @lens:
0091  *  An array of length @num_syms, indexable by symbol, that gives the
0092  *  length of the codeword, in bits, for that symbol.  The length can
0093  *  be 0, which means that the symbol does not have a codeword
0094  *  assigned.
0095  *
0096  * @max_codeword_len:
0097  *  The longest codeword length allowed in the compression format.
0098  *  All entries in 'lens' must be less than or equal to this value.
0099  *  This must be less than or equal to 23.
0100  *
0101  * @working_space
0102  *  A temporary array of length '2 * (max_codeword_len + 1) +
0103  *  num_syms'.
0104  *
0105  * Returns 0 on success, or -1 if the lengths do not form a valid prefix
0106  * code.
0107  */
0108 int make_huffman_decode_table(u16 decode_table[], const u32 num_syms,
0109                   const u32 table_bits, const u8 lens[],
0110                   const u32 max_codeword_len,
0111                   u16 working_space[])
0112 {
0113     const u32 table_num_entries = 1 << table_bits;
0114     u16 * const len_counts = &working_space[0];
0115     u16 * const offsets = &working_space[1 * (max_codeword_len + 1)];
0116     u16 * const sorted_syms = &working_space[2 * (max_codeword_len + 1)];
0117     int left;
0118     void *decode_table_ptr;
0119     u32 sym_idx;
0120     u32 codeword_len;
0121     u32 stores_per_loop;
0122     u32 decode_table_pos;
0123     u32 len;
0124     u32 sym;
0125 
0126     /* Count how many symbols have each possible codeword length.
0127      * Note that a length of 0 indicates the corresponding symbol is not
0128      * used in the code and therefore does not have a codeword.
0129      */
0130     for (len = 0; len <= max_codeword_len; len++)
0131         len_counts[len] = 0;
0132     for (sym = 0; sym < num_syms; sym++)
0133         len_counts[lens[sym]]++;
0134 
0135     /* We can assume all lengths are <= max_codeword_len, but we
0136      * cannot assume they form a valid prefix code.  A codeword of
0137      * length n should require a proportion of the codespace equaling
0138      * (1/2)^n.  The code is valid if and only if the codespace is
0139      * exactly filled by the lengths, by this measure.
0140      */
0141     left = 1;
0142     for (len = 1; len <= max_codeword_len; len++) {
0143         left <<= 1;
0144         left -= len_counts[len];
0145         if (left < 0) {
0146             /* The lengths overflow the codespace; that is, the code
0147              * is over-subscribed.
0148              */
0149             return -1;
0150         }
0151     }
0152 
0153     if (left) {
0154         /* The lengths do not fill the codespace; that is, they form an
0155          * incomplete set.
0156          */
0157         if (left == (1 << max_codeword_len)) {
0158             /* The code is completely empty.  This is arguably
0159              * invalid, but in fact it is valid in LZX and XPRESS,
0160              * so we must allow it.  By definition, no symbols can
0161              * be decoded with an empty code.  Consequently, we
0162              * technically don't even need to fill in the decode
0163              * table.  However, to avoid accessing uninitialized
0164              * memory if the algorithm nevertheless attempts to
0165              * decode symbols using such a code, we zero out the
0166              * decode table.
0167              */
0168             memset(decode_table, 0,
0169                    table_num_entries * sizeof(decode_table[0]));
0170             return 0;
0171         }
0172         return -1;
0173     }
0174 
0175     /* Sort the symbols primarily by length and secondarily by symbol order.
0176      */
0177 
0178     /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
0179      * max_codeword_len is the number of codewords shorter than 'len' bits.
0180      */
0181     offsets[1] = 0;
0182     for (len = 1; len < max_codeword_len; len++)
0183         offsets[len + 1] = offsets[len] + len_counts[len];
0184 
0185     /* Use the 'offsets' array to sort the symbols.  Note that we do not
0186      * include symbols that are not used in the code.  Consequently, fewer
0187      * than 'num_syms' entries in 'sorted_syms' may be filled.
0188      */
0189     for (sym = 0; sym < num_syms; sym++)
0190         if (lens[sym])
0191             sorted_syms[offsets[lens[sym]]++] = sym;
0192 
0193     /* Fill entries for codewords with length <= table_bits
0194      * --- that is, those short enough for a direct mapping.
0195      *
0196      * The table will start with entries for the shortest codeword(s), which
0197      * have the most entries.  From there, the number of entries per
0198      * codeword will decrease.
0199      */
0200     decode_table_ptr = decode_table;
0201     sym_idx = 0;
0202     codeword_len = 1;
0203     stores_per_loop = (1 << (table_bits - codeword_len));
0204     for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
0205         u32 end_sym_idx = sym_idx + len_counts[codeword_len];
0206 
0207         for (; sym_idx < end_sym_idx; sym_idx++) {
0208             u16 entry;
0209             u16 *p;
0210             u32 n;
0211 
0212             entry = ((u32)codeword_len << 11) | sorted_syms[sym_idx];
0213             p = (u16 *)decode_table_ptr;
0214             n = stores_per_loop;
0215 
0216             do {
0217                 *p++ = entry;
0218             } while (--n);
0219 
0220             decode_table_ptr = p;
0221         }
0222     }
0223 
0224     /* If we've filled in the entire table, we are done.  Otherwise,
0225      * there are codewords longer than table_bits for which we must
0226      * generate binary trees.
0227      */
0228     decode_table_pos = (u16 *)decode_table_ptr - decode_table;
0229     if (decode_table_pos != table_num_entries) {
0230         u32 j;
0231         u32 next_free_tree_slot;
0232         u32 cur_codeword;
0233 
0234         /* First, zero out the remaining entries.  This is
0235          * necessary so that these entries appear as
0236          * "unallocated" in the next part.  Each of these entries
0237          * will eventually be filled with the representation of
0238          * the root node of a binary tree.
0239          */
0240         j = decode_table_pos;
0241         do {
0242             decode_table[j] = 0;
0243         } while (++j != table_num_entries);
0244 
0245         /* We allocate child nodes starting at the end of the
0246          * direct lookup table.  Note that there should be
0247          * 2*num_syms extra entries for this purpose, although
0248          * fewer than this may actually be needed.
0249          */
0250         next_free_tree_slot = table_num_entries;
0251 
0252         /* Iterate through each codeword with length greater than
0253          * 'table_bits', primarily in order of codeword length
0254          * and secondarily in order of symbol.
0255          */
0256         for (cur_codeword = decode_table_pos << 1;
0257              codeword_len <= max_codeword_len;
0258              codeword_len++, cur_codeword <<= 1) {
0259             u32 end_sym_idx = sym_idx + len_counts[codeword_len];
0260 
0261             for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++) {
0262                 /* 'sorted_sym' is the symbol represented by the
0263                  * codeword.
0264                  */
0265                 u32 sorted_sym = sorted_syms[sym_idx];
0266                 u32 extra_bits = codeword_len - table_bits;
0267                 u32 node_idx = cur_codeword >> extra_bits;
0268 
0269                 /* Go through each bit of the current codeword
0270                  * beyond the prefix of length @table_bits and
0271                  * walk the appropriate binary tree, allocating
0272                  * any slots that have not yet been allocated.
0273                  *
0274                  * Note that the 'pointer' entry to the binary
0275                  * tree, which is stored in the direct lookup
0276                  * portion of the table, is represented
0277                  * identically to other internal (non-leaf)
0278                  * nodes of the binary tree; it can be thought
0279                  * of as simply the root of the tree.  The
0280                  * representation of these internal nodes is
0281                  * simply the index of the left child combined
0282                  * with the special bits 0xC000 to distinguish
0283                  * the entry from direct mapping and leaf node
0284                  * entries.
0285                  */
0286                 do {
0287                     /* At least one bit remains in the
0288                      * codeword, but the current node is an
0289                      * unallocated leaf.  Change it to an
0290                      * internal node.
0291                      */
0292                     if (decode_table[node_idx] == 0) {
0293                         decode_table[node_idx] =
0294                             next_free_tree_slot | 0xC000;
0295                         decode_table[next_free_tree_slot++] = 0;
0296                         decode_table[next_free_tree_slot++] = 0;
0297                     }
0298 
0299                     /* Go to the left child if the next bit
0300                      * in the codeword is 0; otherwise go to
0301                      * the right child.
0302                      */
0303                     node_idx = decode_table[node_idx] & 0x3FFF;
0304                     --extra_bits;
0305                     node_idx += (cur_codeword >> extra_bits) & 1;
0306                 } while (extra_bits != 0);
0307 
0308                 /* We've traversed the tree using the entire
0309                  * codeword, and we're now at the entry where
0310                  * the actual symbol will be stored.  This is
0311                  * distinguished from internal nodes by not
0312                  * having its high two bits set.
0313                  */
0314                 decode_table[node_idx] = sorted_sym;
0315             }
0316         }
0317     }
0318     return 0;
0319 }