]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
lz_optimal.h: Cleanup, better comments
[wimlib] / src / lzx-compress.c
1 /*
2  * lzx-compress.c
3  *
4  * LZX compression routines
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
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)
15  * any later version.
16  *
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
20  * details.
21  *
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/.
24  */
25
26
27 /*
28  * This file contains a compressor for the LZX compression format, as used in
29  * the WIM file format.
30  *
31  * Format
32  * ======
33  *
34  * First, the primary reference for the LZX compression format is the
35  * specification released by Microsoft.
36  *
37  * Second, the comments in lzx-decompress.c provide some more information about
38  * the LZX compression format, including errors in the Microsoft specification.
39  *
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:
44  *
45  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
46  *   compressible before attempting to compress it further.
47  * - LZX uses a "main" alphabet which combines literals and matches, with the
48  *   match symbols containing a "length header" (giving all or part of the match
49  *   length) and a "position slot" (giving, roughly speaking, the order of
50  *   magnitude of the match offset).
51  * - LZX does not have static Huffman blocks; however it does have two types of
52  *   dynamic Huffman blocks ("aligned offset" and "verbatim").
53  * - LZX has a minimum match length of 2 rather than 3.
54  * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
55  *   queue of match offsets.  This is very useful for certain types of files,
56  *   such as binary files that have repeating records.
57  *
58  * Algorithms
59  * ==========
60  *
61  * There are actually two distinct overall algorithms implemented here.  We
62  * shall refer to them as the "slow" algorithm and the "fast" algorithm.  The
63  * "slow" algorithm spends more time compressing to achieve a higher compression
64  * ratio compared to the "fast" algorithm.  More details are presented below.
65  *
66  * Slow algorithm
67  * --------------
68  *
69  * The "slow" algorithm to generate LZX-compressed data is roughly as follows:
70  *
71  * 1. Preprocess the input data to translate the targets of x86 call
72  *    instructions to absolute offsets.
73  *
74  * 2. Build the suffix array and inverse suffix array for the input data.  The
75  *    suffix array contains the indices of all suffixes of the input data,
76  *    sorted lexcographically by the corresponding suffixes.  The "position" of
77  *    a suffix is the index of that suffix in the original string, whereas the
78  *    "rank" of a suffix is the index at which that suffix's position is found
79  *    in the suffix array.
80  *
81  * 3. Build the longest common prefix array corresponding to the suffix array.
82  *
83  * 4. For each suffix, find the highest lower ranked suffix that has a lower
84  *    position, the lowest higher ranked suffix that has a lower position, and
85  *    the length of the common prefix shared between each.   This information is
86  *    later used to link suffix ranks into a doubly-linked list for searching
87  *    the suffix array.
88  *
89  * 5. Set a default cost model for matches/literals.
90  *
91  * 6. Determine the lowest cost sequence of LZ77 matches ((offset, length)
92  *    pairs) and literal bytes to divide the input into.  Raw match-finding is
93  *    done by searching the suffix array using a linked list to avoid
94  *    considering any suffixes that start after the current position.  Each run
95  *    of the match-finder returns the approximate lowest-cost longest match as
96  *    well as any shorter matches that have even lower approximate costs.  Each
97  *    such run also adds the suffix rank of the current position into the linked
98  *    list being used to search the suffix array.  Parsing, or match-choosing,
99  *    is solved as a minimum-cost path problem using a forward "optimal parsing"
100  *    algorithm based on the Deflate encoder from 7-Zip.  This algorithm moves
101  *    forward calculating the minimum cost to reach each byte until either a
102  *    very long match is found or until a position is found at which no matches
103  *    start or overlap.
104  *
105  * 7. Build the Huffman codes needed to output the matches/literals.
106  *
107  * 8. Up to a certain number of iterations, use the resulting Huffman codes to
108  *    refine a cost model and go back to Step #6 to determine an improved
109  *    sequence of matches and literals.
110  *
111  * 9. Output the resulting block using the match/literal sequences and the
112  *    Huffman codes that were computed for the block.
113  *
114  * Note: the algorithm does not yet attempt to split the input into multiple LZX
115  * blocks, instead using a series of blocks of LZX_DIV_BLOCK_SIZE bytes.
116  *
117  * Fast algorithm
118  * --------------
119  *
120  * The fast algorithm (and the only one available in wimlib v1.5.1 and earlier)
121  * spends much less time on the main bottlenecks of the compression process ---
122  * that is, the match finding and match choosing.  Matches are found and chosen
123  * with hash chains using a greedy parse with one position of look-ahead.  No
124  * block splitting is done; only compressing the full input into an aligned
125  * offset block is considered.
126  *
127  * Acknowledgments
128  * ===============
129  *
130  * Acknowledgments to several open-source projects and research papers that made
131  * it possible to implement this code:
132  *
133  * - divsufsort (author: Yuta Mori), for the suffix array construction code,
134  *   located in a separate directory (divsufsort/).
135  *
136  * - "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its
137  *   Applications" (Kasai et al. 2001), for the LCP array computation.
138  *
139  * - "LPF computation revisited" (Crochemore et al. 2009) for the prev and next
140  *   array computations.
141  *
142  * - 7-Zip (author: Igor Pavlov) for the algorithm for forward optimal parsing
143  *   (match-choosing).
144  *
145  * - zlib (author: Jean-loup Gailly and Mark Adler), for the hash table
146  *   match-finding algorithm (used in lz77.c).
147  *
148  * - lzx-compress (author: Matthew T. Russotto), on which some parts of this
149  *   code were originally based.
150  */
151
152 #ifdef HAVE_CONFIG_H
153 #  include "config.h"
154 #endif
155
156 #include "wimlib.h"
157 #include "wimlib/compressor_ops.h"
158 #include "wimlib/compress_common.h"
159 #include "wimlib/endianness.h"
160 #include "wimlib/error.h"
161 #include "wimlib/lz_hash.h"
162 #include "wimlib/lz_sarray.h"
163 #include "wimlib/lzx.h"
164 #include "wimlib/util.h"
165 #include <pthread.h>
166 #include <math.h>
167 #include <string.h>
168
169 #ifdef ENABLE_LZX_DEBUG
170 #  include "wimlib/decompress_common.h"
171 #endif
172
173 typedef u32 block_cost_t;
174 #define INFINITE_BLOCK_COST     (~(block_cost_t)0)
175
176 #define LZX_OPTIM_ARRAY_SIZE    4096
177
178 #define LZX_DIV_BLOCK_SIZE      32768
179
180 #define LZX_MAX_CACHE_PER_POS   10
181
182 /* Codewords for the LZX main, length, and aligned offset Huffman codes  */
183 struct lzx_codewords {
184         u16 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
185         u16 len[LZX_LENCODE_NUM_SYMBOLS];
186         u16 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
187 };
188
189 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
190  * Huffman codes.
191  *
192  * A 0 length means the codeword has zero frequency.
193  */
194 struct lzx_lens {
195         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
196         u8 len[LZX_LENCODE_NUM_SYMBOLS];
197         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
198 };
199
200 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
201  *
202  * If a codeword has zero frequency, it must still be assigned some nonzero cost
203  * --- generally a high cost, since even if it gets used in the next iteration,
204  * it probably will not be used very times.  */
205 struct lzx_costs {
206         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
207         u8 len[LZX_LENCODE_NUM_SYMBOLS];
208         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
209 };
210
211 /* The LZX main, length, and aligned offset Huffman codes  */
212 struct lzx_codes {
213         struct lzx_codewords codewords;
214         struct lzx_lens lens;
215 };
216
217 /* Tables for tallying symbol frequencies in the three LZX alphabets  */
218 struct lzx_freqs {
219         input_idx_t main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
220         input_idx_t len[LZX_LENCODE_NUM_SYMBOLS];
221         input_idx_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
222 };
223
224 /* LZX intermediate match/literal format  */
225 struct lzx_match {
226         /* Bit     Description
227          *
228          * 31      1 if a match, 0 if a literal.
229          *
230          * 30-25   position slot.  This can be at most 50, so it will fit in 6
231          *         bits.
232          *
233          * 8-24    position footer.  This is the offset of the real formatted
234          *         offset from the position base.  This can be at most 17 bits
235          *         (since lzx_extra_bits[LZX_MAX_POSITION_SLOTS - 1] is 17).
236          *
237          * 0-7     length of match, minus 2.  This can be at most
238          *         (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits.  */
239         u32 data;
240 };
241
242 /* Specification for an LZX block.  */
243 struct lzx_block_spec {
244
245         /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
246          * block.  */
247         int block_type;
248
249         /* 0-based position in the window at which this block starts.  */
250         input_idx_t window_pos;
251
252         /* The number of bytes of uncompressed data this block represents.  */
253         input_idx_t block_size;
254
255         /* The position in the 'chosen_matches' array in the `struct
256          * lzx_compressor' at which the match/literal specifications for
257          * this block begin.  */
258         input_idx_t chosen_matches_start_pos;
259
260         /* The number of match/literal specifications for this block.  */
261         input_idx_t num_chosen_matches;
262
263         /* Huffman codes for this block.  */
264         struct lzx_codes codes;
265 };
266
267 /* Include template for the match-choosing algorithm.  */
268 #define LZ_COMPRESSOR           struct lzx_compressor
269 #define LZ_ADAPTIVE_STATE       struct lzx_lru_queue
270 struct lzx_compressor;
271 #include "wimlib/lz_optimal.h"
272
273 /* State of the LZX compressor.  */
274 struct lzx_compressor {
275
276         /* The parameters that were used to create the compressor.  */
277         struct wimlib_lzx_compressor_params params;
278
279         /* The buffer of data to be compressed.
280          *
281          * 0xe8 byte preprocessing is done directly on the data here before
282          * further compression.
283          *
284          * Note that this compressor does *not* use a real sliding window!!!!
285          * It's not needed in the WIM format, since every chunk is compressed
286          * independently.  This is by design, to allow random access to the
287          * chunks.
288          *
289          * We reserve a few extra bytes to potentially allow reading off the end
290          * of the array in the match-finding code for optimization purposes.
291          */
292         u8 *window;
293
294         /* Number of bytes of data to be compressed, which is the number of
295          * bytes of data in @window that are actually valid.  */
296         input_idx_t window_size;
297
298         /* Allocated size of the @window.  */
299         input_idx_t max_window_size;
300
301         /* Number of symbols in the main alphabet (depends on the
302          * @max_window_size since it determines the maximum allowed offset).  */
303         unsigned num_main_syms;
304
305         /* The current match offset LRU queue.  */
306         struct lzx_lru_queue queue;
307
308         /* Space for the sequences of matches/literals that were chosen for each
309          * block.  */
310         struct lzx_match *chosen_matches;
311
312         /* Information about the LZX blocks the preprocessed input was divided
313          * into.  */
314         struct lzx_block_spec *block_specs;
315
316         /* Number of LZX blocks the input was divided into; a.k.a. the number of
317          * elements of @block_specs that are valid.  */
318         unsigned num_blocks;
319
320         /* This is simply filled in with zeroes and used to avoid special-casing
321          * the output of the first compressed Huffman code, which conceptually
322          * has a delta taken from a code with all symbols having zero-length
323          * codewords.  */
324         struct lzx_codes zero_codes;
325
326         /* The current cost model.  */
327         struct lzx_costs costs;
328
329         /* Fast algorithm only:  Array of hash table links.  */
330         input_idx_t *prev_tab;
331
332         /* Slow algorithm only: Suffix array match-finder.  */
333         struct lz_sarray lz_sarray;
334
335         /* Position in window of next match to return.  */
336         input_idx_t match_window_pos;
337
338         /* The match-finder shall ensure the length of matches does not exceed
339          * this position in the input.  */
340         input_idx_t match_window_end;
341
342         /* Matches found by the match-finder are cached in the following array
343          * to achieve a slight speedup when the same matches are needed on
344          * subsequent passes.  This is suboptimal because different matches may
345          * be preferred with different cost models, but seems to be a worthwhile
346          * speedup.  */
347         struct raw_match *cached_matches;
348         unsigned cached_matches_pos;
349         bool matches_cached;
350
351         /* Match chooser.  */
352         struct lz_match_chooser mc;
353 };
354
355 /* Returns the LZX position slot that corresponds to a given match offset,
356  * taking into account the recent offset queue and updating it if the offset is
357  * found in it.  */
358 static unsigned
359 lzx_get_position_slot(unsigned offset, struct lzx_lru_queue *queue)
360 {
361         unsigned position_slot;
362
363         /* See if the offset was recently used.  */
364         for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
365                 if (offset == queue->R[i]) {
366                         /* Found it.  */
367
368                         /* Bring the repeat offset to the front of the
369                          * queue.  Note: this is, in fact, not a real
370                          * LRU queue because repeat matches are simply
371                          * swapped to the front.  */
372                         swap(queue->R[0], queue->R[i]);
373
374                         /* The resulting position slot is simply the first index
375                          * at which the offset was found in the queue.  */
376                         return i;
377                 }
378         }
379
380         /* The offset was not recently used; look up its real position slot.  */
381         position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
382
383         /* Bring the new offset to the front of the queue.  */
384         for (unsigned i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
385                 queue->R[i] = queue->R[i - 1];
386         queue->R[0] = offset;
387
388         return position_slot;
389 }
390
391 /* Build the main, length, and aligned offset Huffman codes used in LZX.
392  *
393  * This takes as input the frequency tables for each code and produces as output
394  * a set of tables that map symbols to codewords and codeword lengths.  */
395 static void
396 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
397                        struct lzx_codes *codes,
398                        unsigned num_main_syms)
399 {
400         make_canonical_huffman_code(num_main_syms,
401                                     LZX_MAX_MAIN_CODEWORD_LEN,
402                                     freqs->main,
403                                     codes->lens.main,
404                                     codes->codewords.main);
405
406         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
407                                     LZX_MAX_LEN_CODEWORD_LEN,
408                                     freqs->len,
409                                     codes->lens.len,
410                                     codes->codewords.len);
411
412         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
413                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
414                                     freqs->aligned,
415                                     codes->lens.aligned,
416                                     codes->codewords.aligned);
417 }
418
419 /*
420  * Output an LZX match.
421  *
422  * @out:         The bitstream to write the match to.
423  * @block_type:  The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
424  * @match:       The match.
425  * @codes:       Pointer to a structure that contains the codewords for the
426  *               main, length, and aligned offset Huffman codes.
427  */
428 static void
429 lzx_write_match(struct output_bitstream *out, int block_type,
430                 struct lzx_match match, const struct lzx_codes *codes)
431 {
432         /* low 8 bits are the match length minus 2 */
433         unsigned match_len_minus_2 = match.data & 0xff;
434         /* Next 17 bits are the position footer */
435         unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
436         /* Next 6 bits are the position slot. */
437         unsigned position_slot = (match.data >> 25) & 0x3f;     /* 6 bits */
438         unsigned len_header;
439         unsigned len_footer;
440         unsigned main_symbol;
441         unsigned num_extra_bits;
442         unsigned verbatim_bits;
443         unsigned aligned_bits;
444
445         /* If the match length is less than MIN_MATCH_LEN (= 2) +
446          * NUM_PRIMARY_LENS (= 7), the length header contains
447          * the match length minus MIN_MATCH_LEN, and there is no
448          * length footer.
449          *
450          * Otherwise, the length header contains
451          * NUM_PRIMARY_LENS, and the length footer contains
452          * the match length minus NUM_PRIMARY_LENS minus
453          * MIN_MATCH_LEN. */
454         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
455                 len_header = match_len_minus_2;
456                 /* No length footer-- mark it with a special
457                  * value. */
458                 len_footer = (unsigned)(-1);
459         } else {
460                 len_header = LZX_NUM_PRIMARY_LENS;
461                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
462         }
463
464         /* Combine the position slot with the length header into a single symbol
465          * that will be encoded with the main code.
466          *
467          * The actual main symbol is offset by LZX_NUM_CHARS because values
468          * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
469          * match.  */
470         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
471
472         /* Output main symbol. */
473         bitstream_put_bits(out, codes->codewords.main[main_symbol],
474                            codes->lens.main[main_symbol]);
475
476         /* If there is a length footer, output it using the
477          * length Huffman code. */
478         if (len_footer != (unsigned)(-1)) {
479                 bitstream_put_bits(out, codes->codewords.len[len_footer],
480                                    codes->lens.len[len_footer]);
481         }
482
483         num_extra_bits = lzx_get_num_extra_bits(position_slot);
484
485         /* For aligned offset blocks with at least 3 extra bits, output the
486          * verbatim bits literally, then the aligned bits encoded using the
487          * aligned offset code.  Otherwise, only the verbatim bits need to be
488          * output. */
489         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
490
491                 verbatim_bits = position_footer >> 3;
492                 bitstream_put_bits(out, verbatim_bits,
493                                    num_extra_bits - 3);
494
495                 aligned_bits = (position_footer & 7);
496                 bitstream_put_bits(out,
497                                    codes->codewords.aligned[aligned_bits],
498                                    codes->lens.aligned[aligned_bits]);
499         } else {
500                 /* verbatim bits is the same as the position
501                  * footer, in this case. */
502                 bitstream_put_bits(out, position_footer, num_extra_bits);
503         }
504 }
505
506 static unsigned
507 lzx_build_precode(const u8 lens[restrict],
508                   const u8 prev_lens[restrict],
509                   const unsigned num_syms,
510                   input_idx_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
511                   u8 output_syms[restrict num_syms],
512                   u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
513                   u16 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
514                   unsigned *num_additional_bits_ret)
515 {
516         memset(precode_freqs, 0,
517                LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
518
519         /* Since the code word lengths use a form of RLE encoding, the goal here
520          * is to find each run of identical lengths when going through them in
521          * symbol order (including runs of length 1).  For each run, as many
522          * lengths are encoded using RLE as possible, and the rest are output
523          * literally.
524          *
525          * output_syms[] will be filled in with the length symbols that will be
526          * output, including RLE codes, not yet encoded using the precode.
527          *
528          * cur_run_len keeps track of how many code word lengths are in the
529          * current run of identical lengths.  */
530         unsigned output_syms_idx = 0;
531         unsigned cur_run_len = 1;
532         unsigned num_additional_bits = 0;
533         for (unsigned i = 1; i <= num_syms; i++) {
534
535                 if (i != num_syms && lens[i] == lens[i - 1]) {
536                         /* Still in a run--- keep going. */
537                         cur_run_len++;
538                         continue;
539                 }
540
541                 /* Run ended! Check if it is a run of zeroes or a run of
542                  * nonzeroes. */
543
544                 /* The symbol that was repeated in the run--- not to be confused
545                  * with the length *of* the run (cur_run_len) */
546                 unsigned len_in_run = lens[i - 1];
547
548                 if (len_in_run == 0) {
549                         /* A run of 0's.  Encode it in as few length
550                          * codes as we can. */
551
552                         /* The magic length 18 indicates a run of 20 + n zeroes,
553                          * where n is an uncompressed literal 5-bit integer that
554                          * follows the magic length. */
555                         while (cur_run_len >= 20) {
556                                 unsigned additional_bits;
557
558                                 additional_bits = min(cur_run_len - 20, 0x1f);
559                                 num_additional_bits += 5;
560                                 precode_freqs[18]++;
561                                 output_syms[output_syms_idx++] = 18;
562                                 output_syms[output_syms_idx++] = additional_bits;
563                                 cur_run_len -= 20 + additional_bits;
564                         }
565
566                         /* The magic length 17 indicates a run of 4 + n zeroes,
567                          * where n is an uncompressed literal 4-bit integer that
568                          * follows the magic length. */
569                         while (cur_run_len >= 4) {
570                                 unsigned additional_bits;
571
572                                 additional_bits = min(cur_run_len - 4, 0xf);
573                                 num_additional_bits += 4;
574                                 precode_freqs[17]++;
575                                 output_syms[output_syms_idx++] = 17;
576                                 output_syms[output_syms_idx++] = additional_bits;
577                                 cur_run_len -= 4 + additional_bits;
578                         }
579
580                 } else {
581
582                         /* A run of nonzero lengths. */
583
584                         /* The magic length 19 indicates a run of 4 + n
585                          * nonzeroes, where n is a literal bit that follows the
586                          * magic length, and where the value of the lengths in
587                          * the run is given by an extra length symbol, encoded
588                          * with the precode, that follows the literal bit.
589                          *
590                          * The extra length symbol is encoded as a difference
591                          * from the length of the codeword for the first symbol
592                          * in the run in the previous code.
593                          * */
594                         while (cur_run_len >= 4) {
595                                 unsigned additional_bits;
596                                 signed char delta;
597
598                                 additional_bits = (cur_run_len > 4);
599                                 num_additional_bits += 1;
600                                 delta = (signed char)prev_lens[i - cur_run_len] -
601                                         (signed char)len_in_run;
602                                 if (delta < 0)
603                                         delta += 17;
604                                 precode_freqs[19]++;
605                                 precode_freqs[(unsigned char)delta]++;
606                                 output_syms[output_syms_idx++] = 19;
607                                 output_syms[output_syms_idx++] = additional_bits;
608                                 output_syms[output_syms_idx++] = delta;
609                                 cur_run_len -= 4 + additional_bits;
610                         }
611                 }
612
613                 /* Any remaining lengths in the run are outputted without RLE,
614                  * as a difference from the length of that codeword in the
615                  * previous code. */
616                 while (cur_run_len > 0) {
617                         signed char delta;
618
619                         delta = (signed char)prev_lens[i - cur_run_len] -
620                                 (signed char)len_in_run;
621                         if (delta < 0)
622                                 delta += 17;
623
624                         precode_freqs[(unsigned char)delta]++;
625                         output_syms[output_syms_idx++] = delta;
626                         cur_run_len--;
627                 }
628
629                 cur_run_len = 1;
630         }
631
632         /* Build the precode from the frequencies of the length symbols. */
633
634         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
635                                     LZX_MAX_PRE_CODEWORD_LEN,
636                                     precode_freqs, precode_lens,
637                                     precode_codewords);
638
639         *num_additional_bits_ret = num_additional_bits;
640
641         return output_syms_idx;
642 }
643
644 /*
645  * Writes a compressed Huffman code to the output, preceded by the precode for
646  * it.
647  *
648  * The Huffman code is represented in the output as a series of path lengths
649  * from which the canonical Huffman code can be reconstructed.  The path lengths
650  * themselves are compressed using a separate Huffman code, the precode, which
651  * consists of LZX_PRECODE_NUM_SYMBOLS (= 20) symbols that cover all possible
652  * code lengths, plus extra codes for repeated lengths.  The path lengths of the
653  * precode precede the path lengths of the larger code and are uncompressed,
654  * consisting of 20 entries of 4 bits each.
655  *
656  * @out:                Bitstream to write the code to.
657  * @lens:               The code lengths for the Huffman code, indexed by symbol.
658  * @prev_lens:          Code lengths for this Huffman code, indexed by symbol,
659  *                      in the *previous block*, or all zeroes if this is the
660  *                      first block.
661  * @num_syms:           The number of symbols in the code.
662  */
663 static void
664 lzx_write_compressed_code(struct output_bitstream *out,
665                           const u8 lens[restrict],
666                           const u8 prev_lens[restrict],
667                           unsigned num_syms)
668 {
669         input_idx_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
670         u8 output_syms[num_syms];
671         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
672         u16 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
673         unsigned i;
674         unsigned num_output_syms;
675         u8 precode_sym;
676         unsigned dummy;
677
678         num_output_syms = lzx_build_precode(lens,
679                                             prev_lens,
680                                             num_syms,
681                                             precode_freqs,
682                                             output_syms,
683                                             precode_lens,
684                                             precode_codewords,
685                                             &dummy);
686
687         /* Write the lengths of the precode codes to the output. */
688         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
689                 bitstream_put_bits(out, precode_lens[i],
690                                    LZX_PRECODE_ELEMENT_SIZE);
691
692         /* Write the length symbols, encoded with the precode, to the output. */
693
694         for (i = 0; i < num_output_syms; ) {
695                 precode_sym = output_syms[i++];
696
697                 bitstream_put_bits(out, precode_codewords[precode_sym],
698                                    precode_lens[precode_sym]);
699                 switch (precode_sym) {
700                 case 17:
701                         bitstream_put_bits(out, output_syms[i++], 4);
702                         break;
703                 case 18:
704                         bitstream_put_bits(out, output_syms[i++], 5);
705                         break;
706                 case 19:
707                         bitstream_put_bits(out, output_syms[i++], 1);
708                         bitstream_put_bits(out,
709                                            precode_codewords[output_syms[i]],
710                                            precode_lens[output_syms[i]]);
711                         i++;
712                         break;
713                 default:
714                         break;
715                 }
716         }
717 }
718
719 /*
720  * Writes all compressed matches and literal bytes in an LZX block to the the
721  * output bitstream.
722  *
723  * @ostream
724  *      The output bitstream.
725  * @block_type
726  *      The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM).
727  * @match_tab
728  *      The array of matches/literals that will be output (length @match_count).
729  * @match_count
730  *      Number of matches/literals to be output.
731  * @codes
732  *      Pointer to a structure that contains the codewords for the main, length,
733  *      and aligned offset Huffman codes.
734  */
735 static void
736 lzx_write_matches_and_literals(struct output_bitstream *ostream,
737                                int block_type,
738                                const struct lzx_match match_tab[],
739                                unsigned match_count,
740                                const struct lzx_codes *codes)
741 {
742         for (unsigned i = 0; i < match_count; i++) {
743                 struct lzx_match match = match_tab[i];
744
745                 /* High bit of the match indicates whether the match is an
746                  * actual match (1) or a literal uncompressed byte (0)  */
747                 if (match.data & 0x80000000) {
748                         /* match */
749                         lzx_write_match(ostream, block_type,
750                                         match, codes);
751                 } else {
752                         /* literal byte */
753                         bitstream_put_bits(ostream,
754                                            codes->codewords.main[match.data],
755                                            codes->lens.main[match.data]);
756                 }
757         }
758 }
759
760 static void
761 lzx_assert_codes_valid(const struct lzx_codes * codes, unsigned num_main_syms)
762 {
763 #ifdef ENABLE_LZX_DEBUG
764         unsigned i;
765
766         for (i = 0; i < num_main_syms; i++)
767                 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
768
769         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
770                 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
771
772         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
773                 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
774
775         const unsigned tablebits = 10;
776         u16 decode_table[(1 << tablebits) +
777                          (2 * max(num_main_syms, LZX_LENCODE_NUM_SYMBOLS))]
778                          _aligned_attribute(DECODE_TABLE_ALIGNMENT);
779         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
780                                                   num_main_syms,
781                                                   min(tablebits, LZX_MAINCODE_TABLEBITS),
782                                                   codes->lens.main,
783                                                   LZX_MAX_MAIN_CODEWORD_LEN));
784         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
785                                                   LZX_LENCODE_NUM_SYMBOLS,
786                                                   min(tablebits, LZX_LENCODE_TABLEBITS),
787                                                   codes->lens.len,
788                                                   LZX_MAX_LEN_CODEWORD_LEN));
789         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
790                                                   LZX_ALIGNEDCODE_NUM_SYMBOLS,
791                                                   min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
792                                                   codes->lens.aligned,
793                                                   LZX_MAX_ALIGNED_CODEWORD_LEN));
794 #endif /* ENABLE_LZX_DEBUG */
795 }
796
797 /* Write an LZX aligned offset or verbatim block to the output.  */
798 static void
799 lzx_write_compressed_block(int block_type,
800                            unsigned block_size,
801                            unsigned max_window_size,
802                            unsigned num_main_syms,
803                            struct lzx_match * chosen_matches,
804                            unsigned num_chosen_matches,
805                            const struct lzx_codes * codes,
806                            const struct lzx_codes * prev_codes,
807                            struct output_bitstream * ostream)
808 {
809         unsigned i;
810
811         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
812                    block_type == LZX_BLOCKTYPE_VERBATIM);
813         lzx_assert_codes_valid(codes, num_main_syms);
814
815         /* The first three bits indicate the type of block and are one of the
816          * LZX_BLOCKTYPE_* constants.  */
817         bitstream_put_bits(ostream, block_type, 3);
818
819         /* Output the block size.
820          *
821          * The original LZX format seemed to always encode the block size in 3
822          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
823          * uses the first bit to indicate whether the block is the default size
824          * (32768) or a different size given explicitly by the next 16 bits.
825          *
826          * By default, this compressor uses a window size of 32768 and therefore
827          * follows the WIMGAPI behavior.  However, this compressor also supports
828          * window sizes greater than 32768 bytes, which do not appear to be
829          * supported by WIMGAPI.  In such cases, we retain the default size bit
830          * to mean a size of 32768 bytes but output non-default block size in 24
831          * bits rather than 16.  The compatibility of this behavior is unknown
832          * because WIMs created with chunk size greater than 32768 can seemingly
833          * only be opened by wimlib anyway.  */
834         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
835                 bitstream_put_bits(ostream, 1, 1);
836         } else {
837                 bitstream_put_bits(ostream, 0, 1);
838
839                 if (max_window_size >= 65536)
840                         bitstream_put_bits(ostream, block_size >> 16, 8);
841
842                 bitstream_put_bits(ostream, block_size, 16);
843         }
844
845         /* Write out lengths of the main code. Note that the LZX specification
846          * incorrectly states that the aligned offset code comes after the
847          * length code, but in fact it is the very first code to be written
848          * (before the main code).  */
849         if (block_type == LZX_BLOCKTYPE_ALIGNED)
850                 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
851                         bitstream_put_bits(ostream, codes->lens.aligned[i],
852                                            LZX_ALIGNEDCODE_ELEMENT_SIZE);
853
854         LZX_DEBUG("Writing main code...");
855
856         /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
857          * the main code, which are the codewords for literal bytes.  */
858         lzx_write_compressed_code(ostream,
859                                   codes->lens.main,
860                                   prev_codes->lens.main,
861                                   LZX_NUM_CHARS);
862
863         /* Write the precode and lengths for the rest of the main code, which
864          * are the codewords for match headers.  */
865         lzx_write_compressed_code(ostream,
866                                   codes->lens.main + LZX_NUM_CHARS,
867                                   prev_codes->lens.main + LZX_NUM_CHARS,
868                                   num_main_syms - LZX_NUM_CHARS);
869
870         LZX_DEBUG("Writing length code...");
871
872         /* Write the precode and lengths for the length code.  */
873         lzx_write_compressed_code(ostream,
874                                   codes->lens.len,
875                                   prev_codes->lens.len,
876                                   LZX_LENCODE_NUM_SYMBOLS);
877
878         LZX_DEBUG("Writing matches and literals...");
879
880         /* Write the actual matches and literals.  */
881         lzx_write_matches_and_literals(ostream, block_type,
882                                        chosen_matches, num_chosen_matches,
883                                        codes);
884
885         LZX_DEBUG("Done writing block.");
886 }
887
888 /* Write out the LZX blocks that were computed.  */
889 static void
890 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
891 {
892
893         const struct lzx_codes *prev_codes = &ctx->zero_codes;
894         for (unsigned i = 0; i < ctx->num_blocks; i++) {
895                 const struct lzx_block_spec *spec = &ctx->block_specs[i];
896
897                 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
898                           i + 1, ctx->num_blocks,
899                           spec->block_type, spec->block_size,
900                           spec->num_chosen_matches);
901
902                 lzx_write_compressed_block(spec->block_type,
903                                            spec->block_size,
904                                            ctx->max_window_size,
905                                            ctx->num_main_syms,
906                                            &ctx->chosen_matches[spec->chosen_matches_start_pos],
907                                            spec->num_chosen_matches,
908                                            &spec->codes,
909                                            prev_codes,
910                                            ostream);
911
912                 prev_codes = &spec->codes;
913         }
914 }
915
916 /* Constructs an LZX match from a literal byte and updates the main code symbol
917  * frequencies.  */
918 static u32
919 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
920 {
921         freqs->main[lit]++;
922         return (u32)lit;
923 }
924
925 /* Constructs an LZX match from an offset and a length, and updates the LRU
926  * queue and the frequency of symbols in the main, length, and aligned offset
927  * alphabets.  The return value is a 32-bit number that provides the match in an
928  * intermediate representation documented below.  */
929 static u32
930 lzx_tally_match(unsigned match_len, unsigned match_offset,
931                 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
932 {
933         unsigned position_slot;
934         unsigned position_footer;
935         u32 len_header;
936         unsigned main_symbol;
937         unsigned len_footer;
938         unsigned adjusted_match_len;
939
940         LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
941
942         /* The match offset shall be encoded as a position slot (itself encoded
943          * as part of the main symbol) and a position footer.  */
944         position_slot = lzx_get_position_slot(match_offset, queue);
945         position_footer = (match_offset + LZX_OFFSET_OFFSET) &
946                                 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
947
948         /* The match length shall be encoded as a length header (itself encoded
949          * as part of the main symbol) and an optional length footer.  */
950         adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
951         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
952                 /* No length footer needed.  */
953                 len_header = adjusted_match_len;
954         } else {
955                 /* Length footer needed.  It will be encoded using the length
956                  * code.  */
957                 len_header = LZX_NUM_PRIMARY_LENS;
958                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
959                 freqs->len[len_footer]++;
960         }
961
962         /* Account for the main symbol.  */
963         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
964
965         freqs->main[main_symbol]++;
966
967         /* In an aligned offset block, 3 bits of the position footer are output
968          * as an aligned offset symbol.  Account for this, although we may
969          * ultimately decide to output the block as verbatim.  */
970
971         /* The following check is equivalent to:
972          *
973          * if (lzx_extra_bits[position_slot] >= 3)
974          *
975          * Note that this correctly excludes position slots that correspond to
976          * recent offsets.  */
977         if (position_slot >= 8)
978                 freqs->aligned[position_footer & 7]++;
979
980         /* Pack the position slot, position footer, and match length into an
981          * intermediate representation.  See `struct lzx_match' for details.
982          */
983         LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
984         LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
985         LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
986
987         LZX_ASSERT(position_slot      <= (1U << (31 - 25)) - 1);
988         LZX_ASSERT(position_footer    <= (1U << (25 -  8)) - 1);
989         LZX_ASSERT(adjusted_match_len <= (1U << (8  -  0)) - 1);
990         return 0x80000000 |
991                 (position_slot << 25) |
992                 (position_footer << 8) |
993                 (adjusted_match_len);
994 }
995
996 struct lzx_record_ctx {
997         struct lzx_freqs freqs;
998         struct lzx_lru_queue queue;
999         struct lzx_match *matches;
1000 };
1001
1002 static void
1003 lzx_record_match(unsigned len, unsigned offset, void *_ctx)
1004 {
1005         struct lzx_record_ctx *ctx = _ctx;
1006
1007         (ctx->matches++)->data = lzx_tally_match(len, offset, &ctx->freqs, &ctx->queue);
1008 }
1009
1010 static void
1011 lzx_record_literal(u8 lit, void *_ctx)
1012 {
1013         struct lzx_record_ctx *ctx = _ctx;
1014
1015         (ctx->matches++)->data = lzx_tally_literal(lit, &ctx->freqs);
1016 }
1017
1018 /* Returns the cost, in bits, to output a literal byte using the specified cost
1019  * model.  */
1020 static unsigned
1021 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1022 {
1023         return costs->main[c];
1024 }
1025
1026 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1027  * well as costs for the codewords in the main, length, and aligned Huffman
1028  * codes, return the approximate number of bits it will take to represent this
1029  * match in the compressed output.  Take into account the match offset LRU
1030  * queue and optionally update it.  */
1031 static unsigned
1032 lzx_match_cost(unsigned length, unsigned offset, const struct lzx_costs *costs,
1033                struct lzx_lru_queue *queue)
1034 {
1035         unsigned position_slot;
1036         unsigned len_header, main_symbol;
1037         unsigned cost = 0;
1038
1039         position_slot = lzx_get_position_slot(offset, queue);
1040
1041         len_header = min(length - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1042         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1043
1044         /* Account for main symbol.  */
1045         cost += costs->main[main_symbol];
1046
1047         /* Account for extra position information.  */
1048         unsigned num_extra_bits = lzx_get_num_extra_bits(position_slot);
1049         if (num_extra_bits >= 3) {
1050                 cost += num_extra_bits - 3;
1051                 cost += costs->aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1052         } else {
1053                 cost += num_extra_bits;
1054         }
1055
1056         /* Account for extra length information.  */
1057         if (len_header == LZX_NUM_PRIMARY_LENS)
1058                 cost += costs->len[length - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1059
1060         return cost;
1061
1062 }
1063
1064 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
1065  * Unlike lzx_match_cost() which does a true cost evaluation, this simply
1066  * prioritize matches based on their offset.  */
1067 static input_idx_t
1068 lzx_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_queue)
1069 {
1070         const struct lzx_lru_queue *queue = _queue;
1071
1072         /* It seems well worth it to take the time to give priority to recently
1073          * used offsets.  */
1074         for (input_idx_t i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
1075                 if (offset == queue->R[i])
1076                         return i;
1077
1078         return offset;
1079 }
1080
1081 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1082  * @lens.
1083  *
1084  * The cost model and codeword lengths are almost the same thing, but the
1085  * Huffman codewords with length 0 correspond to symbols with zero frequency
1086  * that still need to be assigned actual costs.  The specific values assigned
1087  * are arbitrary, but they should be fairly high (near the maximum codeword
1088  * length) to take into account the fact that uses of these symbols are expected
1089  * to be rare.  */
1090 static void
1091 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1092 {
1093         unsigned i;
1094         unsigned num_main_syms = ctx->num_main_syms;
1095
1096         /* Main code  */
1097         for (i = 0; i < num_main_syms; i++) {
1098                 ctx->costs.main[i] = lens->main[i];
1099                 if (ctx->costs.main[i] == 0)
1100                         ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1101         }
1102
1103         /* Length code  */
1104         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1105                 ctx->costs.len[i] = lens->len[i];
1106                 if (ctx->costs.len[i] == 0)
1107                         ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1108         }
1109
1110         /* Aligned offset code  */
1111         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1112                 ctx->costs.aligned[i] = lens->aligned[i];
1113                 if (ctx->costs.aligned[i] == 0)
1114                         ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1115         }
1116 }
1117
1118 /* Tell the match-finder to skip the specified number of bytes (@n) in the
1119  * input.  */
1120 static void
1121 lzx_lz_skip_bytes(struct lzx_compressor *ctx, input_idx_t n)
1122 {
1123         LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1124         if (ctx->matches_cached) {
1125                 ctx->match_window_pos += n;
1126                 while (n--) {
1127                         ctx->cached_matches_pos +=
1128                                 ctx->cached_matches[ctx->cached_matches_pos].len + 1;
1129                 }
1130         } else {
1131                 while (n--) {
1132                         ctx->cached_matches[ctx->cached_matches_pos++].len = 0;
1133                         lz_sarray_skip_position(&ctx->lz_sarray);
1134                         ctx->match_window_pos++;
1135                 }
1136                 LZX_ASSERT(lz_sarray_get_pos(&ctx->lz_sarray) == ctx->match_window_pos);
1137         }
1138 }
1139
1140 /* Retrieve a list of matches available at the next position in the input.
1141  *
1142  * The matches are written to ctx->matches in decreasing order of length, and
1143  * the return value is the number of matches found.  */
1144 static u32
1145 lzx_lz_get_matches_caching(struct lzx_compressor *ctx,
1146                            const struct lzx_lru_queue *queue,
1147                            struct raw_match **matches_ret)
1148 {
1149         u32 num_matches;
1150         struct raw_match *matches;
1151
1152         LZX_ASSERT(ctx->match_window_pos <= ctx->match_window_end);
1153
1154         matches = &ctx->cached_matches[ctx->cached_matches_pos + 1];
1155
1156         if (ctx->matches_cached) {
1157                 num_matches = matches[-1].len;
1158         } else {
1159                 LZX_ASSERT(lz_sarray_get_pos(&ctx->lz_sarray) == ctx->match_window_pos);
1160                 num_matches = lz_sarray_get_matches(&ctx->lz_sarray,
1161                                                     matches,
1162                                                     lzx_match_cost_fast,
1163                                                     queue);
1164                 matches[-1].len = num_matches;
1165         }
1166         ctx->cached_matches_pos += num_matches + 1;
1167         *matches_ret = matches;
1168
1169         /* Cap the length of returned matches to the number of bytes remaining,
1170          * if it is not the whole window.  */
1171         if (ctx->match_window_end < ctx->window_size) {
1172                 unsigned maxlen = ctx->match_window_end - ctx->match_window_pos;
1173                 for (u32 i = 0; i < num_matches; i++)
1174                         if (matches[i].len > maxlen)
1175                                 matches[i].len = maxlen;
1176         }
1177 #if 0
1178         fprintf(stderr, "Pos %u/%u: %u matches\n",
1179                 ctx->match_window_pos, ctx->match_window_end, num_matches);
1180         for (unsigned i = 0; i < num_matches; i++)
1181                 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1182 #endif
1183
1184 #ifdef ENABLE_LZX_DEBUG
1185         for (u32 i = 0; i < num_matches; i++) {
1186                 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1187                 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1188                 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1189                 LZX_ASSERT(matches[i].offset > 0);
1190                 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1191                 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1192                                    &ctx->window[ctx->match_window_pos - matches[i].offset],
1193                                    matches[i].len));
1194         }
1195 #endif
1196
1197         ctx->match_window_pos++;
1198         return num_matches;
1199 }
1200
1201 static u32
1202 lzx_get_prev_literal_cost(struct lzx_compressor *ctx,
1203                           struct lzx_lru_queue *queue)
1204 {
1205         return lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1206                                 &ctx->costs);
1207 }
1208
1209 static u32
1210 lzx_get_match_cost(struct lzx_compressor *ctx,
1211                    struct lzx_lru_queue *queue,
1212                    input_idx_t length, input_idx_t offset)
1213 {
1214         return lzx_match_cost(length, offset, &ctx->costs, queue);
1215 }
1216
1217 static struct raw_match
1218 lzx_lz_get_near_optimal_match(struct lzx_compressor *ctx)
1219 {
1220         return lz_get_near_optimal_match(&ctx->mc,
1221                                          lzx_lz_get_matches_caching,
1222                                          lzx_lz_skip_bytes,
1223                                          lzx_get_prev_literal_cost,
1224                                          lzx_get_match_cost,
1225                                          ctx,
1226                                          &ctx->queue);
1227 }
1228
1229 /*
1230  * Set default symbol costs.
1231  */
1232 static void
1233 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1234 {
1235         unsigned i;
1236
1237         /* Literal symbols  */
1238         for (i = 0; i < LZX_NUM_CHARS; i++)
1239                 costs->main[i] = 8;
1240
1241         /* Match header symbols  */
1242         for (; i < num_main_syms; i++)
1243                 costs->main[i] = 10;
1244
1245         /* Length symbols  */
1246         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1247                 costs->len[i] = 8;
1248
1249         /* Aligned offset symbols  */
1250         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1251                 costs->aligned[i] = 3;
1252 }
1253
1254 /* Given the frequencies of symbols in a compressed block and the corresponding
1255  * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1256  * aligned offset or verbatim block, respectively, will take fewer bits to
1257  * output.  */
1258 static int
1259 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1260                                const struct lzx_codes * codes)
1261 {
1262         unsigned aligned_cost = 0;
1263         unsigned verbatim_cost = 0;
1264
1265         /* Verbatim blocks have a constant 3 bits per position footer.  Aligned
1266          * offset blocks have an aligned offset symbol per position footer, plus
1267          * an extra 24 bits to output the lengths necessary to reconstruct the
1268          * aligned offset code itself.  */
1269         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1270                 verbatim_cost += 3 * freqs->aligned[i];
1271                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1272         }
1273         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1274         if (aligned_cost < verbatim_cost)
1275                 return LZX_BLOCKTYPE_ALIGNED;
1276         else
1277                 return LZX_BLOCKTYPE_VERBATIM;
1278 }
1279
1280 /* Find a near-optimal sequence of matches/literals with which to output the
1281  * specified LZX block, then set its type to that which has the minimum cost to
1282  * output.  */
1283 static void
1284 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1285                    unsigned num_passes)
1286 {
1287         const struct lzx_lru_queue orig_queue = ctx->queue;
1288         struct lzx_freqs freqs;
1289
1290         unsigned orig_window_pos = spec->window_pos;
1291         unsigned orig_cached_pos = ctx->cached_matches_pos;
1292
1293         LZX_ASSERT(ctx->match_window_pos == spec->window_pos);
1294
1295         ctx->match_window_end = spec->window_pos + spec->block_size;
1296         spec->chosen_matches_start_pos = spec->window_pos;
1297
1298         LZX_ASSERT(num_passes >= 1);
1299
1300         /* The first optimal parsing pass is done using the cost model already
1301          * set in ctx->costs.  Each later pass is done using a cost model
1302          * computed from the previous pass.  */
1303         for (unsigned pass = 0; pass < num_passes; pass++) {
1304
1305                 ctx->match_window_pos = orig_window_pos;
1306                 ctx->cached_matches_pos = orig_cached_pos;
1307                 ctx->queue = orig_queue;
1308                 spec->num_chosen_matches = 0;
1309                 memset(&freqs, 0, sizeof(freqs));
1310
1311                 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
1312                         struct raw_match raw_match;
1313                         struct lzx_match lzx_match;
1314
1315                         raw_match = lzx_lz_get_near_optimal_match(ctx);
1316                         if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1317                                 lzx_match.data = lzx_tally_match(raw_match.len, raw_match.offset,
1318                                                                  &freqs, &ctx->queue);
1319                                 i += raw_match.len;
1320                         } else {
1321                                 lzx_match.data = lzx_tally_literal(ctx->window[i], &freqs);
1322                                 i += 1;
1323                         }
1324                         ctx->chosen_matches[spec->chosen_matches_start_pos +
1325                                             spec->num_chosen_matches++] = lzx_match;
1326                 }
1327
1328                 lzx_make_huffman_codes(&freqs, &spec->codes,
1329                                        ctx->num_main_syms);
1330                 if (pass < num_passes - 1)
1331                         lzx_set_costs(ctx, &spec->codes.lens);
1332                 ctx->matches_cached = true;
1333         }
1334         spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1335         ctx->matches_cached = false;
1336 }
1337
1338 static void
1339 lzx_optimize_blocks(struct lzx_compressor *ctx)
1340 {
1341         lzx_lru_queue_init(&ctx->queue);
1342         lz_match_chooser_begin(&ctx->mc);
1343
1344         const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
1345
1346         for (unsigned i = 0; i < ctx->num_blocks; i++)
1347                 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
1348 }
1349
1350 /* Prepare the input window into one or more LZX blocks ready to be output.  */
1351 static void
1352 lzx_prepare_blocks(struct lzx_compressor * ctx)
1353 {
1354         /* Initialize the match-finder.  */
1355         lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
1356         ctx->cached_matches_pos = 0;
1357         ctx->matches_cached = false;
1358         ctx->match_window_pos = 0;
1359
1360         /* Set up a default cost model.  */
1361         lzx_set_default_costs(&ctx->costs, ctx->num_main_syms);
1362
1363         ctx->num_blocks = DIV_ROUND_UP(ctx->window_size, LZX_DIV_BLOCK_SIZE);
1364         for (unsigned i = 0; i < ctx->num_blocks; i++) {
1365                 unsigned pos = LZX_DIV_BLOCK_SIZE * i;
1366                 ctx->block_specs[i].window_pos = pos;
1367                 ctx->block_specs[i].block_size = min(ctx->window_size - pos, LZX_DIV_BLOCK_SIZE);
1368         }
1369
1370         /* Determine sequence of matches/literals to output for each block.  */
1371         lzx_optimize_blocks(ctx);
1372 }
1373
1374 /*
1375  * This is the fast version of lzx_prepare_blocks().  This version "quickly"
1376  * prepares a single compressed block containing the entire input.  See the
1377  * description of the "Fast algorithm" at the beginning of this file for more
1378  * information.
1379  *
1380  * Input ---  the preprocessed data:
1381  *
1382  *      ctx->window[]
1383  *      ctx->window_size
1384  *
1385  * Output --- the block specification and the corresponding match/literal data:
1386  *
1387  *      ctx->block_specs[]
1388  *      ctx->num_blocks
1389  *      ctx->chosen_matches[]
1390  */
1391 static void
1392 lzx_prepare_block_fast(struct lzx_compressor * ctx)
1393 {
1394         struct lzx_record_ctx record_ctx;
1395         struct lzx_block_spec *spec;
1396
1397         /* Parameters to hash chain LZ match finder
1398          * (lazy with 1 match lookahead)  */
1399         static const struct lz_params lzx_lz_params = {
1400                 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
1401                  * aren't worth choosing when using greedy or lazy parsing.  */
1402                 .min_match      = 3,
1403                 .max_match      = LZX_MAX_MATCH_LEN,
1404                 .max_offset     = LZX_MAX_WINDOW_SIZE,
1405                 .good_match     = LZX_MAX_MATCH_LEN,
1406                 .nice_match     = LZX_MAX_MATCH_LEN,
1407                 .max_chain_len  = LZX_MAX_MATCH_LEN,
1408                 .max_lazy_match = LZX_MAX_MATCH_LEN,
1409                 .too_far        = 4096,
1410         };
1411
1412         /* Initialize symbol frequencies and match offset LRU queue.  */
1413         memset(&record_ctx.freqs, 0, sizeof(struct lzx_freqs));
1414         lzx_lru_queue_init(&record_ctx.queue);
1415         record_ctx.matches = ctx->chosen_matches;
1416
1417         /* Determine series of matches/literals to output.  */
1418         lz_analyze_block(ctx->window,
1419                          ctx->window_size,
1420                          lzx_record_match,
1421                          lzx_record_literal,
1422                          &record_ctx,
1423                          &lzx_lz_params,
1424                          ctx->prev_tab);
1425
1426         /* Set up block specification.  */
1427         spec = &ctx->block_specs[0];
1428         spec->block_type = LZX_BLOCKTYPE_ALIGNED;
1429         spec->window_pos = 0;
1430         spec->block_size = ctx->window_size;
1431         spec->num_chosen_matches = (record_ctx.matches - ctx->chosen_matches);
1432         spec->chosen_matches_start_pos = 0;
1433         lzx_make_huffman_codes(&record_ctx.freqs, &spec->codes,
1434                                ctx->num_main_syms);
1435         ctx->num_blocks = 1;
1436 }
1437
1438 static void
1439 do_call_insn_translation(u32 *call_insn_target, int input_pos,
1440                          s32 file_size)
1441 {
1442         s32 abs_offset;
1443         s32 rel_offset;
1444
1445         rel_offset = le32_to_cpu(*call_insn_target);
1446         if (rel_offset >= -input_pos && rel_offset < file_size) {
1447                 if (rel_offset < file_size - input_pos) {
1448                         /* "good translation" */
1449                         abs_offset = rel_offset + input_pos;
1450                 } else {
1451                         /* "compensating translation" */
1452                         abs_offset = rel_offset - file_size;
1453                 }
1454                 *call_insn_target = cpu_to_le32(abs_offset);
1455         }
1456 }
1457
1458 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
1459  * See the comment above that function for more information.  */
1460 static void
1461 do_call_insn_preprocessing(u8 data[], int size)
1462 {
1463         for (int i = 0; i < size - 10; i++) {
1464                 if (data[i] == 0xe8) {
1465                         do_call_insn_translation((u32*)&data[i + 1], i,
1466                                                  LZX_WIM_MAGIC_FILESIZE);
1467                         i += 4;
1468                 }
1469         }
1470 }
1471
1472 static size_t
1473 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
1474              void *compressed_data, size_t compressed_size_avail, void *_ctx)
1475 {
1476         struct lzx_compressor *ctx = _ctx;
1477         struct output_bitstream ostream;
1478         size_t compressed_size;
1479
1480         if (uncompressed_size < 100) {
1481                 LZX_DEBUG("Too small to bother compressing.");
1482                 return 0;
1483         }
1484
1485         if (uncompressed_size > ctx->max_window_size) {
1486                 LZX_DEBUG("Can't compress %zu bytes using window of %u bytes!",
1487                           uncompressed_size, ctx->max_window_size);
1488                 return 0;
1489         }
1490
1491         LZX_DEBUG("Attempting to compress %zu bytes...",
1492                   uncompressed_size);
1493
1494         /* The input data must be preprocessed.  To avoid changing the original
1495          * input, copy it to a temporary buffer.  */
1496         memcpy(ctx->window, uncompressed_data, uncompressed_size);
1497         ctx->window_size = uncompressed_size;
1498
1499         /* This line is unnecessary; it just avoids inconsequential accesses of
1500          * uninitialized memory that would show up in memory-checking tools such
1501          * as valgrind.  */
1502         memset(&ctx->window[ctx->window_size], 0, 12);
1503
1504         LZX_DEBUG("Preprocessing data...");
1505
1506         /* Before doing any actual compression, do the call instruction (0xe8
1507          * byte) translation on the uncompressed data.  */
1508         do_call_insn_preprocessing(ctx->window, ctx->window_size);
1509
1510         LZX_DEBUG("Preparing blocks...");
1511
1512         /* Prepare the compressed data.  */
1513         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
1514                 lzx_prepare_block_fast(ctx);
1515         else
1516                 lzx_prepare_blocks(ctx);
1517
1518         LZX_DEBUG("Writing compressed blocks...");
1519
1520         /* Generate the compressed data.  */
1521         init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
1522         lzx_write_all_blocks(ctx, &ostream);
1523
1524         LZX_DEBUG("Flushing bitstream...");
1525         compressed_size = flush_output_bitstream(&ostream);
1526         if (compressed_size == ~(input_idx_t)0) {
1527                 LZX_DEBUG("Data did not compress to %zu bytes or less!",
1528                           compressed_size_avail);
1529                 return 0;
1530         }
1531
1532         LZX_DEBUG("Done: compressed %zu => %zu bytes.",
1533                   uncompressed_size, compressed_size);
1534
1535         /* Verify that we really get the same thing back when decompressing.
1536          * Although this could be disabled by default in all cases, it only
1537          * takes around 2-3% of the running time of the slow algorithm to do the
1538          * verification.  */
1539         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
1540         #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
1541             || 1
1542         #endif
1543             )
1544         {
1545                 struct wimlib_decompressor *decompressor;
1546
1547                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZX,
1548                                                     ctx->max_window_size,
1549                                                     NULL,
1550                                                     &decompressor))
1551                 {
1552                         int ret;
1553                         ret = wimlib_decompress(compressed_data,
1554                                                 compressed_size,
1555                                                 ctx->window,
1556                                                 uncompressed_size,
1557                                                 decompressor);
1558                         wimlib_free_decompressor(decompressor);
1559
1560                         if (ret) {
1561                                 ERROR("Failed to decompress data we "
1562                                       "compressed using LZX algorithm");
1563                                 wimlib_assert(0);
1564                                 return 0;
1565                         }
1566                         if (memcmp(uncompressed_data, ctx->window, uncompressed_size)) {
1567                                 ERROR("Data we compressed using LZX algorithm "
1568                                       "didn't decompress to original");
1569                                 wimlib_assert(0);
1570                                 return 0;
1571                         }
1572                 } else {
1573                         WARNING("Failed to create decompressor for "
1574                                 "data verification!");
1575                 }
1576         }
1577         return compressed_size;
1578 }
1579
1580 static bool
1581 lzx_params_valid(const struct wimlib_lzx_compressor_params *params)
1582 {
1583         /* Validate parameters.  */
1584         if (params->hdr.size != sizeof(struct wimlib_lzx_compressor_params)) {
1585                 LZX_DEBUG("Invalid parameter structure size!");
1586                 return false;
1587         }
1588
1589         if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
1590             params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
1591         {
1592                 LZX_DEBUG("Invalid algorithm.");
1593                 return false;
1594         }
1595
1596         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1597                 if (params->alg_params.slow.num_optim_passes < 1)
1598                 {
1599                         LZX_DEBUG("Invalid number of optimization passes!");
1600                         return false;
1601                 }
1602
1603                 if (params->alg_params.slow.main_nostat_cost < 1 ||
1604                     params->alg_params.slow.main_nostat_cost > 16)
1605                 {
1606                         LZX_DEBUG("Invalid main_nostat_cost!");
1607                         return false;
1608                 }
1609
1610                 if (params->alg_params.slow.len_nostat_cost < 1 ||
1611                     params->alg_params.slow.len_nostat_cost > 16)
1612                 {
1613                         LZX_DEBUG("Invalid len_nostat_cost!");
1614                         return false;
1615                 }
1616
1617                 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
1618                     params->alg_params.slow.aligned_nostat_cost > 8)
1619                 {
1620                         LZX_DEBUG("Invalid aligned_nostat_cost!");
1621                         return false;
1622                 }
1623         }
1624         return true;
1625 }
1626
1627 static void
1628 lzx_free_compressor(void *_ctx)
1629 {
1630         struct lzx_compressor *ctx = _ctx;
1631
1632         if (ctx) {
1633                 FREE(ctx->chosen_matches);
1634                 FREE(ctx->cached_matches);
1635                 lz_match_chooser_destroy(&ctx->mc);
1636                 lz_sarray_destroy(&ctx->lz_sarray);
1637                 FREE(ctx->block_specs);
1638                 FREE(ctx->prev_tab);
1639                 FREE(ctx->window);
1640                 FREE(ctx);
1641         }
1642 }
1643
1644 static int
1645 lzx_create_compressor(size_t window_size,
1646                       const struct wimlib_compressor_params_header *_params,
1647                       void **ctx_ret)
1648 {
1649         const struct wimlib_lzx_compressor_params *params =
1650                 (const struct wimlib_lzx_compressor_params*)_params;
1651         struct lzx_compressor *ctx;
1652
1653         LZX_DEBUG("Allocating LZX context...");
1654
1655         if (!lzx_window_size_valid(window_size))
1656                 return WIMLIB_ERR_INVALID_PARAM;
1657
1658         static const struct wimlib_lzx_compressor_params fast_default = {
1659                 .hdr = {
1660                         .size = sizeof(struct wimlib_lzx_compressor_params),
1661                 },
1662                 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
1663                 .use_defaults = 0,
1664                 .alg_params = {
1665                         .fast = {
1666                         },
1667                 },
1668         };
1669         static const struct wimlib_lzx_compressor_params slow_default = {
1670                 .hdr = {
1671                         .size = sizeof(struct wimlib_lzx_compressor_params),
1672                 },
1673                 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
1674                 .use_defaults = 0,
1675                 .alg_params = {
1676                         .slow = {
1677                                 .use_len2_matches = 1,
1678                                 .num_fast_bytes = 32,
1679                                 .num_optim_passes = 2,
1680                                 .max_search_depth = 50,
1681                                 .max_matches_per_pos = 3,
1682                                 .main_nostat_cost = 15,
1683                                 .len_nostat_cost = 15,
1684                                 .aligned_nostat_cost = 7,
1685                         },
1686                 },
1687         };
1688
1689         if (params) {
1690                 if (!lzx_params_valid(params))
1691                         return WIMLIB_ERR_INVALID_PARAM;
1692         } else {
1693                 LZX_DEBUG("Using default algorithm and parameters.");
1694                 params = &slow_default;
1695         }
1696
1697         if (params->use_defaults) {
1698                 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
1699                         params = &slow_default;
1700                 else
1701                         params = &fast_default;
1702         }
1703
1704         LZX_DEBUG("Allocating memory.");
1705
1706         ctx = CALLOC(1, sizeof(struct lzx_compressor));
1707         if (ctx == NULL)
1708                 goto oom;
1709
1710         ctx->num_main_syms = lzx_get_num_main_syms(window_size);
1711         ctx->max_window_size = window_size;
1712         ctx->window = MALLOC(window_size + 12);
1713         if (ctx->window == NULL)
1714                 goto oom;
1715
1716         if (params->algorithm == WIMLIB_LZX_ALGORITHM_FAST) {
1717                 ctx->prev_tab = MALLOC(window_size * sizeof(ctx->prev_tab[0]));
1718                 if (ctx->prev_tab == NULL)
1719                         goto oom;
1720         }
1721
1722         size_t block_specs_length = DIV_ROUND_UP(window_size, LZX_DIV_BLOCK_SIZE);
1723         ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
1724         if (ctx->block_specs == NULL)
1725                 goto oom;
1726
1727         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1728                 unsigned min_match_len = LZX_MIN_MATCH_LEN;
1729                 if (!params->alg_params.slow.use_len2_matches)
1730                         min_match_len = max(min_match_len, 3);
1731
1732                 if (!lz_sarray_init(&ctx->lz_sarray,
1733                                     window_size,
1734                                     min_match_len,
1735                                     LZX_MAX_MATCH_LEN,
1736                                     params->alg_params.slow.max_search_depth,
1737                                     params->alg_params.slow.max_matches_per_pos))
1738                         goto oom;
1739         }
1740
1741         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1742                 if (!lz_match_chooser_init(&ctx->mc,
1743                                            LZX_OPTIM_ARRAY_SIZE,
1744                                            params->alg_params.slow.num_fast_bytes,
1745                                            LZX_MAX_MATCH_LEN))
1746                         goto oom;
1747         }
1748
1749         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1750                 u32 cache_per_pos;
1751
1752                 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
1753                 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
1754                         cache_per_pos = LZX_MAX_CACHE_PER_POS;
1755
1756                 ctx->cached_matches = MALLOC(window_size * (cache_per_pos + 1) *
1757                                              sizeof(ctx->cached_matches[0]));
1758                 if (ctx->cached_matches == NULL)
1759                         goto oom;
1760         }
1761
1762         ctx->chosen_matches = MALLOC(window_size * sizeof(ctx->chosen_matches[0]));
1763         if (ctx->chosen_matches == NULL)
1764                 goto oom;
1765
1766         memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_compressor_params));
1767         memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
1768
1769         LZX_DEBUG("Successfully allocated new LZX context.");
1770
1771         *ctx_ret = ctx;
1772         return 0;
1773
1774 oom:
1775         lzx_free_compressor(ctx);
1776         return WIMLIB_ERR_NOMEM;
1777 }
1778
1779 const struct compressor_ops lzx_compressor_ops = {
1780         .create_compressor  = lzx_create_compressor,
1781         .compress           = lzx_compress,
1782         .free_compressor    = lzx_free_compressor,
1783 };