4 * A compressor for the LZX compression format, as used in WIM files.
8 * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
10 * This file is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option) any
15 * This file 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 GNU Lesser General Public License for more
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this file; if not, see http://www.gnu.org/licenses/.
26 * This file contains a compressor for the LZX ("Lempel-Ziv eXtended")
27 * compression format, as used in the WIM (Windows IMaging) file format.
29 * Two different parsing algorithms are implemented: "near-optimal" and "lazy".
30 * "Near-optimal" is significantly slower than "lazy", but results in a better
31 * compression ratio. The "near-optimal" algorithm is used at the default
34 * This file may need some slight modifications to be used outside of the WIM
35 * format. In particular, in other situations the LZX block header might be
36 * slightly different, and sliding window support might be required.
38 * Note: LZX is a compression format derived from DEFLATE, the format used by
39 * zlib and gzip. Both LZX and DEFLATE use LZ77 matching and Huffman coding.
40 * Certain details are quite similar, such as the method for storing Huffman
41 * codes. However, the main differences are:
43 * - LZX preprocesses the data to attempt to make x86 machine code slightly more
44 * compressible before attempting to compress it further.
46 * - LZX uses a "main" alphabet which combines literals and matches, with the
47 * match symbols containing a "length header" (giving all or part of the match
48 * length) and an "offset slot" (giving, roughly speaking, the order of
49 * magnitude of the match offset).
51 * - LZX does not have static Huffman blocks (that is, the kind with preset
52 * Huffman codes); however it does have two types of dynamic Huffman blocks
53 * ("verbatim" and "aligned").
55 * - LZX has a minimum match length of 2 rather than 3. Length 2 matches can be
56 * useful, but generally only if the parser is smart about choosing them.
58 * - In LZX, offset slots 0 through 2 actually represent entries in an LRU queue
59 * of match offsets. This is very useful for certain types of files, such as
60 * binary files that have repeating records.
68 * Start a new LZX block (with new Huffman codes) after this many bytes.
70 * Note: actual block sizes may slightly exceed this value.
72 * TODO: recursive splitting and cost evaluation might be good for an extremely
73 * high compression mode, but otherwise it is almost always far too slow for how
74 * much it helps. Perhaps some sort of heuristic would be useful?
76 #define LZX_DIV_BLOCK_SIZE 32768
79 * LZX_CACHE_PER_POS is the number of lz_match structures to reserve in the
80 * match cache for each byte position. This value should be high enough so that
81 * nearly the time, all matches found in a given block can fit in the match
82 * cache. However, fallback behavior (immediately terminating the block) on
83 * cache overflow is still required.
85 #define LZX_CACHE_PER_POS 7
88 * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
89 * excluding the extra "overflow" entries. The per-position multiplier is '1 +
90 * LZX_CACHE_PER_POS' instead of 'LZX_CACHE_PER_POS' because there is an
91 * overhead of one lz_match per position, used to hold the match count at that
94 #define LZX_CACHE_LENGTH (LZX_DIV_BLOCK_SIZE * (1 + LZX_CACHE_PER_POS))
97 * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
98 * ever be saved in the match cache for a single position. Since each match we
99 * save for a single position has a distinct length, we can use the number of
100 * possible match lengths in LZX as this bound. This bound is guaranteed to be
101 * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
102 * it will never actually be reached.
104 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
107 * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
108 * This makes it possible to consider fractional bit costs.
110 * Note: this is only useful as a statistical trick for when the true costs are
111 * unknown. In reality, each token in LZX requires a whole number of bits to
114 #define LZX_BIT_COST 16
117 * Consideration of aligned offset costs is disabled for now, due to
118 * insufficient benefit gained from the time spent.
120 #define LZX_CONSIDER_ALIGNED_COSTS 0
123 * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
126 #define LZX_MAX_FAST_LEVEL 34
129 * LZX_HASH2_ORDER is the log base 2 of the number of entries in the hash table
130 * for finding length 2 matches. This can be as high as 16 (in which case the
131 * hash function is trivial), but using a smaller hash table speeds up
132 * compression due to reduced cache pressure.
134 #define LZX_HASH2_ORDER 12
135 #define LZX_HASH2_LENGTH (1UL << LZX_HASH2_ORDER)
137 #include "wimlib/lzx_common.h"
140 * The maximum allowed window order for the matchfinder.
142 #define MATCHFINDER_MAX_WINDOW_ORDER LZX_MAX_WINDOW_ORDER
146 #include "wimlib/bt_matchfinder.h"
147 #include "wimlib/compress_common.h"
148 #include "wimlib/compressor_ops.h"
149 #include "wimlib/error.h"
150 #include "wimlib/hc_matchfinder.h"
151 #include "wimlib/lz_extend.h"
152 #include "wimlib/unaligned.h"
153 #include "wimlib/util.h"
155 struct lzx_output_bitstream;
157 /* Codewords for the LZX Huffman codes. */
158 struct lzx_codewords {
159 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
160 u32 len[LZX_LENCODE_NUM_SYMBOLS];
161 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
164 /* Codeword lengths (in bits) for the LZX Huffman codes.
165 * A zero length means the corresponding codeword has zero frequency. */
167 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
168 u8 len[LZX_LENCODE_NUM_SYMBOLS];
169 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
172 /* Cost model for near-optimal parsing */
175 /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
176 * length 'len' match that has an offset belonging to 'offset_slot'. */
177 u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
179 /* Cost for each symbol in the main code */
180 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
182 /* Cost for each symbol in the length code */
183 u32 len[LZX_LENCODE_NUM_SYMBOLS];
185 #if LZX_CONSIDER_ALIGNED_COSTS
186 /* Cost for each symbol in the aligned code */
187 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
191 /* Codewords and lengths for the LZX Huffman codes. */
193 struct lzx_codewords codewords;
194 struct lzx_lens lens;
197 /* Symbol frequency counters for the LZX Huffman codes. */
199 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
200 u32 len[LZX_LENCODE_NUM_SYMBOLS];
201 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
204 /* Intermediate LZX match/literal format */
207 /* Bits 0 - 9: Main symbol
208 * Bits 10 - 17: Length symbol
209 * Bits 18 - 22: Number of extra offset bits
210 * Bits 23+ : Extra offset bits */
215 * This structure represents a byte position in the input buffer and a node in
216 * the graph of possible match/literal choices.
218 * Logically, each incoming edge to this node is labeled with a literal or a
219 * match that can be taken to reach this position from an earlier position; and
220 * each outgoing edge from this node is labeled with a literal or a match that
221 * can be taken to advance from this position to a later position.
223 struct lzx_optimum_node {
225 /* The cost, in bits, of the lowest-cost path that has been found to
226 * reach this position. This can change as progressively lower cost
227 * paths are found to reach this position. */
231 * The match or literal that was taken to reach this position. This can
232 * change as progressively lower cost paths are found to reach this
235 * This variable is divided into two bitfields.
238 * Low bits are 1, high bits are the literal.
240 * Explicit offset matches:
241 * Low bits are the match length, high bits are the offset plus 2.
243 * Repeat offset matches:
244 * Low bits are the match length, high bits are the queue index.
247 #define OPTIMUM_OFFSET_SHIFT 9
248 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
249 } _aligned_attribute(8);
252 * Least-recently-used queue for match offsets.
254 * This is represented as a 64-bit integer for efficiency. There are three
255 * offsets of 21 bits each. Bit 64 is garbage.
257 struct lzx_lru_queue {
261 #define LZX_QUEUE64_OFFSET_SHIFT 21
262 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
264 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
265 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
266 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
268 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
269 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
270 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
273 lzx_lru_queue_init(struct lzx_lru_queue *queue)
275 queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
276 ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
277 ((u64)1 << LZX_QUEUE64_R2_SHIFT);
281 lzx_lru_queue_R0(struct lzx_lru_queue queue)
283 return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
287 lzx_lru_queue_R1(struct lzx_lru_queue queue)
289 return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
293 lzx_lru_queue_R2(struct lzx_lru_queue queue)
295 return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
298 /* Push a match offset onto the front (most recently used) end of the queue. */
299 static inline struct lzx_lru_queue
300 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
302 return (struct lzx_lru_queue) {
303 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
307 /* Pop a match offset off the front (most recently used) end of the queue. */
309 lzx_lru_queue_pop(struct lzx_lru_queue *queue_p)
311 u32 offset = queue_p->R & LZX_QUEUE64_OFFSET_MASK;
312 queue_p->R >>= LZX_QUEUE64_OFFSET_SHIFT;
316 /* Swap a match offset to the front of the queue. */
317 static inline struct lzx_lru_queue
318 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
324 return (struct lzx_lru_queue) {
325 .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
326 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
327 (queue.R & LZX_QUEUE64_R2_MASK),
330 return (struct lzx_lru_queue) {
331 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
332 (queue.R & LZX_QUEUE64_R1_MASK) |
333 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
337 /* The main LZX compressor structure */
338 struct lzx_compressor {
340 /* The "nice" match length: if a match of this length is found, then
341 * choose it immediately without further consideration. */
342 unsigned nice_match_length;
344 /* The maximum search depth: consider at most this many potential
345 * matches at each position. */
346 unsigned max_search_depth;
348 /* The log base 2 of the LZX window size for LZ match offset encoding
349 * purposes. This will be >= LZX_MIN_WINDOW_ORDER and <=
350 * LZX_MAX_WINDOW_ORDER. */
351 unsigned window_order;
353 /* The number of symbols in the main alphabet. This depends on
354 * @window_order, since @window_order determines the maximum possible
356 unsigned num_main_syms;
358 /* Number of optimization passes per block */
359 unsigned num_optim_passes;
361 /* The preprocessed buffer of data being compressed */
364 /* The number of bytes of data to be compressed, which is the number of
365 * bytes of data in @in_buffer that are actually valid. */
368 /* Pointer to the compress() implementation chosen at allocation time */
369 void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
371 /* If true, the compressor need not preserve the input buffer if it
372 * compresses the data successfully. */
375 /* The Huffman symbol frequency counters for the current block. */
376 struct lzx_freqs freqs;
378 /* The Huffman codes for the current and previous blocks. The one with
379 * index 'codes_index' is for the current block, and the other one is
380 * for the previous block. */
381 struct lzx_codes codes[2];
382 unsigned codes_index;
385 * The match/literal sequence the algorithm chose for the current block.
387 * Notes on how large this array actually needs to be:
389 * - In lzx_compress_near_optimal(), the maximum block size is
390 * 'LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1' bytes. This occurs if
391 * a match of the maximum length is found on the last byte. Although
392 * it is impossible for this particular case to actually result in a
393 * parse of all literals, we reserve this many spaces anyway.
395 * - The worst case for lzx_compress_lazy() is a block of almost all
396 * literals that ends with a series of matches of increasing scores,
397 * causing a sequence of literals to be chosen before the last match
398 * is finally chosen. The number of items actually chosen in this
399 * scenario is limited by the number of distinct match scores that
400 * exist for matches shorter than 'nice_match_length'. Having
401 * 'LZX_MAX_MATCH_LEN - 1' extra spaces is plenty for now.
403 struct lzx_item chosen_items[LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1];
405 /* Table mapping match offset => offset slot for small offsets */
406 #define LZX_NUM_FAST_OFFSETS 32768
407 u8 offset_slot_fast[LZX_NUM_FAST_OFFSETS];
410 /* Data for greedy or lazy parsing */
412 /* Hash chains matchfinder (MUST BE LAST!!!) */
413 struct hc_matchfinder hc_mf;
416 /* Data for near-optimal parsing */
419 * The graph nodes for the current block.
421 * We need at least 'LZX_DIV_BLOCK_SIZE +
422 * LZX_MAX_MATCH_LEN - 1' nodes because that is the
423 * maximum block size that may be used. Add 1 because
424 * we need a node to represent end-of-block.
426 * It is possible that nodes past end-of-block are
427 * accessed during match consideration, but this can
428 * only occur if the block was truncated at
429 * LZX_DIV_BLOCK_SIZE. So the same bound still applies.
430 * Note that since nodes past the end of the block will
431 * never actually have an effect on the items that are
432 * chosen for the block, it makes no difference what
433 * their costs are initialized to (if anything).
435 struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
436 LZX_MAX_MATCH_LEN - 1 + 1];
438 /* The cost model for the current block */
439 struct lzx_costs costs;
442 * Cached matches for the current block. This array
443 * contains the matches that were found at each position
444 * in the block. Specifically, for each position, there
445 * is a special 'struct lz_match' whose 'length' field
446 * contains the number of matches that were found at
447 * that position; this is followed by the matches
448 * themselves, if any, sorted by strictly increasing
451 * Note: in rare cases, there will be a very high number
452 * of matches in the block and this array will overflow.
453 * If this happens, we force the end of the current
454 * block. LZX_CACHE_LENGTH is the length at which we
455 * actually check for overflow. The extra slots beyond
456 * this are enough to absorb the worst case overflow,
457 * which occurs if starting at
458 * &match_cache[LZX_CACHE_LENGTH - 1], we write the
459 * match count header, then write
460 * LZX_MAX_MATCHES_PER_POS matches, then skip searching
461 * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
462 * write the match count header for each.
464 struct lz_match match_cache[LZX_CACHE_LENGTH +
465 LZX_MAX_MATCHES_PER_POS +
466 LZX_MAX_MATCH_LEN - 1];
468 /* Hash table for finding length 2 matches */
469 pos_t hash2_tab[LZX_HASH2_LENGTH]
470 _aligned_attribute(MATCHFINDER_ALIGNMENT);
472 /* Binary trees matchfinder (MUST BE LAST!!!) */
473 struct bt_matchfinder bt_mf;
479 * Structure to keep track of the current state of sending bits to the
480 * compressed output buffer.
482 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
484 struct lzx_output_bitstream {
486 /* Bits that haven't yet been written to the output buffer. */
489 /* Number of bits currently held in @bitbuf. */
492 /* Pointer to the start of the output buffer. */
495 /* Pointer to the position in the output buffer at which the next coding
496 * unit should be written. */
499 /* Pointer just past the end of the output buffer, rounded down to a
500 * 2-byte boundary. */
505 * Initialize the output bitstream.
508 * The output bitstream structure to initialize.
510 * The buffer being written to.
512 * Size of @buffer, in bytes.
515 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
520 os->next = os->start;
521 os->end = os->start + (size & ~1);
525 * Write some bits to the output bitstream.
527 * The bits are given by the low-order @num_bits bits of @bits. Higher-order
528 * bits in @bits cannot be set. At most 17 bits can be written at once.
530 * @max_num_bits is a compile-time constant that specifies the maximum number of
531 * bits that can ever be written at the call site. It is used to optimize away
532 * the conditional code for writing a second 16-bit coding unit when writing
533 * fewer than 17 bits.
535 * If the output buffer space is exhausted, then the bits will be ignored, and
536 * lzx_flush_output() will return 0 when it gets called.
539 lzx_write_varbits(struct lzx_output_bitstream *os,
540 const u32 bits, const unsigned num_bits,
541 const unsigned max_num_bits)
543 /* This code is optimized for LZX, which never needs to write more than
544 * 17 bits at once. */
545 LZX_ASSERT(num_bits <= 17);
546 LZX_ASSERT(num_bits <= max_num_bits);
547 LZX_ASSERT(os->bitcount <= 15);
549 /* Add the bits to the bit buffer variable. @bitcount will be at most
550 * 15, so there will be just enough space for the maximum possible
551 * @num_bits of 17. */
552 os->bitcount += num_bits;
553 os->bitbuf = (os->bitbuf << num_bits) | bits;
555 /* Check whether any coding units need to be written. */
556 if (os->bitcount >= 16) {
560 /* Write a coding unit, unless it would overflow the buffer. */
561 if (os->next != os->end) {
562 put_unaligned_u16_le(os->bitbuf >> os->bitcount, os->next);
566 /* If writing 17 bits, a second coding unit might need to be
567 * written. But because 'max_num_bits' is a compile-time
568 * constant, the compiler will optimize away this code at most
570 if (max_num_bits == 17 && os->bitcount == 16) {
571 if (os->next != os->end) {
572 put_unaligned_u16_le(os->bitbuf, os->next);
580 /* Use when @num_bits is a compile-time constant. Otherwise use
581 * lzx_write_varbits(). */
583 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
585 lzx_write_varbits(os, bits, num_bits, num_bits);
589 * Flush the last coding unit to the output buffer if needed. Return the total
590 * number of bytes written to the output buffer, or 0 if an overflow occurred.
593 lzx_flush_output(struct lzx_output_bitstream *os)
595 if (os->next == os->end)
598 if (os->bitcount != 0) {
599 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next);
603 return os->next - os->start;
606 /* Build the main, length, and aligned offset Huffman codes used in LZX.
608 * This takes as input the frequency tables for each code and produces as output
609 * a set of tables that map symbols to codewords and codeword lengths. */
611 lzx_make_huffman_codes(struct lzx_compressor *c)
613 const struct lzx_freqs *freqs = &c->freqs;
614 struct lzx_codes *codes = &c->codes[c->codes_index];
616 make_canonical_huffman_code(c->num_main_syms,
617 LZX_MAX_MAIN_CODEWORD_LEN,
620 codes->codewords.main);
622 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
623 LZX_MAX_LEN_CODEWORD_LEN,
626 codes->codewords.len);
628 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
629 LZX_MAX_ALIGNED_CODEWORD_LEN,
632 codes->codewords.aligned);
635 /* Reset the symbol frequencies for the LZX Huffman codes. */
637 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
639 memset(&c->freqs, 0, sizeof(c->freqs));
643 lzx_compute_precode_items(const u8 lens[restrict],
644 const u8 prev_lens[restrict],
645 const unsigned num_lens,
646 u32 precode_freqs[restrict],
647 unsigned precode_items[restrict])
656 itemptr = precode_items;
659 /* Find the next run of codeword lengths. */
661 /* len = the length being repeated */
662 len = lens[run_start];
664 run_end = run_start + 1;
666 /* Fast case for a single length. */
667 if (likely(run_end == num_lens || len != lens[run_end])) {
668 delta = prev_lens[run_start] - len;
671 precode_freqs[delta]++;
677 /* Extend the run. */
680 } while (run_end != num_lens && len == lens[run_end]);
685 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
686 while ((run_end - run_start) >= 20) {
687 extra_bits = min((run_end - run_start) - 20, 0x1f);
689 *itemptr++ = 18 | (extra_bits << 5);
690 run_start += 20 + extra_bits;
693 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
694 if ((run_end - run_start) >= 4) {
695 extra_bits = min((run_end - run_start) - 4, 0xf);
697 *itemptr++ = 17 | (extra_bits << 5);
698 run_start += 4 + extra_bits;
702 /* A run of nonzero lengths. */
704 /* Symbol 19: RLE 4 to 5 of any length at a time. */
705 while ((run_end - run_start) >= 4) {
706 extra_bits = (run_end - run_start) > 4;
707 delta = prev_lens[run_start] - len;
711 precode_freqs[delta]++;
712 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
713 run_start += 4 + extra_bits;
717 /* Output any remaining lengths without RLE. */
718 while (run_start != run_end) {
719 delta = prev_lens[run_start] - len;
722 precode_freqs[delta]++;
726 } while (run_start != num_lens);
728 return itemptr - precode_items;
732 * Output a Huffman code in the compressed form used in LZX.
734 * The Huffman code is represented in the output as a logical series of codeword
735 * lengths from which the Huffman code, which must be in canonical form, can be
738 * The codeword lengths are themselves compressed using a separate Huffman code,
739 * the "precode", which contains a symbol for each possible codeword length in
740 * the larger code as well as several special symbols to represent repeated
741 * codeword lengths (a form of run-length encoding). The precode is itself
742 * constructed in canonical form, and its codeword lengths are represented
743 * literally in 20 4-bit fields that immediately precede the compressed codeword
744 * lengths of the larger code.
746 * Furthermore, the codeword lengths of the larger code are actually represented
747 * as deltas from the codeword lengths of the corresponding code in the previous
751 * Bitstream to which to write the compressed Huffman code.
753 * The codeword lengths, indexed by symbol, in the Huffman code.
755 * The codeword lengths, indexed by symbol, in the corresponding Huffman
756 * code in the previous block, or all zeroes if this is the first block.
758 * The number of symbols in the Huffman code.
761 lzx_write_compressed_code(struct lzx_output_bitstream *os,
762 const u8 lens[restrict],
763 const u8 prev_lens[restrict],
766 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
767 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
768 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
769 unsigned precode_items[num_lens];
770 unsigned num_precode_items;
771 unsigned precode_item;
772 unsigned precode_sym;
775 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
776 precode_freqs[i] = 0;
778 /* Compute the "items" (RLE / literal tokens and extra bits) with which
779 * the codeword lengths in the larger code will be output. */
780 num_precode_items = lzx_compute_precode_items(lens,
786 /* Build the precode. */
787 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
788 LZX_MAX_PRE_CODEWORD_LEN,
789 precode_freqs, precode_lens,
792 /* Output the lengths of the codewords in the precode. */
793 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
794 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
796 /* Output the encoded lengths of the codewords in the larger code. */
797 for (i = 0; i < num_precode_items; i++) {
798 precode_item = precode_items[i];
799 precode_sym = precode_item & 0x1F;
800 lzx_write_varbits(os, precode_codewords[precode_sym],
801 precode_lens[precode_sym],
802 LZX_MAX_PRE_CODEWORD_LEN);
803 if (precode_sym >= 17) {
804 if (precode_sym == 17) {
805 lzx_write_bits(os, precode_item >> 5, 4);
806 } else if (precode_sym == 18) {
807 lzx_write_bits(os, precode_item >> 5, 5);
809 lzx_write_bits(os, (precode_item >> 5) & 1, 1);
810 precode_sym = precode_item >> 6;
811 lzx_write_varbits(os, precode_codewords[precode_sym],
812 precode_lens[precode_sym],
813 LZX_MAX_PRE_CODEWORD_LEN);
819 /* Output a match or literal. */
821 lzx_write_item(struct lzx_output_bitstream *os, struct lzx_item item,
822 unsigned ones_if_aligned, const struct lzx_codes *codes)
824 u64 data = item.data;
825 unsigned main_symbol;
827 unsigned num_extra_bits;
830 main_symbol = data & 0x3FF;
832 lzx_write_varbits(os, codes->codewords.main[main_symbol],
833 codes->lens.main[main_symbol],
834 LZX_MAX_MAIN_CODEWORD_LEN);
836 if (main_symbol < LZX_NUM_CHARS) /* Literal? */
839 len_symbol = (data >> 10) & 0xFF;
841 if (len_symbol != LZX_LENCODE_NUM_SYMBOLS) {
842 lzx_write_varbits(os, codes->codewords.len[len_symbol],
843 codes->lens.len[len_symbol],
844 LZX_MAX_LEN_CODEWORD_LEN);
847 num_extra_bits = (data >> 18) & 0x1F;
848 if (num_extra_bits == 0) /* Small offset or repeat offset match? */
851 extra_bits = data >> 23;
853 if ((num_extra_bits & ones_if_aligned) >= LZX_NUM_ALIGNED_OFFSET_BITS) {
855 /* Aligned offset blocks: The low 3 bits of the extra offset
856 * bits are Huffman-encoded using the aligned offset code. The
857 * remaining bits are output literally. */
859 lzx_write_varbits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
860 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS,
861 17 - LZX_NUM_ALIGNED_OFFSET_BITS);
863 lzx_write_varbits(os,
864 codes->codewords.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
865 codes->lens.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
866 LZX_MAX_ALIGNED_CODEWORD_LEN);
868 /* Verbatim blocks, or fewer than 3 extra bits: All extra
869 * offset bits are output literally. */
870 lzx_write_varbits(os, extra_bits, num_extra_bits, 17);
875 * Write all matches and literal bytes (which were precomputed) in an LZX
876 * compressed block to the output bitstream in the final compressed
880 * The output bitstream.
882 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
883 * LZX_BLOCKTYPE_VERBATIM).
885 * The array of matches/literals to output.
887 * Number of matches/literals to output (length of @items).
889 * The main, length, and aligned offset Huffman codes for the current
890 * LZX compressed block.
893 lzx_write_items(struct lzx_output_bitstream *os, int block_type,
894 const struct lzx_item items[], u32 num_items,
895 const struct lzx_codes *codes)
897 unsigned ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
899 for (u32 i = 0; i < num_items; i++)
900 lzx_write_item(os, items[i], ones_if_aligned, codes);
904 lzx_write_compressed_block(int block_type,
906 unsigned window_order,
907 unsigned num_main_syms,
908 const struct lzx_item chosen_items[],
909 u32 num_chosen_items,
910 const struct lzx_codes * codes,
911 const struct lzx_lens * prev_lens,
912 struct lzx_output_bitstream * os)
914 LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
915 block_type == LZX_BLOCKTYPE_VERBATIM);
917 /* The first three bits indicate the type of block and are one of the
918 * LZX_BLOCKTYPE_* constants. */
919 lzx_write_bits(os, block_type, 3);
921 /* Output the block size.
923 * The original LZX format seemed to always encode the block size in 3
924 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
925 * uses the first bit to indicate whether the block is the default size
926 * (32768) or a different size given explicitly by the next 16 bits.
928 * By default, this compressor uses a window size of 32768 and therefore
929 * follows the WIMGAPI behavior. However, this compressor also supports
930 * window sizes greater than 32768 bytes, which do not appear to be
931 * supported by WIMGAPI. In such cases, we retain the default size bit
932 * to mean a size of 32768 bytes but output non-default block size in 24
933 * bits rather than 16. The compatibility of this behavior is unknown
934 * because WIMs created with chunk size greater than 32768 can seemingly
935 * only be opened by wimlib anyway. */
936 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
937 lzx_write_bits(os, 1, 1);
939 lzx_write_bits(os, 0, 1);
941 if (window_order >= 16)
942 lzx_write_bits(os, block_size >> 16, 8);
944 lzx_write_bits(os, block_size & 0xFFFF, 16);
947 /* If it's an aligned offset block, output the aligned offset code. */
948 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
949 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
950 lzx_write_bits(os, codes->lens.aligned[i],
951 LZX_ALIGNEDCODE_ELEMENT_SIZE);
955 /* Output the main code (two parts). */
956 lzx_write_compressed_code(os, codes->lens.main,
959 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
960 prev_lens->main + LZX_NUM_CHARS,
961 num_main_syms - LZX_NUM_CHARS);
963 /* Output the length code. */
964 lzx_write_compressed_code(os, codes->lens.len,
966 LZX_LENCODE_NUM_SYMBOLS);
968 /* Output the compressed matches and literals. */
969 lzx_write_items(os, block_type, chosen_items, num_chosen_items, codes);
972 /* Given the frequencies of symbols in an LZX-compressed block and the
973 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
974 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
975 * will take fewer bits to output. */
977 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
978 const struct lzx_codes * codes)
980 u32 aligned_cost = 0;
981 u32 verbatim_cost = 0;
983 /* A verbatim block requires 3 bits in each place that an aligned symbol
984 * would be used in an aligned offset block. */
985 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
986 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
987 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
990 /* Account for output of the aligned offset code. */
991 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
993 if (aligned_cost < verbatim_cost)
994 return LZX_BLOCKTYPE_ALIGNED;
996 return LZX_BLOCKTYPE_VERBATIM;
1000 * Finish an LZX block:
1002 * - build the Huffman codes
1003 * - decide whether to output the block as VERBATIM or ALIGNED
1004 * - output the block
1005 * - swap the indices of the current and previous Huffman codes
1008 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1009 u32 block_size, u32 num_chosen_items)
1013 lzx_make_huffman_codes(c);
1015 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1016 &c->codes[c->codes_index]);
1017 lzx_write_compressed_block(block_type,
1023 &c->codes[c->codes_index],
1024 &c->codes[c->codes_index ^ 1].lens,
1026 c->codes_index ^= 1;
1029 /* Return the offset slot for the specified offset, which must be
1030 * less than LZX_NUM_FAST_OFFSETS. */
1031 static inline unsigned
1032 lzx_get_offset_slot_fast(struct lzx_compressor *c, u32 offset)
1034 LZX_ASSERT(offset < LZX_NUM_FAST_OFFSETS);
1035 return c->offset_slot_fast[offset];
1038 /* Tally, and optionally record, the specified literal byte. */
1040 lzx_declare_literal(struct lzx_compressor *c, unsigned literal,
1041 struct lzx_item **next_chosen_item)
1043 unsigned main_symbol = lzx_main_symbol_for_literal(literal);
1045 c->freqs.main[main_symbol]++;
1047 if (next_chosen_item) {
1048 *(*next_chosen_item)++ = (struct lzx_item) {
1049 .data = main_symbol,
1054 /* Tally, and optionally record, the specified repeat offset match. */
1056 lzx_declare_repeat_offset_match(struct lzx_compressor *c,
1057 unsigned len, unsigned rep_index,
1058 struct lzx_item **next_chosen_item)
1060 unsigned len_header;
1061 unsigned len_symbol;
1062 unsigned main_symbol;
1064 if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1065 len_header = len - LZX_MIN_MATCH_LEN;
1066 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1068 len_header = LZX_NUM_PRIMARY_LENS;
1069 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1070 c->freqs.len[len_symbol]++;
1073 main_symbol = lzx_main_symbol_for_match(rep_index, len_header);
1075 c->freqs.main[main_symbol]++;
1077 if (next_chosen_item) {
1078 *(*next_chosen_item)++ = (struct lzx_item) {
1079 .data = (u64)main_symbol | ((u64)len_symbol << 10),
1084 /* Tally, and optionally record, the specified explicit offset match. */
1086 lzx_declare_explicit_offset_match(struct lzx_compressor *c, unsigned len, u32 offset,
1087 struct lzx_item **next_chosen_item)
1089 unsigned len_header;
1090 unsigned len_symbol;
1091 unsigned main_symbol;
1092 unsigned offset_slot;
1093 unsigned num_extra_bits;
1096 if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1097 len_header = len - LZX_MIN_MATCH_LEN;
1098 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1100 len_header = LZX_NUM_PRIMARY_LENS;
1101 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1102 c->freqs.len[len_symbol]++;
1105 offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1106 lzx_get_offset_slot_fast(c, offset) :
1107 lzx_get_offset_slot(offset);
1109 main_symbol = lzx_main_symbol_for_match(offset_slot, len_header);
1111 c->freqs.main[main_symbol]++;
1113 num_extra_bits = lzx_extra_offset_bits[offset_slot];
1115 if (num_extra_bits >= LZX_NUM_ALIGNED_OFFSET_BITS)
1116 c->freqs.aligned[(offset + LZX_OFFSET_ADJUSTMENT) &
1117 LZX_ALIGNED_OFFSET_BITMASK]++;
1119 if (next_chosen_item) {
1121 extra_bits = (offset + LZX_OFFSET_ADJUSTMENT) -
1122 lzx_offset_slot_base[offset_slot];
1124 BUILD_BUG_ON(LZX_MAINCODE_MAX_NUM_SYMBOLS > (1 << 10));
1125 BUILD_BUG_ON(LZX_LENCODE_NUM_SYMBOLS > (1 << 8));
1126 *(*next_chosen_item)++ = (struct lzx_item) {
1127 .data = (u64)main_symbol |
1128 ((u64)len_symbol << 10) |
1129 ((u64)num_extra_bits << 18) |
1130 ((u64)extra_bits << 23),
1136 /* Tally, and optionally record, the specified match or literal. */
1138 lzx_declare_item(struct lzx_compressor *c, u32 item,
1139 struct lzx_item **next_chosen_item)
1141 u32 len = item & OPTIMUM_LEN_MASK;
1142 u32 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1145 lzx_declare_literal(c, offset_data, next_chosen_item);
1146 else if (offset_data < LZX_NUM_RECENT_OFFSETS)
1147 lzx_declare_repeat_offset_match(c, len, offset_data,
1150 lzx_declare_explicit_offset_match(c, len,
1151 offset_data - LZX_OFFSET_ADJUSTMENT,
1156 lzx_record_item_list(struct lzx_compressor *c,
1157 struct lzx_optimum_node *cur_node,
1158 struct lzx_item **next_chosen_item)
1160 struct lzx_optimum_node *end_node;
1164 /* The list is currently in reverse order (last item to first item).
1166 end_node = cur_node;
1167 saved_item = cur_node->item;
1170 cur_node -= item & OPTIMUM_LEN_MASK;
1171 saved_item = cur_node->item;
1172 cur_node->item = item;
1173 } while (cur_node != c->optimum_nodes);
1175 /* Walk the list of items from beginning to end, tallying and recording
1178 lzx_declare_item(c, cur_node->item, next_chosen_item);
1179 cur_node += (cur_node->item) & OPTIMUM_LEN_MASK;
1180 } while (cur_node != end_node);
1184 lzx_tally_item_list(struct lzx_compressor *c, struct lzx_optimum_node *cur_node)
1186 /* Since we're just tallying the items, we don't need to reverse the
1187 * list. Processing the items in reverse order is fine. */
1189 lzx_declare_item(c, cur_node->item, NULL);
1190 cur_node -= (cur_node->item & OPTIMUM_LEN_MASK);
1191 } while (cur_node != c->optimum_nodes);
1195 * Find an inexpensive path through the graph of possible match/literal choices
1196 * for the current block. The nodes of the graph are
1197 * c->optimum_nodes[0...block_size]. They correspond directly to the bytes in
1198 * the current block, plus one extra node for end-of-block. The edges of the
1199 * graph are matches and literals. The goal is to find the minimum cost path
1200 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1202 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1203 * proceeding forwards one node at a time. At each node, a selection of matches
1204 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1205 * length 'len' provides a new path to reach the node 'len' bytes later. If
1206 * such a path is the lowest cost found so far to reach that later node, then
1207 * that later node is updated with the new path.
1209 * Note that although this algorithm is based on minimum cost path search, due
1210 * to various simplifying assumptions the result is not guaranteed to be the
1211 * true minimum cost, or "optimal", path over the graph of all valid LZX
1212 * representations of this block.
1214 * Also, note that because of the presence of the recent offsets queue (which is
1215 * a type of adaptive state), the algorithm cannot work backwards and compute
1216 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1217 * algorithm handles this adaptive state in the "minimum cost" parse is actually
1218 * only an approximation. It's possible for the globally optimal, minimum cost
1219 * path to contain a prefix, ending at a position, where that path prefix is
1220 * *not* the minimum cost path to that position. This can happen if such a path
1221 * prefix results in a different adaptive state which results in lower costs
1222 * later. The algorithm does not solve this problem; it only considers the
1223 * lowest cost to reach each individual position.
1225 static struct lzx_lru_queue
1226 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1227 const u8 * const restrict block_begin,
1228 const u32 block_size,
1229 const struct lzx_lru_queue initial_queue)
1231 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1232 struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1233 struct lz_match *cache_ptr = c->match_cache;
1234 const u8 *in_next = block_begin;
1235 const u8 * const block_end = block_begin + block_size;
1237 /* Instead of storing the match offset LRU queues in the
1238 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1239 * storing them in a smaller array. This works because the algorithm
1240 * only requires a limited history of the adaptive state. Once a given
1241 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1242 * it is no longer needed. */
1243 struct lzx_lru_queue queues[512];
1245 BUILD_BUG_ON(ARRAY_LEN(queues) < LZX_MAX_MATCH_LEN + 1);
1246 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1248 /* Initially, the cost to reach each node is "infinity". */
1249 memset(c->optimum_nodes, 0xFF,
1250 (block_size + 1) * sizeof(c->optimum_nodes[0]));
1252 QUEUE(block_begin) = initial_queue;
1254 /* The following loop runs 'block_size' iterations, one per node. */
1256 unsigned num_matches;
1261 * A selection of matches for the block was already saved in
1262 * memory so that we don't have to run the uncompressed data
1263 * through the matchfinder on every optimization pass. However,
1264 * we still search for repeat offset matches during each
1265 * optimization pass because we cannot predict the state of the
1266 * recent offsets queue. But as a heuristic, we don't bother
1267 * searching for repeat offset matches if the general-purpose
1268 * matchfinder failed to find any matches.
1270 * Note that a match of length n at some offset implies there is
1271 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1272 * that same offset. In other words, we don't necessarily need
1273 * to use the full length of a match. The key heuristic that
1274 * saves a significicant amount of time is that for each
1275 * distinct length, we only consider the smallest offset for
1276 * which that length is available. This heuristic also applies
1277 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1278 * any explicit offset. Of course, this heuristic may be
1279 * produce suboptimal results because offset slots in LZX are
1280 * subject to entropy encoding, but in practice this is a useful
1284 num_matches = cache_ptr->length;
1288 struct lz_match *end_matches = cache_ptr + num_matches;
1289 unsigned next_len = LZX_MIN_MATCH_LEN;
1290 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1293 /* Consider R0 match */
1294 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1295 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1297 BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1299 u32 cost = cur_node->cost +
1300 c->costs.match_cost[0][
1301 next_len - LZX_MIN_MATCH_LEN];
1302 if (cost <= (cur_node + next_len)->cost) {
1303 (cur_node + next_len)->cost = cost;
1304 (cur_node + next_len)->item =
1305 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1307 if (unlikely(++next_len > max_len)) {
1308 cache_ptr = end_matches;
1311 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1315 /* Consider R1 match */
1316 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1317 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1319 if (matchptr[next_len - 1] != in_next[next_len - 1])
1321 for (unsigned len = 2; len < next_len - 1; len++)
1322 if (matchptr[len] != in_next[len])
1325 u32 cost = cur_node->cost +
1326 c->costs.match_cost[1][
1327 next_len - LZX_MIN_MATCH_LEN];
1328 if (cost <= (cur_node + next_len)->cost) {
1329 (cur_node + next_len)->cost = cost;
1330 (cur_node + next_len)->item =
1331 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1333 if (unlikely(++next_len > max_len)) {
1334 cache_ptr = end_matches;
1337 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1341 /* Consider R2 match */
1342 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1343 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1345 if (matchptr[next_len - 1] != in_next[next_len - 1])
1347 for (unsigned len = 2; len < next_len - 1; len++)
1348 if (matchptr[len] != in_next[len])
1351 u32 cost = cur_node->cost +
1352 c->costs.match_cost[2][
1353 next_len - LZX_MIN_MATCH_LEN];
1354 if (cost <= (cur_node + next_len)->cost) {
1355 (cur_node + next_len)->cost = cost;
1356 (cur_node + next_len)->item =
1357 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1359 if (unlikely(++next_len > max_len)) {
1360 cache_ptr = end_matches;
1363 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1367 while (next_len > cache_ptr->length)
1368 if (++cache_ptr == end_matches)
1371 /* Consider explicit offset matches */
1373 u32 offset = cache_ptr->offset;
1374 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1375 unsigned offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1376 lzx_get_offset_slot_fast(c, offset) :
1377 lzx_get_offset_slot(offset);
1379 u32 cost = cur_node->cost +
1380 c->costs.match_cost[offset_slot][
1381 next_len - LZX_MIN_MATCH_LEN];
1382 #if LZX_CONSIDER_ALIGNED_COSTS
1383 if (lzx_extra_offset_bits[offset_slot] >=
1384 LZX_NUM_ALIGNED_OFFSET_BITS)
1385 cost += c->costs.aligned[offset_data &
1386 LZX_ALIGNED_OFFSET_BITMASK];
1388 if (cost < (cur_node + next_len)->cost) {
1389 (cur_node + next_len)->cost = cost;
1390 (cur_node + next_len)->item =
1391 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1393 } while (++next_len <= cache_ptr->length);
1394 } while (++cache_ptr != end_matches);
1399 /* Consider coding a literal.
1401 * To avoid an extra branch, actually checking the preferability
1402 * of coding the literal is integrated into the queue update
1404 literal = *in_next++;
1405 cost = cur_node->cost +
1406 c->costs.main[lzx_main_symbol_for_literal(literal)];
1408 /* Advance to the next position. */
1411 /* The lowest-cost path to the current position is now known.
1412 * Finalize the recent offsets queue that results from taking
1413 * this lowest-cost path. */
1415 if (cost <= cur_node->cost) {
1416 /* Literal: queue remains unchanged. */
1417 cur_node->cost = cost;
1418 cur_node->item = (literal << OPTIMUM_OFFSET_SHIFT) | 1;
1419 QUEUE(in_next) = QUEUE(in_next - 1);
1421 /* Match: queue update is needed. */
1422 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1423 u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1424 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1425 /* Explicit offset match: insert offset at front */
1427 lzx_lru_queue_push(QUEUE(in_next - len),
1428 offset_data - LZX_OFFSET_ADJUSTMENT);
1430 /* Repeat offset match: swap offset to front */
1432 lzx_lru_queue_swap(QUEUE(in_next - len),
1436 } while (cur_node != end_node);
1438 /* Return the match offset queue at the end of the minimum cost path. */
1439 return QUEUE(block_end);
1442 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1444 lzx_compute_match_costs(struct lzx_compressor *c)
1446 unsigned num_offset_slots = lzx_get_num_offset_slots(c->window_order);
1447 struct lzx_costs *costs = &c->costs;
1449 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1451 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1452 unsigned main_symbol = lzx_main_symbol_for_match(offset_slot, 0);
1455 #if LZX_CONSIDER_ALIGNED_COSTS
1456 if (lzx_extra_offset_bits[offset_slot] >= LZX_NUM_ALIGNED_OFFSET_BITS)
1457 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1460 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1461 costs->match_cost[offset_slot][i] =
1462 costs->main[main_symbol++] + extra_cost;
1464 extra_cost += costs->main[main_symbol];
1466 for (; i < LZX_NUM_LENS; i++)
1467 costs->match_cost[offset_slot][i] =
1468 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1472 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1475 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1478 bool have_byte[256];
1479 unsigned num_used_bytes;
1481 /* The costs below are hard coded to use a scaling factor of 16. */
1482 BUILD_BUG_ON(LZX_BIT_COST != 16);
1487 * - Use smaller initial costs for literal symbols when the input buffer
1488 * contains fewer distinct bytes.
1490 * - Assume that match symbols are more costly than literal symbols.
1492 * - Assume that length symbols for shorter lengths are less costly than
1493 * length symbols for longer lengths.
1496 for (i = 0; i < 256; i++)
1497 have_byte[i] = false;
1499 for (i = 0; i < block_size; i++)
1500 have_byte[block[i]] = true;
1503 for (i = 0; i < 256; i++)
1504 num_used_bytes += have_byte[i];
1506 for (i = 0; i < 256; i++)
1507 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1509 for (; i < c->num_main_syms; i++)
1510 c->costs.main[i] = 170;
1512 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1513 c->costs.len[i] = 103 + (i / 4);
1515 #if LZX_CONSIDER_ALIGNED_COSTS
1516 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1517 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1520 lzx_compute_match_costs(c);
1523 /* Update the current cost model to reflect the computed Huffman codes. */
1525 lzx_update_costs(struct lzx_compressor *c)
1528 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1530 for (i = 0; i < c->num_main_syms; i++)
1531 c->costs.main[i] = (lens->main[i] ? lens->main[i] : 15) * LZX_BIT_COST;
1533 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1534 c->costs.len[i] = (lens->len[i] ? lens->len[i] : 15) * LZX_BIT_COST;
1536 #if LZX_CONSIDER_ALIGNED_COSTS
1537 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1538 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] : 7) * LZX_BIT_COST;
1541 lzx_compute_match_costs(c);
1544 static struct lzx_lru_queue
1545 lzx_optimize_and_write_block(struct lzx_compressor *c,
1546 struct lzx_output_bitstream *os,
1547 const u8 *block_begin, const u32 block_size,
1548 const struct lzx_lru_queue initial_queue)
1550 unsigned num_passes_remaining = c->num_optim_passes;
1551 struct lzx_item *next_chosen_item;
1552 struct lzx_lru_queue new_queue;
1554 /* The first optimization pass uses a default cost model. Each
1555 * additional optimization pass uses a cost model derived from the
1556 * Huffman code computed in the previous pass. */
1558 lzx_set_default_costs(c, block_begin, block_size);
1559 lzx_reset_symbol_frequencies(c);
1561 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1563 if (num_passes_remaining > 1) {
1564 lzx_tally_item_list(c, c->optimum_nodes + block_size);
1565 lzx_make_huffman_codes(c);
1566 lzx_update_costs(c);
1567 lzx_reset_symbol_frequencies(c);
1569 } while (--num_passes_remaining);
1571 next_chosen_item = c->chosen_items;
1572 lzx_record_item_list(c, c->optimum_nodes + block_size, &next_chosen_item);
1573 lzx_finish_block(c, os, block_size, next_chosen_item - c->chosen_items);
1578 * This is the "near-optimal" LZX compressor.
1580 * For each block, it performs a relatively thorough graph search to find an
1581 * inexpensive (in terms of compressed size) way to output that block.
1583 * Note: there are actually many things this algorithm leaves on the table in
1584 * terms of compression ratio. So although it may be "near-optimal", it is
1585 * certainly not "optimal". The goal is not to produce the optimal compression
1586 * ratio, which for LZX is probably impossible within any practical amount of
1587 * time, but rather to produce a compression ratio significantly better than a
1588 * simpler "greedy" or "lazy" parse while still being relatively fast.
1591 lzx_compress_near_optimal(struct lzx_compressor *c,
1592 struct lzx_output_bitstream *os)
1594 const u8 * const in_begin = c->in_buffer;
1595 const u8 * in_next = in_begin;
1596 const u8 * const in_end = in_begin + c->in_nbytes;
1597 unsigned max_len = LZX_MAX_MATCH_LEN;
1598 unsigned nice_len = min(c->nice_match_length, max_len);
1600 struct lzx_lru_queue queue;
1602 bt_matchfinder_init(&c->bt_mf);
1603 matchfinder_init(c->hash2_tab, LZX_HASH2_LENGTH);
1604 next_hash = bt_matchfinder_hash_3_bytes(in_next);
1605 lzx_lru_queue_init(&queue);
1608 /* Starting a new block */
1609 const u8 * const in_block_begin = in_next;
1610 const u8 * const in_block_end =
1611 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1613 /* Run the block through the matchfinder and cache the matches. */
1614 struct lz_match *cache_ptr = c->match_cache;
1616 struct lz_match *lz_matchptr;
1621 /* If approaching the end of the input buffer, adjust
1622 * 'max_len' and 'nice_len' accordingly. */
1623 if (unlikely(max_len > in_end - in_next)) {
1624 max_len = in_end - in_next;
1625 nice_len = min(max_len, nice_len);
1627 /* This extra check is needed to ensure that we
1628 * never output a length 2 match of the very
1629 * last two bytes with the very first two bytes,
1630 * since such a match has an offset too large to
1631 * be represented. */
1632 if (unlikely(max_len < 3)) {
1634 cache_ptr->length = 0;
1640 lz_matchptr = cache_ptr + 1;
1642 /* Check for a length 2 match. */
1643 hash2 = lz_hash_2_bytes(in_next, LZX_HASH2_ORDER);
1644 cur_match = c->hash2_tab[hash2];
1645 c->hash2_tab[hash2] = in_next - in_begin;
1646 if (matchfinder_node_valid(cur_match) &&
1647 (LZX_HASH2_ORDER == 16 ||
1648 load_u16_unaligned(&in_begin[cur_match]) ==
1649 load_u16_unaligned(in_next)))
1651 lz_matchptr->length = 2;
1652 lz_matchptr->offset = in_next - &in_begin[cur_match];
1656 /* Check for matches of length >= 3. */
1657 lz_matchptr = bt_matchfinder_get_matches(&c->bt_mf,
1663 c->max_search_depth,
1668 cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1669 cache_ptr = lz_matchptr;
1672 * If there was a very long match found, then don't
1673 * cache any matches for the bytes covered by that
1674 * match. This avoids degenerate behavior when
1675 * compressing highly redundant data, where the number
1676 * of matches can be very large.
1678 * This heuristic doesn't actually hurt the compression
1679 * ratio very much. If there's a long match, then the
1680 * data must be highly compressible, so it doesn't
1681 * matter as much what we do.
1683 if (best_len >= nice_len) {
1686 if (unlikely(max_len > in_end - in_next)) {
1687 max_len = in_end - in_next;
1688 nice_len = min(max_len, nice_len);
1689 if (unlikely(max_len < 3)) {
1691 cache_ptr->length = 0;
1696 c->hash2_tab[lz_hash_2_bytes(in_next, LZX_HASH2_ORDER)] =
1698 bt_matchfinder_skip_position(&c->bt_mf,
1703 c->max_search_depth,
1706 cache_ptr->length = 0;
1708 } while (--best_len);
1710 } while (in_next < in_block_end &&
1711 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1713 /* We've finished running the block through the matchfinder.
1714 * Now choose a match/literal sequence and write the block. */
1716 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1717 in_next - in_block_begin,
1719 } while (in_next != in_end);
1723 * Given a pointer to the current byte sequence and the current list of recent
1724 * match offsets, find the longest repeat offset match.
1726 * If no match of at least 2 bytes is found, then return 0.
1728 * If a match of at least 2 bytes is found, then return its length and set
1729 * *rep_max_idx_ret to the index of its offset in @queue.
1732 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1733 const u32 bytes_remaining,
1734 struct lzx_lru_queue queue,
1735 unsigned *rep_max_idx_ret)
1737 BUILD_BUG_ON(LZX_NUM_RECENT_OFFSETS != 3);
1738 LZX_ASSERT(bytes_remaining >= 2);
1740 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1741 const u16 next_2_bytes = load_u16_unaligned(in_next);
1743 unsigned rep_max_len;
1744 unsigned rep_max_idx;
1747 matchptr = in_next - lzx_lru_queue_pop(&queue);
1748 if (load_u16_unaligned(matchptr) == next_2_bytes)
1749 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1754 matchptr = in_next - lzx_lru_queue_pop(&queue);
1755 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1756 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1757 if (rep_len > rep_max_len) {
1758 rep_max_len = rep_len;
1763 matchptr = in_next - lzx_lru_queue_pop(&queue);
1764 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1765 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1766 if (rep_len > rep_max_len) {
1767 rep_max_len = rep_len;
1772 *rep_max_idx_ret = rep_max_idx;
1776 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
1777 static inline unsigned
1778 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1780 unsigned score = len;
1782 if (adjusted_offset < 4096)
1785 if (adjusted_offset < 256)
1791 static inline unsigned
1792 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1797 /* This is the "lazy" LZX compressor. */
1799 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os)
1801 const u8 * const in_begin = c->in_buffer;
1802 const u8 * in_next = in_begin;
1803 const u8 * const in_end = in_begin + c->in_nbytes;
1804 unsigned max_len = LZX_MAX_MATCH_LEN;
1805 unsigned nice_len = min(c->nice_match_length, max_len);
1806 struct lzx_lru_queue queue;
1808 hc_matchfinder_init(&c->hc_mf);
1809 lzx_lru_queue_init(&queue);
1812 /* Starting a new block */
1814 const u8 * const in_block_begin = in_next;
1815 const u8 * const in_block_end =
1816 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1817 struct lzx_item *next_chosen_item = c->chosen_items;
1820 u32 cur_offset_data;
1824 u32 next_offset_data;
1825 unsigned next_score;
1826 unsigned rep_max_len;
1827 unsigned rep_max_idx;
1831 lzx_reset_symbol_frequencies(c);
1834 if (unlikely(max_len > in_end - in_next)) {
1835 max_len = in_end - in_next;
1836 nice_len = min(max_len, nice_len);
1839 /* Find the longest match at the current position. */
1841 cur_len = hc_matchfinder_longest_match(&c->hc_mf,
1847 c->max_search_depth,
1851 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
1852 cur_offset != lzx_lru_queue_R0(queue) &&
1853 cur_offset != lzx_lru_queue_R1(queue) &&
1854 cur_offset != lzx_lru_queue_R2(queue)))
1856 /* There was no match found, or the only match found
1857 * was a distant length 3 match. Output a literal. */
1858 lzx_declare_literal(c, *in_next++,
1863 if (cur_offset == lzx_lru_queue_R0(queue)) {
1865 cur_offset_data = 0;
1866 skip_len = cur_len - 1;
1867 goto choose_cur_match;
1870 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
1871 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
1873 /* Consider a repeat offset match */
1874 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1880 if (rep_max_len >= 3 &&
1881 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1882 rep_max_idx)) >= cur_score)
1884 cur_len = rep_max_len;
1885 cur_offset_data = rep_max_idx;
1886 skip_len = rep_max_len - 1;
1887 goto choose_cur_match;
1892 /* We have a match at the current position. */
1894 /* If we have a very long match, choose it immediately. */
1895 if (cur_len >= nice_len) {
1896 skip_len = cur_len - 1;
1897 goto choose_cur_match;
1900 /* See if there's a better match at the next position. */
1902 if (unlikely(max_len > in_end - in_next)) {
1903 max_len = in_end - in_next;
1904 nice_len = min(max_len, nice_len);
1907 next_len = hc_matchfinder_longest_match(&c->hc_mf,
1913 c->max_search_depth / 2,
1916 if (next_len <= cur_len - 2) {
1918 skip_len = cur_len - 2;
1919 goto choose_cur_match;
1922 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
1923 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
1925 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1931 if (rep_max_len >= 3 &&
1932 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1933 rep_max_idx)) >= next_score)
1936 if (rep_score > cur_score) {
1937 /* The next match is better, and it's a
1938 * repeat offset match. */
1939 lzx_declare_literal(c, *(in_next - 2),
1941 cur_len = rep_max_len;
1942 cur_offset_data = rep_max_idx;
1943 skip_len = cur_len - 1;
1944 goto choose_cur_match;
1947 if (next_score > cur_score) {
1948 /* The next match is better, and it's an
1949 * explicit offset match. */
1950 lzx_declare_literal(c, *(in_next - 2),
1953 cur_offset_data = next_offset_data;
1954 cur_score = next_score;
1955 goto have_cur_match;
1959 /* The original match was better. */
1960 skip_len = cur_len - 2;
1963 if (cur_offset_data < LZX_NUM_RECENT_OFFSETS) {
1964 lzx_declare_repeat_offset_match(c, cur_len,
1967 queue = lzx_lru_queue_swap(queue, cur_offset_data);
1969 lzx_declare_explicit_offset_match(c, cur_len,
1970 cur_offset_data - LZX_OFFSET_ADJUSTMENT,
1972 queue = lzx_lru_queue_push(queue, cur_offset_data - LZX_OFFSET_ADJUSTMENT);
1975 hc_matchfinder_skip_positions(&c->hc_mf,
1980 in_next += skip_len;
1981 } while (in_next < in_block_end);
1983 lzx_finish_block(c, os, in_next - in_block_begin,
1984 next_chosen_item - c->chosen_items);
1985 } while (in_next != in_end);
1989 lzx_init_offset_slot_fast(struct lzx_compressor *c)
1993 for (u32 offset = 0; offset < LZX_NUM_FAST_OFFSETS; offset++) {
1995 while (offset + LZX_OFFSET_ADJUSTMENT >= lzx_offset_slot_base[slot + 1])
1998 c->offset_slot_fast[offset] = slot;
2003 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2005 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2006 return offsetof(struct lzx_compressor, hc_mf) +
2007 hc_matchfinder_size(max_bufsize);
2009 return offsetof(struct lzx_compressor, bt_mf) +
2010 bt_matchfinder_size(max_bufsize);
2015 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2020 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2023 size += lzx_get_compressor_size(max_bufsize, compression_level);
2025 size += max_bufsize; /* in_buffer */
2030 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2031 bool destructive, void **c_ret)
2033 unsigned window_order;
2034 struct lzx_compressor *c;
2036 window_order = lzx_get_window_order(max_bufsize);
2037 if (window_order == 0)
2038 return WIMLIB_ERR_INVALID_PARAM;
2040 c = ALIGNED_MALLOC(lzx_get_compressor_size(max_bufsize,
2042 MATCHFINDER_ALIGNMENT);
2046 c->destructive = destructive;
2048 c->num_main_syms = lzx_get_num_main_syms(window_order);
2049 c->window_order = window_order;
2051 if (!c->destructive) {
2052 c->in_buffer = MALLOC(max_bufsize);
2057 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2059 /* Fast compression: Use lazy parsing. */
2061 c->impl = lzx_compress_lazy;
2062 c->max_search_depth = (36 * compression_level) / 20;
2063 c->nice_match_length = (72 * compression_level) / 20;
2065 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2066 * halves the max_search_depth when attempting a lazy match, and
2067 * max_search_depth cannot be 0. */
2068 if (c->max_search_depth < 2)
2069 c->max_search_depth = 2;
2072 /* Normal / high compression: Use near-optimal parsing. */
2074 c->impl = lzx_compress_near_optimal;
2076 /* Scale nice_match_length and max_search_depth with the
2077 * compression level. */
2078 c->max_search_depth = (24 * compression_level) / 50;
2079 c->nice_match_length = (32 * compression_level) / 50;
2081 /* Set a number of optimization passes appropriate for the
2082 * compression level. */
2084 c->num_optim_passes = 1;
2086 if (compression_level >= 45)
2087 c->num_optim_passes++;
2089 /* Use more optimization passes for higher compression levels.
2090 * But the more passes there are, the less they help --- so
2091 * don't add them linearly. */
2092 if (compression_level >= 70) {
2093 c->num_optim_passes++;
2094 if (compression_level >= 100)
2095 c->num_optim_passes++;
2096 if (compression_level >= 150)
2097 c->num_optim_passes++;
2098 if (compression_level >= 200)
2099 c->num_optim_passes++;
2100 if (compression_level >= 300)
2101 c->num_optim_passes++;
2105 /* max_search_depth == 0 is invalid. */
2106 if (c->max_search_depth < 1)
2107 c->max_search_depth = 1;
2109 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2110 c->nice_match_length = LZX_MAX_MATCH_LEN;
2112 lzx_init_offset_slot_fast(c);
2119 return WIMLIB_ERR_NOMEM;
2123 lzx_compress(const void *restrict in, size_t in_nbytes,
2124 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2126 struct lzx_compressor *c = _c;
2127 struct lzx_output_bitstream os;
2130 /* Don't bother trying to compress very small inputs. */
2131 if (in_nbytes < 100)
2134 /* Copy the input data into the internal buffer and preprocess it. */
2136 c->in_buffer = (void *)in;
2138 memcpy(c->in_buffer, in, in_nbytes);
2139 c->in_nbytes = in_nbytes;
2140 lzx_do_e8_preprocessing(c->in_buffer, in_nbytes);
2142 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2144 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2146 /* Initialize the output bitstream. */
2147 lzx_init_output(&os, out, out_nbytes_avail);
2149 /* Call the compression level-specific compress() function. */
2152 /* Flush the output bitstream and return the compressed size or 0. */
2153 result = lzx_flush_output(&os);
2154 if (!result && c->destructive)
2155 lzx_undo_e8_preprocessing(c->in_buffer, c->in_nbytes);
2160 lzx_free_compressor(void *_c)
2162 struct lzx_compressor *c = _c;
2164 if (!c->destructive)
2169 const struct compressor_ops lzx_compressor_ops = {
2170 .get_needed_memory = lzx_get_needed_memory,
2171 .create_compressor = lzx_create_compressor,
2172 .compress = lzx_compress,
2173 .free_compressor = lzx_free_compressor,