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 12 /* 64-bit: can buffer 4 main symbols */
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 the match offset minus LZX_OFFSET_ADJUSTMENT in bits 9-30.
236 * Otherwise, this sequence's literal run was the last literal run in
237 * the block, so there is no match that follows it. */
238 u32 adjusted_offset_and_match_hdr;
242 * This structure represents a byte position in the input buffer and a node in
243 * the graph of possible match/literal choices.
245 * Logically, each incoming edge to this node is labeled with a literal or a
246 * match that can be taken to reach this position from an earlier position; and
247 * each outgoing edge from this node is labeled with a literal or a match that
248 * can be taken to advance from this position to a later position.
250 struct lzx_optimum_node {
252 /* The cost, in bits, of the lowest-cost path that has been found to
253 * reach this position. This can change as progressively lower cost
254 * paths are found to reach this position. */
258 * The match or literal that was taken to reach this position. This can
259 * change as progressively lower cost paths are found to reach this
262 * This variable is divided into two bitfields.
265 * Low bits are 0, high bits are the literal.
267 * Explicit offset matches:
268 * Low bits are the match length, high bits are the offset plus 2.
270 * Repeat offset matches:
271 * Low bits are the match length, high bits are the queue index.
274 #define OPTIMUM_OFFSET_SHIFT 9
275 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
276 } _aligned_attribute(8);
279 * Least-recently-used queue for match offsets.
281 * This is represented as a 64-bit integer for efficiency. There are three
282 * offsets of 21 bits each. Bit 64 is garbage.
284 struct lzx_lru_queue {
288 #define LZX_QUEUE64_OFFSET_SHIFT 21
289 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
291 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
292 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
293 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
295 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
296 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
297 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
300 lzx_lru_queue_init(struct lzx_lru_queue *queue)
302 queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
303 ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
304 ((u64)1 << LZX_QUEUE64_R2_SHIFT);
308 lzx_lru_queue_R0(struct lzx_lru_queue queue)
310 return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
314 lzx_lru_queue_R1(struct lzx_lru_queue queue)
316 return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
320 lzx_lru_queue_R2(struct lzx_lru_queue queue)
322 return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
325 /* Push a match offset onto the front (most recently used) end of the queue. */
326 static inline struct lzx_lru_queue
327 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
329 return (struct lzx_lru_queue) {
330 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
334 /* Pop a match offset off the front (most recently used) end of the queue. */
336 lzx_lru_queue_pop(struct lzx_lru_queue *queue_p)
338 u32 offset = queue_p->R & LZX_QUEUE64_OFFSET_MASK;
339 queue_p->R >>= LZX_QUEUE64_OFFSET_SHIFT;
343 /* Swap a match offset to the front of the queue. */
344 static inline struct lzx_lru_queue
345 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
351 return (struct lzx_lru_queue) {
352 .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
353 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
354 (queue.R & LZX_QUEUE64_R2_MASK),
357 return (struct lzx_lru_queue) {
358 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
359 (queue.R & LZX_QUEUE64_R1_MASK) |
360 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
364 /* The main LZX compressor structure */
365 struct lzx_compressor {
367 /* The "nice" match length: if a match of this length is found, then
368 * choose it immediately without further consideration. */
369 unsigned nice_match_length;
371 /* The maximum search depth: consider at most this many potential
372 * matches at each position. */
373 unsigned max_search_depth;
375 /* The log base 2 of the LZX window size for LZ match offset encoding
376 * purposes. This will be >= LZX_MIN_WINDOW_ORDER and <=
377 * LZX_MAX_WINDOW_ORDER. */
378 unsigned window_order;
380 /* The number of symbols in the main alphabet. This depends on
381 * @window_order, since @window_order determines the maximum possible
383 unsigned num_main_syms;
385 /* Number of optimization passes per block */
386 unsigned num_optim_passes;
388 /* The preprocessed buffer of data being compressed */
391 /* The number of bytes of data to be compressed, which is the number of
392 * bytes of data in @in_buffer that are actually valid. */
395 /* Pointer to the compress() implementation chosen at allocation time */
396 void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
398 /* If true, the compressor need not preserve the input buffer if it
399 * compresses the data successfully. */
402 /* The Huffman symbol frequency counters for the current block. */
403 struct lzx_freqs freqs;
405 /* The Huffman codes for the current and previous blocks. The one with
406 * index 'codes_index' is for the current block, and the other one is
407 * for the previous block. */
408 struct lzx_codes codes[2];
409 unsigned codes_index;
411 /* The matches and literals that the parser has chosen for the current
412 * block. The required length of this array is limited by the maximum
413 * number of matches that can ever be chosen for a single block, plus
414 * one for the special entry at the end. */
415 struct lzx_sequence chosen_sequences[
416 DIV_ROUND_UP(LZX_DIV_BLOCK_SIZE, LZX_MIN_MATCH_LEN) + 1];
418 /* Tables for mapping adjusted offsets to offset slots */
420 /* offset slots [0, 29] */
421 u8 offset_slot_tab_1[32768];
423 /* offset slots [30, 49] */
424 u8 offset_slot_tab_2[128];
427 /* Data for greedy or lazy parsing */
429 /* Hash chains matchfinder (MUST BE LAST!!!) */
431 struct hc_matchfinder_16 hc_mf_16;
432 struct hc_matchfinder_32 hc_mf_32;
436 /* Data for near-optimal parsing */
439 * The graph nodes for the current block.
441 * We need at least 'LZX_DIV_BLOCK_SIZE +
442 * LZX_MAX_MATCH_LEN - 1' nodes because that is the
443 * maximum block size that may be used. Add 1 because
444 * we need a node to represent end-of-block.
446 * It is possible that nodes past end-of-block are
447 * accessed during match consideration, but this can
448 * only occur if the block was truncated at
449 * LZX_DIV_BLOCK_SIZE. So the same bound still applies.
450 * Note that since nodes past the end of the block will
451 * never actually have an effect on the items that are
452 * chosen for the block, it makes no difference what
453 * their costs are initialized to (if anything).
455 struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
456 LZX_MAX_MATCH_LEN - 1 + 1];
458 /* The cost model for the current block */
459 struct lzx_costs costs;
462 * Cached matches for the current block. This array
463 * contains the matches that were found at each position
464 * in the block. Specifically, for each position, there
465 * is a special 'struct lz_match' whose 'length' field
466 * contains the number of matches that were found at
467 * that position; this is followed by the matches
468 * themselves, if any, sorted by strictly increasing
471 * Note: in rare cases, there will be a very high number
472 * of matches in the block and this array will overflow.
473 * If this happens, we force the end of the current
474 * block. LZX_CACHE_LENGTH is the length at which we
475 * actually check for overflow. The extra slots beyond
476 * this are enough to absorb the worst case overflow,
477 * which occurs if starting at
478 * &match_cache[LZX_CACHE_LENGTH - 1], we write the
479 * match count header, then write
480 * LZX_MAX_MATCHES_PER_POS matches, then skip searching
481 * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
482 * write the match count header for each.
484 struct lz_match match_cache[LZX_CACHE_LENGTH +
485 LZX_MAX_MATCHES_PER_POS +
486 LZX_MAX_MATCH_LEN - 1];
488 /* Binary trees matchfinder (MUST BE LAST!!!) */
490 struct bt_matchfinder_16 bt_mf_16;
491 struct bt_matchfinder_32 bt_mf_32;
498 * Will a matchfinder using 16-bit positions be sufficient for compressing
499 * buffers of up to the specified size? The limit could be 65536 bytes, but we
500 * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
501 * This requires that the limit be no more than the length of offset_slot_tab_1
505 lzx_is_16_bit(size_t max_bufsize)
507 STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
508 return max_bufsize <= 32768;
512 * The following macros call either the 16-bit or the 32-bit version of a
513 * matchfinder function based on the value of 'is_16_bit', which will be known
514 * at compilation time.
517 #define CALL_HC_MF(is_16_bit, c, funcname, ...) \
518 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
519 CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
521 #define CALL_BT_MF(is_16_bit, c, funcname, ...) \
522 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->bt_mf_16, ##__VA_ARGS__) : \
523 CONCAT(funcname, _32)(&(c)->bt_mf_32, ##__VA_ARGS__));
526 * Structure to keep track of the current state of sending bits to the
527 * compressed output buffer.
529 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
531 struct lzx_output_bitstream {
533 /* Bits that haven't yet been written to the output buffer. */
534 machine_word_t bitbuf;
536 /* Number of bits currently held in @bitbuf. */
539 /* Pointer to the start of the output buffer. */
542 /* Pointer to the position in the output buffer at which the next coding
543 * unit should be written. */
546 /* Pointer just past the end of the output buffer, rounded down to a
547 * 2-byte boundary. */
551 /* Can the specified number of bits always be added to 'bitbuf' after any
552 * pending 16-bit coding units have been flushed? */
553 #define CAN_BUFFER(n) ((n) <= (8 * sizeof(machine_word_t)) - 15)
556 * Initialize the output bitstream.
559 * The output bitstream structure to initialize.
561 * The buffer being written to.
563 * Size of @buffer, in bytes.
566 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
571 os->next = os->start;
572 os->end = os->start + (size & ~1);
575 /* Add some bits to the bitbuffer variable of the output bitstream. The caller
576 * must make sure there is enough room. */
578 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
580 os->bitbuf = (os->bitbuf << num_bits) | bits;
581 os->bitcount += num_bits;
584 /* Flush bits from the bitbuffer variable to the output buffer. 'max_num_bits'
585 * specifies the maximum number of bits that may have been added since the last
588 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
590 /* Masking the number of bits to shift is only needed to avoid undefined
591 * behavior; we don't actually care about the results of bad shifts. On
592 * x86, the explicit masking generates no extra code. */
593 const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
595 if (os->end - os->next < 6)
597 put_unaligned_u16_le(os->bitbuf >> ((os->bitcount - 16) &
598 shift_mask), os->next + 0);
599 if (max_num_bits > 16)
600 put_unaligned_u16_le(os->bitbuf >> ((os->bitcount - 32) &
601 shift_mask), os->next + 2);
602 if (max_num_bits > 32)
603 put_unaligned_u16_le(os->bitbuf >> ((os->bitcount - 48) &
604 shift_mask), os->next + 4);
605 os->next += (os->bitcount >> 4) << 1;
609 /* Add at most 16 bits to the bitbuffer and flush it. */
611 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
613 lzx_add_bits(os, bits, num_bits);
614 lzx_flush_bits(os, 16);
618 * Flush the last coding unit to the output buffer if needed. Return the total
619 * number of bytes written to the output buffer, or 0 if an overflow occurred.
622 lzx_flush_output(struct lzx_output_bitstream *os)
624 if (os->end - os->next < 6)
627 if (os->bitcount != 0) {
628 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next);
632 return os->next - os->start;
635 /* Build the main, length, and aligned offset Huffman codes used in LZX.
637 * This takes as input the frequency tables for each code and produces as output
638 * a set of tables that map symbols to codewords and codeword lengths. */
640 lzx_make_huffman_codes(struct lzx_compressor *c)
642 const struct lzx_freqs *freqs = &c->freqs;
643 struct lzx_codes *codes = &c->codes[c->codes_index];
645 STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
646 MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
647 STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
648 LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
649 STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
650 ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
652 make_canonical_huffman_code(c->num_main_syms,
656 codes->codewords.main);
658 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
659 LENGTH_CODEWORD_LIMIT,
662 codes->codewords.len);
664 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
665 ALIGNED_CODEWORD_LIMIT,
668 codes->codewords.aligned);
671 /* Reset the symbol frequencies for the LZX Huffman codes. */
673 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
675 memset(&c->freqs, 0, sizeof(c->freqs));
679 lzx_compute_precode_items(const u8 lens[restrict],
680 const u8 prev_lens[restrict],
681 u32 precode_freqs[restrict],
682 unsigned precode_items[restrict])
691 itemptr = precode_items;
694 while (!((len = lens[run_start]) & 0x80)) {
696 /* len = the length being repeated */
698 /* Find the next run of codeword lengths. */
700 run_end = run_start + 1;
702 /* Fast case for a single length. */
703 if (likely(len != lens[run_end])) {
704 delta = prev_lens[run_start] - len;
707 precode_freqs[delta]++;
713 /* Extend the run. */
716 } while (len == lens[run_end]);
721 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
722 while ((run_end - run_start) >= 20) {
723 extra_bits = min((run_end - run_start) - 20, 0x1f);
725 *itemptr++ = 18 | (extra_bits << 5);
726 run_start += 20 + extra_bits;
729 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
730 if ((run_end - run_start) >= 4) {
731 extra_bits = min((run_end - run_start) - 4, 0xf);
733 *itemptr++ = 17 | (extra_bits << 5);
734 run_start += 4 + extra_bits;
738 /* A run of nonzero lengths. */
740 /* Symbol 19: RLE 4 to 5 of any length at a time. */
741 while ((run_end - run_start) >= 4) {
742 extra_bits = (run_end - run_start) > 4;
743 delta = prev_lens[run_start] - len;
747 precode_freqs[delta]++;
748 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
749 run_start += 4 + extra_bits;
753 /* Output any remaining lengths without RLE. */
754 while (run_start != run_end) {
755 delta = prev_lens[run_start] - len;
758 precode_freqs[delta]++;
764 return itemptr - precode_items;
768 * Output a Huffman code in the compressed form used in LZX.
770 * The Huffman code is represented in the output as a logical series of codeword
771 * lengths from which the Huffman code, which must be in canonical form, can be
774 * The codeword lengths are themselves compressed using a separate Huffman code,
775 * the "precode", which contains a symbol for each possible codeword length in
776 * the larger code as well as several special symbols to represent repeated
777 * codeword lengths (a form of run-length encoding). The precode is itself
778 * constructed in canonical form, and its codeword lengths are represented
779 * literally in 20 4-bit fields that immediately precede the compressed codeword
780 * lengths of the larger code.
782 * Furthermore, the codeword lengths of the larger code are actually represented
783 * as deltas from the codeword lengths of the corresponding code in the previous
787 * Bitstream to which to write the compressed Huffman code.
789 * The codeword lengths, indexed by symbol, in the Huffman code.
791 * The codeword lengths, indexed by symbol, in the corresponding Huffman
792 * code in the previous block, or all zeroes if this is the first block.
794 * The number of symbols in the Huffman code.
797 lzx_write_compressed_code(struct lzx_output_bitstream *os,
798 const u8 lens[restrict],
799 const u8 prev_lens[restrict],
802 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
803 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
804 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
805 unsigned precode_items[num_lens];
806 unsigned num_precode_items;
807 unsigned precode_item;
808 unsigned precode_sym;
810 u8 saved = lens[num_lens];
811 *(u8 *)(lens + num_lens) = 0x80;
813 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
814 precode_freqs[i] = 0;
816 /* Compute the "items" (RLE / literal tokens and extra bits) with which
817 * the codeword lengths in the larger code will be output. */
818 num_precode_items = lzx_compute_precode_items(lens,
823 /* Build the precode. */
824 STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
825 PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
826 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
828 precode_freqs, precode_lens,
831 /* Output the lengths of the codewords in the precode. */
832 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
833 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
835 /* Output the encoded lengths of the codewords in the larger code. */
836 for (i = 0; i < num_precode_items; i++) {
837 precode_item = precode_items[i];
838 precode_sym = precode_item & 0x1F;
839 lzx_add_bits(os, precode_codewords[precode_sym],
840 precode_lens[precode_sym]);
841 if (precode_sym >= 17) {
842 if (precode_sym == 17) {
843 lzx_add_bits(os, precode_item >> 5, 4);
844 } else if (precode_sym == 18) {
845 lzx_add_bits(os, precode_item >> 5, 5);
847 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
848 precode_sym = precode_item >> 6;
849 lzx_add_bits(os, precode_codewords[precode_sym],
850 precode_lens[precode_sym]);
853 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
854 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
857 *(u8 *)(lens + num_lens) = saved;
861 * Write all matches and literal bytes (which were precomputed) in an LZX
862 * compressed block to the output bitstream in the final compressed
866 * The output bitstream.
868 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
869 * LZX_BLOCKTYPE_VERBATIM).
871 * The uncompressed data of the block.
873 * The matches and literals to output, given as a series of sequences.
875 * The main, length, and aligned offset Huffman codes for the current
876 * LZX compressed block.
879 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
880 const u8 *block_data, const struct lzx_sequence sequences[],
881 const struct lzx_codes *codes)
883 const struct lzx_sequence *seq = sequences;
884 u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
887 /* Output the next sequence. */
889 unsigned litrunlen = seq->litrunlen;
891 unsigned main_symbol;
892 unsigned adjusted_length;
894 unsigned offset_slot;
895 unsigned num_extra_bits;
898 /* Output the literal run of the sequence. */
900 if (litrunlen) { /* Is the literal run nonempty? */
902 /* Verify optimization is enabled on 64-bit */
903 STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
904 CAN_BUFFER(4 * MAIN_CODEWORD_LIMIT));
906 if (CAN_BUFFER(4 * MAIN_CODEWORD_LIMIT)) {
908 /* 64-bit: write 4 literals at a time. */
909 while (litrunlen >= 4) {
910 unsigned lit0 = block_data[0];
911 unsigned lit1 = block_data[1];
912 unsigned lit2 = block_data[2];
913 unsigned lit3 = block_data[3];
914 lzx_add_bits(os, codes->codewords.main[lit0], codes->lens.main[lit0]);
915 lzx_add_bits(os, codes->codewords.main[lit1], codes->lens.main[lit1]);
916 lzx_add_bits(os, codes->codewords.main[lit2], codes->lens.main[lit2]);
917 lzx_add_bits(os, codes->codewords.main[lit3], codes->lens.main[lit3]);
918 lzx_flush_bits(os, 4 * MAIN_CODEWORD_LIMIT);
923 unsigned lit = *block_data++;
924 lzx_add_bits(os, codes->codewords.main[lit], codes->lens.main[lit]);
926 unsigned lit = *block_data++;
927 lzx_add_bits(os, codes->codewords.main[lit], codes->lens.main[lit]);
929 unsigned lit = *block_data++;
930 lzx_add_bits(os, codes->codewords.main[lit], codes->lens.main[lit]);
931 lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
933 lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
936 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
940 /* 32-bit: write 1 literal at a time. */
942 unsigned lit = *block_data++;
943 lzx_add_bits(os, codes->codewords.main[lit], codes->lens.main[lit]);
944 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
945 } while (--litrunlen);
949 /* Was this the last literal run? */
950 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
953 /* Nope; output the match. */
955 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
956 main_symbol = LZX_NUM_CHARS + match_hdr;
957 adjusted_length = seq->adjusted_length;
959 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
961 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
962 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
964 num_extra_bits = lzx_extra_offset_bits[offset_slot];
965 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
967 #define MAX_MATCH_BITS (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
968 14 + ALIGNED_CODEWORD_LIMIT)
970 /* Verify optimization is enabled on 64-bit */
971 STATIC_ASSERT(sizeof(machine_word_t) < 8 || CAN_BUFFER(MAX_MATCH_BITS));
973 /* Output the main symbol for the match. */
975 lzx_add_bits(os, codes->codewords.main[main_symbol],
976 codes->lens.main[main_symbol]);
977 if (!CAN_BUFFER(MAX_MATCH_BITS))
978 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
980 /* If needed, output the length symbol for the match. */
982 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
983 lzx_add_bits(os, codes->codewords.len[adjusted_length - LZX_NUM_PRIMARY_LENS],
984 codes->lens.len[adjusted_length - LZX_NUM_PRIMARY_LENS]);
985 if (!CAN_BUFFER(MAX_MATCH_BITS))
986 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
989 /* Output the extra offset bits for the match. In aligned
990 * offset blocks, the lowest 3 bits of the adjusted offset are
991 * Huffman-encoded using the aligned offset code, provided that
992 * there are at least extra 3 offset bits required. All other
993 * extra offset bits are output verbatim. */
995 if ((adjusted_offset & ones_if_aligned) >= 16) {
997 lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
998 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
999 if (!CAN_BUFFER(MAX_MATCH_BITS))
1000 lzx_flush_bits(os, 14);
1002 lzx_add_bits(os, codes->codewords.aligned[adjusted_offset & LZX_ALIGNED_OFFSET_BITMASK],
1003 codes->lens.aligned[adjusted_offset & LZX_ALIGNED_OFFSET_BITMASK]);
1004 if (!CAN_BUFFER(MAX_MATCH_BITS))
1005 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1007 STATIC_ASSERT(CAN_BUFFER(17));
1009 lzx_add_bits(os, extra_bits, num_extra_bits);
1010 if (!CAN_BUFFER(MAX_MATCH_BITS))
1011 lzx_flush_bits(os, 17);
1014 if (CAN_BUFFER(MAX_MATCH_BITS))
1015 lzx_flush_bits(os, MAX_MATCH_BITS);
1017 /* Advance to the next sequence. */
1023 lzx_write_compressed_block(const u8 *block_begin,
1026 unsigned window_order,
1027 unsigned num_main_syms,
1028 const struct lzx_sequence sequences[],
1029 const struct lzx_codes * codes,
1030 const struct lzx_lens * prev_lens,
1031 struct lzx_output_bitstream * os)
1033 /* The first three bits indicate the type of block and are one of the
1034 * LZX_BLOCKTYPE_* constants. */
1035 lzx_write_bits(os, block_type, 3);
1037 /* Output the block size.
1039 * The original LZX format seemed to always encode the block size in 3
1040 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
1041 * uses the first bit to indicate whether the block is the default size
1042 * (32768) or a different size given explicitly by the next 16 bits.
1044 * By default, this compressor uses a window size of 32768 and therefore
1045 * follows the WIMGAPI behavior. However, this compressor also supports
1046 * window sizes greater than 32768 bytes, which do not appear to be
1047 * supported by WIMGAPI. In such cases, we retain the default size bit
1048 * to mean a size of 32768 bytes but output non-default block size in 24
1049 * bits rather than 16. The compatibility of this behavior is unknown
1050 * because WIMs created with chunk size greater than 32768 can seemingly
1051 * only be opened by wimlib anyway. */
1052 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1053 lzx_write_bits(os, 1, 1);
1055 lzx_write_bits(os, 0, 1);
1057 if (window_order >= 16)
1058 lzx_write_bits(os, block_size >> 16, 8);
1060 lzx_write_bits(os, block_size & 0xFFFF, 16);
1063 /* If it's an aligned offset block, output the aligned offset code. */
1064 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1065 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1066 lzx_write_bits(os, codes->lens.aligned[i],
1067 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1071 /* Output the main code (two parts). */
1072 lzx_write_compressed_code(os, codes->lens.main,
1075 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1076 prev_lens->main + LZX_NUM_CHARS,
1077 num_main_syms - LZX_NUM_CHARS);
1079 /* Output the length code. */
1080 lzx_write_compressed_code(os, codes->lens.len,
1082 LZX_LENCODE_NUM_SYMBOLS);
1084 /* Output the compressed matches and literals. */
1085 lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1088 /* Given the frequencies of symbols in an LZX-compressed block and the
1089 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1090 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1091 * will take fewer bits to output. */
1093 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1094 const struct lzx_codes * codes)
1096 u32 aligned_cost = 0;
1097 u32 verbatim_cost = 0;
1099 /* A verbatim block requires 3 bits in each place that an aligned symbol
1100 * would be used in an aligned offset block. */
1101 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1102 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1103 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1106 /* Account for output of the aligned offset code. */
1107 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1109 if (aligned_cost < verbatim_cost)
1110 return LZX_BLOCKTYPE_ALIGNED;
1112 return LZX_BLOCKTYPE_VERBATIM;
1116 * Return the offset slot for the specified adjusted match offset, using the
1117 * compressor's acceleration tables to speed up the mapping.
1119 static inline unsigned
1120 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1123 if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1124 return c->offset_slot_tab_1[adjusted_offset];
1125 return c->offset_slot_tab_2[adjusted_offset >> 14];
1129 * Finish an LZX block:
1131 * - build the Huffman codes
1132 * - decide whether to output the block as VERBATIM or ALIGNED
1133 * - output the block
1134 * - swap the indices of the current and previous Huffman codes
1137 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1138 const u8 *block_begin, u32 block_size, u32 seq_idx)
1142 lzx_make_huffman_codes(c);
1144 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1145 &c->codes[c->codes_index]);
1146 lzx_write_compressed_block(block_begin,
1151 &c->chosen_sequences[seq_idx],
1152 &c->codes[c->codes_index],
1153 &c->codes[c->codes_index ^ 1].lens,
1155 c->codes_index ^= 1;
1158 /* Tally the Huffman symbol for a literal and increment the literal run length.
1161 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1163 c->freqs.main[literal]++;
1167 /* Tally the Huffman symbol for a match, save the match data and the length of
1168 * the preceding literal run in the next lzx_sequence, and update the recent
1171 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1172 u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1173 u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1175 u32 litrunlen = *litrunlen_p;
1176 struct lzx_sequence *next_seq = *next_seq_p;
1177 unsigned offset_slot;
1180 v = length - LZX_MIN_MATCH_LEN;
1182 /* Save the literal run length and adjusted length. */
1183 next_seq->litrunlen = litrunlen;
1184 next_seq->adjusted_length = v;
1186 /* Compute the length header and tally the length symbol if needed */
1187 if (v >= LZX_NUM_PRIMARY_LENS) {
1188 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1189 v = LZX_NUM_PRIMARY_LENS;
1192 /* Compute the offset slot */
1193 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1195 /* Compute the match header. */
1196 v += offset_slot * LZX_NUM_LEN_HEADERS;
1198 /* Save the adjusted offset and match header. */
1199 next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1201 /* Tally the main symbol. */
1202 c->freqs.main[LZX_NUM_CHARS + v]++;
1204 /* Update the recent offsets queue. */
1205 if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1206 /* Repeat offset match */
1207 swap(recent_offsets[0], recent_offsets[offset_data]);
1209 /* Explicit offset match */
1211 /* Tally the aligned offset symbol if needed */
1212 if (offset_data >= 16)
1213 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1215 recent_offsets[2] = recent_offsets[1];
1216 recent_offsets[1] = recent_offsets[0];
1217 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1220 /* Reset the literal run length and advance to the next sequence. */
1221 *next_seq_p = next_seq + 1;
1225 /* Finish the last lzx_sequence. The last lzx_sequence is just a literal run;
1226 * there is no match. This literal run may be empty. */
1228 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1230 last_seq->litrunlen = litrunlen;
1232 /* Special value to mark last sequence */
1233 last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1237 * Given the minimum-cost path computed through the item graph for the current
1238 * block, walk the path and count how many of each symbol in each Huffman-coded
1239 * alphabet would be required to output the items (matches and literals) along
1242 * Note that the path will be walked backwards (from the end of the block to the
1243 * beginning of the block), but this doesn't matter because this function only
1244 * computes frequencies.
1247 lzx_tally_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1249 u32 node_idx = block_size;
1254 unsigned offset_slot;
1256 /* Tally literals until either a match or the beginning of the
1257 * block is reached. */
1259 u32 item = c->optimum_nodes[node_idx].item;
1261 len = item & OPTIMUM_LEN_MASK;
1262 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1264 if (len != 0) /* Not a literal? */
1267 /* Tally the main symbol for the literal. */
1268 c->freqs.main[offset_data]++;
1270 if (--node_idx == 0) /* Beginning of block was reached? */
1276 /* Tally a match. */
1278 /* Tally the aligned offset symbol if needed. */
1279 if (offset_data >= 16)
1280 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1282 /* Tally the length symbol if needed. */
1283 v = len - LZX_MIN_MATCH_LEN;;
1284 if (v >= LZX_NUM_PRIMARY_LENS) {
1285 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1286 v = LZX_NUM_PRIMARY_LENS;
1289 /* Tally the main symbol. */
1290 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1291 v += offset_slot * LZX_NUM_LEN_HEADERS;
1292 c->freqs.main[LZX_NUM_CHARS + v]++;
1294 if (node_idx == 0) /* Beginning of block was reached? */
1300 * Like lzx_tally_item_list(), but this function also generates the list of
1301 * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1302 * ready to be output to the bitstream after the Huffman codes are computed.
1303 * The lzx_sequences will be written to decreasing memory addresses as the path
1304 * is walked backwards, which means they will end up in the expected
1305 * first-to-last order. The return value is the index in c->chosen_sequences at
1306 * which the lzx_sequences begin.
1309 lzx_record_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1311 u32 node_idx = block_size;
1312 u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1315 /* Special value to mark last sequence */
1316 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1318 lit_start_node = node_idx;
1323 unsigned offset_slot;
1325 /* Record literals until either a match or the beginning of the
1326 * block is reached. */
1328 u32 item = c->optimum_nodes[node_idx].item;
1330 len = item & OPTIMUM_LEN_MASK;
1331 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1333 if (len != 0) /* Not a literal? */
1336 /* Tally the main symbol for the literal. */
1337 c->freqs.main[offset_data]++;
1339 if (--node_idx == 0) /* Beginning of block was reached? */
1343 /* Save the literal run length for the next sequence (the
1344 * "previous sequence" when walking backwards). */
1345 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1347 lit_start_node = node_idx;
1349 /* Record a match. */
1351 /* Tally the aligned offset symbol if needed. */
1352 if (offset_data >= 16)
1353 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1355 /* Save the adjusted length. */
1356 v = len - LZX_MIN_MATCH_LEN;
1357 c->chosen_sequences[seq_idx].adjusted_length = v;
1359 /* Tally the length symbol if needed. */
1360 if (v >= LZX_NUM_PRIMARY_LENS) {
1361 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1362 v = LZX_NUM_PRIMARY_LENS;
1365 /* Tally the main symbol. */
1366 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1367 v += offset_slot * LZX_NUM_LEN_HEADERS;
1368 c->freqs.main[LZX_NUM_CHARS + v]++;
1370 /* Save the adjusted offset and match header. */
1371 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1372 (offset_data << 9) | v;
1374 if (node_idx == 0) /* Beginning of block was reached? */
1379 /* Save the literal run length for the first sequence. */
1380 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1382 /* Return the index in c->chosen_sequences at which the lzx_sequences
1388 * Find an inexpensive path through the graph of possible match/literal choices
1389 * for the current block. The nodes of the graph are
1390 * c->optimum_nodes[0...block_size]. They correspond directly to the bytes in
1391 * the current block, plus one extra node for end-of-block. The edges of the
1392 * graph are matches and literals. The goal is to find the minimum cost path
1393 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1395 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1396 * proceeding forwards one node at a time. At each node, a selection of matches
1397 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1398 * length 'len' provides a new path to reach the node 'len' bytes later. If
1399 * such a path is the lowest cost found so far to reach that later node, then
1400 * that later node is updated with the new path.
1402 * Note that although this algorithm is based on minimum cost path search, due
1403 * to various simplifying assumptions the result is not guaranteed to be the
1404 * true minimum cost, or "optimal", path over the graph of all valid LZX
1405 * representations of this block.
1407 * Also, note that because of the presence of the recent offsets queue (which is
1408 * a type of adaptive state), the algorithm cannot work backwards and compute
1409 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1410 * algorithm handles this adaptive state in the "minimum cost" parse is actually
1411 * only an approximation. It's possible for the globally optimal, minimum cost
1412 * path to contain a prefix, ending at a position, where that path prefix is
1413 * *not* the minimum cost path to that position. This can happen if such a path
1414 * prefix results in a different adaptive state which results in lower costs
1415 * later. The algorithm does not solve this problem; it only considers the
1416 * lowest cost to reach each individual position.
1418 static inline struct lzx_lru_queue
1419 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1420 const u8 * const restrict block_begin,
1421 const u32 block_size,
1422 const struct lzx_lru_queue initial_queue,
1425 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1426 struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1427 struct lz_match *cache_ptr = c->match_cache;
1428 const u8 *in_next = block_begin;
1429 const u8 * const block_end = block_begin + block_size;
1431 /* Instead of storing the match offset LRU queues in the
1432 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1433 * storing them in a smaller array. This works because the algorithm
1434 * only requires a limited history of the adaptive state. Once a given
1435 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1436 * it is no longer needed. */
1437 struct lzx_lru_queue queues[512];
1439 STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1440 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1442 /* Initially, the cost to reach each node is "infinity". */
1443 memset(c->optimum_nodes, 0xFF,
1444 (block_size + 1) * sizeof(c->optimum_nodes[0]));
1446 QUEUE(block_begin) = initial_queue;
1448 /* The following loop runs 'block_size' iterations, one per node. */
1450 unsigned num_matches;
1455 * A selection of matches for the block was already saved in
1456 * memory so that we don't have to run the uncompressed data
1457 * through the matchfinder on every optimization pass. However,
1458 * we still search for repeat offset matches during each
1459 * optimization pass because we cannot predict the state of the
1460 * recent offsets queue. But as a heuristic, we don't bother
1461 * searching for repeat offset matches if the general-purpose
1462 * matchfinder failed to find any matches.
1464 * Note that a match of length n at some offset implies there is
1465 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1466 * that same offset. In other words, we don't necessarily need
1467 * to use the full length of a match. The key heuristic that
1468 * saves a significicant amount of time is that for each
1469 * distinct length, we only consider the smallest offset for
1470 * which that length is available. This heuristic also applies
1471 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1472 * any explicit offset. Of course, this heuristic may be
1473 * produce suboptimal results because offset slots in LZX are
1474 * subject to entropy encoding, but in practice this is a useful
1478 num_matches = cache_ptr->length;
1482 struct lz_match *end_matches = cache_ptr + num_matches;
1483 unsigned next_len = LZX_MIN_MATCH_LEN;
1484 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1487 /* Consider R0 match */
1488 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1489 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1491 STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1493 u32 cost = cur_node->cost +
1494 c->costs.match_cost[0][
1495 next_len - LZX_MIN_MATCH_LEN];
1496 if (cost <= (cur_node + next_len)->cost) {
1497 (cur_node + next_len)->cost = cost;
1498 (cur_node + next_len)->item =
1499 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1501 if (unlikely(++next_len > max_len)) {
1502 cache_ptr = end_matches;
1505 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1509 /* Consider R1 match */
1510 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1511 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1513 if (matchptr[next_len - 1] != in_next[next_len - 1])
1515 for (unsigned len = 2; len < next_len - 1; len++)
1516 if (matchptr[len] != in_next[len])
1519 u32 cost = cur_node->cost +
1520 c->costs.match_cost[1][
1521 next_len - LZX_MIN_MATCH_LEN];
1522 if (cost <= (cur_node + next_len)->cost) {
1523 (cur_node + next_len)->cost = cost;
1524 (cur_node + next_len)->item =
1525 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1527 if (unlikely(++next_len > max_len)) {
1528 cache_ptr = end_matches;
1531 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1535 /* Consider R2 match */
1536 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1537 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1539 if (matchptr[next_len - 1] != in_next[next_len - 1])
1541 for (unsigned len = 2; len < next_len - 1; len++)
1542 if (matchptr[len] != in_next[len])
1545 u32 cost = cur_node->cost +
1546 c->costs.match_cost[2][
1547 next_len - LZX_MIN_MATCH_LEN];
1548 if (cost <= (cur_node + next_len)->cost) {
1549 (cur_node + next_len)->cost = cost;
1550 (cur_node + next_len)->item =
1551 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1553 if (unlikely(++next_len > max_len)) {
1554 cache_ptr = end_matches;
1557 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1561 while (next_len > cache_ptr->length)
1562 if (++cache_ptr == end_matches)
1565 /* Consider explicit offset matches */
1567 u32 offset = cache_ptr->offset;
1568 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1569 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1571 u32 base_cost = cur_node->cost;
1573 #if LZX_CONSIDER_ALIGNED_COSTS
1574 if (offset_data >= 16)
1575 base_cost += c->costs.aligned[offset_data &
1576 LZX_ALIGNED_OFFSET_BITMASK];
1580 u32 cost = base_cost +
1581 c->costs.match_cost[offset_slot][
1582 next_len - LZX_MIN_MATCH_LEN];
1583 if (cost < (cur_node + next_len)->cost) {
1584 (cur_node + next_len)->cost = cost;
1585 (cur_node + next_len)->item =
1586 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1588 } while (++next_len <= cache_ptr->length);
1589 } while (++cache_ptr != end_matches);
1594 /* Consider coding a literal.
1596 * To avoid an extra branch, actually checking the preferability
1597 * of coding the literal is integrated into the queue update
1599 literal = *in_next++;
1600 cost = cur_node->cost + c->costs.main[literal];
1602 /* Advance to the next position. */
1605 /* The lowest-cost path to the current position is now known.
1606 * Finalize the recent offsets queue that results from taking
1607 * this lowest-cost path. */
1609 if (cost <= cur_node->cost) {
1610 /* Literal: queue remains unchanged. */
1611 cur_node->cost = cost;
1612 cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1613 QUEUE(in_next) = QUEUE(in_next - 1);
1615 /* Match: queue update is needed. */
1616 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1617 u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1618 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1619 /* Explicit offset match: insert offset at front */
1621 lzx_lru_queue_push(QUEUE(in_next - len),
1622 offset_data - LZX_OFFSET_ADJUSTMENT);
1624 /* Repeat offset match: swap offset to front */
1626 lzx_lru_queue_swap(QUEUE(in_next - len),
1630 } while (cur_node != end_node);
1632 /* Return the match offset queue at the end of the minimum cost path. */
1633 return QUEUE(block_end);
1636 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1638 lzx_compute_match_costs(struct lzx_compressor *c)
1640 unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) / LZX_NUM_LEN_HEADERS;
1641 struct lzx_costs *costs = &c->costs;
1643 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1645 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1646 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot * LZX_NUM_LEN_HEADERS);
1649 #if LZX_CONSIDER_ALIGNED_COSTS
1650 if (offset_slot >= 8)
1651 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1654 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1655 costs->match_cost[offset_slot][i] =
1656 costs->main[main_symbol++] + extra_cost;
1658 extra_cost += costs->main[main_symbol];
1660 for (; i < LZX_NUM_LENS; i++)
1661 costs->match_cost[offset_slot][i] =
1662 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1666 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1669 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1672 bool have_byte[256];
1673 unsigned num_used_bytes;
1675 /* The costs below are hard coded to use a scaling factor of 16. */
1676 STATIC_ASSERT(LZX_BIT_COST == 16);
1681 * - Use smaller initial costs for literal symbols when the input buffer
1682 * contains fewer distinct bytes.
1684 * - Assume that match symbols are more costly than literal symbols.
1686 * - Assume that length symbols for shorter lengths are less costly than
1687 * length symbols for longer lengths.
1690 for (i = 0; i < 256; i++)
1691 have_byte[i] = false;
1693 for (i = 0; i < block_size; i++)
1694 have_byte[block[i]] = true;
1697 for (i = 0; i < 256; i++)
1698 num_used_bytes += have_byte[i];
1700 for (i = 0; i < 256; i++)
1701 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1703 for (; i < c->num_main_syms; i++)
1704 c->costs.main[i] = 170;
1706 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1707 c->costs.len[i] = 103 + (i / 4);
1709 #if LZX_CONSIDER_ALIGNED_COSTS
1710 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1711 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1714 lzx_compute_match_costs(c);
1717 /* Update the current cost model to reflect the computed Huffman codes. */
1719 lzx_update_costs(struct lzx_compressor *c)
1722 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1724 for (i = 0; i < c->num_main_syms; i++) {
1725 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1726 MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1729 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1730 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1731 LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1734 #if LZX_CONSIDER_ALIGNED_COSTS
1735 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1736 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1737 ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1741 lzx_compute_match_costs(c);
1744 static inline struct lzx_lru_queue
1745 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1746 struct lzx_output_bitstream * const restrict os,
1747 const u8 * const restrict block_begin,
1748 const u32 block_size,
1749 const struct lzx_lru_queue initial_queue,
1752 unsigned num_passes_remaining = c->num_optim_passes;
1753 struct lzx_lru_queue new_queue;
1756 /* The first optimization pass uses a default cost model. Each
1757 * additional optimization pass uses a cost model derived from the
1758 * Huffman code computed in the previous pass. */
1760 lzx_set_default_costs(c, block_begin, block_size);
1761 lzx_reset_symbol_frequencies(c);
1763 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1764 initial_queue, is_16_bit);
1765 if (num_passes_remaining > 1) {
1766 lzx_tally_item_list(c, block_size, is_16_bit);
1767 lzx_make_huffman_codes(c);
1768 lzx_update_costs(c);
1769 lzx_reset_symbol_frequencies(c);
1771 } while (--num_passes_remaining);
1773 seq_idx = lzx_record_item_list(c, block_size, is_16_bit);
1774 lzx_finish_block(c, os, block_begin, block_size, seq_idx);
1779 * This is the "near-optimal" LZX compressor.
1781 * For each block, it performs a relatively thorough graph search to find an
1782 * inexpensive (in terms of compressed size) way to output that block.
1784 * Note: there are actually many things this algorithm leaves on the table in
1785 * terms of compression ratio. So although it may be "near-optimal", it is
1786 * certainly not "optimal". The goal is not to produce the optimal compression
1787 * ratio, which for LZX is probably impossible within any practical amount of
1788 * time, but rather to produce a compression ratio significantly better than a
1789 * simpler "greedy" or "lazy" parse while still being relatively fast.
1792 lzx_compress_near_optimal(struct lzx_compressor *c,
1793 struct lzx_output_bitstream *os,
1796 const u8 * const in_begin = c->in_buffer;
1797 const u8 * in_next = in_begin;
1798 const u8 * const in_end = in_begin + c->in_nbytes;
1799 u32 max_len = LZX_MAX_MATCH_LEN;
1800 u32 nice_len = min(c->nice_match_length, max_len);
1801 u32 next_hashes[2] = {};
1802 struct lzx_lru_queue queue;
1804 CALL_BT_MF(is_16_bit, c, bt_matchfinder_init);
1805 lzx_lru_queue_init(&queue);
1808 /* Starting a new block */
1809 const u8 * const in_block_begin = in_next;
1810 const u8 * const in_block_end =
1811 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1813 /* Run the block through the matchfinder and cache the matches. */
1814 struct lz_match *cache_ptr = c->match_cache;
1816 struct lz_match *lz_matchptr;
1819 /* If approaching the end of the input buffer, adjust
1820 * 'max_len' and 'nice_len' accordingly. */
1821 if (unlikely(max_len > in_end - in_next)) {
1822 max_len = in_end - in_next;
1823 nice_len = min(max_len, nice_len);
1824 if (unlikely(max_len < BT_MATCHFINDER_REQUIRED_NBYTES)) {
1826 cache_ptr->length = 0;
1832 /* Check for matches. */
1833 lz_matchptr = CALL_BT_MF(is_16_bit, c, bt_matchfinder_get_matches,
1838 c->max_search_depth,
1843 cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1844 cache_ptr = lz_matchptr;
1847 * If there was a very long match found, then don't
1848 * cache any matches for the bytes covered by that
1849 * match. This avoids degenerate behavior when
1850 * compressing highly redundant data, where the number
1851 * of matches can be very large.
1853 * This heuristic doesn't actually hurt the compression
1854 * ratio very much. If there's a long match, then the
1855 * data must be highly compressible, so it doesn't
1856 * matter as much what we do.
1858 if (best_len >= nice_len) {
1861 if (unlikely(max_len > in_end - in_next)) {
1862 max_len = in_end - in_next;
1863 nice_len = min(max_len, nice_len);
1864 if (unlikely(max_len < BT_MATCHFINDER_REQUIRED_NBYTES)) {
1866 cache_ptr->length = 0;
1871 CALL_BT_MF(is_16_bit, c, bt_matchfinder_skip_position,
1876 c->max_search_depth,
1879 cache_ptr->length = 0;
1881 } while (--best_len);
1883 } while (in_next < in_block_end &&
1884 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1886 /* We've finished running the block through the matchfinder.
1887 * Now choose a match/literal sequence and write the block. */
1889 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1890 in_next - in_block_begin,
1892 } while (in_next != in_end);
1896 lzx_compress_near_optimal_16(struct lzx_compressor *c,
1897 struct lzx_output_bitstream *os)
1899 lzx_compress_near_optimal(c, os, true);
1903 lzx_compress_near_optimal_32(struct lzx_compressor *c,
1904 struct lzx_output_bitstream *os)
1906 lzx_compress_near_optimal(c, os, false);
1910 * Given a pointer to the current byte sequence and the current list of recent
1911 * match offsets, find the longest repeat offset match.
1913 * If no match of at least 2 bytes is found, then return 0.
1915 * If a match of at least 2 bytes is found, then return its length and set
1916 * *rep_max_idx_ret to the index of its offset in @queue.
1919 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1920 const u32 bytes_remaining,
1921 const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
1922 unsigned *rep_max_idx_ret)
1924 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
1926 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1927 const u16 next_2_bytes = load_u16_unaligned(in_next);
1929 unsigned rep_max_len;
1930 unsigned rep_max_idx;
1933 matchptr = in_next - recent_offsets[0];
1934 if (load_u16_unaligned(matchptr) == next_2_bytes)
1935 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1940 matchptr = in_next - recent_offsets[1];
1941 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1942 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1943 if (rep_len > rep_max_len) {
1944 rep_max_len = rep_len;
1949 matchptr = in_next - recent_offsets[2];
1950 if (load_u16_unaligned(matchptr) == next_2_bytes) {
1951 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1952 if (rep_len > rep_max_len) {
1953 rep_max_len = rep_len;
1958 *rep_max_idx_ret = rep_max_idx;
1962 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
1963 static inline unsigned
1964 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1966 unsigned score = len;
1968 if (adjusted_offset < 4096)
1971 if (adjusted_offset < 256)
1977 static inline unsigned
1978 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1983 /* This is the "lazy" LZX compressor. */
1985 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1988 const u8 * const in_begin = c->in_buffer;
1989 const u8 * in_next = in_begin;
1990 const u8 * const in_end = in_begin + c->in_nbytes;
1991 unsigned max_len = LZX_MAX_MATCH_LEN;
1992 unsigned nice_len = min(c->nice_match_length, max_len);
1993 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
1994 u32 recent_offsets[3] = {1, 1, 1};
1995 u32 next_hashes[2] = {};
1997 CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2000 /* Starting a new block */
2002 const u8 * const in_block_begin = in_next;
2003 const u8 * const in_block_end =
2004 in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
2005 struct lzx_sequence *next_seq = c->chosen_sequences;
2008 u32 cur_offset_data;
2012 u32 next_offset_data;
2013 unsigned next_score;
2014 unsigned rep_max_len;
2015 unsigned rep_max_idx;
2020 lzx_reset_symbol_frequencies(c);
2023 if (unlikely(max_len > in_end - in_next)) {
2024 max_len = in_end - in_next;
2025 nice_len = min(max_len, nice_len);
2028 /* Find the longest match at the current position. */
2030 cur_len = CALL_HC_MF(is_16_bit, c, hc_matchfinder_longest_match,
2036 c->max_search_depth,
2041 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2042 cur_offset != recent_offsets[0] &&
2043 cur_offset != recent_offsets[1] &&
2044 cur_offset != recent_offsets[2]))
2046 /* There was no match found, or the only match found
2047 * was a distant length 3 match. Output a literal. */
2048 lzx_record_literal(c, *in_next++, &litrunlen);
2052 if (cur_offset == recent_offsets[0]) {
2054 cur_offset_data = 0;
2055 skip_len = cur_len - 1;
2056 goto choose_cur_match;
2059 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2060 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2062 /* Consider a repeat offset match */
2063 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2069 if (rep_max_len >= 3 &&
2070 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2071 rep_max_idx)) >= cur_score)
2073 cur_len = rep_max_len;
2074 cur_offset_data = rep_max_idx;
2075 skip_len = rep_max_len - 1;
2076 goto choose_cur_match;
2081 /* We have a match at the current position. */
2083 /* If we have a very long match, choose it immediately. */
2084 if (cur_len >= nice_len) {
2085 skip_len = cur_len - 1;
2086 goto choose_cur_match;
2089 /* See if there's a better match at the next position. */
2091 if (unlikely(max_len > in_end - in_next)) {
2092 max_len = in_end - in_next;
2093 nice_len = min(max_len, nice_len);
2096 next_len = CALL_HC_MF(is_16_bit, c, hc_matchfinder_longest_match,
2102 c->max_search_depth / 2,
2106 if (next_len <= cur_len - 2) {
2108 skip_len = cur_len - 2;
2109 goto choose_cur_match;
2112 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2113 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2115 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2121 if (rep_max_len >= 3 &&
2122 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2123 rep_max_idx)) >= next_score)
2126 if (rep_score > cur_score) {
2127 /* The next match is better, and it's a
2128 * repeat offset match. */
2129 lzx_record_literal(c, *(in_next - 2),
2131 cur_len = rep_max_len;
2132 cur_offset_data = rep_max_idx;
2133 skip_len = cur_len - 1;
2134 goto choose_cur_match;
2137 if (next_score > cur_score) {
2138 /* The next match is better, and it's an
2139 * explicit offset match. */
2140 lzx_record_literal(c, *(in_next - 2),
2143 cur_offset_data = next_offset_data;
2144 cur_score = next_score;
2145 goto have_cur_match;
2149 /* The original match was better. */
2150 skip_len = cur_len - 2;
2153 lzx_record_match(c, cur_len, cur_offset_data,
2154 recent_offsets, is_16_bit,
2155 &litrunlen, &next_seq);
2156 in_next = CALL_HC_MF(is_16_bit, c, hc_matchfinder_skip_positions,
2162 } while (in_next < in_block_end);
2164 lzx_finish_sequence(next_seq, litrunlen);
2166 lzx_finish_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2168 } while (in_next != in_end);
2172 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2174 lzx_compress_lazy(c, os, true);
2178 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2180 lzx_compress_lazy(c, os, false);
2183 /* Generate the acceleration tables for offset slots. */
2185 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2187 u32 adjusted_offset = 0;
2191 for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2194 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2196 c->offset_slot_tab_1[adjusted_offset] = slot;
2199 /* slots [30, 49] */
2200 for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2201 adjusted_offset += (u32)1 << 14)
2203 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2205 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2210 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2212 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2213 if (lzx_is_16_bit(max_bufsize))
2214 return offsetof(struct lzx_compressor, hc_mf_16) +
2215 hc_matchfinder_size_16(max_bufsize);
2217 return offsetof(struct lzx_compressor, hc_mf_32) +
2218 hc_matchfinder_size_32(max_bufsize);
2220 if (lzx_is_16_bit(max_bufsize))
2221 return offsetof(struct lzx_compressor, bt_mf_16) +
2222 bt_matchfinder_size_16(max_bufsize);
2224 return offsetof(struct lzx_compressor, bt_mf_32) +
2225 bt_matchfinder_size_32(max_bufsize);
2230 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2235 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2238 size += lzx_get_compressor_size(max_bufsize, compression_level);
2240 size += max_bufsize; /* in_buffer */
2245 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2246 bool destructive, void **c_ret)
2248 unsigned window_order;
2249 struct lzx_compressor *c;
2251 window_order = lzx_get_window_order(max_bufsize);
2252 if (window_order == 0)
2253 return WIMLIB_ERR_INVALID_PARAM;
2255 c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2259 c->destructive = destructive;
2261 c->num_main_syms = lzx_get_num_main_syms(window_order);
2262 c->window_order = window_order;
2264 if (!c->destructive) {
2265 c->in_buffer = MALLOC(max_bufsize);
2270 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2272 /* Fast compression: Use lazy parsing. */
2274 if (lzx_is_16_bit(max_bufsize))
2275 c->impl = lzx_compress_lazy_16;
2277 c->impl = lzx_compress_lazy_32;
2278 c->max_search_depth = (60 * compression_level) / 20;
2279 c->nice_match_length = (80 * compression_level) / 20;
2281 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2282 * halves the max_search_depth when attempting a lazy match, and
2283 * max_search_depth cannot be 0. */
2284 if (c->max_search_depth < 2)
2285 c->max_search_depth = 2;
2288 /* Normal / high compression: Use near-optimal parsing. */
2290 if (lzx_is_16_bit(max_bufsize))
2291 c->impl = lzx_compress_near_optimal_16;
2293 c->impl = lzx_compress_near_optimal_32;
2295 /* Scale nice_match_length and max_search_depth with the
2296 * compression level. */
2297 c->max_search_depth = (24 * compression_level) / 50;
2298 c->nice_match_length = (48 * compression_level) / 50;
2300 /* Set a number of optimization passes appropriate for the
2301 * compression level. */
2303 c->num_optim_passes = 1;
2305 if (compression_level >= 45)
2306 c->num_optim_passes++;
2308 /* Use more optimization passes for higher compression levels.
2309 * But the more passes there are, the less they help --- so
2310 * don't add them linearly. */
2311 if (compression_level >= 70) {
2312 c->num_optim_passes++;
2313 if (compression_level >= 100)
2314 c->num_optim_passes++;
2315 if (compression_level >= 150)
2316 c->num_optim_passes++;
2317 if (compression_level >= 200)
2318 c->num_optim_passes++;
2319 if (compression_level >= 300)
2320 c->num_optim_passes++;
2324 /* max_search_depth == 0 is invalid. */
2325 if (c->max_search_depth < 1)
2326 c->max_search_depth = 1;
2328 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2329 c->nice_match_length = LZX_MAX_MATCH_LEN;
2331 lzx_init_offset_slot_tabs(c);
2338 return WIMLIB_ERR_NOMEM;
2342 lzx_compress(const void *restrict in, size_t in_nbytes,
2343 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2345 struct lzx_compressor *c = _c;
2346 struct lzx_output_bitstream os;
2349 /* Don't bother trying to compress very small inputs. */
2350 if (in_nbytes < 100)
2353 /* Copy the input data into the internal buffer and preprocess it. */
2355 c->in_buffer = (void *)in;
2357 memcpy(c->in_buffer, in, in_nbytes);
2358 c->in_nbytes = in_nbytes;
2359 lzx_preprocess(c->in_buffer, in_nbytes);
2361 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2363 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2365 /* Initialize the output bitstream. */
2366 lzx_init_output(&os, out, out_nbytes_avail);
2368 /* Call the compression level-specific compress() function. */
2371 /* Flush the output bitstream and return the compressed size or 0. */
2372 result = lzx_flush_output(&os);
2373 if (!result && c->destructive)
2374 lzx_postprocess(c->in_buffer, c->in_nbytes);
2379 lzx_free_compressor(void *_c)
2381 struct lzx_compressor *c = _c;
2383 if (!c->destructive)
2388 const struct compressor_ops lzx_compressor_ops = {
2389 .get_needed_memory = lzx_get_needed_memory,
2390 .create_compressor = lzx_create_compressor,
2391 .compress = lzx_compress,
2392 .free_compressor = lzx_free_compressor,