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 instructions
72 * 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
84 * lower position, the lowest higher ranked suffix that has a lower position,
85 * and the length of the common prefix shared between each. This
86 * information is later used to link suffix ranks into a doubly-linked list
87 * for searching the suffix array.
89 * 5. Set a default cost model for matches/literals.
91 * 6. Determine the lowest cost sequence of LZ77 matches ((offset, length) pairs)
92 * and literal bytes to divide the input into. Raw match-finding is done by
93 * searching the suffix array using a linked list to avoid considering any
94 * suffixes that start after the current position. Each run of the
95 * match-finder returns the approximate lowest-cost longest match as well as
96 * any shorter matches that have even lower approximate costs. Each such run
97 * also adds the suffix rank of the current position into the linked list
98 * being used to search the suffix array. Parsing, or match-choosing, is
99 * 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
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 * The old API (retained for backward compatibility) consists of just one function:
132 * wimlib_lzx_compress()
134 * The new compressor has more potential parameters and needs more memory, so
135 * the new API ties up memory allocations and compression parameters into a
138 * wimlib_lzx_alloc_context()
139 * wimlib_lzx_compress2()
140 * wimlib_lzx_free_context()
141 * wimlib_lzx_set_default_params()
143 * Both wimlib_lzx_compress() and wimlib_lzx_compress2() are designed to
144 * compress an in-memory buffer of up to 32768 bytes. There is no sliding
145 * window. This is suitable for the WIM format, which uses fixed-size chunks
146 * that are seemingly always 32768 bytes. If needed, the compressor potentially
147 * could be extended to support a larger and/or sliding window.
149 * Both wimlib_lzx_compress() and wimlib_lzx_compress2() return 0 if the data
150 * could not be compressed to less than the size of the uncompressed data.
151 * Again, this is suitable for the WIM format, which stores such data chunks
154 * The functions in this LZX compression API are exported from the library,
155 * although with the possible exception of wimlib_lzx_set_default_params(), this
156 * is only in case other programs happen to have uses for it other than WIM
157 * reading/writing as already handled through the rest of the library.
162 * Acknowledgments to several open-source projects and research papers that made
163 * it possible to implement this code:
165 * - divsufsort (author: Yuta Mori), for the suffix array construction code,
166 * located in a separate directory (divsufsort/).
168 * - "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its
169 * Applications" (Kasai et al. 2001), for the LCP array computation.
171 * - "LPF computation revisited" (Crochemore et al. 2009) for the prev and next
172 * array computations.
174 * - 7-Zip (author: Igor Pavlov) for the algorithm for forward optimal parsing
177 * - zlib (author: Jean-loup Gailly and Mark Adler), for the hash table
178 * match-finding algorithm (used in lz77.c).
180 * - lzx-compress (author: Matthew T. Russotto), on which some parts of this
181 * code were originally based.
189 #include "wimlib/compress.h"
190 #include "wimlib/error.h"
191 #include "wimlib/lzx.h"
192 #include "wimlib/util.h"
197 #ifdef ENABLE_LZX_DEBUG
198 # include <wimlib/decompress.h>
201 #include "divsufsort/divsufsort.h"
203 typedef freq_t input_idx_t;
204 typedef u32 block_cost_t;
205 #define INFINITE_BLOCK_COST ((block_cost_t)~0U)
207 #define LZX_OPTIM_ARRAY_SIZE 4096
209 /* Currently, this constant can't simply be changed because the code currently
210 * uses a static number of position slots (and may make other assumptions as
212 #define LZX_MAX_WINDOW_SIZE 32768
214 /* This may be WIM-specific */
215 #define LZX_DEFAULT_BLOCK_SIZE 32768
217 #define LZX_MAX_CACHE_PER_POS 10
219 /* Codewords for the LZX main, length, and aligned offset Huffman codes */
220 struct lzx_codewords {
221 u16 main[LZX_MAINCODE_NUM_SYMBOLS];
222 u16 len[LZX_LENCODE_NUM_SYMBOLS];
223 u16 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
226 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
229 * A 0 length means the codeword has zero frequency.
232 u8 main[LZX_MAINCODE_NUM_SYMBOLS];
233 u8 len[LZX_LENCODE_NUM_SYMBOLS];
234 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
237 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
239 * If a codeword has zero frequency, it must still be assigned some nonzero cost
240 * --- generally a high cost, since even if it gets used in the next iteration,
241 * it probably will not be used very times. */
243 u8 main[LZX_MAINCODE_NUM_SYMBOLS];
244 u8 len[LZX_LENCODE_NUM_SYMBOLS];
245 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
248 /* The LZX main, length, and aligned offset Huffman codes */
250 struct lzx_codewords codewords;
251 struct lzx_lens lens;
254 /* Tables for tallying symbol frequencies in the three LZX alphabets */
256 freq_t main[LZX_MAINCODE_NUM_SYMBOLS];
257 freq_t len[LZX_LENCODE_NUM_SYMBOLS];
258 freq_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
261 /* LZX intermediate match/literal format */
265 * 31 1 if a match, 0 if a literal.
267 * 30-25 position slot. This can be at most 50, so it will fit in 6
270 * 8-24 position footer. This is the offset of the real formatted
271 * offset from the position base. This can be at most 17 bits
272 * (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
274 * 0-7 length of match, minus 2. This can be at most
275 * (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits. */
279 /* Raw LZ match/literal format: just a length and offset.
281 * The length is the number of bytes of the match, and the offset is the number
282 * of bytes back in the input the match is from the current position.
284 * If @len < LZX_MIN_MATCH_LEN, then it's really just a literal byte and @offset is
291 /* Specification for an LZX block. */
292 struct lzx_block_spec {
294 /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
298 /* 0-based position in the window at which this block starts. */
299 input_idx_t window_pos;
301 /* The number of bytes of uncompressed data this block represents. */
302 input_idx_t block_size;
304 /* The position in the 'chosen_matches' array in the `struct
305 * lzx_compressor' at which the match/literal specifications for
306 * this block begin. */
307 input_idx_t chosen_matches_start_pos;
309 /* The number of match/literal specifications for this block. */
310 input_idx_t num_chosen_matches;
312 /* Huffman codes for this block. */
313 struct lzx_codes codes;
317 * An array of these structures is used during the match-choosing algorithm.
318 * They correspond to consecutive positions in the window and are used to keep
319 * track of the cost to reach each position, and the match/literal choices that
320 * need to be chosen to reach that position.
323 /* The approximate minimum cost, in bits, to reach this position in the
324 * window which has been found so far. */
327 /* The union here is just for clarity, since the fields are used in two
328 * slightly different ways. Initially, the @prev structure is filled in
329 * first, and links go from later in the window to earlier in the
330 * window. Later, @next structure is filled in and links go from
331 * earlier in the window to later in the window. */
334 /* Position of the start of the match or literal that
335 * was taken to get to this position in the approximate
336 * minimum-cost parse. */
339 /* Offset (as in an LZ (length, offset) pair) of the
340 * match or literal that was taken to get to this
341 * position in the approximate minimum-cost parse. */
342 input_idx_t match_offset;
345 /* Position at which the match or literal starting at
346 * this position ends in the minimum-cost parse. */
349 /* Offset (as in an LZ (length, offset) pair) of the
350 * match or literal starting at this position in the
351 * approximate minimum-cost parse. */
352 input_idx_t match_offset;
356 /* The match offset LRU queue that will exist when the approximate
357 * minimum-cost path to reach this position is taken. */
358 struct lzx_lru_queue queue;
361 /* Suffix array link */
363 /* Rank of highest ranked suffix that has rank lower than the suffix
364 * corresponding to this structure and either has a lower position
365 * (initially) or has a position lower than the highest position at
366 * which matches have been searched for so far, or -1 if there is no
370 /* Rank of lowest ranked suffix that has rank greater than the suffix
371 * corresponding to this structure and either has a lower position
372 * (intially) or has a position lower than the highest position at which
373 * matches have been searched for so far, or -1 if there is no such
377 /* Length of longest common prefix between the suffix corresponding to
378 * this structure and the suffix with rank @prev, or 0 if @prev is -1.
382 /* Length of longest common prefix between the suffix corresponding to
383 * this structure and the suffix with rank @next, or 0 if @next is -1.
388 /* State of the LZX compressor. */
389 struct lzx_compressor {
391 /* The parameters that were used to create the compressor. */
392 struct wimlib_lzx_params params;
394 /* The buffer of data to be compressed.
396 * 0xe8 byte preprocessing is done directly on the data here before
397 * further compression.
399 * Note that this compressor does *not* use a sliding window!!!! It's
400 * not needed in the WIM format, since every chunk is compressed
401 * independently. This is by design, to allow random access to the
404 * We reserve a few extra bytes to potentially allow reading off the end
405 * of the array in the match-finding code for optimization purposes.
407 u8 window[LZX_MAX_WINDOW_SIZE + 12];
409 /* Number of bytes of data to be compressed, which is the number of
410 * bytes of data in @window that are actually valid. */
411 input_idx_t window_size;
413 /* The current match offset LRU queue. */
414 struct lzx_lru_queue queue;
416 /* Space for the sequences of matches/literals that were chosen for each
418 struct lzx_match *chosen_matches;
420 /* Information about the LZX blocks the preprocessed input was divided
422 struct lzx_block_spec *block_specs;
424 /* Number of LZX blocks the input was divided into; a.k.a. the number of
425 * elements of @block_specs that are valid. */
428 /* This is simply filled in with zeroes and used to avoid special-casing
429 * the output of the first compressed Huffman code, which conceptually
430 * has a delta taken from a code with all symbols having zero-length
432 struct lzx_codes zero_codes;
434 /* The current cost model. */
435 struct lzx_costs costs;
437 /* Suffix array for window.
438 * This is a mapping from suffix rank to suffix position. */
441 /* Inverse suffix array for window.
442 * This is a mapping from suffix position to suffix rank.
443 * If 0 <= r < window_size, then ISA[SA[r]] == r. */
446 /* Suffix array links.
448 * During a linear scan of the input string to find matches, this array
449 * used to keep track of which rank suffixes in the suffix array appear
450 * before the current position. Instead of searching in the original
451 * suffix array, scans for matches at a given position traverse a linked
452 * list containing only suffixes that appear before that position. */
453 struct salink *salink;
455 /* Position in window of next match to return.
456 * Note: This cannot simply be modified, as the match-finder must still
457 * be synchronized on the same position. To seek forwards or backwards,
458 * use lzx_lz_skip_bytes() or lzx_lz_rewind_matchfinder(), respectively.
460 input_idx_t match_window_pos;
462 /* The match-finder shall ensure the length of matches does not exceed
463 * this position in the input. */
464 input_idx_t match_window_end;
466 /* Matches found by the match-finder are cached in the following array
467 * to achieve a slight speedup when the same matches are needed on
468 * subsequent passes. This is suboptimal because different matches may
469 * be preferred with different cost models, but seems to be a worthwhile
471 struct raw_match *cached_matches;
472 unsigned cached_matches_pos;
475 /* Slow algorithm only: Temporary space used for match-choosing
478 * The size of this array must be at least LZX_MAX_MATCH_LEN but
479 * otherwise is arbitrary. More space simply allows the match-choosing
480 * algorithm to potentially find better matches (depending on the input,
482 struct lzx_optimal *optimum;
484 /* Slow algorithm only: Variables used by the match-choosing algorithm.
486 * When matches have been chosen, optimum_cur_idx is set to the position
487 * in the window of the next match/literal to return and optimum_end_idx
488 * is set to the position in the window at the end of the last
489 * match/literal to return. */
494 /* Returns the LZX position slot that corresponds to a given formatted offset.
496 * Logically, this returns the smallest i such that
497 * formatted_offset >= lzx_position_base[i].
499 * The actual implementation below takes advantage of the regularity of the
500 * numbers in the lzx_position_base array to calculate the slot directly from
501 * the formatted offset without actually looking at the array.
504 lzx_get_position_slot_raw(unsigned formatted_offset)
508 * Slots 36-49 (formatted_offset >= 262144) can be found by
509 * (formatted_offset/131072) + 34 == (formatted_offset >> 17) + 34;
510 * however, this check for formatted_offset >= 262144 is commented out
511 * because WIM chunks cannot be that large.
513 if (formatted_offset >= 262144) {
514 return (formatted_offset >> 17) + 34;
518 /* Note: this part here only works if:
520 * 2 <= formatted_offset < 655360
522 * It is < 655360 because the frequency of the position bases
523 * increases starting at the 655360 entry, and it is >= 2
524 * because the below calculation fails if the most significant
525 * bit is lower than the 2's place. */
526 LZX_ASSERT(2 <= formatted_offset && formatted_offset < 655360);
527 unsigned mssb_idx = bsr32(formatted_offset);
528 return (mssb_idx << 1) |
529 ((formatted_offset >> (mssb_idx - 1)) & 1);
534 /* Returns the LZX position slot that corresponds to a given match offset,
535 * taking into account the recent offset queue and updating it if the offset is
538 lzx_get_position_slot(unsigned offset, struct lzx_lru_queue *queue)
540 unsigned position_slot;
542 /* See if the offset was recently used. */
543 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
544 if (offset == queue->R[i]) {
547 /* Bring the repeat offset to the front of the
548 * queue. Note: this is, in fact, not a real
549 * LRU queue because repeat matches are simply
550 * swapped to the front. */
551 swap(queue->R[0], queue->R[i]);
553 /* The resulting position slot is simply the first index
554 * at which the offset was found in the queue. */
559 /* The offset was not recently used; look up its real position slot. */
560 position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
562 /* Bring the new offset to the front of the queue. */
563 for (unsigned i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
564 queue->R[i] = queue->R[i - 1];
565 queue->R[0] = offset;
567 return position_slot;
570 /* Build the main, length, and aligned offset Huffman codes used in LZX.
572 * This takes as input the frequency tables for each code and produces as output
573 * a set of tables that map symbols to codewords and codeword lengths. */
575 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
576 struct lzx_codes *codes)
578 make_canonical_huffman_code(LZX_MAINCODE_NUM_SYMBOLS,
579 LZX_MAX_MAIN_CODEWORD_LEN,
582 codes->codewords.main);
584 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
585 LZX_MAX_LEN_CODEWORD_LEN,
588 codes->codewords.len);
590 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
591 LZX_MAX_ALIGNED_CODEWORD_LEN,
594 codes->codewords.aligned);
598 * Output an LZX match.
600 * @out: The bitstream to write the match to.
601 * @block_type: The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
603 * @codes: Pointer to a structure that contains the codewords for the
604 * main, length, and aligned offset Huffman codes.
607 lzx_write_match(struct output_bitstream *out, int block_type,
608 struct lzx_match match, const struct lzx_codes *codes)
610 /* low 8 bits are the match length minus 2 */
611 unsigned match_len_minus_2 = match.data & 0xff;
612 /* Next 17 bits are the position footer */
613 unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
614 /* Next 6 bits are the position slot. */
615 unsigned position_slot = (match.data >> 25) & 0x3f; /* 6 bits */
618 unsigned main_symbol;
619 unsigned num_extra_bits;
620 unsigned verbatim_bits;
621 unsigned aligned_bits;
623 /* If the match length is less than MIN_MATCH_LEN (= 2) +
624 * NUM_PRIMARY_LENS (= 7), the length header contains
625 * the match length minus MIN_MATCH_LEN, and there is no
628 * Otherwise, the length header contains
629 * NUM_PRIMARY_LENS, and the length footer contains
630 * the match length minus NUM_PRIMARY_LENS minus
632 if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
633 len_header = match_len_minus_2;
634 /* No length footer-- mark it with a special
636 len_footer = (unsigned)(-1);
638 len_header = LZX_NUM_PRIMARY_LENS;
639 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
642 /* Combine the position slot with the length header into a single symbol
643 * that will be encoded with the main tree.
645 * The actual main symbol is offset by LZX_NUM_CHARS because values
646 * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
648 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
650 /* Output main symbol. */
651 bitstream_put_bits(out, codes->codewords.main[main_symbol],
652 codes->lens.main[main_symbol]);
654 /* If there is a length footer, output it using the
655 * length Huffman code. */
656 if (len_footer != (unsigned)(-1)) {
657 bitstream_put_bits(out, codes->codewords.len[len_footer],
658 codes->lens.len[len_footer]);
661 num_extra_bits = lzx_get_num_extra_bits(position_slot);
663 /* For aligned offset blocks with at least 3 extra bits, output the
664 * verbatim bits literally, then the aligned bits encoded using the
665 * aligned offset tree. Otherwise, only the verbatim bits need to be
667 if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
669 verbatim_bits = position_footer >> 3;
670 bitstream_put_bits(out, verbatim_bits,
673 aligned_bits = (position_footer & 7);
674 bitstream_put_bits(out,
675 codes->codewords.aligned[aligned_bits],
676 codes->lens.aligned[aligned_bits]);
678 /* verbatim bits is the same as the position
679 * footer, in this case. */
680 bitstream_put_bits(out, position_footer, num_extra_bits);
685 lzx_build_precode(const u8 lens[restrict],
686 const u8 prev_lens[restrict],
687 const unsigned num_syms,
688 freq_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
689 u8 output_syms[restrict num_syms],
690 u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
691 u16 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
692 unsigned *num_additional_bits_ret)
694 memset(precode_freqs, 0,
695 LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
697 /* Since the code word lengths use a form of RLE encoding, the goal here
698 * is to find each run of identical lengths when going through them in
699 * symbol order (including runs of length 1). For each run, as many
700 * lengths are encoded using RLE as possible, and the rest are output
703 * output_syms[] will be filled in with the length symbols that will be
704 * output, including RLE codes, not yet encoded using the pre-tree.
706 * cur_run_len keeps track of how many code word lengths are in the
707 * current run of identical lengths. */
708 unsigned output_syms_idx = 0;
709 unsigned cur_run_len = 1;
710 unsigned num_additional_bits = 0;
711 for (unsigned i = 1; i <= num_syms; i++) {
713 if (i != num_syms && lens[i] == lens[i - 1]) {
714 /* Still in a run--- keep going. */
719 /* Run ended! Check if it is a run of zeroes or a run of
722 /* The symbol that was repeated in the run--- not to be confused
723 * with the length *of* the run (cur_run_len) */
724 unsigned len_in_run = lens[i - 1];
726 if (len_in_run == 0) {
727 /* A run of 0's. Encode it in as few length
728 * codes as we can. */
730 /* The magic length 18 indicates a run of 20 + n zeroes,
731 * where n is an uncompressed literal 5-bit integer that
732 * follows the magic length. */
733 while (cur_run_len >= 20) {
734 unsigned additional_bits;
736 additional_bits = min(cur_run_len - 20, 0x1f);
737 num_additional_bits += 5;
739 output_syms[output_syms_idx++] = 18;
740 output_syms[output_syms_idx++] = additional_bits;
741 cur_run_len -= 20 + additional_bits;
744 /* The magic length 17 indicates a run of 4 + n zeroes,
745 * where n is an uncompressed literal 4-bit integer that
746 * follows the magic length. */
747 while (cur_run_len >= 4) {
748 unsigned additional_bits;
750 additional_bits = min(cur_run_len - 4, 0xf);
751 num_additional_bits += 4;
753 output_syms[output_syms_idx++] = 17;
754 output_syms[output_syms_idx++] = additional_bits;
755 cur_run_len -= 4 + additional_bits;
760 /* A run of nonzero lengths. */
762 /* The magic length 19 indicates a run of 4 + n
763 * nonzeroes, where n is a literal bit that follows the
764 * magic length, and where the value of the lengths in
765 * the run is given by an extra length symbol, encoded
766 * with the precode, that follows the literal bit.
768 * The extra length symbol is encoded as a difference
769 * from the length of the codeword for the first symbol
770 * in the run in the previous tree.
772 while (cur_run_len >= 4) {
773 unsigned additional_bits;
776 additional_bits = (cur_run_len > 4);
777 num_additional_bits += 1;
778 delta = (signed char)prev_lens[i - cur_run_len] -
779 (signed char)len_in_run;
783 precode_freqs[(unsigned char)delta]++;
784 output_syms[output_syms_idx++] = 19;
785 output_syms[output_syms_idx++] = additional_bits;
786 output_syms[output_syms_idx++] = delta;
787 cur_run_len -= 4 + additional_bits;
791 /* Any remaining lengths in the run are outputted without RLE,
792 * as a difference from the length of that codeword in the
794 while (cur_run_len > 0) {
797 delta = (signed char)prev_lens[i - cur_run_len] -
798 (signed char)len_in_run;
802 precode_freqs[(unsigned char)delta]++;
803 output_syms[output_syms_idx++] = delta;
810 /* Build the precode from the frequencies of the length symbols. */
812 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
813 LZX_MAX_PRE_CODEWORD_LEN,
814 precode_freqs, precode_lens,
817 *num_additional_bits_ret = num_additional_bits;
819 return output_syms_idx;
823 * Writes a compressed Huffman code to the output, preceded by the precode for
826 * The Huffman code is represented in the output as a series of path lengths
827 * from which the canonical Huffman code can be reconstructed. The path lengths
828 * themselves are compressed using a separate Huffman code, the precode, which
829 * consists of LZX_PRECODE_NUM_SYMBOLS (= 20) symbols that cover all possible
830 * code lengths, plus extra codes for repeated lengths. The path lengths of the
831 * precode precede the path lengths of the larger code and are uncompressed,
832 * consisting of 20 entries of 4 bits each.
834 * @out: Bitstream to write the code to.
835 * @lens: The code lengths for the Huffman code, indexed by symbol.
836 * @prev_lens: Code lengths for this Huffman code, indexed by symbol,
837 * in the *previous block*, or all zeroes if this is the
839 * @num_syms: The number of symbols in the code.
842 lzx_write_compressed_code(struct output_bitstream *out,
843 const u8 lens[restrict],
844 const u8 prev_lens[restrict],
847 freq_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
848 u8 output_syms[num_syms];
849 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
850 u16 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
852 unsigned num_output_syms;
856 num_output_syms = lzx_build_precode(lens,
865 /* Write the lengths of the precode codes to the output. */
866 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
867 bitstream_put_bits(out, precode_lens[i],
868 LZX_PRECODE_ELEMENT_SIZE);
870 /* Write the length symbols, encoded with the precode, to the output. */
872 for (i = 0; i < num_output_syms; ) {
873 precode_sym = output_syms[i++];
875 bitstream_put_bits(out, precode_codewords[precode_sym],
876 precode_lens[precode_sym]);
877 switch (precode_sym) {
879 bitstream_put_bits(out, output_syms[i++], 4);
882 bitstream_put_bits(out, output_syms[i++], 5);
885 bitstream_put_bits(out, output_syms[i++], 1);
886 bitstream_put_bits(out,
887 precode_codewords[output_syms[i]],
888 precode_lens[output_syms[i]]);
898 * Writes all compressed matches and literal bytes in an LZX block to the the
902 * The output bitstream.
904 * The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM).
906 * The array of matches/literals that will be output (length @match_count).
908 * Number of matches/literals to be output.
910 * Pointer to a structure that contains the codewords for the main, length,
911 * and aligned offset Huffman codes.
914 lzx_write_matches_and_literals(struct output_bitstream *ostream,
916 const struct lzx_match match_tab[],
917 unsigned match_count,
918 const struct lzx_codes *codes)
920 for (unsigned i = 0; i < match_count; i++) {
921 struct lzx_match match = match_tab[i];
923 /* High bit of the match indicates whether the match is an
924 * actual match (1) or a literal uncompressed byte (0) */
925 if (match.data & 0x80000000) {
927 lzx_write_match(ostream, block_type,
931 bitstream_put_bits(ostream,
932 codes->codewords.main[match.data],
933 codes->lens.main[match.data]);
939 lzx_assert_codes_valid(const struct lzx_codes * codes)
941 #ifdef ENABLE_LZX_DEBUG
944 for (i = 0; i < LZX_MAINCODE_NUM_SYMBOLS; i++)
945 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
947 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
948 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
950 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
951 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
953 const unsigned tablebits = 10;
954 u16 decode_table[(1 << tablebits) +
955 (2 * max(LZX_MAINCODE_NUM_SYMBOLS, LZX_LENCODE_NUM_SYMBOLS))]
956 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
957 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
958 LZX_MAINCODE_NUM_SYMBOLS,
959 min(tablebits, LZX_MAINCODE_TABLEBITS),
961 LZX_MAX_MAIN_CODEWORD_LEN));
962 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
963 LZX_LENCODE_NUM_SYMBOLS,
964 min(tablebits, LZX_LENCODE_TABLEBITS),
966 LZX_MAX_LEN_CODEWORD_LEN));
967 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
968 LZX_ALIGNEDCODE_NUM_SYMBOLS,
969 min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
971 LZX_MAX_ALIGNED_CODEWORD_LEN));
972 #endif /* ENABLE_LZX_DEBUG */
975 /* Write an LZX aligned offset or verbatim block to the output. */
977 lzx_write_compressed_block(int block_type,
979 struct lzx_match * chosen_matches,
980 unsigned num_chosen_matches,
981 const struct lzx_codes * codes,
982 const struct lzx_codes * prev_codes,
983 struct output_bitstream * ostream)
987 LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
988 block_type == LZX_BLOCKTYPE_VERBATIM);
989 LZX_ASSERT(block_size <= LZX_MAX_WINDOW_SIZE);
990 LZX_ASSERT(num_chosen_matches <= LZX_MAX_WINDOW_SIZE);
991 lzx_assert_codes_valid(codes);
993 /* The first three bits indicate the type of block and are one of the
994 * LZX_BLOCKTYPE_* constants. */
995 bitstream_put_bits(ostream, block_type, LZX_BLOCKTYPE_NBITS);
997 /* The next bit indicates whether the block size is the default (32768),
998 * indicated by a 1 bit, or whether the block size is given by the next
999 * 16 bits, indicated by a 0 bit. */
1000 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1001 bitstream_put_bits(ostream, 1, 1);
1003 bitstream_put_bits(ostream, 0, 1);
1004 bitstream_put_bits(ostream, block_size, LZX_BLOCKSIZE_NBITS);
1007 /* Write out lengths of the main code. Note that the LZX specification
1008 * incorrectly states that the aligned offset code comes after the
1009 * length code, but in fact it is the very first tree to be written
1010 * (before the main code). */
1011 if (block_type == LZX_BLOCKTYPE_ALIGNED)
1012 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1013 bitstream_put_bits(ostream, codes->lens.aligned[i],
1014 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1016 LZX_DEBUG("Writing main code...");
1018 /* Write the pre-tree and lengths for the first LZX_NUM_CHARS symbols in
1019 * the main code, which are the codewords for literal bytes. */
1020 lzx_write_compressed_code(ostream,
1022 prev_codes->lens.main,
1025 /* Write the pre-tree and lengths for the rest of the main code, which
1026 * are the codewords for match headers. */
1027 lzx_write_compressed_code(ostream,
1028 codes->lens.main + LZX_NUM_CHARS,
1029 prev_codes->lens.main + LZX_NUM_CHARS,
1030 LZX_MAINCODE_NUM_SYMBOLS - LZX_NUM_CHARS);
1032 LZX_DEBUG("Writing length code...");
1034 /* Write the pre-tree and lengths for the length code. */
1035 lzx_write_compressed_code(ostream,
1037 prev_codes->lens.len,
1038 LZX_LENCODE_NUM_SYMBOLS);
1040 LZX_DEBUG("Writing matches and literals...");
1042 /* Write the actual matches and literals. */
1043 lzx_write_matches_and_literals(ostream, block_type,
1044 chosen_matches, num_chosen_matches,
1047 LZX_DEBUG("Done writing block.");
1050 /* Write out the LZX blocks that were computed. */
1052 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
1054 const struct lzx_codes *prev_codes = &ctx->zero_codes;
1055 for (unsigned i = 0; i < ctx->num_blocks; i++) {
1056 const struct lzx_block_spec *spec = &ctx->block_specs[i];
1058 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
1059 i + 1, ctx->num_blocks,
1060 spec->block_type, spec->block_size,
1061 spec->num_chosen_matches);
1063 lzx_write_compressed_block(spec->block_type,
1065 &ctx->chosen_matches[spec->chosen_matches_start_pos],
1066 spec->num_chosen_matches,
1070 prev_codes = &spec->codes;
1074 /* Constructs an LZX match from a literal byte and updates the main code symbol
1077 lzx_record_literal(u8 literal, void *_freqs)
1079 struct lzx_freqs *freqs = _freqs;
1081 freqs->main[literal]++;
1083 return (u32)literal;
1086 /* Constructs an LZX match from an offset and a length, and updates the LRU
1087 * queue and the frequency of symbols in the main, length, and aligned offset
1088 * alphabets. The return value is a 32-bit number that provides the match in an
1089 * intermediate representation documented below. */
1091 lzx_record_match(unsigned match_offset, unsigned match_len,
1092 void *_freqs, void *_queue)
1094 struct lzx_freqs *freqs = _freqs;
1095 struct lzx_lru_queue *queue = _queue;
1096 unsigned position_slot;
1097 unsigned position_footer;
1099 unsigned main_symbol;
1100 unsigned len_footer;
1101 unsigned adjusted_match_len;
1103 LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
1105 /* The match offset shall be encoded as a position slot (itself encoded
1106 * as part of the main symbol) and a position footer. */
1107 position_slot = lzx_get_position_slot(match_offset, queue);
1108 position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1109 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1111 /* The match length shall be encoded as a length header (itself encoded
1112 * as part of the main symbol) and an optional length footer. */
1113 adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1114 if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1115 /* No length footer needed. */
1116 len_header = adjusted_match_len;
1118 /* Length footer needed. It will be encoded using the length
1120 len_header = LZX_NUM_PRIMARY_LENS;
1121 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1122 freqs->len[len_footer]++;
1125 /* Account for the main symbol. */
1126 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1128 freqs->main[main_symbol]++;
1130 /* In an aligned offset block, 3 bits of the position footer are output
1131 * as an aligned offset symbol. Account for this, although we may
1132 * ultimately decide to output the block as verbatim. */
1134 /* The following check is equivalent to:
1136 * if (lzx_extra_bits[position_slot] >= 3)
1138 * Note that this correctly excludes position slots that correspond to
1139 * recent offsets. */
1140 if (position_slot >= 8)
1141 freqs->aligned[position_footer & 7]++;
1143 /* Pack the position slot, position footer, and match length into an
1144 * intermediate representation.
1147 * ---- -----------------------------------------------------------
1149 * 31 1 if a match, 0 if a literal.
1151 * 30-25 position slot. This can be at most 50, so it will fit in 6
1154 * 8-24 position footer. This is the offset of the real formatted
1155 * offset from the position base. This can be at most 17 bits
1156 * (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
1158 * 0-7 length of match, offset by 2. This can be at most
1159 * (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits. */
1160 BUILD_BUG_ON(LZX_NUM_POSITION_SLOTS > 64);
1161 LZX_ASSERT(lzx_get_num_extra_bits(LZX_NUM_POSITION_SLOTS - 1) <= 17);
1162 BUILD_BUG_ON(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 > 256);
1164 (position_slot << 25) |
1165 (position_footer << 8) |
1166 (adjusted_match_len);
1169 /* Returns the cost, in bits, to output a literal byte using the specified cost
1172 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1174 return costs->main[c];
1177 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1178 * well as costs for the codewords in the main, length, and aligned Huffman
1179 * codes, return the approximate number of bits it will take to represent this
1180 * match in the compressed output. Take into account the match offset LRU
1181 * queue and optionally update it. */
1183 lzx_match_cost(unsigned length, unsigned offset, const struct lzx_costs *costs,
1184 struct lzx_lru_queue *queue)
1186 unsigned position_slot;
1187 unsigned len_header, main_symbol;
1190 position_slot = lzx_get_position_slot(offset, queue);
1192 len_header = min(length - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1193 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1195 /* Account for main symbol. */
1196 cost += costs->main[main_symbol];
1198 /* Account for extra position information. */
1199 unsigned num_extra_bits = lzx_get_num_extra_bits(position_slot);
1200 if (num_extra_bits >= 3) {
1201 cost += num_extra_bits - 3;
1202 cost += costs->aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1204 cost += num_extra_bits;
1207 /* Account for extra length information. */
1208 if (len_header == LZX_NUM_PRIMARY_LENS)
1209 cost += costs->len[length - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1215 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
1216 * Unlike lzx_match_cost() which does a true cost evaluation, this simply
1217 * prioritize matches based on their offset. */
1219 lzx_match_cost_fast(unsigned offset, const struct lzx_lru_queue *queue)
1221 /* It seems well worth it to take the time to give priority to recently
1223 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
1224 if (offset == queue->R[i])
1227 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE >= (block_cost_t)~0U);
1231 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1234 * The cost model and codeword lengths are almost the same thing, but the
1235 * Huffman codewords with length 0 correspond to symbols with zero frequency
1236 * that still need to be assigned actual costs. The specific values assigned
1237 * are arbitrary, but they should be fairly high (near the maximum codeword
1238 * length) to take into account the fact that uses of these symbols are expected
1241 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1246 for (i = 0; i < LZX_MAINCODE_NUM_SYMBOLS; i++) {
1247 ctx->costs.main[i] = lens->main[i];
1248 if (ctx->costs.main[i] == 0)
1249 ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1253 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1254 ctx->costs.len[i] = lens->len[i];
1255 if (ctx->costs.len[i] == 0)
1256 ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1259 /* Aligned offset code */
1260 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1261 ctx->costs.aligned[i] = lens->aligned[i];
1262 if (ctx->costs.aligned[i] == 0)
1263 ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1267 /* Advance the suffix array match-finder to the next position. */
1269 lzx_lz_update_salink(input_idx_t i,
1270 const input_idx_t SA[restrict],
1271 const input_idx_t ISA[restrict],
1272 struct salink link[restrict])
1274 /* r = Rank of the suffix at the current position. */
1275 const input_idx_t r = ISA[i];
1277 /* next = rank of LOWEST ranked suffix that is ranked HIGHER than the
1278 * current suffix AND has a LOWER position, or -1 if none exists. */
1279 const input_idx_t next = link[r].next;
1281 /* prev = rank of HIGHEST ranked suffix that is ranked LOWER than the
1282 * current suffix AND has a LOWER position, or -1 if none exists. */
1283 const input_idx_t prev = link[r].prev;
1285 /* Link the suffix at the current position into the linked list that
1286 * contains all suffixes in the suffix array that are appear at or
1287 * before the current position, sorted by rank.
1289 * Save the values of all fields we overwrite so that rollback is
1291 if (next != (input_idx_t)~0U) {
1293 link[next].prev = r;
1294 link[next].lcpprev = link[r].lcpnext;
1297 if (prev != (input_idx_t)~0U) {
1299 link[prev].next = r;
1300 link[prev].lcpnext = link[r].lcpprev;
1304 /* Rewind the suffix array match-finder to the specified position.
1306 * This undoes a series of updates by lzx_lz_update_salink(). */
1308 lzx_lz_rewind_matchfinder(struct lzx_compressor *ctx,
1309 const unsigned orig_pos)
1311 LZX_DEBUG("Rewind match-finder %u => %u", ctx->match_window_pos, orig_pos);
1313 if (ctx->match_window_pos == orig_pos)
1316 /* NOTE: this has been optimized for the current algorithm where no
1317 * block-splitting is done and matches are cached, so that the suffix
1318 * array match-finder only runs through the input one time. Generalized
1319 * rewinds of the suffix array match-finder are possible, but require
1320 * incrementally saving fields being overwritten in
1321 * lzx_lz_update_salink(), then restoring them here in reverse order.
1324 LZX_ASSERT(ctx->match_window_pos > orig_pos);
1325 LZX_ASSERT(orig_pos == 0);
1326 ctx->matches_cached = true;
1327 ctx->cached_matches_pos = 0;
1328 ctx->match_window_pos = orig_pos;
1332 * Use the suffix array match-finder to retrieve a list of LZ matches at the
1335 * [in] @i Current position in the window.
1336 * [in] @SA Suffix array for the window.
1337 * [in] @ISA Inverse suffix array for the window.
1338 * [inout] @link Suffix array links used internally by the match-finder.
1339 * [out] @matches The (length, offset) pairs of the resulting matches will
1340 * be written here, sorted in decreasing order by
1341 * length. All returned lengths will be unique.
1342 * [in] @queue Recently used match offsets, used when evaluating the
1344 * [in] @min_match_len Minimum match length to return.
1345 * [in] @max_matches_to_consider Maximum number of matches to consider at
1347 * [in] @max_matches_to_return Maximum number of matches to return.
1349 * The return value is the number of matches found and written to @matches.
1352 lzx_lz_get_matches(const input_idx_t i,
1353 const input_idx_t SA[const restrict],
1354 const input_idx_t ISA[const restrict],
1355 struct salink link[const restrict],
1356 struct raw_match matches[const restrict],
1357 const struct lzx_lru_queue * const restrict queue,
1358 const unsigned min_match_len,
1359 const uint32_t max_matches_to_consider,
1360 const uint32_t max_matches_to_return)
1362 /* r = Rank of the suffix at the current position. */
1363 const input_idx_t r = ISA[i];
1365 /* Prepare for searching the current position. */
1366 lzx_lz_update_salink(i, SA, ISA, link);
1368 /* L = rank of next suffix to the left;
1369 * R = rank of next suffix to the right;
1370 * lenL = length of match between current position and the suffix with rank L;
1371 * lenR = length of match between current position and the suffix with rank R.
1373 * This is left and right relative to the rank of the current suffix.
1374 * Since the suffixes in the suffix array are sorted, the longest
1375 * matches are immediately to the left and right (using the linked list
1376 * to ignore all suffixes that occur later in the window). The match
1377 * length decreases the farther left and right we go. We shall keep the
1378 * length on both sides in sync in order to choose the lowest-cost match
1381 input_idx_t L = link[r].prev;
1382 input_idx_t R = link[r].next;
1383 input_idx_t lenL = link[r].lcpprev;
1384 input_idx_t lenR = link[r].lcpnext;
1386 /* nmatches = number of matches found so far. */
1387 unsigned nmatches = 0;
1389 /* best_cost = cost of lowest-cost match found so far.
1391 * We keep track of this so that we can ignore shorter matches that do
1392 * not have lower costs than a longer matches already found.
1394 block_cost_t best_cost = INFINITE_BLOCK_COST;
1396 /* count_remaining = maximum number of possible matches remaining to be
1398 uint32_t count_remaining = max_matches_to_consider;
1400 /* pending = match currently being considered for a specific length. */
1401 struct raw_match pending;
1402 block_cost_t pending_cost;
1404 while (lenL >= min_match_len || lenR >= min_match_len)
1407 pending_cost = INFINITE_BLOCK_COST;
1411 if (lenL >= min_match_len && lenL >= lenR) {
1414 if (--count_remaining == 0)
1415 goto out_save_pending;
1417 input_idx_t offset = i - SA[L];
1419 /* Save match if it has smaller cost. */
1420 cost = lzx_match_cost_fast(offset, queue);
1421 if (cost < pending_cost) {
1422 pending.offset = offset;
1423 pending_cost = cost;
1426 if (link[L].lcpprev < lenL) {
1427 /* Match length decreased. */
1429 lenL = link[L].lcpprev;
1431 /* Save the pending match unless the
1432 * right side still may have matches of
1433 * this length to be scanned, or if a
1434 * previous (longer) match had lower
1436 if (pending.len > lenR) {
1437 if (pending_cost < best_cost) {
1438 best_cost = pending_cost;
1439 matches[nmatches++] = pending;
1440 if (nmatches == max_matches_to_return)
1444 pending_cost = INFINITE_BLOCK_COST;
1446 if (lenL < min_match_len || lenL < lenR)
1456 if (lenR >= min_match_len && lenR > lenL) {
1459 if (--count_remaining == 0)
1460 goto out_save_pending;
1462 input_idx_t offset = i - SA[R];
1464 /* Save match if it has smaller cost. */
1465 cost = lzx_match_cost_fast(offset, queue);
1466 if (cost < pending_cost) {
1467 pending.offset = offset;
1468 pending_cost = cost;
1471 if (link[R].lcpnext < lenR) {
1472 /* Match length decreased. */
1474 lenR = link[R].lcpnext;
1476 /* Save the pending match unless a
1477 * previous (longer) match had lower
1479 if (pending_cost < best_cost) {
1480 matches[nmatches++] = pending;
1481 best_cost = pending_cost;
1482 if (nmatches == max_matches_to_return)
1486 if (lenR < min_match_len || lenR <= lenL)
1490 pending_cost = INFINITE_BLOCK_COST;
1499 if (pending_cost != INFINITE_BLOCK_COST)
1500 matches[nmatches++] = pending;
1507 /* Tell the match-finder to skip the specified number of bytes (@n) in the
1510 lzx_lz_skip_bytes(struct lzx_compressor *ctx, unsigned n)
1512 LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1513 if (ctx->matches_cached) {
1514 ctx->match_window_pos += n;
1516 ctx->cached_matches_pos +=
1517 ctx->cached_matches[ctx->cached_matches_pos].len + 1;
1521 ctx->cached_matches[ctx->cached_matches_pos++].len = 0;
1522 lzx_lz_update_salink(ctx->match_window_pos++, ctx->SA,
1523 ctx->ISA, ctx->salink);
1528 /* Retrieve a list of matches available at the next position in the input.
1530 * The matches are written to ctx->matches in decreasing order of length, and
1531 * the return value is the number of matches found. */
1533 lzx_lz_get_matches_caching(struct lzx_compressor *ctx,
1534 const struct lzx_lru_queue *queue,
1535 struct raw_match **matches_ret)
1537 unsigned num_matches;
1538 struct raw_match *matches;
1540 LZX_ASSERT(ctx->match_window_pos <= ctx->match_window_end);
1542 matches = &ctx->cached_matches[ctx->cached_matches_pos + 1];
1544 if (ctx->matches_cached) {
1545 num_matches = matches[-1].len;
1547 unsigned min_match_len = LZX_MIN_MATCH_LEN;
1548 if (!ctx->params.alg_params.slow.use_len2_matches)
1549 min_match_len = max(min_match_len, 3);
1550 const uint32_t max_search_depth = ctx->params.alg_params.slow.max_search_depth;
1551 const uint32_t max_matches_per_pos = ctx->params.alg_params.slow.max_matches_per_pos;
1553 if (unlikely(max_search_depth == 0 || max_matches_per_pos == 0))
1556 num_matches = lzx_lz_get_matches(ctx->match_window_pos,
1564 max_matches_per_pos);
1565 matches[-1].len = num_matches;
1567 ctx->cached_matches_pos += num_matches + 1;
1568 *matches_ret = matches;
1570 /* Cap the length of returned matches to the number of bytes remaining,
1571 * if it is not the whole window. */
1572 if (ctx->match_window_end < ctx->window_size) {
1573 unsigned maxlen = ctx->match_window_end - ctx->match_window_pos;
1574 for (unsigned i = 0; i < num_matches; i++)
1575 if (matches[i].len > maxlen)
1576 matches[i].len = maxlen;
1579 fprintf(stderr, "Pos %u/%u: %u matches\n",
1580 ctx->match_window_pos, ctx->match_window_end, num_matches);
1581 for (unsigned i = 0; i < num_matches; i++)
1582 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1585 #ifdef ENABLE_LZX_DEBUG
1586 for (unsigned i = 0; i < num_matches; i++) {
1587 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1588 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1589 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1590 LZX_ASSERT(matches[i].offset > 0);
1591 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1592 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1593 &ctx->window[ctx->match_window_pos - matches[i].offset],
1598 ctx->match_window_pos++;
1603 * Reverse the linked list of near-optimal matches so that they can be returned
1604 * in forwards order.
1606 * Returns the first match in the list.
1608 static struct raw_match
1609 lzx_lz_reverse_near_optimal_match_list(struct lzx_compressor *ctx,
1612 unsigned prev_link, saved_prev_link;
1613 unsigned prev_match_offset, saved_prev_match_offset;
1615 ctx->optimum_end_idx = cur_pos;
1617 saved_prev_link = ctx->optimum[cur_pos].prev.link;
1618 saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
1621 prev_link = saved_prev_link;
1622 prev_match_offset = saved_prev_match_offset;
1624 saved_prev_link = ctx->optimum[prev_link].prev.link;
1625 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
1627 ctx->optimum[prev_link].next.link = cur_pos;
1628 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
1630 cur_pos = prev_link;
1631 } while (cur_pos != 0);
1633 ctx->optimum_cur_idx = ctx->optimum[0].next.link;
1635 return (struct raw_match)
1636 { .len = ctx->optimum_cur_idx,
1637 .offset = ctx->optimum[0].next.match_offset,
1642 * lzx_lz_get_near_optimal_match() -
1644 * Choose the optimal match or literal to use at the next position in the input.
1646 * Unlike a greedy parser that always takes the longest match, or even a
1647 * parser with one match/literal look-ahead like zlib, the algorithm used here
1648 * may look ahead many matches/literals to determine the optimal match/literal to
1649 * output next. The motivation is that the compression ratio is improved if the
1650 * compressor can do things like use a shorter-than-possible match in order to
1651 * allow a longer match later, and also take into account the Huffman code cost
1652 * model rather than simply assuming that longer is better.
1654 * Still, this is not truly an optimal parser because very long matches are
1655 * taken immediately, and the raw match-finder takes some shortcuts. This is
1656 * done to avoid considering many different alternatives that are unlikely to
1657 * be significantly better.
1659 * This algorithm is based on that used in 7-Zip's DEFLATE encoder.
1661 * Each call to this function does one of two things:
1663 * 1. Build a near-optimal sequence of matches/literals, up to some point, that
1664 * will be returned by subsequent calls to this function, then return the
1669 * 2. Return the next match/literal previously computed by a call to this
1672 * This function relies on the following state in the compressor context:
1674 * ctx->window (read-only: preprocessed data being compressed)
1675 * ctx->cost (read-only: cost model to use)
1676 * ctx->optimum (internal state; leave uninitialized)
1677 * ctx->optimum_cur_idx (must set to 0 before first call)
1678 * ctx->optimum_end_idx (must set to 0 before first call)
1680 * Plus any state used by the raw match-finder.
1682 * The return value is a (length, offset) pair specifying the match or literal
1683 * chosen. For literals, the length is less than LZX_MIN_MATCH_LEN and the
1684 * offset is meaningless.
1686 static struct raw_match
1687 lzx_lz_get_near_optimal_match(struct lzx_compressor * ctx)
1689 unsigned num_possible_matches;
1690 struct raw_match *possible_matches;
1691 struct raw_match match;
1692 unsigned longest_match_len;
1694 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1695 /* Case 2: Return the next match/literal already found. */
1696 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1697 ctx->optimum_cur_idx;
1698 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1700 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1704 /* Case 1: Compute a new list of matches/literals to return. */
1706 ctx->optimum_cur_idx = 0;
1707 ctx->optimum_end_idx = 0;
1709 /* Get matches at this position. */
1710 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &possible_matches);
1712 /* If no matches found, return literal. */
1713 if (num_possible_matches == 0)
1714 return (struct raw_match){ .len = 0 };
1716 /* The matches that were found are sorted in decreasing order by length.
1717 * Get the length of the longest one. */
1718 longest_match_len = possible_matches[0].len;
1720 /* Greedy heuristic: if the longest match that was found is greater
1721 * than the number of fast bytes, return it immediately; don't both
1722 * doing more work. */
1723 if (longest_match_len > ctx->params.alg_params.slow.num_fast_bytes) {
1724 lzx_lz_skip_bytes(ctx, longest_match_len - 1);
1725 return possible_matches[0];
1728 /* Calculate the cost to reach the next position by outputting a
1730 ctx->optimum[0].queue = ctx->queue;
1731 ctx->optimum[1].queue = ctx->optimum[0].queue;
1732 ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos],
1734 ctx->optimum[1].prev.link = 0;
1736 /* Calculate the cost to reach any position up to and including that
1737 * reached by the longest match, using the shortest (i.e. closest) match
1738 * that reaches each position. */
1739 BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1740 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1741 len <= longest_match_len; len++) {
1743 LZX_ASSERT(match_idx < num_possible_matches);
1745 ctx->optimum[len].queue = ctx->optimum[0].queue;
1746 ctx->optimum[len].prev.link = 0;
1747 ctx->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
1748 ctx->optimum[len].cost = lzx_match_cost(len,
1749 possible_matches[match_idx].offset,
1751 &ctx->optimum[len].queue);
1752 if (len == possible_matches[match_idx].len)
1756 unsigned cur_pos = 0;
1758 /* len_end: greatest index forward at which costs have been calculated
1760 unsigned len_end = longest_match_len;
1763 /* Advance to next position. */
1766 if (cur_pos == len_end || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1767 return lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1769 /* retrieve the number of matches available at this position */
1770 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->optimum[cur_pos].queue,
1773 unsigned new_len = 0;
1775 if (num_possible_matches != 0) {
1776 new_len = possible_matches[0].len;
1778 /* Greedy heuristic: if we found a match greater than
1779 * the number of fast bytes, stop immediately. */
1780 if (new_len > ctx->params.alg_params.slow.num_fast_bytes) {
1782 /* Build the list of matches to return and get
1784 match = lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1786 /* Append the long match to the end of the list. */
1787 ctx->optimum[cur_pos].next.match_offset =
1788 possible_matches[0].offset;
1789 ctx->optimum[cur_pos].next.link = cur_pos + new_len;
1790 ctx->optimum_end_idx = cur_pos + new_len;
1792 /* Skip over the remaining bytes of the long match. */
1793 lzx_lz_skip_bytes(ctx, new_len - 1);
1795 /* Return first match in the list */
1800 /* Consider proceeding with a literal byte. */
1801 block_cost_t cur_cost = ctx->optimum[cur_pos].cost;
1802 block_cost_t cur_plus_literal_cost = cur_cost +
1803 lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1805 if (cur_plus_literal_cost < ctx->optimum[cur_pos + 1].cost) {
1806 ctx->optimum[cur_pos + 1].cost = cur_plus_literal_cost;
1807 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1808 ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1811 if (num_possible_matches == 0)
1814 /* Consider proceeding with a match. */
1816 while (len_end < cur_pos + new_len)
1817 ctx->optimum[++len_end].cost = INFINITE_BLOCK_COST;
1819 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1820 len <= new_len; len++) {
1821 LZX_ASSERT(match_idx < num_possible_matches);
1822 struct lzx_lru_queue q = ctx->optimum[cur_pos].queue;
1823 block_cost_t cost = cur_cost + lzx_match_cost(len,
1824 possible_matches[match_idx].offset,
1828 if (cost < ctx->optimum[cur_pos + len].cost) {
1829 ctx->optimum[cur_pos + len].cost = cost;
1830 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1831 ctx->optimum[cur_pos + len].prev.match_offset =
1832 possible_matches[match_idx].offset;
1833 ctx->optimum[cur_pos + len].queue = q;
1836 if (len == possible_matches[match_idx].len)
1843 * Set default symbol costs.
1846 lzx_set_default_costs(struct lzx_costs * costs)
1850 /* Literal symbols */
1851 for (i = 0; i < LZX_NUM_CHARS; i++)
1854 /* Match header symbols */
1855 for (; i < LZX_MAINCODE_NUM_SYMBOLS; i++)
1856 costs->main[i] = 10;
1858 /* Length symbols */
1859 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1862 /* Aligned offset symbols */
1863 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1864 costs->aligned[i] = 3;
1867 /* Given the frequencies of symbols in a compressed block and the corresponding
1868 * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1869 * aligned offset or verbatim block, respectively, will take fewer bits to
1872 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1873 const struct lzx_codes * codes)
1875 unsigned aligned_cost = 0;
1876 unsigned verbatim_cost = 0;
1878 /* Verbatim blocks have a constant 3 bits per position footer. Aligned
1879 * offset blocks have an aligned offset symbol per position footer, plus
1880 * an extra 24 bits to output the lengths necessary to reconstruct the
1881 * aligned offset code itself. */
1882 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1883 verbatim_cost += 3 * freqs->aligned[i];
1884 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1886 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1887 if (aligned_cost < verbatim_cost)
1888 return LZX_BLOCKTYPE_ALIGNED;
1890 return LZX_BLOCKTYPE_VERBATIM;
1893 /* Find a near-optimal sequence of matches/literals with which to output the
1894 * specified LZX block, then set its type to that which has the minimum cost to
1897 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1898 unsigned num_passes)
1900 const struct lzx_lru_queue orig_queue = ctx->queue;
1901 struct lzx_freqs freqs;
1903 ctx->match_window_end = spec->window_pos + spec->block_size;
1904 spec->chosen_matches_start_pos = spec->window_pos;
1906 LZX_ASSERT(num_passes >= 1);
1908 /* The first optimal parsing pass is done using the cost model already
1909 * set in ctx->costs. Each later pass is done using a cost model
1910 * computed from the previous pass. */
1911 for (unsigned pass = 0; pass < num_passes; pass++) {
1913 lzx_lz_rewind_matchfinder(ctx, spec->window_pos);
1914 ctx->queue = orig_queue;
1915 spec->num_chosen_matches = 0;
1916 memset(&freqs, 0, sizeof(freqs));
1918 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
1919 struct raw_match raw_match;
1920 struct lzx_match lzx_match;
1922 raw_match = lzx_lz_get_near_optimal_match(ctx);
1923 if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1924 lzx_match.data = lzx_record_match(raw_match.offset, raw_match.len,
1925 &freqs, &ctx->queue);
1928 lzx_match.data = lzx_record_literal(ctx->window[i], &freqs);
1931 ctx->chosen_matches[spec->chosen_matches_start_pos +
1932 spec->num_chosen_matches++] = lzx_match;
1935 lzx_make_huffman_codes(&freqs, &spec->codes);
1936 if (pass < num_passes - 1)
1937 lzx_set_costs(ctx, &spec->codes.lens);
1939 spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1943 lzx_optimize_blocks(struct lzx_compressor *ctx)
1945 lzx_lru_queue_init(&ctx->queue);
1946 ctx->optimum_cur_idx = 0;
1947 ctx->optimum_end_idx = 0;
1949 const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
1951 for (unsigned i = 0; i < ctx->num_blocks; i++)
1952 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
1955 /* Initialize the suffix array match-finder for the specified input. */
1957 lzx_lz_init_matchfinder(const u8 T[const restrict],
1958 const input_idx_t n,
1959 input_idx_t SA[const restrict],
1960 input_idx_t ISA[const restrict],
1961 struct salink link[const restrict],
1962 const unsigned max_match_len)
1964 /* Compute SA (Suffix Array). */
1968 /* ISA and link are used as temporary space. */
1969 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * sizeof(ISA[0]) < 256 * sizeof(saidx_t));
1970 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * 2 * sizeof(link[0]) < 256 * 256 * sizeof(saidx_t));
1971 divsufsort(T, sa, n, (saidx_t*)ISA, (saidx_t*)link);
1972 for (input_idx_t i = 0; i < n; i++)
1976 #ifdef ENABLE_LZX_DEBUG
1980 /* Verify suffix array. */
1984 for (input_idx_t r = 0; r < n; r++) {
1985 input_idx_t i = SA[r];
1987 LZX_ASSERT(!found[i]);
1992 for (input_idx_t r = 0; r < n - 1; r++) {
1994 input_idx_t i1 = SA[r];
1995 input_idx_t i2 = SA[r + 1];
1997 input_idx_t n1 = n - i1;
1998 input_idx_t n2 = n - i2;
2000 LZX_ASSERT(memcmp(&T[i1], &T[i2], min(n1, n2)) <= 0);
2002 LZX_DEBUG("Verified SA (len %u)", n);
2003 #endif /* ENABLE_LZX_DEBUG */
2005 /* Compute ISA (Inverse Suffix Array) */
2006 for (input_idx_t r = 0; r < n; r++)
2011 /* Compute LCP (longest common prefix) array.
2013 * Algorithm adapted from Kasai et al. 2001: "Linear-Time
2014 * Longest-Common-Prefix Computation in Suffix Arrays and Its
2018 for (input_idx_t i = 0; i < n; i++) {
2019 input_idx_t r = ISA[i];
2021 input_idx_t j = SA[r - 1];
2023 input_idx_t lim = min(n - i, n - j);
2025 while (h < lim && T[i + h] == T[j + h])
2034 #ifdef ENABLE_LZX_DEBUG
2035 /* Verify LCP array. */
2036 for (input_idx_t r = 0; r < n - 1; r++) {
2037 LZX_ASSERT(ISA[SA[r]] == r);
2038 LZX_ASSERT(ISA[SA[r + 1]] == r + 1);
2040 input_idx_t i1 = SA[r];
2041 input_idx_t i2 = SA[r + 1];
2042 input_idx_t lcp = LCP[r + 1];
2044 input_idx_t n1 = n - i1;
2045 input_idx_t n2 = n - i2;
2047 LZX_ASSERT(lcp <= min(n1, n2));
2049 LZX_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
2050 if (lcp < min(n1, n2))
2051 LZX_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
2053 #endif /* ENABLE_LZX_DEBUG */
2055 /* Compute salink.next and salink.lcpnext.
2057 * Algorithm adapted from Crochemore et al. 2009:
2058 * "LPF computation revisited".
2060 * Note: we cap lcpnext to the maximum match length so that the
2061 * match-finder need not worry about it later. */
2062 link[n - 1].next = (input_idx_t)~0U;
2063 link[n - 1].prev = (input_idx_t)~0U;
2064 link[n - 1].lcpnext = 0;
2065 link[n - 1].lcpprev = 0;
2066 for (input_idx_t r = n - 2; r != (input_idx_t)~0U; r--) {
2067 input_idx_t t = r + 1;
2068 input_idx_t l = LCP[t];
2069 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2070 l = min(l, link[t].lcpnext);
2074 link[r].lcpnext = min(l, max_match_len);
2075 LZX_ASSERT(t == (input_idx_t)~0U || l <= n - SA[t]);
2076 LZX_ASSERT(l <= n - SA[r]);
2077 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2080 /* Compute salink.prev and salink.lcpprev.
2082 * Algorithm adapted from Crochemore et al. 2009:
2083 * "LPF computation revisited".
2085 * Note: we cap lcpprev to the maximum match length so that the
2086 * match-finder need not worry about it later. */
2087 link[0].prev = (input_idx_t)~0;
2088 link[0].next = (input_idx_t)~0;
2089 link[0].lcpprev = 0;
2090 link[0].lcpnext = 0;
2091 for (input_idx_t r = 1; r < n; r++) {
2092 input_idx_t t = r - 1;
2093 input_idx_t l = LCP[r];
2094 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2095 l = min(l, link[t].lcpprev);
2099 link[r].lcpprev = min(l, max_match_len);
2100 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2101 LZX_ASSERT(l <= n - SA[r]);
2102 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2107 /* Prepare the input window into one or more LZX blocks ready to be output. */
2109 lzx_prepare_blocks(struct lzx_compressor * ctx)
2111 /* Initialize the match-finder. */
2112 lzx_lz_init_matchfinder(ctx->window, ctx->window_size,
2113 ctx->SA, ctx->ISA, ctx->salink,
2115 ctx->cached_matches_pos = 0;
2116 ctx->matches_cached = false;
2117 ctx->match_window_pos = 0;
2119 /* Set up a default cost model. */
2120 lzx_set_default_costs(&ctx->costs);
2122 /* Assume that the entire input will be one LZX block. */
2123 ctx->block_specs[0].window_pos = 0;
2124 ctx->block_specs[0].block_size = ctx->window_size;
2125 ctx->num_blocks = 1;
2127 /* Determine sequence of matches/literals to output for each block. */
2128 lzx_optimize_blocks(ctx);
2132 * This is the fast version of lzx_prepare_blocks(). This version "quickly"
2133 * prepares a single compressed block containing the entire input. See the
2134 * description of the "Fast algorithm" at the beginning of this file for more
2137 * Input --- the preprocessed data:
2145 * Output --- the block specification and the corresponding match/literal data:
2147 * ctx->block_specs[]
2149 * ctx->chosen_matches[]
2152 lzx_prepare_block_fast(struct lzx_compressor * ctx)
2154 unsigned num_matches;
2155 struct lzx_freqs freqs;
2156 struct lzx_block_spec *spec;
2158 /* Parameters to hash chain LZ match finder
2159 * (lazy with 1 match lookahead) */
2160 static const struct lz_params lzx_lz_params = {
2161 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
2162 * aren't worth choosing when using greedy or lazy parsing. */
2164 .max_match = LZX_MAX_MATCH_LEN,
2165 .good_match = LZX_MAX_MATCH_LEN,
2166 .nice_match = LZX_MAX_MATCH_LEN,
2167 .max_chain_len = LZX_MAX_MATCH_LEN,
2168 .max_lazy_match = LZX_MAX_MATCH_LEN,
2172 /* Initialize symbol frequencies and match offset LRU queue. */
2173 memset(&freqs, 0, sizeof(struct lzx_freqs));
2174 lzx_lru_queue_init(&ctx->queue);
2176 /* Determine series of matches/literals to output. */
2177 num_matches = lz_analyze_block(ctx->window,
2179 (u32*)ctx->chosen_matches,
2188 /* Set up block specification. */
2189 spec = &ctx->block_specs[0];
2190 spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2191 spec->window_pos = 0;
2192 spec->block_size = ctx->window_size;
2193 spec->num_chosen_matches = num_matches;
2194 spec->chosen_matches_start_pos = 0;
2195 lzx_make_huffman_codes(&freqs, &spec->codes);
2196 ctx->num_blocks = 1;
2200 do_call_insn_translation(u32 *call_insn_target, int input_pos,
2206 rel_offset = le32_to_cpu(*call_insn_target);
2207 if (rel_offset >= -input_pos && rel_offset < file_size) {
2208 if (rel_offset < file_size - input_pos) {
2209 /* "good translation" */
2210 abs_offset = rel_offset + input_pos;
2212 /* "compensating translation" */
2213 abs_offset = rel_offset - file_size;
2215 *call_insn_target = cpu_to_le32(abs_offset);
2219 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
2220 * See the comment above that function for more information. */
2222 do_call_insn_preprocessing(u8 data[], int size)
2224 for (int i = 0; i < size - 10; i++) {
2225 if (data[i] == 0xe8) {
2226 do_call_insn_translation((u32*)&data[i + 1], i,
2227 LZX_WIM_MAGIC_FILESIZE);
2233 /* API function documented in wimlib.h */
2235 wimlib_lzx_compress2(const void * const restrict uncompressed_data,
2236 unsigned const uncompressed_len,
2237 void * const restrict compressed_data,
2238 struct wimlib_lzx_context * const restrict lzx_ctx)
2240 struct lzx_compressor *ctx = (struct lzx_compressor*)lzx_ctx;
2241 struct output_bitstream ostream;
2242 unsigned compressed_len;
2244 if (uncompressed_len < 100) {
2245 LZX_DEBUG("Too small to bother compressing.");
2249 if (uncompressed_len > 32768) {
2250 LZX_DEBUG("Only up to 32768 bytes of uncompressed data are supported.");
2254 wimlib_assert(lzx_ctx != NULL);
2256 LZX_DEBUG("Attempting to compress %u bytes...", uncompressed_len);
2258 /* The input data must be preprocessed. To avoid changing the original
2259 * input, copy it to a temporary buffer. */
2260 memcpy(ctx->window, uncompressed_data, uncompressed_len);
2261 ctx->window_size = uncompressed_len;
2263 /* This line is unnecessary; it just avoids inconsequential accesses of
2264 * uninitialized memory that would show up in memory-checking tools such
2266 memset(&ctx->window[ctx->window_size], 0, 12);
2268 LZX_DEBUG("Preprocessing data...");
2270 /* Before doing any actual compression, do the call instruction (0xe8
2271 * byte) translation on the uncompressed data. */
2272 do_call_insn_preprocessing(ctx->window, ctx->window_size);
2274 LZX_DEBUG("Preparing blocks...");
2276 /* Prepare the compressed data. */
2277 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2278 lzx_prepare_block_fast(ctx);
2280 lzx_prepare_blocks(ctx);
2282 LZX_DEBUG("Writing compressed blocks...");
2284 /* Generate the compressed data. */
2285 init_output_bitstream(&ostream, compressed_data, ctx->window_size - 1);
2286 lzx_write_all_blocks(ctx, &ostream);
2288 LZX_DEBUG("Flushing bitstream...");
2289 if (flush_output_bitstream(&ostream)) {
2290 /* If the bitstream cannot be flushed, then the output space was
2292 LZX_DEBUG("Data did not compress to less than original length!");
2296 /* Compute the length of the compressed data. */
2297 compressed_len = ostream.bit_output - (u8*)compressed_data;
2299 LZX_DEBUG("Done: compressed %u => %u bytes.",
2300 uncompressed_len, compressed_len);
2302 /* Verify that we really get the same thing back when decompressing.
2303 * Although this could be disabled by default in all cases, it only
2304 * takes around 2-3% of the running time of the slow algorithm to do the
2306 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2307 #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2312 u8 buf[uncompressed_len];
2315 ret = wimlib_lzx_decompress(compressed_data, compressed_len,
2316 buf, uncompressed_len);
2318 ERROR("Failed to decompress data we "
2319 "compressed using LZX algorithm");
2324 if (memcmp(uncompressed_data, buf, uncompressed_len)) {
2325 ERROR("Data we compressed using LZX algorithm "
2326 "didn't decompress to original");
2331 return compressed_len;
2335 lzx_params_compatible(const struct wimlib_lzx_params *oldparams,
2336 const struct wimlib_lzx_params *newparams)
2338 return 0 == memcmp(oldparams, newparams, sizeof(struct wimlib_lzx_params));
2341 static struct wimlib_lzx_params lzx_user_default_params;
2342 static struct wimlib_lzx_params *lzx_user_default_params_ptr;
2345 lzx_params_valid(const struct wimlib_lzx_params *params)
2347 /* Validate parameters. */
2348 if (params->size_of_this != sizeof(struct wimlib_lzx_params)) {
2349 LZX_DEBUG("Invalid parameter structure size!");
2353 if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2354 params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2356 LZX_DEBUG("Invalid algorithm.");
2360 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2361 if (params->alg_params.slow.num_optim_passes < 1)
2363 LZX_DEBUG("Invalid number of optimization passes!");
2367 if (params->alg_params.slow.main_nostat_cost < 1 ||
2368 params->alg_params.slow.main_nostat_cost > 16)
2370 LZX_DEBUG("Invalid main_nostat_cost!");
2374 if (params->alg_params.slow.len_nostat_cost < 1 ||
2375 params->alg_params.slow.len_nostat_cost > 16)
2377 LZX_DEBUG("Invalid len_nostat_cost!");
2381 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2382 params->alg_params.slow.aligned_nostat_cost > 8)
2384 LZX_DEBUG("Invalid aligned_nostat_cost!");
2391 /* API function documented in wimlib.h */
2393 wimlib_lzx_set_default_params(const struct wimlib_lzx_params * params)
2396 if (!lzx_params_valid(params))
2397 return WIMLIB_ERR_INVALID_PARAM;
2398 lzx_user_default_params = *params;
2399 lzx_user_default_params_ptr = &lzx_user_default_params;
2401 lzx_user_default_params_ptr = NULL;
2406 /* API function documented in wimlib.h */
2408 wimlib_lzx_alloc_context(const struct wimlib_lzx_params *params,
2409 struct wimlib_lzx_context **ctx_pp)
2412 LZX_DEBUG("Allocating LZX context...");
2414 struct lzx_compressor *ctx;
2416 static const struct wimlib_lzx_params fast_default = {
2417 .size_of_this = sizeof(struct wimlib_lzx_params),
2418 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2425 static const struct wimlib_lzx_params slow_default = {
2426 .size_of_this = sizeof(struct wimlib_lzx_params),
2427 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2431 .use_len2_matches = 1,
2432 .num_fast_bytes = 32,
2433 .num_optim_passes = 2,
2434 .max_search_depth = 50,
2435 .max_matches_per_pos = 3,
2436 .main_nostat_cost = 15,
2437 .len_nostat_cost = 15,
2438 .aligned_nostat_cost = 7,
2444 if (!lzx_params_valid(params))
2445 return WIMLIB_ERR_INVALID_PARAM;
2447 LZX_DEBUG("Using default algorithm and parameters.");
2448 if (lzx_user_default_params_ptr)
2449 params = lzx_user_default_params_ptr;
2451 params = &slow_default;
2454 if (params->use_defaults) {
2455 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2456 params = &slow_default;
2458 params = &fast_default;
2462 ctx = *(struct lzx_compressor**)ctx_pp;
2464 if (ctx && lzx_params_compatible(&ctx->params, params))
2467 LZX_DEBUG("Check parameters only.");
2471 LZX_DEBUG("Allocating memory.");
2473 ctx = MALLOC(sizeof(struct lzx_compressor));
2477 size_t block_specs_length;
2480 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2481 block_specs_length = 1U << params->alg_params.slow.num_split_passes;
2484 block_specs_length = 1U;
2485 ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2486 if (ctx->block_specs == NULL)
2489 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2490 ctx->SA = MALLOC(3U * LZX_MAX_WINDOW_SIZE * sizeof(ctx->SA[0]));
2491 if (ctx->SA == NULL)
2492 goto err_free_block_specs;
2493 ctx->ISA = ctx->SA + LZX_MAX_WINDOW_SIZE;
2494 ctx->salink = MALLOC(LZX_MAX_WINDOW_SIZE * sizeof(ctx->salink[0]));
2495 if (ctx->salink == NULL)
2503 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2504 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE + LZX_MAX_MATCH_LEN) *
2505 sizeof(ctx->optimum[0]));
2506 if (ctx->optimum == NULL)
2507 goto err_free_salink;
2509 ctx->optimum = NULL;
2512 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2513 uint32_t cache_per_pos;
2515 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
2516 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
2517 cache_per_pos = LZX_MAX_CACHE_PER_POS;
2519 ctx->cached_matches = MALLOC(LZX_MAX_WINDOW_SIZE * (cache_per_pos + 1) *
2520 sizeof(ctx->cached_matches[0]));
2521 if (ctx->cached_matches == NULL)
2522 goto err_free_optimum;
2524 ctx->cached_matches = NULL;
2527 ctx->chosen_matches = MALLOC(LZX_MAX_WINDOW_SIZE *
2528 sizeof(ctx->chosen_matches[0]));
2529 if (ctx->chosen_matches == NULL)
2530 goto err_free_cached_matches;
2532 memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_params));
2533 memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2535 LZX_DEBUG("Successfully allocated new LZX context.");
2537 wimlib_lzx_free_context(*ctx_pp);
2538 *ctx_pp = (struct wimlib_lzx_context*)ctx;
2541 err_free_cached_matches:
2542 FREE(ctx->cached_matches);
2549 err_free_block_specs:
2550 FREE(ctx->block_specs);
2554 LZX_DEBUG("Ran out of memory.");
2555 return WIMLIB_ERR_NOMEM;
2558 /* API function documented in wimlib.h */
2560 wimlib_lzx_free_context(struct wimlib_lzx_context *_ctx)
2562 struct lzx_compressor *ctx = (struct lzx_compressor*)_ctx;
2565 FREE(ctx->chosen_matches);
2566 FREE(ctx->cached_matches);
2570 FREE(ctx->block_specs);
2575 /* API function documented in wimlib.h */
2577 wimlib_lzx_compress(const void * const restrict uncompressed_data,
2578 unsigned const uncompressed_len,
2579 void * const restrict compressed_data)
2582 struct wimlib_lzx_context *ctx = NULL;
2583 unsigned compressed_len;
2585 ret = wimlib_lzx_alloc_context(NULL, &ctx);
2587 wimlib_assert(ret != WIMLIB_ERR_INVALID_PARAM);
2588 WARNING("Couldn't allocate LZX compression context: %"TS"",
2589 wimlib_get_error_string(ret));
2593 compressed_len = wimlib_lzx_compress2(uncompressed_data,
2598 wimlib_lzx_free_context(ctx);
2600 return compressed_len;