1522e010bSKonstantin Komarov// SPDX-License-Identifier: GPL-2.0-or-later
2522e010bSKonstantin Komarov/*
3522e010bSKonstantin Komarov * decompress_common.c - Code shared by the XPRESS and LZX decompressors
4522e010bSKonstantin Komarov *
5522e010bSKonstantin Komarov * Copyright (C) 2015 Eric Biggers
6522e010bSKonstantin Komarov */
7522e010bSKonstantin Komarov
8522e010bSKonstantin Komarov#include "decompress_common.h"
9522e010bSKonstantin Komarov
10522e010bSKonstantin Komarov/*
11522e010bSKonstantin Komarov * make_huffman_decode_table() -
12522e010bSKonstantin Komarov *
13522e010bSKonstantin Komarov * Build a decoding table for a canonical prefix code, or "Huffman code".
14522e010bSKonstantin Komarov *
15522e010bSKonstantin Komarov * This is an internal function, not part of the library API!
16522e010bSKonstantin Komarov *
17522e010bSKonstantin Komarov * This takes as input the length of the codeword for each symbol in the
18522e010bSKonstantin Komarov * alphabet and produces as output a table that can be used for fast
19522e010bSKonstantin Komarov * decoding of prefix-encoded symbols using read_huffsym().
20522e010bSKonstantin Komarov *
21522e010bSKonstantin Komarov * Strictly speaking, a canonical prefix code might not be a Huffman
22522e010bSKonstantin Komarov * code.  But this algorithm will work either way; and in fact, since
23522e010bSKonstantin Komarov * Huffman codes are defined in terms of symbol frequencies, there is no
24522e010bSKonstantin Komarov * way for the decompressor to know whether the code is a true Huffman
25522e010bSKonstantin Komarov * code or not until all symbols have been decoded.
26522e010bSKonstantin Komarov *
27522e010bSKonstantin Komarov * Because the prefix code is assumed to be "canonical", it can be
28522e010bSKonstantin Komarov * reconstructed directly from the codeword lengths.  A prefix code is
29522e010bSKonstantin Komarov * canonical if and only if a longer codeword never lexicographically
30522e010bSKonstantin Komarov * precedes a shorter codeword, and the lexicographic ordering of
31522e010bSKonstantin Komarov * codewords of the same length is the same as the lexicographic ordering
32522e010bSKonstantin Komarov * of the corresponding symbols.  Consequently, we can sort the symbols
33522e010bSKonstantin Komarov * primarily by codeword length and secondarily by symbol value, then
34522e010bSKonstantin Komarov * reconstruct the prefix code by generating codewords lexicographically
35522e010bSKonstantin Komarov * in that order.
36522e010bSKonstantin Komarov *
37522e010bSKonstantin Komarov * This function does not, however, generate the prefix code explicitly.
38522e010bSKonstantin Komarov * Instead, it directly builds a table for decoding symbols using the
39522e010bSKonstantin Komarov * code.  The basic idea is this: given the next 'max_codeword_len' bits
40522e010bSKonstantin Komarov * in the input, we can look up the decoded symbol by indexing a table
41522e010bSKonstantin Komarov * containing 2**max_codeword_len entries.  A codeword with length
42522e010bSKonstantin Komarov * 'max_codeword_len' will have exactly one entry in this table, whereas
43522e010bSKonstantin Komarov * a codeword shorter than 'max_codeword_len' will have multiple entries
44522e010bSKonstantin Komarov * in this table.  Precisely, a codeword of length n will be represented
45522e010bSKonstantin Komarov * by 2**(max_codeword_len - n) entries in this table.  The 0-based index
46522e010bSKonstantin Komarov * of each such entry will contain the corresponding codeword as a prefix
47522e010bSKonstantin Komarov * when zero-padded on the left to 'max_codeword_len' binary digits.
48522e010bSKonstantin Komarov *
49522e010bSKonstantin Komarov * That's the basic idea, but we implement two optimizations regarding
50522e010bSKonstantin Komarov * the format of the decode table itself:
51522e010bSKonstantin Komarov *
52522e010bSKonstantin Komarov * - For many compression formats, the maximum codeword length is too
53522e010bSKonstantin Komarov *   long for it to be efficient to build the full decoding table
54522e010bSKonstantin Komarov *   whenever a new prefix code is used.  Instead, we can build the table
55522e010bSKonstantin Komarov *   using only 2**table_bits entries, where 'table_bits' is some number
56522e010bSKonstantin Komarov *   less than or equal to 'max_codeword_len'.  Then, only codewords of
57522e010bSKonstantin Komarov *   length 'table_bits' and shorter can be directly looked up.  For
58522e010bSKonstantin Komarov *   longer codewords, the direct lookup instead produces the root of a
59522e010bSKonstantin Komarov *   binary tree.  Using this tree, the decoder can do traditional
60522e010bSKonstantin Komarov *   bit-by-bit decoding of the remainder of the codeword.  Child nodes
61522e010bSKonstantin Komarov *   are allocated in extra entries at the end of the table; leaf nodes
62522e010bSKonstantin Komarov *   contain symbols.  Note that the long-codeword case is, in general,
63522e010bSKonstantin Komarov *   not performance critical, since in Huffman codes the most frequently
64522e010bSKonstantin Komarov *   used symbols are assigned the shortest codeword lengths.
65522e010bSKonstantin Komarov *
66522e010bSKonstantin Komarov * - When we decode a symbol using a direct lookup of the table, we still
67522e010bSKonstantin Komarov *   need to know its length so that the bitstream can be advanced by the
68522e010bSKonstantin Komarov *   appropriate number of bits.  The simple solution is to simply retain
69522e010bSKonstantin Komarov *   the 'lens' array and use the decoded symbol as an index into it.
70522e010bSKonstantin Komarov *   However, this requires two separate array accesses in the fast path.
71522e010bSKonstantin Komarov *   The optimization is to store the length directly in the decode
72522e010bSKonstantin Komarov *   table.  We use the bottom 11 bits for the symbol and the top 5 bits
73522e010bSKonstantin Komarov *   for the length.  In addition, to combine this optimization with the
74522e010bSKonstantin Komarov *   previous one, we introduce a special case where the top 2 bits of
75522e010bSKonstantin Komarov *   the length are both set if the entry is actually the root of a
76522e010bSKonstantin Komarov *   binary tree.
77522e010bSKonstantin Komarov *
78522e010bSKonstantin Komarov * @decode_table:
79522e010bSKonstantin Komarov *	The array in which to create the decoding table.  This must have
80522e010bSKonstantin Komarov *	a length of at least ((2**table_bits) + 2 * num_syms) entries.
81522e010bSKonstantin Komarov *
82522e010bSKonstantin Komarov * @num_syms:
83522e010bSKonstantin Komarov *	The number of symbols in the alphabet; also, the length of the
84522e010bSKonstantin Komarov *	'lens' array.  Must be less than or equal to 2048.
85522e010bSKonstantin Komarov *
86522e010bSKonstantin Komarov * @table_bits:
87522e010bSKonstantin Komarov *	The order of the decode table size, as explained above.  Must be
88522e010bSKonstantin Komarov *	less than or equal to 13.
89522e010bSKonstantin Komarov *
90522e010bSKonstantin Komarov * @lens:
91522e010bSKonstantin Komarov *	An array of length @num_syms, indexable by symbol, that gives the
92522e010bSKonstantin Komarov *	length of the codeword, in bits, for that symbol.  The length can
93522e010bSKonstantin Komarov *	be 0, which means that the symbol does not have a codeword
94522e010bSKonstantin Komarov *	assigned.
95522e010bSKonstantin Komarov *
96522e010bSKonstantin Komarov * @max_codeword_len:
97522e010bSKonstantin Komarov *	The longest codeword length allowed in the compression format.
98522e010bSKonstantin Komarov *	All entries in 'lens' must be less than or equal to this value.
99522e010bSKonstantin Komarov *	This must be less than or equal to 23.
100522e010bSKonstantin Komarov *
101522e010bSKonstantin Komarov * @working_space
102522e010bSKonstantin Komarov *	A temporary array of length '2 * (max_codeword_len + 1) +
103522e010bSKonstantin Komarov *	num_syms'.
104522e010bSKonstantin Komarov *
105522e010bSKonstantin Komarov * Returns 0 on success, or -1 if the lengths do not form a valid prefix
106522e010bSKonstantin Komarov * code.
107522e010bSKonstantin Komarov */
108522e010bSKonstantin Komarovint make_huffman_decode_table(u16 decode_table[], const u32 num_syms,
109522e010bSKonstantin Komarov			      const u32 table_bits, const u8 lens[],
110522e010bSKonstantin Komarov			      const u32 max_codeword_len,
111522e010bSKonstantin Komarov			      u16 working_space[])
112522e010bSKonstantin Komarov{
113522e010bSKonstantin Komarov	const u32 table_num_entries = 1 << table_bits;
114522e010bSKonstantin Komarov	u16 * const len_counts = &working_space[0];
115522e010bSKonstantin Komarov	u16 * const offsets = &working_space[1 * (max_codeword_len + 1)];
116522e010bSKonstantin Komarov	u16 * const sorted_syms = &working_space[2 * (max_codeword_len + 1)];
117522e010bSKonstantin Komarov	int left;
118522e010bSKonstantin Komarov	void *decode_table_ptr;
119522e010bSKonstantin Komarov	u32 sym_idx;
120522e010bSKonstantin Komarov	u32 codeword_len;
121522e010bSKonstantin Komarov	u32 stores_per_loop;
122522e010bSKonstantin Komarov	u32 decode_table_pos;
123522e010bSKonstantin Komarov	u32 len;
124522e010bSKonstantin Komarov	u32 sym;
125522e010bSKonstantin Komarov
126522e010bSKonstantin Komarov	/* Count how many symbols have each possible codeword length.
127522e010bSKonstantin Komarov	 * Note that a length of 0 indicates the corresponding symbol is not
128522e010bSKonstantin Komarov	 * used in the code and therefore does not have a codeword.
129522e010bSKonstantin Komarov	 */
130522e010bSKonstantin Komarov	for (len = 0; len <= max_codeword_len; len++)
131522e010bSKonstantin Komarov		len_counts[len] = 0;
132522e010bSKonstantin Komarov	for (sym = 0; sym < num_syms; sym++)
133522e010bSKonstantin Komarov		len_counts[lens[sym]]++;
134522e010bSKonstantin Komarov
135522e010bSKonstantin Komarov	/* We can assume all lengths are <= max_codeword_len, but we
136522e010bSKonstantin Komarov	 * cannot assume they form a valid prefix code.  A codeword of
137522e010bSKonstantin Komarov	 * length n should require a proportion of the codespace equaling
138522e010bSKonstantin Komarov	 * (1/2)^n.  The code is valid if and only if the codespace is
139522e010bSKonstantin Komarov	 * exactly filled by the lengths, by this measure.
140522e010bSKonstantin Komarov	 */
141522e010bSKonstantin Komarov	left = 1;
142522e010bSKonstantin Komarov	for (len = 1; len <= max_codeword_len; len++) {
143522e010bSKonstantin Komarov		left <<= 1;
144522e010bSKonstantin Komarov		left -= len_counts[len];
145522e010bSKonstantin Komarov		if (left < 0) {
146522e010bSKonstantin Komarov			/* The lengths overflow the codespace; that is, the code
147522e010bSKonstantin Komarov			 * is over-subscribed.
148522e010bSKonstantin Komarov			 */
149522e010bSKonstantin Komarov			return -1;
150522e010bSKonstantin Komarov		}
151522e010bSKonstantin Komarov	}
152522e010bSKonstantin Komarov
153522e010bSKonstantin Komarov	if (left) {
154522e010bSKonstantin Komarov		/* The lengths do not fill the codespace; that is, they form an
155522e010bSKonstantin Komarov		 * incomplete set.
156522e010bSKonstantin Komarov		 */
157522e010bSKonstantin Komarov		if (left == (1 << max_codeword_len)) {
158522e010bSKonstantin Komarov			/* The code is completely empty.  This is arguably
159522e010bSKonstantin Komarov			 * invalid, but in fact it is valid in LZX and XPRESS,
160522e010bSKonstantin Komarov			 * so we must allow it.  By definition, no symbols can
161522e010bSKonstantin Komarov			 * be decoded with an empty code.  Consequently, we
162522e010bSKonstantin Komarov			 * technically don't even need to fill in the decode
163522e010bSKonstantin Komarov			 * table.  However, to avoid accessing uninitialized
164522e010bSKonstantin Komarov			 * memory if the algorithm nevertheless attempts to
165522e010bSKonstantin Komarov			 * decode symbols using such a code, we zero out the
166522e010bSKonstantin Komarov			 * decode table.
167522e010bSKonstantin Komarov			 */
168522e010bSKonstantin Komarov			memset(decode_table, 0,
169522e010bSKonstantin Komarov			       table_num_entries * sizeof(decode_table[0]));
170522e010bSKonstantin Komarov			return 0;
171522e010bSKonstantin Komarov		}
172522e010bSKonstantin Komarov		return -1;
173522e010bSKonstantin Komarov	}
174522e010bSKonstantin Komarov
175522e010bSKonstantin Komarov	/* Sort the symbols primarily by length and secondarily by symbol order.
176522e010bSKonstantin Komarov	 */
177522e010bSKonstantin Komarov
178522e010bSKonstantin Komarov	/* Initialize 'offsets' so that offsets[len] for 1 <= len <=
179522e010bSKonstantin Komarov	 * max_codeword_len is the number of codewords shorter than 'len' bits.
180522e010bSKonstantin Komarov	 */
181522e010bSKonstantin Komarov	offsets[1] = 0;
182522e010bSKonstantin Komarov	for (len = 1; len < max_codeword_len; len++)
183522e010bSKonstantin Komarov		offsets[len + 1] = offsets[len] + len_counts[len];
184522e010bSKonstantin Komarov
185522e010bSKonstantin Komarov	/* Use the 'offsets' array to sort the symbols.  Note that we do not
186522e010bSKonstantin Komarov	 * include symbols that are not used in the code.  Consequently, fewer
187522e010bSKonstantin Komarov	 * than 'num_syms' entries in 'sorted_syms' may be filled.
188522e010bSKonstantin Komarov	 */
189522e010bSKonstantin Komarov	for (sym = 0; sym < num_syms; sym++)
190522e010bSKonstantin Komarov		if (lens[sym])
191522e010bSKonstantin Komarov			sorted_syms[offsets[lens[sym]]++] = sym;
192522e010bSKonstantin Komarov
193522e010bSKonstantin Komarov	/* Fill entries for codewords with length <= table_bits
194522e010bSKonstantin Komarov	 * --- that is, those short enough for a direct mapping.
195522e010bSKonstantin Komarov	 *
196522e010bSKonstantin Komarov	 * The table will start with entries for the shortest codeword(s), which
197522e010bSKonstantin Komarov	 * have the most entries.  From there, the number of entries per
198522e010bSKonstantin Komarov	 * codeword will decrease.
199522e010bSKonstantin Komarov	 */
200522e010bSKonstantin Komarov	decode_table_ptr = decode_table;
201522e010bSKonstantin Komarov	sym_idx = 0;
202522e010bSKonstantin Komarov	codeword_len = 1;
203522e010bSKonstantin Komarov	stores_per_loop = (1 << (table_bits - codeword_len));
204522e010bSKonstantin Komarov	for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
205522e010bSKonstantin Komarov		u32 end_sym_idx = sym_idx + len_counts[codeword_len];
206522e010bSKonstantin Komarov
207522e010bSKonstantin Komarov		for (; sym_idx < end_sym_idx; sym_idx++) {
208522e010bSKonstantin Komarov			u16 entry;
209522e010bSKonstantin Komarov			u16 *p;
210522e010bSKonstantin Komarov			u32 n;
211522e010bSKonstantin Komarov
212522e010bSKonstantin Komarov			entry = ((u32)codeword_len << 11) | sorted_syms[sym_idx];
213522e010bSKonstantin Komarov			p = (u16 *)decode_table_ptr;
214522e010bSKonstantin Komarov			n = stores_per_loop;
215522e010bSKonstantin Komarov
216522e010bSKonstantin Komarov			do {
217522e010bSKonstantin Komarov				*p++ = entry;
218522e010bSKonstantin Komarov			} while (--n);
219522e010bSKonstantin Komarov
220522e010bSKonstantin Komarov			decode_table_ptr = p;
221522e010bSKonstantin Komarov		}
222522e010bSKonstantin Komarov	}
223522e010bSKonstantin Komarov
224522e010bSKonstantin Komarov	/* If we've filled in the entire table, we are done.  Otherwise,
225522e010bSKonstantin Komarov	 * there are codewords longer than table_bits for which we must
226522e010bSKonstantin Komarov	 * generate binary trees.
227522e010bSKonstantin Komarov	 */
228522e010bSKonstantin Komarov	decode_table_pos = (u16 *)decode_table_ptr - decode_table;
229522e010bSKonstantin Komarov	if (decode_table_pos != table_num_entries) {
230522e010bSKonstantin Komarov		u32 j;
231522e010bSKonstantin Komarov		u32 next_free_tree_slot;
232522e010bSKonstantin Komarov		u32 cur_codeword;
233522e010bSKonstantin Komarov
234522e010bSKonstantin Komarov		/* First, zero out the remaining entries.  This is
235522e010bSKonstantin Komarov		 * necessary so that these entries appear as
236522e010bSKonstantin Komarov		 * "unallocated" in the next part.  Each of these entries
237522e010bSKonstantin Komarov		 * will eventually be filled with the representation of
238522e010bSKonstantin Komarov		 * the root node of a binary tree.
239522e010bSKonstantin Komarov		 */
240522e010bSKonstantin Komarov		j = decode_table_pos;
241522e010bSKonstantin Komarov		do {
242522e010bSKonstantin Komarov			decode_table[j] = 0;
243522e010bSKonstantin Komarov		} while (++j != table_num_entries);
244522e010bSKonstantin Komarov
245522e010bSKonstantin Komarov		/* We allocate child nodes starting at the end of the
246522e010bSKonstantin Komarov		 * direct lookup table.  Note that there should be
247522e010bSKonstantin Komarov		 * 2*num_syms extra entries for this purpose, although
248522e010bSKonstantin Komarov		 * fewer than this may actually be needed.
249522e010bSKonstantin Komarov		 */
250522e010bSKonstantin Komarov		next_free_tree_slot = table_num_entries;
251522e010bSKonstantin Komarov
252522e010bSKonstantin Komarov		/* Iterate through each codeword with length greater than
253522e010bSKonstantin Komarov		 * 'table_bits', primarily in order of codeword length
254522e010bSKonstantin Komarov		 * and secondarily in order of symbol.
255522e010bSKonstantin Komarov		 */
256522e010bSKonstantin Komarov		for (cur_codeword = decode_table_pos << 1;
257522e010bSKonstantin Komarov		     codeword_len <= max_codeword_len;
258522e010bSKonstantin Komarov		     codeword_len++, cur_codeword <<= 1) {
259522e010bSKonstantin Komarov			u32 end_sym_idx = sym_idx + len_counts[codeword_len];
260522e010bSKonstantin Komarov
261522e010bSKonstantin Komarov			for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++) {
262522e010bSKonstantin Komarov				/* 'sorted_sym' is the symbol represented by the
263522e010bSKonstantin Komarov				 * codeword.
264522e010bSKonstantin Komarov				 */
265522e010bSKonstantin Komarov				u32 sorted_sym = sorted_syms[sym_idx];
266522e010bSKonstantin Komarov				u32 extra_bits = codeword_len - table_bits;
267522e010bSKonstantin Komarov				u32 node_idx = cur_codeword >> extra_bits;
268522e010bSKonstantin Komarov
269522e010bSKonstantin Komarov				/* Go through each bit of the current codeword
270522e010bSKonstantin Komarov				 * beyond the prefix of length @table_bits and
271522e010bSKonstantin Komarov				 * walk the appropriate binary tree, allocating
272522e010bSKonstantin Komarov				 * any slots that have not yet been allocated.
273522e010bSKonstantin Komarov				 *
274522e010bSKonstantin Komarov				 * Note that the 'pointer' entry to the binary
275522e010bSKonstantin Komarov				 * tree, which is stored in the direct lookup
276522e010bSKonstantin Komarov				 * portion of the table, is represented
277522e010bSKonstantin Komarov				 * identically to other internal (non-leaf)
278522e010bSKonstantin Komarov				 * nodes of the binary tree; it can be thought
279522e010bSKonstantin Komarov				 * of as simply the root of the tree.  The
280522e010bSKonstantin Komarov				 * representation of these internal nodes is
281522e010bSKonstantin Komarov				 * simply the index of the left child combined
282f8d87ed9SColin Ian King				 * with the special bits 0xC000 to distinguish
283522e010bSKonstantin Komarov				 * the entry from direct mapping and leaf node
284522e010bSKonstantin Komarov				 * entries.
285522e010bSKonstantin Komarov				 */
286522e010bSKonstantin Komarov				do {
287522e010bSKonstantin Komarov					/* At least one bit remains in the
288522e010bSKonstantin Komarov					 * codeword, but the current node is an
289522e010bSKonstantin Komarov					 * unallocated leaf.  Change it to an
290522e010bSKonstantin Komarov					 * internal node.
291522e010bSKonstantin Komarov					 */
292522e010bSKonstantin Komarov					if (decode_table[node_idx] == 0) {
293522e010bSKonstantin Komarov						decode_table[node_idx] =
294522e010bSKonstantin Komarov							next_free_tree_slot | 0xC000;
295522e010bSKonstantin Komarov						decode_table[next_free_tree_slot++] = 0;
296522e010bSKonstantin Komarov						decode_table[next_free_tree_slot++] = 0;
297522e010bSKonstantin Komarov					}
298522e010bSKonstantin Komarov
299522e010bSKonstantin Komarov					/* Go to the left child if the next bit
300522e010bSKonstantin Komarov					 * in the codeword is 0; otherwise go to
301522e010bSKonstantin Komarov					 * the right child.
302522e010bSKonstantin Komarov					 */
303522e010bSKonstantin Komarov					node_idx = decode_table[node_idx] & 0x3FFF;
304522e010bSKonstantin Komarov					--extra_bits;
305522e010bSKonstantin Komarov					node_idx += (cur_codeword >> extra_bits) & 1;
306522e010bSKonstantin Komarov				} while (extra_bits != 0);
307522e010bSKonstantin Komarov
308522e010bSKonstantin Komarov				/* We've traversed the tree using the entire
309522e010bSKonstantin Komarov				 * codeword, and we're now at the entry where
310522e010bSKonstantin Komarov				 * the actual symbol will be stored.  This is
311522e010bSKonstantin Komarov				 * distinguished from internal nodes by not
312522e010bSKonstantin Komarov				 * having its high two bits set.
313522e010bSKonstantin Komarov				 */
314522e010bSKonstantin Komarov				decode_table[node_idx] = sorted_sym;
315522e010bSKonstantin Komarov			}
316522e010bSKonstantin Komarov		}
317522e010bSKonstantin Komarov	}
318522e010bSKonstantin Komarov	return 0;
319522e010bSKonstantin Komarov}