4 * LZX compression routines
8 * Copyright (C) 2012, 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
28 * This file contains a compressor for the LZX compression format, as used in
29 * the WIM file format.
34 * First, the primary reference for the LZX compression format is the
35 * specification released by Microsoft.
37 * Second, the comments in lzx-decompress.c provide some more information about
38 * the LZX compression format, including errors in the Microsoft specification.
40 * Do note that LZX shares many similarities with DEFLATE, the algorithm used by
41 * zlib and gzip. Both LZX and DEFLATE use LZ77 matching and Huffman coding,
42 * and certain other details are quite similar, such as the method for storing
43 * Huffman codes. However, some of the main differences are:
45 * - LZX preprocesses the data to attempt to make x86 machine code slightly more
46 * compressible before attempting to compress it further.
47 * - LZX uses a "main" alphabet which combines literals and matches, with the
48 * match symbols containing a "length header" (giving all or part of the match
49 * length) and a "position slot" (giving, roughly speaking, the order of
50 * magnitude of the match offset).
51 * - LZX does not have static Huffman blocks; however it does have two types of
52 * dynamic Huffman blocks ("aligned offset" and "verbatim").
53 * - LZX has a minimum match length of 2 rather than 3.
54 * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
55 * queue of match offsets. This is very useful for certain types of files,
56 * such as binary files that have repeating records.
61 * There are actually two distinct overall algorithms implemented here. We
62 * shall refer to them as the "slow" algorithm and the "fast" algorithm. The
63 * "slow" algorithm spends more time compressing to achieve a higher compression
64 * ratio compared to the "fast" algorithm. More details are presented below.
69 * The "slow" algorithm to generate LZX-compressed data is roughly as follows:
71 * 1. Preprocess the input data to translate the targets of x86 call
72 * instructions to absolute offsets.
74 * 2. Build the suffix array and inverse suffix array for the input data. The
75 * suffix array contains the indices of all suffixes of the input data,
76 * sorted lexcographically by the corresponding suffixes. The "position" of
77 * a suffix is the index of that suffix in the original string, whereas the
78 * "rank" of a suffix is the index at which that suffix's position is found
79 * in the suffix array.
81 * 3. Build the longest common prefix array corresponding to the suffix array.
83 * 4. For each suffix, find the highest lower ranked suffix that has a lower
84 * position, the lowest higher ranked suffix that has a lower position, and
85 * the length of the common prefix shared between each. This information is
86 * later used to link suffix ranks into a doubly-linked list for searching
89 * 5. Set a default cost model for matches/literals.
91 * 6. Determine the lowest cost sequence of LZ77 matches ((offset, length)
92 * pairs) and literal bytes to divide the input into. Raw match-finding is
93 * done by searching the suffix array using a linked list to avoid
94 * considering any suffixes that start after the current position. Each run
95 * of the match-finder returns the approximate lowest-cost longest match as
96 * well as any shorter matches that have even lower approximate costs. Each
97 * such run also adds the suffix rank of the current position into the linked
98 * list being used to search the suffix array. Parsing, or match-choosing,
99 * is solved as a minimum-cost path problem using a forward "optimal parsing"
100 * algorithm based on the Deflate encoder from 7-Zip. This algorithm moves
101 * forward calculating the minimum cost to reach each byte until either a
102 * very long match is found or until a position is found at which no matches
105 * 7. Build the Huffman codes needed to output the matches/literals.
107 * 8. Up to a certain number of iterations, use the resulting Huffman codes to
108 * refine a cost model and go back to Step #6 to determine an improved
109 * sequence of matches and literals.
111 * 9. Output the resulting block using the match/literal sequences and the
112 * Huffman codes that were computed for the block.
114 * Note: the algorithm does not yet attempt to split the input into multiple LZX
115 * blocks, instead using a series of blocks of LZX_DIV_BLOCK_SIZE bytes.
120 * The fast algorithm (and the only one available in wimlib v1.5.1 and earlier)
121 * spends much less time on the main bottlenecks of the compression process ---
122 * that is, the match finding and match choosing. Matches are found and chosen
123 * with hash chains using a greedy parse with one position of look-ahead. No
124 * block splitting is done; only compressing the full input into an aligned
125 * offset block is considered.
130 * Acknowledgments to several open-source projects and research papers that made
131 * it possible to implement this code:
133 * - divsufsort (author: Yuta Mori), for the suffix array construction code,
134 * located in a separate directory (divsufsort/).
136 * - "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its
137 * Applications" (Kasai et al. 2001), for the LCP array computation.
139 * - "LPF computation revisited" (Crochemore et al. 2009) for the prev and next
140 * array computations.
142 * - 7-Zip (author: Igor Pavlov) for the algorithm for forward optimal parsing
145 * - zlib (author: Jean-loup Gailly and Mark Adler), for the hash table
146 * match-finding algorithm (used in lz77.c).
148 * - lzx-compress (author: Matthew T. Russotto), on which some parts of this
149 * code were originally based.
157 #include "wimlib/compressor_ops.h"
158 #include "wimlib/compress_common.h"
159 #include "wimlib/endianness.h"
160 #include "wimlib/error.h"
161 #include "wimlib/lzx.h"
162 #include "wimlib/util.h"
167 #ifdef ENABLE_LZX_DEBUG
168 # include "wimlib/decompress_common.h"
171 #include "divsufsort/divsufsort.h"
173 typedef u32 block_cost_t;
174 #define INFINITE_BLOCK_COST ((block_cost_t)~0U)
176 #define LZX_OPTIM_ARRAY_SIZE 4096
178 #define LZX_DIV_BLOCK_SIZE 32768
180 #define LZX_MAX_CACHE_PER_POS 10
182 /* Codewords for the LZX main, length, and aligned offset Huffman codes */
183 struct lzx_codewords {
184 u16 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
185 u16 len[LZX_LENCODE_NUM_SYMBOLS];
186 u16 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
189 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
192 * A 0 length means the codeword has zero frequency.
195 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
196 u8 len[LZX_LENCODE_NUM_SYMBOLS];
197 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
200 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
202 * If a codeword has zero frequency, it must still be assigned some nonzero cost
203 * --- generally a high cost, since even if it gets used in the next iteration,
204 * it probably will not be used very times. */
206 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
207 u8 len[LZX_LENCODE_NUM_SYMBOLS];
208 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
211 /* The LZX main, length, and aligned offset Huffman codes */
213 struct lzx_codewords codewords;
214 struct lzx_lens lens;
217 /* Tables for tallying symbol frequencies in the three LZX alphabets */
219 input_idx_t main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
220 input_idx_t len[LZX_LENCODE_NUM_SYMBOLS];
221 input_idx_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
224 /* LZX intermediate match/literal format */
228 * 31 1 if a match, 0 if a literal.
230 * 30-25 position slot. This can be at most 50, so it will fit in 6
233 * 8-24 position footer. This is the offset of the real formatted
234 * offset from the position base. This can be at most 17 bits
235 * (since lzx_extra_bits[LZX_MAX_POSITION_SLOTS - 1] is 17).
237 * 0-7 length of match, minus 2. This can be at most
238 * (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits. */
242 /* Raw LZ match/literal format: just a length and offset.
244 * The length is the number of bytes of the match, and the offset is the number
245 * of bytes back in the input the match is from the current position.
247 * If @len < LZX_MIN_MATCH_LEN, then it's really just a literal byte and @offset is
254 /* Specification for an LZX block. */
255 struct lzx_block_spec {
257 /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
261 /* 0-based position in the window at which this block starts. */
262 input_idx_t window_pos;
264 /* The number of bytes of uncompressed data this block represents. */
265 input_idx_t block_size;
267 /* The position in the 'chosen_matches' array in the `struct
268 * lzx_compressor' at which the match/literal specifications for
269 * this block begin. */
270 input_idx_t chosen_matches_start_pos;
272 /* The number of match/literal specifications for this block. */
273 input_idx_t num_chosen_matches;
275 /* Huffman codes for this block. */
276 struct lzx_codes codes;
280 * An array of these structures is used during the match-choosing algorithm.
281 * They correspond to consecutive positions in the window and are used to keep
282 * track of the cost to reach each position, and the match/literal choices that
283 * need to be chosen to reach that position.
286 /* The approximate minimum cost, in bits, to reach this position in the
287 * window which has been found so far. */
290 /* The union here is just for clarity, since the fields are used in two
291 * slightly different ways. Initially, the @prev structure is filled in
292 * first, and links go from later in the window to earlier in the
293 * window. Later, @next structure is filled in and links go from
294 * earlier in the window to later in the window. */
297 /* Position of the start of the match or literal that
298 * was taken to get to this position in the approximate
299 * minimum-cost parse. */
302 /* Offset (as in an LZ (length, offset) pair) of the
303 * match or literal that was taken to get to this
304 * position in the approximate minimum-cost parse. */
305 input_idx_t match_offset;
308 /* Position at which the match or literal starting at
309 * this position ends in the minimum-cost parse. */
312 /* Offset (as in an LZ (length, offset) pair) of the
313 * match or literal starting at this position in the
314 * approximate minimum-cost parse. */
315 input_idx_t match_offset;
319 /* The match offset LRU queue that will exist when the approximate
320 * minimum-cost path to reach this position is taken. */
321 struct lzx_lru_queue queue;
324 /* Suffix array link */
326 /* Rank of highest ranked suffix that has rank lower than the suffix
327 * corresponding to this structure and either has a lower position
328 * (initially) or has a position lower than the highest position at
329 * which matches have been searched for so far, or -1 if there is no
333 /* Rank of lowest ranked suffix that has rank greater than the suffix
334 * corresponding to this structure and either has a lower position
335 * (intially) or has a position lower than the highest position at which
336 * matches have been searched for so far, or -1 if there is no such
340 /* Length of longest common prefix between the suffix corresponding to
341 * this structure and the suffix with rank @prev, or 0 if @prev is -1.
345 /* Length of longest common prefix between the suffix corresponding to
346 * this structure and the suffix with rank @next, or 0 if @next is -1.
351 /* State of the LZX compressor. */
352 struct lzx_compressor {
354 /* The parameters that were used to create the compressor. */
355 struct wimlib_lzx_compressor_params params;
357 /* The buffer of data to be compressed.
359 * 0xe8 byte preprocessing is done directly on the data here before
360 * further compression.
362 * Note that this compressor does *not* use a real sliding window!!!!
363 * It's not needed in the WIM format, since every chunk is compressed
364 * independently. This is by design, to allow random access to the
367 * We reserve a few extra bytes to potentially allow reading off the end
368 * of the array in the match-finding code for optimization purposes.
372 /* Number of bytes of data to be compressed, which is the number of
373 * bytes of data in @window that are actually valid. */
374 input_idx_t window_size;
376 /* Allocated size of the @window. */
377 input_idx_t max_window_size;
379 /* Number of symbols in the main alphabet (depends on the
380 * @max_window_size since it determines the maximum allowed offset). */
381 unsigned num_main_syms;
383 /* The current match offset LRU queue. */
384 struct lzx_lru_queue queue;
386 /* Space for the sequences of matches/literals that were chosen for each
388 struct lzx_match *chosen_matches;
390 /* Information about the LZX blocks the preprocessed input was divided
392 struct lzx_block_spec *block_specs;
394 /* Number of LZX blocks the input was divided into; a.k.a. the number of
395 * elements of @block_specs that are valid. */
398 /* This is simply filled in with zeroes and used to avoid special-casing
399 * the output of the first compressed Huffman code, which conceptually
400 * has a delta taken from a code with all symbols having zero-length
402 struct lzx_codes zero_codes;
404 /* The current cost model. */
405 struct lzx_costs costs;
407 /* Fast algorithm only: Array of hash table links. */
408 input_idx_t *prev_tab;
410 /* Suffix array for window.
411 * This is a mapping from suffix rank to suffix position. */
414 /* Inverse suffix array for window.
415 * This is a mapping from suffix position to suffix rank.
416 * If 0 <= r < window_size, then ISA[SA[r]] == r. */
419 /* Longest common prefix array corresponding to the suffix array SA.
420 * LCP[i] is the length of the longest common prefix between the
421 * suffixes with positions SA[i - 1] and SA[i]. LCP[0] is undefined.
425 /* Suffix array links.
427 * During a linear scan of the input string to find matches, this array
428 * used to keep track of which rank suffixes in the suffix array appear
429 * before the current position. Instead of searching in the original
430 * suffix array, scans for matches at a given position traverse a linked
431 * list containing only suffixes that appear before that position. */
432 struct salink *salink;
434 /* Position in window of next match to return. */
435 input_idx_t match_window_pos;
437 /* The match-finder shall ensure the length of matches does not exceed
438 * this position in the input. */
439 input_idx_t match_window_end;
441 /* Matches found by the match-finder are cached in the following array
442 * to achieve a slight speedup when the same matches are needed on
443 * subsequent passes. This is suboptimal because different matches may
444 * be preferred with different cost models, but seems to be a worthwhile
446 struct raw_match *cached_matches;
447 unsigned cached_matches_pos;
450 /* Slow algorithm only: Temporary space used for match-choosing
453 * The size of this array must be at least LZX_MAX_MATCH_LEN but
454 * otherwise is arbitrary. More space simply allows the match-choosing
455 * algorithm to potentially find better matches (depending on the input,
457 struct lzx_optimal *optimum;
459 /* Slow algorithm only: Variables used by the match-choosing algorithm.
461 * When matches have been chosen, optimum_cur_idx is set to the position
462 * in the window of the next match/literal to return and optimum_end_idx
463 * is set to the position in the window at the end of the last
464 * match/literal to return. */
469 /* Returns the LZX position slot that corresponds to a given match offset,
470 * taking into account the recent offset queue and updating it if the offset is
473 lzx_get_position_slot(unsigned offset, struct lzx_lru_queue *queue)
475 unsigned position_slot;
477 /* See if the offset was recently used. */
478 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
479 if (offset == queue->R[i]) {
482 /* Bring the repeat offset to the front of the
483 * queue. Note: this is, in fact, not a real
484 * LRU queue because repeat matches are simply
485 * swapped to the front. */
486 swap(queue->R[0], queue->R[i]);
488 /* The resulting position slot is simply the first index
489 * at which the offset was found in the queue. */
494 /* The offset was not recently used; look up its real position slot. */
495 position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
497 /* Bring the new offset to the front of the queue. */
498 for (unsigned i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
499 queue->R[i] = queue->R[i - 1];
500 queue->R[0] = offset;
502 return position_slot;
505 /* Build the main, length, and aligned offset Huffman codes used in LZX.
507 * This takes as input the frequency tables for each code and produces as output
508 * a set of tables that map symbols to codewords and codeword lengths. */
510 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
511 struct lzx_codes *codes,
512 unsigned num_main_syms)
514 make_canonical_huffman_code(num_main_syms,
515 LZX_MAX_MAIN_CODEWORD_LEN,
518 codes->codewords.main);
520 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
521 LZX_MAX_LEN_CODEWORD_LEN,
524 codes->codewords.len);
526 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
527 LZX_MAX_ALIGNED_CODEWORD_LEN,
530 codes->codewords.aligned);
534 * Output an LZX match.
536 * @out: The bitstream to write the match to.
537 * @block_type: The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
539 * @codes: Pointer to a structure that contains the codewords for the
540 * main, length, and aligned offset Huffman codes.
543 lzx_write_match(struct output_bitstream *out, int block_type,
544 struct lzx_match match, const struct lzx_codes *codes)
546 /* low 8 bits are the match length minus 2 */
547 unsigned match_len_minus_2 = match.data & 0xff;
548 /* Next 17 bits are the position footer */
549 unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
550 /* Next 6 bits are the position slot. */
551 unsigned position_slot = (match.data >> 25) & 0x3f; /* 6 bits */
554 unsigned main_symbol;
555 unsigned num_extra_bits;
556 unsigned verbatim_bits;
557 unsigned aligned_bits;
559 /* If the match length is less than MIN_MATCH_LEN (= 2) +
560 * NUM_PRIMARY_LENS (= 7), the length header contains
561 * the match length minus MIN_MATCH_LEN, and there is no
564 * Otherwise, the length header contains
565 * NUM_PRIMARY_LENS, and the length footer contains
566 * the match length minus NUM_PRIMARY_LENS minus
568 if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
569 len_header = match_len_minus_2;
570 /* No length footer-- mark it with a special
572 len_footer = (unsigned)(-1);
574 len_header = LZX_NUM_PRIMARY_LENS;
575 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
578 /* Combine the position slot with the length header into a single symbol
579 * that will be encoded with the main code.
581 * The actual main symbol is offset by LZX_NUM_CHARS because values
582 * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
584 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
586 /* Output main symbol. */
587 bitstream_put_bits(out, codes->codewords.main[main_symbol],
588 codes->lens.main[main_symbol]);
590 /* If there is a length footer, output it using the
591 * length Huffman code. */
592 if (len_footer != (unsigned)(-1)) {
593 bitstream_put_bits(out, codes->codewords.len[len_footer],
594 codes->lens.len[len_footer]);
597 num_extra_bits = lzx_get_num_extra_bits(position_slot);
599 /* For aligned offset blocks with at least 3 extra bits, output the
600 * verbatim bits literally, then the aligned bits encoded using the
601 * aligned offset code. Otherwise, only the verbatim bits need to be
603 if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
605 verbatim_bits = position_footer >> 3;
606 bitstream_put_bits(out, verbatim_bits,
609 aligned_bits = (position_footer & 7);
610 bitstream_put_bits(out,
611 codes->codewords.aligned[aligned_bits],
612 codes->lens.aligned[aligned_bits]);
614 /* verbatim bits is the same as the position
615 * footer, in this case. */
616 bitstream_put_bits(out, position_footer, num_extra_bits);
621 lzx_build_precode(const u8 lens[restrict],
622 const u8 prev_lens[restrict],
623 const unsigned num_syms,
624 input_idx_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
625 u8 output_syms[restrict num_syms],
626 u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
627 u16 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
628 unsigned *num_additional_bits_ret)
630 memset(precode_freqs, 0,
631 LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
633 /* Since the code word lengths use a form of RLE encoding, the goal here
634 * is to find each run of identical lengths when going through them in
635 * symbol order (including runs of length 1). For each run, as many
636 * lengths are encoded using RLE as possible, and the rest are output
639 * output_syms[] will be filled in with the length symbols that will be
640 * output, including RLE codes, not yet encoded using the precode.
642 * cur_run_len keeps track of how many code word lengths are in the
643 * current run of identical lengths. */
644 unsigned output_syms_idx = 0;
645 unsigned cur_run_len = 1;
646 unsigned num_additional_bits = 0;
647 for (unsigned i = 1; i <= num_syms; i++) {
649 if (i != num_syms && lens[i] == lens[i - 1]) {
650 /* Still in a run--- keep going. */
655 /* Run ended! Check if it is a run of zeroes or a run of
658 /* The symbol that was repeated in the run--- not to be confused
659 * with the length *of* the run (cur_run_len) */
660 unsigned len_in_run = lens[i - 1];
662 if (len_in_run == 0) {
663 /* A run of 0's. Encode it in as few length
664 * codes as we can. */
666 /* The magic length 18 indicates a run of 20 + n zeroes,
667 * where n is an uncompressed literal 5-bit integer that
668 * follows the magic length. */
669 while (cur_run_len >= 20) {
670 unsigned additional_bits;
672 additional_bits = min(cur_run_len - 20, 0x1f);
673 num_additional_bits += 5;
675 output_syms[output_syms_idx++] = 18;
676 output_syms[output_syms_idx++] = additional_bits;
677 cur_run_len -= 20 + additional_bits;
680 /* The magic length 17 indicates a run of 4 + n zeroes,
681 * where n is an uncompressed literal 4-bit integer that
682 * follows the magic length. */
683 while (cur_run_len >= 4) {
684 unsigned additional_bits;
686 additional_bits = min(cur_run_len - 4, 0xf);
687 num_additional_bits += 4;
689 output_syms[output_syms_idx++] = 17;
690 output_syms[output_syms_idx++] = additional_bits;
691 cur_run_len -= 4 + additional_bits;
696 /* A run of nonzero lengths. */
698 /* The magic length 19 indicates a run of 4 + n
699 * nonzeroes, where n is a literal bit that follows the
700 * magic length, and where the value of the lengths in
701 * the run is given by an extra length symbol, encoded
702 * with the precode, that follows the literal bit.
704 * The extra length symbol is encoded as a difference
705 * from the length of the codeword for the first symbol
706 * in the run in the previous code.
708 while (cur_run_len >= 4) {
709 unsigned additional_bits;
712 additional_bits = (cur_run_len > 4);
713 num_additional_bits += 1;
714 delta = (signed char)prev_lens[i - cur_run_len] -
715 (signed char)len_in_run;
719 precode_freqs[(unsigned char)delta]++;
720 output_syms[output_syms_idx++] = 19;
721 output_syms[output_syms_idx++] = additional_bits;
722 output_syms[output_syms_idx++] = delta;
723 cur_run_len -= 4 + additional_bits;
727 /* Any remaining lengths in the run are outputted without RLE,
728 * as a difference from the length of that codeword in the
730 while (cur_run_len > 0) {
733 delta = (signed char)prev_lens[i - cur_run_len] -
734 (signed char)len_in_run;
738 precode_freqs[(unsigned char)delta]++;
739 output_syms[output_syms_idx++] = delta;
746 /* Build the precode from the frequencies of the length symbols. */
748 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
749 LZX_MAX_PRE_CODEWORD_LEN,
750 precode_freqs, precode_lens,
753 *num_additional_bits_ret = num_additional_bits;
755 return output_syms_idx;
759 * Writes a compressed Huffman code to the output, preceded by the precode for
762 * The Huffman code is represented in the output as a series of path lengths
763 * from which the canonical Huffman code can be reconstructed. The path lengths
764 * themselves are compressed using a separate Huffman code, the precode, which
765 * consists of LZX_PRECODE_NUM_SYMBOLS (= 20) symbols that cover all possible
766 * code lengths, plus extra codes for repeated lengths. The path lengths of the
767 * precode precede the path lengths of the larger code and are uncompressed,
768 * consisting of 20 entries of 4 bits each.
770 * @out: Bitstream to write the code to.
771 * @lens: The code lengths for the Huffman code, indexed by symbol.
772 * @prev_lens: Code lengths for this Huffman code, indexed by symbol,
773 * in the *previous block*, or all zeroes if this is the
775 * @num_syms: The number of symbols in the code.
778 lzx_write_compressed_code(struct output_bitstream *out,
779 const u8 lens[restrict],
780 const u8 prev_lens[restrict],
783 input_idx_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
784 u8 output_syms[num_syms];
785 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
786 u16 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
788 unsigned num_output_syms;
792 num_output_syms = lzx_build_precode(lens,
801 /* Write the lengths of the precode codes to the output. */
802 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
803 bitstream_put_bits(out, precode_lens[i],
804 LZX_PRECODE_ELEMENT_SIZE);
806 /* Write the length symbols, encoded with the precode, to the output. */
808 for (i = 0; i < num_output_syms; ) {
809 precode_sym = output_syms[i++];
811 bitstream_put_bits(out, precode_codewords[precode_sym],
812 precode_lens[precode_sym]);
813 switch (precode_sym) {
815 bitstream_put_bits(out, output_syms[i++], 4);
818 bitstream_put_bits(out, output_syms[i++], 5);
821 bitstream_put_bits(out, output_syms[i++], 1);
822 bitstream_put_bits(out,
823 precode_codewords[output_syms[i]],
824 precode_lens[output_syms[i]]);
834 * Writes all compressed matches and literal bytes in an LZX block to the the
838 * The output bitstream.
840 * The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM).
842 * The array of matches/literals that will be output (length @match_count).
844 * Number of matches/literals to be output.
846 * Pointer to a structure that contains the codewords for the main, length,
847 * and aligned offset Huffman codes.
850 lzx_write_matches_and_literals(struct output_bitstream *ostream,
852 const struct lzx_match match_tab[],
853 unsigned match_count,
854 const struct lzx_codes *codes)
856 for (unsigned i = 0; i < match_count; i++) {
857 struct lzx_match match = match_tab[i];
859 /* High bit of the match indicates whether the match is an
860 * actual match (1) or a literal uncompressed byte (0) */
861 if (match.data & 0x80000000) {
863 lzx_write_match(ostream, block_type,
867 bitstream_put_bits(ostream,
868 codes->codewords.main[match.data],
869 codes->lens.main[match.data]);
875 lzx_assert_codes_valid(const struct lzx_codes * codes, unsigned num_main_syms)
877 #ifdef ENABLE_LZX_DEBUG
880 for (i = 0; i < num_main_syms; i++)
881 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
883 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
884 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
886 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
887 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
889 const unsigned tablebits = 10;
890 u16 decode_table[(1 << tablebits) +
891 (2 * max(num_main_syms, LZX_LENCODE_NUM_SYMBOLS))]
892 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
893 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
895 min(tablebits, LZX_MAINCODE_TABLEBITS),
897 LZX_MAX_MAIN_CODEWORD_LEN));
898 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
899 LZX_LENCODE_NUM_SYMBOLS,
900 min(tablebits, LZX_LENCODE_TABLEBITS),
902 LZX_MAX_LEN_CODEWORD_LEN));
903 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
904 LZX_ALIGNEDCODE_NUM_SYMBOLS,
905 min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
907 LZX_MAX_ALIGNED_CODEWORD_LEN));
908 #endif /* ENABLE_LZX_DEBUG */
911 /* Write an LZX aligned offset or verbatim block to the output. */
913 lzx_write_compressed_block(int block_type,
915 unsigned max_window_size,
916 unsigned num_main_syms,
917 struct lzx_match * chosen_matches,
918 unsigned num_chosen_matches,
919 const struct lzx_codes * codes,
920 const struct lzx_codes * prev_codes,
921 struct output_bitstream * ostream)
925 LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
926 block_type == LZX_BLOCKTYPE_VERBATIM);
927 lzx_assert_codes_valid(codes, num_main_syms);
929 /* The first three bits indicate the type of block and are one of the
930 * LZX_BLOCKTYPE_* constants. */
931 bitstream_put_bits(ostream, block_type, 3);
933 /* Output the block size.
935 * The original LZX format seemed to always encode the block size in 3
936 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
937 * uses the first bit to indicate whether the block is the default size
938 * (32768) or a different size given explicitly by the next 16 bits.
940 * By default, this compressor uses a window size of 32768 and therefore
941 * follows the WIMGAPI behavior. However, this compressor also supports
942 * window sizes greater than 32768 bytes, which do not appear to be
943 * supported by WIMGAPI. In such cases, we retain the default size bit
944 * to mean a size of 32768 bytes but output non-default block size in 24
945 * bits rather than 16. The compatibility of this behavior is unknown
946 * because WIMs created with chunk size greater than 32768 can seemingly
947 * only be opened by wimlib anyway. */
948 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
949 bitstream_put_bits(ostream, 1, 1);
951 bitstream_put_bits(ostream, 0, 1);
953 if (max_window_size >= 65536)
954 bitstream_put_bits(ostream, block_size >> 16, 8);
956 bitstream_put_bits(ostream, block_size, 16);
959 /* Write out lengths of the main code. Note that the LZX specification
960 * incorrectly states that the aligned offset code comes after the
961 * length code, but in fact it is the very first code to be written
962 * (before the main code). */
963 if (block_type == LZX_BLOCKTYPE_ALIGNED)
964 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
965 bitstream_put_bits(ostream, codes->lens.aligned[i],
966 LZX_ALIGNEDCODE_ELEMENT_SIZE);
968 LZX_DEBUG("Writing main code...");
970 /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
971 * the main code, which are the codewords for literal bytes. */
972 lzx_write_compressed_code(ostream,
974 prev_codes->lens.main,
977 /* Write the precode and lengths for the rest of the main code, which
978 * are the codewords for match headers. */
979 lzx_write_compressed_code(ostream,
980 codes->lens.main + LZX_NUM_CHARS,
981 prev_codes->lens.main + LZX_NUM_CHARS,
982 num_main_syms - LZX_NUM_CHARS);
984 LZX_DEBUG("Writing length code...");
986 /* Write the precode and lengths for the length code. */
987 lzx_write_compressed_code(ostream,
989 prev_codes->lens.len,
990 LZX_LENCODE_NUM_SYMBOLS);
992 LZX_DEBUG("Writing matches and literals...");
994 /* Write the actual matches and literals. */
995 lzx_write_matches_and_literals(ostream, block_type,
996 chosen_matches, num_chosen_matches,
999 LZX_DEBUG("Done writing block.");
1002 /* Write out the LZX blocks that were computed. */
1004 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
1007 const struct lzx_codes *prev_codes = &ctx->zero_codes;
1008 for (unsigned i = 0; i < ctx->num_blocks; i++) {
1009 const struct lzx_block_spec *spec = &ctx->block_specs[i];
1011 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
1012 i + 1, ctx->num_blocks,
1013 spec->block_type, spec->block_size,
1014 spec->num_chosen_matches);
1016 lzx_write_compressed_block(spec->block_type,
1018 ctx->max_window_size,
1020 &ctx->chosen_matches[spec->chosen_matches_start_pos],
1021 spec->num_chosen_matches,
1026 prev_codes = &spec->codes;
1030 /* Constructs an LZX match from a literal byte and updates the main code symbol
1033 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
1039 /* Constructs an LZX match from an offset and a length, and updates the LRU
1040 * queue and the frequency of symbols in the main, length, and aligned offset
1041 * alphabets. The return value is a 32-bit number that provides the match in an
1042 * intermediate representation documented below. */
1044 lzx_tally_match(unsigned match_len, unsigned match_offset,
1045 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
1047 unsigned position_slot;
1048 unsigned position_footer;
1050 unsigned main_symbol;
1051 unsigned len_footer;
1052 unsigned adjusted_match_len;
1054 LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
1056 /* The match offset shall be encoded as a position slot (itself encoded
1057 * as part of the main symbol) and a position footer. */
1058 position_slot = lzx_get_position_slot(match_offset, queue);
1059 position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1060 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1062 /* The match length shall be encoded as a length header (itself encoded
1063 * as part of the main symbol) and an optional length footer. */
1064 adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1065 if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1066 /* No length footer needed. */
1067 len_header = adjusted_match_len;
1069 /* Length footer needed. It will be encoded using the length
1071 len_header = LZX_NUM_PRIMARY_LENS;
1072 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1073 freqs->len[len_footer]++;
1076 /* Account for the main symbol. */
1077 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1079 freqs->main[main_symbol]++;
1081 /* In an aligned offset block, 3 bits of the position footer are output
1082 * as an aligned offset symbol. Account for this, although we may
1083 * ultimately decide to output the block as verbatim. */
1085 /* The following check is equivalent to:
1087 * if (lzx_extra_bits[position_slot] >= 3)
1089 * Note that this correctly excludes position slots that correspond to
1090 * recent offsets. */
1091 if (position_slot >= 8)
1092 freqs->aligned[position_footer & 7]++;
1094 /* Pack the position slot, position footer, and match length into an
1095 * intermediate representation. See `struct lzx_match' for details.
1097 LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
1098 LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
1099 LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
1101 LZX_ASSERT(position_slot <= (1U << (31 - 25)) - 1);
1102 LZX_ASSERT(position_footer <= (1U << (25 - 8)) - 1);
1103 LZX_ASSERT(adjusted_match_len <= (1U << (8 - 0)) - 1);
1105 (position_slot << 25) |
1106 (position_footer << 8) |
1107 (adjusted_match_len);
1110 struct lzx_record_ctx {
1111 struct lzx_freqs freqs;
1112 struct lzx_lru_queue queue;
1113 struct lzx_match *matches;
1117 lzx_record_match(unsigned len, unsigned offset, void *_ctx)
1119 struct lzx_record_ctx *ctx = _ctx;
1121 (ctx->matches++)->data = lzx_tally_match(len, offset, &ctx->freqs, &ctx->queue);
1125 lzx_record_literal(u8 lit, void *_ctx)
1127 struct lzx_record_ctx *ctx = _ctx;
1129 (ctx->matches++)->data = lzx_tally_literal(lit, &ctx->freqs);
1132 /* Returns the cost, in bits, to output a literal byte using the specified cost
1135 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1137 return costs->main[c];
1140 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1141 * well as costs for the codewords in the main, length, and aligned Huffman
1142 * codes, return the approximate number of bits it will take to represent this
1143 * match in the compressed output. Take into account the match offset LRU
1144 * queue and optionally update it. */
1146 lzx_match_cost(unsigned length, unsigned offset, const struct lzx_costs *costs,
1147 struct lzx_lru_queue *queue)
1149 unsigned position_slot;
1150 unsigned len_header, main_symbol;
1153 position_slot = lzx_get_position_slot(offset, queue);
1155 len_header = min(length - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1156 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1158 /* Account for main symbol. */
1159 cost += costs->main[main_symbol];
1161 /* Account for extra position information. */
1162 unsigned num_extra_bits = lzx_get_num_extra_bits(position_slot);
1163 if (num_extra_bits >= 3) {
1164 cost += num_extra_bits - 3;
1165 cost += costs->aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1167 cost += num_extra_bits;
1170 /* Account for extra length information. */
1171 if (len_header == LZX_NUM_PRIMARY_LENS)
1172 cost += costs->len[length - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1178 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
1179 * Unlike lzx_match_cost() which does a true cost evaluation, this simply
1180 * prioritize matches based on their offset. */
1182 lzx_match_cost_fast(unsigned offset, const struct lzx_lru_queue *queue)
1184 /* It seems well worth it to take the time to give priority to recently
1186 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
1187 if (offset == queue->R[i])
1190 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE >= (block_cost_t)~0U);
1194 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1197 * The cost model and codeword lengths are almost the same thing, but the
1198 * Huffman codewords with length 0 correspond to symbols with zero frequency
1199 * that still need to be assigned actual costs. The specific values assigned
1200 * are arbitrary, but they should be fairly high (near the maximum codeword
1201 * length) to take into account the fact that uses of these symbols are expected
1204 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1207 unsigned num_main_syms = ctx->num_main_syms;
1210 for (i = 0; i < num_main_syms; i++) {
1211 ctx->costs.main[i] = lens->main[i];
1212 if (ctx->costs.main[i] == 0)
1213 ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1217 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1218 ctx->costs.len[i] = lens->len[i];
1219 if (ctx->costs.len[i] == 0)
1220 ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1223 /* Aligned offset code */
1224 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1225 ctx->costs.aligned[i] = lens->aligned[i];
1226 if (ctx->costs.aligned[i] == 0)
1227 ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1231 /* Advance the suffix array match-finder to the next position. */
1233 lzx_lz_update_salink(input_idx_t i,
1234 const input_idx_t SA[restrict],
1235 const input_idx_t ISA[restrict],
1236 struct salink link[restrict])
1238 /* r = Rank of the suffix at the current position. */
1239 const input_idx_t r = ISA[i];
1241 /* next = rank of LOWEST ranked suffix that is ranked HIGHER than the
1242 * current suffix AND has a LOWER position, or -1 if none exists. */
1243 const input_idx_t next = link[r].next;
1245 /* prev = rank of HIGHEST ranked suffix that is ranked LOWER than the
1246 * current suffix AND has a LOWER position, or -1 if none exists. */
1247 const input_idx_t prev = link[r].prev;
1249 /* Link the suffix at the current position into the linked list that
1250 * contains all suffixes in the suffix array that are appear at or
1251 * before the current position, sorted by rank.
1253 * Save the values of all fields we overwrite so that rollback is
1255 if (next != (input_idx_t)~0U) {
1257 link[next].prev = r;
1258 link[next].lcpprev = link[r].lcpnext;
1261 if (prev != (input_idx_t)~0U) {
1263 link[prev].next = r;
1264 link[prev].lcpnext = link[r].lcpprev;
1269 * Use the suffix array match-finder to retrieve a list of LZ matches at the
1272 * [in] @i Current position in the window.
1273 * [in] @SA Suffix array for the window.
1274 * [in] @ISA Inverse suffix array for the window.
1275 * [inout] @link Suffix array links used internally by the match-finder.
1276 * [out] @matches The (length, offset) pairs of the resulting matches will
1277 * be written here, sorted in decreasing order by
1278 * length. All returned lengths will be unique.
1279 * [in] @queue Recently used match offsets, used when evaluating the
1281 * [in] @min_match_len Minimum match length to return.
1282 * [in] @max_matches_to_consider Maximum number of matches to consider at
1284 * [in] @max_matches_to_return Maximum number of matches to return.
1286 * The return value is the number of matches found and written to @matches.
1289 lzx_lz_get_matches(const input_idx_t i,
1290 const input_idx_t SA[const restrict],
1291 const input_idx_t ISA[const restrict],
1292 struct salink link[const restrict],
1293 struct raw_match matches[const restrict],
1294 const struct lzx_lru_queue * const restrict queue,
1295 const unsigned min_match_len,
1296 const u32 max_matches_to_consider,
1297 const u32 max_matches_to_return)
1299 /* r = Rank of the suffix at the current position. */
1300 const input_idx_t r = ISA[i];
1302 /* Prepare for searching the current position. */
1303 lzx_lz_update_salink(i, SA, ISA, link);
1305 /* L = rank of next suffix to the left;
1306 * R = rank of next suffix to the right;
1307 * lenL = length of match between current position and the suffix with rank L;
1308 * lenR = length of match between current position and the suffix with rank R.
1310 * This is left and right relative to the rank of the current suffix.
1311 * Since the suffixes in the suffix array are sorted, the longest
1312 * matches are immediately to the left and right (using the linked list
1313 * to ignore all suffixes that occur later in the window). The match
1314 * length decreases the farther left and right we go. We shall keep the
1315 * length on both sides in sync in order to choose the lowest-cost match
1318 input_idx_t L = link[r].prev;
1319 input_idx_t R = link[r].next;
1320 input_idx_t lenL = link[r].lcpprev;
1321 input_idx_t lenR = link[r].lcpnext;
1323 /* nmatches = number of matches found so far. */
1324 unsigned nmatches = 0;
1326 /* best_cost = cost of lowest-cost match found so far.
1328 * We keep track of this so that we can ignore shorter matches that do
1329 * not have lower costs than a longer matches already found.
1331 block_cost_t best_cost = INFINITE_BLOCK_COST;
1333 /* count_remaining = maximum number of possible matches remaining to be
1335 u32 count_remaining = max_matches_to_consider;
1337 /* pending = match currently being considered for a specific length. */
1338 struct raw_match pending;
1339 block_cost_t pending_cost;
1341 while (lenL >= min_match_len || lenR >= min_match_len)
1344 pending_cost = INFINITE_BLOCK_COST;
1348 if (lenL >= min_match_len && lenL >= lenR) {
1351 if (--count_remaining == 0)
1352 goto out_save_pending;
1354 input_idx_t offset = i - SA[L];
1356 /* Save match if it has smaller cost. */
1357 cost = lzx_match_cost_fast(offset, queue);
1358 if (cost < pending_cost) {
1359 pending.offset = offset;
1360 pending_cost = cost;
1363 if (link[L].lcpprev < lenL) {
1364 /* Match length decreased. */
1366 lenL = link[L].lcpprev;
1368 /* Save the pending match unless the
1369 * right side still may have matches of
1370 * this length to be scanned, or if a
1371 * previous (longer) match had lower
1373 if (pending.len > lenR) {
1374 if (pending_cost < best_cost) {
1375 best_cost = pending_cost;
1376 matches[nmatches++] = pending;
1377 if (nmatches == max_matches_to_return)
1381 pending_cost = INFINITE_BLOCK_COST;
1383 if (lenL < min_match_len || lenL < lenR)
1393 if (lenR >= min_match_len && lenR > lenL) {
1396 if (--count_remaining == 0)
1397 goto out_save_pending;
1399 input_idx_t offset = i - SA[R];
1401 /* Save match if it has smaller cost. */
1402 cost = lzx_match_cost_fast(offset, queue);
1403 if (cost < pending_cost) {
1404 pending.offset = offset;
1405 pending_cost = cost;
1408 if (link[R].lcpnext < lenR) {
1409 /* Match length decreased. */
1411 lenR = link[R].lcpnext;
1413 /* Save the pending match unless a
1414 * previous (longer) match had lower
1416 if (pending_cost < best_cost) {
1417 matches[nmatches++] = pending;
1418 best_cost = pending_cost;
1419 if (nmatches == max_matches_to_return)
1423 if (lenR < min_match_len || lenR <= lenL)
1427 pending_cost = INFINITE_BLOCK_COST;
1436 if (pending_cost != INFINITE_BLOCK_COST)
1437 matches[nmatches++] = pending;
1444 /* Tell the match-finder to skip the specified number of bytes (@n) in the
1447 lzx_lz_skip_bytes(struct lzx_compressor *ctx, unsigned n)
1449 LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1450 if (ctx->matches_cached) {
1451 ctx->match_window_pos += n;
1453 ctx->cached_matches_pos +=
1454 ctx->cached_matches[ctx->cached_matches_pos].len + 1;
1458 ctx->cached_matches[ctx->cached_matches_pos++].len = 0;
1459 lzx_lz_update_salink(ctx->match_window_pos++, ctx->SA,
1460 ctx->ISA, ctx->salink);
1465 /* Retrieve a list of matches available at the next position in the input.
1467 * The matches are written to ctx->matches in decreasing order of length, and
1468 * the return value is the number of matches found. */
1470 lzx_lz_get_matches_caching(struct lzx_compressor *ctx,
1471 const struct lzx_lru_queue *queue,
1472 struct raw_match **matches_ret)
1474 unsigned num_matches;
1475 struct raw_match *matches;
1477 LZX_ASSERT(ctx->match_window_pos <= ctx->match_window_end);
1479 matches = &ctx->cached_matches[ctx->cached_matches_pos + 1];
1481 if (ctx->matches_cached) {
1482 num_matches = matches[-1].len;
1484 unsigned min_match_len = LZX_MIN_MATCH_LEN;
1485 if (!ctx->params.alg_params.slow.use_len2_matches)
1486 min_match_len = max(min_match_len, 3);
1487 const u32 max_search_depth = ctx->params.alg_params.slow.max_search_depth;
1488 const u32 max_matches_per_pos = ctx->params.alg_params.slow.max_matches_per_pos;
1490 if (unlikely(max_search_depth == 0 || max_matches_per_pos == 0))
1493 num_matches = lzx_lz_get_matches(ctx->match_window_pos,
1501 max_matches_per_pos);
1502 matches[-1].len = num_matches;
1504 ctx->cached_matches_pos += num_matches + 1;
1505 *matches_ret = matches;
1507 /* Cap the length of returned matches to the number of bytes remaining,
1508 * if it is not the whole window. */
1509 if (ctx->match_window_end < ctx->window_size) {
1510 unsigned maxlen = ctx->match_window_end - ctx->match_window_pos;
1511 for (unsigned i = 0; i < num_matches; i++)
1512 if (matches[i].len > maxlen)
1513 matches[i].len = maxlen;
1516 fprintf(stderr, "Pos %u/%u: %u matches\n",
1517 ctx->match_window_pos, ctx->match_window_end, num_matches);
1518 for (unsigned i = 0; i < num_matches; i++)
1519 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1522 #ifdef ENABLE_LZX_DEBUG
1523 for (unsigned i = 0; i < num_matches; i++) {
1524 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1525 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1526 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1527 LZX_ASSERT(matches[i].offset > 0);
1528 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1529 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1530 &ctx->window[ctx->match_window_pos - matches[i].offset],
1535 ctx->match_window_pos++;
1540 * Reverse the linked list of near-optimal matches so that they can be returned
1541 * in forwards order.
1543 * Returns the first match in the list.
1545 static struct raw_match
1546 lzx_lz_reverse_near_optimal_match_list(struct lzx_compressor *ctx,
1549 unsigned prev_link, saved_prev_link;
1550 unsigned prev_match_offset, saved_prev_match_offset;
1552 ctx->optimum_end_idx = cur_pos;
1554 saved_prev_link = ctx->optimum[cur_pos].prev.link;
1555 saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
1558 prev_link = saved_prev_link;
1559 prev_match_offset = saved_prev_match_offset;
1561 saved_prev_link = ctx->optimum[prev_link].prev.link;
1562 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
1564 ctx->optimum[prev_link].next.link = cur_pos;
1565 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
1567 cur_pos = prev_link;
1568 } while (cur_pos != 0);
1570 ctx->optimum_cur_idx = ctx->optimum[0].next.link;
1572 return (struct raw_match)
1573 { .len = ctx->optimum_cur_idx,
1574 .offset = ctx->optimum[0].next.match_offset,
1579 * lzx_lz_get_near_optimal_match() -
1581 * Choose the optimal match or literal to use at the next position in the input.
1583 * Unlike a greedy parser that always takes the longest match, or even a
1584 * parser with one match/literal look-ahead like zlib, the algorithm used here
1585 * may look ahead many matches/literals to determine the optimal match/literal to
1586 * output next. The motivation is that the compression ratio is improved if the
1587 * compressor can do things like use a shorter-than-possible match in order to
1588 * allow a longer match later, and also take into account the Huffman code cost
1589 * model rather than simply assuming that longer is better.
1591 * Still, this is not truly an optimal parser because very long matches are
1592 * taken immediately, and the raw match-finder takes some shortcuts. This is
1593 * done to avoid considering many different alternatives that are unlikely to
1594 * be significantly better.
1596 * This algorithm is based on that used in 7-Zip's DEFLATE encoder.
1598 * Each call to this function does one of two things:
1600 * 1. Build a near-optimal sequence of matches/literals, up to some point, that
1601 * will be returned by subsequent calls to this function, then return the
1606 * 2. Return the next match/literal previously computed by a call to this
1609 * This function relies on the following state in the compressor context:
1611 * ctx->window (read-only: preprocessed data being compressed)
1612 * ctx->cost (read-only: cost model to use)
1613 * ctx->optimum (internal state; leave uninitialized)
1614 * ctx->optimum_cur_idx (must set to 0 before first call)
1615 * ctx->optimum_end_idx (must set to 0 before first call)
1617 * Plus any state used by the raw match-finder.
1619 * The return value is a (length, offset) pair specifying the match or literal
1620 * chosen. For literals, the length is less than LZX_MIN_MATCH_LEN and the
1621 * offset is meaningless.
1623 static struct raw_match
1624 lzx_lz_get_near_optimal_match(struct lzx_compressor * ctx)
1626 unsigned num_possible_matches;
1627 struct raw_match *possible_matches;
1628 struct raw_match match;
1629 unsigned longest_match_len;
1631 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1632 /* Case 2: Return the next match/literal already found. */
1633 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1634 ctx->optimum_cur_idx;
1635 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1637 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1641 /* Case 1: Compute a new list of matches/literals to return. */
1643 ctx->optimum_cur_idx = 0;
1644 ctx->optimum_end_idx = 0;
1646 /* Get matches at this position. */
1647 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &possible_matches);
1649 /* If no matches found, return literal. */
1650 if (num_possible_matches == 0)
1651 return (struct raw_match){ .len = 0 };
1653 /* The matches that were found are sorted in decreasing order by length.
1654 * Get the length of the longest one. */
1655 longest_match_len = possible_matches[0].len;
1657 /* Greedy heuristic: if the longest match that was found is greater
1658 * than the number of fast bytes, return it immediately; don't both
1659 * doing more work. */
1660 if (longest_match_len > ctx->params.alg_params.slow.num_fast_bytes) {
1661 lzx_lz_skip_bytes(ctx, longest_match_len - 1);
1662 return possible_matches[0];
1665 /* Calculate the cost to reach the next position by outputting a
1667 ctx->optimum[0].queue = ctx->queue;
1668 ctx->optimum[1].queue = ctx->optimum[0].queue;
1669 ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos],
1671 ctx->optimum[1].prev.link = 0;
1673 /* Calculate the cost to reach any position up to and including that
1674 * reached by the longest match, using the shortest (i.e. closest) match
1675 * that reaches each position. */
1676 BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1677 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1678 len <= longest_match_len; len++) {
1680 LZX_ASSERT(match_idx < num_possible_matches);
1682 ctx->optimum[len].queue = ctx->optimum[0].queue;
1683 ctx->optimum[len].prev.link = 0;
1684 ctx->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
1685 ctx->optimum[len].cost = lzx_match_cost(len,
1686 possible_matches[match_idx].offset,
1688 &ctx->optimum[len].queue);
1689 if (len == possible_matches[match_idx].len)
1693 unsigned cur_pos = 0;
1695 /* len_end: greatest index forward at which costs have been calculated
1697 unsigned len_end = longest_match_len;
1700 /* Advance to next position. */
1703 if (cur_pos == len_end || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1704 return lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1706 /* retrieve the number of matches available at this position */
1707 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->optimum[cur_pos].queue,
1710 unsigned new_len = 0;
1712 if (num_possible_matches != 0) {
1713 new_len = possible_matches[0].len;
1715 /* Greedy heuristic: if we found a match greater than
1716 * the number of fast bytes, stop immediately. */
1717 if (new_len > ctx->params.alg_params.slow.num_fast_bytes) {
1719 /* Build the list of matches to return and get
1721 match = lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1723 /* Append the long match to the end of the list. */
1724 ctx->optimum[cur_pos].next.match_offset =
1725 possible_matches[0].offset;
1726 ctx->optimum[cur_pos].next.link = cur_pos + new_len;
1727 ctx->optimum_end_idx = cur_pos + new_len;
1729 /* Skip over the remaining bytes of the long match. */
1730 lzx_lz_skip_bytes(ctx, new_len - 1);
1732 /* Return first match in the list */
1737 /* Consider proceeding with a literal byte. */
1738 block_cost_t cur_cost = ctx->optimum[cur_pos].cost;
1739 block_cost_t cur_plus_literal_cost = cur_cost +
1740 lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1742 if (cur_plus_literal_cost < ctx->optimum[cur_pos + 1].cost) {
1743 ctx->optimum[cur_pos + 1].cost = cur_plus_literal_cost;
1744 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1745 ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1748 if (num_possible_matches == 0)
1751 /* Consider proceeding with a match. */
1753 while (len_end < cur_pos + new_len)
1754 ctx->optimum[++len_end].cost = INFINITE_BLOCK_COST;
1756 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1757 len <= new_len; len++) {
1758 LZX_ASSERT(match_idx < num_possible_matches);
1759 struct lzx_lru_queue q = ctx->optimum[cur_pos].queue;
1760 block_cost_t cost = cur_cost + lzx_match_cost(len,
1761 possible_matches[match_idx].offset,
1765 if (cost < ctx->optimum[cur_pos + len].cost) {
1766 ctx->optimum[cur_pos + len].cost = cost;
1767 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1768 ctx->optimum[cur_pos + len].prev.match_offset =
1769 possible_matches[match_idx].offset;
1770 ctx->optimum[cur_pos + len].queue = q;
1773 if (len == possible_matches[match_idx].len)
1780 * Set default symbol costs.
1783 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1787 /* Literal symbols */
1788 for (i = 0; i < LZX_NUM_CHARS; i++)
1791 /* Match header symbols */
1792 for (; i < num_main_syms; i++)
1793 costs->main[i] = 10;
1795 /* Length symbols */
1796 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1799 /* Aligned offset symbols */
1800 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1801 costs->aligned[i] = 3;
1804 /* Given the frequencies of symbols in a compressed block and the corresponding
1805 * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1806 * aligned offset or verbatim block, respectively, will take fewer bits to
1809 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1810 const struct lzx_codes * codes)
1812 unsigned aligned_cost = 0;
1813 unsigned verbatim_cost = 0;
1815 /* Verbatim blocks have a constant 3 bits per position footer. Aligned
1816 * offset blocks have an aligned offset symbol per position footer, plus
1817 * an extra 24 bits to output the lengths necessary to reconstruct the
1818 * aligned offset code itself. */
1819 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1820 verbatim_cost += 3 * freqs->aligned[i];
1821 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1823 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1824 if (aligned_cost < verbatim_cost)
1825 return LZX_BLOCKTYPE_ALIGNED;
1827 return LZX_BLOCKTYPE_VERBATIM;
1830 /* Find a near-optimal sequence of matches/literals with which to output the
1831 * specified LZX block, then set its type to that which has the minimum cost to
1834 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1835 unsigned num_passes)
1837 const struct lzx_lru_queue orig_queue = ctx->queue;
1838 struct lzx_freqs freqs;
1840 unsigned orig_window_pos = spec->window_pos;
1841 unsigned orig_cached_pos = ctx->cached_matches_pos;
1843 LZX_ASSERT(ctx->match_window_pos == spec->window_pos);
1845 ctx->match_window_end = spec->window_pos + spec->block_size;
1846 spec->chosen_matches_start_pos = spec->window_pos;
1848 LZX_ASSERT(num_passes >= 1);
1850 /* The first optimal parsing pass is done using the cost model already
1851 * set in ctx->costs. Each later pass is done using a cost model
1852 * computed from the previous pass. */
1853 for (unsigned pass = 0; pass < num_passes; pass++) {
1855 ctx->match_window_pos = orig_window_pos;
1856 ctx->cached_matches_pos = orig_cached_pos;
1857 ctx->queue = orig_queue;
1858 spec->num_chosen_matches = 0;
1859 memset(&freqs, 0, sizeof(freqs));
1861 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
1862 struct raw_match raw_match;
1863 struct lzx_match lzx_match;
1865 raw_match = lzx_lz_get_near_optimal_match(ctx);
1866 if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1867 lzx_match.data = lzx_tally_match(raw_match.len, raw_match.offset,
1868 &freqs, &ctx->queue);
1871 lzx_match.data = lzx_tally_literal(ctx->window[i], &freqs);
1874 ctx->chosen_matches[spec->chosen_matches_start_pos +
1875 spec->num_chosen_matches++] = lzx_match;
1878 lzx_make_huffman_codes(&freqs, &spec->codes,
1879 ctx->num_main_syms);
1880 if (pass < num_passes - 1)
1881 lzx_set_costs(ctx, &spec->codes.lens);
1882 ctx->matches_cached = true;
1884 spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1885 ctx->matches_cached = false;
1889 lzx_optimize_blocks(struct lzx_compressor *ctx)
1891 lzx_lru_queue_init(&ctx->queue);
1892 ctx->optimum_cur_idx = 0;
1893 ctx->optimum_end_idx = 0;
1895 const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
1897 for (unsigned i = 0; i < ctx->num_blocks; i++)
1898 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
1901 /* Initialize the suffix array match-finder for the specified input. */
1903 lzx_lz_init_matchfinder(const u8 T[const restrict],
1904 const input_idx_t n,
1905 input_idx_t SA[const restrict],
1906 input_idx_t ISA[const restrict],
1907 input_idx_t LCP[const restrict],
1908 struct salink link[const restrict],
1909 const unsigned max_match_len)
1911 /* Compute SA (Suffix Array). */
1914 /* ISA and link are used as temporary space. */
1915 BUILD_BUG_ON(LZX_MIN_WINDOW_SIZE * sizeof(ISA[0]) < 256 * sizeof(saidx_t));
1916 BUILD_BUG_ON(LZX_MIN_WINDOW_SIZE * 2 * sizeof(link[0]) < 256 * 256 * sizeof(saidx_t));
1918 if (sizeof(input_idx_t) == sizeof(saidx_t)) {
1919 divsufsort(T, SA, n, (saidx_t*)ISA, (saidx_t*)link);
1922 divsufsort(T, sa, n, (saidx_t*)ISA, (saidx_t*)link);
1923 for (input_idx_t i = 0; i < n; i++)
1928 #ifdef ENABLE_LZX_DEBUG
1932 /* Verify suffix array. */
1936 for (input_idx_t r = 0; r < n; r++) {
1937 input_idx_t i = SA[r];
1939 LZX_ASSERT(!found[i]);
1944 for (input_idx_t r = 0; r < n - 1; r++) {
1946 input_idx_t i1 = SA[r];
1947 input_idx_t i2 = SA[r + 1];
1949 input_idx_t n1 = n - i1;
1950 input_idx_t n2 = n - i2;
1952 LZX_ASSERT(memcmp(&T[i1], &T[i2], min(n1, n2)) <= 0);
1954 LZX_DEBUG("Verified SA (len %u)", n);
1955 #endif /* ENABLE_LZX_DEBUG */
1957 /* Compute ISA (Inverse Suffix Array) */
1958 for (input_idx_t r = 0; r < n; r++)
1961 /* Compute LCP (longest common prefix) array.
1963 * Algorithm adapted from Kasai et al. 2001: "Linear-Time
1964 * Longest-Common-Prefix Computation in Suffix Arrays and Its
1968 for (input_idx_t i = 0; i < n; i++) {
1969 input_idx_t r = ISA[i];
1971 input_idx_t j = SA[r - 1];
1973 input_idx_t lim = min(n - i, n - j);
1975 while (h < lim && T[i + h] == T[j + h])
1984 #ifdef ENABLE_LZX_DEBUG
1985 /* Verify LCP array. */
1986 for (input_idx_t r = 0; r < n - 1; r++) {
1987 LZX_ASSERT(ISA[SA[r]] == r);
1988 LZX_ASSERT(ISA[SA[r + 1]] == r + 1);
1990 input_idx_t i1 = SA[r];
1991 input_idx_t i2 = SA[r + 1];
1992 input_idx_t lcp = LCP[r + 1];
1994 input_idx_t n1 = n - i1;
1995 input_idx_t n2 = n - i2;
1997 LZX_ASSERT(lcp <= min(n1, n2));
1999 LZX_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
2000 if (lcp < min(n1, n2))
2001 LZX_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
2003 #endif /* ENABLE_LZX_DEBUG */
2005 /* Compute salink.next and salink.lcpnext.
2007 * Algorithm adapted from Crochemore et al. 2009:
2008 * "LPF computation revisited".
2010 * Note: we cap lcpnext to the maximum match length so that the
2011 * match-finder need not worry about it later. */
2012 link[n - 1].next = (input_idx_t)~0U;
2013 link[n - 1].prev = (input_idx_t)~0U;
2014 link[n - 1].lcpnext = 0;
2015 link[n - 1].lcpprev = 0;
2016 for (input_idx_t r = n - 2; r != (input_idx_t)~0U; r--) {
2017 input_idx_t t = r + 1;
2018 input_idx_t l = LCP[t];
2019 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2020 l = min(l, link[t].lcpnext);
2024 link[r].lcpnext = min(l, max_match_len);
2025 LZX_ASSERT(t == (input_idx_t)~0U || l <= n - SA[t]);
2026 LZX_ASSERT(l <= n - SA[r]);
2027 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2030 /* Compute salink.prev and salink.lcpprev.
2032 * Algorithm adapted from Crochemore et al. 2009:
2033 * "LPF computation revisited".
2035 * Note: we cap lcpprev to the maximum match length so that the
2036 * match-finder need not worry about it later. */
2037 link[0].prev = (input_idx_t)~0;
2038 link[0].next = (input_idx_t)~0;
2039 link[0].lcpprev = 0;
2040 link[0].lcpnext = 0;
2041 for (input_idx_t r = 1; r < n; r++) {
2042 input_idx_t t = r - 1;
2043 input_idx_t l = LCP[r];
2044 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2045 l = min(l, link[t].lcpprev);
2049 link[r].lcpprev = min(l, max_match_len);
2050 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2051 LZX_ASSERT(l <= n - SA[r]);
2052 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2056 /* Prepare the input window into one or more LZX blocks ready to be output. */
2058 lzx_prepare_blocks(struct lzx_compressor * ctx)
2060 /* Initialize the match-finder. */
2061 lzx_lz_init_matchfinder(ctx->window, ctx->window_size,
2062 ctx->SA, ctx->ISA, ctx->LCP, ctx->salink,
2064 ctx->cached_matches_pos = 0;
2065 ctx->matches_cached = false;
2066 ctx->match_window_pos = 0;
2068 /* Set up a default cost model. */
2069 lzx_set_default_costs(&ctx->costs, ctx->num_main_syms);
2071 ctx->num_blocks = DIV_ROUND_UP(ctx->window_size, LZX_DIV_BLOCK_SIZE);
2072 for (unsigned i = 0; i < ctx->num_blocks; i++) {
2073 unsigned pos = LZX_DIV_BLOCK_SIZE * i;
2074 ctx->block_specs[i].window_pos = pos;
2075 ctx->block_specs[i].block_size = min(ctx->window_size - pos, LZX_DIV_BLOCK_SIZE);
2078 /* Determine sequence of matches/literals to output for each block. */
2079 lzx_optimize_blocks(ctx);
2083 * This is the fast version of lzx_prepare_blocks(). This version "quickly"
2084 * prepares a single compressed block containing the entire input. See the
2085 * description of the "Fast algorithm" at the beginning of this file for more
2088 * Input --- the preprocessed data:
2093 * Output --- the block specification and the corresponding match/literal data:
2095 * ctx->block_specs[]
2097 * ctx->chosen_matches[]
2100 lzx_prepare_block_fast(struct lzx_compressor * ctx)
2102 struct lzx_record_ctx record_ctx;
2103 struct lzx_block_spec *spec;
2105 /* Parameters to hash chain LZ match finder
2106 * (lazy with 1 match lookahead) */
2107 static const struct lz_params lzx_lz_params = {
2108 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
2109 * aren't worth choosing when using greedy or lazy parsing. */
2111 .max_match = LZX_MAX_MATCH_LEN,
2112 .max_offset = LZX_MAX_WINDOW_SIZE,
2113 .good_match = LZX_MAX_MATCH_LEN,
2114 .nice_match = LZX_MAX_MATCH_LEN,
2115 .max_chain_len = LZX_MAX_MATCH_LEN,
2116 .max_lazy_match = LZX_MAX_MATCH_LEN,
2120 /* Initialize symbol frequencies and match offset LRU queue. */
2121 memset(&record_ctx.freqs, 0, sizeof(struct lzx_freqs));
2122 lzx_lru_queue_init(&record_ctx.queue);
2123 record_ctx.matches = ctx->chosen_matches;
2125 /* Determine series of matches/literals to output. */
2126 lz_analyze_block(ctx->window,
2134 /* Set up block specification. */
2135 spec = &ctx->block_specs[0];
2136 spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2137 spec->window_pos = 0;
2138 spec->block_size = ctx->window_size;
2139 spec->num_chosen_matches = (record_ctx.matches - ctx->chosen_matches);
2140 spec->chosen_matches_start_pos = 0;
2141 lzx_make_huffman_codes(&record_ctx.freqs, &spec->codes,
2142 ctx->num_main_syms);
2143 ctx->num_blocks = 1;
2147 do_call_insn_translation(u32 *call_insn_target, int input_pos,
2153 rel_offset = le32_to_cpu(*call_insn_target);
2154 if (rel_offset >= -input_pos && rel_offset < file_size) {
2155 if (rel_offset < file_size - input_pos) {
2156 /* "good translation" */
2157 abs_offset = rel_offset + input_pos;
2159 /* "compensating translation" */
2160 abs_offset = rel_offset - file_size;
2162 *call_insn_target = cpu_to_le32(abs_offset);
2166 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
2167 * See the comment above that function for more information. */
2169 do_call_insn_preprocessing(u8 data[], int size)
2171 for (int i = 0; i < size - 10; i++) {
2172 if (data[i] == 0xe8) {
2173 do_call_insn_translation((u32*)&data[i + 1], i,
2174 LZX_WIM_MAGIC_FILESIZE);
2181 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
2182 void *compressed_data, size_t compressed_size_avail, void *_ctx)
2184 struct lzx_compressor *ctx = _ctx;
2185 struct output_bitstream ostream;
2186 size_t compressed_size;
2188 if (uncompressed_size < 100) {
2189 LZX_DEBUG("Too small to bother compressing.");
2193 if (uncompressed_size > ctx->max_window_size) {
2194 LZX_DEBUG("Can't compress %zu bytes using window of %u bytes!",
2195 uncompressed_size, ctx->max_window_size);
2199 LZX_DEBUG("Attempting to compress %zu bytes...",
2202 /* The input data must be preprocessed. To avoid changing the original
2203 * input, copy it to a temporary buffer. */
2204 memcpy(ctx->window, uncompressed_data, uncompressed_size);
2205 ctx->window_size = uncompressed_size;
2207 /* This line is unnecessary; it just avoids inconsequential accesses of
2208 * uninitialized memory that would show up in memory-checking tools such
2210 memset(&ctx->window[ctx->window_size], 0, 12);
2212 LZX_DEBUG("Preprocessing data...");
2214 /* Before doing any actual compression, do the call instruction (0xe8
2215 * byte) translation on the uncompressed data. */
2216 do_call_insn_preprocessing(ctx->window, ctx->window_size);
2218 LZX_DEBUG("Preparing blocks...");
2220 /* Prepare the compressed data. */
2221 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2222 lzx_prepare_block_fast(ctx);
2224 lzx_prepare_blocks(ctx);
2226 LZX_DEBUG("Writing compressed blocks...");
2228 /* Generate the compressed data. */
2229 init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
2230 lzx_write_all_blocks(ctx, &ostream);
2232 LZX_DEBUG("Flushing bitstream...");
2233 compressed_size = flush_output_bitstream(&ostream);
2234 if (compressed_size == ~(input_idx_t)0) {
2235 LZX_DEBUG("Data did not compress to %zu bytes or less!",
2236 compressed_size_avail);
2240 LZX_DEBUG("Done: compressed %zu => %zu bytes.",
2241 uncompressed_size, compressed_size);
2243 /* Verify that we really get the same thing back when decompressing.
2244 * Although this could be disabled by default in all cases, it only
2245 * takes around 2-3% of the running time of the slow algorithm to do the
2247 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2248 #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2253 struct wimlib_decompressor *decompressor;
2255 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZX,
2256 ctx->max_window_size,
2261 ret = wimlib_decompress(compressed_data,
2266 wimlib_free_decompressor(decompressor);
2269 ERROR("Failed to decompress data we "
2270 "compressed using LZX algorithm");
2274 if (memcmp(uncompressed_data, ctx->window, uncompressed_size)) {
2275 ERROR("Data we compressed using LZX algorithm "
2276 "didn't decompress to original");
2281 WARNING("Failed to create decompressor for "
2282 "data verification!");
2285 return compressed_size;
2289 lzx_params_valid(const struct wimlib_lzx_compressor_params *params)
2291 /* Validate parameters. */
2292 if (params->hdr.size != sizeof(struct wimlib_lzx_compressor_params)) {
2293 LZX_DEBUG("Invalid parameter structure size!");
2297 if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2298 params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2300 LZX_DEBUG("Invalid algorithm.");
2304 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2305 if (params->alg_params.slow.num_optim_passes < 1)
2307 LZX_DEBUG("Invalid number of optimization passes!");
2311 if (params->alg_params.slow.main_nostat_cost < 1 ||
2312 params->alg_params.slow.main_nostat_cost > 16)
2314 LZX_DEBUG("Invalid main_nostat_cost!");
2318 if (params->alg_params.slow.len_nostat_cost < 1 ||
2319 params->alg_params.slow.len_nostat_cost > 16)
2321 LZX_DEBUG("Invalid len_nostat_cost!");
2325 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2326 params->alg_params.slow.aligned_nostat_cost > 8)
2328 LZX_DEBUG("Invalid aligned_nostat_cost!");
2336 lzx_free_compressor(void *_ctx)
2338 struct lzx_compressor *ctx = _ctx;
2341 FREE(ctx->chosen_matches);
2342 FREE(ctx->cached_matches);
2346 FREE(ctx->block_specs);
2347 FREE(ctx->prev_tab);
2354 lzx_create_compressor(size_t window_size,
2355 const struct wimlib_compressor_params_header *_params,
2358 const struct wimlib_lzx_compressor_params *params =
2359 (const struct wimlib_lzx_compressor_params*)_params;
2360 struct lzx_compressor *ctx;
2362 LZX_DEBUG("Allocating LZX context...");
2364 if (!lzx_window_size_valid(window_size))
2365 return WIMLIB_ERR_INVALID_PARAM;
2367 static const struct wimlib_lzx_compressor_params fast_default = {
2369 .size = sizeof(struct wimlib_lzx_compressor_params),
2371 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2378 static const struct wimlib_lzx_compressor_params slow_default = {
2380 .size = sizeof(struct wimlib_lzx_compressor_params),
2382 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2386 .use_len2_matches = 1,
2387 .num_fast_bytes = 32,
2388 .num_optim_passes = 2,
2389 .max_search_depth = 50,
2390 .max_matches_per_pos = 3,
2391 .main_nostat_cost = 15,
2392 .len_nostat_cost = 15,
2393 .aligned_nostat_cost = 7,
2399 if (!lzx_params_valid(params))
2400 return WIMLIB_ERR_INVALID_PARAM;
2402 LZX_DEBUG("Using default algorithm and parameters.");
2403 params = &slow_default;
2406 if (params->use_defaults) {
2407 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2408 params = &slow_default;
2410 params = &fast_default;
2413 LZX_DEBUG("Allocating memory.");
2415 ctx = CALLOC(1, sizeof(struct lzx_compressor));
2419 ctx->num_main_syms = lzx_get_num_main_syms(window_size);
2420 ctx->max_window_size = window_size;
2421 ctx->window = MALLOC(window_size + 12);
2422 if (ctx->window == NULL)
2425 if (params->algorithm == WIMLIB_LZX_ALGORITHM_FAST) {
2426 ctx->prev_tab = MALLOC(window_size * sizeof(ctx->prev_tab[0]));
2427 if (ctx->prev_tab == NULL)
2431 size_t block_specs_length = DIV_ROUND_UP(window_size, LZX_DIV_BLOCK_SIZE);
2432 ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2433 if (ctx->block_specs == NULL)
2436 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2437 ctx->SA = MALLOC(3U * window_size * sizeof(ctx->SA[0]));
2438 if (ctx->SA == NULL)
2440 ctx->ISA = ctx->SA + window_size;
2441 ctx->LCP = ctx->ISA + window_size;
2443 ctx->salink = MALLOC(window_size * sizeof(ctx->salink[0]));
2444 if (ctx->salink == NULL)
2448 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2449 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE + LZX_MAX_MATCH_LEN) *
2450 sizeof(ctx->optimum[0]));
2451 if (ctx->optimum == NULL)
2455 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2458 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
2459 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
2460 cache_per_pos = LZX_MAX_CACHE_PER_POS;
2462 ctx->cached_matches = MALLOC(window_size * (cache_per_pos + 1) *
2463 sizeof(ctx->cached_matches[0]));
2464 if (ctx->cached_matches == NULL)
2468 ctx->chosen_matches = MALLOC(window_size * sizeof(ctx->chosen_matches[0]));
2469 if (ctx->chosen_matches == NULL)
2472 memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_compressor_params));
2473 memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2475 LZX_DEBUG("Successfully allocated new LZX context.");
2481 lzx_free_compressor(ctx);
2482 return WIMLIB_ERR_NOMEM;
2485 const struct compressor_ops lzx_compressor_ops = {
2486 .create_compressor = lzx_create_compressor,
2487 .compress = lzx_compress,
2488 .free_compressor = lzx_free_compressor,