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 * Should the compressor take into account the costs of aligned offset symbols?
119 #define LZX_CONSIDER_ALIGNED_COSTS 1
122 * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
125 #define LZX_MAX_FAST_LEVEL 34
128 * BT_MATCHFINDER_HASH2_ORDER is the log base 2 of the number of entries in the
129 * hash table for finding length 2 matches. This could be as high as 16, but
130 * using a smaller hash table speeds up compression due to reduced cache
133 #define BT_MATCHFINDER_HASH2_ORDER 12
136 * These are the compressor-side limits on the codeword lengths for each Huffman
137 * code. To make outputting bits slightly faster, some of these limits are
138 * lower than the limits defined by the LZX format. This does not significantly
139 * affect the compression ratio, at least for the block sizes we use.
141 #define MAIN_CODEWORD_LIMIT 16
142 #define LENGTH_CODEWORD_LIMIT 12
143 #define ALIGNED_CODEWORD_LIMIT 7
144 #define PRE_CODEWORD_LIMIT 7
146 #include "wimlib/compress_common.h"
147 #include "wimlib/compressor_ops.h"
148 #include "wimlib/error.h"
149 #include "wimlib/lz_extend.h"
150 #include "wimlib/lzx_common.h"
151 #include "wimlib/unaligned.h"
152 #include "wimlib/util.h"
154 /* Matchfinders with 16-bit positions */
156 #define MF_SUFFIX _16
157 #include "wimlib/bt_matchfinder.h"
158 #include "wimlib/hc_matchfinder.h"
160 /* Matchfinders with 32-bit positions */
164 #define MF_SUFFIX _32
165 #include "wimlib/bt_matchfinder.h"
166 #include "wimlib/hc_matchfinder.h"
168 struct lzx_output_bitstream;
170 /* Codewords for the LZX Huffman codes. */
171 struct lzx_codewords {
172 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
173 u32 len[LZX_LENCODE_NUM_SYMBOLS];
174 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
177 /* Codeword lengths (in bits) for the LZX Huffman codes.
178 * A zero length means the corresponding codeword has zero frequency. */
180 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS + 1];
181 u8 len[LZX_LENCODE_NUM_SYMBOLS + 1];
182 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
185 /* Cost model for near-optimal parsing */
188 /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
189 * length 'len' match that has an offset belonging to 'offset_slot'. */
190 u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
192 /* Cost for each symbol in the main code */
193 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
195 /* Cost for each symbol in the length code */
196 u32 len[LZX_LENCODE_NUM_SYMBOLS];
198 #if LZX_CONSIDER_ALIGNED_COSTS
199 /* Cost for each symbol in the aligned code */
200 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
204 /* Codewords and lengths for the LZX Huffman codes. */
206 struct lzx_codewords codewords;
207 struct lzx_lens lens;
210 /* Symbol frequency counters for the LZX Huffman codes. */
212 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
213 u32 len[LZX_LENCODE_NUM_SYMBOLS];
214 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
218 * Represents a run of literals followed by a match or end-of-block. This
219 * struct is needed to temporarily store items chosen by the parser, since items
220 * cannot be written until all items for the block have been chosen and the
221 * block's Huffman codes have been computed.
223 struct lzx_sequence {
225 /* The number of literals in the run. This may be 0. The literals are
226 * not stored explicitly in this structure; instead, they are read
227 * directly from the uncompressed data. */
230 /* If the next field doesn't indicate end-of-block, then this is the
231 * match length minus LZX_MIN_MATCH_LEN. */
234 /* If bit 31 is clear, then this field contains the match header in bits
235 * 0-8, and either the match offset plus LZX_OFFSET_ADJUSTMENT or a
236 * recent offset code in bits 9-30. Otherwise (if bit 31 is set), this
237 * sequence's literal run was the last literal run in the block, so
238 * there is no match that follows it. */
239 u32 adjusted_offset_and_match_hdr;
243 * This structure represents a byte position in the input buffer and a node in
244 * the graph of possible match/literal choices.
246 * Logically, each incoming edge to this node is labeled with a literal or a
247 * match that can be taken to reach this position from an earlier position; and
248 * each outgoing edge from this node is labeled with a literal or a match that
249 * can be taken to advance from this position to a later position.
251 struct lzx_optimum_node {
253 /* The cost, in bits, of the lowest-cost path that has been found to
254 * reach this position. This can change as progressively lower cost
255 * paths are found to reach this position. */
259 * The match or literal that was taken to reach this position. This can
260 * change as progressively lower cost paths are found to reach this
263 * This variable is divided into two bitfields.
266 * Low bits are 0, high bits are the literal.
268 * Explicit offset matches:
269 * Low bits are the match length, high bits are the offset plus 2.
271 * Repeat offset matches:
272 * Low bits are the match length, high bits are the queue index.
275 #define OPTIMUM_OFFSET_SHIFT 9
276 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
277 } _aligned_attribute(8);
280 * Least-recently-used queue for match offsets.
282 * This is represented as a 64-bit integer for efficiency. There are three
283 * offsets of 21 bits each. Bit 64 is garbage.
285 struct lzx_lru_queue {
289 #define LZX_QUEUE64_OFFSET_SHIFT 21
290 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
292 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
293 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
294 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
296 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
297 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
298 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
301 lzx_lru_queue_init(struct lzx_lru_queue *queue)
303 queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
304 ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
305 ((u64)1 << LZX_QUEUE64_R2_SHIFT);
309 lzx_lru_queue_R0(struct lzx_lru_queue queue)
311 return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
315 lzx_lru_queue_R1(struct lzx_lru_queue queue)
317 return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
321 lzx_lru_queue_R2(struct lzx_lru_queue queue)
323 return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
326 /* Push a match offset onto the front (most recently used) end of the queue. */
327 static inline struct lzx_lru_queue
328 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
330 return (struct lzx_lru_queue) {
331 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
335 /* Swap a match offset to the front of the queue. */
336 static inline struct lzx_lru_queue
337 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
343 return (struct lzx_lru_queue) {
344 .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
345 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
346 (queue.R & LZX_QUEUE64_R2_MASK),
349 return (struct lzx_lru_queue) {
350 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
351 (queue.R & LZX_QUEUE64_R1_MASK) |
352 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
356 /* The main LZX compressor structure */
357 struct lzx_compressor {
359 /* The "nice" match length: if a match of this length is found, then
360 * choose it immediately without further consideration. */
361 unsigned nice_match_length;
363 /* The maximum search depth: consider at most this many potential
364 * matches at each position. */
365 unsigned max_search_depth;
367 /* The log base 2 of the LZX window size for LZ match offset encoding
368 * purposes. This will be >= LZX_MIN_WINDOW_ORDER and <=
369 * LZX_MAX_WINDOW_ORDER. */
370 unsigned window_order;
372 /* The number of symbols in the main alphabet. This depends on
373 * @window_order, since @window_order determines the maximum possible
375 unsigned num_main_syms;
377 /* Number of optimization passes per block */
378 unsigned num_optim_passes;
380 /* The preprocessed buffer of data being compressed */
383 /* The number of bytes of data to be compressed, which is the number of
384 * bytes of data in @in_buffer that are actually valid. */
387 /* Pointer to the compress() implementation chosen at allocation time */
388 void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
390 /* If true, the compressor need not preserve the input buffer if it
391 * compresses the data successfully. */
394 /* The Huffman symbol frequency counters for the current block. */
395 struct lzx_freqs freqs;
397 /* The Huffman codes for the current and previous blocks. The one with
398 * index 'codes_index' is for the current block, and the other one is
399 * for the previous block. */
400 struct lzx_codes codes[2];
401 unsigned codes_index;
403 /* The matches and literals that the parser has chosen for the current
404 * block. The required length of this array is limited by the maximum
405 * number of matches that can ever be chosen for a single block, plus
406 * one for the special entry at the end. */
407 struct lzx_sequence chosen_sequences[
408 DIV_ROUND_UP(LZX_DIV_BLOCK_SIZE, LZX_MIN_MATCH_LEN) + 1];
410 /* Tables for mapping adjusted offsets to offset slots */
412 /* offset slots [0, 29] */
413 u8 offset_slot_tab_1[32768];
415 /* offset slots [30, 49] */
416 u8 offset_slot_tab_2[128];
419 /* Data for greedy or lazy parsing */
421 /* Hash chains matchfinder (MUST BE LAST!!!) */
423 struct hc_matchfinder_16 hc_mf_16;
424 struct hc_matchfinder_32 hc_mf_32;
428 /* Data for near-optimal parsing */
431 * The graph nodes for the current block.
433 * We need at least 'LZX_DIV_BLOCK_SIZE +
434 * LZX_MAX_MATCH_LEN - 1' nodes because that is the
435 * maximum block size that may be used. Add 1 because
436 * we need a node to represent end-of-block.
438 * It is possible that nodes past end-of-block are
439 * accessed during match consideration, but this can
440 * only occur if the block was truncated at
441 * LZX_DIV_BLOCK_SIZE. So the same bound still applies.
442 * Note that since nodes past the end of the block will
443 * never actually have an effect on the items that are
444 * chosen for the block, it makes no difference what
445 * their costs are initialized to (if anything).
447 struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
448 LZX_MAX_MATCH_LEN - 1 + 1];
450 /* The cost model for the current block */
451 struct lzx_costs costs;
454 * Cached matches for the current block. This array
455 * contains the matches that were found at each position
456 * in the block. Specifically, for each position, there
457 * is a special 'struct lz_match' whose 'length' field
458 * contains the number of matches that were found at
459 * that position; this is followed by the matches
460 * themselves, if any, sorted by strictly increasing
463 * Note: in rare cases, there will be a very high number
464 * of matches in the block and this array will overflow.
465 * If this happens, we force the end of the current
466 * block. LZX_CACHE_LENGTH is the length at which we
467 * actually check for overflow. The extra slots beyond
468 * this are enough to absorb the worst case overflow,
469 * which occurs if starting at
470 * &match_cache[LZX_CACHE_LENGTH - 1], we write the
471 * match count header, then write
472 * LZX_MAX_MATCHES_PER_POS matches, then skip searching
473 * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
474 * write the match count header for each.
476 struct lz_match match_cache[LZX_CACHE_LENGTH +
477 LZX_MAX_MATCHES_PER_POS +
478 LZX_MAX_MATCH_LEN - 1];
480 /* Binary trees matchfinder (MUST BE LAST!!!) */
482 struct bt_matchfinder_16 bt_mf_16;
483 struct bt_matchfinder_32 bt_mf_32;
490 * Will a matchfinder using 16-bit positions be sufficient for compressing
491 * buffers of up to the specified size? The limit could be 65536 bytes, but we
492 * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
493 * This requires that the limit be no more than the length of offset_slot_tab_1
497 lzx_is_16_bit(size_t max_bufsize)
499 STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
500 return max_bufsize <= 32768;
504 * The following macros call either the 16-bit or the 32-bit version of a
505 * matchfinder function based on the value of 'is_16_bit', which will be known
506 * at compilation time.
509 #define CALL_HC_MF(is_16_bit, c, funcname, ...) \
510 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
511 CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
513 #define CALL_BT_MF(is_16_bit, c, funcname, ...) \
514 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->bt_mf_16, ##__VA_ARGS__) : \
515 CONCAT(funcname, _32)(&(c)->bt_mf_32, ##__VA_ARGS__));
518 * Structure to keep track of the current state of sending bits to the
519 * compressed output buffer.
521 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
523 struct lzx_output_bitstream {
525 /* Bits that haven't yet been written to the output buffer. */
526 machine_word_t bitbuf;
528 /* Number of bits currently held in @bitbuf. */
531 /* Pointer to the start of the output buffer. */
534 /* Pointer to the position in the output buffer at which the next coding
535 * unit should be written. */
538 /* Pointer just past the end of the output buffer, rounded down to a
539 * 2-byte boundary. */
543 /* Can the specified number of bits always be added to 'bitbuf' after any
544 * pending 16-bit coding units have been flushed? */
545 #define CAN_BUFFER(n) ((n) <= (8 * sizeof(machine_word_t)) - 15)
548 * Initialize the output bitstream.
551 * The output bitstream structure to initialize.
553 * The buffer being written to.
555 * Size of @buffer, in bytes.
558 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
563 os->next = os->start;
564 os->end = os->start + (size & ~1);
567 /* Add some bits to the bitbuffer variable of the output bitstream. The caller
568 * must make sure there is enough room. */
570 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
572 os->bitbuf = (os->bitbuf << num_bits) | bits;
573 os->bitcount += num_bits;
576 /* Flush bits from the bitbuffer variable to the output buffer. 'max_num_bits'
577 * specifies the maximum number of bits that may have been added since the last
580 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
582 /* Masking the number of bits to shift is only needed to avoid undefined
583 * behavior; we don't actually care about the results of bad shifts. On
584 * x86, the explicit masking generates no extra code. */
585 const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
587 if (os->end - os->next < 6)
589 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 16) &
590 shift_mask), os->next + 0);
591 if (max_num_bits > 16)
592 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 32) &
593 shift_mask), os->next + 2);
594 if (max_num_bits > 32)
595 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 48) &
596 shift_mask), os->next + 4);
597 os->next += (os->bitcount >> 4) << 1;
601 /* Add at most 16 bits to the bitbuffer and flush it. */
603 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
605 lzx_add_bits(os, bits, num_bits);
606 lzx_flush_bits(os, 16);
610 * Flush the last coding unit to the output buffer if needed. Return the total
611 * number of bytes written to the output buffer, or 0 if an overflow occurred.
614 lzx_flush_output(struct lzx_output_bitstream *os)
616 if (os->end - os->next < 6)
619 if (os->bitcount != 0) {
620 put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
624 return os->next - os->start;
627 /* Build the main, length, and aligned offset Huffman codes used in LZX.
629 * This takes as input the frequency tables for each code and produces as output
630 * a set of tables that map symbols to codewords and codeword lengths. */
632 lzx_make_huffman_codes(struct lzx_compressor *c)
634 const struct lzx_freqs *freqs = &c->freqs;
635 struct lzx_codes *codes = &c->codes[c->codes_index];
637 STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
638 MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
639 STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
640 LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
641 STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
642 ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
644 make_canonical_huffman_code(c->num_main_syms,
648 codes->codewords.main);
650 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
651 LENGTH_CODEWORD_LIMIT,
654 codes->codewords.len);
656 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
657 ALIGNED_CODEWORD_LIMIT,
660 codes->codewords.aligned);
663 /* Reset the symbol frequencies for the LZX Huffman codes. */
665 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
667 memset(&c->freqs, 0, sizeof(c->freqs));
671 lzx_compute_precode_items(const u8 lens[restrict],
672 const u8 prev_lens[restrict],
673 u32 precode_freqs[restrict],
674 unsigned precode_items[restrict])
683 itemptr = precode_items;
686 while (!((len = lens[run_start]) & 0x80)) {
688 /* len = the length being repeated */
690 /* Find the next run of codeword lengths. */
692 run_end = run_start + 1;
694 /* Fast case for a single length. */
695 if (likely(len != lens[run_end])) {
696 delta = prev_lens[run_start] - len;
699 precode_freqs[delta]++;
705 /* Extend the run. */
708 } while (len == lens[run_end]);
713 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
714 while ((run_end - run_start) >= 20) {
715 extra_bits = min((run_end - run_start) - 20, 0x1f);
717 *itemptr++ = 18 | (extra_bits << 5);
718 run_start += 20 + extra_bits;
721 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
722 if ((run_end - run_start) >= 4) {
723 extra_bits = min((run_end - run_start) - 4, 0xf);
725 *itemptr++ = 17 | (extra_bits << 5);
726 run_start += 4 + extra_bits;
730 /* A run of nonzero lengths. */
732 /* Symbol 19: RLE 4 to 5 of any length at a time. */
733 while ((run_end - run_start) >= 4) {
734 extra_bits = (run_end - run_start) > 4;
735 delta = prev_lens[run_start] - len;
739 precode_freqs[delta]++;
740 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
741 run_start += 4 + extra_bits;
745 /* Output any remaining lengths without RLE. */
746 while (run_start != run_end) {
747 delta = prev_lens[run_start] - len;
750 precode_freqs[delta]++;
756 return itemptr - precode_items;
760 * Output a Huffman code in the compressed form used in LZX.
762 * The Huffman code is represented in the output as a logical series of codeword
763 * lengths from which the Huffman code, which must be in canonical form, can be
766 * The codeword lengths are themselves compressed using a separate Huffman code,
767 * the "precode", which contains a symbol for each possible codeword length in
768 * the larger code as well as several special symbols to represent repeated
769 * codeword lengths (a form of run-length encoding). The precode is itself
770 * constructed in canonical form, and its codeword lengths are represented
771 * literally in 20 4-bit fields that immediately precede the compressed codeword
772 * lengths of the larger code.
774 * Furthermore, the codeword lengths of the larger code are actually represented
775 * as deltas from the codeword lengths of the corresponding code in the previous
779 * Bitstream to which to write the compressed Huffman code.
781 * The codeword lengths, indexed by symbol, in the Huffman code.
783 * The codeword lengths, indexed by symbol, in the corresponding Huffman
784 * code in the previous block, or all zeroes if this is the first block.
786 * The number of symbols in the Huffman code.
789 lzx_write_compressed_code(struct lzx_output_bitstream *os,
790 const u8 lens[restrict],
791 const u8 prev_lens[restrict],
794 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
795 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
796 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
797 unsigned precode_items[num_lens];
798 unsigned num_precode_items;
799 unsigned precode_item;
800 unsigned precode_sym;
802 u8 saved = lens[num_lens];
803 *(u8 *)(lens + num_lens) = 0x80;
805 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
806 precode_freqs[i] = 0;
808 /* Compute the "items" (RLE / literal tokens and extra bits) with which
809 * the codeword lengths in the larger code will be output. */
810 num_precode_items = lzx_compute_precode_items(lens,
815 /* Build the precode. */
816 STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
817 PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
818 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
820 precode_freqs, precode_lens,
823 /* Output the lengths of the codewords in the precode. */
824 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
825 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
827 /* Output the encoded lengths of the codewords in the larger code. */
828 for (i = 0; i < num_precode_items; i++) {
829 precode_item = precode_items[i];
830 precode_sym = precode_item & 0x1F;
831 lzx_add_bits(os, precode_codewords[precode_sym],
832 precode_lens[precode_sym]);
833 if (precode_sym >= 17) {
834 if (precode_sym == 17) {
835 lzx_add_bits(os, precode_item >> 5, 4);
836 } else if (precode_sym == 18) {
837 lzx_add_bits(os, precode_item >> 5, 5);
839 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
840 precode_sym = precode_item >> 6;
841 lzx_add_bits(os, precode_codewords[precode_sym],
842 precode_lens[precode_sym]);
845 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
846 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
849 *(u8 *)(lens + num_lens) = saved;
853 * Write all matches and literal bytes (which were precomputed) in an LZX
854 * compressed block to the output bitstream in the final compressed
858 * The output bitstream.
860 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
861 * LZX_BLOCKTYPE_VERBATIM).
863 * The uncompressed data of the block.
865 * The matches and literals to output, given as a series of sequences.
867 * The main, length, and aligned offset Huffman codes for the current
868 * LZX compressed block.
871 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
872 const u8 *block_data, const struct lzx_sequence sequences[],
873 const struct lzx_codes *codes)
875 const struct lzx_sequence *seq = sequences;
876 u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
879 /* Output the next sequence. */
881 unsigned litrunlen = seq->litrunlen;
883 unsigned main_symbol;
884 unsigned adjusted_length;
886 unsigned offset_slot;
887 unsigned num_extra_bits;
890 /* Output the literal run of the sequence. */
892 if (litrunlen) { /* Is the literal run nonempty? */
894 /* Verify optimization is enabled on 64-bit */
895 STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
896 CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT));
898 if (CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT)) {
900 /* 64-bit: write 3 literals at a time. */
901 while (litrunlen >= 3) {
902 unsigned lit0 = block_data[0];
903 unsigned lit1 = block_data[1];
904 unsigned lit2 = block_data[2];
905 lzx_add_bits(os, codes->codewords.main[lit0],
906 codes->lens.main[lit0]);
907 lzx_add_bits(os, codes->codewords.main[lit1],
908 codes->lens.main[lit1]);
909 lzx_add_bits(os, codes->codewords.main[lit2],
910 codes->lens.main[lit2]);
911 lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
916 unsigned lit = *block_data++;
917 lzx_add_bits(os, codes->codewords.main[lit],
918 codes->lens.main[lit]);
920 unsigned lit = *block_data++;
921 lzx_add_bits(os, codes->codewords.main[lit],
922 codes->lens.main[lit]);
923 lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
925 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
929 /* 32-bit: write 1 literal at a time. */
931 unsigned lit = *block_data++;
932 lzx_add_bits(os, codes->codewords.main[lit],
933 codes->lens.main[lit]);
934 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
935 } while (--litrunlen);
939 /* Was this the last literal run? */
940 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
943 /* Nope; output the match. */
945 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
946 main_symbol = LZX_NUM_CHARS + match_hdr;
947 adjusted_length = seq->adjusted_length;
949 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
951 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
952 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
954 num_extra_bits = lzx_extra_offset_bits[offset_slot];
955 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
957 #define MAX_MATCH_BITS (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
958 14 + ALIGNED_CODEWORD_LIMIT)
960 /* Verify optimization is enabled on 64-bit */
961 STATIC_ASSERT(sizeof(machine_word_t) < 8 || CAN_BUFFER(MAX_MATCH_BITS));
963 /* Output the main symbol for the match. */
965 lzx_add_bits(os, codes->codewords.main[main_symbol],
966 codes->lens.main[main_symbol]);
967 if (!CAN_BUFFER(MAX_MATCH_BITS))
968 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
970 /* If needed, output the length symbol for the match. */
972 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
973 lzx_add_bits(os, codes->codewords.len[adjusted_length -
974 LZX_NUM_PRIMARY_LENS],
975 codes->lens.len[adjusted_length -
976 LZX_NUM_PRIMARY_LENS]);
977 if (!CAN_BUFFER(MAX_MATCH_BITS))
978 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
981 /* Output the extra offset bits for the match. In aligned
982 * offset blocks, the lowest 3 bits of the adjusted offset are
983 * Huffman-encoded using the aligned offset code, provided that
984 * there are at least extra 3 offset bits required. All other
985 * extra offset bits are output verbatim. */
987 if ((adjusted_offset & ones_if_aligned) >= 16) {
989 lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
990 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
991 if (!CAN_BUFFER(MAX_MATCH_BITS))
992 lzx_flush_bits(os, 14);
994 lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
995 LZX_ALIGNED_OFFSET_BITMASK],
996 codes->lens.aligned[adjusted_offset &
997 LZX_ALIGNED_OFFSET_BITMASK]);
998 if (!CAN_BUFFER(MAX_MATCH_BITS))
999 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1001 STATIC_ASSERT(CAN_BUFFER(17));
1003 lzx_add_bits(os, extra_bits, num_extra_bits);
1004 if (!CAN_BUFFER(MAX_MATCH_BITS))
1005 lzx_flush_bits(os, 17);
1008 if (CAN_BUFFER(MAX_MATCH_BITS))
1009 lzx_flush_bits(os, MAX_MATCH_BITS);
1011 /* Advance to the next sequence. */
1017 lzx_write_compressed_block(const u8 *block_begin,
1020 unsigned window_order,
1021 unsigned num_main_syms,
1022 const struct lzx_sequence sequences[],
1023 const struct lzx_codes * codes,
1024 const struct lzx_lens * prev_lens,
1025 struct lzx_output_bitstream * os)
1027 /* The first three bits indicate the type of block and are one of the
1028 * LZX_BLOCKTYPE_* constants. */
1029 lzx_write_bits(os, block_type, 3);
1031 /* Output the block size.
1033 * The original LZX format seemed to always encode the block size in 3
1034 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
1035 * uses the first bit to indicate whether the block is the default size
1036 * (32768) or a different size given explicitly by the next 16 bits.
1038 * By default, this compressor uses a window size of 32768 and therefore
1039 * follows the WIMGAPI behavior. However, this compressor also supports
1040 * window sizes greater than 32768 bytes, which do not appear to be
1041 * supported by WIMGAPI. In such cases, we retain the default size bit
1042 * to mean a size of 32768 bytes but output non-default block size in 24
1043 * bits rather than 16. The compatibility of this behavior is unknown
1044 * because WIMs created with chunk size greater than 32768 can seemingly
1045 * only be opened by wimlib anyway. */
1046 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1047 lzx_write_bits(os, 1, 1);
1049 lzx_write_bits(os, 0, 1);
1051 if (window_order >= 16)
1052 lzx_write_bits(os, block_size >> 16, 8);
1054 lzx_write_bits(os, block_size & 0xFFFF, 16);
1057 /* If it's an aligned offset block, output the aligned offset code. */
1058 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1059 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1060 lzx_write_bits(os, codes->lens.aligned[i],
1061 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1065 /* Output the main code (two parts). */
1066 lzx_write_compressed_code(os, codes->lens.main,
1069 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1070 prev_lens->main + LZX_NUM_CHARS,
1071 num_main_syms - LZX_NUM_CHARS);
1073 /* Output the length code. */
1074 lzx_write_compressed_code(os, codes->lens.len,
1076 LZX_LENCODE_NUM_SYMBOLS);
1078 /* Output the compressed matches and literals. */
1079 lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1082 /* Given the frequencies of symbols in an LZX-compressed block and the
1083 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1084 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1085 * will take fewer bits to output. */
1087 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1088 const struct lzx_codes * codes)
1090 u32 aligned_cost = 0;
1091 u32 verbatim_cost = 0;
1093 /* A verbatim block requires 3 bits in each place that an aligned symbol
1094 * would be used in an aligned offset block. */
1095 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1096 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1097 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1100 /* Account for output of the aligned offset code. */
1101 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1103 if (aligned_cost < verbatim_cost)
1104 return LZX_BLOCKTYPE_ALIGNED;
1106 return LZX_BLOCKTYPE_VERBATIM;
1110 * Return the offset slot for the specified adjusted match offset, using the
1111 * compressor's acceleration tables to speed up the mapping.
1113 static inline unsigned
1114 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1117 if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1118 return c->offset_slot_tab_1[adjusted_offset];
1119 return c->offset_slot_tab_2[adjusted_offset >> 14];
1123 * Finish an LZX block:
1125 * - build the Huffman codes
1126 * - decide whether to output the block as VERBATIM or ALIGNED
1127 * - output the block
1128 * - swap the indices of the current and previous Huffman codes
1131 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1132 const u8 *block_begin, u32 block_size, u32 seq_idx)
1136 lzx_make_huffman_codes(c);
1138 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1139 &c->codes[c->codes_index]);
1140 lzx_write_compressed_block(block_begin,
1145 &c->chosen_sequences[seq_idx],
1146 &c->codes[c->codes_index],
1147 &c->codes[c->codes_index ^ 1].lens,
1149 c->codes_index ^= 1;
1152 /* Tally the Huffman symbol for a literal and increment the literal run length.
1155 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1157 c->freqs.main[literal]++;
1161 /* Tally the Huffman symbol for a match, save the match data and the length of
1162 * the preceding literal run in the next lzx_sequence, and update the recent
1165 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1166 u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1167 u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1169 u32 litrunlen = *litrunlen_p;
1170 struct lzx_sequence *next_seq = *next_seq_p;
1171 unsigned offset_slot;
1174 v = length - LZX_MIN_MATCH_LEN;
1176 /* Save the literal run length and adjusted length. */
1177 next_seq->litrunlen = litrunlen;
1178 next_seq->adjusted_length = v;
1180 /* Compute the length header and tally the length symbol if needed */
1181 if (v >= LZX_NUM_PRIMARY_LENS) {
1182 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1183 v = LZX_NUM_PRIMARY_LENS;
1186 /* Compute the offset slot */
1187 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1189 /* Compute the match header. */
1190 v += offset_slot * LZX_NUM_LEN_HEADERS;
1192 /* Save the adjusted offset and match header. */
1193 next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1195 /* Tally the main symbol. */
1196 c->freqs.main[LZX_NUM_CHARS + v]++;
1198 /* Update the recent offsets queue. */
1199 if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1200 /* Repeat offset match */
1201 swap(recent_offsets[0], recent_offsets[offset_data]);
1203 /* Explicit offset match */
1205 /* Tally the aligned offset symbol if needed */
1206 if (offset_data >= 16)
1207 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1209 recent_offsets[2] = recent_offsets[1];
1210 recent_offsets[1] = recent_offsets[0];
1211 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1214 /* Reset the literal run length and advance to the next sequence. */
1215 *next_seq_p = next_seq + 1;
1219 /* Finish the last lzx_sequence. The last lzx_sequence is just a literal run;
1220 * there is no match. This literal run may be empty. */
1222 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1224 last_seq->litrunlen = litrunlen;
1226 /* Special value to mark last sequence */
1227 last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1231 * Given the minimum-cost path computed through the item graph for the current
1232 * block, walk the path and count how many of each symbol in each Huffman-coded
1233 * alphabet would be required to output the items (matches and literals) along
1236 * Note that the path will be walked backwards (from the end of the block to the
1237 * beginning of the block), but this doesn't matter because this function only
1238 * computes frequencies.
1241 lzx_tally_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1243 u32 node_idx = block_size;
1248 unsigned offset_slot;
1250 /* Tally literals until either a match or the beginning of the
1251 * block is reached. */
1253 u32 item = c->optimum_nodes[node_idx].item;
1255 len = item & OPTIMUM_LEN_MASK;
1256 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1258 if (len != 0) /* Not a literal? */
1261 /* Tally the main symbol for the literal. */
1262 c->freqs.main[offset_data]++;
1264 if (--node_idx == 0) /* Beginning of block was reached? */
1270 /* Tally a match. */
1272 /* Tally the aligned offset symbol if needed. */
1273 if (offset_data >= 16)
1274 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1276 /* Tally the length symbol if needed. */
1277 v = len - LZX_MIN_MATCH_LEN;;
1278 if (v >= LZX_NUM_PRIMARY_LENS) {
1279 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1280 v = LZX_NUM_PRIMARY_LENS;
1283 /* Tally the main symbol. */
1284 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1285 v += offset_slot * LZX_NUM_LEN_HEADERS;
1286 c->freqs.main[LZX_NUM_CHARS + v]++;
1288 if (node_idx == 0) /* Beginning of block was reached? */
1294 * Like lzx_tally_item_list(), but this function also generates the list of
1295 * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1296 * ready to be output to the bitstream after the Huffman codes are computed.
1297 * The lzx_sequences will be written to decreasing memory addresses as the path
1298 * is walked backwards, which means they will end up in the expected
1299 * first-to-last order. The return value is the index in c->chosen_sequences at
1300 * which the lzx_sequences begin.
1303 lzx_record_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1305 u32 node_idx = block_size;
1306 u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1309 /* Special value to mark last sequence */
1310 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1312 lit_start_node = node_idx;
1317 unsigned offset_slot;
1319 /* Record literals until either a match or the beginning of the
1320 * block is reached. */
1322 u32 item = c->optimum_nodes[node_idx].item;
1324 len = item & OPTIMUM_LEN_MASK;
1325 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1327 if (len != 0) /* Not a literal? */
1330 /* Tally the main symbol for the literal. */
1331 c->freqs.main[offset_data]++;
1333 if (--node_idx == 0) /* Beginning of block was reached? */
1337 /* Save the literal run length for the next sequence (the
1338 * "previous sequence" when walking backwards). */
1339 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1341 lit_start_node = node_idx;
1343 /* Record a match. */
1345 /* Tally the aligned offset symbol if needed. */
1346 if (offset_data >= 16)
1347 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1349 /* Save the adjusted length. */
1350 v = len - LZX_MIN_MATCH_LEN;
1351 c->chosen_sequences[seq_idx].adjusted_length = v;
1353 /* Tally the length symbol if needed. */
1354 if (v >= LZX_NUM_PRIMARY_LENS) {
1355 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1356 v = LZX_NUM_PRIMARY_LENS;
1359 /* Tally the main symbol. */
1360 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1361 v += offset_slot * LZX_NUM_LEN_HEADERS;
1362 c->freqs.main[LZX_NUM_CHARS + v]++;
1364 /* Save the adjusted offset and match header. */
1365 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1366 (offset_data << 9) | v;
1368 if (node_idx == 0) /* Beginning of block was reached? */
1373 /* Save the literal run length for the first sequence. */
1374 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1376 /* Return the index in c->chosen_sequences at which the lzx_sequences
1382 * Find an inexpensive path through the graph of possible match/literal choices
1383 * for the current block. The nodes of the graph are
1384 * c->optimum_nodes[0...block_size]. They correspond directly to the bytes in
1385 * the current block, plus one extra node for end-of-block. The edges of the
1386 * graph are matches and literals. The goal is to find the minimum cost path
1387 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1389 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1390 * proceeding forwards one node at a time. At each node, a selection of matches
1391 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1392 * length 'len' provides a new path to reach the node 'len' bytes later. If
1393 * such a path is the lowest cost found so far to reach that later node, then
1394 * that later node is updated with the new path.
1396 * Note that although this algorithm is based on minimum cost path search, due
1397 * to various simplifying assumptions the result is not guaranteed to be the
1398 * true minimum cost, or "optimal", path over the graph of all valid LZX
1399 * representations of this block.
1401 * Also, note that because of the presence of the recent offsets queue (which is
1402 * a type of adaptive state), the algorithm cannot work backwards and compute
1403 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1404 * algorithm handles this adaptive state in the "minimum cost" parse is actually
1405 * only an approximation. It's possible for the globally optimal, minimum cost
1406 * path to contain a prefix, ending at a position, where that path prefix is
1407 * *not* the minimum cost path to that position. This can happen if such a path
1408 * prefix results in a different adaptive state which results in lower costs
1409 * later. The algorithm does not solve this problem; it only considers the
1410 * lowest cost to reach each individual position.
1412 static inline struct lzx_lru_queue
1413 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1414 const u8 * const restrict block_begin,
1415 const u32 block_size,
1416 const struct lzx_lru_queue initial_queue,
1419 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1420 struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1421 struct lz_match *cache_ptr = c->match_cache;
1422 const u8 *in_next = block_begin;
1423 const u8 * const block_end = block_begin + block_size;
1425 /* Instead of storing the match offset LRU queues in the
1426 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1427 * storing them in a smaller array. This works because the algorithm
1428 * only requires a limited history of the adaptive state. Once a given
1429 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1430 * it is no longer needed. */
1431 struct lzx_lru_queue queues[512];
1433 STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1434 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1436 /* Initially, the cost to reach each node is "infinity". */
1437 memset(c->optimum_nodes, 0xFF,
1438 (block_size + 1) * sizeof(c->optimum_nodes[0]));
1440 QUEUE(block_begin) = initial_queue;
1442 /* The following loop runs 'block_size' iterations, one per node. */
1444 unsigned num_matches;
1449 * A selection of matches for the block was already saved in
1450 * memory so that we don't have to run the uncompressed data
1451 * through the matchfinder on every optimization pass. However,
1452 * we still search for repeat offset matches during each
1453 * optimization pass because we cannot predict the state of the
1454 * recent offsets queue. But as a heuristic, we don't bother
1455 * searching for repeat offset matches if the general-purpose
1456 * matchfinder failed to find any matches.
1458 * Note that a match of length n at some offset implies there is
1459 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1460 * that same offset. In other words, we don't necessarily need
1461 * to use the full length of a match. The key heuristic that
1462 * saves a significicant amount of time is that for each
1463 * distinct length, we only consider the smallest offset for
1464 * which that length is available. This heuristic also applies
1465 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1466 * any explicit offset. Of course, this heuristic may be
1467 * produce suboptimal results because offset slots in LZX are
1468 * subject to entropy encoding, but in practice this is a useful
1472 num_matches = cache_ptr->length;
1476 struct lz_match *end_matches = cache_ptr + num_matches;
1477 unsigned next_len = LZX_MIN_MATCH_LEN;
1478 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1481 /* Consider R0 match */
1482 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1483 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1485 STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1487 u32 cost = cur_node->cost +
1488 c->costs.match_cost[0][
1489 next_len - LZX_MIN_MATCH_LEN];
1490 if (cost <= (cur_node + next_len)->cost) {
1491 (cur_node + next_len)->cost = cost;
1492 (cur_node + next_len)->item =
1493 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1495 if (unlikely(++next_len > max_len)) {
1496 cache_ptr = end_matches;
1499 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1503 /* Consider R1 match */
1504 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1505 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1507 if (matchptr[next_len - 1] != in_next[next_len - 1])
1509 for (unsigned len = 2; len < next_len - 1; len++)
1510 if (matchptr[len] != in_next[len])
1513 u32 cost = cur_node->cost +
1514 c->costs.match_cost[1][
1515 next_len - LZX_MIN_MATCH_LEN];
1516 if (cost <= (cur_node + next_len)->cost) {
1517 (cur_node + next_len)->cost = cost;
1518 (cur_node + next_len)->item =
1519 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1521 if (unlikely(++next_len > max_len)) {
1522 cache_ptr = end_matches;
1525 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1529 /* Consider R2 match */
1530 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1531 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1533 if (matchptr[next_len - 1] != in_next[next_len - 1])
1535 for (unsigned len = 2; len < next_len - 1; len++)
1536 if (matchptr[len] != in_next[len])
1539 u32 cost = cur_node->cost +
1540 c->costs.match_cost[2][
1541 next_len - LZX_MIN_MATCH_LEN];
1542 if (cost <= (cur_node + next_len)->cost) {
1543 (cur_node + next_len)->cost = cost;
1544 (cur_node + next_len)->item =
1545 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1547 if (unlikely(++next_len > max_len)) {
1548 cache_ptr = end_matches;
1551 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1555 while (next_len > cache_ptr->length)
1556 if (++cache_ptr == end_matches)
1559 /* Consider explicit offset matches */
1561 u32 offset = cache_ptr->offset;
1562 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1563 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1565 u32 base_cost = cur_node->cost;
1567 #if LZX_CONSIDER_ALIGNED_COSTS
1568 if (offset_data >= 16)
1569 base_cost += c->costs.aligned[offset_data &
1570 LZX_ALIGNED_OFFSET_BITMASK];
1574 u32 cost = base_cost +
1575 c->costs.match_cost[offset_slot][
1576 next_len - LZX_MIN_MATCH_LEN];
1577 if (cost < (cur_node + next_len)->cost) {
1578 (cur_node + next_len)->cost = cost;
1579 (cur_node + next_len)->item =
1580 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1582 } while (++next_len <= cache_ptr->length);
1583 } while (++cache_ptr != end_matches);
1588 /* Consider coding a literal.
1590 * To avoid an extra branch, actually checking the preferability
1591 * of coding the literal is integrated into the queue update
1593 literal = *in_next++;
1594 cost = cur_node->cost + c->costs.main[literal];
1596 /* Advance to the next position. */
1599 /* The lowest-cost path to the current position is now known.
1600 * Finalize the recent offsets queue that results from taking
1601 * this lowest-cost path. */
1603 if (cost <= cur_node->cost) {
1604 /* Literal: queue remains unchanged. */
1605 cur_node->cost = cost;
1606 cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1607 QUEUE(in_next) = QUEUE(in_next - 1);
1609 /* Match: queue update is needed. */
1610 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1611 u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1612 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1613 /* Explicit offset match: insert offset at front */
1615 lzx_lru_queue_push(QUEUE(in_next - len),
1616 offset_data - LZX_OFFSET_ADJUSTMENT);
1618 /* Repeat offset match: swap offset to front */
1620 lzx_lru_queue_swap(QUEUE(in_next - len),
1624 } while (cur_node != end_node);
1626 /* Return the match offset queue at the end of the minimum cost path. */
1627 return QUEUE(block_end);
1630 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1632 lzx_compute_match_costs(struct lzx_compressor *c)
1634 unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1635 LZX_NUM_LEN_HEADERS;
1636 struct lzx_costs *costs = &c->costs;
1638 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1640 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1641 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1642 LZX_NUM_LEN_HEADERS);
1645 #if LZX_CONSIDER_ALIGNED_COSTS
1646 if (offset_slot >= 8)
1647 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1650 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1651 costs->match_cost[offset_slot][i] =
1652 costs->main[main_symbol++] + extra_cost;
1654 extra_cost += costs->main[main_symbol];
1656 for (; i < LZX_NUM_LENS; i++)
1657 costs->match_cost[offset_slot][i] =
1658 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1662 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1665 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1668 bool have_byte[256];
1669 unsigned num_used_bytes;
1671 /* The costs below are hard coded to use a scaling factor of 16. */
1672 STATIC_ASSERT(LZX_BIT_COST == 16);
1677 * - Use smaller initial costs for literal symbols when the input buffer
1678 * contains fewer distinct bytes.
1680 * - Assume that match symbols are more costly than literal symbols.
1682 * - Assume that length symbols for shorter lengths are less costly than
1683 * length symbols for longer lengths.
1686 for (i = 0; i < 256; i++)
1687 have_byte[i] = false;
1689 for (i = 0; i < block_size; i++)
1690 have_byte[block[i]] = true;
1693 for (i = 0; i < 256; i++)
1694 num_used_bytes += have_byte[i];
1696 for (i = 0; i < 256; i++)
1697 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1699 for (; i < c->num_main_syms; i++)
1700 c->costs.main[i] = 170;
1702 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1703 c->costs.len[i] = 103 + (i / 4);
1705 #if LZX_CONSIDER_ALIGNED_COSTS
1706 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1707 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1710 lzx_compute_match_costs(c);
1713 /* Update the current cost model to reflect the computed Huffman codes. */
1715 lzx_update_costs(struct lzx_compressor *c)
1718 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1720 for (i = 0; i < c->num_main_syms; i++) {
1721 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1722 MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1725 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1726 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1727 LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1730 #if LZX_CONSIDER_ALIGNED_COSTS
1731 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1732 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1733 ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1737 lzx_compute_match_costs(c);
1740 static inline struct lzx_lru_queue
1741 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1742 struct lzx_output_bitstream * const restrict os,
1743 const u8 * const restrict block_begin,
1744 const u32 block_size,
1745 const struct lzx_lru_queue initial_queue,
1748 unsigned num_passes_remaining = c->num_optim_passes;
1749 struct lzx_lru_queue new_queue;
1752 /* The first optimization pass uses a default cost model. Each
1753 * additional optimization pass uses a cost model derived from the
1754 * Huffman code computed in the previous pass. */
1756 lzx_set_default_costs(c, block_begin, block_size);
1757 lzx_reset_symbol_frequencies(c);
1759 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1760 initial_queue, is_16_bit);
1761 if (num_passes_remaining > 1) {
1762 lzx_tally_item_list(c, block_size, is_16_bit);
1763 lzx_make_huffman_codes(c);
1764 lzx_update_costs(c);
1765 lzx_reset_symbol_frequencies(c);
1767 } while (--num_passes_remaining);
1769 seq_idx = lzx_record_item_list(c, block_size, is_16_bit);
1770 lzx_finish_block(c, os, block_begin, block_size, seq_idx);
1775 * This is the "near-optimal" LZX compressor.
1777 * For each block, it performs a relatively thorough graph search to find an
1778 * inexpensive (in terms of compressed size) way to output that block.
1780 * Note: there are actually many things this algorithm leaves on the table in
1781 * terms of compression ratio. So although it may be "near-optimal", it is
1782 * certainly not "optimal". The goal is not to produce the optimal compression
1783 * ratio, which for LZX is probably impossible within any practical amount of
1784 * time, but rather to produce a compression ratio significantly better than a
1785 * simpler "greedy" or "lazy" parse while still being relatively fast.
1788 lzx_compress_near_optimal(struct lzx_compressor *c,
1789 struct lzx_output_bitstream *os,
1792 const u8 * const in_begin = c->in_buffer;
1793 const u8 * in_next = in_begin;
1794 const u8 * const in_end = in_begin + c->in_nbytes;
1795 u32 max_len = LZX_MAX_MATCH_LEN;
1796 u32 nice_len = min(c->nice_match_length, max_len);
1797 u32 next_hashes[2] = {};
1798 struct lzx_lru_queue queue;
1800 CALL_BT_MF(is_16_bit, c, bt_matchfinder_init);
1801 lzx_lru_queue_init(&queue);
1804 /* Starting a new block */
1805 const u8 * const in_block_begin = in_next;
1806 const u8 * const in_block_end =
1807 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1809 /* Run the block through the matchfinder and cache the matches. */
1810 struct lz_match *cache_ptr = c->match_cache;
1812 struct lz_match *lz_matchptr;
1815 /* If approaching the end of the input buffer, adjust
1816 * 'max_len' and 'nice_len' accordingly. */
1817 if (unlikely(max_len > in_end - in_next)) {
1818 max_len = in_end - in_next;
1819 nice_len = min(max_len, nice_len);
1820 if (unlikely(max_len <
1821 BT_MATCHFINDER_REQUIRED_NBYTES))
1824 cache_ptr->length = 0;
1830 /* Check for matches. */
1831 lz_matchptr = CALL_BT_MF(is_16_bit, c,
1832 bt_matchfinder_get_matches,
1837 c->max_search_depth,
1842 cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1843 cache_ptr = lz_matchptr;
1846 * If there was a very long match found, then don't
1847 * cache any matches for the bytes covered by that
1848 * match. This avoids degenerate behavior when
1849 * compressing highly redundant data, where the number
1850 * of matches can be very large.
1852 * This heuristic doesn't actually hurt the compression
1853 * ratio very much. If there's a long match, then the
1854 * data must be highly compressible, so it doesn't
1855 * matter as much what we do.
1857 if (best_len >= nice_len) {
1860 if (unlikely(max_len > in_end - in_next)) {
1861 max_len = in_end - in_next;
1862 nice_len = min(max_len, nice_len);
1863 if (unlikely(max_len <
1864 BT_MATCHFINDER_REQUIRED_NBYTES))
1867 cache_ptr->length = 0;
1872 CALL_BT_MF(is_16_bit, c,
1873 bt_matchfinder_skip_position,
1877 c->max_search_depth,
1880 cache_ptr->length = 0;
1882 } while (--best_len);
1884 } while (in_next < in_block_end &&
1885 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1887 /* We've finished running the block through the matchfinder.
1888 * Now choose a match/literal sequence and write the block. */
1890 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1891 in_next - in_block_begin,
1893 } while (in_next != in_end);
1897 lzx_compress_near_optimal_16(struct lzx_compressor *c,
1898 struct lzx_output_bitstream *os)
1900 lzx_compress_near_optimal(c, os, true);
1904 lzx_compress_near_optimal_32(struct lzx_compressor *c,
1905 struct lzx_output_bitstream *os)
1907 lzx_compress_near_optimal(c, os, false);
1911 * Given a pointer to the current byte sequence and the current list of recent
1912 * match offsets, find the longest repeat offset match.
1914 * If no match of at least 2 bytes is found, then return 0.
1916 * If a match of at least 2 bytes is found, then return its length and set
1917 * *rep_max_idx_ret to the index of its offset in @queue.
1920 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1921 const u32 bytes_remaining,
1922 const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
1923 unsigned *rep_max_idx_ret)
1925 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
1927 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1928 const u16 next_2_bytes = load_u16_unaligned(in_next);
1930 unsigned rep_max_len;
1931 unsigned rep_max_idx;
1934 matchptr = in_next - recent_offsets[0];
1935 if (load_u16_unaligned(matchptr) == next_2_bytes)
1936 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1941 matchptr = in_next - recent_offsets[1];
1942 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1943 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1944 if (rep_len > rep_max_len) {
1945 rep_max_len = rep_len;
1950 matchptr = in_next - recent_offsets[2];
1951 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1952 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1953 if (rep_len > rep_max_len) {
1954 rep_max_len = rep_len;
1959 *rep_max_idx_ret = rep_max_idx;
1963 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
1964 static inline unsigned
1965 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1967 unsigned score = len;
1969 if (adjusted_offset < 4096)
1972 if (adjusted_offset < 256)
1978 static inline unsigned
1979 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1984 /* This is the "lazy" LZX compressor. */
1986 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1989 const u8 * const in_begin = c->in_buffer;
1990 const u8 * in_next = in_begin;
1991 const u8 * const in_end = in_begin + c->in_nbytes;
1992 unsigned max_len = LZX_MAX_MATCH_LEN;
1993 unsigned nice_len = min(c->nice_match_length, max_len);
1994 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
1995 u32 recent_offsets[3] = {1, 1, 1};
1996 u32 next_hashes[2] = {};
1998 CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2001 /* Starting a new block */
2003 const u8 * const in_block_begin = in_next;
2004 const u8 * const in_block_end =
2005 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
2006 struct lzx_sequence *next_seq = c->chosen_sequences;
2009 u32 cur_offset_data;
2013 u32 next_offset_data;
2014 unsigned next_score;
2015 unsigned rep_max_len;
2016 unsigned rep_max_idx;
2021 lzx_reset_symbol_frequencies(c);
2024 if (unlikely(max_len > in_end - in_next)) {
2025 max_len = in_end - in_next;
2026 nice_len = min(max_len, nice_len);
2029 /* Find the longest match at the current position. */
2031 cur_len = CALL_HC_MF(is_16_bit, c,
2032 hc_matchfinder_longest_match,
2038 c->max_search_depth,
2043 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2044 cur_offset != recent_offsets[0] &&
2045 cur_offset != recent_offsets[1] &&
2046 cur_offset != recent_offsets[2]))
2048 /* There was no match found, or the only match found
2049 * was a distant length 3 match. Output a literal. */
2050 lzx_record_literal(c, *in_next++, &litrunlen);
2054 if (cur_offset == recent_offsets[0]) {
2056 cur_offset_data = 0;
2057 skip_len = cur_len - 1;
2058 goto choose_cur_match;
2061 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2062 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2064 /* Consider a repeat offset match */
2065 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2071 if (rep_max_len >= 3 &&
2072 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2073 rep_max_idx)) >= cur_score)
2075 cur_len = rep_max_len;
2076 cur_offset_data = rep_max_idx;
2077 skip_len = rep_max_len - 1;
2078 goto choose_cur_match;
2083 /* We have a match at the current position. */
2085 /* If we have a very long match, choose it immediately. */
2086 if (cur_len >= nice_len) {
2087 skip_len = cur_len - 1;
2088 goto choose_cur_match;
2091 /* See if there's a better match at the next position. */
2093 if (unlikely(max_len > in_end - in_next)) {
2094 max_len = in_end - in_next;
2095 nice_len = min(max_len, nice_len);
2098 next_len = CALL_HC_MF(is_16_bit, c,
2099 hc_matchfinder_longest_match,
2105 c->max_search_depth / 2,
2109 if (next_len <= cur_len - 2) {
2111 skip_len = cur_len - 2;
2112 goto choose_cur_match;
2115 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2116 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2118 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2124 if (rep_max_len >= 3 &&
2125 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2126 rep_max_idx)) >= next_score)
2129 if (rep_score > cur_score) {
2130 /* The next match is better, and it's a
2131 * repeat offset match. */
2132 lzx_record_literal(c, *(in_next - 2),
2134 cur_len = rep_max_len;
2135 cur_offset_data = rep_max_idx;
2136 skip_len = cur_len - 1;
2137 goto choose_cur_match;
2140 if (next_score > cur_score) {
2141 /* The next match is better, and it's an
2142 * explicit offset match. */
2143 lzx_record_literal(c, *(in_next - 2),
2146 cur_offset_data = next_offset_data;
2147 cur_score = next_score;
2148 goto have_cur_match;
2152 /* The original match was better. */
2153 skip_len = cur_len - 2;
2156 lzx_record_match(c, cur_len, cur_offset_data,
2157 recent_offsets, is_16_bit,
2158 &litrunlen, &next_seq);
2159 in_next = CALL_HC_MF(is_16_bit, c,
2160 hc_matchfinder_skip_positions,
2166 } while (in_next < in_block_end);
2168 lzx_finish_sequence(next_seq, litrunlen);
2170 lzx_finish_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2172 } while (in_next != in_end);
2176 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2178 lzx_compress_lazy(c, os, true);
2182 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2184 lzx_compress_lazy(c, os, false);
2187 /* Generate the acceleration tables for offset slots. */
2189 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2191 u32 adjusted_offset = 0;
2195 for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2198 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2200 c->offset_slot_tab_1[adjusted_offset] = slot;
2203 /* slots [30, 49] */
2204 for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2205 adjusted_offset += (u32)1 << 14)
2207 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2209 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2214 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2216 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2217 if (lzx_is_16_bit(max_bufsize))
2218 return offsetof(struct lzx_compressor, hc_mf_16) +
2219 hc_matchfinder_size_16(max_bufsize);
2221 return offsetof(struct lzx_compressor, hc_mf_32) +
2222 hc_matchfinder_size_32(max_bufsize);
2224 if (lzx_is_16_bit(max_bufsize))
2225 return offsetof(struct lzx_compressor, bt_mf_16) +
2226 bt_matchfinder_size_16(max_bufsize);
2228 return offsetof(struct lzx_compressor, bt_mf_32) +
2229 bt_matchfinder_size_32(max_bufsize);
2234 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2239 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2242 size += lzx_get_compressor_size(max_bufsize, compression_level);
2244 size += max_bufsize; /* in_buffer */
2249 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2250 bool destructive, void **c_ret)
2252 unsigned window_order;
2253 struct lzx_compressor *c;
2255 window_order = lzx_get_window_order(max_bufsize);
2256 if (window_order == 0)
2257 return WIMLIB_ERR_INVALID_PARAM;
2259 c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2263 c->destructive = destructive;
2265 c->num_main_syms = lzx_get_num_main_syms(window_order);
2266 c->window_order = window_order;
2268 if (!c->destructive) {
2269 c->in_buffer = MALLOC(max_bufsize);
2274 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2276 /* Fast compression: Use lazy parsing. */
2278 if (lzx_is_16_bit(max_bufsize))
2279 c->impl = lzx_compress_lazy_16;
2281 c->impl = lzx_compress_lazy_32;
2282 c->max_search_depth = (60 * compression_level) / 20;
2283 c->nice_match_length = (80 * compression_level) / 20;
2285 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2286 * halves the max_search_depth when attempting a lazy match, and
2287 * max_search_depth cannot be 0. */
2288 if (c->max_search_depth < 2)
2289 c->max_search_depth = 2;
2292 /* Normal / high compression: Use near-optimal parsing. */
2294 if (lzx_is_16_bit(max_bufsize))
2295 c->impl = lzx_compress_near_optimal_16;
2297 c->impl = lzx_compress_near_optimal_32;
2299 /* Scale nice_match_length and max_search_depth with the
2300 * compression level. */
2301 c->max_search_depth = (24 * compression_level) / 50;
2302 c->nice_match_length = (48 * compression_level) / 50;
2304 /* Set a number of optimization passes appropriate for the
2305 * compression level. */
2307 c->num_optim_passes = 1;
2309 if (compression_level >= 45)
2310 c->num_optim_passes++;
2312 /* Use more optimization passes for higher compression levels.
2313 * But the more passes there are, the less they help --- so
2314 * don't add them linearly. */
2315 if (compression_level >= 70) {
2316 c->num_optim_passes++;
2317 if (compression_level >= 100)
2318 c->num_optim_passes++;
2319 if (compression_level >= 150)
2320 c->num_optim_passes++;
2321 if (compression_level >= 200)
2322 c->num_optim_passes++;
2323 if (compression_level >= 300)
2324 c->num_optim_passes++;
2328 /* max_search_depth == 0 is invalid. */
2329 if (c->max_search_depth < 1)
2330 c->max_search_depth = 1;
2332 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2333 c->nice_match_length = LZX_MAX_MATCH_LEN;
2335 lzx_init_offset_slot_tabs(c);
2342 return WIMLIB_ERR_NOMEM;
2346 lzx_compress(const void *restrict in, size_t in_nbytes,
2347 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2349 struct lzx_compressor *c = _c;
2350 struct lzx_output_bitstream os;
2353 /* Don't bother trying to compress very small inputs. */
2354 if (in_nbytes < 100)
2357 /* Copy the input data into the internal buffer and preprocess it. */
2359 c->in_buffer = (void *)in;
2361 memcpy(c->in_buffer, in, in_nbytes);
2362 c->in_nbytes = in_nbytes;
2363 lzx_preprocess(c->in_buffer, in_nbytes);
2365 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2367 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2369 /* Initialize the output bitstream. */
2370 lzx_init_output(&os, out, out_nbytes_avail);
2372 /* Call the compression level-specific compress() function. */
2375 /* Flush the output bitstream and return the compressed size or 0. */
2376 result = lzx_flush_output(&os);
2377 if (!result && c->destructive)
2378 lzx_postprocess(c->in_buffer, c->in_nbytes);
2383 lzx_free_compressor(void *_c)
2385 struct lzx_compressor *c = _c;
2387 if (!c->destructive)
2392 const struct compressor_ops lzx_compressor_ops = {
2393 .get_needed_memory = lzx_get_needed_memory,
2394 .create_compressor = lzx_create_compressor,
2395 .compress = lzx_compress,
2396 .free_compressor = lzx_free_compressor,