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 static struct raw_match
1627 lzx_lz_get_greedy_match(struct lzx_compressor * ctx)
1629 struct raw_match *matches;
1631 if (!lzx_lz_get_matches_caching(ctx, &ctx->queue, &matches))
1632 return (struct raw_match) {.len = 0};
1634 lzx_lz_skip_bytes(ctx, matches[0].len - 1);
1640 static struct raw_match
1641 lzx_lz_get_lazy_match(struct lzx_compressor * ctx)
1643 unsigned num_matches;
1644 struct raw_match *matches;
1645 struct raw_match prev_match;
1646 struct lzx_lru_queue queue;
1648 if (ctx->optimum_cur_idx != ctx->optimum_end_idx)
1651 /* Check for matches at first position. */
1652 num_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &matches);
1654 /* Return literal if no matches were found. */
1655 if (num_matches == 0)
1656 return (struct raw_match) { .len = 0 };
1658 /* Immediately choose match if longer than threshold. */
1659 if (matches[0].len > ctx->params.alg_params.slow.num_fast_bytes)
1662 ctx->optimum_cur_idx = ctx->optimum_end_idx = 0;
1664 prev_match = matches[0];
1666 /* Check for matches at next position. */
1667 num_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &matches);
1669 /* Choose previous match if there is not a match at this
1671 if (num_matches == 0)
1674 /* Choose previous match the longest match at the next position
1675 * is the same place, just one character shifted over. */
1676 if (matches[0].offset == prev_match.offset ||
1677 matches[0].len < prev_match.len)
1680 struct lzx_lru_queue q1 = ctx->queue, q2 = ctx->queue;
1681 double lazycost = lzx_literal_cost(ctx->window[ctx->match_window_pos - 2],
1683 lzx_match_cost(matches[0].len, matches[0].offset,
1685 double greedycost = lzx_match_cost(prev_match.len, prev_match.offset,
1687 lazycost *= (double)prev_match.len / (1 + matches[0].len);
1689 /* Choose previous match if greedy cost was lower. */
1690 if (greedycost <= lazycost)
1693 /* Choose literal at the previous position. */
1694 ctx->optimum[ctx->optimum_end_idx++].next.link = 0;
1697 /* Immediately choose match if longer than threshold. */
1698 if (matches[0].len > ctx->params.alg_params.slow.num_fast_bytes)
1703 lzx_lz_skip_bytes(ctx, 1);
1704 prev_match = matches[0];
1707 lzx_lz_skip_bytes(ctx, prev_match.len - 2);
1708 ctx->optimum[ctx->optimum_end_idx].next.link = prev_match.len;
1709 ctx->optimum[ctx->optimum_end_idx].next.match_offset = prev_match.offset;
1710 ctx->optimum_end_idx++;
1712 prev_match.len = ctx->optimum[ctx->optimum_cur_idx].next.link;
1713 prev_match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1714 ctx->optimum_cur_idx++;
1721 * lzx_lz_get_near_optimal_match() -
1723 * Choose the optimal match or literal to use at the next position in the input.
1725 * Unlike a greedy parser that always takes the longest match, or even a
1726 * parser with one match/literal look-ahead like zlib, the algorithm used here
1727 * may look ahead many matches/literals to determine the optimal match/literal to
1728 * output next. The motivation is that the compression ratio is improved if the
1729 * compressor can do things like use a shorter-than-possible match in order to
1730 * allow a longer match later, and also take into account the Huffman code cost
1731 * model rather than simply assuming that longer is better.
1733 * Still, this is not truly an optimal parser because very long matches are
1734 * taken immediately. This is done to avoid considering many different
1735 * alternatives that are unlikely to significantly be better.
1737 * This algorithm is based on that used in 7-Zip's DEFLATE encoder.
1739 * Each call to this function does one of two things:
1741 * 1. Build a near-optimal sequence of matches/literals, up to some point, that
1742 * will be returned by subsequent calls to this function, then return the
1747 * 2. Return the next match/literal previously computed by a call to this
1750 * This function relies on the following state in the compressor context:
1752 * ctx->window (read-only: preprocessed data being compressed)
1753 * ctx->cost (read-only: cost model to use)
1754 * ctx->optimum (internal state; leave uninitialized)
1755 * ctx->optimum_cur_idx (must set to 0 before first call)
1756 * ctx->optimum_end_idx (must set to 0 before first call)
1757 * ctx->SA (must be built before first call)
1758 * ctx->ISA (must be built before first call)
1759 * ctx->salink (must be built before first call)
1760 * ctx->match_window_pos (must initialize to position of next match to
1761 * return; subsequent calls return subsequent
1763 * ctx->match_window_end (must initialize to limit of match-finding region;
1764 * subsequent calls use the same limit)
1766 * The return value is a (length, offset) pair specifying the match or literal
1767 * chosen. For literals, the length is less than LZX_MIN_MATCH_LEN and the
1768 * offset is meaningless.
1770 static struct raw_match
1771 lzx_lz_get_near_optimal_match(struct lzx_compressor * ctx)
1773 unsigned num_possible_matches;
1774 struct raw_match *possible_matches;
1775 struct raw_match match;
1776 unsigned longest_match_len;
1778 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1779 /* Case 2: Return the next match/literal already found. */
1780 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1781 ctx->optimum_cur_idx;
1782 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1784 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1788 /* Case 1: Compute a new list of matches/literals to return. */
1790 ctx->optimum_cur_idx = 0;
1791 ctx->optimum_end_idx = 0;
1793 /* Get matches at this position. */
1794 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &possible_matches);
1796 /* If no matches found, return literal. */
1797 if (num_possible_matches == 0)
1798 return (struct raw_match){ .len = 0 };
1800 /* The matches that were found are sorted in decreasing order by length.
1801 * Get the length of the longest one. */
1802 longest_match_len = possible_matches[0].len;
1804 /* Greedy heuristic: if the longest match that was found is greater
1805 * than the number of fast bytes, return it immediately; don't both
1806 * doing more work. */
1807 if (longest_match_len > ctx->params.alg_params.slow.num_fast_bytes) {
1808 lzx_lz_skip_bytes(ctx, longest_match_len - 1);
1809 return possible_matches[0];
1812 /* Calculate the cost to reach the next position by outputting a
1814 ctx->optimum[0].queue = ctx->queue;
1815 ctx->optimum[1].queue = ctx->optimum[0].queue;
1816 ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos],
1818 ctx->optimum[1].prev.link = 0;
1820 /* Calculate the cost to reach any position up to and including that
1821 * reached by the longest match, using the shortest (i.e. closest) match
1822 * that reaches each position. */
1823 BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1824 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1825 len <= longest_match_len; len++) {
1827 LZX_ASSERT(match_idx < num_possible_matches);
1829 ctx->optimum[len].queue = ctx->optimum[0].queue;
1830 ctx->optimum[len].prev.link = 0;
1831 ctx->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
1832 ctx->optimum[len].cost = lzx_match_cost(len,
1833 possible_matches[match_idx].offset,
1835 &ctx->optimum[len].queue);
1836 if (len == possible_matches[match_idx].len)
1840 unsigned cur_pos = 0;
1842 /* len_end: greatest index forward at which costs have been calculated
1844 unsigned len_end = longest_match_len;
1847 /* Advance to next position. */
1850 if (cur_pos == len_end || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1851 return lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1853 /* retrieve the number of matches available at this position */
1854 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->optimum[cur_pos].queue,
1857 unsigned new_len = 0;
1859 if (num_possible_matches != 0) {
1860 new_len = possible_matches[0].len;
1862 /* Greedy heuristic: if we found a match greater than
1863 * the number of fast bytes, stop immediately. */
1864 if (new_len > ctx->params.alg_params.slow.num_fast_bytes) {
1866 /* Build the list of matches to return and get
1868 match = lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1870 /* Append the long match to the end of the list. */
1871 ctx->optimum[cur_pos].next.match_offset =
1872 possible_matches[0].offset;
1873 ctx->optimum[cur_pos].next.link = cur_pos + new_len;
1874 ctx->optimum_end_idx = cur_pos + new_len;
1876 /* Skip over the remaining bytes of the long match. */
1877 lzx_lz_skip_bytes(ctx, new_len - 1);
1879 /* Return first match in the list */
1884 /* Consider proceeding with a literal byte. */
1885 block_cost_t cur_cost = ctx->optimum[cur_pos].cost;
1886 block_cost_t cur_plus_literal_cost = cur_cost +
1887 lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1889 if (cur_plus_literal_cost < ctx->optimum[cur_pos + 1].cost) {
1890 ctx->optimum[cur_pos + 1].cost = cur_plus_literal_cost;
1891 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1892 ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1895 if (num_possible_matches == 0)
1898 /* Consider proceeding with a match. */
1900 while (len_end < cur_pos + new_len)
1901 ctx->optimum[++len_end].cost = INFINITE_BLOCK_COST;
1903 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1904 len <= new_len; len++) {
1905 LZX_ASSERT(match_idx < num_possible_matches);
1906 struct lzx_lru_queue q = ctx->optimum[cur_pos].queue;
1907 block_cost_t cost = cur_cost + lzx_match_cost(len,
1908 possible_matches[match_idx].offset,
1912 if (cost < ctx->optimum[cur_pos + len].cost) {
1913 ctx->optimum[cur_pos + len].cost = cost;
1914 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1915 ctx->optimum[cur_pos + len].prev.match_offset =
1916 possible_matches[match_idx].offset;
1917 ctx->optimum[cur_pos + len].queue = q;
1920 if (len == possible_matches[match_idx].len)
1927 * Set default symbol costs.
1930 lzx_set_default_costs(struct lzx_costs * costs)
1934 /* Literal symbols */
1935 for (i = 0; i < LZX_NUM_CHARS; i++)
1938 /* Match header symbols */
1939 for (; i < LZX_MAINCODE_NUM_SYMBOLS; i++)
1940 costs->main[i] = 10;
1942 /* Length symbols */
1943 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1946 /* Aligned offset symbols */
1947 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1948 costs->aligned[i] = 3;
1951 /* Given the frequencies of symbols in a compressed block and the corresponding
1952 * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1953 * aligned offset or verbatim block, respectively, will take fewer bits to
1956 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1957 const struct lzx_codes * codes)
1959 unsigned aligned_cost = 0;
1960 unsigned verbatim_cost = 0;
1962 /* Verbatim blocks have a constant 3 bits per position footer. Aligned
1963 * offset blocks have an aligned offset symbol per position footer, plus
1964 * an extra 24 bits to output the lengths necessary to reconstruct the
1965 * aligned offset code itself. */
1966 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1967 verbatim_cost += 3 * freqs->aligned[i];
1968 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1970 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1971 if (aligned_cost < verbatim_cost)
1972 return LZX_BLOCKTYPE_ALIGNED;
1974 return LZX_BLOCKTYPE_VERBATIM;
1977 /* Find a near-optimal sequence of matches/literals with which to output the
1978 * specified LZX block, and set its type to that which has the minimum cost to
1981 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1982 unsigned num_passes)
1984 struct lzx_lru_queue orig_queue = ctx->queue;
1985 struct lzx_freqs freqs;
1987 ctx->match_window_end = spec->window_pos + spec->block_size;
1988 spec->chosen_matches_start_pos = spec->window_pos;
1990 LZX_ASSERT(num_passes >= 1);
1992 /* The first optimal parsing pass is done using the cost model already
1993 * set in ctx->costs. Each later pass is done using a cost model
1994 * computed from the previous pass. */
1995 for (unsigned pass = 0; pass < num_passes; pass++) {
1997 lzx_lz_rewind_matchfinder(ctx, spec->window_pos);
1998 ctx->queue = orig_queue;
1999 spec->num_chosen_matches = 0;
2000 memset(&freqs, 0, sizeof(freqs));
2002 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
2003 struct raw_match raw_match;
2004 struct lzx_match lzx_match;
2006 raw_match = lzx_lz_get_near_optimal_match(ctx);
2007 if (raw_match.len >= LZX_MIN_MATCH_LEN) {
2008 lzx_match.data = lzx_record_match(raw_match.offset, raw_match.len,
2009 &freqs, &ctx->queue);
2012 lzx_match.data = lzx_record_literal(ctx->window[i], &freqs);
2015 ctx->chosen_matches[spec->chosen_matches_start_pos +
2016 spec->num_chosen_matches++] = lzx_match;
2019 lzx_make_huffman_codes(&freqs, &spec->codes);
2020 if (pass < num_passes - 1)
2021 lzx_set_costs(ctx, &spec->codes.lens);
2023 spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
2027 lzx_optimize_blocks(struct lzx_compressor *ctx)
2029 lzx_lru_queue_init(&ctx->queue);
2030 ctx->optimum_cur_idx = 0;
2031 ctx->optimum_end_idx = 0;
2033 const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
2035 for (unsigned i = 0; i < ctx->num_blocks; i++)
2036 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
2039 static bool entropy_val_tab_inited = false;
2040 static double entropy_val_tab[LZX_MAX_WINDOW_SIZE];
2041 static pthread_mutex_t entropy_val_tab_mutex = PTHREAD_MUTEX_INITIALIZER;
2043 static double entropy_val(unsigned count)
2045 /*return count * log(count);*/
2046 return entropy_val_tab[count];
2049 /* Split a LZX block into several if it is advantageous to do so.
2051 * TODO: This doesn't work very well yet. Should optimal parsing be done
2052 * before or after splitting? */
2054 lzx_block_split(const u32 matches[restrict],
2055 const input_idx_t n,
2056 const double epsilon,
2057 const unsigned max_num_blocks,
2058 const unsigned min_block_len,
2059 struct lzx_block_spec block_specs[restrict],
2060 unsigned * const restrict num_blocks_ret)
2062 const double block_overhead = 1500;
2064 if (!entropy_val_tab_inited) {
2065 pthread_mutex_lock(&entropy_val_tab_mutex);
2066 if (!entropy_val_tab_inited) {
2067 entropy_val_tab[0] = 0;
2068 for (input_idx_t i = 1; i < LZX_MAX_WINDOW_SIZE; i++)
2069 entropy_val_tab[i] = i * log2(i);
2070 entropy_val_tab_inited = true;
2072 pthread_mutex_unlock(&entropy_val_tab_mutex);
2078 input_idx_t orig_input_indices[n + 1];
2080 LZX_ASSERT(epsilon >= 0);
2081 LZX_ASSERT(max_num_blocks >= 1);
2083 /* For convenience, extract the main, length, and aligned symbols from
2084 * the matches. Every position will have a main symbol, but not every
2085 * position will have a length and aligned symbol. Special values
2086 * larger than the valid symbols are used to indicate the absense of a
2088 orig_input_indices[0] = 0;
2089 for (input_idx_t i = 0, orig_input_idx = 0; i < n; i++) {
2090 u32 match = matches[i];
2092 u8 len_sym = LZX_LENCODE_NUM_SYMBOLS;
2093 u8 aligned_sym = LZX_ALIGNEDCODE_NUM_SYMBOLS;
2094 if (match & 0x80000000) {
2095 unsigned match_len_minus_2 = match & 0xff;
2096 unsigned position_footer = (match >> 8) & 0x1ffff;
2097 unsigned position_slot = (match >> 25) & 0x3f;
2098 unsigned len_header;
2100 if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
2101 len_header = match_len_minus_2;
2103 len_header = LZX_NUM_PRIMARY_LENS;
2104 len_sym = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
2106 main_sym = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
2107 if (position_slot >= 8)
2108 aligned_sym = position_footer & 7;
2109 orig_input_idx += match_len_minus_2 + 2;
2114 main_syms[i] = main_sym;
2115 len_syms[i] = len_sym;
2116 aligned_syms[i] = aligned_sym;
2117 orig_input_indices[i + 1] = orig_input_idx;
2120 /* Compute the number of sliding windows that will be used for the
2121 * entropy calculations. */
2122 int num_windows = 0;
2123 unsigned window_len;
2125 double e = min_block_len;
2130 } while (window_len < n);
2133 /* Compute the length of each sliding window. */
2134 unsigned window_lens[num_windows];
2136 double e = min_block_len;
2137 unsigned window_idx = 0;
2140 window_lens[window_idx++] = min(window_len, n);
2142 } while (window_len < n);
2145 /* Best estimated compression size, in bits, found so far for the input
2146 * matches up to each position. */
2147 unsigned shortest_paths[n + 1];
2149 /* Pointers to follow to get the sequence of blocks that represents the
2150 * shortest path (in terms of estimated compressed size) up to each
2151 * position in the input matches. */
2152 input_idx_t back_ptrs[n + 1];
2154 for (input_idx_t i = 0; i < n + 1; i++) {
2155 shortest_paths[i] = ~0U;
2158 shortest_paths[0] = 0;
2161 /* Initialize the per-window symbol and entropy counters */
2162 input_idx_t mainsym_ctrs[num_windows][LZX_MAINCODE_NUM_SYMBOLS];
2163 input_idx_t lensym_ctrs[num_windows][LZX_LENCODE_NUM_SYMBOLS + 1];
2164 input_idx_t alignedsym_ctrs[num_windows][LZX_ALIGNEDCODE_NUM_SYMBOLS + 1];
2165 ZERO_ARRAY(mainsym_ctrs);
2166 ZERO_ARRAY(lensym_ctrs);
2167 ZERO_ARRAY(alignedsym_ctrs);
2170 int start_win_idx = 0;
2171 for (input_idx_t i = 0; i < n; i++) {
2172 while (i >= window_lens[start_win_idx])
2174 for (int j = start_win_idx; j < num_windows; j++) {
2175 mainsym_ctrs[j][main_syms[i]]++;
2176 lensym_ctrs[j][len_syms[i]]++;
2177 alignedsym_ctrs[j][aligned_syms[i]]++;
2182 double entropy_ctrs[num_windows];
2183 for (int i = 0; i < num_windows; i++) {
2184 entropy_ctrs[i] = 0;
2185 for (unsigned j = 0; j < LZX_MAINCODE_NUM_SYMBOLS; j++)
2186 entropy_ctrs[i] += entropy_val(mainsym_ctrs[i][j]);
2187 for (unsigned j = 0; j < LZX_LENCODE_NUM_SYMBOLS; j++)
2188 entropy_ctrs[i] += entropy_val(lensym_ctrs[i][j]);
2189 for (unsigned j = 0; j < LZX_ALIGNEDCODE_NUM_SYMBOLS; j++)
2190 entropy_ctrs[i] += entropy_val(alignedsym_ctrs[i][j]);
2193 /* Slide the windows along the input and compute the shortest
2194 * path to each position in the matches. */
2195 int end_window_idx = (int)num_windows - 1;
2196 for (input_idx_t i = 0; i < n; i++) {
2197 for (int j = 0; j <= end_window_idx; j++) {
2198 if (shortest_paths[i] == ~0U)
2200 unsigned num_mainsyms = window_lens[j];
2201 unsigned num_lensyms = window_lens[j] -
2202 lensym_ctrs[j][LZX_LENCODE_NUM_SYMBOLS];
2203 unsigned num_alignedsyms = window_lens[j] -
2204 alignedsym_ctrs[j][LZX_ALIGNEDCODE_NUM_SYMBOLS];
2205 unsigned entropy = entropy_val(num_mainsyms) +
2206 entropy_val(num_lensyms) +
2207 entropy_val(num_alignedsyms) -
2209 unsigned est_csize = entropy + block_overhead;
2211 unsigned end_idx = i + window_lens[j];
2212 if (est_csize + shortest_paths[i] < shortest_paths[end_idx]) {
2213 shortest_paths[end_idx] = est_csize + shortest_paths[i];
2214 back_ptrs[end_idx] = i;
2217 /* Remove left symbol from windows */
2218 for (int j = 0; j <= end_window_idx; j++) {
2219 input_idx_t orig_maincnt = mainsym_ctrs[j][main_syms[i]]--;
2220 entropy_ctrs[j] -= entropy_val(orig_maincnt);
2221 entropy_ctrs[j] += entropy_val(orig_maincnt - 1);
2223 input_idx_t orig_lencnt =
2224 lensym_ctrs[j][len_syms[i]]--;
2225 if (len_syms[i] != LZX_LENCODE_NUM_SYMBOLS) {
2226 entropy_ctrs[j] -= entropy_val(orig_lencnt);
2227 entropy_ctrs[j] += entropy_val(orig_lencnt - 1);
2230 input_idx_t orig_alignedcnt =
2231 alignedsym_ctrs[j][aligned_syms[i]]--;
2232 if (aligned_syms[i] != LZX_ALIGNEDCODE_NUM_SYMBOLS) {
2233 entropy_ctrs[j] -= entropy_val(orig_alignedcnt);
2234 entropy_ctrs[j] += entropy_val(orig_alignedcnt - 1);
2238 /* Calculate index of longest window remaining */
2239 while (end_window_idx >= 0 && window_lens[end_window_idx] >= n - i)
2242 /* Append right symbol to windows */
2243 for (int j = 0; j <= end_window_idx; j++) {
2244 input_idx_t orig_maincnt = mainsym_ctrs[j][
2245 main_syms[i + window_lens[j]]]++;
2246 entropy_ctrs[j] -= entropy_val(orig_maincnt);
2247 entropy_ctrs[j] += entropy_val(orig_maincnt + 1);
2249 input_idx_t orig_lencnt =
2250 lensym_ctrs[j][len_syms[i + window_lens[j]]]++;
2251 if (len_syms[i + window_lens[j]] != LZX_LENCODE_NUM_SYMBOLS) {
2252 entropy_ctrs[j] -= entropy_val(orig_lencnt);
2253 entropy_ctrs[j] += entropy_val(orig_lencnt + 1);
2256 input_idx_t orig_alignedcnt =
2257 alignedsym_ctrs[j][aligned_syms[i + window_lens[j]]]++;
2258 if (aligned_syms[i + window_lens[j]] != LZX_ALIGNEDCODE_NUM_SYMBOLS) {
2259 entropy_ctrs[j] -= entropy_val(orig_alignedcnt);
2260 entropy_ctrs[j] += entropy_val(orig_alignedcnt + 1);
2267 /* If no cost was computed for the first block (due to it being shorter
2268 * than all the windows), merge it with the second block. */
2269 for (input_idx_t i = n; i != 0; i = back_ptrs[i])
2270 if (back_ptrs[i] != 0 && shortest_paths[back_ptrs[i]] == ~0U)
2274 /* Calculate number of blocks */
2275 input_idx_t num_blocks = 0;
2276 for (input_idx_t i = n; i != 0; i = back_ptrs[i])
2279 while (num_blocks > max_num_blocks) {
2280 LZX_DEBUG("Joining blocks to bring total under max_num_blucks=%u",
2282 back_ptrs[n] = back_ptrs[back_ptrs[n]];
2286 LZX_ASSERT(num_blocks != 0);
2288 /* fill in the 'struct lzx_block_spec' for each block */
2289 for (input_idx_t i = n, j = num_blocks - 1; i != 0; i = back_ptrs[i], j--) {
2291 block_specs[j].chosen_matches_start_pos = back_ptrs[i];
2292 block_specs[j].num_chosen_matches = i - back_ptrs[i];
2293 block_specs[j].window_pos = orig_input_indices[back_ptrs[i]];
2294 block_specs[j].block_size = orig_input_indices[i] -
2295 orig_input_indices[back_ptrs[i]];
2296 /*block_specs[j].est_csize = (shortest_paths[i] -*/
2297 /*shortest_paths[back_ptrs[i]]) / 8;*/
2299 LZX_DEBUG("block match_indices [%u, %u) est_csize %u bits\n",
2301 shortest_paths[i] - shortest_paths[back_ptrs[i]]);
2303 struct lzx_freqs freqs = {};
2305 for (input_idx_t k = back_ptrs[i]; k < i; k++) {
2306 freqs.main[main_syms[k]]++;
2307 if (len_syms[k] != LZX_LENCODE_NUM_SYMBOLS)
2308 freqs.len[len_syms[k]]++;
2309 if (aligned_syms[k] != LZX_LENCODE_NUM_SYMBOLS)
2310 freqs.aligned[aligned_syms[k]]++;
2312 lzx_make_huffman_codes(&freqs, &block_specs[j].codes);
2314 block_specs[j].block_type = lzx_choose_verbatim_or_aligned(&freqs,
2315 &block_specs[j].codes);
2317 *num_blocks_ret = num_blocks;
2321 /* Initialize the suffix array match-finder for the specified input. */
2323 lzx_lz_init_matchfinder(const u8 T[const restrict],
2324 const input_idx_t n,
2325 input_idx_t SA[const restrict],
2326 input_idx_t ISA[const restrict],
2327 input_idx_t LCP[const restrict],
2328 struct salink link[const restrict],
2329 const unsigned max_match_len)
2331 /* Compute SA (Suffix Array). */
2335 /* ISA and link are used as temporary space. */
2336 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * sizeof(ISA[0]) < 256 * sizeof(saidx_t));
2337 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * 2 * sizeof(link[0]) < 256 * 256 * sizeof(saidx_t));
2338 divsufsort(T, sa, n, (saidx_t*)ISA, (saidx_t*)link);
2339 for (input_idx_t i = 0; i < n; i++)
2343 #ifdef ENABLE_LZX_DEBUG
2347 /* Verify suffix array. */
2351 for (input_idx_t r = 0; r < n; r++) {
2352 input_idx_t i = SA[r];
2354 LZX_ASSERT(!found[i]);
2359 for (input_idx_t r = 0; r < n - 1; r++) {
2361 input_idx_t i1 = SA[r];
2362 input_idx_t i2 = SA[r + 1];
2364 input_idx_t n1 = n - i1;
2365 input_idx_t n2 = n - i2;
2367 LZX_ASSERT(memcmp(&T[i1], &T[i2], min(n1, n2)) <= 0);
2369 LZX_DEBUG("Verified SA (len %u)", n);
2370 #endif /* ENABLE_LZX_DEBUG */
2372 /* Compute ISA (Inverse Suffix Array) */
2373 for (input_idx_t r = 0; r < n; r++)
2376 /* Compute LCP (longest common prefix) array.
2378 * Algorithm adapted from Kasai et al. 2001: "Linear-Time
2379 * Longest-Common-Prefix Computation in Suffix Arrays and Its
2383 for (input_idx_t i = 0; i < n; i++) {
2384 input_idx_t r = ISA[i];
2386 input_idx_t j = SA[r - 1];
2388 input_idx_t lim = min(n - i, n - j);
2390 while (h < lim && T[i + h] == T[j + h])
2399 #ifdef ENABLE_LZX_DEBUG
2400 /* Verify LCP array. */
2401 for (input_idx_t r = 0; r < n - 1; r++) {
2402 LZX_ASSERT(ISA[SA[r]] == r);
2403 LZX_ASSERT(ISA[SA[r + 1]] == r + 1);
2405 input_idx_t i1 = SA[r];
2406 input_idx_t i2 = SA[r + 1];
2407 input_idx_t lcp = LCP[r + 1];
2409 input_idx_t n1 = n - i1;
2410 input_idx_t n2 = n - i2;
2412 LZX_ASSERT(lcp <= min(n1, n2));
2414 LZX_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
2415 if (lcp < min(n1, n2))
2416 LZX_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
2418 #endif /* ENABLE_LZX_DEBUG */
2420 /* Compute salink.next and salink.lcpnext.
2422 * Algorithm adapted from Crochemore et al. 2009:
2423 * "LPF computation revisited".
2425 * Note: we cap lcpnext to the maximum match length so that the
2426 * match-finder need not worry about it later. */
2427 link[n - 1].next = (input_idx_t)~0U;
2428 link[n - 1].prev = (input_idx_t)~0U;
2429 link[n - 1].lcpnext = 0;
2430 link[n - 1].lcpprev = 0;
2431 for (input_idx_t r = n - 2; r != (input_idx_t)~0U; r--) {
2432 input_idx_t t = r + 1;
2433 input_idx_t l = LCP[t];
2434 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2435 l = min(l, link[t].lcpnext);
2439 link[r].lcpnext = min(l, max_match_len);
2440 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2441 LZX_ASSERT(l <= n - SA[r]);
2442 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2445 /* Compute salink.prev and salink.lcpprev.
2447 * Algorithm adapted from Crochemore et al. 2009:
2448 * "LPF computation revisited".
2450 * Note: we cap lcpprev to the maximum match length so that the
2451 * match-finder need not worry about it later. */
2452 link[0].prev = (input_idx_t)~0;
2453 link[0].next = (input_idx_t)~0;
2454 link[0].lcpprev = 0;
2455 link[0].lcpnext = 0;
2456 for (input_idx_t r = 1; r < n; r++) {
2457 input_idx_t t = r - 1;
2458 input_idx_t l = LCP[r];
2459 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2460 l = min(l, link[t].lcpprev);
2464 link[r].lcpprev = min(l, max_match_len);
2465 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2466 LZX_ASSERT(l <= n - SA[r]);
2467 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2471 /* Prepare the input window into one or more LZX blocks ready to be output. */
2473 lzx_prepare_blocks(struct lzx_compressor * ctx)
2475 /* Initialize the match-finder. */
2476 lzx_lz_init_matchfinder(ctx->window, ctx->window_size,
2477 ctx->SA, ctx->ISA, ctx->LCP, ctx->salink,
2479 ctx->cached_matches_pos = 0;
2480 ctx->matches_cached = false;
2481 ctx->match_window_pos = 0;
2483 /* Set up a default cost model. */
2484 lzx_set_default_costs(&ctx->costs);
2486 /* Initially assume that the entire input will be one LZX block. */
2487 ctx->block_specs[0].block_type = LZX_BLOCKTYPE_ALIGNED;
2488 ctx->block_specs[0].window_pos = 0;
2489 ctx->block_specs[0].block_size = ctx->window_size;
2490 ctx->num_blocks = 1;
2492 /* Perform near-optimal LZ parsing. */
2493 lzx_optimize_blocks(ctx);
2495 /* Possibly divide up the LZX block. */
2496 const unsigned max_num_blocks = 1U << ctx->params.alg_params.slow.num_split_passes;
2497 if (max_num_blocks > 1) {
2498 const double epsilon = 0.2;
2499 const unsigned min_block_len = 500;
2501 lzx_block_split((const u32*)ctx->chosen_matches,
2502 ctx->block_specs[0].num_chosen_matches,
2503 epsilon, max_num_blocks, min_block_len,
2504 ctx->block_specs, &ctx->num_blocks);
2509 * This is the fast version of lzx_prepare_blocks(). This version "quickly"
2510 * prepares a single compressed block containing the entire input. See the
2511 * description of the "Fast algorithm" at the beginning of this file for more
2514 * Input --- the preprocessed data:
2522 * Output --- the block specification and the corresponding match/literal data:
2524 * ctx->block_specs[]
2526 * ctx->chosen_matches[]
2529 lzx_prepare_block_fast(struct lzx_compressor * ctx)
2531 unsigned num_matches;
2532 struct lzx_freqs freqs;
2533 struct lzx_block_spec *spec;
2535 /* Parameters to hash chain LZ match finder
2536 * (lazy with 1 match lookahead) */
2537 static const struct lz_params lzx_lz_params = {
2538 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
2539 * aren't worth choosing when using greedy or lazy parsing. */
2541 .max_match = LZX_MAX_MATCH_LEN,
2542 .good_match = LZX_MAX_MATCH_LEN,
2543 .nice_match = LZX_MAX_MATCH_LEN,
2544 .max_chain_len = LZX_MAX_MATCH_LEN,
2545 .max_lazy_match = LZX_MAX_MATCH_LEN,
2549 /* Initialize symbol frequencies and match offset LRU queue. */
2550 memset(&freqs, 0, sizeof(struct lzx_freqs));
2551 lzx_lru_queue_init(&ctx->queue);
2553 /* Determine series of matches/literals to output. */
2554 num_matches = lz_analyze_block(ctx->window,
2556 (u32*)ctx->chosen_matches,
2565 /* Set up block specification. */
2566 spec = &ctx->block_specs[0];
2567 spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2568 spec->window_pos = 0;
2569 spec->block_size = ctx->window_size;
2570 spec->num_chosen_matches = num_matches;
2571 spec->chosen_matches_start_pos = 0;
2572 lzx_make_huffman_codes(&freqs, &spec->codes);
2573 ctx->num_blocks = 1;
2577 do_call_insn_translation(u32 *call_insn_target, int input_pos,
2583 rel_offset = le32_to_cpu(*call_insn_target);
2584 if (rel_offset >= -input_pos && rel_offset < file_size) {
2585 if (rel_offset < file_size - input_pos) {
2586 /* "good translation" */
2587 abs_offset = rel_offset + input_pos;
2589 /* "compensating translation" */
2590 abs_offset = rel_offset - file_size;
2592 *call_insn_target = cpu_to_le32(abs_offset);
2596 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
2597 * See the comment above that function for more information. */
2599 do_call_insn_preprocessing(u8 data[], int size)
2601 for (int i = 0; i < size - 10; i++) {
2602 if (data[i] == 0xe8) {
2603 do_call_insn_translation((u32*)&data[i + 1], i,
2604 LZX_WIM_MAGIC_FILESIZE);
2610 /* API function documented in wimlib.h */
2612 wimlib_lzx_compress2(const void * const restrict uncompressed_data,
2613 unsigned const uncompressed_len,
2614 void * const restrict compressed_data,
2615 struct wimlib_lzx_context * const restrict lzx_ctx)
2617 struct lzx_compressor *ctx = (struct lzx_compressor*)lzx_ctx;
2618 struct output_bitstream ostream;
2619 unsigned compressed_len;
2621 if (uncompressed_len < 100) {
2622 LZX_DEBUG("Too small to bother compressing.");
2626 if (uncompressed_len > 32768) {
2627 LZX_DEBUG("Only up to 32768 bytes of uncompressed data are supported.");
2631 wimlib_assert(lzx_ctx != NULL);
2633 LZX_DEBUG("Attempting to compress %u bytes...", uncompressed_len);
2635 /* The input data must be preprocessed. To avoid changing the original
2636 * input, copy it to a temporary buffer. */
2637 memcpy(ctx->window, uncompressed_data, uncompressed_len);
2638 ctx->window_size = uncompressed_len;
2640 /* This line is unnecessary; it just avoids inconsequential accesses of
2641 * uninitialized memory that would show up in memory-checking tools such
2643 memset(&ctx->window[ctx->window_size], 0, 12);
2645 LZX_DEBUG("Preprocessing data...");
2647 /* Before doing any actual compression, do the call instruction (0xe8
2648 * byte) translation on the uncompressed data. */
2649 do_call_insn_preprocessing(ctx->window, ctx->window_size);
2651 LZX_DEBUG("Preparing blocks...");
2653 /* Prepare the compressed data. */
2654 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2655 lzx_prepare_block_fast(ctx);
2657 lzx_prepare_blocks(ctx);
2659 LZX_DEBUG("Writing compressed blocks...");
2661 /* Generate the compressed data. */
2662 init_output_bitstream(&ostream, compressed_data, ctx->window_size - 1);
2663 lzx_write_all_blocks(ctx, &ostream);
2665 LZX_DEBUG("Flushing bitstream...");
2666 if (flush_output_bitstream(&ostream)) {
2667 /* If the bitstream cannot be flushed, then the output space was
2669 LZX_DEBUG("Data did not compress to less than original length!");
2673 /* Compute the length of the compressed data. */
2674 compressed_len = ostream.bit_output - (u8*)compressed_data;
2676 LZX_DEBUG("Done: compressed %u => %u bytes.",
2677 uncompressed_len, compressed_len);
2679 /* Verify that we really get the same thing back when decompressing.
2680 * TODO: Disable this check by default on the slow algorithm. */
2681 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2682 #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2687 u8 buf[uncompressed_len];
2690 ret = wimlib_lzx_decompress(compressed_data, compressed_len,
2691 buf, uncompressed_len);
2693 ERROR("Failed to decompress data we "
2694 "compressed using LZX algorithm");
2699 if (memcmp(uncompressed_data, buf, uncompressed_len)) {
2700 ERROR("Data we compressed using LZX algorithm "
2701 "didn't decompress to original");
2706 return compressed_len;
2710 lzx_params_compatible(const struct wimlib_lzx_params *oldparams,
2711 const struct wimlib_lzx_params *newparams)
2713 return 0 == memcmp(oldparams, newparams, sizeof(struct wimlib_lzx_params));
2716 static struct wimlib_lzx_params lzx_user_default_params;
2717 static struct wimlib_lzx_params *lzx_user_default_params_ptr;
2720 lzx_params_valid(const struct wimlib_lzx_params *params)
2722 /* Validate parameters. */
2723 if (params->size_of_this != sizeof(struct wimlib_lzx_params)) {
2724 LZX_DEBUG("Invalid parameter structure size!");
2728 if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2729 params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2731 LZX_DEBUG("Invalid algorithm.");
2735 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2736 if (params->alg_params.slow.num_optim_passes < 1)
2738 LZX_DEBUG("Invalid number of optimization passes!");
2742 if (params->alg_params.slow.main_nostat_cost < 1 ||
2743 params->alg_params.slow.main_nostat_cost > 16)
2745 LZX_DEBUG("Invalid main_nostat_cost!");
2749 if (params->alg_params.slow.len_nostat_cost < 1 ||
2750 params->alg_params.slow.len_nostat_cost > 16)
2752 LZX_DEBUG("Invalid len_nostat_cost!");
2756 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2757 params->alg_params.slow.aligned_nostat_cost > 8)
2759 LZX_DEBUG("Invalid aligned_nostat_cost!");
2763 if (params->alg_params.slow.num_split_passes > 31) {
2764 LZX_DEBUG("Invalid num_split_passes!");
2772 wimlib_lzx_set_default_params(const struct wimlib_lzx_params * params)
2775 if (!lzx_params_valid(params))
2776 return WIMLIB_ERR_INVALID_PARAM;
2777 lzx_user_default_params = *params;
2778 lzx_user_default_params_ptr = &lzx_user_default_params;
2780 lzx_user_default_params_ptr = NULL;
2785 /* API function documented in wimlib.h */
2787 wimlib_lzx_alloc_context(const struct wimlib_lzx_params *params,
2788 struct wimlib_lzx_context **ctx_pp)
2791 LZX_DEBUG("Allocating LZX context...");
2793 struct lzx_compressor *ctx;
2795 static const struct wimlib_lzx_params fast_default = {
2796 .size_of_this = sizeof(struct wimlib_lzx_params),
2797 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2804 static const struct wimlib_lzx_params slow_default = {
2805 .size_of_this = sizeof(struct wimlib_lzx_params),
2806 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2810 .use_len2_matches = 1,
2811 .num_fast_bytes = 32,
2812 .num_optim_passes = 2,
2813 .num_split_passes = 0,
2814 .max_search_depth = 50,
2815 .max_matches_per_pos = 3,
2816 .main_nostat_cost = 15,
2817 .len_nostat_cost = 15,
2818 .aligned_nostat_cost = 7,
2824 if (!lzx_params_valid(params))
2825 return WIMLIB_ERR_INVALID_PARAM;
2827 LZX_DEBUG("Using default algorithm and parameters.");
2828 if (lzx_user_default_params_ptr)
2829 params = lzx_user_default_params_ptr;
2831 params = &slow_default;
2834 if (params->use_defaults) {
2835 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2836 params = &slow_default;
2838 params = &fast_default;
2842 ctx = *(struct lzx_compressor**)ctx_pp;
2844 if (ctx && lzx_params_compatible(&ctx->params, params))
2847 LZX_DEBUG("Check parameters only.");
2851 LZX_DEBUG("Allocating memory.");
2853 ctx = MALLOC(sizeof(struct lzx_compressor));
2857 size_t block_specs_length;
2859 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2860 block_specs_length = 1U << params->alg_params.slow.num_split_passes;
2862 block_specs_length = 1U;
2863 ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2864 if (ctx->block_specs == NULL)
2867 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2868 ctx->SA = MALLOC(3U * LZX_MAX_WINDOW_SIZE * sizeof(ctx->SA[0]));
2869 if (ctx->SA == NULL)
2870 goto err_free_block_specs;
2871 ctx->ISA = ctx->SA + LZX_MAX_WINDOW_SIZE;
2872 ctx->LCP = ctx->ISA + LZX_MAX_WINDOW_SIZE;
2873 ctx->salink = MALLOC(LZX_MAX_WINDOW_SIZE * sizeof(ctx->salink[0]));
2874 if (ctx->salink == NULL)
2883 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2884 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE + LZX_MAX_MATCH_LEN) *
2885 sizeof(ctx->optimum[0]));
2886 if (ctx->optimum == NULL)
2887 goto err_free_salink;
2889 ctx->optimum = NULL;
2892 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2893 uint32_t cache_per_pos;
2895 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
2896 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
2897 cache_per_pos = LZX_MAX_CACHE_PER_POS;
2899 ctx->cached_matches = MALLOC(LZX_MAX_WINDOW_SIZE * (cache_per_pos + 1) *
2900 sizeof(ctx->cached_matches[0]));
2901 if (ctx->cached_matches == NULL)
2902 goto err_free_optimum;
2904 ctx->cached_matches = NULL;
2907 ctx->chosen_matches = MALLOC(LZX_MAX_WINDOW_SIZE *
2908 sizeof(ctx->chosen_matches[0]));
2909 if (ctx->chosen_matches == NULL)
2910 goto err_free_cached_matches;
2912 memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_params));
2913 memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2915 LZX_DEBUG("Successfully allocated new LZX context.");
2917 wimlib_lzx_free_context(*ctx_pp);
2918 *ctx_pp = (struct wimlib_lzx_context*)ctx;
2921 err_free_cached_matches:
2922 FREE(ctx->cached_matches);
2929 err_free_block_specs:
2930 FREE(ctx->block_specs);
2934 LZX_DEBUG("Ran out of memory.");
2935 return WIMLIB_ERR_NOMEM;
2938 /* API function documented in wimlib.h */
2940 wimlib_lzx_free_context(struct wimlib_lzx_context *_ctx)
2942 struct lzx_compressor *ctx = (struct lzx_compressor*)_ctx;
2945 FREE(ctx->cached_matches);
2946 FREE(ctx->chosen_matches);
2950 FREE(ctx->block_specs);
2955 /* API function documented in wimlib.h */
2957 wimlib_lzx_compress(const void * const restrict uncompressed_data,
2958 unsigned const uncompressed_len,
2959 void * const restrict compressed_data)
2962 struct wimlib_lzx_context *ctx = NULL;
2963 unsigned compressed_len;
2965 ret = wimlib_lzx_alloc_context(NULL, &ctx);
2967 wimlib_assert(ret != WIMLIB_ERR_INVALID_PARAM);
2968 WARNING("Couldn't allocate LZX compression context: %"TS"",
2969 wimlib_get_error_string(ret));
2973 compressed_len = wimlib_lzx_compress2(uncompressed_data,
2978 wimlib_lzx_free_context(ctx);
2980 return compressed_len;