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 6
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 * The maximum compression level at which we use the faster algorithm.
125 #define LZX_MAX_FAST_LEVEL 34
128 * LZX_HASH2_ORDER is the log base 2 of the number of entries in the hash table
129 * for finding length 2 matches. This can be as high as 16 (in which case the
130 * hash function is trivial), but using a smaller hash table actually speeds up
131 * compression due to reduced cache pressure.
133 #define LZX_HASH2_ORDER 12
134 #define LZX_HASH2_LENGTH (1UL << LZX_HASH2_ORDER)
136 #include "wimlib/lzx_common.h"
139 * The maximum allowed window order for the matchfinder.
141 #define MATCHFINDER_MAX_WINDOW_ORDER LZX_MAX_WINDOW_ORDER
145 #include "wimlib/bt_matchfinder.h"
146 #include "wimlib/compress_common.h"
147 #include "wimlib/compressor_ops.h"
148 #include "wimlib/endianness.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 /* The Huffman symbol frequency counters for the current block. */
372 struct lzx_freqs freqs;
374 /* The Huffman codes for the current and previous blocks. The one with
375 * index 'codes_index' is for the current block, and the other one is
376 * for the previous block. */
377 struct lzx_codes codes[2];
378 unsigned codes_index;
381 * The match/literal sequence the algorithm chose for the current block.
383 * Notes on how large this array actually needs to be:
385 * - In lzx_compress_near_optimal(), the maximum block size is
386 * 'LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1' bytes. This occurs if
387 * a match of the maximum length is found on the last byte. Although
388 * it is impossible for this particular case to actually result in a
389 * parse of all literals, we reserve this many spaces anyway.
391 * - The worst case for lzx_compress_lazy() is a block of almost all
392 * literals that ends with a series of matches of increasing scores,
393 * causing a sequence of literals to be chosen before the last match
394 * is finally chosen. The number of items actually chosen in this
395 * scenario is limited by the number of distinct match scores that
396 * exist for matches shorter than 'nice_match_length'. Having
397 * 'LZX_MAX_MATCH_LEN - 1' extra spaces is plenty for now.
399 struct lzx_item chosen_items[LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1];
401 /* Table mapping match offset => offset slot for small offsets */
402 #define LZX_NUM_FAST_OFFSETS 32768
403 u8 offset_slot_fast[LZX_NUM_FAST_OFFSETS];
406 /* Data for greedy or lazy parsing */
408 /* Hash chains matchfinder (MUST BE LAST!!!) */
409 struct hc_matchfinder hc_mf;
412 /* Data for near-optimal parsing */
415 * The graph nodes for the current block.
417 * We need at least 'LZX_DIV_BLOCK_SIZE +
418 * LZX_MAX_MATCH_LEN - 1' nodes because that is the
419 * maximum block size that may be used. Add 1 because
420 * we need a node to represent end-of-block.
422 * It is possible that nodes past end-of-block are
423 * accessed during match consideration, but this can
424 * only occur if the block was truncated at
425 * LZX_DIV_BLOCK_SIZE. So the same bound still applies.
426 * Note that since nodes past the end of the block will
427 * never actually have an effect on the items that are
428 * chosen for the block, it makes no difference what
429 * their costs are initialized to (if anything).
431 struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
432 LZX_MAX_MATCH_LEN - 1 + 1];
434 /* The cost model for the current block */
435 struct lzx_costs costs;
438 * Cached matches for the current block. This array
439 * contains the matches that were found at each position
440 * in the block. Specifically, for each position, there
441 * is a special 'struct lz_match' whose 'length' field
442 * contains the number of matches that were found at
443 * that position; this is followed by the matches
444 * themselves, if any, sorted by strictly increasing
445 * length and strictly increasing offset.
447 * Note: in rare cases, there will be a very high number
448 * of matches in the block and this array will overflow.
449 * If this happens, we force the end of the current
450 * block. LZX_CACHE_LENGTH is the length at which we
451 * actually check for overflow. The extra slots beyond
452 * this are enough to absorb the worst case overflow,
453 * which occurs if starting at
454 * &match_cache[LZX_CACHE_LENGTH - 1], we write the
455 * match count header, then write
456 * LZX_MAX_MATCHES_PER_POS matches, then skip searching
457 * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
458 * write the match count header for each.
460 struct lz_match match_cache[LZX_CACHE_LENGTH +
461 LZX_MAX_MATCHES_PER_POS +
462 LZX_MAX_MATCH_LEN - 1];
464 /* Hash table for finding length 2 matches */
465 pos_t hash2_tab[LZX_HASH2_LENGTH]
466 _aligned_attribute(MATCHFINDER_ALIGNMENT);
468 /* Binary trees matchfinder (MUST BE LAST!!!) */
469 struct bt_matchfinder bt_mf;
474 /* Compute a hash value for the next 2 bytes of uncompressed data. */
476 lz_hash_2_bytes(const u8 *in_next)
478 u16 next_2_bytes = load_u16_unaligned(in_next);
479 if (LZX_HASH2_ORDER == 16)
482 return lz_hash(next_2_bytes, LZX_HASH2_ORDER);
486 * Structure to keep track of the current state of sending bits to the
487 * compressed output buffer.
489 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
491 struct lzx_output_bitstream {
493 /* Bits that haven't yet been written to the output buffer. */
496 /* Number of bits currently held in @bitbuf. */
499 /* Pointer to the start of the output buffer. */
502 /* Pointer to the position in the output buffer at which the next coding
503 * unit should be written. */
506 /* Pointer past the end of the output buffer. */
511 * Initialize the output bitstream.
514 * The output bitstream structure to initialize.
516 * The buffer being written to.
518 * Size of @buffer, in bytes.
521 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
526 os->next = os->start;
527 os->end = os->start + size / sizeof(le16);
531 * Write some bits to the output bitstream.
533 * The bits are given by the low-order @num_bits bits of @bits. Higher-order
534 * bits in @bits cannot be set. At most 17 bits can be written at once.
536 * @max_num_bits is a compile-time constant that specifies the maximum number of
537 * bits that can ever be written at the call site. Currently, it is used to
538 * optimize away the conditional code for writing a second 16-bit coding unit
539 * when writing fewer than 17 bits.
541 * If the output buffer space is exhausted, then the bits will be ignored, and
542 * lzx_flush_output() will return 0 when it gets called.
545 lzx_write_varbits(struct lzx_output_bitstream *os,
546 const u32 bits, const unsigned num_bits,
547 const unsigned max_num_bits)
549 /* This code is optimized for LZX, which never needs to write more than
550 * 17 bits at once. */
551 LZX_ASSERT(num_bits <= 17);
552 LZX_ASSERT(num_bits <= max_num_bits);
553 LZX_ASSERT(os->bitcount <= 15);
555 /* Add the bits to the bit buffer variable. @bitcount will be at most
556 * 15, so there will be just enough space for the maximum possible
557 * @num_bits of 17. */
558 os->bitcount += num_bits;
559 os->bitbuf = (os->bitbuf << num_bits) | bits;
561 /* Check whether any coding units need to be written. */
562 if (os->bitcount >= 16) {
566 /* Write a coding unit, unless it would overflow the buffer. */
567 if (os->next != os->end)
568 put_unaligned_u16_le(os->bitbuf >> os->bitcount, os->next++);
570 /* If writing 17 bits, a second coding unit might need to be
571 * written. But because 'max_num_bits' is a compile-time
572 * constant, the compiler will optimize away this code at most
574 if (max_num_bits == 17 && os->bitcount == 16) {
575 if (os->next != os->end)
576 put_unaligned_u16_le(os->bitbuf, os->next++);
582 /* Use when @num_bits is a compile-time constant. Otherwise use
583 * lzx_write_varbits(). */
585 lzx_write_bits(struct lzx_output_bitstream *os,
586 const u32 bits, const unsigned num_bits)
588 lzx_write_varbits(os, bits, num_bits, num_bits);
592 * Flush the last coding unit to the output buffer if needed. Return the total
593 * number of bytes written to the output buffer, or 0 if an overflow occurred.
596 lzx_flush_output(struct lzx_output_bitstream *os)
598 if (os->next == os->end)
601 if (os->bitcount != 0)
602 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next++);
604 return (const u8 *)os->next - (const u8 *)os->start;
607 /* Build the main, length, and aligned offset Huffman codes used in LZX.
609 * This takes as input the frequency tables for each code and produces as output
610 * a set of tables that map symbols to codewords and codeword lengths. */
612 lzx_make_huffman_codes(struct lzx_compressor *c)
614 const struct lzx_freqs *freqs = &c->freqs;
615 struct lzx_codes *codes = &c->codes[c->codes_index];
617 make_canonical_huffman_code(c->num_main_syms,
618 LZX_MAX_MAIN_CODEWORD_LEN,
621 codes->codewords.main);
623 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
624 LZX_MAX_LEN_CODEWORD_LEN,
627 codes->codewords.len);
629 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
630 LZX_MAX_ALIGNED_CODEWORD_LEN,
633 codes->codewords.aligned);
636 /* Reset the symbol frequencies for the LZX Huffman codes. */
638 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
640 memset(&c->freqs, 0, sizeof(c->freqs));
644 lzx_compute_precode_items(const u8 lens[restrict],
645 const u8 prev_lens[restrict],
646 const unsigned num_lens,
647 u32 precode_freqs[restrict],
648 unsigned precode_items[restrict])
657 itemptr = precode_items;
660 /* Find the next run of codeword lengths. */
662 /* len = the length being repeated */
663 len = lens[run_start];
665 run_end = run_start + 1;
667 /* Fast case for a single length. */
668 if (likely(run_end == num_lens || len != lens[run_end])) {
669 delta = prev_lens[run_start] - len;
672 precode_freqs[delta]++;
678 /* Extend the run. */
681 } while (run_end != num_lens && len == lens[run_end]);
686 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
687 while ((run_end - run_start) >= 20) {
688 extra_bits = min((run_end - run_start) - 20, 0x1f);
690 *itemptr++ = 18 | (extra_bits << 5);
691 run_start += 20 + extra_bits;
694 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
695 if ((run_end - run_start) >= 4) {
696 extra_bits = min((run_end - run_start) - 4, 0xf);
698 *itemptr++ = 17 | (extra_bits << 5);
699 run_start += 4 + extra_bits;
703 /* A run of nonzero lengths. */
705 /* Symbol 19: RLE 4 to 5 of any length at a time. */
706 while ((run_end - run_start) >= 4) {
707 extra_bits = (run_end - run_start) > 4;
708 delta = prev_lens[run_start] - len;
712 precode_freqs[delta]++;
713 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
714 run_start += 4 + extra_bits;
718 /* Output any remaining lengths without RLE. */
719 while (run_start != run_end) {
720 delta = prev_lens[run_start] - len;
723 precode_freqs[delta]++;
727 } while (run_start != num_lens);
729 return itemptr - precode_items;
733 * Output a Huffman code in the compressed form used in LZX.
735 * The Huffman code is represented in the output as a logical series of codeword
736 * lengths from which the Huffman code, which must be in canonical form, can be
739 * The codeword lengths are themselves compressed using a separate Huffman code,
740 * the "precode", which contains a symbol for each possible codeword length in
741 * the larger code as well as several special symbols to represent repeated
742 * codeword lengths (a form of run-length encoding). The precode is itself
743 * constructed in canonical form, and its codeword lengths are represented
744 * literally in 20 4-bit fields that immediately precede the compressed codeword
745 * lengths of the larger code.
747 * Furthermore, the codeword lengths of the larger code are actually represented
748 * as deltas from the codeword lengths of the corresponding code in the previous
752 * Bitstream to which to write the compressed Huffman code.
754 * The codeword lengths, indexed by symbol, in the Huffman code.
756 * The codeword lengths, indexed by symbol, in the corresponding Huffman
757 * code in the previous block, or all zeroes if this is the first block.
759 * The number of symbols in the Huffman code.
762 lzx_write_compressed_code(struct lzx_output_bitstream *os,
763 const u8 lens[restrict],
764 const u8 prev_lens[restrict],
767 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
768 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
769 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
770 unsigned precode_items[num_lens];
771 unsigned num_precode_items;
772 unsigned precode_item;
773 unsigned precode_sym;
776 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
777 precode_freqs[i] = 0;
779 /* Compute the "items" (RLE / literal tokens and extra bits) with which
780 * the codeword lengths in the larger code will be output. */
781 num_precode_items = lzx_compute_precode_items(lens,
787 /* Build the precode. */
788 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
789 LZX_MAX_PRE_CODEWORD_LEN,
790 precode_freqs, precode_lens,
793 /* Output the lengths of the codewords in the precode. */
794 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
795 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
797 /* Output the encoded lengths of the codewords in the larger code. */
798 for (i = 0; i < num_precode_items; i++) {
799 precode_item = precode_items[i];
800 precode_sym = precode_item & 0x1F;
801 lzx_write_varbits(os, precode_codewords[precode_sym],
802 precode_lens[precode_sym],
803 LZX_MAX_PRE_CODEWORD_LEN);
804 if (precode_sym >= 17) {
805 if (precode_sym == 17) {
806 lzx_write_bits(os, precode_item >> 5, 4);
807 } else if (precode_sym == 18) {
808 lzx_write_bits(os, precode_item >> 5, 5);
810 lzx_write_bits(os, (precode_item >> 5) & 1, 1);
811 precode_sym = precode_item >> 6;
812 lzx_write_varbits(os, precode_codewords[precode_sym],
813 precode_lens[precode_sym],
814 LZX_MAX_PRE_CODEWORD_LEN);
820 /* Output a match or literal. */
822 lzx_write_item(struct lzx_output_bitstream *os, struct lzx_item item,
823 unsigned ones_if_aligned, const struct lzx_codes *codes)
825 u64 data = item.data;
826 unsigned main_symbol;
828 unsigned num_extra_bits;
831 main_symbol = data & 0x3FF;
833 lzx_write_varbits(os, codes->codewords.main[main_symbol],
834 codes->lens.main[main_symbol],
835 LZX_MAX_MAIN_CODEWORD_LEN);
837 if (main_symbol < LZX_NUM_CHARS) /* Literal? */
840 len_symbol = (data >> 10) & 0xFF;
842 if (len_symbol != LZX_LENCODE_NUM_SYMBOLS) {
843 lzx_write_varbits(os, codes->codewords.len[len_symbol],
844 codes->lens.len[len_symbol],
845 LZX_MAX_LEN_CODEWORD_LEN);
848 num_extra_bits = (data >> 18) & 0x1F;
849 if (num_extra_bits == 0) /* Small offset or repeat offset match? */
852 extra_bits = data >> 23;
854 if ((num_extra_bits & ones_if_aligned) >= LZX_NUM_ALIGNED_OFFSET_BITS) {
856 /* Aligned offset blocks: The low 3 bits of the extra offset
857 * bits are Huffman-encoded using the aligned offset code. The
858 * remaining bits are output literally. */
860 lzx_write_varbits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
861 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS,
862 17 - LZX_NUM_ALIGNED_OFFSET_BITS);
864 lzx_write_varbits(os,
865 codes->codewords.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
866 codes->lens.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
867 LZX_MAX_ALIGNED_CODEWORD_LEN);
869 /* Verbatim blocks, or fewer than 3 extra bits: All extra
870 * offset bits are output literally. */
871 lzx_write_varbits(os, extra_bits, num_extra_bits, 17);
876 * Write all matches and literal bytes (which were precomputed) in an LZX
877 * compressed block to the output bitstream in the final compressed
881 * The output bitstream.
883 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
884 * LZX_BLOCKTYPE_VERBATIM).
886 * The array of matches/literals to output.
888 * Number of matches/literals to output (length of @items).
890 * The main, length, and aligned offset Huffman codes for the current
891 * LZX compressed block.
894 lzx_write_items(struct lzx_output_bitstream *os, int block_type,
895 const struct lzx_item items[], u32 num_items,
896 const struct lzx_codes *codes)
898 unsigned ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
900 for (u32 i = 0; i < num_items; i++)
901 lzx_write_item(os, items[i], ones_if_aligned, codes);
905 lzx_write_compressed_block(int block_type,
907 unsigned window_order,
908 unsigned num_main_syms,
909 const struct lzx_item chosen_items[],
910 u32 num_chosen_items,
911 const struct lzx_codes * codes,
912 const struct lzx_lens * prev_lens,
913 struct lzx_output_bitstream * os)
915 LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
916 block_type == LZX_BLOCKTYPE_VERBATIM);
918 /* The first three bits indicate the type of block and are one of the
919 * LZX_BLOCKTYPE_* constants. */
920 lzx_write_bits(os, block_type, 3);
922 /* Output the block size.
924 * The original LZX format seemed to always encode the block size in 3
925 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
926 * uses the first bit to indicate whether the block is the default size
927 * (32768) or a different size given explicitly by the next 16 bits.
929 * By default, this compressor uses a window size of 32768 and therefore
930 * follows the WIMGAPI behavior. However, this compressor also supports
931 * window sizes greater than 32768 bytes, which do not appear to be
932 * supported by WIMGAPI. In such cases, we retain the default size bit
933 * to mean a size of 32768 bytes but output non-default block size in 24
934 * bits rather than 16. The compatibility of this behavior is unknown
935 * because WIMs created with chunk size greater than 32768 can seemingly
936 * only be opened by wimlib anyway. */
937 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
938 lzx_write_bits(os, 1, 1);
940 lzx_write_bits(os, 0, 1);
942 if (window_order >= 16)
943 lzx_write_bits(os, block_size >> 16, 8);
945 lzx_write_bits(os, block_size & 0xFFFF, 16);
948 /* If it's an aligned offset block, output the aligned offset code. */
949 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
950 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
951 lzx_write_bits(os, codes->lens.aligned[i],
952 LZX_ALIGNEDCODE_ELEMENT_SIZE);
956 /* Output the main code (two parts). */
957 lzx_write_compressed_code(os, codes->lens.main,
960 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
961 prev_lens->main + LZX_NUM_CHARS,
962 num_main_syms - LZX_NUM_CHARS);
964 /* Output the length code. */
965 lzx_write_compressed_code(os, codes->lens.len,
967 LZX_LENCODE_NUM_SYMBOLS);
969 /* Output the compressed matches and literals. */
970 lzx_write_items(os, block_type, chosen_items, num_chosen_items, codes);
973 /* Given the frequencies of symbols in an LZX-compressed block and the
974 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
975 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
976 * will take fewer bits to output. */
978 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
979 const struct lzx_codes * codes)
981 u32 aligned_cost = 0;
982 u32 verbatim_cost = 0;
984 /* A verbatim block requires 3 bits in each place that an aligned symbol
985 * would be used in an aligned offset block. */
986 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
987 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
988 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
991 /* Account for output of the aligned offset code. */
992 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
994 if (aligned_cost < verbatim_cost)
995 return LZX_BLOCKTYPE_ALIGNED;
997 return LZX_BLOCKTYPE_VERBATIM;
1001 * Finish an LZX block:
1003 * - build the Huffman codes
1004 * - decide whether to output the block as VERBATIM or ALIGNED
1005 * - output the block
1006 * - swap the indices of the current and previous Huffman codes
1009 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1010 u32 block_size, u32 num_chosen_items)
1014 lzx_make_huffman_codes(c);
1016 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1017 &c->codes[c->codes_index]);
1018 lzx_write_compressed_block(block_type,
1024 &c->codes[c->codes_index],
1025 &c->codes[c->codes_index ^ 1].lens,
1027 c->codes_index ^= 1;
1030 /* Return the offset slot for the specified offset, which must be
1031 * less than LZX_NUM_FAST_OFFSETS. */
1032 static inline unsigned
1033 lzx_get_offset_slot_fast(struct lzx_compressor *c, u32 offset)
1035 LZX_ASSERT(offset < LZX_NUM_FAST_OFFSETS);
1036 return c->offset_slot_fast[offset];
1039 /* Tally, and optionally record, the specified literal byte. */
1041 lzx_declare_literal(struct lzx_compressor *c, unsigned literal,
1042 struct lzx_item **next_chosen_item)
1044 unsigned main_symbol = lzx_main_symbol_for_literal(literal);
1046 c->freqs.main[main_symbol]++;
1048 if (next_chosen_item) {
1049 *(*next_chosen_item)++ = (struct lzx_item) {
1050 .data = main_symbol,
1055 /* Tally, and optionally record, the specified repeat offset match. */
1057 lzx_declare_repeat_offset_match(struct lzx_compressor *c,
1058 unsigned len, unsigned rep_index,
1059 struct lzx_item **next_chosen_item)
1061 unsigned len_header;
1062 unsigned len_symbol;
1063 unsigned main_symbol;
1065 if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1066 len_header = len - LZX_MIN_MATCH_LEN;
1067 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1069 len_header = LZX_NUM_PRIMARY_LENS;
1070 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1071 c->freqs.len[len_symbol]++;
1074 main_symbol = lzx_main_symbol_for_match(rep_index, len_header);
1076 c->freqs.main[main_symbol]++;
1078 if (next_chosen_item) {
1079 *(*next_chosen_item)++ = (struct lzx_item) {
1080 .data = (u64)main_symbol | ((u64)len_symbol << 10),
1085 /* Tally, and optionally record, the specified explicit offset match. */
1087 lzx_declare_explicit_offset_match(struct lzx_compressor *c, unsigned len, u32 offset,
1088 struct lzx_item **next_chosen_item)
1090 unsigned len_header;
1091 unsigned len_symbol;
1092 unsigned main_symbol;
1093 unsigned offset_slot;
1094 unsigned num_extra_bits;
1097 if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1098 len_header = len - LZX_MIN_MATCH_LEN;
1099 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1101 len_header = LZX_NUM_PRIMARY_LENS;
1102 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1103 c->freqs.len[len_symbol]++;
1106 offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1107 lzx_get_offset_slot_fast(c, offset) :
1108 lzx_get_offset_slot(offset);
1110 main_symbol = lzx_main_symbol_for_match(offset_slot, len_header);
1112 c->freqs.main[main_symbol]++;
1114 num_extra_bits = lzx_extra_offset_bits[offset_slot];
1116 if (num_extra_bits >= LZX_NUM_ALIGNED_OFFSET_BITS)
1117 c->freqs.aligned[(offset + LZX_OFFSET_ADJUSTMENT) &
1118 LZX_ALIGNED_OFFSET_BITMASK]++;
1120 if (next_chosen_item) {
1122 extra_bits = (offset + LZX_OFFSET_ADJUSTMENT) -
1123 lzx_offset_slot_base[offset_slot];
1125 BUILD_BUG_ON(LZX_MAINCODE_MAX_NUM_SYMBOLS > (1 << 10));
1126 BUILD_BUG_ON(LZX_LENCODE_NUM_SYMBOLS > (1 << 8));
1127 *(*next_chosen_item)++ = (struct lzx_item) {
1128 .data = (u64)main_symbol |
1129 ((u64)len_symbol << 10) |
1130 ((u64)num_extra_bits << 18) |
1131 ((u64)extra_bits << 23),
1137 /* Tally, and optionally record, the specified match or literal. */
1139 lzx_declare_item(struct lzx_compressor *c, u32 item,
1140 struct lzx_item **next_chosen_item)
1142 u32 len = item & OPTIMUM_LEN_MASK;
1143 u32 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1146 lzx_declare_literal(c, offset_data, next_chosen_item);
1147 else if (offset_data < LZX_NUM_RECENT_OFFSETS)
1148 lzx_declare_repeat_offset_match(c, len, offset_data,
1151 lzx_declare_explicit_offset_match(c, len,
1152 offset_data - LZX_OFFSET_ADJUSTMENT,
1157 lzx_record_item_list(struct lzx_compressor *c,
1158 struct lzx_optimum_node *cur_node,
1159 struct lzx_item **next_chosen_item)
1161 struct lzx_optimum_node *end_node;
1165 /* The list is currently in reverse order (last item to first item).
1167 end_node = cur_node;
1168 saved_item = cur_node->item;
1171 cur_node -= item & OPTIMUM_LEN_MASK;
1172 saved_item = cur_node->item;
1173 cur_node->item = item;
1174 } while (cur_node != c->optimum_nodes);
1176 /* Walk the list of items from beginning to end, tallying and recording
1179 lzx_declare_item(c, cur_node->item, next_chosen_item);
1180 cur_node += (cur_node->item) & OPTIMUM_LEN_MASK;
1181 } while (cur_node != end_node);
1185 lzx_tally_item_list(struct lzx_compressor *c, struct lzx_optimum_node *cur_node)
1187 /* Since we're just tallying the items, we don't need to reverse the
1188 * list. Processing the items in reverse order is fine. */
1190 lzx_declare_item(c, cur_node->item, NULL);
1191 cur_node -= (cur_node->item & OPTIMUM_LEN_MASK);
1192 } while (cur_node != c->optimum_nodes);
1196 * Find an inexpensive path through the graph of possible match/literal choices
1197 * for the current block. The nodes of the graph are
1198 * c->optimum_nodes[0...block_size]. They correspond directly to the bytes in
1199 * the current block, plus one extra node for end-of-block. The edges of the
1200 * graph are matches and literals. The goal is to find the minimum cost path
1201 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1203 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1204 * proceeding forwards one node at a time. At each node, a selection of matches
1205 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1206 * length 'len' provides a new path to reach the node 'len' bytes later. If
1207 * such a path is the lowest cost found so far to reach that later node, then
1208 * that later node is updated with the new path.
1210 * Note that although this algorithm is based on minimum cost path search, due
1211 * to various simplifying assumptions the result is not guaranteed to be the
1212 * true minimum cost, or "optimal", path over the graph of all valid LZX
1213 * representations of this block.
1215 * Also, note that because of the presence of the recent offsets queue (which is
1216 * a type of adaptive state), the algorithm cannot work backwards and compute
1217 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1218 * algorithm handles this adaptive state in the "minimum-cost" parse is actually
1219 * only an approximation. It's possible for the globally optimal, minimum cost
1220 * path to contain a prefix, ending at a position, where that path prefix is
1221 * *not* the minimum cost path to that position. This can happen if such a path
1222 * prefix results in a different adaptive state which results in lower costs
1223 * later. The algorithm does not solve this problem; it only considers the
1224 * lowest cost to reach each individual position.
1226 static struct lzx_lru_queue
1227 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1228 const u8 * const restrict block_begin,
1229 const u32 block_size,
1230 const struct lzx_lru_queue initial_queue)
1232 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1233 struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1234 struct lz_match *cache_ptr = c->match_cache;
1235 const u8 *in_next = block_begin;
1236 const u8 * const block_end = block_begin + block_size;
1238 /* Instead of storing the match offset LRU queues in the
1239 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1240 * storing them in a smaller array. This works because the algorithm
1241 * only requires a limited history of the adaptive state. Once a given
1242 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1243 * it is no longer needed. */
1244 struct lzx_lru_queue queues[512];
1246 BUILD_BUG_ON(ARRAY_LEN(queues) < LZX_MAX_MATCH_LEN + 1);
1247 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1249 /* Initially, the cost to reach each node is "infinity". */
1250 memset(c->optimum_nodes, 0xFF,
1251 (block_size + 1) * sizeof(c->optimum_nodes[0]));
1253 QUEUE(block_begin) = initial_queue;
1255 /* The following loop runs 'block_size' iterations, one per node. */
1257 unsigned num_matches;
1262 * A selection of matches for the block was already saved in
1263 * memory so that we don't have to run the uncompressed data
1264 * through the matchfinder on every optimization pass. However,
1265 * we still search for repeat offset matches during each
1266 * optimization pass because we cannot predict the state of the
1267 * recent offsets queue. But as a heuristic, we don't bother
1268 * searching for repeat offset matches if the general-purpose
1269 * matchfinder failed to find any matches.
1271 * Note that a match of length n at some offset implies there is
1272 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1273 * that same offset. In other words, we don't necessarily need
1274 * to use the full length of a match. The key heuristic that
1275 * saves a significicant amount of time is that for each
1276 * distinct length, we only consider the smallest offset for
1277 * which that length is available. This heuristic also applies
1278 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1279 * any explicit offset. Of course, this heuristic may be
1280 * produce suboptimal results because offset slots in LZX are
1281 * subject to entropy encoding, but in practice this is a useful
1285 num_matches = cache_ptr->length;
1289 struct lz_match *end_matches = cache_ptr + num_matches;
1290 unsigned next_len = LZX_MIN_MATCH_LEN;
1291 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1294 /* Consider R0 match */
1295 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1296 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1298 BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1300 u32 cost = cur_node->cost +
1301 c->costs.match_cost[0][
1302 next_len - LZX_MIN_MATCH_LEN];
1303 if (cost <= (cur_node + next_len)->cost) {
1304 (cur_node + next_len)->cost = cost;
1305 (cur_node + next_len)->item =
1306 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1308 if (unlikely(++next_len > max_len)) {
1309 cache_ptr = end_matches;
1312 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1316 /* Consider R1 match */
1317 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1318 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1320 if (matchptr[next_len - 1] != in_next[next_len - 1])
1322 for (unsigned len = 2; len < next_len - 1; len++)
1323 if (matchptr[len] != in_next[len])
1326 u32 cost = cur_node->cost +
1327 c->costs.match_cost[1][
1328 next_len - LZX_MIN_MATCH_LEN];
1329 if (cost <= (cur_node + next_len)->cost) {
1330 (cur_node + next_len)->cost = cost;
1331 (cur_node + next_len)->item =
1332 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1334 if (unlikely(++next_len > max_len)) {
1335 cache_ptr = end_matches;
1338 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1342 /* Consider R2 match */
1343 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1344 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1346 if (matchptr[next_len - 1] != in_next[next_len - 1])
1348 for (unsigned len = 2; len < next_len - 1; len++)
1349 if (matchptr[len] != in_next[len])
1352 u32 cost = cur_node->cost +
1353 c->costs.match_cost[2][
1354 next_len - LZX_MIN_MATCH_LEN];
1355 if (cost <= (cur_node + next_len)->cost) {
1356 (cur_node + next_len)->cost = cost;
1357 (cur_node + next_len)->item =
1358 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1360 if (unlikely(++next_len > max_len)) {
1361 cache_ptr = end_matches;
1364 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1368 while (next_len > cache_ptr->length)
1369 if (++cache_ptr == end_matches)
1372 /* Consider explicit offset matches */
1374 u32 offset = cache_ptr->offset;
1375 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1376 unsigned offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1377 lzx_get_offset_slot_fast(c, offset) :
1378 lzx_get_offset_slot(offset);
1380 u32 cost = cur_node->cost +
1381 c->costs.match_cost[offset_slot][
1382 next_len - LZX_MIN_MATCH_LEN];
1383 #if LZX_CONSIDER_ALIGNED_COSTS
1384 if (lzx_extra_offset_bits[offset_slot] >=
1385 LZX_NUM_ALIGNED_OFFSET_BITS)
1386 cost += c->costs.aligned[offset_data &
1387 LZX_ALIGNED_OFFSET_BITMASK];
1389 if (cost < (cur_node + next_len)->cost) {
1390 (cur_node + next_len)->cost = cost;
1391 (cur_node + next_len)->item =
1392 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1394 } while (++next_len <= cache_ptr->length);
1395 } while (++cache_ptr != end_matches);
1400 /* Consider coding a literal.
1402 * To avoid an extra branch, actually checking the preferability
1403 * of coding the literal is integrated into the queue update
1405 literal = *in_next++;
1406 cost = cur_node->cost +
1407 c->costs.main[lzx_main_symbol_for_literal(literal)];
1409 /* Advance to the next position. */
1412 /* The lowest-cost path to the current position is now known.
1413 * Finalize the recent offsets queue that results from taking
1414 * this lowest-cost path. */
1416 if (cost <= cur_node->cost) {
1417 /* Literal: queue remains unchanged. */
1418 cur_node->cost = cost;
1419 cur_node->item = (literal << OPTIMUM_OFFSET_SHIFT) | 1;
1420 QUEUE(in_next) = QUEUE(in_next - 1);
1422 /* Match: queue update is needed. */
1423 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1424 u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1425 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1426 /* Explicit offset match: insert offset at front */
1428 lzx_lru_queue_push(QUEUE(in_next - len),
1429 offset_data - LZX_OFFSET_ADJUSTMENT);
1431 /* Repeat offset match: swap offset to front */
1433 lzx_lru_queue_swap(QUEUE(in_next - len),
1437 } while (cur_node != end_node);
1439 /* Return the match offset queue at the end of the minimum-cost path. */
1440 return QUEUE(block_end);
1443 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1445 lzx_compute_match_costs(struct lzx_compressor *c)
1447 unsigned num_offset_slots = lzx_get_num_offset_slots(c->window_order);
1448 struct lzx_costs *costs = &c->costs;
1450 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1452 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1453 unsigned main_symbol = lzx_main_symbol_for_match(offset_slot, 0);
1456 #if LZX_CONSIDER_ALIGNED_COSTS
1457 if (lzx_extra_offset_bits[offset_slot] >= LZX_NUM_ALIGNED_OFFSET_BITS)
1458 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1461 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1462 costs->match_cost[offset_slot][i] =
1463 costs->main[main_symbol++] + extra_cost;
1465 extra_cost += costs->main[main_symbol];
1467 for (; i < LZX_NUM_LENS; i++)
1468 costs->match_cost[offset_slot][i] =
1469 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1473 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1476 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1479 bool have_byte[256];
1480 unsigned num_used_bytes;
1482 /* The costs below are hard coded to use a scaling factor of 16. */
1483 BUILD_BUG_ON(LZX_BIT_COST != 16);
1488 * - Use smaller initial costs for literal symbols when the input buffer
1489 * contains fewer distinct bytes.
1491 * - Assume that match symbols are more costly than literal symbols.
1493 * - Assume that length symbols for shorter lengths are less costly than
1494 * length symbols for longer lengths.
1497 for (i = 0; i < 256; i++)
1498 have_byte[i] = false;
1500 for (i = 0; i < block_size; i++)
1501 have_byte[block[i]] = true;
1504 for (i = 0; i < 256; i++)
1505 num_used_bytes += have_byte[i];
1507 for (i = 0; i < 256; i++)
1508 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1510 for (; i < c->num_main_syms; i++)
1511 c->costs.main[i] = 170;
1513 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1514 c->costs.len[i] = 103 + (i / 4);
1516 #if LZX_CONSIDER_ALIGNED_COSTS
1517 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1518 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1521 lzx_compute_match_costs(c);
1524 /* Update the current cost model to reflect the computed Huffman codes. */
1526 lzx_update_costs(struct lzx_compressor *c)
1529 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1531 for (i = 0; i < c->num_main_syms; i++)
1532 c->costs.main[i] = (lens->main[i] ? lens->main[i] : 15) * LZX_BIT_COST;
1534 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1535 c->costs.len[i] = (lens->len[i] ? lens->len[i] : 15) * LZX_BIT_COST;
1537 #if LZX_CONSIDER_ALIGNED_COSTS
1538 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1539 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] : 7) * LZX_BIT_COST;
1542 lzx_compute_match_costs(c);
1545 static struct lzx_lru_queue
1546 lzx_optimize_and_write_block(struct lzx_compressor *c,
1547 struct lzx_output_bitstream *os,
1548 const u8 *block_begin, const u32 block_size,
1549 const struct lzx_lru_queue initial_queue)
1551 unsigned num_passes_remaining = c->num_optim_passes;
1552 struct lzx_item *next_chosen_item;
1553 struct lzx_lru_queue new_queue;
1555 /* The first optimization pass uses a default cost model. Each
1556 * additional optimization pass uses a cost model derived from the
1557 * Huffman code computed in the previous pass. */
1559 lzx_set_default_costs(c, block_begin, block_size);
1560 lzx_reset_symbol_frequencies(c);
1562 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1564 if (num_passes_remaining > 1) {
1565 lzx_tally_item_list(c, c->optimum_nodes + block_size);
1566 lzx_make_huffman_codes(c);
1567 lzx_update_costs(c);
1568 lzx_reset_symbol_frequencies(c);
1570 } while (--num_passes_remaining);
1572 next_chosen_item = c->chosen_items;
1573 lzx_record_item_list(c, c->optimum_nodes + block_size, &next_chosen_item);
1574 lzx_finish_block(c, os, block_size, next_chosen_item - c->chosen_items);
1579 * This is the "near-optimal" LZX compressor.
1581 * For each block, it performs a relatively thorough graph search to find an
1582 * inexpensive (in terms of compressed size) way to output that block.
1584 * Note: there are actually many things this algorithm leaves on the table in
1585 * terms of compression ratio. So although it may be "near-optimal", it is
1586 * certainly not "optimal". The goal is not to produce the optimal compression
1587 * ratio, which for LZX is probably impossible within any practical amount of
1588 * time, but rather to produce a compression ratio significantly better than a
1589 * simpler "greedy" or "lazy" parse while still being relatively fast.
1592 lzx_compress_near_optimal(struct lzx_compressor *c,
1593 struct lzx_output_bitstream *os)
1595 const u8 * const in_begin = c->in_buffer;
1596 const u8 * in_next = in_begin;
1597 const u8 * const in_end = in_begin + c->in_nbytes;
1598 unsigned max_len = LZX_MAX_MATCH_LEN;
1599 unsigned nice_len = min(c->nice_match_length, max_len);
1601 struct lzx_lru_queue queue;
1603 bt_matchfinder_init(&c->bt_mf);
1604 matchfinder_init(c->hash2_tab, LZX_HASH2_LENGTH);
1605 next_hash = bt_matchfinder_hash_3_bytes(in_next);
1606 lzx_lru_queue_init(&queue);
1609 /* Starting a new block */
1610 const u8 * const in_block_begin = in_next;
1611 const u8 * const in_block_end =
1612 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1614 /* Run the block through the matchfinder and cache the matches. */
1615 struct lz_match *cache_ptr = c->match_cache;
1617 struct lz_match *lz_matchptr;
1622 /* If approaching the end of the input buffer, adjust
1623 * 'max_len' and 'nice_len' accordingly. */
1624 if (unlikely(max_len > in_end - in_next)) {
1625 max_len = in_end - in_next;
1626 nice_len = min(max_len, nice_len);
1628 /* This extra check is needed to ensure that
1629 * reading the next 3 bytes when looking for a
1630 * length 2 match is valid. In addition, we
1631 * cannot allow ourselves to find a length 2
1632 * match of the very last two bytes with the
1633 * very first two bytes, since such a match has
1634 * an offset too large to be represented. */
1635 if (unlikely(max_len <
1636 max(LZ_HASH_REQUIRED_NBYTES, 3)))
1639 cache_ptr->length = 0;
1645 lz_matchptr = cache_ptr + 1;
1647 /* Check for a length 2 match. */
1648 hash2 = lz_hash_2_bytes(in_next);
1649 cur_match = c->hash2_tab[hash2];
1650 c->hash2_tab[hash2] = in_next - in_begin;
1651 if (matchfinder_node_valid(cur_match) &&
1652 (LZX_HASH2_ORDER == 16 ||
1653 load_u16_unaligned(&in_begin[cur_match]) ==
1654 load_u16_unaligned(in_next)) &&
1655 in_begin[cur_match + 2] != in_next[2])
1657 lz_matchptr->length = 2;
1658 lz_matchptr->offset = in_next - &in_begin[cur_match];
1662 /* Check for matches of length >= 3. */
1663 lz_matchptr = bt_matchfinder_get_matches(&c->bt_mf,
1669 c->max_search_depth,
1674 cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1675 cache_ptr = lz_matchptr;
1678 * If there was a very long match found, then don't
1679 * cache any matches for the bytes covered by that
1680 * match. This avoids degenerate behavior when
1681 * compressing highly redundant data, where the number
1682 * of matches can be very large.
1684 * This heuristic doesn't actually hurt the compression
1685 * ratio very much. If there's a long match, then the
1686 * data must be highly compressible, so it doesn't
1687 * matter as much what we do.
1689 if (best_len >= nice_len) {
1692 if (unlikely(max_len > in_end - in_next)) {
1693 max_len = in_end - in_next;
1694 nice_len = min(max_len, nice_len);
1695 if (unlikely(max_len <
1696 max(LZ_HASH_REQUIRED_NBYTES, 3)))
1699 cache_ptr->length = 0;
1704 c->hash2_tab[lz_hash_2_bytes(in_next)] =
1706 bt_matchfinder_skip_position(&c->bt_mf,
1711 c->max_search_depth,
1714 cache_ptr->length = 0;
1716 } while (--best_len);
1718 } while (in_next < in_block_end &&
1719 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1721 /* We've finished running the block through the matchfinder.
1722 * Now choose a match/literal sequence and write the block. */
1724 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1725 in_next - in_block_begin,
1727 } while (in_next != in_end);
1731 * Given a pointer to the current byte sequence and the current list of recent
1732 * match offsets, find the longest repeat offset match.
1734 * If no match of at least 2 bytes is found, then return 0.
1736 * If a match of at least 2 bytes is found, then return its length and set
1737 * *rep_max_idx_ret to the index of its offset in @queue.
1740 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1741 const u32 bytes_remaining,
1742 struct lzx_lru_queue queue,
1743 unsigned *rep_max_idx_ret)
1745 BUILD_BUG_ON(LZX_NUM_RECENT_OFFSETS != 3);
1746 LZX_ASSERT(bytes_remaining >= 2);
1748 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1749 const u16 next_2_bytes = load_u16_unaligned(in_next);
1751 unsigned rep_max_len;
1752 unsigned rep_max_idx;
1755 matchptr = in_next - lzx_lru_queue_pop(&queue);
1756 if (load_u16_unaligned(matchptr) == next_2_bytes)
1757 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1762 matchptr = in_next - lzx_lru_queue_pop(&queue);
1763 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1764 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1765 if (rep_len > rep_max_len) {
1766 rep_max_len = rep_len;
1771 matchptr = in_next - lzx_lru_queue_pop(&queue);
1772 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1773 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1774 if (rep_len > rep_max_len) {
1775 rep_max_len = rep_len;
1780 *rep_max_idx_ret = rep_max_idx;
1784 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
1785 static inline unsigned
1786 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1788 unsigned score = len;
1790 if (adjusted_offset < 4096)
1793 if (adjusted_offset < 256)
1799 static inline unsigned
1800 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1805 /* This is the "lazy" LZX compressor. */
1807 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os)
1809 const u8 * const in_begin = c->in_buffer;
1810 const u8 * in_next = in_begin;
1811 const u8 * const in_end = in_begin + c->in_nbytes;
1812 unsigned max_len = LZX_MAX_MATCH_LEN;
1813 unsigned nice_len = min(c->nice_match_length, max_len);
1814 struct lzx_lru_queue queue;
1816 hc_matchfinder_init(&c->hc_mf);
1817 lzx_lru_queue_init(&queue);
1820 /* Starting a new block */
1822 const u8 * const in_block_begin = in_next;
1823 const u8 * const in_block_end =
1824 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1825 struct lzx_item *next_chosen_item = c->chosen_items;
1828 u32 cur_offset_data;
1832 u32 next_offset_data;
1833 unsigned next_score;
1834 unsigned rep_max_len;
1835 unsigned rep_max_idx;
1839 lzx_reset_symbol_frequencies(c);
1842 if (unlikely(max_len > in_end - in_next)) {
1843 max_len = in_end - in_next;
1844 nice_len = min(max_len, nice_len);
1847 /* Find the longest match at the current position. */
1849 cur_len = hc_matchfinder_longest_match(&c->hc_mf,
1855 c->max_search_depth,
1859 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
1860 cur_offset != lzx_lru_queue_R0(queue) &&
1861 cur_offset != lzx_lru_queue_R1(queue) &&
1862 cur_offset != lzx_lru_queue_R2(queue)))
1864 /* There was no match found, or the only match found
1865 * was a distant length 3 match. Output a literal. */
1866 lzx_declare_literal(c, *in_next++,
1871 if (cur_offset == lzx_lru_queue_R0(queue)) {
1873 cur_offset_data = 0;
1874 skip_len = cur_len - 1;
1875 goto choose_cur_match;
1878 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
1879 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
1881 /* Consider a repeat offset match */
1882 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1888 if (rep_max_len >= 3 &&
1889 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1890 rep_max_idx)) >= cur_score)
1892 cur_len = rep_max_len;
1893 cur_offset_data = rep_max_idx;
1894 skip_len = rep_max_len - 1;
1895 goto choose_cur_match;
1900 /* We have a match at the current position. */
1902 /* If we have a very long match, choose it immediately. */
1903 if (cur_len >= nice_len) {
1904 skip_len = cur_len - 1;
1905 goto choose_cur_match;
1908 /* See if there's a better match at the next position. */
1910 if (unlikely(max_len > in_end - in_next)) {
1911 max_len = in_end - in_next;
1912 nice_len = min(max_len, nice_len);
1915 next_len = hc_matchfinder_longest_match(&c->hc_mf,
1921 c->max_search_depth / 2,
1924 if (next_len <= cur_len - 2) {
1926 skip_len = cur_len - 2;
1927 goto choose_cur_match;
1930 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
1931 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
1933 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1939 if (rep_max_len >= 3 &&
1940 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1941 rep_max_idx)) >= next_score)
1944 if (rep_score > cur_score) {
1945 /* The next match is better, and it's a
1946 * repeat offset match. */
1947 lzx_declare_literal(c, *(in_next - 2),
1949 cur_len = rep_max_len;
1950 cur_offset_data = rep_max_idx;
1951 skip_len = cur_len - 1;
1952 goto choose_cur_match;
1955 if (next_score > cur_score) {
1956 /* The next match is better, and it's an
1957 * explicit offset match. */
1958 lzx_declare_literal(c, *(in_next - 2),
1961 cur_offset_data = next_offset_data;
1962 cur_score = next_score;
1963 goto have_cur_match;
1967 /* The original match was better. */
1968 skip_len = cur_len - 2;
1971 if (cur_offset_data < LZX_NUM_RECENT_OFFSETS) {
1972 lzx_declare_repeat_offset_match(c, cur_len,
1975 queue = lzx_lru_queue_swap(queue, cur_offset_data);
1977 lzx_declare_explicit_offset_match(c, cur_len,
1978 cur_offset_data - LZX_OFFSET_ADJUSTMENT,
1980 queue = lzx_lru_queue_push(queue, cur_offset_data - LZX_OFFSET_ADJUSTMENT);
1983 hc_matchfinder_skip_positions(&c->hc_mf,
1988 in_next += skip_len;
1989 } while (in_next < in_block_end);
1991 lzx_finish_block(c, os, in_next - in_block_begin,
1992 next_chosen_item - c->chosen_items);
1993 } while (in_next != in_end);
1997 lzx_init_offset_slot_fast(struct lzx_compressor *c)
2001 for (u32 offset = 0; offset < LZX_NUM_FAST_OFFSETS; offset++) {
2003 while (offset + LZX_OFFSET_ADJUSTMENT >= lzx_offset_slot_base[slot + 1])
2006 c->offset_slot_fast[offset] = slot;
2011 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2013 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2014 return offsetof(struct lzx_compressor, hc_mf) +
2015 hc_matchfinder_size(max_bufsize);
2017 return offsetof(struct lzx_compressor, bt_mf) +
2018 bt_matchfinder_size(max_bufsize);
2023 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level)
2027 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2030 size += lzx_get_compressor_size(max_bufsize, compression_level);
2031 size += max_bufsize; /* in_buffer */
2036 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2039 unsigned window_order;
2040 struct lzx_compressor *c;
2042 window_order = lzx_get_window_order(max_bufsize);
2043 if (window_order == 0)
2044 return WIMLIB_ERR_INVALID_PARAM;
2046 c = ALIGNED_MALLOC(lzx_get_compressor_size(max_bufsize,
2048 MATCHFINDER_ALIGNMENT);
2052 c->num_main_syms = lzx_get_num_main_syms(window_order);
2053 c->window_order = window_order;
2055 c->in_buffer = MALLOC(max_bufsize);
2059 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2061 /* Fast compression: Use lazy parsing. */
2063 c->impl = lzx_compress_lazy;
2064 c->max_search_depth = (36 * compression_level) / 20;
2065 c->nice_match_length = (72 * compression_level) / 20;
2067 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2068 * halves the max_search_depth when attempting a lazy match, and
2069 * max_search_depth cannot be 0. */
2070 if (c->max_search_depth < 2)
2071 c->max_search_depth = 2;
2074 /* Normal / high compression: Use near-optimal parsing. */
2076 c->impl = lzx_compress_near_optimal;
2078 /* Scale nice_match_length and max_search_depth with the
2079 * compression level. */
2080 c->max_search_depth = (24 * compression_level) / 50;
2081 c->nice_match_length = (32 * compression_level) / 50;
2083 /* Set a number of optimization passes appropriate for the
2084 * compression level. */
2086 c->num_optim_passes = 1;
2088 if (compression_level >= 45)
2089 c->num_optim_passes++;
2091 /* Use more optimization passes for higher compression levels.
2092 * But the more passes there are, the less they help --- so
2093 * don't add them linearly. */
2094 if (compression_level >= 70) {
2095 c->num_optim_passes++;
2096 if (compression_level >= 100)
2097 c->num_optim_passes++;
2098 if (compression_level >= 150)
2099 c->num_optim_passes++;
2100 if (compression_level >= 200)
2101 c->num_optim_passes++;
2102 if (compression_level >= 300)
2103 c->num_optim_passes++;
2107 /* max_search_depth == 0 is invalid. */
2108 if (c->max_search_depth < 1)
2109 c->max_search_depth = 1;
2111 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2112 c->nice_match_length = LZX_MAX_MATCH_LEN;
2114 lzx_init_offset_slot_fast(c);
2121 return WIMLIB_ERR_NOMEM;
2125 lzx_compress(const void *in, size_t in_nbytes,
2126 void *out, size_t out_nbytes_avail, void *_c)
2128 struct lzx_compressor *c = _c;
2129 struct lzx_output_bitstream os;
2131 /* Don't bother trying to compress very small inputs. */
2132 if (in_nbytes < 100)
2135 /* Copy the input data into the internal buffer and preprocess it. */
2136 memcpy(c->in_buffer, in, in_nbytes);
2137 c->in_nbytes = in_nbytes;
2138 lzx_do_e8_preprocessing(c->in_buffer, in_nbytes);
2140 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2142 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2144 /* Initialize the output bitstream. */
2145 lzx_init_output(&os, out, out_nbytes_avail);
2147 /* Call the compression level-specific compress() function. */
2150 /* Flush the output bitstream and return the compressed size or 0. */
2151 return lzx_flush_output(&os);
2155 lzx_free_compressor(void *_c)
2157 struct lzx_compressor *c = _c;
2163 const struct compressor_ops lzx_compressor_ops = {
2164 .get_needed_memory = lzx_get_needed_memory,
2165 .create_compressor = lzx_create_compressor,
2166 .compress = lzx_compress,
2167 .free_compressor = lzx_free_compressor,