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_LENGTH bytes,
69 * except if the last block has to be shorter.
71 #define MIN_BLOCK_LENGTH 6500
74 * The compressor attempts to end blocks after SOFT_MAX_BLOCK_LENGTH 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_LENGTH'th byte.
81 * - The lazy parser may choose a sequence of literals starting at the
82 * SOFT_MAX_BLOCK_LENGTH'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_LENGTH 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_LENGTH * 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 lengths 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/lcpit_matchfinder.h"
166 #include "wimlib/hc_matchfinder.h"
168 /* Matchfinders with 32-bit positions */
172 #define MF_SUFFIX _32
173 #include "wimlib/lcpit_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_LENGTH, 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_LENGTH - 1, producing a block of length
463 * SOFT_MAX_BLOCK_LENGTH - 1 + LZX_MAX_MATCH_LEN. Add one
464 * for the end-of-block node.
466 struct lzx_optimum_node optimum_nodes[SOFT_MAX_BLOCK_LENGTH - 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 struct lcpit_matchfinder lcpit_mf;
505 * Will a matchfinder using 16-bit positions be sufficient for compressing
506 * buffers of up to the specified size? The limit could be 65536 bytes, but we
507 * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
508 * This requires that the limit be no more than the length of offset_slot_tab_1
512 lzx_is_16_bit(size_t max_bufsize)
514 STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
515 return max_bufsize <= 32768;
519 * The following macros call either the 16-bit or the 32-bit version of a
520 * matchfinder function based on the value of 'is_16_bit', which will be known
521 * at compilation time.
524 #define CALL_HC_MF(is_16_bit, c, funcname, ...) \
525 ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
526 CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
529 * Structure to keep track of the current state of sending bits to the
530 * compressed output buffer.
532 * The LZX bitstream is encoded as a sequence of 16-bit coding units.
534 struct lzx_output_bitstream {
536 /* Bits that haven't yet been written to the output buffer. */
537 machine_word_t bitbuf;
539 /* Number of bits currently held in @bitbuf. */
542 /* Pointer to the start of the output buffer. */
545 /* Pointer to the position in the output buffer at which the next coding
546 * unit should be written. */
549 /* Pointer just past the end of the output buffer, rounded down to a
550 * 2-byte boundary. */
554 /* Can the specified number of bits always be added to 'bitbuf' after any
555 * pending 16-bit coding units have been flushed? */
556 #define CAN_BUFFER(n) ((n) <= (8 * sizeof(machine_word_t)) - 15)
559 * Initialize the output bitstream.
562 * The output bitstream structure to initialize.
564 * The buffer being written to.
566 * Size of @buffer, in bytes.
569 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
574 os->next = os->start;
575 os->end = os->start + (size & ~1);
578 /* Add some bits to the bitbuffer variable of the output bitstream. The caller
579 * must make sure there is enough room. */
581 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
583 os->bitbuf = (os->bitbuf << num_bits) | bits;
584 os->bitcount += num_bits;
587 /* Flush bits from the bitbuffer variable to the output buffer. 'max_num_bits'
588 * specifies the maximum number of bits that may have been added since the last
591 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
593 /* Masking the number of bits to shift is only needed to avoid undefined
594 * behavior; we don't actually care about the results of bad shifts. On
595 * x86, the explicit masking generates no extra code. */
596 const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
598 if (os->end - os->next < 6)
600 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 16) &
601 shift_mask), os->next + 0);
602 if (max_num_bits > 16)
603 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 32) &
604 shift_mask), os->next + 2);
605 if (max_num_bits > 32)
606 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 48) &
607 shift_mask), os->next + 4);
608 os->next += (os->bitcount >> 4) << 1;
612 /* Add at most 16 bits to the bitbuffer and flush it. */
614 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
616 lzx_add_bits(os, bits, num_bits);
617 lzx_flush_bits(os, 16);
621 * Flush the last coding unit to the output buffer if needed. Return the total
622 * number of bytes written to the output buffer, or 0 if an overflow occurred.
625 lzx_flush_output(struct lzx_output_bitstream *os)
627 if (os->end - os->next < 6)
630 if (os->bitcount != 0) {
631 put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
635 return os->next - os->start;
639 * Build the main, length, and aligned offset Huffman codes used in LZX.
641 * This takes as input the frequency tables for each code and produces as output
642 * a set of tables that map symbols to codewords and codeword lengths.
645 lzx_make_huffman_codes(struct lzx_compressor *c)
647 const struct lzx_freqs *freqs = &c->freqs;
648 struct lzx_codes *codes = &c->codes[c->codes_index];
650 STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
651 MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
652 STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
653 LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
654 STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
655 ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
657 make_canonical_huffman_code(c->num_main_syms,
661 codes->codewords.main);
663 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
664 LENGTH_CODEWORD_LIMIT,
667 codes->codewords.len);
669 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
670 ALIGNED_CODEWORD_LIMIT,
673 codes->codewords.aligned);
676 /* Reset the symbol frequencies for the LZX Huffman codes. */
678 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
680 memset(&c->freqs, 0, sizeof(c->freqs));
684 lzx_compute_precode_items(const u8 lens[restrict],
685 const u8 prev_lens[restrict],
686 u32 precode_freqs[restrict],
687 unsigned precode_items[restrict])
696 itemptr = precode_items;
699 while (!((len = lens[run_start]) & 0x80)) {
701 /* len = the length being repeated */
703 /* Find the next run of codeword lengths. */
705 run_end = run_start + 1;
707 /* Fast case for a single length. */
708 if (likely(len != lens[run_end])) {
709 delta = prev_lens[run_start] - len;
712 precode_freqs[delta]++;
718 /* Extend the run. */
721 } while (len == lens[run_end]);
726 /* Symbol 18: RLE 20 to 51 zeroes at a time. */
727 while ((run_end - run_start) >= 20) {
728 extra_bits = min((run_end - run_start) - 20, 0x1f);
730 *itemptr++ = 18 | (extra_bits << 5);
731 run_start += 20 + extra_bits;
734 /* Symbol 17: RLE 4 to 19 zeroes at a time. */
735 if ((run_end - run_start) >= 4) {
736 extra_bits = min((run_end - run_start) - 4, 0xf);
738 *itemptr++ = 17 | (extra_bits << 5);
739 run_start += 4 + extra_bits;
743 /* A run of nonzero lengths. */
745 /* Symbol 19: RLE 4 to 5 of any length at a time. */
746 while ((run_end - run_start) >= 4) {
747 extra_bits = (run_end - run_start) > 4;
748 delta = prev_lens[run_start] - len;
752 precode_freqs[delta]++;
753 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
754 run_start += 4 + extra_bits;
758 /* Output any remaining lengths without RLE. */
759 while (run_start != run_end) {
760 delta = prev_lens[run_start] - len;
763 precode_freqs[delta]++;
769 return itemptr - precode_items;
773 * Output a Huffman code in the compressed form used in LZX.
775 * The Huffman code is represented in the output as a logical series of codeword
776 * lengths from which the Huffman code, which must be in canonical form, can be
779 * The codeword lengths are themselves compressed using a separate Huffman code,
780 * the "precode", which contains a symbol for each possible codeword length in
781 * the larger code as well as several special symbols to represent repeated
782 * codeword lengths (a form of run-length encoding). The precode is itself
783 * constructed in canonical form, and its codeword lengths are represented
784 * literally in 20 4-bit fields that immediately precede the compressed codeword
785 * lengths of the larger code.
787 * Furthermore, the codeword lengths of the larger code are actually represented
788 * as deltas from the codeword lengths of the corresponding code in the previous
792 * Bitstream to which to write the compressed Huffman code.
794 * The codeword lengths, indexed by symbol, in the Huffman code.
796 * The codeword lengths, indexed by symbol, in the corresponding Huffman
797 * code in the previous block, or all zeroes if this is the first block.
799 * The number of symbols in the Huffman code.
802 lzx_write_compressed_code(struct lzx_output_bitstream *os,
803 const u8 lens[restrict],
804 const u8 prev_lens[restrict],
807 u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
808 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
809 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
810 unsigned precode_items[num_lens];
811 unsigned num_precode_items;
812 unsigned precode_item;
813 unsigned precode_sym;
815 u8 saved = lens[num_lens];
816 *(u8 *)(lens + num_lens) = 0x80;
818 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
819 precode_freqs[i] = 0;
821 /* Compute the "items" (RLE / literal tokens and extra bits) with which
822 * the codeword lengths in the larger code will be output. */
823 num_precode_items = lzx_compute_precode_items(lens,
828 /* Build the precode. */
829 STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
830 PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
831 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
833 precode_freqs, precode_lens,
836 /* Output the lengths of the codewords in the precode. */
837 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
838 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
840 /* Output the encoded lengths of the codewords in the larger code. */
841 for (i = 0; i < num_precode_items; i++) {
842 precode_item = precode_items[i];
843 precode_sym = precode_item & 0x1F;
844 lzx_add_bits(os, precode_codewords[precode_sym],
845 precode_lens[precode_sym]);
846 if (precode_sym >= 17) {
847 if (precode_sym == 17) {
848 lzx_add_bits(os, precode_item >> 5, 4);
849 } else if (precode_sym == 18) {
850 lzx_add_bits(os, precode_item >> 5, 5);
852 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
853 precode_sym = precode_item >> 6;
854 lzx_add_bits(os, precode_codewords[precode_sym],
855 precode_lens[precode_sym]);
858 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
859 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
862 *(u8 *)(lens + num_lens) = saved;
866 * Write all matches and literal bytes (which were precomputed) in an LZX
867 * compressed block to the output bitstream in the final compressed
871 * The output bitstream.
873 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
874 * LZX_BLOCKTYPE_VERBATIM).
876 * The uncompressed data of the block.
878 * The matches and literals to output, given as a series of sequences.
880 * The main, length, and aligned offset Huffman codes for the current
881 * LZX compressed block.
884 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
885 const u8 *block_data, const struct lzx_sequence sequences[],
886 const struct lzx_codes *codes)
888 const struct lzx_sequence *seq = sequences;
889 u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
892 /* Output the next sequence. */
894 unsigned litrunlen = seq->litrunlen;
896 unsigned main_symbol;
897 unsigned adjusted_length;
899 unsigned offset_slot;
900 unsigned num_extra_bits;
903 /* Output the literal run of the sequence. */
905 if (litrunlen) { /* Is the literal run nonempty? */
907 /* Verify optimization is enabled on 64-bit */
908 STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
909 CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT));
911 if (CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT)) {
913 /* 64-bit: write 3 literals at a time. */
914 while (litrunlen >= 3) {
915 unsigned lit0 = block_data[0];
916 unsigned lit1 = block_data[1];
917 unsigned lit2 = block_data[2];
918 lzx_add_bits(os, codes->codewords.main[lit0],
919 codes->lens.main[lit0]);
920 lzx_add_bits(os, codes->codewords.main[lit1],
921 codes->lens.main[lit1]);
922 lzx_add_bits(os, codes->codewords.main[lit2],
923 codes->lens.main[lit2]);
924 lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
929 unsigned lit = *block_data++;
930 lzx_add_bits(os, codes->codewords.main[lit],
931 codes->lens.main[lit]);
933 unsigned lit = *block_data++;
934 lzx_add_bits(os, codes->codewords.main[lit],
935 codes->lens.main[lit]);
936 lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
938 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
942 /* 32-bit: write 1 literal at a time. */
944 unsigned lit = *block_data++;
945 lzx_add_bits(os, codes->codewords.main[lit],
946 codes->lens.main[lit]);
947 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
948 } while (--litrunlen);
952 /* Was this the last literal run? */
953 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
956 /* Nope; output the match. */
958 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
959 main_symbol = LZX_NUM_CHARS + match_hdr;
960 adjusted_length = seq->adjusted_length;
962 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
964 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
965 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
967 num_extra_bits = lzx_extra_offset_bits[offset_slot];
968 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
970 #define MAX_MATCH_BITS (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
971 14 + ALIGNED_CODEWORD_LIMIT)
973 /* Verify optimization is enabled on 64-bit */
974 STATIC_ASSERT(sizeof(machine_word_t) < 8 || CAN_BUFFER(MAX_MATCH_BITS));
976 /* Output the main symbol for the match. */
978 lzx_add_bits(os, codes->codewords.main[main_symbol],
979 codes->lens.main[main_symbol]);
980 if (!CAN_BUFFER(MAX_MATCH_BITS))
981 lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
983 /* If needed, output the length symbol for the match. */
985 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
986 lzx_add_bits(os, codes->codewords.len[adjusted_length -
987 LZX_NUM_PRIMARY_LENS],
988 codes->lens.len[adjusted_length -
989 LZX_NUM_PRIMARY_LENS]);
990 if (!CAN_BUFFER(MAX_MATCH_BITS))
991 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
994 /* Output the extra offset bits for the match. In aligned
995 * offset blocks, the lowest 3 bits of the adjusted offset are
996 * Huffman-encoded using the aligned offset code, provided that
997 * there are at least extra 3 offset bits required. All other
998 * extra offset bits are output verbatim. */
1000 if ((adjusted_offset & ones_if_aligned) >= 16) {
1002 lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
1003 num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
1004 if (!CAN_BUFFER(MAX_MATCH_BITS))
1005 lzx_flush_bits(os, 14);
1007 lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
1008 LZX_ALIGNED_OFFSET_BITMASK],
1009 codes->lens.aligned[adjusted_offset &
1010 LZX_ALIGNED_OFFSET_BITMASK]);
1011 if (!CAN_BUFFER(MAX_MATCH_BITS))
1012 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1014 STATIC_ASSERT(CAN_BUFFER(17));
1016 lzx_add_bits(os, extra_bits, num_extra_bits);
1017 if (!CAN_BUFFER(MAX_MATCH_BITS))
1018 lzx_flush_bits(os, 17);
1021 if (CAN_BUFFER(MAX_MATCH_BITS))
1022 lzx_flush_bits(os, MAX_MATCH_BITS);
1024 /* Advance to the next sequence. */
1030 lzx_write_compressed_block(const u8 *block_begin,
1033 unsigned window_order,
1034 unsigned num_main_syms,
1035 const struct lzx_sequence sequences[],
1036 const struct lzx_codes * codes,
1037 const struct lzx_lens * prev_lens,
1038 struct lzx_output_bitstream * os)
1040 /* The first three bits indicate the type of block and are one of the
1041 * LZX_BLOCKTYPE_* constants. */
1042 lzx_write_bits(os, block_type, 3);
1045 * Output the block length.
1047 * The original LZX format seemed to always encode the block length in 3
1048 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
1049 * uses the first bit to indicate whether the block is the default
1050 * length (32768) or a different length given explicitly by the next 16
1053 * By default, this compressor uses a window size of 32768 and therefore
1054 * follows the WIMGAPI behavior. However, this compressor also supports
1055 * window sizes greater than 32768 bytes, which do not appear to be
1056 * supported by WIMGAPI. In such cases, we retain the default size bit
1057 * to mean a size of 32768 bytes but output non-default block length in
1058 * 24 bits rather than 16. The compatibility of this behavior is
1059 * unknown because WIMs created with chunk size greater than 32768 can
1060 * seemingly only be opened by wimlib anyway.
1062 if (block_length == LZX_DEFAULT_BLOCK_SIZE) {
1063 lzx_write_bits(os, 1, 1);
1065 lzx_write_bits(os, 0, 1);
1067 if (window_order >= 16)
1068 lzx_write_bits(os, block_length >> 16, 8);
1070 lzx_write_bits(os, block_length & 0xFFFF, 16);
1073 /* If it's an aligned offset block, output the aligned offset code. */
1074 if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1075 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1076 lzx_write_bits(os, codes->lens.aligned[i],
1077 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1081 /* Output the main code (two parts). */
1082 lzx_write_compressed_code(os, codes->lens.main,
1085 lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1086 prev_lens->main + LZX_NUM_CHARS,
1087 num_main_syms - LZX_NUM_CHARS);
1089 /* Output the length code. */
1090 lzx_write_compressed_code(os, codes->lens.len,
1092 LZX_LENCODE_NUM_SYMBOLS);
1094 /* Output the compressed matches and literals. */
1095 lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1098 /* Given the frequencies of symbols in an LZX-compressed block and the
1099 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1100 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1101 * will take fewer bits to output. */
1103 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1104 const struct lzx_codes * codes)
1106 u32 aligned_cost = 0;
1107 u32 verbatim_cost = 0;
1109 /* A verbatim block requires 3 bits in each place that an aligned symbol
1110 * would be used in an aligned offset block. */
1111 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1112 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1113 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1116 /* Account for output of the aligned offset code. */
1117 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1119 if (aligned_cost < verbatim_cost)
1120 return LZX_BLOCKTYPE_ALIGNED;
1122 return LZX_BLOCKTYPE_VERBATIM;
1126 * Return the offset slot for the specified adjusted match offset, using the
1127 * compressor's acceleration tables to speed up the mapping.
1129 static inline unsigned
1130 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1133 if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1134 return c->offset_slot_tab_1[adjusted_offset];
1135 return c->offset_slot_tab_2[adjusted_offset >> 14];
1139 * Flush an LZX block:
1141 * 1. Build the Huffman codes.
1142 * 2. Decide whether to output the block as VERBATIM or ALIGNED.
1143 * 3. Write the block.
1144 * 4. Swap the indices of the current and previous Huffman codes.
1147 lzx_flush_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1148 const u8 *block_begin, u32 block_length, u32 seq_idx)
1152 lzx_make_huffman_codes(c);
1154 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1155 &c->codes[c->codes_index]);
1156 lzx_write_compressed_block(block_begin,
1161 &c->chosen_sequences[seq_idx],
1162 &c->codes[c->codes_index],
1163 &c->codes[c->codes_index ^ 1].lens,
1165 c->codes_index ^= 1;
1168 /* Tally the Huffman symbol for a literal and increment the literal run length.
1171 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1173 c->freqs.main[literal]++;
1177 /* Tally the Huffman symbol for a match, save the match data and the length of
1178 * the preceding literal run in the next lzx_sequence, and update the recent
1181 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1182 u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1183 u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1185 u32 litrunlen = *litrunlen_p;
1186 struct lzx_sequence *next_seq = *next_seq_p;
1187 unsigned offset_slot;
1190 v = length - LZX_MIN_MATCH_LEN;
1192 /* Save the literal run length and adjusted length. */
1193 next_seq->litrunlen = litrunlen;
1194 next_seq->adjusted_length = v;
1196 /* Compute the length header and tally the length symbol if needed */
1197 if (v >= LZX_NUM_PRIMARY_LENS) {
1198 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1199 v = LZX_NUM_PRIMARY_LENS;
1202 /* Compute the offset slot */
1203 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1205 /* Compute the match header. */
1206 v += offset_slot * LZX_NUM_LEN_HEADERS;
1208 /* Save the adjusted offset and match header. */
1209 next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1211 /* Tally the main symbol. */
1212 c->freqs.main[LZX_NUM_CHARS + v]++;
1214 /* Update the recent offsets queue. */
1215 if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1216 /* Repeat offset match */
1217 swap(recent_offsets[0], recent_offsets[offset_data]);
1219 /* Explicit offset match */
1221 /* Tally the aligned offset symbol if needed */
1222 if (offset_data >= 16)
1223 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1225 recent_offsets[2] = recent_offsets[1];
1226 recent_offsets[1] = recent_offsets[0];
1227 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1230 /* Reset the literal run length and advance to the next sequence. */
1231 *next_seq_p = next_seq + 1;
1235 /* Finish the last lzx_sequence. The last lzx_sequence is just a literal run;
1236 * there is no match. This literal run may be empty. */
1238 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1240 last_seq->litrunlen = litrunlen;
1242 /* Special value to mark last sequence */
1243 last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1246 /******************************************************************************/
1249 * Block splitting algorithm. The problem is to decide when it is worthwhile to
1250 * start a new block with new entropy codes. There is a theoretically optimal
1251 * solution: recursively consider every possible block split, considering the
1252 * exact cost of each block, and choose the minimum cost approach. But this is
1253 * far too slow. Instead, as an approximation, we can count symbols and after
1254 * every N symbols, compare the expected distribution of symbols based on the
1255 * previous data with the actual distribution. If they differ "by enough", then
1256 * start a new block.
1258 * As an optimization and heuristic, we don't distinguish between every symbol
1259 * but rather we combine many symbols into a single "observation type". For
1260 * literals we only look at the high bits and low bits, and for matches we only
1261 * look at whether the match is long or not. The assumption is that for typical
1262 * "real" data, places that are good block boundaries will tend to be noticable
1263 * based only on changes in these aggregate frequencies, without looking for
1264 * subtle differences in individual symbols. For example, a change from ASCII
1265 * bytes to non-ASCII bytes, or from few matches (generally less compressible)
1266 * to many matches (generally more compressible), would be easily noticed based
1267 * on the aggregates.
1269 * For determining whether the frequency distributions are "different enough" to
1270 * start a new block, the simply heuristic of splitting when the sum of absolute
1271 * differences exceeds a constant seems to be good enough. We also add a number
1272 * proportional to the block length so that the algorithm is more likely to end
1273 * long blocks than short blocks. This reflects the general expectation that it
1274 * will become increasingly beneficial to start a new block as the current
1275 * blocks grows larger.
1277 * Finally, for an approximation, it is not strictly necessary that the exact
1278 * symbols being used are considered. With "near-optimal parsing", for example,
1279 * the actual symbols that will be used are unknown until after the block
1280 * boundary is chosen and the block has been optimized. Since the final choices
1281 * cannot be used, we can use preliminary "greedy" choices instead.
1284 /* Initialize the block split statistics when starting a new block. */
1286 init_block_split_stats(struct block_split_stats *stats)
1288 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1289 stats->new_observations[i] = 0;
1290 stats->observations[i] = 0;
1292 stats->num_new_observations = 0;
1293 stats->num_observations = 0;
1296 /* Literal observation. Heuristic: use the top 2 bits and low 1 bits of the
1297 * literal, for 8 possible literal observation types. */
1299 observe_literal(struct block_split_stats *stats, u8 lit)
1301 stats->new_observations[((lit >> 5) & 0x6) | (lit & 1)]++;
1302 stats->num_new_observations++;
1305 /* Match observation. Heuristic: use one observation type for "short match" and
1306 * one observation type for "long match". */
1308 observe_match(struct block_split_stats *stats, unsigned length)
1310 stats->new_observations[NUM_LITERAL_OBSERVATION_TYPES + (length >= 5)]++;
1311 stats->num_new_observations++;
1315 do_end_block_check(struct block_split_stats *stats, u32 block_length)
1317 if (stats->num_observations > 0) {
1319 /* Note: to avoid slow divisions, we do not divide by
1320 * 'num_observations', but rather do all math with the numbers
1321 * multiplied by 'num_observations'. */
1322 u32 total_delta = 0;
1323 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1324 u32 expected = stats->observations[i] * stats->num_new_observations;
1325 u32 actual = stats->new_observations[i] * stats->num_observations;
1326 u32 delta = (actual > expected) ? actual - expected :
1328 total_delta += delta;
1331 /* Ready to end the block? */
1332 if (total_delta + (block_length / 1024) * stats->num_observations >=
1333 stats->num_new_observations * 51 / 64 * stats->num_observations)
1337 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1338 stats->num_observations += stats->new_observations[i];
1339 stats->observations[i] += stats->new_observations[i];
1340 stats->new_observations[i] = 0;
1342 stats->num_new_observations = 0;
1347 should_end_block(struct block_split_stats *stats,
1348 const u8 *in_block_begin, const u8 *in_next, const u8 *in_end)
1350 /* Ready to check block split statistics? */
1351 if (stats->num_new_observations < NUM_OBSERVATIONS_PER_BLOCK_CHECK ||
1352 in_next - in_block_begin < MIN_BLOCK_LENGTH ||
1353 in_end - in_next < MIN_BLOCK_LENGTH)
1356 return do_end_block_check(stats, in_next - in_block_begin);
1359 /******************************************************************************/
1362 * Given the minimum-cost path computed through the item graph for the current
1363 * block, walk the path and count how many of each symbol in each Huffman-coded
1364 * alphabet would be required to output the items (matches and literals) along
1367 * Note that the path will be walked backwards (from the end of the block to the
1368 * beginning of the block), but this doesn't matter because this function only
1369 * computes frequencies.
1372 lzx_tally_item_list(struct lzx_compressor *c, u32 block_length, bool is_16_bit)
1374 u32 node_idx = block_length;
1381 unsigned offset_slot;
1383 /* Tally literals until either a match or the beginning of the
1384 * block is reached. */
1386 item = c->optimum_nodes[node_idx].item;
1387 if (item & OPTIMUM_LEN_MASK)
1389 c->freqs.main[item >> OPTIMUM_OFFSET_SHIFT]++;
1393 if (item & OPTIMUM_EXTRA_FLAG) {
1398 /* Tally a rep0 match. */
1399 len = item & OPTIMUM_LEN_MASK;
1400 v = len - LZX_MIN_MATCH_LEN;
1401 if (v >= LZX_NUM_PRIMARY_LENS) {
1402 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1403 v = LZX_NUM_PRIMARY_LENS;
1405 c->freqs.main[LZX_NUM_CHARS + v]++;
1407 /* Tally a literal. */
1408 c->freqs.main[c->optimum_nodes[node_idx].extra_literal]++;
1410 item = c->optimum_nodes[node_idx].extra_match;
1411 node_idx -= len + 1;
1414 len = item & OPTIMUM_LEN_MASK;
1415 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1419 /* Tally a match. */
1421 /* Tally the aligned offset symbol if needed. */
1422 if (offset_data >= 16)
1423 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1425 /* Tally the length symbol if needed. */
1426 v = len - LZX_MIN_MATCH_LEN;;
1427 if (v >= LZX_NUM_PRIMARY_LENS) {
1428 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1429 v = LZX_NUM_PRIMARY_LENS;
1432 /* Tally the main symbol. */
1433 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1434 v += offset_slot * LZX_NUM_LEN_HEADERS;
1435 c->freqs.main[LZX_NUM_CHARS + v]++;
1440 * Like lzx_tally_item_list(), but this function also generates the list of
1441 * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1442 * ready to be output to the bitstream after the Huffman codes are computed.
1443 * The lzx_sequences will be written to decreasing memory addresses as the path
1444 * is walked backwards, which means they will end up in the expected
1445 * first-to-last order. The return value is the index in c->chosen_sequences at
1446 * which the lzx_sequences begin.
1449 lzx_record_item_list(struct lzx_compressor *c, u32 block_length, bool is_16_bit)
1451 u32 node_idx = block_length;
1452 u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1455 /* Special value to mark last sequence */
1456 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1458 lit_start_node = node_idx;
1464 unsigned offset_slot;
1466 /* Tally literals until either a match or the beginning of the
1467 * block is reached. */
1469 item = c->optimum_nodes[node_idx].item;
1470 if (item & OPTIMUM_LEN_MASK)
1472 c->freqs.main[item >> OPTIMUM_OFFSET_SHIFT]++;
1476 if (item & OPTIMUM_EXTRA_FLAG) {
1481 /* Save the literal run length for the next sequence
1482 * (the "previous sequence" when walking backwards). */
1483 len = item & OPTIMUM_LEN_MASK;
1484 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1486 lit_start_node = node_idx - len;
1488 /* Tally a rep0 match. */
1489 v = len - LZX_MIN_MATCH_LEN;
1490 c->chosen_sequences[seq_idx].adjusted_length = v;
1491 if (v >= LZX_NUM_PRIMARY_LENS) {
1492 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1493 v = LZX_NUM_PRIMARY_LENS;
1495 c->freqs.main[LZX_NUM_CHARS + v]++;
1496 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = v;
1498 /* Tally a literal. */
1499 c->freqs.main[c->optimum_nodes[node_idx].extra_literal]++;
1501 item = c->optimum_nodes[node_idx].extra_match;
1502 node_idx -= len + 1;
1505 len = item & OPTIMUM_LEN_MASK;
1506 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1508 /* Save the literal run length for the next sequence (the
1509 * "previous sequence" when walking backwards). */
1510 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1512 lit_start_node = node_idx;
1514 /* Record a match. */
1516 /* Tally the aligned offset symbol if needed. */
1517 if (offset_data >= 16)
1518 c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1520 /* Save the adjusted length. */
1521 v = len - LZX_MIN_MATCH_LEN;
1522 c->chosen_sequences[seq_idx].adjusted_length = v;
1524 /* Tally the length symbol if needed. */
1525 if (v >= LZX_NUM_PRIMARY_LENS) {
1526 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1527 v = LZX_NUM_PRIMARY_LENS;
1530 /* Tally the main symbol. */
1531 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1532 v += offset_slot * LZX_NUM_LEN_HEADERS;
1533 c->freqs.main[LZX_NUM_CHARS + v]++;
1535 /* Save the adjusted offset and match header. */
1536 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1537 (offset_data << 9) | v;
1540 /* Save the literal run length for the first sequence. */
1541 c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1543 /* Return the index in c->chosen_sequences at which the lzx_sequences
1549 * Find an inexpensive path through the graph of possible match/literal choices
1550 * for the current block. The nodes of the graph are
1551 * c->optimum_nodes[0...block_length]. They correspond directly to the bytes in
1552 * the current block, plus one extra node for end-of-block. The edges of the
1553 * graph are matches and literals. The goal is to find the minimum cost path
1554 * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_length]', given the cost
1557 * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1558 * proceeding forwards one node at a time. At each node, a selection of matches
1559 * (len >= 2), as well as the literal byte (len = 1), is considered. An item of
1560 * length 'len' provides a new path to reach the node 'len' bytes later. If
1561 * such a path is the lowest cost found so far to reach that later node, then
1562 * that later node is updated with the new path.
1564 * Note that although this algorithm is based on minimum cost path search, due
1565 * to various simplifying assumptions the result is not guaranteed to be the
1566 * true minimum cost, or "optimal", path over the graph of all valid LZX
1567 * representations of this block.
1569 * Also, note that because of the presence of the recent offsets queue (which is
1570 * a type of adaptive state), the algorithm cannot work backwards and compute
1571 * "cost to end" instead of "cost to beginning". Furthermore, the way the
1572 * algorithm handles this adaptive state in the "minimum cost" parse is actually
1573 * only an approximation. It's possible for the globally optimal, minimum cost
1574 * path to contain a prefix, ending at a position, where that path prefix is
1575 * *not* the minimum cost path to that position. This can happen if such a path
1576 * prefix results in a different adaptive state which results in lower costs
1577 * later. The algorithm does not solve this problem; it only considers the
1578 * lowest cost to reach each individual position.
1580 static inline struct lzx_lru_queue
1581 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1582 const u8 * const restrict block_begin,
1583 const u32 block_length,
1584 const struct lzx_lru_queue initial_queue,
1587 struct lzx_optimum_node *cur_node = c->optimum_nodes;
1588 struct lz_match *cache_ptr = c->match_cache;
1589 const u8 *in_next = block_begin;
1590 const u8 * const block_end = block_begin + block_length;
1592 /* Instead of storing the match offset LRU queues in the
1593 * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1594 * storing them in a smaller array. This works because the algorithm
1595 * only requires a limited history of the adaptive state. Once a given
1596 * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1597 * it is no longer needed. */
1598 struct lzx_lru_queue queues[512];
1600 STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1601 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1603 /* Initially, the cost to reach each node is "infinity". */
1604 memset(c->optimum_nodes, 0xFF,
1605 (block_length + 1) * sizeof(c->optimum_nodes[0]));
1607 QUEUE(block_begin) = initial_queue;
1609 /* The following loop runs 'block_length' iterations, one per node. */
1611 unsigned num_matches;
1614 struct lz_match *matches;
1617 * A selection of matches for the block was already saved in
1618 * memory so that we don't have to run the uncompressed data
1619 * through the matchfinder on every optimization pass. However,
1620 * we still search for repeat offset matches during each
1621 * optimization pass because we cannot predict the state of the
1622 * recent offsets queue. But as a heuristic, we don't bother
1623 * searching for repeat offset matches if the general-purpose
1624 * matchfinder failed to find any matches.
1626 * Note that a match of length n at some offset implies there is
1627 * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1628 * that same offset. In other words, we don't necessarily need
1629 * to use the full length of a match. The key heuristic that
1630 * saves a significicant amount of time is that for each
1631 * distinct length, we only consider the smallest offset for
1632 * which that length is available. This heuristic also applies
1633 * to repeat offsets, which we order specially: R0 < R1 < R2 <
1634 * any explicit offset. Of course, this heuristic may be
1635 * produce suboptimal results because offset slots in LZX are
1636 * subject to entropy encoding, but in practice this is a useful
1640 num_matches = cache_ptr->length;
1642 matches = cache_ptr;
1645 unsigned next_len = LZX_MIN_MATCH_LEN;
1646 unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1649 /* Consider R0 match */
1650 matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1651 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1653 STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1655 u32 cost = cur_node->cost +
1656 c->costs.match_cost[0][
1657 next_len - LZX_MIN_MATCH_LEN];
1658 if (cost <= (cur_node + next_len)->cost) {
1659 (cur_node + next_len)->cost = cost;
1660 (cur_node + next_len)->item =
1661 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1663 if (unlikely(++next_len > max_len))
1665 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1669 /* Consider R1 match */
1670 matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1671 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1673 if (matchptr[next_len - 1] != in_next[next_len - 1])
1675 for (unsigned len = 2; len < next_len - 1; len++)
1676 if (matchptr[len] != in_next[len])
1679 u32 cost = cur_node->cost +
1680 c->costs.match_cost[1][
1681 next_len - LZX_MIN_MATCH_LEN];
1682 if (cost <= (cur_node + next_len)->cost) {
1683 (cur_node + next_len)->cost = cost;
1684 (cur_node + next_len)->item =
1685 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1687 if (unlikely(++next_len > max_len))
1689 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1693 /* Consider R2 match */
1694 matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1695 if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1697 if (matchptr[next_len - 1] != in_next[next_len - 1])
1699 for (unsigned len = 2; len < next_len - 1; len++)
1700 if (matchptr[len] != in_next[len])
1703 u32 cost = cur_node->cost +
1704 c->costs.match_cost[2][
1705 next_len - LZX_MIN_MATCH_LEN];
1706 if (cost <= (cur_node + next_len)->cost) {
1707 (cur_node + next_len)->cost = cost;
1708 (cur_node + next_len)->item =
1709 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1711 if (unlikely(++next_len > max_len))
1713 } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1716 matches = cache_ptr;
1717 cache_ptr += num_matches - 1;
1718 while (next_len > cache_ptr->length) {
1719 if (cache_ptr == matches)
1724 /* Consider explicit offset matches */
1726 u32 offset = cache_ptr->offset;
1727 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1728 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1730 u32 base_cost = cur_node->cost;
1733 #if LZX_CONSIDER_ALIGNED_COSTS
1734 if (offset_data >= 16)
1735 base_cost += c->costs.aligned[offset_data &
1736 LZX_ALIGNED_OFFSET_BITMASK];
1740 c->costs.match_cost[offset_slot][
1741 next_len - LZX_MIN_MATCH_LEN];
1742 if (cost < (cur_node + next_len)->cost) {
1743 (cur_node + next_len)->cost = cost;
1744 (cur_node + next_len)->item =
1745 (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1747 } while (++next_len <= cache_ptr->length);
1749 if (cache_ptr == matches) {
1750 /* Consider match + lit + rep0 */
1751 u32 remaining = block_end - (in_next + next_len);
1752 if (likely(remaining >= 2)) {
1753 const u8 *strptr = in_next + next_len;
1754 const u8 *matchptr = strptr - offset;
1755 if (unlikely(load_u16_unaligned(strptr) == load_u16_unaligned(matchptr))) {
1756 u32 rep0_len = lz_extend(strptr, matchptr, 2,
1757 min(remaining, LZX_MAX_MATCH_LEN));
1758 u8 lit = strptr[-1];
1759 cost += c->costs.main[lit] +
1760 c->costs.match_cost[0][rep0_len - LZX_MIN_MATCH_LEN];
1761 u32 total_len = next_len + rep0_len;
1762 if (cost < (cur_node + total_len)->cost) {
1763 (cur_node + total_len)->cost = cost;
1764 (cur_node + total_len)->item =
1765 OPTIMUM_EXTRA_FLAG | rep0_len;
1766 (cur_node + total_len)->extra_literal = lit;
1767 (cur_node + total_len)->extra_match =
1768 (offset_data << OPTIMUM_OFFSET_SHIFT) | (next_len - 1);
1779 cache_ptr = matches + num_matches;
1781 /* Consider coding a literal.
1783 * To avoid an extra branch, actually checking the preferability
1784 * of coding the literal is integrated into the queue update
1786 literal = *in_next++;
1787 cost = cur_node->cost + c->costs.main[literal];
1789 /* Advance to the next position. */
1792 /* The lowest-cost path to the current position is now known.
1793 * Finalize the recent offsets queue that results from taking
1794 * this lowest-cost path. */
1796 if (cost <= cur_node->cost) {
1797 /* Literal: queue remains unchanged. */
1798 cur_node->cost = cost;
1799 cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1800 QUEUE(in_next) = QUEUE(in_next - 1);
1802 /* Match: queue update is needed. */
1803 unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1804 u32 offset_data = (cur_node->item &
1805 ~OPTIMUM_EXTRA_FLAG) >> OPTIMUM_OFFSET_SHIFT;
1806 if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1807 /* Explicit offset match: insert offset at front */
1809 lzx_lru_queue_push(QUEUE(in_next - len),
1810 offset_data - LZX_OFFSET_ADJUSTMENT);
1811 } else if (cur_node->item & OPTIMUM_EXTRA_FLAG) {
1812 /* Explicit offset match, then literal, then
1813 * rep0 match: insert offset at front */
1814 len += 1 + (cur_node->extra_match & OPTIMUM_LEN_MASK);
1816 lzx_lru_queue_push(QUEUE(in_next - len),
1817 (cur_node->extra_match >> OPTIMUM_OFFSET_SHIFT) -
1818 LZX_OFFSET_ADJUSTMENT);
1820 /* Repeat offset match: swap offset to front */
1822 lzx_lru_queue_swap(QUEUE(in_next - len),
1826 } while (in_next != block_end);
1828 /* Return the match offset queue at the end of the minimum cost path. */
1829 return QUEUE(block_end);
1832 /* Given the costs for the main and length codewords, compute 'match_costs'. */
1834 lzx_compute_match_costs(struct lzx_compressor *c)
1836 unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1837 LZX_NUM_LEN_HEADERS;
1838 struct lzx_costs *costs = &c->costs;
1840 for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1842 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1843 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1844 LZX_NUM_LEN_HEADERS);
1847 #if LZX_CONSIDER_ALIGNED_COSTS
1848 if (offset_slot >= 8)
1849 extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1852 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1853 costs->match_cost[offset_slot][i] =
1854 costs->main[main_symbol++] + extra_cost;
1856 extra_cost += costs->main[main_symbol];
1858 for (; i < LZX_NUM_LENS; i++)
1859 costs->match_cost[offset_slot][i] =
1860 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1864 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1867 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_length)
1870 bool have_byte[256];
1871 unsigned num_used_bytes;
1873 /* The costs below are hard coded to use a scaling factor of 64. */
1874 STATIC_ASSERT(LZX_BIT_COST == 64);
1879 * - Use smaller initial costs for literal symbols when the input buffer
1880 * contains fewer distinct bytes.
1882 * - Assume that match symbols are more costly than literal symbols.
1884 * - Assume that length symbols for shorter lengths are less costly than
1885 * length symbols for longer lengths.
1888 for (i = 0; i < 256; i++)
1889 have_byte[i] = false;
1891 for (i = 0; i < block_length; i++)
1892 have_byte[block[i]] = true;
1895 for (i = 0; i < 256; i++)
1896 num_used_bytes += have_byte[i];
1898 for (i = 0; i < 256; i++)
1899 c->costs.main[i] = 560 - (256 - num_used_bytes);
1901 for (; i < c->num_main_syms; i++)
1902 c->costs.main[i] = 680;
1904 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1905 c->costs.len[i] = 412 + i;
1907 #if LZX_CONSIDER_ALIGNED_COSTS
1908 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1909 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1912 lzx_compute_match_costs(c);
1915 /* Update the current cost model to reflect the computed Huffman codes. */
1917 lzx_set_costs_from_codes(struct lzx_compressor *c)
1920 const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1922 for (i = 0; i < c->num_main_syms; i++) {
1923 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1924 MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1927 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1928 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1929 LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1932 #if LZX_CONSIDER_ALIGNED_COSTS
1933 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1934 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1935 ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1939 lzx_compute_match_costs(c);
1943 * Choose a "near-optimal" literal/match sequence to use for the current block.
1944 * Because the cost of each Huffman symbol is unknown until the Huffman codes
1945 * have been built and the Huffman codes themselves depend on the symbol
1946 * frequencies, this uses an iterative optimization algorithm to approximate an
1947 * optimal solution. The first optimization pass for the block uses default
1948 * costs. Additional passes use costs taken from the Huffman codes computed in
1949 * the previous pass.
1951 static inline struct lzx_lru_queue
1952 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1953 struct lzx_output_bitstream * const restrict os,
1954 const u8 * const restrict block_begin,
1955 const u32 block_length,
1956 const struct lzx_lru_queue initial_queue,
1959 unsigned num_passes_remaining = c->num_optim_passes;
1960 struct lzx_lru_queue new_queue;
1963 lzx_set_default_costs(c, block_begin, block_length);
1966 new_queue = lzx_find_min_cost_path(c, block_begin, block_length,
1967 initial_queue, is_16_bit);
1969 if (--num_passes_remaining == 0)
1972 /* At least one iteration remains; update the costs. */
1973 lzx_reset_symbol_frequencies(c);
1974 lzx_tally_item_list(c, block_length, is_16_bit);
1975 lzx_make_huffman_codes(c);
1976 lzx_set_costs_from_codes(c);
1979 /* Done optimizing. Generate the sequence list and flush the block. */
1980 lzx_reset_symbol_frequencies(c);
1981 seq_idx = lzx_record_item_list(c, block_length, is_16_bit);
1982 lzx_flush_block(c, os, block_begin, block_length, seq_idx);
1987 * This is the "near-optimal" LZX compressor.
1989 * For each block, it performs a relatively thorough graph search to find an
1990 * inexpensive (in terms of compressed size) way to output that block.
1992 * Note: there are actually many things this algorithm leaves on the table in
1993 * terms of compression ratio. So although it may be "near-optimal", it is
1994 * certainly not "optimal". The goal is not to produce the optimal compression
1995 * ratio, which for LZX is probably impossible within any practical amount of
1996 * time, but rather to produce a compression ratio significantly better than a
1997 * simpler "greedy" or "lazy" parse while still being relatively fast.
2000 lzx_compress_near_optimal(struct lzx_compressor * restrict c,
2001 const u8 * const restrict in_begin,
2002 struct lzx_output_bitstream * restrict os,
2005 const u8 * in_next = in_begin;
2006 const u8 * const in_end = in_begin + c->in_nbytes;
2007 struct lzx_lru_queue queue;
2009 lcpit_matchfinder_load_buffer(&c->lcpit_mf, in_begin, c->in_nbytes);
2010 lzx_lru_queue_init(&queue);
2013 /* Starting a new block */
2014 const u8 * const in_block_begin = in_next;
2015 const u8 * const in_max_block_end =
2016 in_next + min(SOFT_MAX_BLOCK_LENGTH, in_end - in_next);
2017 struct lz_match *cache_ptr = c->match_cache;
2018 const u8 *next_observation = in_next;
2019 const u8 *next_pause_point = min(in_next + MIN_BLOCK_LENGTH,
2020 in_max_block_end - LZX_MAX_MATCH_LEN - 1);
2022 init_block_split_stats(&c->split_stats);
2024 /* Run the block through the matchfinder and cache the matches. */
2030 num_matches = lcpit_matchfinder_get_matches(&c->lcpit_mf, cache_ptr + 1);
2031 cache_ptr->length = num_matches;
2033 best_len = cache_ptr[1].length;
2035 if (in_next >= next_observation) {
2037 observe_match(&c->split_stats, best_len);
2038 next_observation = in_next + best_len;
2040 observe_literal(&c->split_stats, *in_next);
2041 next_observation = in_next + 1;
2046 * If there was a very long match found, then don't
2047 * cache any matches for the bytes covered by that
2048 * match. This avoids degenerate behavior when
2049 * compressing highly redundant data, where the number
2050 * of matches can be very large.
2052 * This heuristic doesn't actually hurt the compression
2053 * ratio very much. If there's a long match, then the
2054 * data must be highly compressible, so it doesn't
2055 * matter as much what we do.
2057 if (best_len >= c->nice_match_length) {
2058 best_len = lz_extend(in_next, in_next - cache_ptr[1].offset,
2060 min(LZX_MAX_MATCH_LEN,
2062 cache_ptr[1].length = best_len;
2063 lcpit_matchfinder_skip_bytes(&c->lcpit_mf, best_len - 1);
2064 cache_ptr += 1 + num_matches;
2065 for (u32 i = 0; i < best_len - 1; i++) {
2066 cache_ptr->length = 0;
2069 in_next += best_len;
2070 next_observation = in_next;
2072 cache_ptr += 1 + num_matches;
2075 } while (in_next < next_pause_point &&
2076 likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
2078 if (unlikely(cache_ptr >= &c->match_cache[LZX_CACHE_LENGTH]))
2081 if (in_next >= in_max_block_end)
2084 if (c->split_stats.num_new_observations >= NUM_OBSERVATIONS_PER_BLOCK_CHECK) {
2085 if (do_end_block_check(&c->split_stats, in_next - in_block_begin))
2087 if (in_max_block_end - in_next <= MIN_BLOCK_LENGTH)
2088 next_observation = in_max_block_end;
2091 next_pause_point = min(in_next +
2092 NUM_OBSERVATIONS_PER_BLOCK_CHECK * 2 -
2093 c->split_stats.num_new_observations,
2094 in_max_block_end - LZX_MAX_MATCH_LEN - 1);
2098 /* We've finished running the block through the matchfinder.
2099 * Now choose a match/literal sequence and write the block. */
2101 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
2102 in_next - in_block_begin,
2104 } while (in_next != in_end);
2108 lzx_compress_near_optimal_16(struct lzx_compressor *c,
2109 struct lzx_output_bitstream *os)
2111 lzx_compress_near_optimal(c, c->in_buffer, os, true);
2115 lzx_compress_near_optimal_32(struct lzx_compressor *c,
2116 struct lzx_output_bitstream *os)
2118 lzx_compress_near_optimal(c, c->in_buffer, os, false);
2122 * Given a pointer to the current byte sequence and the current list of recent
2123 * match offsets, find the longest repeat offset match.
2125 * If no match of at least 2 bytes is found, then return 0.
2127 * If a match of at least 2 bytes is found, then return its length and set
2128 * *rep_max_idx_ret to the index of its offset in @queue.
2131 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
2132 const u32 bytes_remaining,
2133 const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
2134 unsigned *rep_max_idx_ret)
2136 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2138 const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
2139 const u16 next_2_bytes = load_u16_unaligned(in_next);
2141 unsigned rep_max_len;
2142 unsigned rep_max_idx;
2145 matchptr = in_next - recent_offsets[0];
2146 if (load_u16_unaligned(matchptr) == next_2_bytes)
2147 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
2152 matchptr = in_next - recent_offsets[1];
2153 if (load_u16_unaligned(matchptr) == next_2_bytes) {
2154 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2155 if (rep_len > rep_max_len) {
2156 rep_max_len = rep_len;
2161 matchptr = in_next - recent_offsets[2];
2162 if (load_u16_unaligned(matchptr) == next_2_bytes) {
2163 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2164 if (rep_len > rep_max_len) {
2165 rep_max_len = rep_len;
2170 *rep_max_idx_ret = rep_max_idx;
2174 /* Fast heuristic scoring for lazy parsing: how "good" is this match? */
2175 static inline unsigned
2176 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
2178 unsigned score = len;
2180 if (adjusted_offset < 4096)
2183 if (adjusted_offset < 256)
2189 static inline unsigned
2190 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
2195 /* This is the "lazy" LZX compressor. */
2197 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
2200 const u8 * const in_begin = c->in_buffer;
2201 const u8 * in_next = in_begin;
2202 const u8 * const in_end = in_begin + c->in_nbytes;
2203 unsigned max_len = LZX_MAX_MATCH_LEN;
2204 unsigned nice_len = min(c->nice_match_length, max_len);
2205 STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2206 u32 recent_offsets[3] = {1, 1, 1};
2207 u32 next_hashes[2] = {};
2209 CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2212 /* Starting a new block */
2214 const u8 * const in_block_begin = in_next;
2215 const u8 * const in_max_block_end =
2216 in_next + min(SOFT_MAX_BLOCK_LENGTH, in_end - in_next);
2217 struct lzx_sequence *next_seq = c->chosen_sequences;
2220 u32 cur_offset_data;
2224 u32 next_offset_data;
2225 unsigned next_score;
2226 unsigned rep_max_len;
2227 unsigned rep_max_idx;
2232 lzx_reset_symbol_frequencies(c);
2233 init_block_split_stats(&c->split_stats);
2236 if (unlikely(max_len > in_end - in_next)) {
2237 max_len = in_end - in_next;
2238 nice_len = min(max_len, nice_len);
2241 /* Find the longest match at the current position. */
2243 cur_len = CALL_HC_MF(is_16_bit, c,
2244 hc_matchfinder_longest_match,
2250 c->max_search_depth,
2255 cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2256 cur_offset != recent_offsets[0] &&
2257 cur_offset != recent_offsets[1] &&
2258 cur_offset != recent_offsets[2]))
2260 /* There was no match found, or the only match found
2261 * was a distant length 3 match. Output a literal. */
2262 lzx_record_literal(c, *in_next, &litrunlen);
2263 observe_literal(&c->split_stats, *in_next);
2268 observe_match(&c->split_stats, cur_len);
2270 if (cur_offset == recent_offsets[0]) {
2272 cur_offset_data = 0;
2273 skip_len = cur_len - 1;
2274 goto choose_cur_match;
2277 cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2278 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2280 /* Consider a repeat offset match */
2281 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2287 if (rep_max_len >= 3 &&
2288 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2289 rep_max_idx)) >= cur_score)
2291 cur_len = rep_max_len;
2292 cur_offset_data = rep_max_idx;
2293 skip_len = rep_max_len - 1;
2294 goto choose_cur_match;
2299 /* We have a match at the current position. */
2301 /* If we have a very long match, choose it immediately. */
2302 if (cur_len >= nice_len) {
2303 skip_len = cur_len - 1;
2304 goto choose_cur_match;
2307 /* See if there's a better match at the next position. */
2309 if (unlikely(max_len > in_end - in_next)) {
2310 max_len = in_end - in_next;
2311 nice_len = min(max_len, nice_len);
2314 next_len = CALL_HC_MF(is_16_bit, c,
2315 hc_matchfinder_longest_match,
2321 c->max_search_depth / 2,
2325 if (next_len <= cur_len - 2) {
2327 skip_len = cur_len - 2;
2328 goto choose_cur_match;
2331 next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2332 next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2334 rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2340 if (rep_max_len >= 3 &&
2341 (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2342 rep_max_idx)) >= next_score)
2345 if (rep_score > cur_score) {
2346 /* The next match is better, and it's a
2347 * repeat offset match. */
2348 lzx_record_literal(c, *(in_next - 2),
2350 cur_len = rep_max_len;
2351 cur_offset_data = rep_max_idx;
2352 skip_len = cur_len - 1;
2353 goto choose_cur_match;
2356 if (next_score > cur_score) {
2357 /* The next match is better, and it's an
2358 * explicit offset match. */
2359 lzx_record_literal(c, *(in_next - 2),
2362 cur_offset_data = next_offset_data;
2363 cur_score = next_score;
2364 goto have_cur_match;
2368 /* The original match was better. */
2369 skip_len = cur_len - 2;
2372 lzx_record_match(c, cur_len, cur_offset_data,
2373 recent_offsets, is_16_bit,
2374 &litrunlen, &next_seq);
2375 in_next = CALL_HC_MF(is_16_bit, c,
2376 hc_matchfinder_skip_positions,
2382 } while (in_next < in_max_block_end &&
2383 !should_end_block(&c->split_stats, in_block_begin, in_next, in_end));
2385 lzx_finish_sequence(next_seq, litrunlen);
2387 lzx_flush_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2389 } while (in_next != in_end);
2393 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2395 lzx_compress_lazy(c, os, true);
2399 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2401 lzx_compress_lazy(c, os, false);
2404 /* Generate the acceleration tables for offset slots. */
2406 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2408 u32 adjusted_offset = 0;
2412 for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2415 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2417 c->offset_slot_tab_1[adjusted_offset] = slot;
2420 /* slots [30, 49] */
2421 for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2422 adjusted_offset += (u32)1 << 14)
2424 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2426 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2431 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2433 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2434 if (lzx_is_16_bit(max_bufsize))
2435 return offsetof(struct lzx_compressor, hc_mf_16) +
2436 hc_matchfinder_size_16(max_bufsize);
2438 return offsetof(struct lzx_compressor, hc_mf_32) +
2439 hc_matchfinder_size_32(max_bufsize);
2441 if (lzx_is_16_bit(max_bufsize))
2442 return offsetof(struct lzx_compressor, lcpit_mf) +
2443 sizeof(struct lcpit_matchfinder);
2445 return offsetof(struct lzx_compressor, lcpit_mf) +
2446 sizeof(struct lcpit_matchfinder);
2451 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2456 if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2459 size += lzx_get_compressor_size(max_bufsize, compression_level);
2461 size += max_bufsize; /* in_buffer */
2462 if (compression_level > LZX_MAX_FAST_LEVEL)
2463 size += lcpit_matchfinder_get_needed_memory(max_bufsize);
2468 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2469 bool destructive, void **c_ret)
2471 unsigned window_order;
2472 struct lzx_compressor *c;
2474 window_order = lzx_get_window_order(max_bufsize);
2475 if (window_order == 0)
2476 return WIMLIB_ERR_INVALID_PARAM;
2478 c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2482 c->destructive = destructive;
2484 c->num_main_syms = lzx_get_num_main_syms(window_order);
2485 c->window_order = window_order;
2487 if (!c->destructive) {
2488 c->in_buffer = MALLOC(max_bufsize);
2493 if (compression_level <= LZX_MAX_FAST_LEVEL) {
2495 /* Fast compression: Use lazy parsing. */
2497 if (lzx_is_16_bit(max_bufsize))
2498 c->impl = lzx_compress_lazy_16;
2500 c->impl = lzx_compress_lazy_32;
2501 c->max_search_depth = (60 * compression_level) / 20;
2502 c->nice_match_length = (80 * compression_level) / 20;
2504 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2505 * halves the max_search_depth when attempting a lazy match, and
2506 * max_search_depth cannot be 0. */
2507 if (c->max_search_depth < 2)
2508 c->max_search_depth = 2;
2511 /* Normal / high compression: Use near-optimal parsing. */
2513 if (lzx_is_16_bit(max_bufsize))
2514 c->impl = lzx_compress_near_optimal_16;
2516 c->impl = lzx_compress_near_optimal_32;
2518 /* Scale nice_match_length and max_search_depth with the
2519 * compression level. */
2520 c->max_search_depth = (24 * compression_level) / 50;
2521 c->nice_match_length = (48 * compression_level) / 50;
2523 /* Set a number of optimization passes appropriate for the
2524 * compression level. */
2526 c->num_optim_passes = 1;
2528 if (compression_level >= 45)
2529 c->num_optim_passes++;
2531 /* Use more optimization passes for higher compression levels.
2532 * But the more passes there are, the less they help --- so
2533 * don't add them linearly. */
2534 if (compression_level >= 70) {
2535 c->num_optim_passes++;
2536 if (compression_level >= 100)
2537 c->num_optim_passes++;
2538 if (compression_level >= 150)
2539 c->num_optim_passes++;
2540 if (compression_level >= 200)
2541 c->num_optim_passes++;
2542 if (compression_level >= 300)
2543 c->num_optim_passes++;
2547 /* max_search_depth == 0 is invalid. */
2548 if (c->max_search_depth < 1)
2549 c->max_search_depth = 1;
2551 if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2552 c->nice_match_length = LZX_MAX_MATCH_LEN;
2554 if (!lcpit_matchfinder_init(&c->lcpit_mf, max_bufsize,
2555 LZX_MIN_MATCH_LEN, c->nice_match_length))
2558 lzx_init_offset_slot_tabs(c);
2563 if (!c->destructive)
2568 return WIMLIB_ERR_NOMEM;
2572 lzx_compress(const void *restrict in, size_t in_nbytes,
2573 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2575 struct lzx_compressor *c = _c;
2576 struct lzx_output_bitstream os;
2579 /* Don't bother trying to compress very small inputs. */
2580 if (in_nbytes < 100)
2583 /* Copy the input data into the internal buffer and preprocess it. */
2585 c->in_buffer = (void *)in;
2587 memcpy(c->in_buffer, in, in_nbytes);
2588 c->in_nbytes = in_nbytes;
2589 lzx_preprocess(c->in_buffer, in_nbytes);
2591 /* Initially, the previous Huffman codeword lengths are all zeroes. */
2593 memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2595 /* Initialize the output bitstream. */
2596 lzx_init_output(&os, out, out_nbytes_avail);
2598 /* Call the compression level-specific compress() function. */
2601 /* Flush the output bitstream and return the compressed size or 0. */
2602 result = lzx_flush_output(&os);
2603 if (!result && c->destructive)
2604 lzx_postprocess(c->in_buffer, c->in_nbytes);
2609 lzx_free_compressor(void *_c)
2611 struct lzx_compressor *c = _c;
2613 lcpit_matchfinder_destroy(&c->lcpit_mf);
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,