]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
lzx word bitstream
[wimlib] / include / wimlib / decompress_common.h
1 /*
2  * decompress_common.h
3  *
4  * Header for decompression code shared by multiple compression formats.
5  *
6  * The following copying information applies to this specific source code file:
7  *
8  * Written in 2012-2016 by Eric Biggers <ebiggers3@gmail.com>
9  *
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").
14  *
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.
18  *
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/>.
21  */
22
23 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
24 #define _WIMLIB_DECOMPRESS_COMMON_H
25
26 #include <string.h>
27
28 #include "wimlib/compiler.h"
29 #include "wimlib/types.h"
30 #include "wimlib/unaligned.h"
31
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
35  * to low.  */
36 struct input_bitstream {
37
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;
41
42         /* Number of bits currently held in @bitbuf.  */
43         machine_word_t bitsleft;
44
45         /* Pointer to the next byte to be retrieved from the input buffer.  */
46         const u8 *next;
47
48         /* Pointer past the end of the input buffer.  */
49         const u8 *end;
50 };
51
52 /* Initialize a bitstream to read from the specified input buffer.  */
53 static inline void
54 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
55 {
56         is->bitbuf = 0;
57         is->bitsleft = 0;
58         is->next = buffer;
59         is->end = is->next + size;
60 }
61
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
67  * data anyway.  */
68
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.  */
72 static inline void
73 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
74 {
75         /* This currently works for at most 17 bits.  */
76
77         if (is->bitsleft >= num_bits)
78                 return;
79
80         /*if (unlikely(is->end - is->next < 6))*/
81                 /*goto slow;*/
82
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);*/
86         /*is->next += 6;*/
87         /*is->bitsleft += 48;*/
88
89         /*return;*/
90
91 /*slow:*/
92         if (likely(is->end - is->next >= 2)) {
93                 is->bitbuf |=
94                         (machine_word_t)get_unaligned_le16(is->next) <<
95                         (WORDBITS - 16 - is->bitsleft);
96                 is->next += 2;
97         }
98         is->bitsleft += 16;
99         if (unlikely(num_bits > 16 && is->bitsleft < num_bits)) {
100                 if (likely(is->end - is->next >= 2)) {
101                         is->bitbuf |=
102                                 (machine_word_t)get_unaligned_le16(is->next) <<
103                                 (WORDBITS - 16 - is->bitsleft);
104                         is->next += 2;
105                 }
106                 is->bitsleft += 16;
107                 if (unlikely(num_bits > 32 && is->bitsleft < num_bits)) {
108                         if (likely(is->end - is->next >= 2)) {
109                                 is->bitbuf |=
110                                         (machine_word_t)get_unaligned_le16(is->next) <<
111                                         (WORDBITS - 16 - is->bitsleft);
112                                 is->next += 2;
113                         }
114                         is->bitsleft += 16;
115                 }
116         }
117 }
118
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().  */
122 static inline u32
123 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
124 {
125         return (is->bitbuf >> 1) >> (WORDBITS - num_bits - 1);
126 }
127
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().  */
131 static inline void
132 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
133 {
134         is->bitbuf <<= num_bits;
135         is->bitsleft -= num_bits;
136 }
137
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().  */
141 static inline u32
142 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
143 {
144         u32 bits = bitstream_peek_bits(is, num_bits);
145         bitstream_remove_bits(is, num_bits);
146         return bits;
147 }
148
149 /* Read and return the next @num_bits bits from the bitstream.  */
150 static inline u32
151 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
152 {
153         bitstream_ensure_bits(is, num_bits);
154         return bitstream_pop_bits(is, num_bits);
155 }
156
157 /* Read and return the next literal byte embedded in the bitstream.  */
158 static inline u8
159 bitstream_read_byte(struct input_bitstream *is)
160 {
161         if (unlikely(is->end == is->next))
162                 return 0;
163         return *is->next++;
164 }
165
166 /* Read and return the next 16-bit integer embedded in the bitstream.  */
167 static inline u16
168 bitstream_read_u16(struct input_bitstream *is)
169 {
170         u16 v;
171
172         if (unlikely(is->end - is->next < 2))
173                 return 0;
174         v = get_unaligned_le16(is->next);
175         is->next += 2;
176         return v;
177 }
178
179 /* Read and return the next 32-bit integer embedded in the bitstream.  */
180 static inline u32
181 bitstream_read_u32(struct input_bitstream *is)
182 {
183         u32 v;
184
185         if (unlikely(is->end - is->next < 4))
186                 return 0;
187         v = get_unaligned_le32(is->next);
188         is->next += 4;
189         return v;
190 }
191
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. */
194 static inline int
195 bitstream_read_bytes(struct input_bitstream *is, void *dst_buffer, size_t count)
196 {
197         if (unlikely(is->end - is->next < count))
198                 return -1;
199         memcpy(dst_buffer, is->next, count);
200         is->next += count;
201         return 0;
202 }
203
204 /* Align the input bitstream on a coding-unit boundary.  */
205 static inline void
206 bitstream_align(struct input_bitstream *is)
207 {
208         is->bitsleft = 0;
209         is->bitbuf = 0;
210 }
211
212 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
213  *
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
217
218 #define DECODE_TABLE_SYMBOL_SHIFT 4
219 #define DECODE_TABLE_LENGTH_MASK DECODE_TABLE_MAX_LENGTH
220
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)
223
224 /*
225  * Reads and returns the next Huffman-encoded symbol from a bitstream.
226  *
227  * If the input data is exhausted, the Huffman symbol is decoded as if the
228  * missing bits are all zeroes.
229  *
230  * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
231  * lzms_decompress.c.
232  */
233 static inline unsigned
234 pop_huffsym(struct input_bitstream *is, const u16 decode_table[],
235             unsigned table_bits, unsigned max_codeword_len)
236 {
237         unsigned entry;
238         unsigned sym;
239         unsigned len;
240
241         /* Index the root table by the next 'table_bits' bits of input. */
242         entry = decode_table[bitstream_peek_bits(is, table_bits)];
243
244         /* Extract the symbol and length from the entry. */
245         sym = entry >> DECODE_TABLE_SYMBOL_SHIFT;
246         len = entry & DECODE_TABLE_LENGTH_MASK;
247
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)))
256         {
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;
262         }
263
264         /* Discard the bits (or the remaining bits, if a subtable was required)
265          * of the codeword. */
266         bitstream_remove_bits(is, len);
267
268         /* Return the decoded symbol. */
269         return sym;
270 }
271
272 /*
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:
276  *
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
280  *
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.
288  */
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 : \
314         -1)
315
316 /* Wrapper around ENOUGH() that does additional compile-time validation. */
317 #define DECODE_TABLE_LENGTH(num_syms, table_bits, max_codeword_len) (   \
318                                                                         \
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) +   \
322                                                                         \
323         /* There cannot be more symbols than possible codewords. */     \
324         STATIC_ASSERT_ZERO((num_syms) <= 1U << (max_codeword_len)) +    \
325                                                                         \
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)) +        \
329                                                                         \
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) +   \
333                                                                         \
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) +      \
338                                                                         \
339         /* The needed 'enough' value must have been defined. */         \
340         STATIC_ASSERT_ZERO(ENOUGH((num_syms), (table_bits),             \
341                                   (max_codeword_len)) >= 0) +           \
342                                                                         \
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) +    \
348                                                                         \
349         /* The minimum subtable index must be greater than the greatest \
350          * possible symbol value. */                                    \
351         STATIC_ASSERT_ZERO((1U << table_bits) >= num_syms) +            \
352                                                                         \
353         ENOUGH(num_syms, table_bits, max_codeword_len)                  \
354 )
355
356 /*
357  * Declare the decode table for a Huffman code, given several compile-time
358  * constants that describe that code (see ENOUGH() for details).
359  *
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
363  * boundary as well.
364  */
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)
369
370 extern int
371 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
372                           unsigned table_bits, const u8 lens[],
373                           unsigned max_codeword_len);
374
375 static inline void
376 copy_word_unaligned(const void *src, void *dst)
377 {
378         store_word_unaligned(load_word_unaligned(src), dst);
379 }
380
381 static inline machine_word_t
382 repeat_u16(u16 b)
383 {
384         machine_word_t v = b;
385
386         STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
387         v |= v << 16;
388         v |= v << ((WORDBITS == 64) ? 32 : 0);
389         return v;
390 }
391
392 static inline machine_word_t
393 repeat_u8(u8 b)
394 {
395         return repeat_u16(((u16)b << 8) | b);
396 }
397
398 /*
399  * Copy an LZ77 match at (dst - offset) to dst.
400  *
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.
404  *
405  * @winend points to the byte past the end of the output buffer.
406  * This function won't write any data beyond this position.
407  */
408 static inline void
409 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
410 {
411         const u8 *src = dst - offset;
412         const u8 * const end = dst + length;
413
414         /*
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.
420          *
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).
426          */
427         if (UNALIGNED_ACCESS_IS_FAST && likely(winend - end >= WORDBYTES - 1)) {
428
429                 if (offset >= WORDBYTES) {
430                         /* The source and destination words don't overlap.  */
431
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.  */
437
438                         copy_word_unaligned(src, dst);
439                         src += WORDBYTES;
440                         dst += WORDBYTES;
441
442                         if (dst < end) {
443                                 do {
444                                         copy_word_unaligned(src, dst);
445                                         src += WORDBYTES;
446                                         dst += WORDBYTES;
447                                 } while (dst < end);
448                         }
449                         return;
450                 } else if (offset == 1) {
451
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.  */
455
456                         machine_word_t v = repeat_u8(*(dst - 1));
457                         do {
458                                 store_word_unaligned(v, dst);
459                                 src += WORDBYTES;
460                                 dst += WORDBYTES;
461                         } while (dst < end);
462                         return;
463                 }
464                 /*
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.
472                  */
473         }
474
475         /* Fall back to a bytewise copy.  */
476
477         if (min_length >= 2) {
478                 *dst++ = *src++;
479                 length--;
480         }
481         if (min_length >= 3) {
482                 *dst++ = *src++;
483                 length--;
484         }
485         if (min_length >= 4) {
486                 *dst++ = *src++;
487                 length--;
488         }
489         do {
490                 *dst++ = *src++;
491         } while (--length);
492 }
493
494 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */