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 * The number of observed matches or literals that represents sufficient data to
91 * decide whether the current block should be terminated or not.
93 #define NUM_OBSERVATIONS_PER_BLOCK_CHECK 500
96 * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
97 * excluding the extra "overflow" entries. This value should be high enough so
98 * that nearly the time, all matches found in a given block can fit in the match
99 * cache. However, fallback behavior (immediately terminating the block) on
100 * cache overflow is still required.
102 #define LZX_CACHE_LENGTH (SOFT_MAX_BLOCK_SIZE * 5)
105 * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
106 * ever be saved in the match cache for a single position. Since each match we
107 * save for a single position has a distinct length, we can use the number of
108 * possible match lengths in LZX as this bound. This bound is guaranteed to be
109 * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
110 * it will never actually be reached.
112 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
115 * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
116 * This makes it possible to consider fractional bit costs.
118 * Note: this is only useful as a statistical trick for when the true costs are
119 * unknown. In reality, each token in LZX requires a whole number of bits to
122 #define LZX_BIT_COST 64
125 * Should the compressor take into account the costs of aligned offset symbols?
127 #define LZX_CONSIDER_ALIGNED_COSTS 1
130 * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
133 #define LZX_MAX_FAST_LEVEL 34
136 * BT_MATCHFINDER_HASH2_ORDER is the log base 2 of the number of entries in the
137 * hash table for finding length 2 matches. This could be as high as 16, but
138 * using a smaller hash table speeds up compression due to reduced cache
141 #define BT_MATCHFINDER_HASH2_ORDER 12
144 * These are the compressor-side limits on the codeword lengths for each Huffman
145 * code. To make outputting bits slightly faster, some of these limits are
146 * lower than the limits defined by the LZX format. This does not significantly
147 * affect the compression ratio, at least for the block sizes we use.
149 #define MAIN_CODEWORD_LIMIT 16
150 #define LENGTH_CODEWORD_LIMIT 12
151 #define ALIGNED_CODEWORD_LIMIT 7
152 #define PRE_CODEWORD_LIMIT 7
154 #include "wimlib/compress_common.h"
155 #include "wimlib/compressor_ops.h"
156 #include "wimlib/error.h"
157 #include "wimlib/lz_extend.h"
158 #include "wimlib/lzx_common.h"
159 #include "wimlib/unaligned.h"
160 #include "wimlib/util.h"
162 /* Matchfinders with 16-bit positions */
164 #define MF_SUFFIX _16
165 #include "wimlib/bt_matchfinder.h"
166 #include "wimlib/hc_matchfinder.h"
168 /* Matchfinders with 32-bit positions */
172 #define MF_SUFFIX _32
173 #include "wimlib/bt_matchfinder.h"
174 #include "wimlib/hc_matchfinder.h"
176 struct lzx_output_bitstream;
178 /* Codewords for the LZX Huffman codes. */
179 struct lzx_codewords {
180 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
181 u32 len[LZX_LENCODE_NUM_SYMBOLS];
182 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
185 /* Codeword lengths (in bits) for the LZX Huffman codes.
186 * A zero length means the corresponding codeword has zero frequency. */
188 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS + 1];
189 u8 len[LZX_LENCODE_NUM_SYMBOLS + 1];
190 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
193 /* Cost model for near-optimal parsing */
196 /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
197 * length 'len' match that has an offset belonging to 'offset_slot'. */
198 u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
200 /* Cost for each symbol in the main code */
201 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
203 /* Cost for each symbol in the length code */
204 u32 len[LZX_LENCODE_NUM_SYMBOLS];
206 #if LZX_CONSIDER_ALIGNED_COSTS
207 /* Cost for each symbol in the aligned code */
208 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
212 /* Codewords and lengths for the LZX Huffman codes. */
214 struct lzx_codewords codewords;
215 struct lzx_lens lens;
218 /* Symbol frequency counters for the LZX Huffman codes. */
220 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
221 u32 len[LZX_LENCODE_NUM_SYMBOLS];
222 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
225 /* Block split statistics. See "Block splitting algorithm" below. */
226 #define NUM_LITERAL_OBSERVATION_TYPES 8
227 #define NUM_MATCH_OBSERVATION_TYPES 2
228 #define NUM_OBSERVATION_TYPES (NUM_LITERAL_OBSERVATION_TYPES + NUM_MATCH_OBSERVATION_TYPES)
229 struct block_split_stats {
230 u32 new_observations[NUM_OBSERVATION_TYPES];
231 u32 observations[NUM_OBSERVATION_TYPES];
232 u32 num_new_observations;
233 u32 num_observations;
237 * Represents a run of literals followed by a match or end-of-block. This
238 * struct is needed to temporarily store items chosen by the parser, since items
239 * cannot be written until all items for the block have been chosen and the
240 * block's Huffman codes have been computed.
242 struct lzx_sequence {
244 /* The number of literals in the run. This may be 0. The literals are
245 * not stored explicitly in this structure; instead, they are read
246 * directly from the uncompressed data. */
249 /* If the next field doesn't indicate end-of-block, then this is the
250 * match length minus LZX_MIN_MATCH_LEN. */
253 /* If bit 31 is clear, then this field contains the match header in bits
254 * 0-8, and either the match offset plus LZX_OFFSET_ADJUSTMENT or a
255 * recent offset code in bits 9-30. Otherwise (if bit 31 is set), this
256 * sequence's literal run was the last literal run in the block, so
257 * there is no match that follows it. */
258 u32 adjusted_offset_and_match_hdr;
262 * This structure represents a byte position in the input buffer and a node in
263 * the graph of possible match/literal choices.
265 * Logically, each incoming edge to this node is labeled with a literal or a
266 * match that can be taken to reach this position from an earlier position; and
267 * each outgoing edge from this node is labeled with a literal or a match that
268 * can be taken to advance from this position to a later position.
270 struct lzx_optimum_node {
272 /* The cost, in bits, of the lowest-cost path that has been found to
273 * reach this position. This can change as progressively lower cost
274 * paths are found to reach this position. */
278 * The match or literal that was taken to reach this position. This can
279 * change as progressively lower cost paths are found to reach this
282 * This variable is divided into two bitfields.
285 * Low bits are 0, high bits are the literal.
287 * Explicit offset matches:
288 * Low bits are the match length, high bits are the offset plus 2.
290 * Repeat offset matches:
291 * Low bits are the match length, high bits are the queue index.
294 #define OPTIMUM_OFFSET_SHIFT 9
295 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
296 #define OPTIMUM_EXTRA_FLAG 0x80000000
299 } _aligned_attribute(8);
302 * Least-recently-used queue for match offsets.
304 * This is represented as a 64-bit integer for efficiency. There are three
305 * offsets of 21 bits each. Bit 64 is garbage.
307 struct lzx_lru_queue {
311 #define LZX_QUEUE64_OFFSET_SHIFT 21
312 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
314 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
315 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
316 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
318 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
319 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
320 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
323 lzx_lru_queue_init(struct lzx_lru_queue *queue)
325 queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
326 ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
327 ((u64)1 << LZX_QUEUE64_R2_SHIFT);
331 lzx_lru_queue_R0(struct lzx_lru_queue queue)
333 return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
337 lzx_lru_queue_R1(struct lzx_lru_queue queue)
339 return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
343 lzx_lru_queue_R2(struct lzx_lru_queue queue)
345 return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
348 /* Push a match offset onto the front (most recently used) end of the queue. */
349 static inline struct lzx_lru_queue
350 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
352 return (struct lzx_lru_queue) {
353 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
357 /* Swap a match offset to the front of the queue. */
358 static inline struct lzx_lru_queue
359 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
365 return (struct lzx_lru_queue) {
366 .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
367 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
368 (queue.R & LZX_QUEUE64_R2_MASK),
371 return (struct lzx_lru_queue) {
372 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
373 (queue.R & LZX_QUEUE64_R1_MASK) |
374 (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
378 /* The main LZX compressor structure */
379 struct lzx_compressor {
381 /* The "nice" match length: if a match of this length is found, then
382 * choose it immediately without further consideration. */
383 unsigned nice_match_length;
385 /* The maximum search depth: consider at most this many potential
386 * matches at each position. */
387 unsigned max_search_depth;
389 /* The log base 2 of the LZX window size for LZ match offset encoding
390 * purposes. This will be >= LZX_MIN_WINDOW_ORDER and <=
391 * LZX_MAX_WINDOW_ORDER. */
392 unsigned window_order;
394 /* The number of symbols in the main alphabet. This depends on
395 * @window_order, since @window_order determines the maximum possible
397 unsigned num_main_syms;
399 /* Number of optimization passes per block */
400 unsigned num_optim_passes;
402 /* The preprocessed buffer of data being compressed */
405 /* The number of bytes of data to be compressed, which is the number of
406 * bytes of data in @in_buffer that are actually valid. */
409 /* Pointer to the compress() implementation chosen at allocation time */
410 void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
412 /* If true, the compressor need not preserve the input buffer if it
413 * compresses the data successfully. */
416 /* The Huffman symbol frequency counters for the current block. */
417 struct lzx_freqs freqs;
419 /* Block split statistics. */
420 struct block_split_stats split_stats;
422 /* The Huffman codes for the current and previous blocks. The one with
423 * index 'codes_index' is for the current block, and the other one is
424 * for the previous block. */
425 struct lzx_codes codes[2];
426 unsigned codes_index;
428 /* The matches and literals that the parser has chosen for the current
429 * block. The required length of this array is limited by the maximum
430 * number of matches that can ever be chosen for a single block, plus
431 * one for the special entry at the end. */
432 struct lzx_sequence chosen_sequences[
433 DIV_ROUND_UP(SOFT_MAX_BLOCK_SIZE, LZX_MIN_MATCH_LEN) + 1];
435 /* Tables for mapping adjusted offsets to offset slots */
437 /* offset slots [0, 29] */
438 u8 offset_slot_tab_1[32768];
440 /* offset slots [30, 49] */
441 u8 offset_slot_tab_2[128];
444 /* Data for greedy or lazy parsing */
446 /* Hash chains matchfinder (MUST BE LAST!!!) */
448 struct hc_matchfinder_16 hc_mf_16;
449 struct hc_matchfinder_32 hc_mf_32;
453 /* Data for near-optimal parsing */
456 * Array of nodes, one per position, for running the
457 * minimum-cost path algorithm.
459 * This array must be large enough to accommodate the
460 * worst-case number of nodes, which occurs if we find a
461 * match of length LZX_MAX_MATCH_LEN at position
462 * SOFT_MAX_BLOCK_SIZE - 1, producing a block of length
463 * SOFT_MAX_BLOCK_SIZE - 1 + LZX_MAX_MATCH_LEN. Add one
464 * for the end-of-block node.
466 struct lzx_optimum_node optimum_nodes[SOFT_MAX_BLOCK_SIZE - 1 +
467 LZX_MAX_MATCH_LEN + 1];
469 /* The cost model for the current block */
470 struct lzx_costs costs;
473 * Cached matches for the current block. This array
474 * contains the matches that were found at each position
475 * in the block. Specifically, for each position, there
476 * is a special 'struct lz_match' whose 'length' field
477 * contains the number of matches that were found at
478 * that position; this is followed by the matches
479 * themselves, if any, sorted by strictly increasing
482 * Note: in rare cases, there will be a very high number
483 * of matches in the block and this array will overflow.
484 * If this happens, we force the end of the current
485 * block. LZX_CACHE_LENGTH is the length at which we
486 * actually check for overflow. The extra slots beyond
487 * this are enough to absorb the worst case overflow,
488 * which occurs if starting at
489 * &match_cache[LZX_CACHE_LENGTH - 1], we write the
490 * match count header, then write
491 * LZX_MAX_MATCHES_PER_POS matches, then skip searching
492 * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
493 * write the match count header for each.
495 struct lz_match match_cache[LZX_CACHE_LENGTH +
496 LZX_MAX_MATCHES_PER_POS +
497 LZX_MAX_MATCH_LEN - 1];
499 /* Binary trees matchfinder (MUST BE LAST!!!) */
501 struct bt_matchfinder_16 bt_mf_16;
502 struct bt_matchfinder_32 bt_mf_32;
509 * Will a matchfinder using 16-bit positions be sufficient for compressing
510 * buffers of up to the specified size? The limit could be 65536 bytes, but we
511 * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
512 * This requires that the limit be no more than the length of offset_slot_tab_1
516 lzx_is_16_bit(size_t max_bufsize)
518 STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
519 return max_bufsize <= 32768;
523 * The following macros call either the 16-bit or the 32-bit version of a
524 * matchfinder function based on the value of 'is_16_bit', which will be known
525 * at compilation time.
528 #define CALL_HC_MF(is_16_bit, c, funcname, ...) \
529 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
530 CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
532 #define CALL_BT_MF(is_16_bit, c, funcname, ...) \
533 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->bt_mf_16, ##__VA_ARGS__) : \
534 CONCAT(funcname, _32)(&(c)->bt_mf_32, ##__VA_ARGS__));
537 * Structure to keep track of the current state of sending bits to the
538 * compressed output buffer.
540 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
542 struct lzx_output_bitstream {
544 /* Bits that haven't yet been written to the output buffer. */
545 machine_word_t bitbuf;
547 /* Number of bits currently held in @bitbuf. */
550 /* Pointer to the start of the output buffer. */
553 /* Pointer to the position in the output buffer at which the next coding
554 * unit should be written. */
557 /* Pointer just past the end of the output buffer, rounded down to a
558 * 2-byte boundary. */
562 /* Can the specified number of bits always be added to 'bitbuf' after any
563 * pending 16-bit coding units have been flushed? */
564 #define CAN_BUFFER(n) ((n) <= (8 * sizeof(machine_word_t)) - 15)
567 * Initialize the output bitstream.
570 * The output bitstream structure to initialize.
572 * The buffer being written to.
574 * Size of @buffer, in bytes.
577 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
582 os->next = os->start;
583 os->end = os->start + (size & ~1);
586 /* Add some bits to the bitbuffer variable of the output bitstream. The caller
587 * must make sure there is enough room. */
589 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
591 os->bitbuf = (os->bitbuf << num_bits) | bits;
592 os->bitcount += num_bits;
595 /* Flush bits from the bitbuffer variable to the output buffer. 'max_num_bits'
596 * specifies the maximum number of bits that may have been added since the last
599 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
601 /* Masking the number of bits to shift is only needed to avoid undefined
602 * behavior; we don't actually care about the results of bad shifts. On
603 * x86, the explicit masking generates no extra code. */
604 const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
606 if (os->end - os->next < 6)
608 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 16) &
609 shift_mask), os->next + 0);
610 if (max_num_bits > 16)
611 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 32) &
612 shift_mask), os->next + 2);
613 if (max_num_bits > 32)
614 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 48) &
615 shift_mask), os->next + 4);
616 os->next += (os->bitcount >> 4) << 1;
620 /* Add at most 16 bits to the bitbuffer and flush it. */
622 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
624 lzx_add_bits(os, bits, num_bits);
625 lzx_flush_bits(os, 16);
629 * Flush the last coding unit to the output buffer if needed. Return the total
630 * number of bytes written to the output buffer, or 0 if an overflow occurred.
633 lzx_flush_output(struct lzx_output_bitstream *os)
635 if (os->end - os->next < 6)
638 if (os->bitcount != 0) {
639 put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
643 return os->next - os->start;
646 /* Build the main, length, and aligned offset Huffman codes used in LZX.
648 * This takes as input the frequency tables for each code and produces as output
649 * a set of tables that map symbols to codewords and codeword lengths. */
651 lzx_make_huffman_codes(struct lzx_compressor *c)
653 const struct lzx_freqs *freqs = &c->freqs;
654 struct lzx_codes *codes = &c->codes[c->codes_index];
656 STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
657 MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
658 STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
659 LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
660 STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
661 ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
663 make_canonical_huffman_code(c->num_main_syms,
667 codes->codewords.main);
669 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
670 LENGTH_CODEWORD_LIMIT,
673 codes->codewords.len);
675 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
676 ALIGNED_CODEWORD_LIMIT,
679 codes->codewords.aligned);
682 /* Reset the symbol frequencies for the LZX Huffman codes. */
684 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
686 memset(&c->freqs, 0, sizeof(c->freqs));
690 lzx_compute_precode_items(const u8 lens[restrict],
691 const u8 prev_lens[restrict],
692 u32 precode_freqs[restrict],
693 unsigned precode_items[restrict])
702 itemptr = precode_items;
705 while (!((len = lens[run_start]) & 0x80)) {
707 /* len = the length being repeated */
709 /* Find the next run of codeword lengths. */
711 run_end = run_start + 1;
713 /* Fast case for a single length. */
714 if (likely(len != lens[run_end])) {
715 delta = prev_lens[run_start] - len;
718 precode_freqs[delta]++;
724 /* Extend the run. */
727 } while (len == lens[run_end]);
732 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
733 while ((run_end - run_start) >= 20) {
734 extra_bits = min((run_end - run_start) - 20, 0x1f);
736 *itemptr++ = 18 | (extra_bits << 5);
737 run_start += 20 + extra_bits;
740 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
741 if ((run_end - run_start) >= 4) {
742 extra_bits = min((run_end - run_start) - 4, 0xf);
744 *itemptr++ = 17 | (extra_bits << 5);
745 run_start += 4 + extra_bits;
749 /* A run of nonzero lengths. */
751 /* Symbol 19: RLE 4 to 5 of any length at a time. */
752 while ((run_end - run_start) >= 4) {
753 extra_bits = (run_end - run_start) > 4;
754 delta = prev_lens[run_start] - len;
758 precode_freqs[delta]++;
759 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
760 run_start += 4 + extra_bits;
764 /* Output any remaining lengths without RLE. */
765 while (run_start != run_end) {
766 delta = prev_lens[run_start] - len;
769 precode_freqs[delta]++;
775 return itemptr - precode_items;
779 * Output a Huffman code in the compressed form used in LZX.
781 * The Huffman code is represented in the output as a logical series of codeword
782 * lengths from which the Huffman code, which must be in canonical form, can be
785 * The codeword lengths are themselves compressed using a separate Huffman code,
786 * the "precode", which contains a symbol for each possible codeword length in
787 * the larger code as well as several special symbols to represent repeated
788 * codeword lengths (a form of run-length encoding). The precode is itself
789 * constructed in canonical form, and its codeword lengths are represented
790 * literally in 20 4-bit fields that immediately precede the compressed codeword
791 * lengths of the larger code.
793 * Furthermore, the codeword lengths of the larger code are actually represented
794 * as deltas from the codeword lengths of the corresponding code in the previous
798 * Bitstream to which to write the compressed Huffman code.
800 * The codeword lengths, indexed by symbol, in the Huffman code.
802 * The codeword lengths, indexed by symbol, in the corresponding Huffman
803 * code in the previous block, or all zeroes if this is the first block.
805 * The number of symbols in the Huffman code.
808 lzx_write_compressed_code(struct lzx_output_bitstream *os,
809 const u8 lens[restrict],
810 const u8 prev_lens[restrict],
813 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
814 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
815 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
816 unsigned precode_items[num_lens];
817 unsigned num_precode_items;
818 unsigned precode_item;
819 unsigned precode_sym;
821 u8 saved = lens[num_lens];
822 *(u8 *)(lens + num_lens) = 0x80;
824 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
825 precode_freqs[i] = 0;
827 /* Compute the "items" (RLE / literal tokens and extra bits) with which
828 * the codeword lengths in the larger code will be output. */
829 num_precode_items = lzx_compute_precode_items(lens,
834 /* Build the precode. */
835 STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
836 PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
837 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
839 precode_freqs, precode_lens,
842 /* Output the lengths of the codewords in the precode. */
843 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
844 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
846 /* Output the encoded lengths of the codewords in the larger code. */
847 for (i = 0; i < num_precode_items; i++) {
848 precode_item = precode_items[i];
849 precode_sym = precode_item & 0x1F;
850 lzx_add_bits(os, precode_codewords[precode_sym],
851 precode_lens[precode_sym]);
852 if (precode_sym >= 17) {
853 if (precode_sym == 17) {
854 lzx_add_bits(os, precode_item >> 5, 4);
855 } else if (precode_sym == 18) {
856 lzx_add_bits(os, precode_item >> 5, 5);
858 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
859 precode_sym = precode_item >> 6;
860 lzx_add_bits(os, precode_codewords[precode_sym],
861 precode_lens[precode_sym]);
864 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
865 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
868 *(u8 *)(lens + num_lens) = saved;
872 * Write all matches and literal bytes (which were precomputed) in an LZX
873 * compressed block to the output bitstream in the final compressed
877 * The output bitstream.
879 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
880 * LZX_BLOCKTYPE_VERBATIM).
882 * The uncompressed data of the block.
884 * The matches and literals to output, given as a series of sequences.
886 * The main, length, and aligned offset Huffman codes for the current
887 * LZX compressed block.
890 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
891 const u8 *block_data, const struct lzx_sequence sequences[],
892 const struct lzx_codes *codes)
894 const struct lzx_sequence *seq = sequences;
895 u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
898 /* Output the next sequence. */
900 unsigned litrunlen = seq->litrunlen;
902 unsigned main_symbol;
903 unsigned adjusted_length;
905 unsigned offset_slot;
906 unsigned num_extra_bits;
909 /* Output the literal run of the sequence. */
911 if (litrunlen) { /* Is the literal run nonempty? */
913 /* Verify optimization is enabled on 64-bit */
914 STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
915 CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT));
917 if (CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT)) {
919 /* 64-bit: write 3 literals at a time. */
920 while (litrunlen >= 3) {
921 unsigned lit0 = block_data[0];
922 unsigned lit1 = block_data[1];
923 unsigned lit2 = block_data[2];
924 lzx_add_bits(os, codes->codewords.main[lit0],
925 codes->lens.main[lit0]);
926 lzx_add_bits(os, codes->codewords.main[lit1],
927 codes->lens.main[lit1]);
928 lzx_add_bits(os, codes->codewords.main[lit2],
929 codes->lens.main[lit2]);
930 lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
935 unsigned lit = *block_data++;
936 lzx_add_bits(os, codes->codewords.main[lit],
937 codes->lens.main[lit]);
939 unsigned lit = *block_data++;
940 lzx_add_bits(os, codes->codewords.main[lit],
941 codes->lens.main[lit]);
942 lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
944 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
948 /* 32-bit: write 1 literal at a time. */
950 unsigned lit = *block_data++;
951 lzx_add_bits(os, codes->codewords.main[lit],
952 codes->lens.main[lit]);
953 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
954 } while (--litrunlen);
958 /* Was this the last literal run? */
959 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
962 /* Nope; output the match. */
964 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
965 main_symbol = LZX_NUM_CHARS + match_hdr;
966 adjusted_length = seq->adjusted_length;
968 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
970 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
971 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
973 num_extra_bits = lzx_extra_offset_bits[offset_slot];
974 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
976 #define MAX_MATCH_BITS (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
977 14 + ALIGNED_CODEWORD_LIMIT)
979 /* Verify optimization is enabled on 64-bit */
980 STATIC_ASSERT(sizeof(machine_word_t) < 8 || CAN_BUFFER(MAX_MATCH_BITS));
982 /* Output the main symbol for the match. */
984 lzx_add_bits(os, codes->codewords.main[main_symbol],
985 codes->lens.main[main_symbol]);
986 if (!CAN_BUFFER(MAX_MATCH_BITS))
987 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
989 /* If needed, output the length symbol for the match. */
991 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
992 lzx_add_bits(os, codes->codewords.len[adjusted_length -
993 LZX_NUM_PRIMARY_LENS],
994 codes->lens.len[adjusted_length -
995 LZX_NUM_PRIMARY_LENS]);
996 if (!CAN_BUFFER(MAX_MATCH_BITS))
997 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
1000 /* Output the extra offset bits for the match. In aligned
1001 * offset blocks, the lowest 3 bits of the adjusted offset are
1002 * Huffman-encoded using the aligned offset code, provided that
1003 * there are at least extra 3 offset bits required. All other
1004 * extra offset bits are output verbatim. */
1006 if ((adjusted_offset & ones_if_aligned) >= 16) {
1008 lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
1009 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
1010 if (!CAN_BUFFER(MAX_MATCH_BITS))
1011 lzx_flush_bits(os, 14);
1013 lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
1014 LZX_ALIGNED_OFFSET_BITMASK],
1015 codes->lens.aligned[adjusted_offset &
1016 LZX_ALIGNED_OFFSET_BITMASK]);
1017 if (!CAN_BUFFER(MAX_MATCH_BITS))
1018 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1020 STATIC_ASSERT(CAN_BUFFER(17));
1022 lzx_add_bits(os, extra_bits, num_extra_bits);
1023 if (!CAN_BUFFER(MAX_MATCH_BITS))
1024 lzx_flush_bits(os, 17);
1027 if (CAN_BUFFER(MAX_MATCH_BITS))
1028 lzx_flush_bits(os, MAX_MATCH_BITS);
1030 /* Advance to the next sequence. */
1036 lzx_write_compressed_block(const u8 *block_begin,
1039 unsigned window_order,
1040 unsigned num_main_syms,
1041 const struct lzx_sequence sequences[],
1042 const struct lzx_codes * codes,
1043 const struct lzx_lens * prev_lens,
1044 struct lzx_output_bitstream * os)
1046 /* The first three bits indicate the type of block and are one of the
1047 * LZX_BLOCKTYPE_* constants. */
1048 lzx_write_bits(os, block_type, 3);
1050 /* Output the block size.
1052 * The original LZX format seemed to always encode the block size in 3
1053 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
1054 * uses the first bit to indicate whether the block is the default size
1055 * (32768) or a different size given explicitly by the next 16 bits.
1057 * By default, this compressor uses a window size of 32768 and therefore
1058 * follows the WIMGAPI behavior. However, this compressor also supports
1059 * window sizes greater than 32768 bytes, which do not appear to be
1060 * supported by WIMGAPI. In such cases, we retain the default size bit
1061 * to mean a size of 32768 bytes but output non-default block size in 24
1062 * bits rather than 16. The compatibility of this behavior is unknown
1063 * because WIMs created with chunk size greater than 32768 can seemingly
1064 * only be opened by wimlib anyway. */
1065 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1066 lzx_write_bits(os, 1, 1);
1068 lzx_write_bits(os, 0, 1);
1070 if (window_order >= 16)
1071 lzx_write_bits(os, block_size >> 16, 8);
1073 lzx_write_bits(os, block_size & 0xFFFF, 16);
1076 /* If it's an aligned offset block, output the aligned offset code. */
1077 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1078 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1079 lzx_write_bits(os, codes->lens.aligned[i],
1080 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1084 /* Output the main code (two parts). */
1085 lzx_write_compressed_code(os, codes->lens.main,
1088 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1089 prev_lens->main + LZX_NUM_CHARS,
1090 num_main_syms - LZX_NUM_CHARS);
1092 /* Output the length code. */
1093 lzx_write_compressed_code(os, codes->lens.len,
1095 LZX_LENCODE_NUM_SYMBOLS);
1097 /* Output the compressed matches and literals. */
1098 lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1101 /* Given the frequencies of symbols in an LZX-compressed block and the
1102 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1103 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1104 * will take fewer bits to output. */
1106 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1107 const struct lzx_codes * codes)
1109 u32 aligned_cost = 0;
1110 u32 verbatim_cost = 0;
1112 /* A verbatim block requires 3 bits in each place that an aligned symbol
1113 * would be used in an aligned offset block. */
1114 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1115 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1116 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1119 /* Account for output of the aligned offset code. */
1120 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1122 if (aligned_cost < verbatim_cost)
1123 return LZX_BLOCKTYPE_ALIGNED;
1125 return LZX_BLOCKTYPE_VERBATIM;
1129 * Return the offset slot for the specified adjusted match offset, using the
1130 * compressor's acceleration tables to speed up the mapping.
1132 static inline unsigned
1133 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1136 if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1137 return c->offset_slot_tab_1[adjusted_offset];
1138 return c->offset_slot_tab_2[adjusted_offset >> 14];
1142 * Finish an LZX block:
1144 * - build the Huffman codes
1145 * - decide whether to output the block as VERBATIM or ALIGNED
1146 * - output the block
1147 * - swap the indices of the current and previous Huffman codes
1150 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1151 const u8 *block_begin, u32 block_size, u32 seq_idx)
1155 lzx_make_huffman_codes(c);
1157 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1158 &c->codes[c->codes_index]);
1159 lzx_write_compressed_block(block_begin,
1164 &c->chosen_sequences[seq_idx],
1165 &c->codes[c->codes_index],
1166 &c->codes[c->codes_index ^ 1].lens,
1168 c->codes_index ^= 1;
1171 /* Tally the Huffman symbol for a literal and increment the literal run length.
1174 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1176 c->freqs.main[literal]++;
1180 /* Tally the Huffman symbol for a match, save the match data and the length of
1181 * the preceding literal run in the next lzx_sequence, and update the recent
1184 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1185 u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1186 u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1188 u32 litrunlen = *litrunlen_p;
1189 struct lzx_sequence *next_seq = *next_seq_p;
1190 unsigned offset_slot;
1193 v = length - LZX_MIN_MATCH_LEN;
1195 /* Save the literal run length and adjusted length. */
1196 next_seq->litrunlen = litrunlen;
1197 next_seq->adjusted_length = v;
1199 /* Compute the length header and tally the length symbol if needed */
1200 if (v >= LZX_NUM_PRIMARY_LENS) {
1201 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1202 v = LZX_NUM_PRIMARY_LENS;
1205 /* Compute the offset slot */
1206 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1208 /* Compute the match header. */
1209 v += offset_slot * LZX_NUM_LEN_HEADERS;
1211 /* Save the adjusted offset and match header. */
1212 next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1214 /* Tally the main symbol. */
1215 c->freqs.main[LZX_NUM_CHARS + v]++;
1217 /* Update the recent offsets queue. */
1218 if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1219 /* Repeat offset match */
1220 swap(recent_offsets[0], recent_offsets[offset_data]);
1222 /* Explicit offset match */
1224 /* Tally the aligned offset symbol if needed */
1225 if (offset_data >= 16)
1226 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1228 recent_offsets[2] = recent_offsets[1];
1229 recent_offsets[1] = recent_offsets[0];
1230 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1233 /* Reset the literal run length and advance to the next sequence. */
1234 *next_seq_p = next_seq + 1;
1238 /* Finish the last lzx_sequence. The last lzx_sequence is just a literal run;
1239 * there is no match. This literal run may be empty. */
1241 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1243 last_seq->litrunlen = litrunlen;
1245 /* Special value to mark last sequence */
1246 last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1249 /******************************************************************************/
1252 * Block splitting algorithm. The problem is to decide when it is worthwhile to
1253 * start a new block with new entropy codes. There is a theoretically optimal
1254 * solution: recursively consider every possible block split, considering the
1255 * exact cost of each block, and choose the minimum cost approach. But this is
1256 * far too slow. Instead, as an approximation, we can count symbols and after
1257 * every N symbols, compare the expected distribution of symbols based on the
1258 * previous data with the actual distribution. If they differ "by enough", then
1259 * start a new block.
1261 * As an optimization and heuristic, we don't distinguish between every symbol
1262 * but rather we combine many symbols into a single "observation type". For
1263 * literals we only look at the high bits and low bits, and for matches we only
1264 * look at whether the match is long or not. The assumption is that for typical
1265 * "real" data, places that are good block boundaries will tend to be noticable
1266 * based only on changes in these aggregate frequencies, without looking for
1267 * subtle differences in individual symbols. For example, a change from ASCII
1268 * bytes to non-ASCII bytes, or from few matches (generally less compressible)
1269 * to many matches (generally more compressible), would be easily noticed based
1270 * on the aggregates.
1272 * For determining whether the frequency distributions are "different enough" to
1273 * start a new block, the simply heuristic of splitting when the sum of absolute
1274 * differences exceeds a constant seems to be good enough. We also add a number
1275 * proportional to the block size so that the algorithm is more likely to end
1276 * large blocks than small blocks. This reflects the general expectation that
1277 * it will become increasingly beneficial to start a new block as the current
1278 * blocks grows larger.
1280 * Finally, for an approximation, it is not strictly necessary that the exact
1281 * symbols being used are considered. With "near-optimal parsing", for example,
1282 * the actual symbols that will be used are unknown until after the block
1283 * boundary is chosen and the block has been optimized. Since the final choices
1284 * cannot be used, we can use preliminary "greedy" choices instead.
1287 /* Initialize the block split statistics when starting a new block. */
1289 init_block_split_stats(struct block_split_stats *stats)
1291 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1292 stats->new_observations[i] = 0;
1293 stats->observations[i] = 0;
1295 stats->num_new_observations = 0;
1296 stats->num_observations = 0;
1299 /* Literal observation. Heuristic: use the top 2 bits and low 1 bits of the
1300 * literal, for 8 possible literal observation types. */
1302 observe_literal(struct block_split_stats *stats, u8 lit)
1304 stats->new_observations[((lit >> 5) & 0x6) | (lit & 1)]++;
1305 stats->num_new_observations++;
1308 /* Match observation. Heuristic: use one observation type for "short match" and
1309 * one observation type for "long match". */
1311 observe_match(struct block_split_stats *stats, unsigned length)
1313 stats->new_observations[NUM_LITERAL_OBSERVATION_TYPES + (length >= 5)]++;
1314 stats->num_new_observations++;
1318 do_end_block_check(struct block_split_stats *stats, u32 block_size)
1320 if (stats->num_observations > 0) {
1322 /* Note: to avoid slow divisions, we do not divide by
1323 * 'num_observations', but rather do all math with the numbers
1324 * multiplied by 'num_observations'. */
1325 u32 total_delta = 0;
1326 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1327 u32 expected = stats->observations[i] * stats->num_new_observations;
1328 u32 actual = stats->new_observations[i] * stats->num_observations;
1329 u32 delta = (actual > expected) ? actual - expected :
1331 total_delta += delta;
1334 /* Ready to end the block? */
1335 if (total_delta + (block_size / 1024) * stats->num_observations >=
1336 stats->num_new_observations * 51 / 64 * stats->num_observations)
1340 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1341 stats->num_observations += stats->new_observations[i];
1342 stats->observations[i] += stats->new_observations[i];
1343 stats->new_observations[i] = 0;
1345 stats->num_new_observations = 0;
1350 should_end_block(struct block_split_stats *stats,
1351 const u8 *in_block_begin, const u8 *in_next, const u8 *in_end)
1353 /* Ready to check block split statistics? */
1354 if (stats->num_new_observations < NUM_OBSERVATIONS_PER_BLOCK_CHECK ||
1355 in_next - in_block_begin < MIN_BLOCK_SIZE ||
1356 in_end - in_next < MIN_BLOCK_SIZE)
1359 return do_end_block_check(stats, in_next - in_block_begin);
1362 /******************************************************************************/
1365 * Given the minimum-cost path computed through the item graph for the current
1366 * block, walk the path and count how many of each symbol in each Huffman-coded
1367 * alphabet would be required to output the items (matches and literals) along
1370 * Note that the path will be walked backwards (from the end of the block to the
1371 * beginning of the block), but this doesn't matter because this function only
1372 * computes frequencies.
1375 lzx_tally_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1377 u32 node_idx = block_size;
1384 unsigned offset_slot;
1386 /* Tally literals until either a match or the beginning of the
1387 * block is reached. */
1389 item = c->optimum_nodes[node_idx].item;
1390 if (item & OPTIMUM_LEN_MASK)
1392 c->freqs.main[item >> OPTIMUM_OFFSET_SHIFT]++;
1396 if (item & OPTIMUM_EXTRA_FLAG) {
1401 /* Tally a rep0 match. */
1402 len = item & OPTIMUM_LEN_MASK;
1403 v = len - LZX_MIN_MATCH_LEN;
1404 if (v >= LZX_NUM_PRIMARY_LENS) {
1405 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1406 v = LZX_NUM_PRIMARY_LENS;
1408 c->freqs.main[LZX_NUM_CHARS + v]++;
1410 /* Tally a literal. */
1411 c->freqs.main[c->optimum_nodes[node_idx].extra_literal]++;
1413 item = c->optimum_nodes[node_idx].extra_match;
1414 node_idx -= len + 1;
1417 len = item & OPTIMUM_LEN_MASK;
1418 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1422 /* Tally a match. */
1424 /* Tally the aligned offset symbol if needed. */
1425 if (offset_data >= 16)
1426 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1428 /* Tally the length symbol if needed. */
1429 v = len - LZX_MIN_MATCH_LEN;;
1430 if (v >= LZX_NUM_PRIMARY_LENS) {
1431 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1432 v = LZX_NUM_PRIMARY_LENS;
1435 /* Tally the main symbol. */
1436 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1437 v += offset_slot * LZX_NUM_LEN_HEADERS;
1438 c->freqs.main[LZX_NUM_CHARS + v]++;
1443 * Like lzx_tally_item_list(), but this function also generates the list of
1444 * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1445 * ready to be output to the bitstream after the Huffman codes are computed.
1446 * The lzx_sequences will be written to decreasing memory addresses as the path
1447 * is walked backwards, which means they will end up in the expected
1448 * first-to-last order. The return value is the index in c->chosen_sequences at
1449 * which the lzx_sequences begin.
1452 lzx_record_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1454 u32 node_idx = block_size;
1455 u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1458 /* Special value to mark last sequence */
1459 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1461 lit_start_node = node_idx;
1467 unsigned offset_slot;
1469 /* Tally literals until either a match or the beginning of the
1470 * block is reached. */
1472 item = c->optimum_nodes[node_idx].item;
1473 if (item & OPTIMUM_LEN_MASK)
1475 c->freqs.main[item >> OPTIMUM_OFFSET_SHIFT]++;
1479 if (item & OPTIMUM_EXTRA_FLAG) {
1484 /* Save the literal run length for the next sequence
1485 * (the "previous sequence" when walking backwards). */
1486 len = item & OPTIMUM_LEN_MASK;
1487 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1489 lit_start_node = node_idx - len;
1491 /* Tally a rep0 match. */
1492 v = len - LZX_MIN_MATCH_LEN;
1493 c->chosen_sequences[seq_idx].adjusted_length = v;
1494 if (v >= LZX_NUM_PRIMARY_LENS) {
1495 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1496 v = LZX_NUM_PRIMARY_LENS;
1498 c->freqs.main[LZX_NUM_CHARS + v]++;
1499 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = v;
1501 /* Tally a literal. */
1502 c->freqs.main[c->optimum_nodes[node_idx].extra_literal]++;
1504 item = c->optimum_nodes[node_idx].extra_match;
1505 node_idx -= len + 1;
1508 len = item & OPTIMUM_LEN_MASK;
1509 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1511 /* Save the literal run length for the next sequence (the
1512 * "previous sequence" when walking backwards). */
1513 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1515 lit_start_node = node_idx;
1517 /* Record a match. */
1519 /* Tally the aligned offset symbol if needed. */
1520 if (offset_data >= 16)
1521 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1523 /* Save the adjusted length. */
1524 v = len - LZX_MIN_MATCH_LEN;
1525 c->chosen_sequences[seq_idx].adjusted_length = v;
1527 /* Tally the length symbol if needed. */
1528 if (v >= LZX_NUM_PRIMARY_LENS) {
1529 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1530 v = LZX_NUM_PRIMARY_LENS;
1533 /* Tally the main symbol. */
1534 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1535 v += offset_slot * LZX_NUM_LEN_HEADERS;
1536 c->freqs.main[LZX_NUM_CHARS + v]++;
1538 /* Save the adjusted offset and match header. */
1539 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1540 (offset_data << 9) | v;
1543 /* Save the literal run length for the first sequence. */
1544 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1546 /* Return the index in c->chosen_sequences at which the lzx_sequences
1552 * Find an inexpensive path through the graph of possible match/literal choices
1553 * for the current block. The nodes of the graph are
1554 * c->optimum_nodes[0...block_size]. They correspond directly to the bytes in
1555 * the current block, plus one extra node for end-of-block. The edges of the
1556 * graph are matches and literals. The goal is to find the minimum cost path
1557 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1559 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1560 * proceeding forwards one node at a time. At each node, a selection of matches
1561 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1562 * length 'len' provides a new path to reach the node 'len' bytes later. If
1563 * such a path is the lowest cost found so far to reach that later node, then
1564 * that later node is updated with the new path.
1566 * Note that although this algorithm is based on minimum cost path search, due
1567 * to various simplifying assumptions the result is not guaranteed to be the
1568 * true minimum cost, or "optimal", path over the graph of all valid LZX
1569 * representations of this block.
1571 * Also, note that because of the presence of the recent offsets queue (which is
1572 * a type of adaptive state), the algorithm cannot work backwards and compute
1573 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1574 * algorithm handles this adaptive state in the "minimum cost" parse is actually
1575 * only an approximation. It's possible for the globally optimal, minimum cost
1576 * path to contain a prefix, ending at a position, where that path prefix is
1577 * *not* the minimum cost path to that position. This can happen if such a path
1578 * prefix results in a different adaptive state which results in lower costs
1579 * later. The algorithm does not solve this problem; it only considers the
1580 * lowest cost to reach each individual position.
1582 static inline struct lzx_lru_queue
1583 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1584 const u8 * const restrict block_begin,
1585 const u32 block_size,
1586 const struct lzx_lru_queue initial_queue,
1589 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1590 struct lz_match *cache_ptr = c->match_cache;
1591 const u8 *in_next = block_begin;
1592 const u8 * const block_end = block_begin + block_size;
1594 /* Instead of storing the match offset LRU queues in the
1595 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1596 * storing them in a smaller array. This works because the algorithm
1597 * only requires a limited history of the adaptive state. Once a given
1598 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1599 * it is no longer needed. */
1600 struct lzx_lru_queue queues[512];
1602 STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1603 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1605 /* Initially, the cost to reach each node is "infinity". */
1606 memset(c->optimum_nodes, 0xFF,
1607 (block_size + 1) * sizeof(c->optimum_nodes[0]));
1609 QUEUE(block_begin) = initial_queue;
1611 /* The following loop runs 'block_size' iterations, one per node. */
1613 unsigned num_matches;
1618 * A selection of matches for the block was already saved in
1619 * memory so that we don't have to run the uncompressed data
1620 * through the matchfinder on every optimization pass. However,
1621 * we still search for repeat offset matches during each
1622 * optimization pass because we cannot predict the state of the
1623 * recent offsets queue. But as a heuristic, we don't bother
1624 * searching for repeat offset matches if the general-purpose
1625 * matchfinder failed to find any matches.
1627 * Note that a match of length n at some offset implies there is
1628 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1629 * that same offset. In other words, we don't necessarily need
1630 * to use the full length of a match. The key heuristic that
1631 * saves a significicant amount of time is that for each
1632 * distinct length, we only consider the smallest offset for
1633 * which that length is available. This heuristic also applies
1634 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1635 * any explicit offset. Of course, this heuristic may be
1636 * produce suboptimal results because offset slots in LZX are
1637 * subject to entropy encoding, but in practice this is a useful
1641 num_matches = cache_ptr->length;
1645 struct lz_match *end_matches = cache_ptr + num_matches;
1646 unsigned next_len = LZX_MIN_MATCH_LEN;
1647 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1650 /* Consider R0 match */
1651 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1652 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1654 STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1656 u32 cost = cur_node->cost +
1657 c->costs.match_cost[0][
1658 next_len - LZX_MIN_MATCH_LEN];
1659 if (cost <= (cur_node + next_len)->cost) {
1660 (cur_node + next_len)->cost = cost;
1661 (cur_node + next_len)->item =
1662 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1664 if (unlikely(++next_len > max_len)) {
1665 cache_ptr = end_matches;
1668 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1672 /* Consider R1 match */
1673 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1674 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1676 if (matchptr[next_len - 1] != in_next[next_len - 1])
1678 for (unsigned len = 2; len < next_len - 1; len++)
1679 if (matchptr[len] != in_next[len])
1682 u32 cost = cur_node->cost +
1683 c->costs.match_cost[1][
1684 next_len - LZX_MIN_MATCH_LEN];
1685 if (cost <= (cur_node + next_len)->cost) {
1686 (cur_node + next_len)->cost = cost;
1687 (cur_node + next_len)->item =
1688 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1690 if (unlikely(++next_len > max_len)) {
1691 cache_ptr = end_matches;
1694 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1698 /* Consider R2 match */
1699 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1700 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1702 if (matchptr[next_len - 1] != in_next[next_len - 1])
1704 for (unsigned len = 2; len < next_len - 1; len++)
1705 if (matchptr[len] != in_next[len])
1708 u32 cost = cur_node->cost +
1709 c->costs.match_cost[2][
1710 next_len - LZX_MIN_MATCH_LEN];
1711 if (cost <= (cur_node + next_len)->cost) {
1712 (cur_node + next_len)->cost = cost;
1713 (cur_node + next_len)->item =
1714 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1716 if (unlikely(++next_len > max_len)) {
1717 cache_ptr = end_matches;
1720 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1724 while (next_len > cache_ptr->length)
1725 if (++cache_ptr == end_matches)
1728 /* Consider explicit offset matches */
1730 u32 offset = cache_ptr->offset;
1731 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1732 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1734 u32 base_cost = cur_node->cost;
1737 #if LZX_CONSIDER_ALIGNED_COSTS
1738 if (offset_data >= 16)
1739 base_cost += c->costs.aligned[offset_data &
1740 LZX_ALIGNED_OFFSET_BITMASK];
1744 c->costs.match_cost[offset_slot][
1745 next_len - LZX_MIN_MATCH_LEN];
1746 if (cost < (cur_node + next_len)->cost) {
1747 (cur_node + next_len)->cost = cost;
1748 (cur_node + next_len)->item =
1749 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1751 } while (++next_len <= cache_ptr->length);
1753 if (++cache_ptr == end_matches) {
1754 /* Consider match + lit + rep0 */
1755 u32 remaining = block_end - (in_next + next_len);
1756 if (likely(remaining >= 2)) {
1757 const u8 *strptr = in_next + next_len;
1758 const u8 *matchptr = strptr - offset;
1759 if (unlikely(load_u16_unaligned(strptr) == load_u16_unaligned(matchptr))) {
1760 u32 rep0_len = lz_extend(strptr, matchptr, 2,
1761 min(remaining, LZX_MAX_MATCH_LEN));
1762 u8 lit = strptr[-1];
1763 cost += c->costs.main[lit] +
1764 c->costs.match_cost[0][rep0_len - LZX_MIN_MATCH_LEN];
1765 u32 total_len = next_len + rep0_len;
1766 if (cost < (cur_node + total_len)->cost) {
1767 (cur_node + total_len)->cost = cost;
1768 (cur_node + total_len)->item =
1769 OPTIMUM_EXTRA_FLAG | rep0_len;
1770 (cur_node + total_len)->extra_literal = lit;
1771 (cur_node + total_len)->extra_match =
1772 (offset_data << OPTIMUM_OFFSET_SHIFT) | (next_len - 1);
1783 /* Consider coding a literal.
1785 * To avoid an extra branch, actually checking the preferability
1786 * of coding the literal is integrated into the queue update
1788 literal = *in_next++;
1789 cost = cur_node->cost + c->costs.main[literal];
1791 /* Advance to the next position. */
1794 /* The lowest-cost path to the current position is now known.
1795 * Finalize the recent offsets queue that results from taking
1796 * this lowest-cost path. */
1798 if (cost <= cur_node->cost) {
1799 /* Literal: queue remains unchanged. */
1800 cur_node->cost = cost;
1801 cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1802 QUEUE(in_next) = QUEUE(in_next - 1);
1804 /* Match: queue update is needed. */
1805 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1806 u32 offset_data = (cur_node->item &
1807 ~OPTIMUM_EXTRA_FLAG) >> OPTIMUM_OFFSET_SHIFT;
1808 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1809 /* Explicit offset match: insert offset at front */
1811 lzx_lru_queue_push(QUEUE(in_next - len),
1812 offset_data - LZX_OFFSET_ADJUSTMENT);
1813 } else if (cur_node->item & OPTIMUM_EXTRA_FLAG) {
1814 /* Explicit offset match, then literal, then
1815 * rep0 match: insert offset at front */
1816 len += 1 + (cur_node->extra_match & OPTIMUM_LEN_MASK);
1818 lzx_lru_queue_push(QUEUE(in_next - len),
1819 (cur_node->extra_match >> OPTIMUM_OFFSET_SHIFT) -
1820 LZX_OFFSET_ADJUSTMENT);
1822 /* Repeat offset match: swap offset to front */
1824 lzx_lru_queue_swap(QUEUE(in_next - len),
1828 } while (in_next != block_end);
1830 /* Return the match offset queue at the end of the minimum cost path. */
1831 return QUEUE(block_end);
1834 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1836 lzx_compute_match_costs(struct lzx_compressor *c)
1838 unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1839 LZX_NUM_LEN_HEADERS;
1840 struct lzx_costs *costs = &c->costs;
1842 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1844 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1845 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1846 LZX_NUM_LEN_HEADERS);
1849 #if LZX_CONSIDER_ALIGNED_COSTS
1850 if (offset_slot >= 8)
1851 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1854 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1855 costs->match_cost[offset_slot][i] =
1856 costs->main[main_symbol++] + extra_cost;
1858 extra_cost += costs->main[main_symbol];
1860 for (; i < LZX_NUM_LENS; i++)
1861 costs->match_cost[offset_slot][i] =
1862 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1866 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1869 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1872 bool have_byte[256];
1873 unsigned num_used_bytes;
1875 /* The costs below are hard coded to use a scaling factor of 64. */
1876 STATIC_ASSERT(LZX_BIT_COST == 64);
1881 * - Use smaller initial costs for literal symbols when the input buffer
1882 * contains fewer distinct bytes.
1884 * - Assume that match symbols are more costly than literal symbols.
1886 * - Assume that length symbols for shorter lengths are less costly than
1887 * length symbols for longer lengths.
1890 for (i = 0; i < 256; i++)
1891 have_byte[i] = false;
1893 for (i = 0; i < block_size; i++)
1894 have_byte[block[i]] = true;
1897 for (i = 0; i < 256; i++)
1898 num_used_bytes += have_byte[i];
1900 for (i = 0; i < 256; i++)
1901 c->costs.main[i] = 560 - (256 - num_used_bytes);
1903 for (; i < c->num_main_syms; i++)
1904 c->costs.main[i] = 680;
1906 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1907 c->costs.len[i] = 412 + i;
1909 #if LZX_CONSIDER_ALIGNED_COSTS
1910 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1911 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1914 lzx_compute_match_costs(c);
1917 /* Update the current cost model to reflect the computed Huffman codes. */
1919 lzx_update_costs(struct lzx_compressor *c)
1922 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1924 for (i = 0; i < c->num_main_syms; i++) {
1925 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1926 MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1929 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1930 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1931 LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1934 #if LZX_CONSIDER_ALIGNED_COSTS
1935 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1936 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1937 ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1941 lzx_compute_match_costs(c);
1944 static inline struct lzx_lru_queue
1945 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1946 struct lzx_output_bitstream * const restrict os,
1947 const u8 * const restrict block_begin,
1948 const u32 block_size,
1949 const struct lzx_lru_queue initial_queue,
1952 unsigned num_passes_remaining = c->num_optim_passes;
1953 struct lzx_lru_queue new_queue;
1956 /* The first optimization pass uses a default cost model. Each
1957 * additional optimization pass uses a cost model derived from the
1958 * Huffman code computed in the previous pass. */
1960 lzx_set_default_costs(c, block_begin, block_size);
1961 lzx_reset_symbol_frequencies(c);
1963 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1964 initial_queue, is_16_bit);
1965 if (num_passes_remaining > 1) {
1966 lzx_tally_item_list(c, block_size, is_16_bit);
1967 lzx_make_huffman_codes(c);
1968 lzx_update_costs(c);
1969 lzx_reset_symbol_frequencies(c);
1971 } while (--num_passes_remaining);
1973 seq_idx = lzx_record_item_list(c, block_size, is_16_bit);
1974 lzx_finish_block(c, os, block_begin, block_size, seq_idx);
1979 * This is the "near-optimal" LZX compressor.
1981 * For each block, it performs a relatively thorough graph search to find an
1982 * inexpensive (in terms of compressed size) way to output that block.
1984 * Note: there are actually many things this algorithm leaves on the table in
1985 * terms of compression ratio. So although it may be "near-optimal", it is
1986 * certainly not "optimal". The goal is not to produce the optimal compression
1987 * ratio, which for LZX is probably impossible within any practical amount of
1988 * time, but rather to produce a compression ratio significantly better than a
1989 * simpler "greedy" or "lazy" parse while still being relatively fast.
1992 lzx_compress_near_optimal(struct lzx_compressor * restrict c,
1993 const u8 * const restrict in_begin,
1994 struct lzx_output_bitstream * restrict os,
1997 const u8 * in_next = in_begin;
1998 const u8 * const in_end = in_begin + c->in_nbytes;
1999 u32 max_len = LZX_MAX_MATCH_LEN;
2000 u32 nice_len = min(c->nice_match_length, max_len);
2001 u32 next_hashes[2] = {};
2002 struct lzx_lru_queue queue;
2004 CALL_BT_MF(is_16_bit, c, bt_matchfinder_init);
2005 lzx_lru_queue_init(&queue);
2008 /* Starting a new block */
2009 const u8 * const in_block_begin = in_next;
2010 const u8 * const in_max_block_end =
2011 in_next + min(SOFT_MAX_BLOCK_SIZE, in_end - in_next);
2012 const u8 *next_observation = in_next;
2014 init_block_split_stats(&c->split_stats);
2016 /* Run the block through the matchfinder and cache the matches. */
2017 struct lz_match *cache_ptr = c->match_cache;
2019 struct lz_match *lz_matchptr;
2022 /* If approaching the end of the input buffer, adjust
2023 * 'max_len' and 'nice_len' accordingly. */
2024 if (unlikely(max_len > in_end - in_next)) {
2025 max_len = in_end - in_next;
2026 nice_len = min(max_len, nice_len);
2027 if (unlikely(max_len <
2028 BT_MATCHFINDER_REQUIRED_NBYTES))
2031 cache_ptr->length = 0;
2037 /* Check for matches. */
2038 lz_matchptr = CALL_BT_MF(is_16_bit, c,
2039 bt_matchfinder_get_matches,
2044 c->max_search_depth,
2049 cache_ptr->length = lz_matchptr - (cache_ptr + 1);
2050 cache_ptr = lz_matchptr;
2052 if (in_next >= next_observation) {
2053 best_len = cache_ptr[-1].length;
2055 observe_match(&c->split_stats, best_len);
2056 next_observation = in_next + best_len;
2058 observe_literal(&c->split_stats, *in_next);
2059 next_observation = in_next + 1;
2066 * If there was a very long match found, then don't
2067 * cache any matches for the bytes covered by that
2068 * match. This avoids degenerate behavior when
2069 * compressing highly redundant data, where the number
2070 * of matches can be very large.
2072 * This heuristic doesn't actually hurt the compression
2073 * ratio very much. If there's a long match, then the
2074 * data must be highly compressible, so it doesn't
2075 * matter as much what we do.
2077 if (best_len >= nice_len) {
2080 if (unlikely(max_len > in_end - in_next)) {
2081 max_len = in_end - in_next;
2082 nice_len = min(max_len, nice_len);
2083 if (unlikely(max_len <
2084 BT_MATCHFINDER_REQUIRED_NBYTES))
2087 cache_ptr->length = 0;
2092 CALL_BT_MF(is_16_bit, c,
2093 bt_matchfinder_skip_position,
2097 c->max_search_depth,
2100 cache_ptr->length = 0;
2102 } while (--best_len);
2104 } while (in_next < in_max_block_end &&
2105 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]) &&
2106 !should_end_block(&c->split_stats, in_block_begin, in_next, in_end));
2108 /* We've finished running the block through the matchfinder.
2109 * Now choose a match/literal sequence and write the block. */
2111 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
2112 in_next - in_block_begin,
2114 } while (in_next != in_end);
2118 lzx_compress_near_optimal_16(struct lzx_compressor *c,
2119 struct lzx_output_bitstream *os)
2121 lzx_compress_near_optimal(c, c->in_buffer, os, true);
2125 lzx_compress_near_optimal_32(struct lzx_compressor *c,
2126 struct lzx_output_bitstream *os)
2128 lzx_compress_near_optimal(c, c->in_buffer, os, false);
2132 * Given a pointer to the current byte sequence and the current list of recent
2133 * match offsets, find the longest repeat offset match.
2135 * If no match of at least 2 bytes is found, then return 0.
2137 * If a match of at least 2 bytes is found, then return its length and set
2138 * *rep_max_idx_ret to the index of its offset in @queue.
2141 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
2142 const u32 bytes_remaining,
2143 const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
2144 unsigned *rep_max_idx_ret)
2146 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2148 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
2149 const u16 next_2_bytes = load_u16_unaligned(in_next);
2151 unsigned rep_max_len;
2152 unsigned rep_max_idx;
2155 matchptr = in_next - recent_offsets[0];
2156 if (load_u16_unaligned(matchptr) == next_2_bytes)
2157 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
2162 matchptr = in_next - recent_offsets[1];
2163 if (load_u16_unaligned(matchptr) == next_2_bytes) {
2164 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2165 if (rep_len > rep_max_len) {
2166 rep_max_len = rep_len;
2171 matchptr = in_next - recent_offsets[2];
2172 if (load_u16_unaligned(matchptr) == next_2_bytes) {
2173 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2174 if (rep_len > rep_max_len) {
2175 rep_max_len = rep_len;
2180 *rep_max_idx_ret = rep_max_idx;
2184 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
2185 static inline unsigned
2186 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
2188 unsigned score = len;
2190 if (adjusted_offset < 4096)
2193 if (adjusted_offset < 256)
2199 static inline unsigned
2200 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
2205 /* This is the "lazy" LZX compressor. */
2207 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
2210 const u8 * const in_begin = c->in_buffer;
2211 const u8 * in_next = in_begin;
2212 const u8 * const in_end = in_begin + c->in_nbytes;
2213 unsigned max_len = LZX_MAX_MATCH_LEN;
2214 unsigned nice_len = min(c->nice_match_length, max_len);
2215 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2216 u32 recent_offsets[3] = {1, 1, 1};
2217 u32 next_hashes[2] = {};
2219 CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2222 /* Starting a new block */
2224 const u8 * const in_block_begin = in_next;
2225 const u8 * const in_max_block_end =
2226 in_next + min(SOFT_MAX_BLOCK_SIZE, in_end - in_next);
2227 struct lzx_sequence *next_seq = c->chosen_sequences;
2230 u32 cur_offset_data;
2234 u32 next_offset_data;
2235 unsigned next_score;
2236 unsigned rep_max_len;
2237 unsigned rep_max_idx;
2242 lzx_reset_symbol_frequencies(c);
2243 init_block_split_stats(&c->split_stats);
2246 if (unlikely(max_len > in_end - in_next)) {
2247 max_len = in_end - in_next;
2248 nice_len = min(max_len, nice_len);
2251 /* Find the longest match at the current position. */
2253 cur_len = CALL_HC_MF(is_16_bit, c,
2254 hc_matchfinder_longest_match,
2260 c->max_search_depth,
2265 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2266 cur_offset != recent_offsets[0] &&
2267 cur_offset != recent_offsets[1] &&
2268 cur_offset != recent_offsets[2]))
2270 /* There was no match found, or the only match found
2271 * was a distant length 3 match. Output a literal. */
2272 lzx_record_literal(c, *in_next, &litrunlen);
2273 observe_literal(&c->split_stats, *in_next);
2278 observe_match(&c->split_stats, cur_len);
2280 if (cur_offset == recent_offsets[0]) {
2282 cur_offset_data = 0;
2283 skip_len = cur_len - 1;
2284 goto choose_cur_match;
2287 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2288 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2290 /* Consider a repeat offset match */
2291 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2297 if (rep_max_len >= 3 &&
2298 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2299 rep_max_idx)) >= cur_score)
2301 cur_len = rep_max_len;
2302 cur_offset_data = rep_max_idx;
2303 skip_len = rep_max_len - 1;
2304 goto choose_cur_match;
2309 /* We have a match at the current position. */
2311 /* If we have a very long match, choose it immediately. */
2312 if (cur_len >= nice_len) {
2313 skip_len = cur_len - 1;
2314 goto choose_cur_match;
2317 /* See if there's a better match at the next position. */
2319 if (unlikely(max_len > in_end - in_next)) {
2320 max_len = in_end - in_next;
2321 nice_len = min(max_len, nice_len);
2324 next_len = CALL_HC_MF(is_16_bit, c,
2325 hc_matchfinder_longest_match,
2331 c->max_search_depth / 2,
2335 if (next_len <= cur_len - 2) {
2337 skip_len = cur_len - 2;
2338 goto choose_cur_match;
2341 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2342 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2344 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2350 if (rep_max_len >= 3 &&
2351 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2352 rep_max_idx)) >= next_score)
2355 if (rep_score > cur_score) {
2356 /* The next match is better, and it's a
2357 * repeat offset match. */
2358 lzx_record_literal(c, *(in_next - 2),
2360 cur_len = rep_max_len;
2361 cur_offset_data = rep_max_idx;
2362 skip_len = cur_len - 1;
2363 goto choose_cur_match;
2366 if (next_score > cur_score) {
2367 /* The next match is better, and it's an
2368 * explicit offset match. */
2369 lzx_record_literal(c, *(in_next - 2),
2372 cur_offset_data = next_offset_data;
2373 cur_score = next_score;
2374 goto have_cur_match;
2378 /* The original match was better. */
2379 skip_len = cur_len - 2;
2382 lzx_record_match(c, cur_len, cur_offset_data,
2383 recent_offsets, is_16_bit,
2384 &litrunlen, &next_seq);
2385 in_next = CALL_HC_MF(is_16_bit, c,
2386 hc_matchfinder_skip_positions,
2392 } while (in_next < in_max_block_end &&
2393 !should_end_block(&c->split_stats, in_block_begin, in_next, in_end));
2395 lzx_finish_sequence(next_seq, litrunlen);
2397 lzx_finish_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2399 } while (in_next != in_end);
2403 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2405 lzx_compress_lazy(c, os, true);
2409 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2411 lzx_compress_lazy(c, os, false);
2414 /* Generate the acceleration tables for offset slots. */
2416 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2418 u32 adjusted_offset = 0;
2422 for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2425 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2427 c->offset_slot_tab_1[adjusted_offset] = slot;
2430 /* slots [30, 49] */
2431 for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2432 adjusted_offset += (u32)1 << 14)
2434 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2436 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2441 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2443 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2444 if (lzx_is_16_bit(max_bufsize))
2445 return offsetof(struct lzx_compressor, hc_mf_16) +
2446 hc_matchfinder_size_16(max_bufsize);
2448 return offsetof(struct lzx_compressor, hc_mf_32) +
2449 hc_matchfinder_size_32(max_bufsize);
2451 if (lzx_is_16_bit(max_bufsize))
2452 return offsetof(struct lzx_compressor, bt_mf_16) +
2453 bt_matchfinder_size_16(max_bufsize);
2455 return offsetof(struct lzx_compressor, bt_mf_32) +
2456 bt_matchfinder_size_32(max_bufsize);
2461 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2466 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2469 size += lzx_get_compressor_size(max_bufsize, compression_level);
2471 size += max_bufsize; /* in_buffer */
2476 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2477 bool destructive, void **c_ret)
2479 unsigned window_order;
2480 struct lzx_compressor *c;
2482 window_order = lzx_get_window_order(max_bufsize);
2483 if (window_order == 0)
2484 return WIMLIB_ERR_INVALID_PARAM;
2486 c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2490 c->destructive = destructive;
2492 c->num_main_syms = lzx_get_num_main_syms(window_order);
2493 c->window_order = window_order;
2495 if (!c->destructive) {
2496 c->in_buffer = MALLOC(max_bufsize);
2501 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2503 /* Fast compression: Use lazy parsing. */
2505 if (lzx_is_16_bit(max_bufsize))
2506 c->impl = lzx_compress_lazy_16;
2508 c->impl = lzx_compress_lazy_32;
2509 c->max_search_depth = (60 * compression_level) / 20;
2510 c->nice_match_length = (80 * compression_level) / 20;
2512 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2513 * halves the max_search_depth when attempting a lazy match, and
2514 * max_search_depth cannot be 0. */
2515 if (c->max_search_depth < 2)
2516 c->max_search_depth = 2;
2519 /* Normal / high compression: Use near-optimal parsing. */
2521 if (lzx_is_16_bit(max_bufsize))
2522 c->impl = lzx_compress_near_optimal_16;
2524 c->impl = lzx_compress_near_optimal_32;
2526 /* Scale nice_match_length and max_search_depth with the
2527 * compression level. */
2528 c->max_search_depth = (24 * compression_level) / 50;
2529 c->nice_match_length = (48 * compression_level) / 50;
2531 /* Set a number of optimization passes appropriate for the
2532 * compression level. */
2534 c->num_optim_passes = 1;
2536 if (compression_level >= 45)
2537 c->num_optim_passes++;
2539 /* Use more optimization passes for higher compression levels.
2540 * But the more passes there are, the less they help --- so
2541 * don't add them linearly. */
2542 if (compression_level >= 70) {
2543 c->num_optim_passes++;
2544 if (compression_level >= 100)
2545 c->num_optim_passes++;
2546 if (compression_level >= 150)
2547 c->num_optim_passes++;
2548 if (compression_level >= 200)
2549 c->num_optim_passes++;
2550 if (compression_level >= 300)
2551 c->num_optim_passes++;
2555 /* max_search_depth == 0 is invalid. */
2556 if (c->max_search_depth < 1)
2557 c->max_search_depth = 1;
2559 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2560 c->nice_match_length = LZX_MAX_MATCH_LEN;
2562 lzx_init_offset_slot_tabs(c);
2569 return WIMLIB_ERR_NOMEM;
2573 lzx_compress(const void *restrict in, size_t in_nbytes,
2574 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2576 struct lzx_compressor *c = _c;
2577 struct lzx_output_bitstream os;
2580 /* Don't bother trying to compress very small inputs. */
2581 if (in_nbytes < 100)
2584 /* Copy the input data into the internal buffer and preprocess it. */
2586 c->in_buffer = (void *)in;
2588 memcpy(c->in_buffer, in, in_nbytes);
2589 c->in_nbytes = in_nbytes;
2590 lzx_preprocess(c->in_buffer, in_nbytes);
2592 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2594 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2596 /* Initialize the output bitstream. */
2597 lzx_init_output(&os, out, out_nbytes_avail);
2599 /* Call the compression level-specific compress() function. */
2602 /* Flush the output bitstream and return the compressed size or 0. */
2603 result = lzx_flush_output(&os);
2604 if (!result && c->destructive)
2605 lzx_postprocess(c->in_buffer, c->in_nbytes);
2610 lzx_free_compressor(void *_c)
2612 struct lzx_compressor *c = _c;
2614 if (!c->destructive)
2619 const struct compressor_ops lzx_compressor_ops = {
2620 .get_needed_memory = lzx_get_needed_memory,
2621 .create_compressor = lzx_create_compressor,
2622 .compress = lzx_compress,
2623 .free_compressor = lzx_free_compressor,