6 * Copyright (C) 2012, 2013, 2014 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
26 * This file contains a compressor for the LZX ("Lempel-Ziv eXtended"?)
27 * compression format, as used in the WIM (Windows IMaging) file format. This
28 * code may need some slight modifications to be used outside of the WIM format.
29 * In particular, in other situations the LZX block header might be slightly
30 * different, and a sliding window rather than a fixed-size window might be
33 * ----------------------------------------------------------------------------
37 * The primary reference for LZX is the specification released by Microsoft.
38 * However, the comments in lzx-decompress.c provide more information about LZX
39 * and note some errors in the Microsoft specification.
41 * LZX shares many similarities with DEFLATE, the format used by zlib and gzip.
42 * Both LZX and DEFLATE use LZ77 matching and Huffman coding. Certain details
43 * are quite similar, such as the method for storing Huffman codes. However,
44 * the main differences are:
46 * - LZX preprocesses the data to attempt to make x86 machine code slightly more
47 * compressible before attempting to compress it further.
49 * - LZX uses a "main" alphabet which combines literals and matches, with the
50 * match symbols containing a "length header" (giving all or part of the match
51 * length) and a "position slot" (giving, roughly speaking, the order of
52 * magnitude of the match offset).
54 * - LZX does not have static Huffman blocks (that is, the kind with preset
55 * Huffman codes); however it does have two types of dynamic Huffman blocks
56 * ("verbatim" and "aligned").
58 * - LZX has a minimum match length of 2 rather than 3.
60 * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
61 * queue of match offsets. This is very useful for certain types of files,
62 * such as binary files that have repeating records.
64 * ----------------------------------------------------------------------------
66 * Algorithmic Overview
68 * At a high level, any implementation of LZX compression must operate as
71 * 1. Preprocess the input data to translate the targets of 32-bit x86 call
72 * instructions to absolute offsets. (Actually, this is required for WIM,
73 * but might not be in other places LZX is used.)
75 * 2. Find a sequence of LZ77-style matches and literal bytes that expands to
76 * the preprocessed data.
78 * 3. Divide the match/literal sequence into one or more LZX blocks, each of
79 * which may be "uncompressed", "verbatim", or "aligned".
81 * 4. Output each LZX block.
83 * Step (1) is fairly straightforward. It requires looking for 0xe8 bytes in
84 * the input data and performing a translation on the 4 bytes following each
87 * Step (4) is complicated, but it is mostly determined by the LZX format. The
88 * only real choice we have is what algorithm to use to build the length-limited
89 * canonical Huffman codes. See lzx_write_all_blocks() for details.
91 * That leaves steps (2) and (3) as where all the hard stuff happens. Focusing
92 * on step (2), we need to do LZ77-style parsing on the input data, or "window",
93 * to divide it into a sequence of matches and literals. Each position in the
94 * window might have multiple matches associated with it, and we need to choose
95 * which one, if any, to actually use. Therefore, the problem can really be
96 * divided into two areas of concern: (a) finding matches at a given position,
97 * which we shall call "match-finding", and (b) choosing whether to use a
98 * match or a literal at a given position, and if using a match, which one (if
99 * there is more than one available). We shall call this "match-choosing". We
100 * first consider match-finding, then match-choosing.
102 * ----------------------------------------------------------------------------
106 * Given a position in the window, we want to find LZ77-style "matches" with
107 * that position at previous positions in the window. With LZX, the minimum
108 * match length is 2 and the maximum match length is 257. The only restriction
109 * on offsets is that LZX does not allow the last 2 bytes of the window to match
110 * the the beginning of the window.
112 * Depending on how good a compression ratio we want (see the "Match-choosing"
113 * section), we may want to find: (a) all matches, or (b) just the longest
114 * match, or (c) just some "promising" matches that we are able to find quickly,
115 * or (d) just the longest match that we're able to find quickly. Below we
116 * introduce the match-finding methods that the code currently uses or has
119 * - Hash chains. Maintain a table that maps hash codes, computed from
120 * fixed-length byte sequences, to linked lists containing previous window
121 * positions. To search for matches, compute the hash for the current
122 * position in the window and search the appropriate hash chain. When
123 * advancing to the next position, prepend the current position to the
124 * appropriate hash list. This is a good approach for producing matches with
125 * stategy (d) and is useful for fast compression. Therefore, we provide an
126 * option to use this method for LZX compression. See lz_hash.c for the
129 * - Binary trees. Similar to hash chains, but each hash bucket contains a
130 * binary tree of previous window positions rather than a linked list. This
131 * is a good approach for producing matches with stategy (c) and is useful for
132 * achieving a good compression ratio. Therefore, we provide an option to use
133 * this method; see lz_bt.c for the implementation.
135 * - Suffix arrays. This code previously used this method to produce matches
136 * with stategy (c), but I've dropped it because it was slower than the binary
137 * trees approach, used more memory, and did not improve the compression ratio
138 * enough to compensate. Download wimlib v1.6.2 if you want the code.
139 * However, the suffix array method was basically as follows. Build the
140 * suffix array for the entire window. The suffix array contains each
141 * possible window position, sorted by the lexicographic order of the strings
142 * that begin at those positions. Find the matches at a given position by
143 * searching the suffix array outwards, in both directions, from the suffix
144 * array slot for that position. This produces the longest matches first, but
145 * "matches" that actually occur at later positions in the window must be
146 * skipped. To do this skipping, use an auxiliary array with dynamically
147 * constructed linked lists. Also, use the inverse suffix array to quickly
148 * find the suffix array slot for a given position without doing a binary
151 * ----------------------------------------------------------------------------
155 * Usually, choosing the longest match is best because it encodes the most data
156 * in that one item. However, sometimes the longest match is not optimal
157 * because (a) choosing a long match now might prevent using an even longer
158 * match later, or (b) more generally, what we actually care about is the number
159 * of bits it will ultimately take to output each match or literal, which is
160 * actually dependent on the entropy encoding using by the underlying
161 * compression format. Consequently, a longer match usually, but not always,
162 * takes fewer bits to encode than multiple shorter matches or literals that
163 * cover the same data.
165 * This problem of choosing the truly best match/literal sequence is probably
166 * impossible to solve efficiently when combined with entropy encoding. If we
167 * knew how many bits it takes to output each match/literal, then we could
168 * choose the optimal sequence using shortest-path search a la Dijkstra's
169 * algorithm. However, with entropy encoding, the chosen match/literal sequence
170 * affects its own encoding. Therefore, we can't know how many bits it will
171 * take to actually output any one match or literal until we have actually
172 * chosen the full sequence of matches and literals.
174 * Notwithstanding the entropy encoding problem, we also aren't guaranteed to
175 * choose the optimal match/literal sequence unless the match-finder (see
176 * section "Match-finder") provides the match-chooser with all possible matches
177 * at each position. However, this is not computationally efficient. For
178 * example, there might be many matches of the same length, and usually (but not
179 * always) the best choice is the one with the smallest offset. So in practice,
180 * it's fine to only consider the smallest offset for a given match length at a
181 * given position. (Actually, for LZX, it's also worth considering repeat
184 * In addition, as mentioned earlier, in LZX we have the choice of using
185 * multiple blocks, each of which resets the Huffman codes. This expands the
186 * search space even further. Therefore, to simplify the problem, we currently
187 * we don't attempt to actually choose the LZX blocks based on the data.
188 * Instead, we just divide the data into fixed-size blocks of LZX_DIV_BLOCK_SIZE
189 * bytes each, and always use verbatim or aligned blocks (never uncompressed).
190 * A previous version of this code recursively split the input data into
191 * equal-sized blocks, up to a maximum depth, and chose the lowest-cost block
192 * divisions. However, this made compression much slower and did not actually
193 * help very much. It remains an open question whether a sufficiently fast and
194 * useful block-splitting algorithm is possible for LZX. Essentially the same
195 * problem also applies to DEFLATE. The Microsoft LZX compressor seemingly does
196 * do block splitting, although I don't know how fast or useful it is,
199 * Now, back to the entropy encoding problem. The "solution" is to use an
200 * iterative approach to compute a good, but not necessarily optimal,
201 * match/literal sequence. Start with a fixed assignment of symbol costs and
202 * choose an "optimal" match/literal sequence based on those costs, using
203 * shortest-path seach a la Dijkstra's algorithm. Then, for each iteration of
204 * the optimization, update the costs based on the entropy encoding of the
205 * current match/literal sequence, then choose a new match/literal sequence
206 * based on the updated costs. Usually, the actual cost to output the current
207 * match/literal sequence will decrease in each iteration until it converges on
208 * a fixed point. This result may not be the truly optimal match/literal
209 * sequence, but it usually is much better than one chosen by doing a "greedy"
210 * parse where we always chooe the longest match.
212 * An alternative to both greedy parsing and iterative, near-optimal parsing is
213 * "lazy" parsing. Briefly, "lazy" parsing considers just the longest match at
214 * each position, but it waits to choose that match until it has also examined
215 * the next position. This is actually a useful approach; it's used by zlib,
216 * for example. Therefore, for fast compression we combine lazy parsing with
217 * the hash chain max-finder. For normal/high compression we combine
218 * near-optimal parsing with the binary tree match-finder.
220 * Anyway, if you've read through this comment, you hopefully should have a
221 * better idea of why things are done in a certain way in this LZX compressor,
222 * as well as in other compressors for LZ77-based formats (including third-party
223 * ones). In my opinion, the phrase "compression algorithm" is often mis-used
224 * in place of "compression format", since there can be many different
225 * algorithms that all generate compressed data in the same format. The
226 * challenge is to design an algorithm that is efficient but still gives a good
235 #include "wimlib/compressor_ops.h"
236 #include "wimlib/compress_common.h"
237 #include "wimlib/endianness.h"
238 #include "wimlib/error.h"
239 #include "wimlib/lz.h"
240 #include "wimlib/lz_hash.h"
241 #include "wimlib/lz_bt.h"
242 #include "wimlib/lzx.h"
243 #include "wimlib/util.h"
246 #ifdef ENABLE_LZX_DEBUG
247 # include "wimlib/decompress_common.h"
250 #define LZX_OPTIM_ARRAY_SIZE 4096
252 #define LZX_DIV_BLOCK_SIZE 32768
254 #define LZX_CACHE_PER_POS 8
256 #define LZX_CACHE_LEN (LZX_DIV_BLOCK_SIZE * (LZX_CACHE_PER_POS + 1))
257 #define LZX_CACHE_SIZE (LZX_CACHE_LEN * sizeof(struct raw_match))
258 #define LZX_MAX_MATCHES_PER_POS (LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1)
260 /* Codewords for the LZX main, length, and aligned offset Huffman codes */
261 struct lzx_codewords {
262 u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
263 u32 len[LZX_LENCODE_NUM_SYMBOLS];
264 u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
267 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
270 * A 0 length means the codeword has zero frequency.
273 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
274 u8 len[LZX_LENCODE_NUM_SYMBOLS];
275 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
278 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
280 * If a codeword has zero frequency, it must still be assigned some nonzero cost
281 * --- generally a high cost, since even if it gets used in the next iteration,
282 * it probably will not be used very times. */
284 u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
285 u8 len[LZX_LENCODE_NUM_SYMBOLS];
286 u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
289 /* The LZX main, length, and aligned offset Huffman codes */
291 struct lzx_codewords codewords;
292 struct lzx_lens lens;
295 /* Tables for tallying symbol frequencies in the three LZX alphabets */
297 input_idx_t main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
298 input_idx_t len[LZX_LENCODE_NUM_SYMBOLS];
299 input_idx_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
302 /* LZX intermediate match/literal format */
306 * 31 1 if a match, 0 if a literal.
308 * 30-25 position slot. This can be at most 50, so it will fit in 6
311 * 8-24 position footer. This is the offset of the real formatted
312 * offset from the position base. This can be at most 17 bits
313 * (since lzx_extra_bits[LZX_MAX_POSITION_SLOTS - 1] is 17).
315 * 0-7 length of match, minus 2. This can be at most
316 * (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits. */
320 /* Specification for an LZX block. */
321 struct lzx_block_spec {
323 /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
327 /* 0-based position in the window at which this block starts. */
328 input_idx_t window_pos;
330 /* The number of bytes of uncompressed data this block represents. */
331 input_idx_t block_size;
333 /* The match/literal sequence for this block. */
334 struct lzx_match *chosen_matches;
336 /* The length of the @chosen_matches sequence. */
337 input_idx_t num_chosen_matches;
339 /* Huffman codes for this block. */
340 struct lzx_codes codes;
343 /* State of the LZX compressor. */
344 struct lzx_compressor {
346 /* The parameters that were used to create the compressor. */
347 struct wimlib_lzx_compressor_params params;
349 /* The buffer of data to be compressed.
351 * 0xe8 byte preprocessing is done directly on the data here before
352 * further compression.
354 * Note that this compressor does *not* use a real sliding window!!!!
355 * It's not needed in the WIM format, since every chunk is compressed
356 * independently. This is by design, to allow random access to the
359 * We reserve a few extra bytes to potentially allow reading off the end
360 * of the array in the match-finding code for optimization purposes
361 * (currently only needed for the hash chain match-finder). */
364 /* Number of bytes of data to be compressed, which is the number of
365 * bytes of data in @window that are actually valid. */
366 input_idx_t window_size;
368 /* Allocated size of the @window. */
369 input_idx_t max_window_size;
371 /* Number of symbols in the main alphabet (depends on the
372 * @max_window_size since it determines the maximum allowed offset). */
373 unsigned num_main_syms;
375 /* The current match offset LRU queue. */
376 struct lzx_lru_queue queue;
378 /* Space for the sequences of matches/literals that were chosen for each
380 struct lzx_match *chosen_matches;
382 /* Information about the LZX blocks the preprocessed input was divided
384 struct lzx_block_spec *block_specs;
386 /* Number of LZX blocks the input was divided into; a.k.a. the number of
387 * elements of @block_specs that are valid. */
390 /* This is simply filled in with zeroes and used to avoid special-casing
391 * the output of the first compressed Huffman code, which conceptually
392 * has a delta taken from a code with all symbols having zero-length
394 struct lzx_codes zero_codes;
396 /* The current cost model. */
397 struct lzx_costs costs;
399 /* Fast algorithm only: Array of hash table links. */
400 input_idx_t *prev_tab;
402 /* Slow algorithm only: Binary tree match-finder. */
405 /* Position in window of next match to return. */
406 input_idx_t match_window_pos;
408 /* The end-of-block position. We can't allow any matches to span this
410 input_idx_t match_window_end;
412 /* Matches found by the match-finder are cached in the following array
413 * to achieve a slight speedup when the same matches are needed on
414 * subsequent passes. This is suboptimal because different matches may
415 * be preferred with different cost models, but seems to be a worthwhile
417 struct raw_match *cached_matches;
418 struct raw_match *cache_ptr;
420 struct raw_match *cache_limit;
422 /* Match-chooser state.
423 * When matches have been chosen, optimum_cur_idx is set to the position
424 * in the window of the next match/literal to return and optimum_end_idx
425 * is set to the position in the window at the end of the last
426 * match/literal to return. */
427 struct lzx_mc_pos_data *optimum;
428 unsigned optimum_cur_idx;
429 unsigned optimum_end_idx;
433 * Match chooser position data:
435 * An array of these structures is used during the match-choosing algorithm.
436 * They correspond to consecutive positions in the window and are used to keep
437 * track of the cost to reach each position, and the match/literal choices that
438 * need to be chosen to reach that position.
440 struct lzx_mc_pos_data {
441 /* The approximate minimum cost, in bits, to reach this position in the
442 * window which has been found so far. */
444 #define MC_INFINITE_COST ((u32)~0UL)
446 /* The union here is just for clarity, since the fields are used in two
447 * slightly different ways. Initially, the @prev structure is filled in
448 * first, and links go from later in the window to earlier in the
449 * window. Later, @next structure is filled in and links go from
450 * earlier in the window to later in the window. */
453 /* Position of the start of the match or literal that
454 * was taken to get to this position in the approximate
455 * minimum-cost parse. */
458 /* Offset (as in an LZ (length, offset) pair) of the
459 * match or literal that was taken to get to this
460 * position in the approximate minimum-cost parse. */
461 input_idx_t match_offset;
464 /* Position at which the match or literal starting at
465 * this position ends in the minimum-cost parse. */
468 /* Offset (as in an LZ (length, offset) pair) of the
469 * match or literal starting at this position in the
470 * approximate minimum-cost parse. */
471 input_idx_t match_offset;
475 /* Adaptive state that exists after an approximate minimum-cost path to
476 * reach this position is taken. */
477 struct lzx_lru_queue queue;
480 /* Returns the LZX position slot that corresponds to a given match offset,
481 * taking into account the recent offset queue and updating it if the offset is
484 lzx_get_position_slot(u32 offset, struct lzx_lru_queue *queue)
486 unsigned position_slot;
488 /* See if the offset was recently used. */
489 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
490 if (offset == queue->R[i]) {
493 /* Bring the repeat offset to the front of the
494 * queue. Note: this is, in fact, not a real
495 * LRU queue because repeat matches are simply
496 * swapped to the front. */
497 swap(queue->R[0], queue->R[i]);
499 /* The resulting position slot is simply the first index
500 * at which the offset was found in the queue. */
505 /* The offset was not recently used; look up its real position slot. */
506 position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
508 /* Bring the new offset to the front of the queue. */
509 for (int i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
510 queue->R[i] = queue->R[i - 1];
511 queue->R[0] = offset;
513 return position_slot;
516 /* Build the main, length, and aligned offset Huffman codes used in LZX.
518 * This takes as input the frequency tables for each code and produces as output
519 * a set of tables that map symbols to codewords and codeword lengths. */
521 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
522 struct lzx_codes *codes,
523 unsigned num_main_syms)
525 make_canonical_huffman_code(num_main_syms,
526 LZX_MAX_MAIN_CODEWORD_LEN,
529 codes->codewords.main);
531 make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
532 LZX_MAX_LEN_CODEWORD_LEN,
535 codes->codewords.len);
537 make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
538 LZX_MAX_ALIGNED_CODEWORD_LEN,
541 codes->codewords.aligned);
545 * Output a precomputed LZX match.
548 * The bitstream to which to write the match.
550 * The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or
551 * LZX_BLOCKTYPE_VERBATIM)
553 * The match, as a (length, offset) pair.
555 * Pointer to a structure that contains the codewords for the main, length,
556 * and aligned offset Huffman codes for the current LZX compressed block.
559 lzx_write_match(struct output_bitstream *out, int block_type,
560 struct lzx_match match, const struct lzx_codes *codes)
562 /* low 8 bits are the match length minus 2 */
563 unsigned match_len_minus_2 = match.data & 0xff;
564 /* Next 17 bits are the position footer */
565 unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
566 /* Next 6 bits are the position slot. */
567 unsigned position_slot = (match.data >> 25) & 0x3f; /* 6 bits */
570 unsigned main_symbol;
571 unsigned num_extra_bits;
572 unsigned verbatim_bits;
573 unsigned aligned_bits;
575 /* If the match length is less than MIN_MATCH_LEN (= 2) +
576 * NUM_PRIMARY_LENS (= 7), the length header contains
577 * the match length minus MIN_MATCH_LEN, and there is no
580 * Otherwise, the length header contains
581 * NUM_PRIMARY_LENS, and the length footer contains
582 * the match length minus NUM_PRIMARY_LENS minus
584 if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
585 len_header = match_len_minus_2;
587 len_header = LZX_NUM_PRIMARY_LENS;
588 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
591 /* Combine the position slot with the length header into a single symbol
592 * that will be encoded with the main code.
594 * The actual main symbol is offset by LZX_NUM_CHARS because values
595 * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
597 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
599 /* Output main symbol. */
600 bitstream_put_bits(out, codes->codewords.main[main_symbol],
601 codes->lens.main[main_symbol]);
603 /* If there is a length footer, output it using the
604 * length Huffman code. */
605 if (len_header == LZX_NUM_PRIMARY_LENS)
606 bitstream_put_bits(out, codes->codewords.len[len_footer],
607 codes->lens.len[len_footer]);
609 num_extra_bits = lzx_get_num_extra_bits(position_slot);
611 /* For aligned offset blocks with at least 3 extra bits, output the
612 * verbatim bits literally, then the aligned bits encoded using the
613 * aligned offset code. Otherwise, only the verbatim bits need to be
615 if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
617 verbatim_bits = position_footer >> 3;
618 bitstream_put_bits(out, verbatim_bits,
621 aligned_bits = (position_footer & 7);
622 bitstream_put_bits(out,
623 codes->codewords.aligned[aligned_bits],
624 codes->lens.aligned[aligned_bits]);
626 /* verbatim bits is the same as the position
627 * footer, in this case. */
628 bitstream_put_bits(out, position_footer, num_extra_bits);
632 /* Output an LZX literal (encoded with the main Huffman code). */
634 lzx_write_literal(struct output_bitstream *out, u8 literal,
635 const struct lzx_codes *codes)
637 bitstream_put_bits(out,
638 codes->codewords.main[literal],
639 codes->lens.main[literal]);
643 lzx_build_precode(const u8 lens[restrict],
644 const u8 prev_lens[restrict],
645 const unsigned num_syms,
646 input_idx_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
647 u8 output_syms[restrict num_syms],
648 u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
649 u32 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
650 unsigned *num_additional_bits_ret)
652 memset(precode_freqs, 0,
653 LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
655 /* Since the code word lengths use a form of RLE encoding, the goal here
656 * is to find each run of identical lengths when going through them in
657 * symbol order (including runs of length 1). For each run, as many
658 * lengths are encoded using RLE as possible, and the rest are output
661 * output_syms[] will be filled in with the length symbols that will be
662 * output, including RLE codes, not yet encoded using the precode.
664 * cur_run_len keeps track of how many code word lengths are in the
665 * current run of identical lengths. */
666 unsigned output_syms_idx = 0;
667 unsigned cur_run_len = 1;
668 unsigned num_additional_bits = 0;
669 for (unsigned i = 1; i <= num_syms; i++) {
671 if (i != num_syms && lens[i] == lens[i - 1]) {
672 /* Still in a run--- keep going. */
677 /* Run ended! Check if it is a run of zeroes or a run of
680 /* The symbol that was repeated in the run--- not to be confused
681 * with the length *of* the run (cur_run_len) */
682 unsigned len_in_run = lens[i - 1];
684 if (len_in_run == 0) {
685 /* A run of 0's. Encode it in as few length
686 * codes as we can. */
688 /* The magic length 18 indicates a run of 20 + n zeroes,
689 * where n is an uncompressed literal 5-bit integer that
690 * follows the magic length. */
691 while (cur_run_len >= 20) {
692 unsigned additional_bits;
694 additional_bits = min(cur_run_len - 20, 0x1f);
695 num_additional_bits += 5;
697 output_syms[output_syms_idx++] = 18;
698 output_syms[output_syms_idx++] = additional_bits;
699 cur_run_len -= 20 + additional_bits;
702 /* The magic length 17 indicates a run of 4 + n zeroes,
703 * where n is an uncompressed literal 4-bit integer that
704 * follows the magic length. */
705 while (cur_run_len >= 4) {
706 unsigned additional_bits;
708 additional_bits = min(cur_run_len - 4, 0xf);
709 num_additional_bits += 4;
711 output_syms[output_syms_idx++] = 17;
712 output_syms[output_syms_idx++] = additional_bits;
713 cur_run_len -= 4 + additional_bits;
718 /* A run of nonzero lengths. */
720 /* The magic length 19 indicates a run of 4 + n
721 * nonzeroes, where n is a literal bit that follows the
722 * magic length, and where the value of the lengths in
723 * the run is given by an extra length symbol, encoded
724 * with the precode, that follows the literal bit.
726 * The extra length symbol is encoded as a difference
727 * from the length of the codeword for the first symbol
728 * in the run in the previous code.
730 while (cur_run_len >= 4) {
731 unsigned additional_bits;
734 additional_bits = (cur_run_len > 4);
735 num_additional_bits += 1;
736 delta = (signed char)prev_lens[i - cur_run_len] -
737 (signed char)len_in_run;
741 precode_freqs[(unsigned char)delta]++;
742 output_syms[output_syms_idx++] = 19;
743 output_syms[output_syms_idx++] = additional_bits;
744 output_syms[output_syms_idx++] = delta;
745 cur_run_len -= 4 + additional_bits;
749 /* Any remaining lengths in the run are outputted without RLE,
750 * as a difference from the length of that codeword in the
752 while (cur_run_len > 0) {
755 delta = (signed char)prev_lens[i - cur_run_len] -
756 (signed char)len_in_run;
760 precode_freqs[(unsigned char)delta]++;
761 output_syms[output_syms_idx++] = delta;
768 /* Build the precode from the frequencies of the length symbols. */
770 make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
771 LZX_MAX_PRE_CODEWORD_LEN,
772 precode_freqs, precode_lens,
775 *num_additional_bits_ret = num_additional_bits;
777 return output_syms_idx;
781 * Output a Huffman code in the compressed form used in LZX.
783 * The Huffman code is represented in the output as a logical series of codeword
784 * lengths from which the Huffman code, which must be in canonical form, can be
787 * The codeword lengths are themselves compressed using a separate Huffman code,
788 * the "precode", which contains a symbol for each possible codeword length in
789 * the larger code as well as several special symbols to represent repeated
790 * codeword lengths (a form of run-length encoding). The precode is itself
791 * constructed in canonical form, and its codeword lengths are represented
792 * literally in 20 4-bit fields that immediately precede the compressed codeword
793 * lengths of the larger code.
795 * Furthermore, the codeword lengths of the larger code are actually represented
796 * as deltas from the codeword lengths of the corresponding code in the previous
800 * Bitstream to which to write the compressed Huffman code.
802 * The codeword lengths, indexed by symbol, in the Huffman code.
804 * The codeword lengths, indexed by symbol, in the corresponding Huffman
805 * code in the previous block, or all zeroes if this is the first block.
807 * The number of symbols in the Huffman code.
810 lzx_write_compressed_code(struct output_bitstream *out,
811 const u8 lens[restrict],
812 const u8 prev_lens[restrict],
815 input_idx_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
816 u8 output_syms[num_syms];
817 u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
818 u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
820 unsigned num_output_syms;
824 num_output_syms = lzx_build_precode(lens,
833 /* Write the lengths of the precode codes to the output. */
834 for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
835 bitstream_put_bits(out, precode_lens[i],
836 LZX_PRECODE_ELEMENT_SIZE);
838 /* Write the length symbols, encoded with the precode, to the output. */
840 for (i = 0; i < num_output_syms; ) {
841 precode_sym = output_syms[i++];
843 bitstream_put_bits(out, precode_codewords[precode_sym],
844 precode_lens[precode_sym]);
845 switch (precode_sym) {
847 bitstream_put_bits(out, output_syms[i++], 4);
850 bitstream_put_bits(out, output_syms[i++], 5);
853 bitstream_put_bits(out, output_syms[i++], 1);
854 bitstream_put_bits(out,
855 precode_codewords[output_syms[i]],
856 precode_lens[output_syms[i]]);
866 * Write all matches and literal bytes (which were precomputed) in an LZX
867 * compressed block to the output bitstream in the final compressed
871 * The output bitstream.
873 * The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
874 * LZX_BLOCKTYPE_VERBATIM).
876 * The array of matches/literals to output.
878 * Number of matches/literals to output (length of @match_tab).
880 * The main, length, and aligned offset Huffman codes for the current
881 * LZX compressed block.
884 lzx_write_matches_and_literals(struct output_bitstream *ostream,
886 const struct lzx_match match_tab[],
887 unsigned match_count,
888 const struct lzx_codes *codes)
890 for (unsigned i = 0; i < match_count; i++) {
891 struct lzx_match match = match_tab[i];
893 /* The high bit of the 32-bit intermediate representation
894 * indicates whether the item is an actual LZ-style match (1) or
895 * a literal byte (0). */
896 if (match.data & 0x80000000)
897 lzx_write_match(ostream, block_type, match, codes);
899 lzx_write_literal(ostream, match.data, codes);
904 lzx_assert_codes_valid(const struct lzx_codes * codes, unsigned num_main_syms)
906 #ifdef ENABLE_LZX_DEBUG
909 for (i = 0; i < num_main_syms; i++)
910 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
912 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
913 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
915 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
916 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
918 const unsigned tablebits = 10;
919 u16 decode_table[(1 << tablebits) +
920 (2 * max(num_main_syms, LZX_LENCODE_NUM_SYMBOLS))]
921 _aligned_attribute(DECODE_TABLE_ALIGNMENT);
922 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
924 min(tablebits, LZX_MAINCODE_TABLEBITS),
926 LZX_MAX_MAIN_CODEWORD_LEN));
927 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
928 LZX_LENCODE_NUM_SYMBOLS,
929 min(tablebits, LZX_LENCODE_TABLEBITS),
931 LZX_MAX_LEN_CODEWORD_LEN));
932 LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
933 LZX_ALIGNEDCODE_NUM_SYMBOLS,
934 min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
936 LZX_MAX_ALIGNED_CODEWORD_LEN));
937 #endif /* ENABLE_LZX_DEBUG */
940 /* Write an LZX aligned offset or verbatim block to the output. */
942 lzx_write_compressed_block(int block_type,
944 unsigned max_window_size,
945 unsigned num_main_syms,
946 struct lzx_match * chosen_matches,
947 unsigned num_chosen_matches,
948 const struct lzx_codes * codes,
949 const struct lzx_codes * prev_codes,
950 struct output_bitstream * ostream)
954 LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
955 block_type == LZX_BLOCKTYPE_VERBATIM);
956 lzx_assert_codes_valid(codes, num_main_syms);
958 /* The first three bits indicate the type of block and are one of the
959 * LZX_BLOCKTYPE_* constants. */
960 bitstream_put_bits(ostream, block_type, 3);
962 /* Output the block size.
964 * The original LZX format seemed to always encode the block size in 3
965 * bytes. However, the implementation in WIMGAPI, as used in WIM files,
966 * uses the first bit to indicate whether the block is the default size
967 * (32768) or a different size given explicitly by the next 16 bits.
969 * By default, this compressor uses a window size of 32768 and therefore
970 * follows the WIMGAPI behavior. However, this compressor also supports
971 * window sizes greater than 32768 bytes, which do not appear to be
972 * supported by WIMGAPI. In such cases, we retain the default size bit
973 * to mean a size of 32768 bytes but output non-default block size in 24
974 * bits rather than 16. The compatibility of this behavior is unknown
975 * because WIMs created with chunk size greater than 32768 can seemingly
976 * only be opened by wimlib anyway. */
977 if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
978 bitstream_put_bits(ostream, 1, 1);
980 bitstream_put_bits(ostream, 0, 1);
982 if (max_window_size >= 65536)
983 bitstream_put_bits(ostream, block_size >> 16, 8);
985 bitstream_put_bits(ostream, block_size, 16);
988 /* Write out lengths of the main code. Note that the LZX specification
989 * incorrectly states that the aligned offset code comes after the
990 * length code, but in fact it is the very first code to be written
991 * (before the main code). */
992 if (block_type == LZX_BLOCKTYPE_ALIGNED)
993 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
994 bitstream_put_bits(ostream, codes->lens.aligned[i],
995 LZX_ALIGNEDCODE_ELEMENT_SIZE);
997 LZX_DEBUG("Writing main code...");
999 /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
1000 * the main code, which are the codewords for literal bytes. */
1001 lzx_write_compressed_code(ostream,
1003 prev_codes->lens.main,
1006 /* Write the precode and lengths for the rest of the main code, which
1007 * are the codewords for match headers. */
1008 lzx_write_compressed_code(ostream,
1009 codes->lens.main + LZX_NUM_CHARS,
1010 prev_codes->lens.main + LZX_NUM_CHARS,
1011 num_main_syms - LZX_NUM_CHARS);
1013 LZX_DEBUG("Writing length code...");
1015 /* Write the precode and lengths for the length code. */
1016 lzx_write_compressed_code(ostream,
1018 prev_codes->lens.len,
1019 LZX_LENCODE_NUM_SYMBOLS);
1021 LZX_DEBUG("Writing matches and literals...");
1023 /* Write the actual matches and literals. */
1024 lzx_write_matches_and_literals(ostream, block_type,
1025 chosen_matches, num_chosen_matches,
1028 LZX_DEBUG("Done writing block.");
1031 /* Write out the LZX blocks that were computed. */
1033 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
1036 const struct lzx_codes *prev_codes = &ctx->zero_codes;
1037 for (unsigned i = 0; i < ctx->num_blocks; i++) {
1038 const struct lzx_block_spec *spec = &ctx->block_specs[i];
1040 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
1041 i + 1, ctx->num_blocks,
1042 spec->block_type, spec->block_size,
1043 spec->num_chosen_matches);
1045 lzx_write_compressed_block(spec->block_type,
1047 ctx->max_window_size,
1049 spec->chosen_matches,
1050 spec->num_chosen_matches,
1055 prev_codes = &spec->codes;
1059 /* Constructs an LZX match from a literal byte and updates the main code symbol
1062 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
1068 /* Constructs an LZX match from an offset and a length, and updates the LRU
1069 * queue and the frequency of symbols in the main, length, and aligned offset
1070 * alphabets. The return value is a 32-bit number that provides the match in an
1071 * intermediate representation documented below. */
1073 lzx_tally_match(unsigned match_len, u32 match_offset,
1074 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
1076 unsigned position_slot;
1077 unsigned position_footer;
1079 unsigned main_symbol;
1080 unsigned len_footer;
1081 unsigned adjusted_match_len;
1083 LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
1085 /* The match offset shall be encoded as a position slot (itself encoded
1086 * as part of the main symbol) and a position footer. */
1087 position_slot = lzx_get_position_slot(match_offset, queue);
1088 position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1089 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1091 /* The match length shall be encoded as a length header (itself encoded
1092 * as part of the main symbol) and an optional length footer. */
1093 adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1094 if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1095 /* No length footer needed. */
1096 len_header = adjusted_match_len;
1098 /* Length footer needed. It will be encoded using the length
1100 len_header = LZX_NUM_PRIMARY_LENS;
1101 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1102 freqs->len[len_footer]++;
1105 /* Account for the main symbol. */
1106 main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1108 freqs->main[main_symbol]++;
1110 /* In an aligned offset block, 3 bits of the position footer are output
1111 * as an aligned offset symbol. Account for this, although we may
1112 * ultimately decide to output the block as verbatim. */
1114 /* The following check is equivalent to:
1116 * if (lzx_extra_bits[position_slot] >= 3)
1118 * Note that this correctly excludes position slots that correspond to
1119 * recent offsets. */
1120 if (position_slot >= 8)
1121 freqs->aligned[position_footer & 7]++;
1123 /* Pack the position slot, position footer, and match length into an
1124 * intermediate representation. See `struct lzx_match' for details.
1126 LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
1127 LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
1128 LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
1130 LZX_ASSERT(position_slot <= (1U << (31 - 25)) - 1);
1131 LZX_ASSERT(position_footer <= (1U << (25 - 8)) - 1);
1132 LZX_ASSERT(adjusted_match_len <= (1U << (8 - 0)) - 1);
1134 (position_slot << 25) |
1135 (position_footer << 8) |
1136 (adjusted_match_len);
1139 struct lzx_record_ctx {
1140 struct lzx_freqs freqs;
1141 struct lzx_lru_queue queue;
1142 struct lzx_match *matches;
1146 lzx_record_match(unsigned len, unsigned offset, void *_ctx)
1148 struct lzx_record_ctx *ctx = _ctx;
1150 (ctx->matches++)->data = lzx_tally_match(len, offset, &ctx->freqs, &ctx->queue);
1154 lzx_record_literal(u8 lit, void *_ctx)
1156 struct lzx_record_ctx *ctx = _ctx;
1158 (ctx->matches++)->data = lzx_tally_literal(lit, &ctx->freqs);
1161 /* Returns the cost, in bits, to output a literal byte using the specified cost
1164 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1166 return costs->main[c];
1169 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1170 * well as costs for the codewords in the main, length, and aligned Huffman
1171 * codes, return the approximate number of bits it will take to represent this
1172 * match in the compressed output. Take into account the match offset LRU
1173 * queue and optionally update it. */
1175 lzx_match_cost(unsigned length, u32 offset, const struct lzx_costs *costs,
1176 struct lzx_lru_queue *queue)
1178 unsigned position_slot;
1179 unsigned len_header, main_symbol;
1180 unsigned num_extra_bits;
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 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 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1211 * The cost model and codeword lengths are almost the same thing, but the
1212 * Huffman codewords with length 0 correspond to symbols with zero frequency
1213 * that still need to be assigned actual costs. The specific values assigned
1214 * are arbitrary, but they should be fairly high (near the maximum codeword
1215 * length) to take into account the fact that uses of these symbols are expected
1218 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1221 unsigned num_main_syms = ctx->num_main_syms;
1224 for (i = 0; i < num_main_syms; i++) {
1225 ctx->costs.main[i] = lens->main[i];
1226 if (ctx->costs.main[i] == 0)
1227 ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1231 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1232 ctx->costs.len[i] = lens->len[i];
1233 if (ctx->costs.len[i] == 0)
1234 ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1237 /* Aligned offset code */
1238 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1239 ctx->costs.aligned[i] = lens->aligned[i];
1240 if (ctx->costs.aligned[i] == 0)
1241 ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1245 /* Retrieve a list of matches available at the next position in the input.
1247 * A pointer to the matches array is written into @matches_ret, and the return
1248 * value is the number of matches found. */
1250 lzx_get_matches(struct lzx_compressor *ctx,
1251 const struct raw_match **matches_ret)
1253 struct raw_match *cache_ptr;
1254 struct raw_match *matches;
1255 unsigned num_matches;
1257 LZX_ASSERT(ctx->match_window_pos < ctx->match_window_end);
1259 cache_ptr = ctx->cache_ptr;
1260 matches = cache_ptr + 1;
1261 if (likely(cache_ptr <= ctx->cache_limit)) {
1262 if (ctx->matches_cached) {
1263 num_matches = cache_ptr->len;
1265 num_matches = lz_bt_get_matches(&ctx->mf, matches);
1266 cache_ptr->len = num_matches;
1272 /* Don't allow matches to span the end of an LZX block. */
1273 if (ctx->match_window_end < ctx->window_size && num_matches != 0) {
1274 unsigned limit = ctx->match_window_end - ctx->match_window_pos;
1276 if (limit >= LZX_MIN_MATCH_LEN) {
1278 unsigned i = num_matches - 1;
1280 if (matches[i].len >= limit) {
1281 matches[i].len = limit;
1283 /* Truncation might produce multiple
1284 * matches with length 'limit'. Keep at
1286 num_matches = i + 1;
1292 cache_ptr->len = num_matches;
1296 fprintf(stderr, "Pos %u/%u: %u matches\n",
1297 ctx->match_window_pos, ctx->window_size, num_matches);
1298 for (unsigned i = 0; i < num_matches; i++)
1299 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1302 #ifdef ENABLE_LZX_DEBUG
1303 for (unsigned i = 0; i < num_matches; i++) {
1304 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1305 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1306 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1307 LZX_ASSERT(matches[i].offset > 0);
1308 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1309 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1310 &ctx->window[ctx->match_window_pos - matches[i].offset],
1313 LZX_ASSERT(matches[i].len > matches[i - 1].len);
1314 LZX_ASSERT(matches[i].offset > matches[i - 1].offset);
1318 ctx->match_window_pos++;
1319 ctx->cache_ptr = matches + num_matches;
1320 *matches_ret = matches;
1325 lzx_skip_bytes(struct lzx_compressor *ctx, unsigned n)
1327 struct raw_match *cache_ptr;
1329 LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1331 cache_ptr = ctx->cache_ptr;
1332 ctx->match_window_pos += n;
1333 if (ctx->matches_cached) {
1334 while (n-- && cache_ptr <= ctx->cache_limit)
1335 cache_ptr += 1 + cache_ptr->len;
1337 lz_bt_skip_positions(&ctx->mf, n);
1338 while (n-- && cache_ptr <= ctx->cache_limit) {
1343 ctx->cache_ptr = cache_ptr;
1347 * Reverse the linked list of near-optimal matches so that they can be returned
1348 * in forwards order.
1350 * Returns the first match in the list.
1352 static struct raw_match
1353 lzx_match_chooser_reverse_list(struct lzx_compressor *ctx, unsigned cur_pos)
1355 unsigned prev_link, saved_prev_link;
1356 unsigned prev_match_offset, saved_prev_match_offset;
1358 ctx->optimum_end_idx = cur_pos;
1360 saved_prev_link = ctx->optimum[cur_pos].prev.link;
1361 saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
1364 prev_link = saved_prev_link;
1365 prev_match_offset = saved_prev_match_offset;
1367 saved_prev_link = ctx->optimum[prev_link].prev.link;
1368 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
1370 ctx->optimum[prev_link].next.link = cur_pos;
1371 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
1373 cur_pos = prev_link;
1374 } while (cur_pos != 0);
1376 ctx->optimum_cur_idx = ctx->optimum[0].next.link;
1378 return (struct raw_match)
1379 { .len = ctx->optimum_cur_idx,
1380 .offset = ctx->optimum[0].next.match_offset,
1385 * lzx_get_near_optimal_match() -
1387 * Choose an approximately optimal match or literal to use at the next position
1388 * in the string, or "window", being LZ-encoded.
1390 * This is based on algorithms used in 7-Zip, including the DEFLATE encoder
1391 * and the LZMA encoder, written by Igor Pavlov.
1393 * Unlike a greedy parser that always takes the longest match, or even a "lazy"
1394 * parser with one match/literal look-ahead like zlib, the algorithm used here
1395 * may look ahead many matches/literals to determine the approximately optimal
1396 * match/literal to code next. The motivation is that the compression ratio is
1397 * improved if the compressor can do things like use a shorter-than-possible
1398 * match in order to allow a longer match later, and also take into account the
1399 * estimated real cost of coding each match/literal based on the underlying
1402 * Still, this is not a true optimal parser for several reasons:
1404 * - Real compression formats use entropy encoding of the literal/match
1405 * sequence, so the real cost of coding each match or literal is unknown until
1406 * the parse is fully determined. It can be approximated based on iterative
1407 * parses, but the end result is not guaranteed to be globally optimal.
1409 * - Very long matches are chosen immediately. This is because locations with
1410 * long matches are likely to have many possible alternatives that would cause
1411 * slow optimal parsing, but also such locations are already highly
1412 * compressible so it is not too harmful to just grab the longest match.
1414 * - Not all possible matches at each location are considered because the
1415 * underlying match-finder limits the number and type of matches produced at
1416 * each position. For example, for a given match length it's usually not
1417 * worth it to only consider matches other than the lowest-offset match,
1418 * except in the case of a repeat offset.
1420 * - Although we take into account the adaptive state (in LZX, the recent offset
1421 * queue), coding decisions made with respect to the adaptive state will be
1422 * locally optimal but will not necessarily be globally optimal. This is
1423 * because the algorithm only keeps the least-costly path to get to a given
1424 * location and does not take into account that a slightly more costly path
1425 * could result in a different adaptive state that ultimately results in a
1426 * lower global cost.
1428 * - The array space used by this function is bounded, so in degenerate cases it
1429 * is forced to start returning matches/literals before the algorithm has
1432 * Each call to this function does one of two things:
1434 * 1. Build a sequence of near-optimal matches/literals, up to some point, that
1435 * will be returned by subsequent calls to this function, then return the
1440 * 2. Return the next match/literal previously computed by a call to this
1443 * The return value is a (length, offset) pair specifying the match or literal
1444 * chosen. For literals, the length is 0 or 1 and the offset is meaningless.
1446 static struct raw_match
1447 lzx_get_near_optimal_match(struct lzx_compressor *ctx)
1449 unsigned num_matches;
1450 const struct raw_match *matches;
1451 const struct raw_match *matchptr;
1452 struct raw_match match;
1453 unsigned longest_len;
1454 unsigned longest_rep_len;
1455 u32 longest_rep_offset;
1459 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1460 /* Case 2: Return the next match/literal already found. */
1461 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1462 ctx->optimum_cur_idx;
1463 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1465 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1469 /* Case 1: Compute a new list of matches/literals to return. */
1471 ctx->optimum_cur_idx = 0;
1472 ctx->optimum_end_idx = 0;
1474 /* Search for matches at recent offsets. Only keep the one with the
1475 * longest match length. */
1476 longest_rep_len = LZX_MIN_MATCH_LEN - 1;
1477 if (ctx->match_window_pos >= 1) {
1478 unsigned limit = min(LZX_MAX_MATCH_LEN,
1479 ctx->match_window_end - ctx->match_window_pos);
1480 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
1481 u32 offset = ctx->queue.R[i];
1482 const u8 *strptr = &ctx->window[ctx->match_window_pos];
1483 const u8 *matchptr = strptr - offset;
1485 while (len < limit && strptr[len] == matchptr[len])
1487 if (len > longest_rep_len) {
1488 longest_rep_len = len;
1489 longest_rep_offset = offset;
1494 /* If there's a long match with a recent offset, take it. */
1495 if (longest_rep_len >= ctx->params.alg_params.slow.nice_match_length) {
1496 lzx_skip_bytes(ctx, longest_rep_len);
1497 return (struct raw_match) {
1498 .len = longest_rep_len,
1499 .offset = longest_rep_offset,
1503 /* Search other matches. */
1504 num_matches = lzx_get_matches(ctx, &matches);
1506 /* If there's a long match, take it. */
1508 longest_len = matches[num_matches - 1].len;
1509 if (longest_len >= ctx->params.alg_params.slow.nice_match_length) {
1510 lzx_skip_bytes(ctx, longest_len - 1);
1511 return matches[num_matches - 1];
1517 /* Calculate the cost to reach the next position by coding a literal.
1519 ctx->optimum[1].queue = ctx->queue;
1520 ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1522 ctx->optimum[1].prev.link = 0;
1524 /* Calculate the cost to reach any position up to and including that
1525 * reached by the longest match. */
1527 for (unsigned len = 2; len <= longest_len; len++) {
1528 u32 offset = matchptr->offset;
1530 ctx->optimum[len].queue = ctx->queue;
1531 ctx->optimum[len].prev.link = 0;
1532 ctx->optimum[len].prev.match_offset = offset;
1533 ctx->optimum[len].cost = lzx_match_cost(len, offset, &ctx->costs,
1534 &ctx->optimum[len].queue);
1535 if (len == matchptr->len)
1538 end_pos = longest_len;
1540 if (longest_rep_len >= LZX_MIN_MATCH_LEN) {
1541 struct lzx_lru_queue queue;
1544 while (end_pos < longest_rep_len)
1545 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1548 cost = lzx_match_cost(longest_rep_len, longest_rep_offset,
1549 &ctx->costs, &queue);
1550 if (cost <= ctx->optimum[longest_rep_len].cost) {
1551 ctx->optimum[longest_rep_len].queue = queue;
1552 ctx->optimum[longest_rep_len].prev.link = 0;
1553 ctx->optimum[longest_rep_len].prev.match_offset = longest_rep_offset;
1554 ctx->optimum[longest_rep_len].cost = cost;
1558 /* Step forward, calculating the estimated minimum cost to reach each
1559 * position. The algorithm may find multiple paths to reach each
1560 * position; only the lowest-cost path is saved.
1562 * The progress of the parse is tracked in the @ctx->optimum array, which
1563 * for each position contains the minimum cost to reach that position,
1564 * the index of the start of the match/literal taken to reach that
1565 * position through the minimum-cost path, the offset of the match taken
1566 * (not relevant for literals), and the adaptive state that will exist
1567 * at that position after the minimum-cost path is taken. The @cur_pos
1568 * variable stores the position at which the algorithm is currently
1569 * considering coding choices, and the @end_pos variable stores the
1570 * greatest position at which the costs of coding choices have been
1571 * saved. (Actually, the algorithm guarantees that all positions up to
1572 * and including @end_pos are reachable by at least one path.)
1574 * The loop terminates when any one of the following conditions occurs:
1576 * 1. A match with length greater than or equal to @nice_match_length is
1577 * found. When this occurs, the algorithm chooses this match
1578 * unconditionally, and consequently the near-optimal match/literal
1579 * sequence up to and including that match is fully determined and it
1580 * can begin returning the match/literal list.
1582 * 2. @cur_pos reaches a position not overlapped by a preceding match.
1583 * In such cases, the near-optimal match/literal sequence up to
1584 * @cur_pos is fully determined and it can begin returning the
1585 * match/literal list.
1587 * 3. Failing either of the above in a degenerate case, the loop
1588 * terminates when space in the @ctx->optimum array is exhausted.
1589 * This terminates the algorithm and forces it to start returning
1590 * matches/literals even though they may not be globally optimal.
1592 * Upon loop termination, a nonempty list of matches/literals will have
1593 * been produced and stored in the @optimum array. These
1594 * matches/literals are linked in reverse order, so the last thing this
1595 * function does is reverse this list and return the first
1596 * match/literal, leaving the rest to be returned immediately by
1597 * subsequent calls to this function.
1603 /* Advance to next position. */
1606 /* Check termination conditions (2) and (3) noted above. */
1607 if (cur_pos == end_pos || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1608 return lzx_match_chooser_reverse_list(ctx, cur_pos);
1610 /* Search for matches at recent offsets. */
1611 longest_rep_len = LZX_MIN_MATCH_LEN - 1;
1612 unsigned limit = min(LZX_MAX_MATCH_LEN,
1613 ctx->match_window_end - ctx->match_window_pos);
1614 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
1615 u32 offset = ctx->optimum[cur_pos].queue.R[i];
1616 const u8 *strptr = &ctx->window[ctx->match_window_pos];
1617 const u8 *matchptr = strptr - offset;
1619 while (len < limit && strptr[len] == matchptr[len])
1621 if (len > longest_rep_len) {
1622 longest_rep_len = len;
1623 longest_rep_offset = offset;
1627 /* If we found a long match at a recent offset, choose it
1629 if (longest_rep_len >= ctx->params.alg_params.slow.nice_match_length) {
1630 /* Build the list of matches to return and get
1632 match = lzx_match_chooser_reverse_list(ctx, cur_pos);
1634 /* Append the long match to the end of the list. */
1635 ctx->optimum[cur_pos].next.match_offset = longest_rep_offset;
1636 ctx->optimum[cur_pos].next.link = cur_pos + longest_rep_len;
1637 ctx->optimum_end_idx = cur_pos + longest_rep_len;
1639 /* Skip over the remaining bytes of the long match. */
1640 lzx_skip_bytes(ctx, longest_rep_len);
1642 /* Return first match in the list. */
1646 /* Search other matches. */
1647 num_matches = lzx_get_matches(ctx, &matches);
1649 /* If there's a long match, take it. */
1651 longest_len = matches[num_matches - 1].len;
1652 if (longest_len >= ctx->params.alg_params.slow.nice_match_length) {
1653 /* Build the list of matches to return and get
1655 match = lzx_match_chooser_reverse_list(ctx, cur_pos);
1657 /* Append the long match to the end of the list. */
1658 ctx->optimum[cur_pos].next.match_offset =
1659 matches[num_matches - 1].offset;
1660 ctx->optimum[cur_pos].next.link = cur_pos + longest_len;
1661 ctx->optimum_end_idx = cur_pos + longest_len;
1663 /* Skip over the remaining bytes of the long match. */
1664 lzx_skip_bytes(ctx, longest_len - 1);
1666 /* Return first match in the list. */
1673 while (end_pos < cur_pos + longest_len)
1674 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1676 /* Consider coding a literal. */
1677 cost = ctx->optimum[cur_pos].cost +
1678 lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1680 if (cost < ctx->optimum[cur_pos + 1].cost) {
1681 ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1682 ctx->optimum[cur_pos + 1].cost = cost;
1683 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1686 /* Consider coding a match. */
1688 for (unsigned len = 2; len <= longest_len; len++) {
1690 struct lzx_lru_queue queue;
1692 offset = matchptr->offset;
1693 queue = ctx->optimum[cur_pos].queue;
1695 cost = ctx->optimum[cur_pos].cost +
1696 lzx_match_cost(len, offset, &ctx->costs, &queue);
1697 if (cost < ctx->optimum[cur_pos + len].cost) {
1698 ctx->optimum[cur_pos + len].queue = queue;
1699 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1700 ctx->optimum[cur_pos + len].prev.match_offset = offset;
1701 ctx->optimum[cur_pos + len].cost = cost;
1703 if (len == matchptr->len)
1707 if (longest_rep_len >= LZX_MIN_MATCH_LEN) {
1708 struct lzx_lru_queue queue;
1710 while (end_pos < cur_pos + longest_rep_len)
1711 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1713 queue = ctx->optimum[cur_pos].queue;
1715 cost = ctx->optimum[cur_pos].cost +
1716 lzx_match_cost(longest_rep_len, longest_rep_offset,
1717 &ctx->costs, &queue);
1718 if (cost <= ctx->optimum[cur_pos + longest_rep_len].cost) {
1719 ctx->optimum[cur_pos + longest_rep_len].queue =
1721 ctx->optimum[cur_pos + longest_rep_len].prev.link =
1723 ctx->optimum[cur_pos + longest_rep_len].prev.match_offset =
1725 ctx->optimum[cur_pos + longest_rep_len].cost =
1732 /* Set default symbol costs for the LZX Huffman codes. */
1734 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1738 /* Main code (part 1): Literal symbols */
1739 for (i = 0; i < LZX_NUM_CHARS; i++)
1742 /* Main code (part 2): Match header symbols */
1743 for (; i < num_main_syms; i++)
1744 costs->main[i] = 10;
1747 for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1750 /* Aligned offset code */
1751 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1752 costs->aligned[i] = 3;
1755 /* Given the frequencies of symbols in an LZX-compressed block and the
1756 * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1757 * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1758 * will take fewer bits to output. */
1760 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1761 const struct lzx_codes * codes)
1763 unsigned aligned_cost = 0;
1764 unsigned verbatim_cost = 0;
1766 /* Verbatim blocks have a constant 3 bits per position footer. Aligned
1767 * offset blocks have an aligned offset symbol per position footer, plus
1768 * an extra 24 bits per block to output the lengths necessary to
1769 * reconstruct the aligned offset code itself. */
1770 for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1771 verbatim_cost += 3 * freqs->aligned[i];
1772 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1774 aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1775 if (aligned_cost < verbatim_cost)
1776 return LZX_BLOCKTYPE_ALIGNED;
1778 return LZX_BLOCKTYPE_VERBATIM;
1781 /* Find a near-optimal sequence of matches/literals with which to output the
1782 * specified LZX block, then set the block's type to that which has the minimum
1783 * cost to output (either verbatim or aligned). */
1785 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1786 unsigned num_passes)
1788 const struct lzx_lru_queue orig_queue = ctx->queue;
1789 unsigned num_passes_remaining = num_passes;
1790 struct lzx_freqs freqs;
1792 LZX_ASSERT(num_passes >= 1);
1793 LZX_ASSERT(lz_bt_get_position(&ctx->mf) == spec->window_pos);
1795 ctx->match_window_end = spec->window_pos + spec->block_size;
1796 spec->chosen_matches = &ctx->chosen_matches[spec->window_pos];
1797 ctx->matches_cached = false;
1799 /* The first optimal parsing pass is done using the cost model already
1800 * set in ctx->costs. Each later pass is done using a cost model
1801 * computed from the previous pass. */
1803 const u8 *window_ptr;
1804 const u8 *window_end;
1805 struct lzx_match *next_chosen_match;
1807 --num_passes_remaining;
1808 ctx->match_window_pos = spec->window_pos;
1809 ctx->cache_ptr = ctx->cached_matches;
1810 memset(&freqs, 0, sizeof(freqs));
1811 window_ptr = &ctx->window[spec->window_pos];
1812 window_end = window_ptr + spec->block_size;
1813 next_chosen_match = spec->chosen_matches;
1815 while (window_ptr != window_end) {
1816 struct raw_match raw_match;
1817 struct lzx_match lzx_match;
1819 raw_match = lzx_get_near_optimal_match(ctx);
1821 LZX_ASSERT(!(raw_match.len == LZX_MIN_MATCH_LEN &&
1822 raw_match.offset == ctx->max_window_size -
1823 LZX_MIN_MATCH_LEN));
1824 if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1825 lzx_match.data = lzx_tally_match(raw_match.len,
1829 window_ptr += raw_match.len;
1831 lzx_match.data = lzx_tally_literal(*window_ptr,
1835 *next_chosen_match++ = lzx_match;
1837 spec->num_chosen_matches = next_chosen_match - spec->chosen_matches;
1838 lzx_make_huffman_codes(&freqs, &spec->codes, ctx->num_main_syms);
1839 if (num_passes_remaining) {
1840 lzx_set_costs(ctx, &spec->codes.lens);
1841 ctx->queue = orig_queue;
1842 ctx->matches_cached = true;
1844 } while (num_passes_remaining);
1846 spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1849 /* Prepare the input window into one or more LZX blocks ready to be output. */
1851 lzx_prepare_blocks(struct lzx_compressor * ctx)
1853 /* Set up a default cost model. */
1854 lzx_set_default_costs(&ctx->costs, ctx->num_main_syms);
1856 /* Set up the block specifications.
1857 * TODO: The compression ratio could be slightly improved by performing
1858 * data-dependent block splitting instead of using fixed-size blocks.
1859 * Doing so well is a computationally hard problem, however. */
1860 ctx->num_blocks = DIV_ROUND_UP(ctx->window_size, LZX_DIV_BLOCK_SIZE);
1861 for (unsigned i = 0; i < ctx->num_blocks; i++) {
1862 unsigned pos = LZX_DIV_BLOCK_SIZE * i;
1863 ctx->block_specs[i].window_pos = pos;
1864 ctx->block_specs[i].block_size = min(ctx->window_size - pos,
1865 LZX_DIV_BLOCK_SIZE);
1868 /* Load the window into the match-finder. */
1869 lz_bt_load_window(&ctx->mf, ctx->window, ctx->window_size);
1871 /* Determine sequence of matches/literals to output for each block. */
1872 lzx_lru_queue_init(&ctx->queue);
1873 ctx->optimum_cur_idx = 0;
1874 ctx->optimum_end_idx = 0;
1875 for (unsigned i = 0; i < ctx->num_blocks; i++) {
1876 lzx_optimize_block(ctx, &ctx->block_specs[i],
1877 ctx->params.alg_params.slow.num_optim_passes);
1882 * This is the fast version of lzx_prepare_blocks(). This version "quickly"
1883 * prepares a single compressed block containing the entire input. See the
1884 * description of the "Fast algorithm" at the beginning of this file for more
1887 * Input --- the preprocessed data:
1892 * Output --- the block specification and the corresponding match/literal data:
1894 * ctx->block_specs[]
1896 * ctx->chosen_matches[]
1899 lzx_prepare_block_fast(struct lzx_compressor * ctx)
1901 struct lzx_record_ctx record_ctx;
1902 struct lzx_block_spec *spec;
1904 /* Parameters to hash chain LZ match finder
1905 * (lazy with 1 match lookahead) */
1906 static const struct lz_params lzx_lz_params = {
1907 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
1908 * aren't worth choosing when using greedy or lazy parsing. */
1910 .max_match = LZX_MAX_MATCH_LEN,
1911 .max_offset = LZX_MAX_WINDOW_SIZE,
1912 .good_match = LZX_MAX_MATCH_LEN,
1913 .nice_match = LZX_MAX_MATCH_LEN,
1914 .max_chain_len = LZX_MAX_MATCH_LEN,
1915 .max_lazy_match = LZX_MAX_MATCH_LEN,
1919 /* Initialize symbol frequencies and match offset LRU queue. */
1920 memset(&record_ctx.freqs, 0, sizeof(struct lzx_freqs));
1921 lzx_lru_queue_init(&record_ctx.queue);
1922 record_ctx.matches = ctx->chosen_matches;
1924 /* Determine series of matches/literals to output. */
1925 lz_analyze_block(ctx->window,
1933 /* Set up block specification. */
1934 spec = &ctx->block_specs[0];
1935 spec->block_type = LZX_BLOCKTYPE_ALIGNED;
1936 spec->window_pos = 0;
1937 spec->block_size = ctx->window_size;
1938 spec->num_chosen_matches = (record_ctx.matches - ctx->chosen_matches);
1939 spec->chosen_matches = ctx->chosen_matches;
1940 lzx_make_huffman_codes(&record_ctx.freqs, &spec->codes,
1941 ctx->num_main_syms);
1942 ctx->num_blocks = 1;
1946 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
1947 void *compressed_data, size_t compressed_size_avail, void *_ctx)
1949 struct lzx_compressor *ctx = _ctx;
1950 struct output_bitstream ostream;
1951 size_t compressed_size;
1953 if (uncompressed_size < 100) {
1954 LZX_DEBUG("Too small to bother compressing.");
1958 if (uncompressed_size > ctx->max_window_size) {
1959 LZX_DEBUG("Can't compress %zu bytes using window of %u bytes!",
1960 uncompressed_size, ctx->max_window_size);
1964 LZX_DEBUG("Attempting to compress %zu bytes...",
1967 /* The input data must be preprocessed. To avoid changing the original
1968 * input, copy it to a temporary buffer. */
1969 memcpy(ctx->window, uncompressed_data, uncompressed_size);
1970 ctx->window_size = uncompressed_size;
1972 /* This line is unnecessary; it just avoids inconsequential accesses of
1973 * uninitialized memory that would show up in memory-checking tools such
1975 memset(&ctx->window[ctx->window_size], 0, 12);
1977 LZX_DEBUG("Preprocessing data...");
1979 /* Before doing any actual compression, do the call instruction (0xe8
1980 * byte) translation on the uncompressed data. */
1981 lzx_do_e8_preprocessing(ctx->window, ctx->window_size);
1983 LZX_DEBUG("Preparing blocks...");
1985 /* Prepare the compressed data. */
1986 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
1987 lzx_prepare_block_fast(ctx);
1989 lzx_prepare_blocks(ctx);
1991 LZX_DEBUG("Writing compressed blocks...");
1993 /* Generate the compressed data. */
1994 init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
1995 lzx_write_all_blocks(ctx, &ostream);
1997 LZX_DEBUG("Flushing bitstream...");
1998 compressed_size = flush_output_bitstream(&ostream);
1999 if (compressed_size == ~(input_idx_t)0) {
2000 LZX_DEBUG("Data did not compress to %zu bytes or less!",
2001 compressed_size_avail);
2005 LZX_DEBUG("Done: compressed %zu => %zu bytes.",
2006 uncompressed_size, compressed_size);
2008 /* Verify that we really get the same thing back when decompressing.
2009 * Although this could be disabled by default in all cases, it only
2010 * takes around 2-3% of the running time of the slow algorithm to do the
2012 if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2013 #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2018 struct wimlib_decompressor *decompressor;
2020 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZX,
2021 ctx->max_window_size,
2026 ret = wimlib_decompress(compressed_data,
2031 wimlib_free_decompressor(decompressor);
2034 ERROR("Failed to decompress data we "
2035 "compressed using LZX algorithm");
2039 if (memcmp(uncompressed_data, ctx->window, uncompressed_size)) {
2040 ERROR("Data we compressed using LZX algorithm "
2041 "didn't decompress to original");
2046 WARNING("Failed to create decompressor for "
2047 "data verification!");
2050 return compressed_size;
2054 lzx_free_compressor(void *_ctx)
2056 struct lzx_compressor *ctx = _ctx;
2059 FREE(ctx->chosen_matches);
2060 FREE(ctx->cached_matches);
2062 lz_bt_destroy(&ctx->mf);
2063 FREE(ctx->block_specs);
2064 FREE(ctx->prev_tab);
2070 static const struct wimlib_lzx_compressor_params lzx_fast_default = {
2072 .size = sizeof(struct wimlib_lzx_compressor_params),
2074 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2081 static const struct wimlib_lzx_compressor_params lzx_slow_default = {
2083 .size = sizeof(struct wimlib_lzx_compressor_params),
2085 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2089 .use_len2_matches = 1,
2090 .nice_match_length = 32,
2091 .num_optim_passes = 2,
2092 .max_search_depth = 50,
2093 .main_nostat_cost = 15,
2094 .len_nostat_cost = 15,
2095 .aligned_nostat_cost = 7,
2100 static const struct wimlib_lzx_compressor_params *
2101 lzx_get_params(const struct wimlib_compressor_params_header *_params)
2103 const struct wimlib_lzx_compressor_params *params =
2104 (const struct wimlib_lzx_compressor_params*)_params;
2106 if (params == NULL) {
2107 LZX_DEBUG("Using default algorithm and parameters.");
2108 params = &lzx_slow_default;
2110 if (params->use_defaults) {
2111 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2112 params = &lzx_slow_default;
2114 params = &lzx_fast_default;
2121 lzx_create_compressor(size_t window_size,
2122 const struct wimlib_compressor_params_header *_params,
2125 const struct wimlib_lzx_compressor_params *params = lzx_get_params(_params);
2126 struct lzx_compressor *ctx;
2128 LZX_DEBUG("Allocating LZX context...");
2130 if (!lzx_window_size_valid(window_size))
2131 return WIMLIB_ERR_INVALID_PARAM;
2133 LZX_DEBUG("Allocating memory.");
2135 ctx = CALLOC(1, sizeof(struct lzx_compressor));
2139 ctx->num_main_syms = lzx_get_num_main_syms(window_size);
2140 ctx->max_window_size = window_size;
2141 ctx->window = MALLOC(window_size + 12);
2142 if (ctx->window == NULL)
2145 if (params->algorithm == WIMLIB_LZX_ALGORITHM_FAST) {
2146 ctx->prev_tab = MALLOC(window_size * sizeof(ctx->prev_tab[0]));
2147 if (ctx->prev_tab == NULL)
2151 size_t block_specs_length = DIV_ROUND_UP(window_size, LZX_DIV_BLOCK_SIZE);
2152 ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2153 if (ctx->block_specs == NULL)
2156 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2157 unsigned min_match_len = LZX_MIN_MATCH_LEN;
2158 if (!params->alg_params.slow.use_len2_matches)
2159 min_match_len = max(min_match_len, 3);
2161 if (!lz_bt_init(&ctx->mf,
2165 params->alg_params.slow.nice_match_length,
2166 params->alg_params.slow.max_search_depth))
2170 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2171 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE +
2172 min(params->alg_params.slow.nice_match_length,
2173 LZX_MAX_MATCH_LEN)) *
2174 sizeof(ctx->optimum[0]));
2179 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2180 ctx->cached_matches = MALLOC(LZX_CACHE_SIZE);
2181 if (ctx->cached_matches == NULL)
2183 ctx->cache_limit = ctx->cached_matches +
2184 LZX_CACHE_LEN - (LZX_MAX_MATCHES_PER_POS + 1);
2187 ctx->chosen_matches = MALLOC(window_size * sizeof(ctx->chosen_matches[0]));
2188 if (ctx->chosen_matches == NULL)
2191 memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_compressor_params));
2192 memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2194 LZX_DEBUG("Successfully allocated new LZX context.");
2200 lzx_free_compressor(ctx);
2201 return WIMLIB_ERR_NOMEM;
2205 lzx_get_needed_memory(size_t max_block_size,
2206 const struct wimlib_compressor_params_header *_params)
2208 const struct wimlib_lzx_compressor_params *params = lzx_get_params(_params);
2212 size += sizeof(struct lzx_compressor);
2214 size += max_block_size + 12;
2216 size += DIV_ROUND_UP(max_block_size, LZX_DIV_BLOCK_SIZE) *
2217 sizeof(((struct lzx_compressor*)0)->block_specs[0]);
2219 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2220 size += max_block_size * sizeof(((struct lzx_compressor*)0)->chosen_matches[0]);
2221 size += lz_bt_get_needed_memory(max_block_size);
2222 size += (LZX_OPTIM_ARRAY_SIZE +
2223 min(params->alg_params.slow.nice_match_length,
2224 LZX_MAX_MATCH_LEN)) *
2225 sizeof(((struct lzx_compressor *)0)->optimum[0]);
2226 size += LZX_CACHE_SIZE;
2228 size += max_block_size * sizeof(((struct lzx_compressor*)0)->prev_tab[0]);
2234 lzx_params_valid(const struct wimlib_compressor_params_header *_params)
2236 const struct wimlib_lzx_compressor_params *params =
2237 (const struct wimlib_lzx_compressor_params*)_params;
2239 if (params->hdr.size != sizeof(struct wimlib_lzx_compressor_params)) {
2240 LZX_DEBUG("Invalid parameter structure size!");
2244 if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2245 params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2247 LZX_DEBUG("Invalid algorithm.");
2251 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW &&
2252 !params->use_defaults)
2254 if (params->alg_params.slow.num_optim_passes < 1)
2256 LZX_DEBUG("Invalid number of optimization passes!");
2260 if (params->alg_params.slow.main_nostat_cost < 1 ||
2261 params->alg_params.slow.main_nostat_cost > 16)
2263 LZX_DEBUG("Invalid main_nostat_cost!");
2267 if (params->alg_params.slow.len_nostat_cost < 1 ||
2268 params->alg_params.slow.len_nostat_cost > 16)
2270 LZX_DEBUG("Invalid len_nostat_cost!");
2274 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2275 params->alg_params.slow.aligned_nostat_cost > 8)
2277 LZX_DEBUG("Invalid aligned_nostat_cost!");
2284 const struct compressor_ops lzx_compressor_ops = {
2285 .params_valid = lzx_params_valid,
2286 .get_needed_memory = lzx_get_needed_memory,
2287 .create_compressor = lzx_create_compressor,
2288 .compress = lzx_compress,
2289 .free_compressor = lzx_free_compressor,