4 * Header for decompression code shared by multiple compression formats.
6 * The following copying information applies to this specific source code file:
8 * Written in 2012-2016 by Eric Biggers <ebiggers3@gmail.com>
10 * To the extent possible under law, the author(s) have dedicated all copyright
11 * and related and neighboring rights to this software to the public domain
12 * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
13 * Dedication (the "CC0").
15 * This software is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
19 * You should have received a copy of the CC0 along with this software; if not
20 * see <http://creativecommons.org/publicdomain/zero/1.0/>.
23 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
24 #define _WIMLIB_DECOMPRESS_COMMON_H
28 #include "wimlib/compiler.h"
29 #include "wimlib/types.h"
30 #include "wimlib/unaligned.h"
32 /* Structure that encapsulates a block of in-memory data being interpreted as a
33 * stream of bits, optionally with interwoven literal bytes. Bits are assumed
34 * to be stored in little endian 16-bit coding units, with the bits ordered high
36 struct input_bitstream {
38 /* Bits that have been read from the input buffer. The bits are
39 * left-justified; the next bit is always bit 31. */
40 machine_word_t bitbuf;
42 /* Number of bits currently held in @bitbuf. */
43 machine_word_t bitsleft;
45 /* Pointer to the next byte to be retrieved from the input buffer. */
48 /* Pointer past the end of the input buffer. */
52 /* Initialize a bitstream to read from the specified input buffer. */
54 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
59 is->end = is->next + size;
62 /* Note: for performance reasons, the following methods don't return error codes
63 * to the caller if the input buffer is overrun. Instead, they just assume that
64 * all overrun data is zeroes. This has no effect on well-formed compressed
65 * data. The only disadvantage is that bad compressed data may go undetected,
66 * but even this is irrelevant if higher level code checksums the uncompressed
69 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
70 * bits. Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
71 * may be called on the bitstream to peek or remove up to @num_bits bits. */
73 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
75 /* This currently works for at most 17 bits. */
77 if (is->bitsleft >= num_bits)
80 /*if (unlikely(is->end - is->next < 6))*/
83 /*is->bitbuf |= (machine_word_t)get_unaligned_le16(is->next + 0) << (WORDBITS - 16 - is->bitsleft);*/
84 /*is->bitbuf |= (machine_word_t)get_unaligned_le16(is->next + 2) << (WORDBITS - 32 - is->bitsleft);*/
85 /*is->bitbuf |= (machine_word_t)get_unaligned_le16(is->next + 4) << (WORDBITS - 48 - is->bitsleft);*/
87 /*is->bitsleft += 48;*/
92 if (likely(is->end - is->next >= 2)) {
94 (machine_word_t)get_unaligned_le16(is->next) <<
95 (WORDBITS - 16 - is->bitsleft);
99 if (unlikely(num_bits > 16 && is->bitsleft < num_bits)) {
100 if (likely(is->end - is->next >= 2)) {
102 (machine_word_t)get_unaligned_le16(is->next) <<
103 (WORDBITS - 16 - is->bitsleft);
107 if (unlikely(num_bits > 32 && is->bitsleft < num_bits)) {
108 if (likely(is->end - is->next >= 2)) {
110 (machine_word_t)get_unaligned_le16(is->next) <<
111 (WORDBITS - 16 - is->bitsleft);
119 /* Return the next @num_bits bits from the bitstream, without removing them.
120 * There must be at least @num_bits remaining in the buffer variable, from a
121 * previous call to bitstream_ensure_bits(). */
123 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
125 return (is->bitbuf >> 1) >> (WORDBITS - num_bits - 1);
128 /* Remove @num_bits from the bitstream. There must be at least @num_bits
129 * remaining in the buffer variable, from a previous call to
130 * bitstream_ensure_bits(). */
132 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
134 is->bitbuf <<= num_bits;
135 is->bitsleft -= num_bits;
138 /* Remove and return @num_bits bits from the bitstream. There must be at least
139 * @num_bits remaining in the buffer variable, from a previous call to
140 * bitstream_ensure_bits(). */
142 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
144 u32 bits = bitstream_peek_bits(is, num_bits);
145 bitstream_remove_bits(is, num_bits);
149 /* Read and return the next @num_bits bits from the bitstream. */
151 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
153 bitstream_ensure_bits(is, num_bits);
154 return bitstream_pop_bits(is, num_bits);
157 /* Read and return the next literal byte embedded in the bitstream. */
159 bitstream_read_byte(struct input_bitstream *is)
161 if (unlikely(is->end == is->next))
166 /* Read and return the next 16-bit integer embedded in the bitstream. */
168 bitstream_read_u16(struct input_bitstream *is)
172 if (unlikely(is->end - is->next < 2))
174 v = get_unaligned_le16(is->next);
179 /* Read and return the next 32-bit integer embedded in the bitstream. */
181 bitstream_read_u32(struct input_bitstream *is)
185 if (unlikely(is->end - is->next < 4))
187 v = get_unaligned_le32(is->next);
192 /* Read into @dst_buffer an array of literal bytes embedded in the bitstream.
193 * Return 0 if there were enough bytes remaining in the input, otherwise -1. */
195 bitstream_read_bytes(struct input_bitstream *is, void *dst_buffer, size_t count)
197 if (unlikely(is->end - is->next < count))
199 memcpy(dst_buffer, is->next, count);
204 /* Align the input bitstream on a coding-unit boundary. */
206 bitstream_align(struct input_bitstream *is)
212 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
214 * Reason: We may fill the entries with SSE instructions without worrying
215 * about dealing with the unaligned case. */
216 #define DECODE_TABLE_ALIGNMENT 16
218 #define DECODE_TABLE_SYMBOL_SHIFT 4
219 #define DECODE_TABLE_LENGTH_MASK DECODE_TABLE_MAX_LENGTH
221 #define DECODE_TABLE_MAX_NUM_SYMS ((1 << (16 - DECODE_TABLE_SYMBOL_SHIFT)) - 1)
222 #define DECODE_TABLE_MAX_LENGTH ((1 << DECODE_TABLE_SYMBOL_SHIFT) - 1)
225 * Reads and returns the next Huffman-encoded symbol from a bitstream.
227 * If the input data is exhausted, the Huffman symbol is decoded as if the
228 * missing bits are all zeroes.
230 * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
233 static inline unsigned
234 pop_huffsym(struct input_bitstream *is, const u16 decode_table[],
235 unsigned table_bits, unsigned max_codeword_len)
241 /* Index the root table by the next 'table_bits' bits of input. */
242 entry = decode_table[bitstream_peek_bits(is, table_bits)];
244 /* Extract the symbol and length from the entry. */
245 sym = entry >> DECODE_TABLE_SYMBOL_SHIFT;
246 len = entry & DECODE_TABLE_LENGTH_MASK;
248 /* If the root table is indexed by the full 'max_codeword_len' bits,
249 * then there cannot be any subtables. This will be known at compile
250 * time. Otherwise, we must check whether the decoded symbol is really
251 * a subtable pointer. If so, we must discard the bits with which the
252 * root table was indexed, then index the subtable by the next 'len'
253 * bits of input to get the real entry. */
254 if (max_codeword_len > table_bits &&
255 entry >= (1U << (table_bits + DECODE_TABLE_SYMBOL_SHIFT)))
257 /* Subtable required */
258 bitstream_remove_bits(is, table_bits);
259 entry = decode_table[sym + bitstream_peek_bits(is, len)];
260 sym = entry >> DECODE_TABLE_SYMBOL_SHIFT;;
261 len = entry & DECODE_TABLE_LENGTH_MASK;
264 /* Discard the bits (or the remaining bits, if a subtable was required)
265 * of the codeword. */
266 bitstream_remove_bits(is, len);
268 /* Return the decoded symbol. */
273 * The ENOUGH() macro returns the maximum number of decode table entries,
274 * including all subtable entries, that may be required for decoding a given
275 * Huffman code. This depends on three parameters:
277 * num_syms: the maximum number of symbols in the code
278 * table_bits: the number of bits with which the root table will be indexed
279 * max_codeword_len: the maximum allowed codeword length
281 * Given these parameters, the utility program 'enough' from zlib, when run as
282 * './enough num_syms table_bits max_codeword_len', will compute the maximum
283 * number of entries required. This has already been done for the combinations
284 * we need (or may need) and incorporated into the macro below so that the
285 * mapping can be done at compilation time. If an unknown combination is used,
286 * then a compilation error will result. To fix this, use 'enough' to find the
287 * missing value and add it below.
289 #define ENOUGH(num_syms, table_bits, max_codeword_len) ( \
290 ((num_syms) == 8 && (table_bits) == 7 && (max_codeword_len) == 15) ? 128 : \
291 ((num_syms) == 8 && (table_bits) == 5 && (max_codeword_len) == 7) ? 36 : \
292 ((num_syms) == 8 && (table_bits) == 6 && (max_codeword_len) == 7) ? 66 : \
293 ((num_syms) == 8 && (table_bits) == 7 && (max_codeword_len) == 7) ? 128 : \
294 ((num_syms) == 20 && (table_bits) == 5 && (max_codeword_len) == 15) ? 1062 : \
295 ((num_syms) == 20 && (table_bits) == 6 && (max_codeword_len) == 15) ? 582 : \
296 ((num_syms) == 20 && (table_bits) == 7 && (max_codeword_len) == 15) ? 390 : \
297 ((num_syms) == 54 && (table_bits) == 9 && (max_codeword_len) == 15) ? 618 : \
298 ((num_syms) == 54 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1098 : \
299 ((num_syms) == 249 && (table_bits) == 9 && (max_codeword_len) == 16) ? 878 : \
300 ((num_syms) == 249 && (table_bits) == 10 && (max_codeword_len) == 16) ? 1326 : \
301 ((num_syms) == 249 && (table_bits) == 11 && (max_codeword_len) == 16) ? 2318 : \
302 ((num_syms) == 256 && (table_bits) == 9 && (max_codeword_len) == 15) ? 822 : \
303 ((num_syms) == 256 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1302 : \
304 ((num_syms) == 256 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2310 : \
305 ((num_syms) == 512 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1558 : \
306 ((num_syms) == 512 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2566 : \
307 ((num_syms) == 512 && (table_bits) == 12 && (max_codeword_len) == 15) ? 4606 : \
308 ((num_syms) == 656 && (table_bits) == 10 && (max_codeword_len) == 16) ? 1734 : \
309 ((num_syms) == 656 && (table_bits) == 11 && (max_codeword_len) == 16) ? 2726 : \
310 ((num_syms) == 656 && (table_bits) == 12 && (max_codeword_len) == 16) ? 4758 : \
311 ((num_syms) == 799 && (table_bits) == 9 && (max_codeword_len) == 15) ? 1366 : \
312 ((num_syms) == 799 && (table_bits) == 10 && (max_codeword_len) == 15) ? 1846 : \
313 ((num_syms) == 799 && (table_bits) == 11 && (max_codeword_len) == 15) ? 2854 : \
316 /* Wrapper around ENOUGH() that does additional compile-time validation. */
317 #define DECODE_TABLE_LENGTH(num_syms, table_bits, max_codeword_len) ( \
319 /* Every possible symbol value must fit into the symbol portion \
320 * of a decode table entry. */ \
321 STATIC_ASSERT_ZERO((num_syms) <= DECODE_TABLE_MAX_NUM_SYMS) + \
323 /* There cannot be more symbols than possible codewords. */ \
324 STATIC_ASSERT_ZERO((num_syms) <= 1U << (max_codeword_len)) + \
326 /* It doesn't make sense to use a table_bits more than the \
327 * maximum codeword length. */ \
328 STATIC_ASSERT_ZERO((max_codeword_len) >= (table_bits)) + \
330 /* The maximum length in the root table must fit into the \
331 * length portion of a decode table entry. */ \
332 STATIC_ASSERT_ZERO((table_bits) <= DECODE_TABLE_MAX_LENGTH) + \
334 /* The maximum length in a subtable must fit into the length
335 * portion of a decode table entry. */ \
336 STATIC_ASSERT_ZERO((max_codeword_len) - (table_bits) <= \
337 DECODE_TABLE_MAX_LENGTH) + \
339 /* The needed 'enough' value must have been defined. */ \
340 STATIC_ASSERT_ZERO(ENOUGH((num_syms), (table_bits), \
341 (max_codeword_len)) >= 0) + \
343 /* The maximum subtable index must fit in the field which would \
344 * normally hold a symbol value. */ \
345 STATIC_ASSERT_ZERO(ENOUGH((num_syms), (table_bits), \
346 (max_codeword_len)) <= \
347 DECODE_TABLE_MAX_NUM_SYMS) + \
349 /* The minimum subtable index must be greater than the greatest \
350 * possible symbol value. */ \
351 STATIC_ASSERT_ZERO((1U << table_bits) >= num_syms) + \
353 ENOUGH(num_syms, table_bits, max_codeword_len) \
357 * Declare the decode table for a Huffman code, given several compile-time
358 * constants that describe that code (see ENOUGH() for details).
360 * Decode tables must be aligned to a DECODE_TABLE_ALIGNMENT-boundary. This
361 * implies that if a decode table is nested a dynamically allocated structure,
362 * then the outer structure must be allocated on a DECODE_TABLE_ALIGNMENT-byte
365 #define DECODE_TABLE(name, num_syms, table_bits, max_codeword_len) \
366 u16 name[DECODE_TABLE_LENGTH((num_syms), (table_bits), \
367 (max_codeword_len))] \
368 _aligned_attribute(DECODE_TABLE_ALIGNMENT)
371 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
372 unsigned table_bits, const u8 lens[],
373 unsigned max_codeword_len);
376 copy_word_unaligned(const void *src, void *dst)
378 store_word_unaligned(load_word_unaligned(src), dst);
381 static inline machine_word_t
384 machine_word_t v = b;
386 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
388 v |= v << ((WORDBITS == 64) ? 32 : 0);
392 static inline machine_word_t
395 return repeat_u16(((u16)b << 8) | b);
399 * Copy an LZ77 match at (dst - offset) to dst.
401 * The length and offset must be already validated --- that is, (dst - offset)
402 * can't underrun the output buffer, and (dst + length) can't overrun the output
403 * buffer. Also, the length cannot be 0.
405 * @winend points to the byte past the end of the output buffer.
406 * This function won't write any data beyond this position.
409 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
411 const u8 *src = dst - offset;
412 const u8 * const end = dst + length;
415 * Try to copy one machine word at a time. On i386 and x86_64 this is
416 * faster than copying one byte at a time, unless the data is
417 * near-random and all the matches have very short lengths. Note that
418 * since this requires unaligned memory accesses, it won't necessarily
419 * be faster on every architecture.
421 * Also note that we might copy more than the length of the match. For
422 * example, if a word is 8 bytes and the match is of length 5, then
423 * we'll simply copy 8 bytes. This is okay as long as we don't write
424 * beyond the end of the output buffer, hence the check for (winend -
425 * end >= WORDBYTES - 1).
427 if (UNALIGNED_ACCESS_IS_FAST && likely(winend - end >= WORDBYTES - 1)) {
429 if (offset >= WORDBYTES) {
430 /* The source and destination words don't overlap. */
432 /* To improve branch prediction, one iteration of this
433 * loop is unrolled. Most matches are short and will
434 * fail the first check. But if that check passes, then
435 * it becomes increasing likely that the match is long
436 * and we'll need to continue copying. */
438 copy_word_unaligned(src, dst);
444 copy_word_unaligned(src, dst);
450 } else if (offset == 1) {
452 /* Offset 1 matches are equivalent to run-length
453 * encoding of the previous byte. This case is common
454 * if the data contains many repeated bytes. */
456 machine_word_t v = repeat_u8(*(dst - 1));
458 store_word_unaligned(v, dst);
465 * We don't bother with special cases for other 'offset <
466 * WORDBYTES', which are usually rarer than 'offset == 1'.
467 * Extra checks will just slow things down. Actually, it's
468 * possible to handle all the 'offset < WORDBYTES' cases using
469 * the same code, but it still becomes more complicated doesn't
470 * seem any faster overall; it definitely slows down the more
471 * common 'offset == 1' case.
475 /* Fall back to a bytewise copy. */
477 if (min_length >= 2) {
481 if (min_length >= 3) {
485 if (min_length >= 4) {
494 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */