4 * A compressor for the LZX compression format, as used in WIM files.
8 * Copyright (C) 2012-2016 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 * The compressor always chooses a block of at least MIN_BLOCK_SIZE bytes,
69 * except if the last block has to be shorter.
71 #define MIN_BLOCK_SIZE 6500
74 * The compressor attempts to end blocks after SOFT_MAX_BLOCK_SIZE bytes, but
75 * the final size might be larger due to matches extending beyond the end of the
76 * block. Specifically:
78 * - The greedy parser may choose an arbitrarily long match starting at the
79 * SOFT_MAX_BLOCK_SIZE'th byte.
81 * - The lazy parser may choose a sequence of literals starting at the
82 * SOFT_MAX_BLOCK_SIZE'th byte when it sees a sequence of increasing good
83 * matches. The final match may be of arbitrary length. The length of the
84 * literal sequence is approximately limited by the "nice match length"
87 #define SOFT_MAX_BLOCK_SIZE 100000
90 * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
91 * excluding the extra "overflow" entries. This value should be high enough so
92 * that nearly the time, all matches found in a given block can fit in the match
93 * cache. However, fallback behavior (immediately terminating the block) on
94 * cache overflow is still required.
96 #define LZX_CACHE_LENGTH (SOFT_MAX_BLOCK_SIZE * 5)
99 * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
100 * ever be saved in the match cache for a single position. Since each match we
101 * save for a single position has a distinct length, we can use the number of
102 * possible match lengths in LZX as this bound. This bound is guaranteed to be
103 * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
104 * it will never actually be reached.
106 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
109 * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
110 * This makes it possible to consider fractional bit costs.
112 * Note: this is only useful as a statistical trick for when the true costs are
113 * unknown. In reality, each token in LZX requires a whole number of bits to
116 #define LZX_BIT_COST 16
119 * Should the compressor take into account the costs of aligned offset symbols?
121 #define LZX_CONSIDER_ALIGNED_COSTS 1
124 * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
127 #define LZX_MAX_FAST_LEVEL 34
130 * BT_MATCHFINDER_HASH2_ORDER is the log base 2 of the number of entries in the
131 * hash table for finding length 2 matches. This could be as high as 16, but
132 * using a smaller hash table speeds up compression due to reduced cache
135 #define BT_MATCHFINDER_HASH2_ORDER 12
138 * These are the compressor-side limits on the codeword lengths for each Huffman
139 * code. To make outputting bits slightly faster, some of these limits are
140 * lower than the limits defined by the LZX format. This does not significantly
141 * affect the compression ratio, at least for the block sizes we use.
143 #define MAIN_CODEWORD_LIMIT 16
144 #define LENGTH_CODEWORD_LIMIT 12
145 #define ALIGNED_CODEWORD_LIMIT 7
146 #define PRE_CODEWORD_LIMIT 7
148 #include "wimlib/compress_common.h"
149 #include "wimlib/compressor_ops.h"
150 #include "wimlib/error.h"
151 #include "wimlib/lz_extend.h"
152 #include "wimlib/lzx_common.h"
153 #include "wimlib/unaligned.h"
154 #include "wimlib/util.h"
156 /* Matchfinders with 16-bit positions */
158 #define MF_SUFFIX _16
159 #include "wimlib/bt_matchfinder.h"
160 #include "wimlib/hc_matchfinder.h"
162 /* Matchfinders with 32-bit positions */
166 #define MF_SUFFIX _32
167 #include "wimlib/bt_matchfinder.h"
168 #include "wimlib/hc_matchfinder.h"
170 struct lzx_output_bitstream;
172 /* Codewords for the LZX Huffman codes. */
173 struct lzx_codewords {
174 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
175 u32 len[LZX_LENCODE_NUM_SYMBOLS];
176 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
179 /* Codeword lengths (in bits) for the LZX Huffman codes.
180 * A zero length means the corresponding codeword has zero frequency. */
182 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS + 1];
183 u8 len[LZX_LENCODE_NUM_SYMBOLS + 1];
184 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
187 /* Cost model for near-optimal parsing */
190 /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
191 * length 'len' match that has an offset belonging to 'offset_slot'. */
192 u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
194 /* Cost for each symbol in the main code */
195 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
197 /* Cost for each symbol in the length code */
198 u32 len[LZX_LENCODE_NUM_SYMBOLS];
200 #if LZX_CONSIDER_ALIGNED_COSTS
201 /* Cost for each symbol in the aligned code */
202 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
206 /* Codewords and lengths for the LZX Huffman codes. */
208 struct lzx_codewords codewords;
209 struct lzx_lens lens;
212 /* Symbol frequency counters for the LZX Huffman codes. */
214 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
215 u32 len[LZX_LENCODE_NUM_SYMBOLS];
216 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
219 /* Block split statistics. See "Block splitting algorithm" below. */
220 #define NUM_LITERAL_OBSERVATION_TYPES 8
221 #define NUM_MATCH_OBSERVATION_TYPES 2
222 #define NUM_OBSERVATION_TYPES (NUM_LITERAL_OBSERVATION_TYPES + NUM_MATCH_OBSERVATION_TYPES)
223 struct block_split_stats {
224 u32 new_observations[NUM_OBSERVATION_TYPES];
225 u32 observations[NUM_OBSERVATION_TYPES];
226 u32 num_new_observations;
227 u32 num_observations;
231 * Represents a run of literals followed by a match or end-of-block. This
232 * struct is needed to temporarily store items chosen by the parser, since items
233 * cannot be written until all items for the block have been chosen and the
234 * block's Huffman codes have been computed.
236 struct lzx_sequence {
238 /* The number of literals in the run. This may be 0. The literals are
239 * not stored explicitly in this structure; instead, they are read
240 * directly from the uncompressed data. */
243 /* If the next field doesn't indicate end-of-block, then this is the
244 * match length minus LZX_MIN_MATCH_LEN. */
247 /* If bit 31 is clear, then this field contains the match header in bits
248 * 0-8, and either the match offset plus LZX_OFFSET_ADJUSTMENT or a
249 * recent offset code in bits 9-30. Otherwise (if bit 31 is set), this
250 * sequence's literal run was the last literal run in the block, so
251 * there is no match that follows it. */
252 u32 adjusted_offset_and_match_hdr;
256 * This structure represents a byte position in the input buffer and a node in
257 * the graph of possible match/literal choices.
259 * Logically, each incoming edge to this node is labeled with a literal or a
260 * match that can be taken to reach this position from an earlier position; and
261 * each outgoing edge from this node is labeled with a literal or a match that
262 * can be taken to advance from this position to a later position.
264 struct lzx_optimum_node {
266 /* The cost, in bits, of the lowest-cost path that has been found to
267 * reach this position. This can change as progressively lower cost
268 * paths are found to reach this position. */
272 * The match or literal that was taken to reach this position. This can
273 * change as progressively lower cost paths are found to reach this
276 * This variable is divided into two bitfields.
279 * Low bits are 0, high bits are the literal.
281 * Explicit offset matches:
282 * Low bits are the match length, high bits are the offset plus 2.
284 * Repeat offset matches:
285 * Low bits are the match length, high bits are the queue index.
288 #define OPTIMUM_OFFSET_SHIFT 9
289 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
290 } _aligned_attribute(8);
293 * Least-recently-used queue for match offsets.
295 * This is represented as a 64-bit integer for efficiency. There are three
296 * offsets of 21 bits each. Bit 64 is garbage.
298 struct lzx_lru_queue {
302 #define LZX_QUEUE64_OFFSET_SHIFT 21
303 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
305 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
306 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
307 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
309 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
310 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
311 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
314 lzx_lru_queue_init(struct lzx_lru_queue *queue)
316 queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
317 ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
318 ((u64)1 << LZX_QUEUE64_R2_SHIFT);
322 lzx_lru_queue_R0(struct lzx_lru_queue queue)
324 return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
328 lzx_lru_queue_R1(struct lzx_lru_queue queue)
330 return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
334 lzx_lru_queue_R2(struct lzx_lru_queue queue)
336 return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
339 /* Push a match offset onto the front (most recently used) end of the queue. */
340 static inline struct lzx_lru_queue
341 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
343 return (struct lzx_lru_queue) {
344 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
348 /* Swap a match offset to the front of the queue. */
349 static inline struct lzx_lru_queue
350 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
356 return (struct lzx_lru_queue) {
357 .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
358 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
359 (queue.R & LZX_QUEUE64_R2_MASK),
362 return (struct lzx_lru_queue) {
363 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
364 (queue.R & LZX_QUEUE64_R1_MASK) |
365 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
369 /* The main LZX compressor structure */
370 struct lzx_compressor {
372 /* The "nice" match length: if a match of this length is found, then
373 * choose it immediately without further consideration. */
374 unsigned nice_match_length;
376 /* The maximum search depth: consider at most this many potential
377 * matches at each position. */
378 unsigned max_search_depth;
380 /* The log base 2 of the LZX window size for LZ match offset encoding
381 * purposes. This will be >= LZX_MIN_WINDOW_ORDER and <=
382 * LZX_MAX_WINDOW_ORDER. */
383 unsigned window_order;
385 /* The number of symbols in the main alphabet. This depends on
386 * @window_order, since @window_order determines the maximum possible
388 unsigned num_main_syms;
390 /* Number of optimization passes per block */
391 unsigned num_optim_passes;
393 /* The preprocessed buffer of data being compressed */
396 /* The number of bytes of data to be compressed, which is the number of
397 * bytes of data in @in_buffer that are actually valid. */
400 /* Pointer to the compress() implementation chosen at allocation time */
401 void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
403 /* If true, the compressor need not preserve the input buffer if it
404 * compresses the data successfully. */
407 /* The Huffman symbol frequency counters for the current block. */
408 struct lzx_freqs freqs;
410 /* Block split statistics. */
411 struct block_split_stats split_stats;
413 /* The Huffman codes for the current and previous blocks. The one with
414 * index 'codes_index' is for the current block, and the other one is
415 * for the previous block. */
416 struct lzx_codes codes[2];
417 unsigned codes_index;
419 /* The matches and literals that the parser has chosen for the current
420 * block. The required length of this array is limited by the maximum
421 * number of matches that can ever be chosen for a single block, plus
422 * one for the special entry at the end. */
423 struct lzx_sequence chosen_sequences[
424 DIV_ROUND_UP(SOFT_MAX_BLOCK_SIZE, LZX_MIN_MATCH_LEN) + 1];
426 /* Tables for mapping adjusted offsets to offset slots */
428 /* offset slots [0, 29] */
429 u8 offset_slot_tab_1[32768];
431 /* offset slots [30, 49] */
432 u8 offset_slot_tab_2[128];
435 /* Data for greedy or lazy parsing */
437 /* Hash chains matchfinder (MUST BE LAST!!!) */
439 struct hc_matchfinder_16 hc_mf_16;
440 struct hc_matchfinder_32 hc_mf_32;
444 /* Data for near-optimal parsing */
447 * Array of nodes, one per position, for running the
448 * minimum-cost path algorithm.
450 * This array must be large enough to accommodate the
451 * worst-case number of nodes, which occurs if we find a
452 * match of length LZX_MAX_MATCH_LEN at position
453 * SOFT_MAX_BLOCK_SIZE - 1, producing a block of length
454 * SOFT_MAX_BLOCK_SIZE - 1 + LZX_MAX_MATCH_LEN. Add one
455 * for the end-of-block node.
457 struct lzx_optimum_node optimum_nodes[SOFT_MAX_BLOCK_SIZE - 1 +
458 LZX_MAX_MATCH_LEN + 1];
460 /* The cost model for the current block */
461 struct lzx_costs costs;
464 * Cached matches for the current block. This array
465 * contains the matches that were found at each position
466 * in the block. Specifically, for each position, there
467 * is a special 'struct lz_match' whose 'length' field
468 * contains the number of matches that were found at
469 * that position; this is followed by the matches
470 * themselves, if any, sorted by strictly increasing
473 * Note: in rare cases, there will be a very high number
474 * of matches in the block and this array will overflow.
475 * If this happens, we force the end of the current
476 * block. LZX_CACHE_LENGTH is the length at which we
477 * actually check for overflow. The extra slots beyond
478 * this are enough to absorb the worst case overflow,
479 * which occurs if starting at
480 * &match_cache[LZX_CACHE_LENGTH - 1], we write the
481 * match count header, then write
482 * LZX_MAX_MATCHES_PER_POS matches, then skip searching
483 * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
484 * write the match count header for each.
486 struct lz_match match_cache[LZX_CACHE_LENGTH +
487 LZX_MAX_MATCHES_PER_POS +
488 LZX_MAX_MATCH_LEN - 1];
490 /* Binary trees matchfinder (MUST BE LAST!!!) */
492 struct bt_matchfinder_16 bt_mf_16;
493 struct bt_matchfinder_32 bt_mf_32;
500 * Will a matchfinder using 16-bit positions be sufficient for compressing
501 * buffers of up to the specified size? The limit could be 65536 bytes, but we
502 * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
503 * This requires that the limit be no more than the length of offset_slot_tab_1
507 lzx_is_16_bit(size_t max_bufsize)
509 STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
510 return max_bufsize <= 32768;
514 * The following macros call either the 16-bit or the 32-bit version of a
515 * matchfinder function based on the value of 'is_16_bit', which will be known
516 * at compilation time.
519 #define CALL_HC_MF(is_16_bit, c, funcname, ...) \
520 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
521 CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
523 #define CALL_BT_MF(is_16_bit, c, funcname, ...) \
524 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->bt_mf_16, ##__VA_ARGS__) : \
525 CONCAT(funcname, _32)(&(c)->bt_mf_32, ##__VA_ARGS__));
528 * Structure to keep track of the current state of sending bits to the
529 * compressed output buffer.
531 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
533 struct lzx_output_bitstream {
535 /* Bits that haven't yet been written to the output buffer. */
536 machine_word_t bitbuf;
538 /* Number of bits currently held in @bitbuf. */
541 /* Pointer to the start of the output buffer. */
544 /* Pointer to the position in the output buffer at which the next coding
545 * unit should be written. */
548 /* Pointer just past the end of the output buffer, rounded down to a
549 * 2-byte boundary. */
553 /* Can the specified number of bits always be added to 'bitbuf' after any
554 * pending 16-bit coding units have been flushed? */
555 #define CAN_BUFFER(n) ((n) <= (8 * sizeof(machine_word_t)) - 15)
558 * Initialize the output bitstream.
561 * The output bitstream structure to initialize.
563 * The buffer being written to.
565 * Size of @buffer, in bytes.
568 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
573 os->next = os->start;
574 os->end = os->start + (size & ~1);
577 /* Add some bits to the bitbuffer variable of the output bitstream. The caller
578 * must make sure there is enough room. */
580 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
582 os->bitbuf = (os->bitbuf << num_bits) | bits;
583 os->bitcount += num_bits;
586 /* Flush bits from the bitbuffer variable to the output buffer. 'max_num_bits'
587 * specifies the maximum number of bits that may have been added since the last
590 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
592 /* Masking the number of bits to shift is only needed to avoid undefined
593 * behavior; we don't actually care about the results of bad shifts. On
594 * x86, the explicit masking generates no extra code. */
595 const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
597 if (os->end - os->next < 6)
599 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 16) &
600 shift_mask), os->next + 0);
601 if (max_num_bits > 16)
602 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 32) &
603 shift_mask), os->next + 2);
604 if (max_num_bits > 32)
605 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 48) &
606 shift_mask), os->next + 4);
607 os->next += (os->bitcount >> 4) << 1;
611 /* Add at most 16 bits to the bitbuffer and flush it. */
613 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
615 lzx_add_bits(os, bits, num_bits);
616 lzx_flush_bits(os, 16);
620 * Flush the last coding unit to the output buffer if needed. Return the total
621 * number of bytes written to the output buffer, or 0 if an overflow occurred.
624 lzx_flush_output(struct lzx_output_bitstream *os)
626 if (os->end - os->next < 6)
629 if (os->bitcount != 0) {
630 put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
634 return os->next - os->start;
637 /* Build the main, length, and aligned offset Huffman codes used in LZX.
639 * This takes as input the frequency tables for each code and produces as output
640 * a set of tables that map symbols to codewords and codeword lengths. */
642 lzx_make_huffman_codes(struct lzx_compressor *c)
644 const struct lzx_freqs *freqs = &c->freqs;
645 struct lzx_codes *codes = &c->codes[c->codes_index];
647 STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
648 MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
649 STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
650 LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
651 STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
652 ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
654 make_canonical_huffman_code(c->num_main_syms,
658 codes->codewords.main);
660 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
661 LENGTH_CODEWORD_LIMIT,
664 codes->codewords.len);
666 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
667 ALIGNED_CODEWORD_LIMIT,
670 codes->codewords.aligned);
673 /* Reset the symbol frequencies for the LZX Huffman codes. */
675 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
677 memset(&c->freqs, 0, sizeof(c->freqs));
681 lzx_compute_precode_items(const u8 lens[restrict],
682 const u8 prev_lens[restrict],
683 u32 precode_freqs[restrict],
684 unsigned precode_items[restrict])
693 itemptr = precode_items;
696 while (!((len = lens[run_start]) & 0x80)) {
698 /* len = the length being repeated */
700 /* Find the next run of codeword lengths. */
702 run_end = run_start + 1;
704 /* Fast case for a single length. */
705 if (likely(len != lens[run_end])) {
706 delta = prev_lens[run_start] - len;
709 precode_freqs[delta]++;
715 /* Extend the run. */
718 } while (len == lens[run_end]);
723 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
724 while ((run_end - run_start) >= 20) {
725 extra_bits = min((run_end - run_start) - 20, 0x1f);
727 *itemptr++ = 18 | (extra_bits << 5);
728 run_start += 20 + extra_bits;
731 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
732 if ((run_end - run_start) >= 4) {
733 extra_bits = min((run_end - run_start) - 4, 0xf);
735 *itemptr++ = 17 | (extra_bits << 5);
736 run_start += 4 + extra_bits;
740 /* A run of nonzero lengths. */
742 /* Symbol 19: RLE 4 to 5 of any length at a time. */
743 while ((run_end - run_start) >= 4) {
744 extra_bits = (run_end - run_start) > 4;
745 delta = prev_lens[run_start] - len;
749 precode_freqs[delta]++;
750 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
751 run_start += 4 + extra_bits;
755 /* Output any remaining lengths without RLE. */
756 while (run_start != run_end) {
757 delta = prev_lens[run_start] - len;
760 precode_freqs[delta]++;
766 return itemptr - precode_items;
770 * Output a Huffman code in the compressed form used in LZX.
772 * The Huffman code is represented in the output as a logical series of codeword
773 * lengths from which the Huffman code, which must be in canonical form, can be
776 * The codeword lengths are themselves compressed using a separate Huffman code,
777 * the "precode", which contains a symbol for each possible codeword length in
778 * the larger code as well as several special symbols to represent repeated
779 * codeword lengths (a form of run-length encoding). The precode is itself
780 * constructed in canonical form, and its codeword lengths are represented
781 * literally in 20 4-bit fields that immediately precede the compressed codeword
782 * lengths of the larger code.
784 * Furthermore, the codeword lengths of the larger code are actually represented
785 * as deltas from the codeword lengths of the corresponding code in the previous
789 * Bitstream to which to write the compressed Huffman code.
791 * The codeword lengths, indexed by symbol, in the Huffman code.
793 * The codeword lengths, indexed by symbol, in the corresponding Huffman
794 * code in the previous block, or all zeroes if this is the first block.
796 * The number of symbols in the Huffman code.
799 lzx_write_compressed_code(struct lzx_output_bitstream *os,
800 const u8 lens[restrict],
801 const u8 prev_lens[restrict],
804 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
805 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
806 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
807 unsigned precode_items[num_lens];
808 unsigned num_precode_items;
809 unsigned precode_item;
810 unsigned precode_sym;
812 u8 saved = lens[num_lens];
813 *(u8 *)(lens + num_lens) = 0x80;
815 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
816 precode_freqs[i] = 0;
818 /* Compute the "items" (RLE / literal tokens and extra bits) with which
819 * the codeword lengths in the larger code will be output. */
820 num_precode_items = lzx_compute_precode_items(lens,
825 /* Build the precode. */
826 STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
827 PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
828 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
830 precode_freqs, precode_lens,
833 /* Output the lengths of the codewords in the precode. */
834 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
835 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
837 /* Output the encoded lengths of the codewords in the larger code. */
838 for (i = 0; i < num_precode_items; i++) {
839 precode_item = precode_items[i];
840 precode_sym = precode_item & 0x1F;
841 lzx_add_bits(os, precode_codewords[precode_sym],
842 precode_lens[precode_sym]);
843 if (precode_sym >= 17) {
844 if (precode_sym == 17) {
845 lzx_add_bits(os, precode_item >> 5, 4);
846 } else if (precode_sym == 18) {
847 lzx_add_bits(os, precode_item >> 5, 5);
849 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
850 precode_sym = precode_item >> 6;
851 lzx_add_bits(os, precode_codewords[precode_sym],
852 precode_lens[precode_sym]);
855 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
856 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
859 *(u8 *)(lens + num_lens) = saved;
863 * Write all matches and literal bytes (which were precomputed) in an LZX
864 * compressed block to the output bitstream in the final compressed
868 * The output bitstream.
870 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
871 * LZX_BLOCKTYPE_VERBATIM).
873 * The uncompressed data of the block.
875 * The matches and literals to output, given as a series of sequences.
877 * The main, length, and aligned offset Huffman codes for the current
878 * LZX compressed block.
881 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
882 const u8 *block_data, const struct lzx_sequence sequences[],
883 const struct lzx_codes *codes)
885 const struct lzx_sequence *seq = sequences;
886 u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
889 /* Output the next sequence. */
891 unsigned litrunlen = seq->litrunlen;
893 unsigned main_symbol;
894 unsigned adjusted_length;
896 unsigned offset_slot;
897 unsigned num_extra_bits;
900 /* Output the literal run of the sequence. */
902 if (litrunlen) { /* Is the literal run nonempty? */
904 /* Verify optimization is enabled on 64-bit */
905 STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
906 CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT));
908 if (CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT)) {
910 /* 64-bit: write 3 literals at a time. */
911 while (litrunlen >= 3) {
912 unsigned lit0 = block_data[0];
913 unsigned lit1 = block_data[1];
914 unsigned lit2 = block_data[2];
915 lzx_add_bits(os, codes->codewords.main[lit0],
916 codes->lens.main[lit0]);
917 lzx_add_bits(os, codes->codewords.main[lit1],
918 codes->lens.main[lit1]);
919 lzx_add_bits(os, codes->codewords.main[lit2],
920 codes->lens.main[lit2]);
921 lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
926 unsigned lit = *block_data++;
927 lzx_add_bits(os, codes->codewords.main[lit],
928 codes->lens.main[lit]);
930 unsigned lit = *block_data++;
931 lzx_add_bits(os, codes->codewords.main[lit],
932 codes->lens.main[lit]);
933 lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
935 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
939 /* 32-bit: write 1 literal at a time. */
941 unsigned lit = *block_data++;
942 lzx_add_bits(os, codes->codewords.main[lit],
943 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 -
984 LZX_NUM_PRIMARY_LENS],
985 codes->lens.len[adjusted_length -
986 LZX_NUM_PRIMARY_LENS]);
987 if (!CAN_BUFFER(MAX_MATCH_BITS))
988 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
991 /* Output the extra offset bits for the match. In aligned
992 * offset blocks, the lowest 3 bits of the adjusted offset are
993 * Huffman-encoded using the aligned offset code, provided that
994 * there are at least extra 3 offset bits required. All other
995 * extra offset bits are output verbatim. */
997 if ((adjusted_offset & ones_if_aligned) >= 16) {
999 lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
1000 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
1001 if (!CAN_BUFFER(MAX_MATCH_BITS))
1002 lzx_flush_bits(os, 14);
1004 lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
1005 LZX_ALIGNED_OFFSET_BITMASK],
1006 codes->lens.aligned[adjusted_offset &
1007 LZX_ALIGNED_OFFSET_BITMASK]);
1008 if (!CAN_BUFFER(MAX_MATCH_BITS))
1009 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1011 STATIC_ASSERT(CAN_BUFFER(17));
1013 lzx_add_bits(os, extra_bits, num_extra_bits);
1014 if (!CAN_BUFFER(MAX_MATCH_BITS))
1015 lzx_flush_bits(os, 17);
1018 if (CAN_BUFFER(MAX_MATCH_BITS))
1019 lzx_flush_bits(os, MAX_MATCH_BITS);
1021 /* Advance to the next sequence. */
1027 lzx_write_compressed_block(const u8 *block_begin,
1030 unsigned window_order,
1031 unsigned num_main_syms,
1032 const struct lzx_sequence sequences[],
1033 const struct lzx_codes * codes,
1034 const struct lzx_lens * prev_lens,
1035 struct lzx_output_bitstream * os)
1037 /* The first three bits indicate the type of block and are one of the
1038 * LZX_BLOCKTYPE_* constants. */
1039 lzx_write_bits(os, block_type, 3);
1041 /* Output the block size.
1043 * The original LZX format seemed to always encode the block size in 3
1044 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
1045 * uses the first bit to indicate whether the block is the default size
1046 * (32768) or a different size given explicitly by the next 16 bits.
1048 * By default, this compressor uses a window size of 32768 and therefore
1049 * follows the WIMGAPI behavior. However, this compressor also supports
1050 * window sizes greater than 32768 bytes, which do not appear to be
1051 * supported by WIMGAPI. In such cases, we retain the default size bit
1052 * to mean a size of 32768 bytes but output non-default block size in 24
1053 * bits rather than 16. The compatibility of this behavior is unknown
1054 * because WIMs created with chunk size greater than 32768 can seemingly
1055 * only be opened by wimlib anyway. */
1056 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1057 lzx_write_bits(os, 1, 1);
1059 lzx_write_bits(os, 0, 1);
1061 if (window_order >= 16)
1062 lzx_write_bits(os, block_size >> 16, 8);
1064 lzx_write_bits(os, block_size & 0xFFFF, 16);
1067 /* If it's an aligned offset block, output the aligned offset code. */
1068 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1069 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1070 lzx_write_bits(os, codes->lens.aligned[i],
1071 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1075 /* Output the main code (two parts). */
1076 lzx_write_compressed_code(os, codes->lens.main,
1079 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1080 prev_lens->main + LZX_NUM_CHARS,
1081 num_main_syms - LZX_NUM_CHARS);
1083 /* Output the length code. */
1084 lzx_write_compressed_code(os, codes->lens.len,
1086 LZX_LENCODE_NUM_SYMBOLS);
1088 /* Output the compressed matches and literals. */
1089 lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1092 /* Given the frequencies of symbols in an LZX-compressed block and the
1093 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1094 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1095 * will take fewer bits to output. */
1097 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1098 const struct lzx_codes * codes)
1100 u32 aligned_cost = 0;
1101 u32 verbatim_cost = 0;
1103 /* A verbatim block requires 3 bits in each place that an aligned symbol
1104 * would be used in an aligned offset block. */
1105 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1106 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1107 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1110 /* Account for output of the aligned offset code. */
1111 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1113 if (aligned_cost < verbatim_cost)
1114 return LZX_BLOCKTYPE_ALIGNED;
1116 return LZX_BLOCKTYPE_VERBATIM;
1120 * Return the offset slot for the specified adjusted match offset, using the
1121 * compressor's acceleration tables to speed up the mapping.
1123 static inline unsigned
1124 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1127 if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1128 return c->offset_slot_tab_1[adjusted_offset];
1129 return c->offset_slot_tab_2[adjusted_offset >> 14];
1133 * Finish an LZX block:
1135 * - build the Huffman codes
1136 * - decide whether to output the block as VERBATIM or ALIGNED
1137 * - output the block
1138 * - swap the indices of the current and previous Huffman codes
1141 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1142 const u8 *block_begin, u32 block_size, u32 seq_idx)
1146 lzx_make_huffman_codes(c);
1148 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1149 &c->codes[c->codes_index]);
1150 lzx_write_compressed_block(block_begin,
1155 &c->chosen_sequences[seq_idx],
1156 &c->codes[c->codes_index],
1157 &c->codes[c->codes_index ^ 1].lens,
1159 c->codes_index ^= 1;
1162 /* Tally the Huffman symbol for a literal and increment the literal run length.
1165 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1167 c->freqs.main[literal]++;
1171 /* Tally the Huffman symbol for a match, save the match data and the length of
1172 * the preceding literal run in the next lzx_sequence, and update the recent
1175 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1176 u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1177 u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1179 u32 litrunlen = *litrunlen_p;
1180 struct lzx_sequence *next_seq = *next_seq_p;
1181 unsigned offset_slot;
1184 v = length - LZX_MIN_MATCH_LEN;
1186 /* Save the literal run length and adjusted length. */
1187 next_seq->litrunlen = litrunlen;
1188 next_seq->adjusted_length = v;
1190 /* Compute the length header and tally the length symbol if needed */
1191 if (v >= LZX_NUM_PRIMARY_LENS) {
1192 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1193 v = LZX_NUM_PRIMARY_LENS;
1196 /* Compute the offset slot */
1197 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1199 /* Compute the match header. */
1200 v += offset_slot * LZX_NUM_LEN_HEADERS;
1202 /* Save the adjusted offset and match header. */
1203 next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1205 /* Tally the main symbol. */
1206 c->freqs.main[LZX_NUM_CHARS + v]++;
1208 /* Update the recent offsets queue. */
1209 if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1210 /* Repeat offset match */
1211 swap(recent_offsets[0], recent_offsets[offset_data]);
1213 /* Explicit offset match */
1215 /* Tally the aligned offset symbol if needed */
1216 if (offset_data >= 16)
1217 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1219 recent_offsets[2] = recent_offsets[1];
1220 recent_offsets[1] = recent_offsets[0];
1221 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1224 /* Reset the literal run length and advance to the next sequence. */
1225 *next_seq_p = next_seq + 1;
1229 /* Finish the last lzx_sequence. The last lzx_sequence is just a literal run;
1230 * there is no match. This literal run may be empty. */
1232 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1234 last_seq->litrunlen = litrunlen;
1236 /* Special value to mark last sequence */
1237 last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1240 /******************************************************************************/
1243 * Block splitting algorithm. The problem is to decide when it is worthwhile to
1244 * start a new block with new entropy codes. There is a theoretically optimal
1245 * solution: recursively consider every possible block split, considering the
1246 * exact cost of each block, and choose the minimum cost approach. But this is
1247 * far too slow. Instead, as an approximation, we can count symbols and after
1248 * every N symbols, compare the expected distribution of symbols based on the
1249 * previous data with the actual distribution. If they differ "by enough", then
1250 * start a new block.
1252 * As an optimization and heuristic, we don't distinguish between every symbol
1253 * but rather we combine many symbols into a single "observation type". For
1254 * literals we only look at the high bits and low bits, and for matches we only
1255 * look at whether the match is long or not. The assumption is that for typical
1256 * "real" data, places that are good block boundaries will tend to be noticable
1257 * based only on changes in these aggregate frequencies, without looking for
1258 * subtle differences in individual symbols. For example, a change from ASCII
1259 * bytes to non-ASCII bytes, or from few matches (generally less compressible)
1260 * to many matches (generally more compressible), would be easily noticed based
1261 * on the aggregates.
1263 * For determining whether the frequency distributions are "different enough" to
1264 * start a new block, the simply heuristic of splitting when the sum of absolute
1265 * differences exceeds a constant seems to be good enough. We also add a number
1266 * proportional to the block size so that the algorithm is more likely to end
1267 * large blocks than small blocks. This reflects the general expectation that
1268 * it will become increasingly beneficial to start a new block as the current
1269 * blocks grows larger.
1271 * Finally, for an approximation, it is not strictly necessary that the exact
1272 * symbols being used are considered. With "near-optimal parsing", for example,
1273 * the actual symbols that will be used are unknown until after the block
1274 * boundary is chosen and the block has been optimized. Since the final choices
1275 * cannot be used, we can use preliminary "greedy" choices instead.
1278 /* Initialize the block split statistics when starting a new block. */
1280 init_block_split_stats(struct block_split_stats *stats)
1282 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1283 stats->new_observations[i] = 0;
1284 stats->observations[i] = 0;
1286 stats->num_new_observations = 0;
1287 stats->num_observations = 0;
1290 /* Literal observation. Heuristic: use the top 2 bits and low 1 bits of the
1291 * literal, for 8 possible literal observation types. */
1293 observe_literal(struct block_split_stats *stats, u8 lit)
1295 stats->new_observations[((lit >> 5) & 0x6) | (lit & 1)]++;
1296 stats->num_new_observations++;
1299 /* Match observation. Heuristic: use one observation type for "short match" and
1300 * one observation type for "long match". */
1302 observe_match(struct block_split_stats *stats, unsigned length)
1304 stats->new_observations[NUM_LITERAL_OBSERVATION_TYPES + (length >= 5)]++;
1305 stats->num_new_observations++;
1309 do_end_block_check(struct block_split_stats *stats, u32 block_size)
1311 if (stats->num_observations > 0) {
1313 /* Note: to avoid slow divisions, we do not divide by
1314 * 'num_observations', but rather do all math with the numbers
1315 * multiplied by 'num_observations'. */
1316 u32 total_delta = 0;
1317 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1318 u32 expected = stats->observations[i] * stats->num_new_observations;
1319 u32 actual = stats->new_observations[i] * stats->num_observations;
1320 u32 delta = (actual > expected) ? actual - expected :
1322 total_delta += delta;
1325 /* Ready to end the block? */
1326 if (total_delta + (block_size >> 10) * stats->num_observations >=
1327 200 * stats->num_observations)
1331 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1332 stats->num_observations += stats->new_observations[i];
1333 stats->observations[i] += stats->new_observations[i];
1334 stats->new_observations[i] = 0;
1336 stats->num_new_observations = 0;
1341 should_end_block(struct block_split_stats *stats,
1342 const u8 *in_block_begin, const u8 *in_next, const u8 *in_end)
1344 /* Ready to check block split statistics? */
1345 if (stats->num_new_observations < 250 ||
1346 in_next - in_block_begin < MIN_BLOCK_SIZE ||
1347 in_end - in_next < MIN_BLOCK_SIZE)
1350 return do_end_block_check(stats, in_next - in_block_begin);
1353 /******************************************************************************/
1356 * Given the minimum-cost path computed through the item graph for the current
1357 * block, walk the path and count how many of each symbol in each Huffman-coded
1358 * alphabet would be required to output the items (matches and literals) along
1361 * Note that the path will be walked backwards (from the end of the block to the
1362 * beginning of the block), but this doesn't matter because this function only
1363 * computes frequencies.
1366 lzx_tally_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1368 u32 node_idx = block_size;
1373 unsigned offset_slot;
1375 /* Tally literals until either a match or the beginning of the
1376 * block is reached. */
1378 u32 item = c->optimum_nodes[node_idx].item;
1380 len = item & OPTIMUM_LEN_MASK;
1381 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1383 if (len != 0) /* Not a literal? */
1386 /* Tally the main symbol for the literal. */
1387 c->freqs.main[offset_data]++;
1389 if (--node_idx == 0) /* Beginning of block was reached? */
1395 /* Tally a match. */
1397 /* Tally the aligned offset symbol if needed. */
1398 if (offset_data >= 16)
1399 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1401 /* Tally the length symbol if needed. */
1402 v = len - LZX_MIN_MATCH_LEN;;
1403 if (v >= LZX_NUM_PRIMARY_LENS) {
1404 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1405 v = LZX_NUM_PRIMARY_LENS;
1408 /* Tally the main symbol. */
1409 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1410 v += offset_slot * LZX_NUM_LEN_HEADERS;
1411 c->freqs.main[LZX_NUM_CHARS + v]++;
1413 if (node_idx == 0) /* Beginning of block was reached? */
1419 * Like lzx_tally_item_list(), but this function also generates the list of
1420 * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1421 * ready to be output to the bitstream after the Huffman codes are computed.
1422 * The lzx_sequences will be written to decreasing memory addresses as the path
1423 * is walked backwards, which means they will end up in the expected
1424 * first-to-last order. The return value is the index in c->chosen_sequences at
1425 * which the lzx_sequences begin.
1428 lzx_record_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1430 u32 node_idx = block_size;
1431 u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1434 /* Special value to mark last sequence */
1435 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1437 lit_start_node = node_idx;
1442 unsigned offset_slot;
1444 /* Record literals until either a match or the beginning of the
1445 * block is reached. */
1447 u32 item = c->optimum_nodes[node_idx].item;
1449 len = item & OPTIMUM_LEN_MASK;
1450 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1452 if (len != 0) /* Not a literal? */
1455 /* Tally the main symbol for the literal. */
1456 c->freqs.main[offset_data]++;
1458 if (--node_idx == 0) /* Beginning of block was reached? */
1462 /* Save the literal run length for the next sequence (the
1463 * "previous sequence" when walking backwards). */
1464 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1466 lit_start_node = node_idx;
1468 /* Record a match. */
1470 /* Tally the aligned offset symbol if needed. */
1471 if (offset_data >= 16)
1472 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1474 /* Save the adjusted length. */
1475 v = len - LZX_MIN_MATCH_LEN;
1476 c->chosen_sequences[seq_idx].adjusted_length = v;
1478 /* Tally the length symbol if needed. */
1479 if (v >= LZX_NUM_PRIMARY_LENS) {
1480 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1481 v = LZX_NUM_PRIMARY_LENS;
1484 /* Tally the main symbol. */
1485 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1486 v += offset_slot * LZX_NUM_LEN_HEADERS;
1487 c->freqs.main[LZX_NUM_CHARS + v]++;
1489 /* Save the adjusted offset and match header. */
1490 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1491 (offset_data << 9) | v;
1493 if (node_idx == 0) /* Beginning of block was reached? */
1498 /* Save the literal run length for the first sequence. */
1499 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1501 /* Return the index in c->chosen_sequences at which the lzx_sequences
1507 * Find an inexpensive path through the graph of possible match/literal choices
1508 * for the current block. The nodes of the graph are
1509 * c->optimum_nodes[0...block_size]. They correspond directly to the bytes in
1510 * the current block, plus one extra node for end-of-block. The edges of the
1511 * graph are matches and literals. The goal is to find the minimum cost path
1512 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1514 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1515 * proceeding forwards one node at a time. At each node, a selection of matches
1516 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1517 * length 'len' provides a new path to reach the node 'len' bytes later. If
1518 * such a path is the lowest cost found so far to reach that later node, then
1519 * that later node is updated with the new path.
1521 * Note that although this algorithm is based on minimum cost path search, due
1522 * to various simplifying assumptions the result is not guaranteed to be the
1523 * true minimum cost, or "optimal", path over the graph of all valid LZX
1524 * representations of this block.
1526 * Also, note that because of the presence of the recent offsets queue (which is
1527 * a type of adaptive state), the algorithm cannot work backwards and compute
1528 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1529 * algorithm handles this adaptive state in the "minimum cost" parse is actually
1530 * only an approximation. It's possible for the globally optimal, minimum cost
1531 * path to contain a prefix, ending at a position, where that path prefix is
1532 * *not* the minimum cost path to that position. This can happen if such a path
1533 * prefix results in a different adaptive state which results in lower costs
1534 * later. The algorithm does not solve this problem; it only considers the
1535 * lowest cost to reach each individual position.
1537 static inline struct lzx_lru_queue
1538 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1539 const u8 * const restrict block_begin,
1540 const u32 block_size,
1541 const struct lzx_lru_queue initial_queue,
1544 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1545 struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1546 struct lz_match *cache_ptr = c->match_cache;
1547 const u8 *in_next = block_begin;
1548 const u8 * const block_end = block_begin + block_size;
1550 /* Instead of storing the match offset LRU queues in the
1551 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1552 * storing them in a smaller array. This works because the algorithm
1553 * only requires a limited history of the adaptive state. Once a given
1554 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1555 * it is no longer needed. */
1556 struct lzx_lru_queue queues[512];
1558 STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1559 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1561 /* Initially, the cost to reach each node is "infinity". */
1562 memset(c->optimum_nodes, 0xFF,
1563 (block_size + 1) * sizeof(c->optimum_nodes[0]));
1565 QUEUE(block_begin) = initial_queue;
1567 /* The following loop runs 'block_size' iterations, one per node. */
1569 unsigned num_matches;
1574 * A selection of matches for the block was already saved in
1575 * memory so that we don't have to run the uncompressed data
1576 * through the matchfinder on every optimization pass. However,
1577 * we still search for repeat offset matches during each
1578 * optimization pass because we cannot predict the state of the
1579 * recent offsets queue. But as a heuristic, we don't bother
1580 * searching for repeat offset matches if the general-purpose
1581 * matchfinder failed to find any matches.
1583 * Note that a match of length n at some offset implies there is
1584 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1585 * that same offset. In other words, we don't necessarily need
1586 * to use the full length of a match. The key heuristic that
1587 * saves a significicant amount of time is that for each
1588 * distinct length, we only consider the smallest offset for
1589 * which that length is available. This heuristic also applies
1590 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1591 * any explicit offset. Of course, this heuristic may be
1592 * produce suboptimal results because offset slots in LZX are
1593 * subject to entropy encoding, but in practice this is a useful
1597 num_matches = cache_ptr->length;
1601 struct lz_match *end_matches = cache_ptr + num_matches;
1602 unsigned next_len = LZX_MIN_MATCH_LEN;
1603 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1606 /* Consider R0 match */
1607 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1608 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1610 STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1612 u32 cost = cur_node->cost +
1613 c->costs.match_cost[0][
1614 next_len - LZX_MIN_MATCH_LEN];
1615 if (cost <= (cur_node + next_len)->cost) {
1616 (cur_node + next_len)->cost = cost;
1617 (cur_node + next_len)->item =
1618 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1620 if (unlikely(++next_len > max_len)) {
1621 cache_ptr = end_matches;
1624 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1628 /* Consider R1 match */
1629 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1630 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1632 if (matchptr[next_len - 1] != in_next[next_len - 1])
1634 for (unsigned len = 2; len < next_len - 1; len++)
1635 if (matchptr[len] != in_next[len])
1638 u32 cost = cur_node->cost +
1639 c->costs.match_cost[1][
1640 next_len - LZX_MIN_MATCH_LEN];
1641 if (cost <= (cur_node + next_len)->cost) {
1642 (cur_node + next_len)->cost = cost;
1643 (cur_node + next_len)->item =
1644 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1646 if (unlikely(++next_len > max_len)) {
1647 cache_ptr = end_matches;
1650 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1654 /* Consider R2 match */
1655 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1656 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1658 if (matchptr[next_len - 1] != in_next[next_len - 1])
1660 for (unsigned len = 2; len < next_len - 1; len++)
1661 if (matchptr[len] != in_next[len])
1664 u32 cost = cur_node->cost +
1665 c->costs.match_cost[2][
1666 next_len - LZX_MIN_MATCH_LEN];
1667 if (cost <= (cur_node + next_len)->cost) {
1668 (cur_node + next_len)->cost = cost;
1669 (cur_node + next_len)->item =
1670 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1672 if (unlikely(++next_len > max_len)) {
1673 cache_ptr = end_matches;
1676 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1680 while (next_len > cache_ptr->length)
1681 if (++cache_ptr == end_matches)
1684 /* Consider explicit offset matches */
1686 u32 offset = cache_ptr->offset;
1687 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1688 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1690 u32 base_cost = cur_node->cost;
1692 #if LZX_CONSIDER_ALIGNED_COSTS
1693 if (offset_data >= 16)
1694 base_cost += c->costs.aligned[offset_data &
1695 LZX_ALIGNED_OFFSET_BITMASK];
1699 u32 cost = base_cost +
1700 c->costs.match_cost[offset_slot][
1701 next_len - LZX_MIN_MATCH_LEN];
1702 if (cost < (cur_node + next_len)->cost) {
1703 (cur_node + next_len)->cost = cost;
1704 (cur_node + next_len)->item =
1705 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1707 } while (++next_len <= cache_ptr->length);
1708 } while (++cache_ptr != end_matches);
1713 /* Consider coding a literal.
1715 * To avoid an extra branch, actually checking the preferability
1716 * of coding the literal is integrated into the queue update
1718 literal = *in_next++;
1719 cost = cur_node->cost + c->costs.main[literal];
1721 /* Advance to the next position. */
1724 /* The lowest-cost path to the current position is now known.
1725 * Finalize the recent offsets queue that results from taking
1726 * this lowest-cost path. */
1728 if (cost <= cur_node->cost) {
1729 /* Literal: queue remains unchanged. */
1730 cur_node->cost = cost;
1731 cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1732 QUEUE(in_next) = QUEUE(in_next - 1);
1734 /* Match: queue update is needed. */
1735 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1736 u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1737 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1738 /* Explicit offset match: insert offset at front */
1740 lzx_lru_queue_push(QUEUE(in_next - len),
1741 offset_data - LZX_OFFSET_ADJUSTMENT);
1743 /* Repeat offset match: swap offset to front */
1745 lzx_lru_queue_swap(QUEUE(in_next - len),
1749 } while (cur_node != end_node);
1751 /* Return the match offset queue at the end of the minimum cost path. */
1752 return QUEUE(block_end);
1755 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1757 lzx_compute_match_costs(struct lzx_compressor *c)
1759 unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1760 LZX_NUM_LEN_HEADERS;
1761 struct lzx_costs *costs = &c->costs;
1763 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1765 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1766 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1767 LZX_NUM_LEN_HEADERS);
1770 #if LZX_CONSIDER_ALIGNED_COSTS
1771 if (offset_slot >= 8)
1772 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1775 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1776 costs->match_cost[offset_slot][i] =
1777 costs->main[main_symbol++] + extra_cost;
1779 extra_cost += costs->main[main_symbol];
1781 for (; i < LZX_NUM_LENS; i++)
1782 costs->match_cost[offset_slot][i] =
1783 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1787 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1790 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1793 bool have_byte[256];
1794 unsigned num_used_bytes;
1796 /* The costs below are hard coded to use a scaling factor of 16. */
1797 STATIC_ASSERT(LZX_BIT_COST == 16);
1802 * - Use smaller initial costs for literal symbols when the input buffer
1803 * contains fewer distinct bytes.
1805 * - Assume that match symbols are more costly than literal symbols.
1807 * - Assume that length symbols for shorter lengths are less costly than
1808 * length symbols for longer lengths.
1811 for (i = 0; i < 256; i++)
1812 have_byte[i] = false;
1814 for (i = 0; i < block_size; i++)
1815 have_byte[block[i]] = true;
1818 for (i = 0; i < 256; i++)
1819 num_used_bytes += have_byte[i];
1821 for (i = 0; i < 256; i++)
1822 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1824 for (; i < c->num_main_syms; i++)
1825 c->costs.main[i] = 170;
1827 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1828 c->costs.len[i] = 103 + (i / 4);
1830 #if LZX_CONSIDER_ALIGNED_COSTS
1831 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1832 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1835 lzx_compute_match_costs(c);
1838 /* Update the current cost model to reflect the computed Huffman codes. */
1840 lzx_update_costs(struct lzx_compressor *c)
1843 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1845 for (i = 0; i < c->num_main_syms; i++) {
1846 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1847 MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1850 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1851 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1852 LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1855 #if LZX_CONSIDER_ALIGNED_COSTS
1856 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1857 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1858 ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1862 lzx_compute_match_costs(c);
1865 static inline struct lzx_lru_queue
1866 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1867 struct lzx_output_bitstream * const restrict os,
1868 const u8 * const restrict block_begin,
1869 const u32 block_size,
1870 const struct lzx_lru_queue initial_queue,
1873 unsigned num_passes_remaining = c->num_optim_passes;
1874 struct lzx_lru_queue new_queue;
1877 /* The first optimization pass uses a default cost model. Each
1878 * additional optimization pass uses a cost model derived from the
1879 * Huffman code computed in the previous pass. */
1881 lzx_set_default_costs(c, block_begin, block_size);
1882 lzx_reset_symbol_frequencies(c);
1884 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1885 initial_queue, is_16_bit);
1886 if (num_passes_remaining > 1) {
1887 lzx_tally_item_list(c, block_size, is_16_bit);
1888 lzx_make_huffman_codes(c);
1889 lzx_update_costs(c);
1890 lzx_reset_symbol_frequencies(c);
1892 } while (--num_passes_remaining);
1894 seq_idx = lzx_record_item_list(c, block_size, is_16_bit);
1895 lzx_finish_block(c, os, block_begin, block_size, seq_idx);
1900 * This is the "near-optimal" LZX compressor.
1902 * For each block, it performs a relatively thorough graph search to find an
1903 * inexpensive (in terms of compressed size) way to output that block.
1905 * Note: there are actually many things this algorithm leaves on the table in
1906 * terms of compression ratio. So although it may be "near-optimal", it is
1907 * certainly not "optimal". The goal is not to produce the optimal compression
1908 * ratio, which for LZX is probably impossible within any practical amount of
1909 * time, but rather to produce a compression ratio significantly better than a
1910 * simpler "greedy" or "lazy" parse while still being relatively fast.
1913 lzx_compress_near_optimal(struct lzx_compressor *c,
1914 struct lzx_output_bitstream *os,
1917 const u8 * const in_begin = c->in_buffer;
1918 const u8 * in_next = in_begin;
1919 const u8 * const in_end = in_begin + c->in_nbytes;
1920 u32 max_len = LZX_MAX_MATCH_LEN;
1921 u32 nice_len = min(c->nice_match_length, max_len);
1922 u32 next_hashes[2] = {};
1923 struct lzx_lru_queue queue;
1925 CALL_BT_MF(is_16_bit, c, bt_matchfinder_init);
1926 lzx_lru_queue_init(&queue);
1929 /* Starting a new block */
1930 const u8 * const in_block_begin = in_next;
1931 const u8 * const in_max_block_end =
1932 in_next + min(SOFT_MAX_BLOCK_SIZE, in_end - in_next);
1933 const u8 *next_observation = in_next;
1935 init_block_split_stats(&c->split_stats);
1937 /* Run the block through the matchfinder and cache the matches. */
1938 struct lz_match *cache_ptr = c->match_cache;
1940 struct lz_match *lz_matchptr;
1943 /* If approaching the end of the input buffer, adjust
1944 * 'max_len' and 'nice_len' accordingly. */
1945 if (unlikely(max_len > in_end - in_next)) {
1946 max_len = in_end - in_next;
1947 nice_len = min(max_len, nice_len);
1948 if (unlikely(max_len <
1949 BT_MATCHFINDER_REQUIRED_NBYTES))
1952 cache_ptr->length = 0;
1958 /* Check for matches. */
1959 lz_matchptr = CALL_BT_MF(is_16_bit, c,
1960 bt_matchfinder_get_matches,
1965 c->max_search_depth,
1970 if (in_next >= next_observation) {
1972 if (lz_matchptr > cache_ptr + 1)
1973 best_len = (lz_matchptr - 1)->length;
1974 if (best_len >= 2) {
1975 observe_match(&c->split_stats, best_len);
1976 next_observation = in_next + best_len;
1978 observe_literal(&c->split_stats, *in_next);
1979 next_observation = in_next + 1;
1984 cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1985 cache_ptr = lz_matchptr;
1988 * If there was a very long match found, then don't
1989 * cache any matches for the bytes covered by that
1990 * match. This avoids degenerate behavior when
1991 * compressing highly redundant data, where the number
1992 * of matches can be very large.
1994 * This heuristic doesn't actually hurt the compression
1995 * ratio very much. If there's a long match, then the
1996 * data must be highly compressible, so it doesn't
1997 * matter as much what we do.
1999 if (best_len >= nice_len) {
2002 if (unlikely(max_len > in_end - in_next)) {
2003 max_len = in_end - in_next;
2004 nice_len = min(max_len, nice_len);
2005 if (unlikely(max_len <
2006 BT_MATCHFINDER_REQUIRED_NBYTES))
2009 cache_ptr->length = 0;
2014 CALL_BT_MF(is_16_bit, c,
2015 bt_matchfinder_skip_position,
2020 c->max_search_depth,
2023 cache_ptr->length = 0;
2025 } while (--best_len);
2027 } while (in_next < in_max_block_end &&
2028 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]) &&
2029 !should_end_block(&c->split_stats, in_block_begin, in_next, in_end));
2031 /* We've finished running the block through the matchfinder.
2032 * Now choose a match/literal sequence and write the block. */
2034 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
2035 in_next - in_block_begin,
2037 } while (in_next != in_end);
2041 lzx_compress_near_optimal_16(struct lzx_compressor *c,
2042 struct lzx_output_bitstream *os)
2044 lzx_compress_near_optimal(c, os, true);
2048 lzx_compress_near_optimal_32(struct lzx_compressor *c,
2049 struct lzx_output_bitstream *os)
2051 lzx_compress_near_optimal(c, os, false);
2055 * Given a pointer to the current byte sequence and the current list of recent
2056 * match offsets, find the longest repeat offset match.
2058 * If no match of at least 2 bytes is found, then return 0.
2060 * If a match of at least 2 bytes is found, then return its length and set
2061 * *rep_max_idx_ret to the index of its offset in @queue.
2064 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
2065 const u32 bytes_remaining,
2066 const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
2067 unsigned *rep_max_idx_ret)
2069 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2071 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
2072 const u16 next_2_bytes = load_u16_unaligned(in_next);
2074 unsigned rep_max_len;
2075 unsigned rep_max_idx;
2078 matchptr = in_next - recent_offsets[0];
2079 if (load_u16_unaligned(matchptr) == next_2_bytes)
2080 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
2085 matchptr = in_next - recent_offsets[1];
2086 if (load_u16_unaligned(matchptr) == next_2_bytes) {
2087 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2088 if (rep_len > rep_max_len) {
2089 rep_max_len = rep_len;
2094 matchptr = in_next - recent_offsets[2];
2095 if (load_u16_unaligned(matchptr) == next_2_bytes) {
2096 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2097 if (rep_len > rep_max_len) {
2098 rep_max_len = rep_len;
2103 *rep_max_idx_ret = rep_max_idx;
2107 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
2108 static inline unsigned
2109 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
2111 unsigned score = len;
2113 if (adjusted_offset < 4096)
2116 if (adjusted_offset < 256)
2122 static inline unsigned
2123 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
2128 /* This is the "lazy" LZX compressor. */
2130 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
2133 const u8 * const in_begin = c->in_buffer;
2134 const u8 * in_next = in_begin;
2135 const u8 * const in_end = in_begin + c->in_nbytes;
2136 unsigned max_len = LZX_MAX_MATCH_LEN;
2137 unsigned nice_len = min(c->nice_match_length, max_len);
2138 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2139 u32 recent_offsets[3] = {1, 1, 1};
2140 u32 next_hashes[2] = {};
2142 CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2145 /* Starting a new block */
2147 const u8 * const in_block_begin = in_next;
2148 const u8 * const in_max_block_end =
2149 in_next + min(SOFT_MAX_BLOCK_SIZE, in_end - in_next);
2150 struct lzx_sequence *next_seq = c->chosen_sequences;
2153 u32 cur_offset_data;
2157 u32 next_offset_data;
2158 unsigned next_score;
2159 unsigned rep_max_len;
2160 unsigned rep_max_idx;
2165 lzx_reset_symbol_frequencies(c);
2166 init_block_split_stats(&c->split_stats);
2169 if (unlikely(max_len > in_end - in_next)) {
2170 max_len = in_end - in_next;
2171 nice_len = min(max_len, nice_len);
2174 /* Find the longest match at the current position. */
2176 cur_len = CALL_HC_MF(is_16_bit, c,
2177 hc_matchfinder_longest_match,
2183 c->max_search_depth,
2188 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2189 cur_offset != recent_offsets[0] &&
2190 cur_offset != recent_offsets[1] &&
2191 cur_offset != recent_offsets[2]))
2193 /* There was no match found, or the only match found
2194 * was a distant length 3 match. Output a literal. */
2195 lzx_record_literal(c, *in_next, &litrunlen);
2196 observe_literal(&c->split_stats, *in_next);
2201 observe_match(&c->split_stats, cur_len);
2203 if (cur_offset == recent_offsets[0]) {
2205 cur_offset_data = 0;
2206 skip_len = cur_len - 1;
2207 goto choose_cur_match;
2210 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2211 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2213 /* Consider a repeat offset match */
2214 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2220 if (rep_max_len >= 3 &&
2221 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2222 rep_max_idx)) >= cur_score)
2224 cur_len = rep_max_len;
2225 cur_offset_data = rep_max_idx;
2226 skip_len = rep_max_len - 1;
2227 goto choose_cur_match;
2232 /* We have a match at the current position. */
2234 /* If we have a very long match, choose it immediately. */
2235 if (cur_len >= nice_len) {
2236 skip_len = cur_len - 1;
2237 goto choose_cur_match;
2240 /* See if there's a better match at the next position. */
2242 if (unlikely(max_len > in_end - in_next)) {
2243 max_len = in_end - in_next;
2244 nice_len = min(max_len, nice_len);
2247 next_len = CALL_HC_MF(is_16_bit, c,
2248 hc_matchfinder_longest_match,
2254 c->max_search_depth / 2,
2258 if (next_len <= cur_len - 2) {
2260 skip_len = cur_len - 2;
2261 goto choose_cur_match;
2264 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2265 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2267 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2273 if (rep_max_len >= 3 &&
2274 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2275 rep_max_idx)) >= next_score)
2278 if (rep_score > cur_score) {
2279 /* The next match is better, and it's a
2280 * repeat offset match. */
2281 lzx_record_literal(c, *(in_next - 2),
2283 cur_len = rep_max_len;
2284 cur_offset_data = rep_max_idx;
2285 skip_len = cur_len - 1;
2286 goto choose_cur_match;
2289 if (next_score > cur_score) {
2290 /* The next match is better, and it's an
2291 * explicit offset match. */
2292 lzx_record_literal(c, *(in_next - 2),
2295 cur_offset_data = next_offset_data;
2296 cur_score = next_score;
2297 goto have_cur_match;
2301 /* The original match was better. */
2302 skip_len = cur_len - 2;
2305 lzx_record_match(c, cur_len, cur_offset_data,
2306 recent_offsets, is_16_bit,
2307 &litrunlen, &next_seq);
2308 in_next = CALL_HC_MF(is_16_bit, c,
2309 hc_matchfinder_skip_positions,
2315 } while (in_next < in_max_block_end &&
2316 !should_end_block(&c->split_stats, in_block_begin, in_next, in_end));
2318 lzx_finish_sequence(next_seq, litrunlen);
2320 lzx_finish_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2322 } while (in_next != in_end);
2326 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2328 lzx_compress_lazy(c, os, true);
2332 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2334 lzx_compress_lazy(c, os, false);
2337 /* Generate the acceleration tables for offset slots. */
2339 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2341 u32 adjusted_offset = 0;
2345 for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2348 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2350 c->offset_slot_tab_1[adjusted_offset] = slot;
2353 /* slots [30, 49] */
2354 for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2355 adjusted_offset += (u32)1 << 14)
2357 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2359 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2364 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2366 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2367 if (lzx_is_16_bit(max_bufsize))
2368 return offsetof(struct lzx_compressor, hc_mf_16) +
2369 hc_matchfinder_size_16(max_bufsize);
2371 return offsetof(struct lzx_compressor, hc_mf_32) +
2372 hc_matchfinder_size_32(max_bufsize);
2374 if (lzx_is_16_bit(max_bufsize))
2375 return offsetof(struct lzx_compressor, bt_mf_16) +
2376 bt_matchfinder_size_16(max_bufsize);
2378 return offsetof(struct lzx_compressor, bt_mf_32) +
2379 bt_matchfinder_size_32(max_bufsize);
2384 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2389 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2392 size += lzx_get_compressor_size(max_bufsize, compression_level);
2394 size += max_bufsize; /* in_buffer */
2399 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2400 bool destructive, void **c_ret)
2402 unsigned window_order;
2403 struct lzx_compressor *c;
2405 window_order = lzx_get_window_order(max_bufsize);
2406 if (window_order == 0)
2407 return WIMLIB_ERR_INVALID_PARAM;
2409 c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2413 c->destructive = destructive;
2415 c->num_main_syms = lzx_get_num_main_syms(window_order);
2416 c->window_order = window_order;
2418 if (!c->destructive) {
2419 c->in_buffer = MALLOC(max_bufsize);
2424 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2426 /* Fast compression: Use lazy parsing. */
2428 if (lzx_is_16_bit(max_bufsize))
2429 c->impl = lzx_compress_lazy_16;
2431 c->impl = lzx_compress_lazy_32;
2432 c->max_search_depth = (60 * compression_level) / 20;
2433 c->nice_match_length = (80 * compression_level) / 20;
2435 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2436 * halves the max_search_depth when attempting a lazy match, and
2437 * max_search_depth cannot be 0. */
2438 if (c->max_search_depth < 2)
2439 c->max_search_depth = 2;
2442 /* Normal / high compression: Use near-optimal parsing. */
2444 if (lzx_is_16_bit(max_bufsize))
2445 c->impl = lzx_compress_near_optimal_16;
2447 c->impl = lzx_compress_near_optimal_32;
2449 /* Scale nice_match_length and max_search_depth with the
2450 * compression level. */
2451 c->max_search_depth = (24 * compression_level) / 50;
2452 c->nice_match_length = (48 * compression_level) / 50;
2454 /* Set a number of optimization passes appropriate for the
2455 * compression level. */
2457 c->num_optim_passes = 1;
2459 if (compression_level >= 45)
2460 c->num_optim_passes++;
2462 /* Use more optimization passes for higher compression levels.
2463 * But the more passes there are, the less they help --- so
2464 * don't add them linearly. */
2465 if (compression_level >= 70) {
2466 c->num_optim_passes++;
2467 if (compression_level >= 100)
2468 c->num_optim_passes++;
2469 if (compression_level >= 150)
2470 c->num_optim_passes++;
2471 if (compression_level >= 200)
2472 c->num_optim_passes++;
2473 if (compression_level >= 300)
2474 c->num_optim_passes++;
2478 /* max_search_depth == 0 is invalid. */
2479 if (c->max_search_depth < 1)
2480 c->max_search_depth = 1;
2482 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2483 c->nice_match_length = LZX_MAX_MATCH_LEN;
2485 lzx_init_offset_slot_tabs(c);
2492 return WIMLIB_ERR_NOMEM;
2496 lzx_compress(const void *restrict in, size_t in_nbytes,
2497 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2499 struct lzx_compressor *c = _c;
2500 struct lzx_output_bitstream os;
2503 /* Don't bother trying to compress very small inputs. */
2504 if (in_nbytes < 100)
2507 /* Copy the input data into the internal buffer and preprocess it. */
2509 c->in_buffer = (void *)in;
2511 memcpy(c->in_buffer, in, in_nbytes);
2512 c->in_nbytes = in_nbytes;
2513 lzx_preprocess(c->in_buffer, in_nbytes);
2515 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2517 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2519 /* Initialize the output bitstream. */
2520 lzx_init_output(&os, out, out_nbytes_avail);
2522 /* Call the compression level-specific compress() function. */
2525 /* Flush the output bitstream and return the compressed size or 0. */
2526 result = lzx_flush_output(&os);
2527 if (!result && c->destructive)
2528 lzx_postprocess(c->in_buffer, c->in_nbytes);
2533 lzx_free_compressor(void *_c)
2535 struct lzx_compressor *c = _c;
2537 if (!c->destructive)
2542 const struct compressor_ops lzx_compressor_ops = {
2543 .get_needed_memory = lzx_get_needed_memory,
2544 .create_compressor = lzx_create_compressor,
2545 .compress = lzx_compress,
2546 .free_compressor = lzx_free_compressor,