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 before attempting to compress it.
46 * - LZX uses a "main" alphabet which combines literals and matches, with the
47 * match symbols containing a "length header" (giving all or part of the match
48 * length) and a "position slot" (giving, roughly speaking, the order of
49 * magnitude of the match offset).
50 * - LZX does not have static Huffman blocks; however it does have two types of
51 * dynamic Huffman blocks ("aligned offset" and "verbatim").
52 * - LZX has a minimum match length of 2 rather than 3.
53 * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
54 * queue of match offsets.
59 * There are actually two distinct overall algorithms implemented here. We
60 * shall refer to them as the "slow" algorithm and the "fast" algorithm. The
61 * "slow" algorithm spends more time compressing to achieve a higher compression
62 * ratio compared to the "fast" algorithm. More details are presented below.
67 * The "slow" algorithm to generate LZX-compressed data is roughly as follows:
69 * 1. Preprocess the input data to translate the targets of x86 call instructions
70 * to absolute offsets.
72 * 2. Build the suffix array and inverse suffix array for the input data.
74 * 3. Build the longest common prefix array corresponding to the suffix array.
76 * 4. For each suffix rank, find the highest lower suffix rank that has a
77 * lower position, the lowest higher suffix rank that has a lower position,
78 * and the length of the common prefix shared between each. (Position =
79 * index of suffix in original string, rank = index of suffix in suffix
80 * array.) This information is later used to link suffix ranks into a
81 * doubly-linked list for searching the suffix array.
83 * 5. Set a default cost model for matches/literals.
85 * 6. Determine the lowest cost sequence of LZ77 matches ((offset, length) pairs)
86 * and literal bytes to divide the input into. Raw match-finding is done by
87 * searching the suffix array using a linked list to avoid considering any
88 * suffixes that start after the current position. Each run of the
89 * match-finder returns the lowest-cost longest match as well as any shorter
90 * matches that have even lower costs. Each such run also adds the suffix
91 * rank of the current position into the linked list being used to search the
92 * suffix array. Parsing, or match-choosing, is solved as a minimum-cost
93 * path problem using a forward "optimal parsing" algorithm based on the
94 * Deflate encoder from 7-Zip. This algorithm moves forward calculating the
95 * minimum cost to reach each byte until either a very long match is found or
96 * until a position is found at which no matches start or overlap.
98 * 7. Build the Huffman codes needed to output the matches/literals.
100 * 8. Up to a certain number of iterations, use the resulting Huffman codes to
101 * refine a cost model and go back to Step #6 to determine an improved
102 * sequence of matches and literals.
104 * 9. Output the resulting block using the match/literal sequences and the
105 * Huffman codes that were computed for the block.
110 * The fast algorithm (and the only one available in wimlib v1.5.1 and earlier)
111 * spends much less time on the main bottlenecks of the compression process ---
112 * that is the match finding, match choosing, and block splitting. Matches are
113 * found and chosen with hash chains using a greedy parse with one position of
114 * look-ahead. No block splitting is done; only compressing the full input into
115 * an aligned offset block is considered.
120 * The old API (retained for backward compatibility) consists of just one function:
122 * wimlib_lzx_compress()
124 * The new compressor has more potential parameters and needs more memory, so
125 * the new API ties up memory allocations and compression parameters into a
128 * wimlib_lzx_alloc_context()
129 * wimlib_lzx_compress2()
130 * wimlib_lzx_free_context()
132 * Both wimlib_lzx_compress() and wimlib_lzx_compress2() are designed to
133 * compress an in-memory buffer of up to 32768 bytes. There is no sliding
134 * window. This is suitable for the WIM format, which uses fixed-size chunks
135 * that are seemingly always 32768 bytes. If needed, the compressor potentially
136 * could be extended to support a larger and/or sliding window.
138 * Both wimlib_lzx_compress() and wimlib_lzx_compress2() return 0 if the data
139 * could not be compressed to less than the size of the uncompressed data.
140 * Again, this is suitable for the WIM format, which stores such data chunks
143 * The functions in this API are exported from the library, although this is
144 * only in case other programs happen to have uses for it other than WIM
145 * reading/writing as already handled through the rest of the library.
150 * Acknowledgments to several open-source projects and research papers that made
151 * it possible to implement this code:
153 * - divsufsort (author: Yuta Mori), for the suffix array construction code.
155 * - "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its
156 * Applications" (Kasai et al. 2001), for the LCP array computation.
158 * - "LPF computation revisited" (Crochemore et al. 2009) for the prev and next
159 * array computations.
161 * - 7-Zip (author: Igor Pavlov) for the algorithm for forward optimal parsing
164 * - zlib (author: Jean-loup Gailly and Mark Adler), for the hash table
165 * match-finding algorithm.
167 * - lzx-compress (author: Matthew T. Russotto), on which some parts of this
168 * code were originally based.
176 #include "wimlib/compress.h"
177 #include "wimlib/error.h"
178 #include "wimlib/lzx.h"
179 #include "wimlib/util.h"
184 #ifdef ENABLE_LZX_DEBUG
185 # include <wimlib/decompress.h>
188 #include "divsufsort/divsufsort.h"
190 typedef freq_t input_idx_t;
191 typedef u32 sym_cost_t;
192 typedef u32 block_cost_t;
193 #define INFINITE_SYM_COST ((sym_cost_t)~0U)
194 #define INFINITE_BLOCK_COST ((block_cost_t)~0U)
196 #define LZX_OPTIM_ARRAY_SIZE 4096
198 /* Currently, this constant can't simply be changed because the code currently
199 * uses a static number of position slots (and may make other assumptions as
201 #define LZX_MAX_WINDOW_SIZE 32768
203 /* This may be WIM-specific */
204 #define LZX_DEFAULT_BLOCK_SIZE 32768
206 #define LZX_MAX_CACHE_PER_POS 10
208 /* Codewords for the LZX main, length, and aligned offset Huffman codes */
209 struct lzx_codewords {
210 u16 main[LZX_MAINCODE_NUM_SYMBOLS];
211 u16 len[LZX_LENCODE_NUM_SYMBOLS];
212 u16 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
215 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
218 * A 0 length means the codeword has zero frequency.
221 u8 main[LZX_MAINCODE_NUM_SYMBOLS];
222 u8 len[LZX_LENCODE_NUM_SYMBOLS];
223 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
226 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
228 * If a codeword has zero frequency, it must still be assigned some nonzero cost
229 * --- generally a high cost, since even if it gets used in the next iteration,
230 * it probably will not be used very times. */
232 sym_cost_t main[LZX_MAINCODE_NUM_SYMBOLS];
233 sym_cost_t len[LZX_LENCODE_NUM_SYMBOLS];
234 sym_cost_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
237 /* The LZX main, length, and aligned offset Huffman codes */
239 struct lzx_codewords codewords;
240 struct lzx_lens lens;
243 /* Tables for tallying symbol frequencies in the three LZX alphabets */
245 freq_t main[LZX_MAINCODE_NUM_SYMBOLS];
246 freq_t len[LZX_LENCODE_NUM_SYMBOLS];
247 freq_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
250 /* LZX intermediate match/literal format */
254 * 31 1 if a match, 0 if a literal.
256 * 30-25 position slot. This can be at most 50, so it will fit in 6
259 * 8-24 position footer. This is the offset of the real formatted
260 * offset from the position base. This can be at most 17 bits
261 * (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
263 * 0-7 length of match, minus 2. This can be at most
264 * (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits. */
268 /* Raw LZ match/literal format: just a length and offset.
270 * The length is the number of bytes of the match, and the offset is the number
271 * of bytes back in the input the match is from the current position.
273 * If @len < LZX_MIN_MATCH_LEN, then it's really just a literal byte and @offset is
280 /* Specification for an LZX block. */
281 struct lzx_block_spec {
283 /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
287 /* 0-based position in the window at which this block starts. */
288 input_idx_t window_pos;
290 /* The number of bytes of uncompressed data this block represents. */
291 input_idx_t block_size;
293 /* The position in the 'chosen_matches' array in the `struct
294 * lzx_compressor' at which the match/literal specifications for
295 * this block begin. */
296 input_idx_t chosen_matches_start_pos;
298 /* The number of match/literal specifications for this block. */
299 input_idx_t num_chosen_matches;
301 /* Huffman codes for this block. */
302 struct lzx_codes codes;
306 * An array of these structures is used during the match-choosing algorithm.
307 * They correspond to consecutive positions in the window and are used to keep
308 * track of the cost to reach each position, and the match/literal choices that
309 * need to be chosen to reach that position.
312 /* The approximate minimum cost, in bits, to reach this position in the
313 * window which has been found so far. */
316 /* The union here is just for clarity, since the fields are used in two
317 * slightly different ways. Initially, the @prev structure is filled in
318 * first, and links go from later in the window to earlier in the
319 * window. Later, @next structure is filled in and links go from
320 * earlier in the window to later in the window. */
323 /* Position of the start of the match or literal that
324 * was taken to get to this position in the approximate
325 * minimum-cost parse. */
328 /* Offset (as in an LZ (length, offset) pair) of the
329 * match or literal that was taken to get to this
330 * position in the approximate minimum-cost parse. */
331 input_idx_t match_offset;
334 /* Position at which the match or literal starting at
335 * this position ends in the minimum-cost parse. */
338 /* Offset (as in an LZ (length, offset) pair) of the
339 * match or literal starting at this position in the
340 * approximate minimum-cost parse. */
341 input_idx_t match_offset;
345 /* The match offset LRU queue that will exist when the approximate
346 * minimum-cost path to reach this position is taken. */
347 struct lzx_lru_queue queue;
350 /* Suffix array link */
352 /* Rank of highest ranked suffix that has rank lower than the suffix
353 * corresponding to this structure and either has a lower position
354 * (initially) or has a position lower than the highest position at
355 * which matches have been searched for so far, or -1 if there is no
359 /* Rank of lowest ranked suffix that has rank greater than the suffix
360 * corresponding to this structure and either has a lower position
361 * (intially) or has a position lower than the highest position at which
362 * matches have been searched for so far, or -1 if there is no such
366 /* Length of longest common prefix between the suffix corresponding to
367 * this structure and the suffix with rank @prev, or 0 if @prev is -1.
371 /* Length of longest common prefix between the suffix corresponding to
372 * this structure and the suffix with rank @next, or 0 if @next is -1.
377 /* State of the LZX compressor. */
378 struct lzx_compressor {
380 /* The parameters that were used to create the compressor. */
381 struct wimlib_lzx_params params;
383 /* The buffer of data to be compressed.
385 * 0xe8 byte preprocessing is done directly on the data here before
386 * further compression.
388 * Note that this compressor does *not* use a sliding window!!!! It's
389 * not needed in the WIM format, since every chunk is compressed
390 * independently. This is by design, to allow random access to the
393 * We reserve a few extra bytes to potentially allow reading off the end
394 * of the array in the match-finding code for optimization purposes.
396 u8 window[LZX_MAX_WINDOW_SIZE + 12];
398 /* Number of bytes of data to be compressed, which is the number of
399 * bytes of data in @window that are actually valid. */
400 input_idx_t window_size;
402 /* The current match offset LRU queue. */
403 struct lzx_lru_queue queue;
405 /* Space for the sequences of matches/literals that were chosen for each
407 struct lzx_match *chosen_matches;
409 struct raw_match *cached_matches;
410 unsigned cached_matches_pos;
413 /* Information about the LZX blocks the preprocessed input was divided
415 struct lzx_block_spec *block_specs;
417 /* Number of LZX blocks the input was divided into; a.k.a. the number of
418 * elements of @block_specs that are valid. */
421 /* This is simply filled in with zeroes and used to avoid special-casing
422 * the output of the first compressed Huffman code, which conceptually
423 * has a delta taken from a code with all symbols having zero-length
425 struct lzx_codes zero_codes;
427 /* Slow algorithm only: The current cost model. */
428 struct lzx_costs costs;
430 /* Slow algorithm only: Suffix array for window.
431 * This is a mapping from suffix rank to suffix position.
433 * Suffix rank means the index of the suffix in the sorted list of
434 * suffixes, whereas suffix position means the index in the string at
435 * which the suffix starts.
439 /* Slow algorithm only: Inverse suffix array for window.
440 * This is a mapping from suffix position to suffix rank.
441 * In other words, if 0 <= r < window_size, then ISA[SA[r]] == r. */
444 /* Slow algorithm only: Longest Common Prefix array. LCP[i] is the
445 * number of initial bytes that the suffixes at positions SA[i - 1] and
446 * SA[i] share. LCP[0] is undefined. */
449 /* Slow algorithm only: Suffix array links.
451 * During a linear scan of the input string to find matches, this array
452 * used to keep track of which rank suffixes in the suffix array appear
453 * before the current position. Instead of searching in the original
454 * suffix array, scans for matches at a given position traverse a linked
455 * list containing only suffixes that appear before that position. */
456 struct salink *salink;
458 /* Slow algorithm only: Position in window of next match to return.
459 * This cannot simply be modified, as the match-finder must still be
460 * synchronized on the same position. To seek forwards or backwards,
461 * use lzx_lz_skip_bytes() or lzx_lz_rewind_matchfinder(), respectively.
463 input_idx_t match_window_pos;
465 /* Slow algorithm only: The match-finder shall ensure the length of
466 * matches does not exceed this position in the input. */
467 input_idx_t match_window_end;
469 /* Slow algorithm only: Temporary space used for match-choosing
472 * The size of this array must be at least LZX_MAX_MATCH_LEN but
473 * otherwise is arbitrary. More space simply allows the match-choosing
474 * algorithm to potentially find better matches (depending on the input,
476 struct lzx_optimal *optimum;
478 /* Slow algorithm only: Variables used by the match-choosing algorithm.
480 * When matches have been chosen, optimum_cur_idx is set to the position
481 * in the window of the next match/literal to return and optimum_end_idx
482 * is set to the position in the window at the end of the last
483 * match/literal to return. */
488 /* Returns the LZX position slot that corresponds to a given formatted offset.
490 * Logically, this returns the smallest i such that
491 * formatted_offset >= lzx_position_base[i].
493 * The actual implementation below takes advantage of the regularity of the
494 * numbers in the lzx_position_base array to calculate the slot directly from
495 * the formatted offset without actually looking at the array.
497 static _always_inline_attribute unsigned
498 lzx_get_position_slot_raw(unsigned formatted_offset)
502 * Slots 36-49 (formatted_offset >= 262144) can be found by
503 * (formatted_offset/131072) + 34 == (formatted_offset >> 17) + 34;
504 * however, this check for formatted_offset >= 262144 is commented out
505 * because WIM chunks cannot be that large.
507 if (formatted_offset >= 262144) {
508 return (formatted_offset >> 17) + 34;
512 /* Note: this part here only works if:
514 * 2 <= formatted_offset < 655360
516 * It is < 655360 because the frequency of the position bases
517 * increases starting at the 655360 entry, and it is >= 2
518 * because the below calculation fails if the most significant
519 * bit is lower than the 2's place. */
520 LZX_ASSERT(2 <= formatted_offset && formatted_offset < 655360);
521 unsigned mssb_idx = bsr32(formatted_offset);
522 return (mssb_idx << 1) |
523 ((formatted_offset >> (mssb_idx - 1)) & 1);
528 /* Returns the LZX position slot that corresponds to a given match offset,
529 * taking into account the recent offset queue (and optionally updating it). */
530 static _always_inline_attribute unsigned
531 lzx_get_position_slot(unsigned offset, struct lzx_lru_queue *queue)
533 unsigned position_slot;
535 /* See if the offset was recently used. */
536 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
537 if (offset == queue->R[i]) {
540 /* Bring the repeat offset to the front of the
541 * queue. Note: this is, in fact, not a real
542 * LRU queue because repeat matches are simply
543 * swapped to the front. */
544 swap(queue->R[0], queue->R[i]);
545 /* For recent offsets, the position slot is simply the
546 * index of the entry in the queue. */
552 /* The offset was not recently used; look up its real position slot. */
553 position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
555 /* Bring the new offset to the front of the queue. */
556 for (unsigned i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
557 queue->R[i] = queue->R[i - 1];
558 queue->R[0] = offset;
560 return position_slot;
563 /* Build the main, length, and aligned offset Huffman codes used in LZX.
565 * This takes as input the frequency tables for each code and produces as output
566 * a set of tables that map symbols to codewords and codeword lengths. */
568 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
569 struct lzx_codes *codes)
571 make_canonical_huffman_code(LZX_MAINCODE_NUM_SYMBOLS,
572 LZX_MAX_MAIN_CODEWORD_LEN,
575 codes->codewords.main);
577 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
578 LZX_MAX_LEN_CODEWORD_LEN,
581 codes->codewords.len);
583 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
584 LZX_MAX_ALIGNED_CODEWORD_LEN,
587 codes->codewords.aligned);
591 * Output an LZX match.
593 * @out: The bitstream to write the match to.
594 * @block_type: The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
596 * @codes: Pointer to a structure that contains the codewords for the
597 * main, length, and aligned offset Huffman codes.
600 lzx_write_match(struct output_bitstream *out, int block_type,
601 struct lzx_match match, const struct lzx_codes *codes)
603 /* low 8 bits are the match length minus 2 */
604 unsigned match_len_minus_2 = match.data & 0xff;
605 /* Next 17 bits are the position footer */
606 unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
607 /* Next 6 bits are the position slot. */
608 unsigned position_slot = (match.data >> 25) & 0x3f; /* 6 bits */
611 unsigned main_symbol;
612 unsigned num_extra_bits;
613 unsigned verbatim_bits;
614 unsigned aligned_bits;
616 /* If the match length is less than MIN_MATCH_LEN (= 2) +
617 * NUM_PRIMARY_LENS (= 7), the length header contains
618 * the match length minus MIN_MATCH_LEN, and there is no
621 * Otherwise, the length header contains
622 * NUM_PRIMARY_LENS, and the length footer contains
623 * the match length minus NUM_PRIMARY_LENS minus
625 if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
626 len_header = match_len_minus_2;
627 /* No length footer-- mark it with a special
629 len_footer = (unsigned)(-1);
631 len_header = LZX_NUM_PRIMARY_LENS;
632 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
635 /* Combine the position slot with the length header into a single symbol
636 * that will be encoded with the main tree.
638 * The actual main symbol is offset by LZX_NUM_CHARS because values
639 * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
641 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
643 /* Output main symbol. */
644 bitstream_put_bits(out, codes->codewords.main[main_symbol],
645 codes->lens.main[main_symbol]);
647 /* If there is a length footer, output it using the
648 * length Huffman code. */
649 if (len_footer != (unsigned)(-1)) {
650 bitstream_put_bits(out, codes->codewords.len[len_footer],
651 codes->lens.len[len_footer]);
654 num_extra_bits = lzx_get_num_extra_bits(position_slot);
656 /* For aligned offset blocks with at least 3 extra bits, output the
657 * verbatim bits literally, then the aligned bits encoded using the
658 * aligned offset tree. Otherwise, only the verbatim bits need to be
660 if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
662 verbatim_bits = position_footer >> 3;
663 bitstream_put_bits(out, verbatim_bits,
666 aligned_bits = (position_footer & 7);
667 bitstream_put_bits(out,
668 codes->codewords.aligned[aligned_bits],
669 codes->lens.aligned[aligned_bits]);
671 /* verbatim bits is the same as the position
672 * footer, in this case. */
673 bitstream_put_bits(out, position_footer, num_extra_bits);
678 lzx_build_precode(const u8 lens[restrict],
679 const u8 prev_lens[restrict],
680 const unsigned num_syms,
681 freq_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
682 u8 output_syms[restrict num_syms],
683 u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
684 u16 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
685 unsigned *num_additional_bits_ret)
687 memset(precode_freqs, 0,
688 LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
690 /* Since the code word lengths use a form of RLE encoding, the goal here
691 * is to find each run of identical lengths when going through them in
692 * symbol order (including runs of length 1). For each run, as many
693 * lengths are encoded using RLE as possible, and the rest are output
696 * output_syms[] will be filled in with the length symbols that will be
697 * output, including RLE codes, not yet encoded using the pre-tree.
699 * cur_run_len keeps track of how many code word lengths are in the
700 * current run of identical lengths. */
701 unsigned output_syms_idx = 0;
702 unsigned cur_run_len = 1;
703 unsigned num_additional_bits = 0;
704 for (unsigned i = 1; i <= num_syms; i++) {
706 if (i != num_syms && lens[i] == lens[i - 1]) {
707 /* Still in a run--- keep going. */
712 /* Run ended! Check if it is a run of zeroes or a run of
715 /* The symbol that was repeated in the run--- not to be confused
716 * with the length *of* the run (cur_run_len) */
717 unsigned len_in_run = lens[i - 1];
719 if (len_in_run == 0) {
720 /* A run of 0's. Encode it in as few length
721 * codes as we can. */
723 /* The magic length 18 indicates a run of 20 + n zeroes,
724 * where n is an uncompressed literal 5-bit integer that
725 * follows the magic length. */
726 while (cur_run_len >= 20) {
727 unsigned additional_bits;
729 additional_bits = min(cur_run_len - 20, 0x1f);
730 num_additional_bits += 5;
732 output_syms[output_syms_idx++] = 18;
733 output_syms[output_syms_idx++] = additional_bits;
734 cur_run_len -= 20 + additional_bits;
737 /* The magic length 17 indicates a run of 4 + n zeroes,
738 * where n is an uncompressed literal 4-bit integer that
739 * follows the magic length. */
740 while (cur_run_len >= 4) {
741 unsigned additional_bits;
743 additional_bits = min(cur_run_len - 4, 0xf);
744 num_additional_bits += 4;
746 output_syms[output_syms_idx++] = 17;
747 output_syms[output_syms_idx++] = additional_bits;
748 cur_run_len -= 4 + additional_bits;
753 /* A run of nonzero lengths. */
755 /* The magic length 19 indicates a run of 4 + n
756 * nonzeroes, where n is a literal bit that follows the
757 * magic length, and where the value of the lengths in
758 * the run is given by an extra length symbol, encoded
759 * with the precode, that follows the literal bit.
761 * The extra length symbol is encoded as a difference
762 * from the length of the codeword for the first symbol
763 * in the run in the previous tree.
765 while (cur_run_len >= 4) {
766 unsigned additional_bits;
769 additional_bits = (cur_run_len > 4);
770 num_additional_bits += 1;
771 delta = (signed char)prev_lens[i - cur_run_len] -
772 (signed char)len_in_run;
776 precode_freqs[(unsigned char)delta]++;
777 output_syms[output_syms_idx++] = 19;
778 output_syms[output_syms_idx++] = additional_bits;
779 output_syms[output_syms_idx++] = delta;
780 cur_run_len -= 4 + additional_bits;
784 /* Any remaining lengths in the run are outputted without RLE,
785 * as a difference from the length of that codeword in the
787 while (cur_run_len > 0) {
790 delta = (signed char)prev_lens[i - cur_run_len] -
791 (signed char)len_in_run;
795 precode_freqs[(unsigned char)delta]++;
796 output_syms[output_syms_idx++] = delta;
803 /* Build the precode from the frequencies of the length symbols. */
805 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
806 LZX_MAX_PRE_CODEWORD_LEN,
807 precode_freqs, precode_lens,
810 *num_additional_bits_ret = num_additional_bits;
812 return output_syms_idx;
816 * Writes a compressed Huffman code to the output, preceded by the precode for
819 * The Huffman code is represented in the output as a series of path lengths
820 * from which the canonical Huffman code can be reconstructed. The path lengths
821 * themselves are compressed using a separate Huffman code, the precode, which
822 * consists of LZX_PRECODE_NUM_SYMBOLS (= 20) symbols that cover all possible
823 * code lengths, plus extra codes for repeated lengths. The path lengths of the
824 * precode precede the path lengths of the larger code and are uncompressed,
825 * consisting of 20 entries of 4 bits each.
827 * @out: Bitstream to write the code to.
828 * @lens: The code lengths for the Huffman code, indexed by symbol.
829 * @prev_lens: Code lengths for this Huffman code, indexed by symbol,
830 * in the *previous block*, or all zeroes if this is the
832 * @num_syms: The number of symbols in the code.
835 lzx_write_compressed_code(struct output_bitstream *out,
836 const u8 lens[restrict],
837 const u8 prev_lens[restrict],
840 freq_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
841 u8 output_syms[num_syms];
842 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
843 u16 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
845 unsigned num_output_syms;
849 num_output_syms = lzx_build_precode(lens,
858 /* Write the lengths of the precode codes to the output. */
859 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
860 bitstream_put_bits(out, precode_lens[i],
861 LZX_PRECODE_ELEMENT_SIZE);
863 /* Write the length symbols, encoded with the precode, to the output. */
865 for (i = 0; i < num_output_syms; ) {
866 precode_sym = output_syms[i++];
868 bitstream_put_bits(out, precode_codewords[precode_sym],
869 precode_lens[precode_sym]);
870 switch (precode_sym) {
872 bitstream_put_bits(out, output_syms[i++], 4);
875 bitstream_put_bits(out, output_syms[i++], 5);
878 bitstream_put_bits(out, output_syms[i++], 1);
879 bitstream_put_bits(out,
880 precode_codewords[output_syms[i]],
881 precode_lens[output_syms[i]]);
891 * Writes all compressed matches and literal bytes in an LZX block to the the
895 * The output bitstream.
897 * The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM).
899 * The array of matches/literals that will be output (length @match_count).
901 * Number of matches/literals to be output.
903 * Pointer to a structure that contains the codewords for the main, length,
904 * and aligned offset Huffman codes.
907 lzx_write_matches_and_literals(struct output_bitstream *ostream,
909 const struct lzx_match match_tab[],
910 unsigned match_count,
911 const struct lzx_codes *codes)
913 for (unsigned i = 0; i < match_count; i++) {
914 struct lzx_match match = match_tab[i];
916 /* High bit of the match indicates whether the match is an
917 * actual match (1) or a literal uncompressed byte (0) */
918 if (match.data & 0x80000000) {
920 lzx_write_match(ostream, block_type,
924 bitstream_put_bits(ostream,
925 codes->codewords.main[match.data],
926 codes->lens.main[match.data]);
932 lzx_assert_codes_valid(const struct lzx_codes * codes)
934 #ifdef ENABLE_LZX_DEBUG
937 for (i = 0; i < LZX_MAINCODE_NUM_SYMBOLS; i++)
938 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
940 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
941 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
943 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
944 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
946 const unsigned tablebits = 10;
947 u16 decode_table[(1 << tablebits) +
948 (2 * max(LZX_MAINCODE_NUM_SYMBOLS, LZX_LENCODE_NUM_SYMBOLS))]
949 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
950 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
951 LZX_MAINCODE_NUM_SYMBOLS,
952 min(tablebits, LZX_MAINCODE_TABLEBITS),
954 LZX_MAX_MAIN_CODEWORD_LEN));
955 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
956 LZX_LENCODE_NUM_SYMBOLS,
957 min(tablebits, LZX_LENCODE_TABLEBITS),
959 LZX_MAX_LEN_CODEWORD_LEN));
960 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
961 LZX_ALIGNEDCODE_NUM_SYMBOLS,
962 min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
964 LZX_MAX_ALIGNED_CODEWORD_LEN));
965 #endif /* ENABLE_LZX_DEBUG */
968 /* Write an LZX aligned offset or verbatim block to the output. */
970 lzx_write_compressed_block(int block_type,
972 struct lzx_match * chosen_matches,
973 unsigned num_chosen_matches,
974 const struct lzx_codes * codes,
975 const struct lzx_codes * prev_codes,
976 struct output_bitstream * ostream)
980 LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
981 block_type == LZX_BLOCKTYPE_VERBATIM);
982 LZX_ASSERT(block_size <= LZX_MAX_WINDOW_SIZE);
983 LZX_ASSERT(num_chosen_matches <= LZX_MAX_WINDOW_SIZE);
984 lzx_assert_codes_valid(codes);
986 /* The first three bits indicate the type of block and are one of the
987 * LZX_BLOCKTYPE_* constants. */
988 bitstream_put_bits(ostream, block_type, LZX_BLOCKTYPE_NBITS);
990 /* The next bit indicates whether the block size is the default (32768),
991 * indicated by a 1 bit, or whether the block size is given by the next
992 * 16 bits, indicated by a 0 bit. */
993 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
994 bitstream_put_bits(ostream, 1, 1);
996 bitstream_put_bits(ostream, 0, 1);
997 bitstream_put_bits(ostream, block_size, LZX_BLOCKSIZE_NBITS);
1000 /* Write out lengths of the main code. Note that the LZX specification
1001 * incorrectly states that the aligned offset code comes after the
1002 * length code, but in fact it is the very first tree to be written
1003 * (before the main code). */
1004 if (block_type == LZX_BLOCKTYPE_ALIGNED)
1005 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1006 bitstream_put_bits(ostream, codes->lens.aligned[i],
1007 LZX_ALIGNEDCODE_ELEMENT_SIZE);
1009 LZX_DEBUG("Writing main code...");
1011 /* Write the pre-tree and lengths for the first LZX_NUM_CHARS symbols in
1012 * the main code, which are the codewords for literal bytes. */
1013 lzx_write_compressed_code(ostream,
1015 prev_codes->lens.main,
1018 /* Write the pre-tree and lengths for the rest of the main code, which
1019 * are the codewords for match headers. */
1020 lzx_write_compressed_code(ostream,
1021 codes->lens.main + LZX_NUM_CHARS,
1022 prev_codes->lens.main + LZX_NUM_CHARS,
1023 LZX_MAINCODE_NUM_SYMBOLS - LZX_NUM_CHARS);
1025 LZX_DEBUG("Writing length code...");
1027 /* Write the pre-tree and lengths for the length code. */
1028 lzx_write_compressed_code(ostream,
1030 prev_codes->lens.len,
1031 LZX_LENCODE_NUM_SYMBOLS);
1033 LZX_DEBUG("Writing matches and literals...");
1035 /* Write the actual matches and literals. */
1036 lzx_write_matches_and_literals(ostream, block_type,
1037 chosen_matches, num_chosen_matches,
1040 LZX_DEBUG("Done writing block.");
1043 /* Write out the LZX blocks that were computed. */
1045 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
1047 const struct lzx_codes *prev_codes = &ctx->zero_codes;
1048 for (unsigned i = 0; i < ctx->num_blocks; i++) {
1049 const struct lzx_block_spec *spec = &ctx->block_specs[i];
1051 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
1052 i + 1, ctx->num_blocks,
1053 spec->block_type, spec->block_size,
1054 spec->num_chosen_matches);
1056 lzx_write_compressed_block(spec->block_type,
1058 &ctx->chosen_matches[spec->chosen_matches_start_pos],
1059 spec->num_chosen_matches,
1063 prev_codes = &spec->codes;
1067 /* Constructs an LZX match from a literal byte and updates the main code symbol
1070 lzx_record_literal(u8 literal, void *_freqs)
1072 struct lzx_freqs *freqs = _freqs;
1074 freqs->main[literal]++;
1076 return (u32)literal;
1079 /* Constructs an LZX match from an offset and a length, and updates the LRU
1080 * queue and the frequency of symbols in the main, length, and aligned offset
1081 * alphabets. The return value is a 32-bit number that provides the match in an
1082 * intermediate representation documented below. */
1084 lzx_record_match(unsigned match_offset, unsigned match_len,
1085 void *_freqs, void *_queue)
1087 struct lzx_freqs *freqs = _freqs;
1088 struct lzx_lru_queue *queue = _queue;
1089 unsigned position_slot;
1090 unsigned position_footer;
1092 unsigned main_symbol;
1093 unsigned len_footer;
1094 unsigned adjusted_match_len;
1096 LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
1098 /* The match offset shall be encoded as a position slot (itself encoded
1099 * as part of the main symbol) and a position footer. */
1100 position_slot = lzx_get_position_slot(match_offset, queue);
1101 position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1102 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1104 /* The match length shall be encoded as a length header (itself encoded
1105 * as part of the main symbol) and an optional length footer. */
1106 adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1107 if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1108 /* No length footer needed. */
1109 len_header = adjusted_match_len;
1111 /* Length footer needed. It will be encoded using the length
1113 len_header = LZX_NUM_PRIMARY_LENS;
1114 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1115 freqs->len[len_footer]++;
1118 /* Account for the main symbol. */
1119 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1121 freqs->main[main_symbol]++;
1123 /* In an aligned offset block, 3 bits of the position footer are output
1124 * as an aligned offset symbol. Account for this, although we may
1125 * ultimately decide to output the block as verbatim. */
1127 /* The following check is equivalent to:
1129 * if (lzx_extra_bits[position_slot] >= 3)
1131 * Note that this correctly excludes position slots that correspond to
1132 * recent offsets. */
1133 if (position_slot >= 8)
1134 freqs->aligned[position_footer & 7]++;
1136 /* Pack the position slot, position footer, and match length into an
1137 * intermediate representation.
1140 * ---- -----------------------------------------------------------
1142 * 31 1 if a match, 0 if a literal.
1144 * 30-25 position slot. This can be at most 50, so it will fit in 6
1147 * 8-24 position footer. This is the offset of the real formatted
1148 * offset from the position base. This can be at most 17 bits
1149 * (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
1151 * 0-7 length of match, offset by 2. This can be at most
1152 * (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits. */
1153 BUILD_BUG_ON(LZX_NUM_POSITION_SLOTS > 64);
1154 LZX_ASSERT(lzx_get_num_extra_bits(LZX_NUM_POSITION_SLOTS - 1) <= 17);
1155 BUILD_BUG_ON(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 > 256);
1157 (position_slot << 25) |
1158 (position_footer << 8) |
1159 (adjusted_match_len);
1162 /* Returns the cost, in bits, to output a literal byte using the specified cost
1165 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1167 return costs->main[c];
1170 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1171 * well as costs for the codewords in the main, length, and aligned Huffman
1172 * codes, return the approximate number of bits it will take to represent this
1173 * match in the compressed output. Take into account the match offset LRU
1174 * queue and optionally update it. */
1176 lzx_match_cost(unsigned length, unsigned offset, const struct lzx_costs *costs,
1177 struct lzx_lru_queue *queue)
1179 unsigned position_slot;
1180 unsigned len_header, main_symbol;
1181 sym_cost_t cost = 0;
1183 position_slot = lzx_get_position_slot(offset, queue);
1185 len_header = min(length - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1186 main_symbol = (position_slot << 3) | len_header | LZX_NUM_CHARS;
1188 /* Account for main symbol. */
1189 cost += costs->main[main_symbol];
1191 /* Account for extra position information. */
1192 unsigned num_extra_bits = lzx_get_num_extra_bits(position_slot);
1193 if (num_extra_bits >= 3) {
1194 cost += num_extra_bits - 3;
1195 cost += costs->aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1197 cost += num_extra_bits;
1200 /* Account for extra length information. */
1201 if (len_header == LZX_NUM_PRIMARY_LENS)
1202 cost += costs->len[length - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1208 /* Very fast heuristic cost evaluation to use in the inner loop of the
1211 lzx_match_cost_fast(unsigned offset, const struct lzx_lru_queue *queue)
1213 for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
1214 if (offset == queue->R[i])
1217 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE >= (sym_cost_t)~0U);
1221 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1224 * The cost model and codeword lengths are almost the same thing, but the
1225 * Huffman codewords with length 0 correspond to symbols with zero frequency
1226 * that still need to be assigned actual costs. The specific values assigned
1227 * are arbitrary, but they should be fairly high (near the maximum codeword
1228 * length) to take into account the fact that uses of these symbols are expected
1231 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1236 for (i = 0; i < LZX_MAINCODE_NUM_SYMBOLS; i++) {
1237 ctx->costs.main[i] = lens->main[i];
1238 if (ctx->costs.main[i] == 0)
1239 ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1243 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1244 ctx->costs.len[i] = lens->len[i];
1245 if (ctx->costs.len[i] == 0)
1246 ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1249 /* Aligned offset code */
1250 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1251 ctx->costs.aligned[i] = lens->aligned[i];
1252 if (ctx->costs.aligned[i] == 0)
1253 ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1257 /* Advance the suffix array match-finder to the next position. */
1259 lzx_lz_update_salink(input_idx_t i,
1260 const input_idx_t SA[restrict],
1261 const input_idx_t ISA[restrict],
1262 struct salink link[restrict])
1264 /* r = Rank of the suffix at the current position. */
1265 const input_idx_t r = ISA[i];
1267 /* next = rank of LOWEST ranked suffix that is ranked HIGHER than the
1268 * current suffix AND has a LOWER position, or -1 if none exists. */
1269 const input_idx_t next = link[r].next;
1271 /* prev = rank of HIGHEST ranked suffix that is ranked LOWER than the
1272 * current suffix AND has a LOWER position, or -1 if none exists. */
1273 const input_idx_t prev = link[r].prev;
1275 /* Link the suffix at the current position into the linked list that
1276 * contains all suffixes in the suffix array that are appear at or
1277 * before the current position, sorted by rank.
1279 * Save the values of all fields we overwrite so that rollback is
1281 if (next != (input_idx_t)~0U) {
1283 link[next].prev = r;
1284 link[next].lcpprev = link[r].lcpnext;
1287 if (prev != (input_idx_t)~0U) {
1289 link[prev].next = r;
1290 link[prev].lcpnext = link[r].lcpprev;
1294 /* Rewind the suffix array match-finder to the specified position.
1296 * This undoes a series of updates by lzx_lz_update_salink(). */
1298 lzx_lz_rewind_matchfinder(struct lzx_compressor *ctx,
1299 const unsigned orig_pos)
1301 LZX_DEBUG("Rewind match-finder %u => %u", ctx->match_window_pos, orig_pos);
1303 if (ctx->match_window_pos == orig_pos)
1306 LZX_ASSERT(ctx->match_window_pos > orig_pos);
1307 LZX_ASSERT(orig_pos == 0);
1308 ctx->matches_cached = true;
1309 ctx->cached_matches_pos = 0;
1310 ctx->match_window_pos = orig_pos;
1314 * Use the suffix array match-finder to retrieve a list of LZ matches at the
1317 * [in] @i Current position in the window.
1318 * [in] @SA Suffix array for the window.
1319 * [in] @ISA Inverse suffix array for the window.
1320 * [inout] @link Suffix array links used internally by the match-finder.
1321 * [out] @matches The (length, offset) pairs of the resulting matches will
1322 * be written here, sorted in decreasing order by
1323 * length. All returned lengths will be unique.
1324 * [in] @queue Recently used match offsets, used when evaluating the
1326 * [in] @min_match_len Minimum match length to return.
1327 * [in] @max_matches_to_consider Maximum number of matches to consider at
1329 * [in] @max_matches_to_return Maximum number of matches to return.
1331 * The return value is the number of matches found and written to @matches.
1334 lzx_lz_get_matches(const input_idx_t i,
1335 const input_idx_t SA[const restrict],
1336 const input_idx_t ISA[const restrict],
1337 struct salink link[const restrict],
1338 struct raw_match matches[const restrict],
1339 const struct lzx_lru_queue * const restrict queue,
1340 const unsigned min_match_len,
1341 const uint32_t max_matches_to_consider,
1342 const uint32_t max_matches_to_return)
1344 /* r = Rank of the suffix at the current position. */
1345 const input_idx_t r = ISA[i];
1347 /* Prepare for searching the current position. */
1348 lzx_lz_update_salink(i, SA, ISA, link);
1350 /* L = rank of next suffix to the left;
1351 * R = rank of next suffix to the right;
1352 * lenL = length of match between current position and the suffix with rank L;
1353 * lenR = length of match between current position and the suffix with rank R.
1355 * This is left and right relative to the rank of the current suffix.
1356 * Since the suffixes in the suffix array are sorted, the longest
1357 * matches are immediately to the left and right (using the linked list
1358 * to ignore all suffixes that occur later in the window). The match
1359 * length decreases the farther left and right we go. We shall keep the
1360 * length on both sides in sync in order to choose the lowest-cost match
1363 input_idx_t L = link[r].prev;
1364 input_idx_t R = link[r].next;
1365 input_idx_t lenL = link[r].lcpprev;
1366 input_idx_t lenR = link[r].lcpnext;
1368 /* nmatches = number of matches found so far. */
1369 unsigned nmatches = 0;
1371 /* best_cost = cost of lowest-cost match found so far.
1373 * We keep track of this so that we can ignore shorter matches that do
1374 * not have lower costs than a longer matches already found.
1376 sym_cost_t best_cost = INFINITE_SYM_COST;
1378 /* count_remaining = maximum number of possible matches remaining to be
1380 uint32_t count_remaining = max_matches_to_consider;
1382 /* pending = match currently being considered for a specific length. */
1383 struct raw_match pending;
1385 while (lenL >= min_match_len || lenR >= min_match_len)
1388 pending.offset = (input_idx_t)~0U;
1389 sym_cost_t pending_cost = INFINITE_SYM_COST;
1393 if (lenL >= min_match_len && lenL >= lenR) {
1396 if (--count_remaining == 0)
1397 goto out_save_pending;
1399 input_idx_t offset = i - SA[L];
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[L].lcpprev < lenL) {
1409 /* Match length decreased. */
1411 lenL = link[L].lcpprev;
1413 /* Save the pending match unless the
1414 * right side still may have matches of
1415 * this length to be scanned, or if a
1416 * previous (longer) match had lower
1418 if (pending.len > lenR) {
1419 if (pending_cost < best_cost) {
1420 best_cost = pending_cost;
1421 matches[nmatches++] = pending;
1422 if (nmatches == max_matches_to_return)
1426 pending.offset = (input_idx_t)~0U;
1427 pending_cost = INFINITE_SYM_COST;
1429 if (lenL < min_match_len || lenL < lenR)
1439 if (lenR >= min_match_len && lenR > lenL) {
1442 if (--count_remaining == 0)
1443 goto out_save_pending;
1445 input_idx_t offset = i - SA[R];
1447 /* Save match if it has smaller cost. */
1448 cost = lzx_match_cost_fast(offset, queue);
1449 if (cost < pending_cost) {
1450 pending.offset = offset;
1451 pending_cost = cost;
1454 if (link[R].lcpnext < lenR) {
1455 /* Match length decreased. */
1457 lenR = link[R].lcpnext;
1459 /* Save the pending match unless a
1460 * previous (longer) match had lower
1462 if (pending_cost < best_cost) {
1463 matches[nmatches++] = pending;
1464 best_cost = pending_cost;
1465 if (nmatches == max_matches_to_return)
1469 if (lenR < min_match_len || lenR <= lenL)
1473 pending.offset = (input_idx_t)~0U;
1474 pending_cost = INFINITE_SYM_COST;
1483 if (pending.offset != (input_idx_t)~0U)
1484 matches[nmatches++] = pending;
1491 /* Tell the match-finder to skip the specified number of bytes (@n) in the
1494 lzx_lz_skip_bytes(struct lzx_compressor *ctx, unsigned n)
1496 LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1497 if (ctx->matches_cached) {
1498 ctx->match_window_pos += n;
1500 ctx->cached_matches_pos +=
1501 ctx->cached_matches[ctx->cached_matches_pos].len + 1;
1505 ctx->cached_matches[ctx->cached_matches_pos++].len = 0;
1506 lzx_lz_update_salink(ctx->match_window_pos++, ctx->SA,
1507 ctx->ISA, ctx->salink);
1512 /* Retrieve a list of matches available at the next position in the input.
1514 * The matches are written to ctx->matches in decreasing order of length, and
1515 * the return value is the number of matches found. */
1517 lzx_lz_get_matches_caching(struct lzx_compressor *ctx,
1518 const struct lzx_lru_queue *queue,
1519 struct raw_match **matches_ret)
1521 unsigned num_matches;
1522 struct raw_match *matches;
1524 LZX_ASSERT(ctx->match_window_pos <= ctx->match_window_end);
1526 matches = &ctx->cached_matches[ctx->cached_matches_pos + 1];
1528 if (ctx->matches_cached) {
1529 num_matches = matches[-1].len;
1531 unsigned min_match_len = LZX_MIN_MATCH_LEN;
1532 if (min_match_len <= 2 && !ctx->params.alg_params.slow.use_len2_matches)
1534 const uint32_t max_search_depth = ctx->params.alg_params.slow.max_search_depth;
1535 const uint32_t max_matches_per_pos = ctx->params.alg_params.slow.max_matches_per_pos;
1537 if (unlikely(max_search_depth == 0 || max_matches_per_pos == 0))
1540 num_matches = lzx_lz_get_matches(ctx->match_window_pos,
1548 max_matches_per_pos);
1549 matches[-1].len = num_matches;
1551 ctx->cached_matches_pos += num_matches + 1;
1552 *matches_ret = matches;
1554 /* Cap the length of returned matches to the number of bytes remaining,
1555 * if it is not the whole window. */
1556 if (ctx->match_window_end < ctx->window_size) {
1557 unsigned maxlen = ctx->match_window_end - ctx->match_window_pos;
1558 for (unsigned i = 0; i < num_matches; i++)
1559 if (matches[i].len > maxlen)
1560 matches[i].len = maxlen;
1563 fprintf(stderr, "Pos %u/%u: %u matches\n",
1564 ctx->match_window_pos, ctx->match_window_end, num_matches);
1565 for (unsigned i = 0; i < num_matches; i++)
1566 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1569 #ifdef ENABLE_LZX_DEBUG
1570 for (unsigned i = 0; i < num_matches; i++) {
1571 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1572 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1573 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1574 LZX_ASSERT(matches[i].offset > 0);
1575 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1576 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1577 &ctx->window[ctx->match_window_pos - matches[i].offset],
1582 ctx->match_window_pos++;
1587 * Reverse the linked list of near-optimal matches so that they can be returned
1588 * in forwards order.
1590 * Returns the first match in the list.
1592 static struct raw_match
1593 lzx_lz_reverse_near_optimal_match_list(struct lzx_compressor *ctx,
1596 unsigned prev_link, saved_prev_link;
1597 unsigned prev_match_offset, saved_prev_match_offset;
1599 ctx->optimum_end_idx = cur_pos;
1601 saved_prev_link = ctx->optimum[cur_pos].prev.link;
1602 saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
1605 prev_link = saved_prev_link;
1606 prev_match_offset = saved_prev_match_offset;
1608 saved_prev_link = ctx->optimum[prev_link].prev.link;
1609 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
1611 ctx->optimum[prev_link].next.link = cur_pos;
1612 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
1614 cur_pos = prev_link;
1615 } while (cur_pos != 0);
1617 ctx->optimum_cur_idx = ctx->optimum[0].next.link;
1619 return (struct raw_match)
1620 { .len = ctx->optimum_cur_idx,
1621 .offset = ctx->optimum[0].next.match_offset,
1626 * lzx_lz_get_near_optimal_match() -
1628 * Choose the optimal match or literal to use at the next position in the input.
1630 * Unlike a greedy parser that always takes the longest match, or even a
1631 * parser with one match/literal look-ahead like zlib, the algorithm used here
1632 * may look ahead many matches/literals to determine the optimal match/literal to
1633 * output next. The motivation is that the compression ratio is improved if the
1634 * compressor can do things like use a shorter-than-possible match in order to
1635 * allow a longer match later, and also take into account the Huffman code cost
1636 * model rather than simply assuming that longer is better.
1638 * Still, this is not truly an optimal parser because very long matches are
1639 * taken immediately. This is done to avoid considering many different
1640 * alternatives that are unlikely to significantly be better.
1642 * This algorithm is based on that used in 7-Zip's DEFLATE encoder.
1644 * Each call to this function does one of two things:
1646 * 1. Build a near-optimal sequence of matches/literals, up to some point, that
1647 * will be returned by subsequent calls to this function, then return the
1652 * 2. Return the next match/literal previously computed by a call to this
1655 * This function relies on the following state in the compressor context:
1657 * ctx->window (read-only: preprocessed data being compressed)
1658 * ctx->cost (read-only: cost model to use)
1659 * ctx->optimum (internal state; leave uninitialized)
1660 * ctx->optimum_cur_idx (must set to 0 before first call)
1661 * ctx->optimum_end_idx (must set to 0 before first call)
1662 * ctx->SA (must be built before first call)
1663 * ctx->ISA (must be built before first call)
1664 * ctx->salink (must be built before first call)
1665 * ctx->match_window_pos (must initialize to position of next match to
1666 * return; subsequent calls return subsequent
1668 * ctx->match_window_end (must initialize to limit of match-finding region;
1669 * subsequent calls use the same limit)
1671 * The return value is a (length, offset) pair specifying the match or literal
1672 * chosen. For literals, the length is less than LZX_MIN_MATCH_LEN and the
1673 * offset is meaningless.
1675 static struct raw_match
1676 lzx_lz_get_near_optimal_match(struct lzx_compressor * ctx)
1678 unsigned num_possible_matches;
1679 struct raw_match *possible_matches;
1680 struct raw_match match;
1681 unsigned longest_match_len;
1683 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1684 /* Case 2: Return the next match/literal already found. */
1685 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1686 ctx->optimum_cur_idx;
1687 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1689 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1693 /* Case 1: Compute a new list of matches/literals to return. */
1695 ctx->optimum_cur_idx = 0;
1696 ctx->optimum_end_idx = 0;
1698 /* Get matches at this position. */
1699 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &possible_matches);
1701 /* If no matches found, return literal. */
1702 if (num_possible_matches == 0)
1703 return (struct raw_match){ .len = 0 };
1705 /* The matches that were found are sorted in decreasing order by length.
1706 * Get the length of the longest one. */
1707 longest_match_len = possible_matches[0].len;
1709 /* Greedy heuristic: if the longest match that was found is greater
1710 * than the number of fast bytes, return it immediately; don't both
1711 * doing more work. */
1712 if (longest_match_len > ctx->params.alg_params.slow.num_fast_bytes) {
1713 lzx_lz_skip_bytes(ctx, longest_match_len - 1);
1714 return possible_matches[0];
1717 /* Calculate the cost to reach the next position by outputting a
1719 ctx->optimum[0].queue = ctx->queue;
1720 ctx->optimum[1].queue = ctx->optimum[0].queue;
1721 ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos],
1723 ctx->optimum[1].prev.link = 0;
1725 /* Calculate the cost to reach any position up to and including that
1726 * reached by the longest match, using the shortest (i.e. closest) match
1727 * that reaches each position. */
1728 BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1729 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1730 len <= longest_match_len; len++) {
1732 LZX_ASSERT(match_idx < num_possible_matches);
1734 ctx->optimum[len].queue = ctx->optimum[0].queue;
1735 ctx->optimum[len].prev.link = 0;
1736 ctx->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
1737 ctx->optimum[len].cost = lzx_match_cost(len,
1738 possible_matches[match_idx].offset,
1740 &ctx->optimum[len].queue);
1741 if (len == possible_matches[match_idx].len)
1745 unsigned cur_pos = 0;
1747 /* len_end: greatest index forward at which costs have been calculated
1749 unsigned len_end = longest_match_len;
1752 /* Advance to next position. */
1755 if (cur_pos == len_end || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1756 return lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1758 /* retrieve the number of matches available at this position */
1759 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->optimum[cur_pos].queue,
1762 unsigned new_len = 0;
1764 if (num_possible_matches != 0) {
1765 new_len = possible_matches[0].len;
1767 /* Greedy heuristic: if we found a match greater than
1768 * the number of fast bytes, stop immediately. */
1769 if (new_len > ctx->params.alg_params.slow.num_fast_bytes) {
1771 /* Build the list of matches to return and get
1773 match = lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1775 /* Append the long match to the end of the list. */
1776 ctx->optimum[cur_pos].next.match_offset =
1777 possible_matches[0].offset;
1778 ctx->optimum[cur_pos].next.link = cur_pos + new_len;
1779 ctx->optimum_end_idx = cur_pos + new_len;
1781 /* Skip over the remaining bytes of the long match. */
1782 lzx_lz_skip_bytes(ctx, new_len - 1);
1784 /* Return first match in the list */
1789 /* Consider proceeding with a literal byte. */
1790 block_cost_t cur_cost = ctx->optimum[cur_pos].cost;
1791 block_cost_t cur_plus_literal_cost = cur_cost +
1792 lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1794 if (cur_plus_literal_cost < ctx->optimum[cur_pos + 1].cost) {
1795 ctx->optimum[cur_pos + 1].cost = cur_plus_literal_cost;
1796 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1797 ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1800 if (num_possible_matches == 0)
1803 /* Consider proceeding with a match. */
1805 while (len_end < cur_pos + new_len)
1806 ctx->optimum[++len_end].cost = INFINITE_BLOCK_COST;
1808 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1809 len <= new_len; len++) {
1810 LZX_ASSERT(match_idx < num_possible_matches);
1811 struct lzx_lru_queue q = ctx->optimum[cur_pos].queue;
1812 block_cost_t cost = cur_cost + lzx_match_cost(len,
1813 possible_matches[match_idx].offset,
1817 if (cost < ctx->optimum[cur_pos + len].cost) {
1818 ctx->optimum[cur_pos + len].cost = cost;
1819 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1820 ctx->optimum[cur_pos + len].prev.match_offset =
1821 possible_matches[match_idx].offset;
1822 ctx->optimum[cur_pos + len].queue = q;
1825 if (len == possible_matches[match_idx].len)
1832 * Set default symbol costs.
1835 lzx_set_default_costs(struct lzx_costs * costs)
1839 /* Literal symbols */
1840 for (i = 0; i < LZX_NUM_CHARS; i++)
1843 /* Match header symbols */
1844 for (; i < LZX_MAINCODE_NUM_SYMBOLS; i++)
1845 costs->main[i] = 10;
1847 /* Length symbols */
1848 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1851 /* Aligned offset symbols */
1852 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1853 costs->aligned[i] = 3;
1856 /* Given the frequencies of symbols in a compressed block and the corresponding
1857 * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1858 * aligned offset or verbatim block, respectively, will take fewer bits to
1861 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1862 const struct lzx_codes * codes)
1864 unsigned aligned_cost = 0;
1865 unsigned verbatim_cost = 0;
1867 /* Verbatim blocks have a constant 3 bits per position footer. Aligned
1868 * offset blocks have an aligned offset symbol per position footer, plus
1869 * an extra 24 bits to output the lengths necessary to reconstruct the
1870 * aligned offset code itself. */
1871 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1872 verbatim_cost += 3 * freqs->aligned[i];
1873 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1875 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1876 if (aligned_cost < verbatim_cost)
1877 return LZX_BLOCKTYPE_ALIGNED;
1879 return LZX_BLOCKTYPE_VERBATIM;
1882 /* Find a near-optimal sequence of matches/literals with which to output the
1883 * specified LZX block, and set its type to that which has the minimum cost to
1886 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1887 unsigned num_passes)
1889 struct lzx_lru_queue orig_queue = ctx->queue;
1890 struct lzx_freqs freqs;
1892 ctx->match_window_end = spec->window_pos + spec->block_size;
1893 spec->chosen_matches_start_pos = spec->window_pos;
1895 LZX_ASSERT(num_passes >= 1);
1897 /* The first optimal parsing pass is done using the cost model already
1898 * set in ctx->costs. Each later pass is done using a cost model
1899 * computed from the previous pass. */
1900 for (unsigned pass = 0; pass < num_passes; pass++) {
1902 lzx_lz_rewind_matchfinder(ctx, spec->window_pos);
1903 ctx->queue = orig_queue;
1904 spec->num_chosen_matches = 0;
1905 memset(&freqs, 0, sizeof(freqs));
1907 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
1908 struct raw_match raw_match;
1909 struct lzx_match lzx_match;
1911 raw_match = lzx_lz_get_near_optimal_match(ctx);
1912 if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1913 lzx_match.data = lzx_record_match(raw_match.offset, raw_match.len,
1914 &freqs, &ctx->queue);
1917 lzx_match.data = lzx_record_literal(ctx->window[i], &freqs);
1920 ctx->chosen_matches[spec->chosen_matches_start_pos +
1921 spec->num_chosen_matches++] = lzx_match;
1924 lzx_make_huffman_codes(&freqs, &spec->codes);
1925 if (pass < num_passes - 1)
1926 lzx_set_costs(ctx, &spec->codes.lens);
1928 spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1932 lzx_optimize_blocks(struct lzx_compressor *ctx)
1934 lzx_lru_queue_init(&ctx->queue);
1935 ctx->optimum_cur_idx = 0;
1936 ctx->optimum_end_idx = 0;
1938 const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
1940 for (unsigned i = 0; i < ctx->num_blocks; i++)
1941 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
1944 /* Initialize the suffix array match-finder for the specified input. */
1946 lzx_lz_init_matchfinder(const u8 T[const restrict],
1947 const input_idx_t n,
1948 input_idx_t SA[const restrict],
1949 input_idx_t ISA[const restrict],
1950 input_idx_t LCP[const restrict],
1951 struct salink link[const restrict],
1952 const unsigned max_match_len)
1954 /* Compute SA (Suffix Array). */
1958 /* ISA and link are used as temporary space. */
1959 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * sizeof(ISA[0]) < 256 * sizeof(saidx_t));
1960 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * 2 * sizeof(link[0]) < 256 * 256 * sizeof(saidx_t));
1961 divsufsort(T, sa, n, (saidx_t*)ISA, (saidx_t*)link);
1962 for (input_idx_t i = 0; i < n; i++)
1966 #ifdef ENABLE_LZX_DEBUG
1970 /* Verify suffix array. */
1974 for (input_idx_t r = 0; r < n; r++) {
1975 input_idx_t i = SA[r];
1977 LZX_ASSERT(!found[i]);
1982 for (input_idx_t r = 0; r < n - 1; r++) {
1984 input_idx_t i1 = SA[r];
1985 input_idx_t i2 = SA[r + 1];
1987 input_idx_t n1 = n - i1;
1988 input_idx_t n2 = n - i2;
1990 LZX_ASSERT(memcmp(&T[i1], &T[i2], min(n1, n2)) <= 0);
1992 LZX_DEBUG("Verified SA (len %u)", n);
1993 #endif /* ENABLE_LZX_DEBUG */
1995 /* Compute ISA (Inverse Suffix Array) */
1996 for (input_idx_t r = 0; r < n; r++)
1999 /* Compute LCP (longest common prefix) array.
2001 * Algorithm adapted from Kasai et al. 2001: "Linear-Time
2002 * Longest-Common-Prefix Computation in Suffix Arrays and Its
2006 for (input_idx_t i = 0; i < n; i++) {
2007 input_idx_t r = ISA[i];
2009 input_idx_t j = SA[r - 1];
2011 input_idx_t lim = min(n - i, n - j);
2013 while (h < lim && T[i + h] == T[j + h])
2022 #ifdef ENABLE_LZX_DEBUG
2023 /* Verify LCP array. */
2024 for (input_idx_t r = 0; r < n - 1; r++) {
2025 LZX_ASSERT(ISA[SA[r]] == r);
2026 LZX_ASSERT(ISA[SA[r + 1]] == r + 1);
2028 input_idx_t i1 = SA[r];
2029 input_idx_t i2 = SA[r + 1];
2030 input_idx_t lcp = LCP[r + 1];
2032 input_idx_t n1 = n - i1;
2033 input_idx_t n2 = n - i2;
2035 LZX_ASSERT(lcp <= min(n1, n2));
2037 LZX_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
2038 if (lcp < min(n1, n2))
2039 LZX_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
2041 #endif /* ENABLE_LZX_DEBUG */
2043 /* Compute salink.next and salink.lcpnext.
2045 * Algorithm adapted from Crochemore et al. 2009:
2046 * "LPF computation revisited".
2048 * Note: we cap lcpnext to the maximum match length so that the
2049 * match-finder need not worry about it later. */
2050 link[n - 1].next = (input_idx_t)~0U;
2051 link[n - 1].prev = (input_idx_t)~0U;
2052 link[n - 1].lcpnext = 0;
2053 link[n - 1].lcpprev = 0;
2054 for (input_idx_t r = n - 2; r != (input_idx_t)~0U; r--) {
2055 input_idx_t t = r + 1;
2056 input_idx_t l = LCP[t];
2057 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2058 l = min(l, link[t].lcpnext);
2062 link[r].lcpnext = min(l, max_match_len);
2063 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2064 LZX_ASSERT(l <= n - SA[r]);
2065 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2068 /* Compute salink.prev and salink.lcpprev.
2070 * Algorithm adapted from Crochemore et al. 2009:
2071 * "LPF computation revisited".
2073 * Note: we cap lcpprev to the maximum match length so that the
2074 * match-finder need not worry about it later. */
2075 link[0].prev = (input_idx_t)~0;
2076 link[0].next = (input_idx_t)~0;
2077 link[0].lcpprev = 0;
2078 link[0].lcpnext = 0;
2079 for (input_idx_t r = 1; r < n; r++) {
2080 input_idx_t t = r - 1;
2081 input_idx_t l = LCP[r];
2082 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2083 l = min(l, link[t].lcpprev);
2087 link[r].lcpprev = min(l, max_match_len);
2088 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2089 LZX_ASSERT(l <= n - SA[r]);
2090 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2094 /* Prepare the input window into one or more LZX blocks ready to be output. */
2096 lzx_prepare_blocks(struct lzx_compressor * ctx)
2098 /* Initialize the match-finder. */
2099 lzx_lz_init_matchfinder(ctx->window, ctx->window_size,
2100 ctx->SA, ctx->ISA, ctx->LCP, ctx->salink,
2102 ctx->cached_matches_pos = 0;
2103 ctx->matches_cached = false;
2104 ctx->match_window_pos = 0;
2106 /* Set up a default cost model. */
2107 lzx_set_default_costs(&ctx->costs);
2109 /* Initially assume that the entire input will be one LZX block. */
2110 ctx->block_specs[0].block_type = LZX_BLOCKTYPE_ALIGNED;
2111 ctx->block_specs[0].window_pos = 0;
2112 ctx->block_specs[0].block_size = ctx->window_size;
2113 ctx->num_blocks = 1;
2115 /* Perform near-optimal LZ parsing. */
2116 lzx_optimize_blocks(ctx);
2120 * This is the fast version of lzx_prepare_blocks(). This version "quickly"
2121 * prepares a single compressed block containing the entire input. See the
2122 * description of the "Fast algorithm" at the beginning of this file for more
2125 * Input --- the preprocessed data:
2133 * Output --- the block specification and the corresponding match/literal data:
2135 * ctx->block_specs[]
2137 * ctx->chosen_matches[]
2140 lzx_prepare_block_fast(struct lzx_compressor * ctx)
2142 unsigned num_matches;
2143 struct lzx_freqs freqs;
2144 struct lzx_block_spec *spec;
2146 /* Parameters to hash chain LZ match finder
2147 * (lazy with 1 match lookahead) */
2148 static const struct lz_params lzx_lz_params = {
2149 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
2150 * aren't worth choosing when using greedy or lazy parsing. */
2152 .max_match = LZX_MAX_MATCH_LEN,
2153 .good_match = LZX_MAX_MATCH_LEN,
2154 .nice_match = LZX_MAX_MATCH_LEN,
2155 .max_chain_len = LZX_MAX_MATCH_LEN,
2156 .max_lazy_match = LZX_MAX_MATCH_LEN,
2160 /* Initialize symbol frequencies and match offset LRU queue. */
2161 memset(&freqs, 0, sizeof(struct lzx_freqs));
2162 lzx_lru_queue_init(&ctx->queue);
2164 /* Determine series of matches/literals to output. */
2165 num_matches = lz_analyze_block(ctx->window,
2167 (u32*)ctx->chosen_matches,
2176 /* Set up block specification. */
2177 spec = &ctx->block_specs[0];
2178 spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2179 spec->window_pos = 0;
2180 spec->block_size = ctx->window_size;
2181 spec->num_chosen_matches = num_matches;
2182 spec->chosen_matches_start_pos = 0;
2183 lzx_make_huffman_codes(&freqs, &spec->codes);
2184 ctx->num_blocks = 1;
2188 do_call_insn_translation(u32 *call_insn_target, int input_pos,
2194 rel_offset = le32_to_cpu(*call_insn_target);
2195 if (rel_offset >= -input_pos && rel_offset < file_size) {
2196 if (rel_offset < file_size - input_pos) {
2197 /* "good translation" */
2198 abs_offset = rel_offset + input_pos;
2200 /* "compensating translation" */
2201 abs_offset = rel_offset - file_size;
2203 *call_insn_target = cpu_to_le32(abs_offset);
2207 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
2208 * See the comment above that function for more information. */
2210 do_call_insn_preprocessing(u8 data[], int size)
2212 for (int i = 0; i < size - 10; i++) {
2213 if (data[i] == 0xe8) {
2214 do_call_insn_translation((u32*)&data[i + 1], i,
2215 LZX_WIM_MAGIC_FILESIZE);
2221 /* API function documented in wimlib.h */
2223 wimlib_lzx_compress2(const void * const restrict uncompressed_data,
2224 unsigned const uncompressed_len,
2225 void * const restrict compressed_data,
2226 struct wimlib_lzx_context * const restrict lzx_ctx)
2228 struct lzx_compressor *ctx = (struct lzx_compressor*)lzx_ctx;
2229 struct output_bitstream ostream;
2230 unsigned compressed_len;
2232 if (uncompressed_len < 100) {
2233 LZX_DEBUG("Too small to bother compressing.");
2237 if (uncompressed_len > 32768) {
2238 LZX_DEBUG("Only up to 32768 bytes of uncompressed data are supported.");
2242 wimlib_assert(lzx_ctx != NULL);
2244 LZX_DEBUG("Attempting to compress %u bytes...", uncompressed_len);
2246 /* The input data must be preprocessed. To avoid changing the original
2247 * input, copy it to a temporary buffer. */
2248 memcpy(ctx->window, uncompressed_data, uncompressed_len);
2249 ctx->window_size = uncompressed_len;
2251 /* This line is unnecessary; it just avoids inconsequential accesses of
2252 * uninitialized memory that would show up in memory-checking tools such
2254 memset(&ctx->window[ctx->window_size], 0, 12);
2256 LZX_DEBUG("Preprocessing data...");
2258 /* Before doing any actual compression, do the call instruction (0xe8
2259 * byte) translation on the uncompressed data. */
2260 do_call_insn_preprocessing(ctx->window, ctx->window_size);
2262 LZX_DEBUG("Preparing blocks...");
2264 /* Prepare the compressed data. */
2265 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2266 lzx_prepare_block_fast(ctx);
2268 lzx_prepare_blocks(ctx);
2270 LZX_DEBUG("Writing compressed blocks...");
2272 /* Generate the compressed data. */
2273 init_output_bitstream(&ostream, compressed_data, ctx->window_size - 1);
2274 lzx_write_all_blocks(ctx, &ostream);
2276 LZX_DEBUG("Flushing bitstream...");
2277 if (flush_output_bitstream(&ostream)) {
2278 /* If the bitstream cannot be flushed, then the output space was
2280 LZX_DEBUG("Data did not compress to less than original length!");
2284 /* Compute the length of the compressed data. */
2285 compressed_len = ostream.bit_output - (u8*)compressed_data;
2287 LZX_DEBUG("Done: compressed %u => %u bytes.",
2288 uncompressed_len, compressed_len);
2290 /* Verify that we really get the same thing back when decompressing.
2291 * TODO: Disable this check by default on the slow algorithm. */
2292 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2293 #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2298 u8 buf[uncompressed_len];
2301 ret = wimlib_lzx_decompress(compressed_data, compressed_len,
2302 buf, uncompressed_len);
2304 ERROR("Failed to decompress data we "
2305 "compressed using LZX algorithm");
2310 if (memcmp(uncompressed_data, buf, uncompressed_len)) {
2311 ERROR("Data we compressed using LZX algorithm "
2312 "didn't decompress to original");
2317 return compressed_len;
2321 lzx_params_compatible(const struct wimlib_lzx_params *oldparams,
2322 const struct wimlib_lzx_params *newparams)
2324 return 0 == memcmp(oldparams, newparams, sizeof(struct wimlib_lzx_params));
2327 static struct wimlib_lzx_params lzx_user_default_params;
2328 static struct wimlib_lzx_params *lzx_user_default_params_ptr;
2331 lzx_params_valid(const struct wimlib_lzx_params *params)
2333 /* Validate parameters. */
2334 if (params->size_of_this != sizeof(struct wimlib_lzx_params)) {
2335 LZX_DEBUG("Invalid parameter structure size!");
2339 if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2340 params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2342 LZX_DEBUG("Invalid algorithm.");
2346 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2347 if (params->alg_params.slow.num_optim_passes < 1)
2349 LZX_DEBUG("Invalid number of optimization passes!");
2353 if (params->alg_params.slow.main_nostat_cost < 1 ||
2354 params->alg_params.slow.main_nostat_cost > 16)
2356 LZX_DEBUG("Invalid main_nostat_cost!");
2360 if (params->alg_params.slow.len_nostat_cost < 1 ||
2361 params->alg_params.slow.len_nostat_cost > 16)
2363 LZX_DEBUG("Invalid len_nostat_cost!");
2367 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2368 params->alg_params.slow.aligned_nostat_cost > 8)
2370 LZX_DEBUG("Invalid aligned_nostat_cost!");
2378 wimlib_lzx_set_default_params(const struct wimlib_lzx_params * params)
2381 if (!lzx_params_valid(params))
2382 return WIMLIB_ERR_INVALID_PARAM;
2383 lzx_user_default_params = *params;
2384 lzx_user_default_params_ptr = &lzx_user_default_params;
2386 lzx_user_default_params_ptr = NULL;
2391 /* API function documented in wimlib.h */
2393 wimlib_lzx_alloc_context(const struct wimlib_lzx_params *params,
2394 struct wimlib_lzx_context **ctx_pp)
2397 LZX_DEBUG("Allocating LZX context...");
2399 struct lzx_compressor *ctx;
2401 static const struct wimlib_lzx_params fast_default = {
2402 .size_of_this = sizeof(struct wimlib_lzx_params),
2403 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2410 static const struct wimlib_lzx_params slow_default = {
2411 .size_of_this = sizeof(struct wimlib_lzx_params),
2412 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2416 .use_len2_matches = 1,
2417 .num_fast_bytes = 32,
2418 .num_optim_passes = 2,
2419 .max_search_depth = 50,
2420 .max_matches_per_pos = 3,
2421 .main_nostat_cost = 15,
2422 .len_nostat_cost = 15,
2423 .aligned_nostat_cost = 7,
2429 if (!lzx_params_valid(params))
2430 return WIMLIB_ERR_INVALID_PARAM;
2432 LZX_DEBUG("Using default algorithm and parameters.");
2433 if (lzx_user_default_params_ptr)
2434 params = lzx_user_default_params_ptr;
2436 params = &slow_default;
2439 if (params->use_defaults) {
2440 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2441 params = &slow_default;
2443 params = &fast_default;
2447 ctx = *(struct lzx_compressor**)ctx_pp;
2449 if (ctx && lzx_params_compatible(&ctx->params, params))
2452 LZX_DEBUG("Check parameters only.");
2456 LZX_DEBUG("Allocating memory.");
2458 ctx = MALLOC(sizeof(struct lzx_compressor));
2462 size_t block_specs_length;
2465 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2466 block_specs_length = 1U << params->alg_params.slow.num_split_passes;
2469 block_specs_length = 1U;
2470 ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2471 if (ctx->block_specs == NULL)
2474 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2475 ctx->SA = MALLOC(3U * LZX_MAX_WINDOW_SIZE * sizeof(ctx->SA[0]));
2476 if (ctx->SA == NULL)
2477 goto err_free_block_specs;
2478 ctx->ISA = ctx->SA + LZX_MAX_WINDOW_SIZE;
2479 ctx->LCP = ctx->ISA + LZX_MAX_WINDOW_SIZE;
2480 ctx->salink = MALLOC(LZX_MAX_WINDOW_SIZE * sizeof(ctx->salink[0]));
2481 if (ctx->salink == NULL)
2490 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2491 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE + LZX_MAX_MATCH_LEN) *
2492 sizeof(ctx->optimum[0]));
2493 if (ctx->optimum == NULL)
2494 goto err_free_salink;
2496 ctx->optimum = NULL;
2499 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2500 uint32_t cache_per_pos;
2502 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
2503 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
2504 cache_per_pos = LZX_MAX_CACHE_PER_POS;
2506 ctx->cached_matches = MALLOC(LZX_MAX_WINDOW_SIZE * (cache_per_pos + 1) *
2507 sizeof(ctx->cached_matches[0]));
2508 if (ctx->cached_matches == NULL)
2509 goto err_free_optimum;
2511 ctx->cached_matches = NULL;
2514 ctx->chosen_matches = MALLOC(LZX_MAX_WINDOW_SIZE *
2515 sizeof(ctx->chosen_matches[0]));
2516 if (ctx->chosen_matches == NULL)
2517 goto err_free_cached_matches;
2519 memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_params));
2520 memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2522 LZX_DEBUG("Successfully allocated new LZX context.");
2524 wimlib_lzx_free_context(*ctx_pp);
2525 *ctx_pp = (struct wimlib_lzx_context*)ctx;
2528 err_free_cached_matches:
2529 FREE(ctx->cached_matches);
2536 err_free_block_specs:
2537 FREE(ctx->block_specs);
2541 LZX_DEBUG("Ran out of memory.");
2542 return WIMLIB_ERR_NOMEM;
2545 /* API function documented in wimlib.h */
2547 wimlib_lzx_free_context(struct wimlib_lzx_context *_ctx)
2549 struct lzx_compressor *ctx = (struct lzx_compressor*)_ctx;
2552 FREE(ctx->cached_matches);
2553 FREE(ctx->chosen_matches);
2557 FREE(ctx->block_specs);
2562 /* API function documented in wimlib.h */
2564 wimlib_lzx_compress(const void * const restrict uncompressed_data,
2565 unsigned const uncompressed_len,
2566 void * const restrict compressed_data)
2569 struct wimlib_lzx_context *ctx = NULL;
2570 unsigned compressed_len;
2572 ret = wimlib_lzx_alloc_context(NULL, &ctx);
2574 wimlib_assert(ret != WIMLIB_ERR_INVALID_PARAM);
2575 WARNING("Couldn't allocate LZX compression context: %"TS"",
2576 wimlib_get_error_string(ret));
2580 compressed_len = wimlib_lzx_compress2(uncompressed_data,
2585 wimlib_lzx_free_context(ctx);
2587 return compressed_len;