]> wimlib.net Git - wimlib/blob - src/lzx_compress.c
d38c5819d31af3f80cc6414da762f0c93ddf0812
[wimlib] / src / lzx_compress.c
1 /*
2  * lzx_compress.c
3  *
4  * A compressor for the LZX compression format, as used in WIM files.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23
24
25 /*
26  * This file contains a compressor for the LZX ("Lempel-Ziv eXtended")
27  * compression format, as used in the WIM (Windows IMaging) file format.
28  *
29  * Two different parsing algorithms are implemented: "near-optimal" and "lazy".
30  * "Near-optimal" is significantly slower than "lazy", but results in a better
31  * compression ratio.  The "near-optimal" algorithm is used at the default
32  * compression level.
33  *
34  * This file may need some slight modifications to be used outside of the WIM
35  * format.  In particular, in other situations the LZX block header might be
36  * slightly different, and sliding window support might be required.
37  *
38  * Note: LZX is a compression format derived from DEFLATE, the format used by
39  * zlib and gzip.  Both LZX and DEFLATE use LZ77 matching and Huffman coding.
40  * Certain details are quite similar, such as the method for storing Huffman
41  * codes.  However, the main differences are:
42  *
43  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
44  *   compressible before attempting to compress it further.
45  *
46  * - LZX uses a "main" alphabet which combines literals and matches, with the
47  *   match symbols containing a "length header" (giving all or part of the match
48  *   length) and an "offset slot" (giving, roughly speaking, the order of
49  *   magnitude of the match offset).
50  *
51  * - LZX does not have static Huffman blocks (that is, the kind with preset
52  *   Huffman codes); however it does have two types of dynamic Huffman blocks
53  *   ("verbatim" and "aligned").
54  *
55  * - LZX has a minimum match length of 2 rather than 3.  Length 2 matches can be
56  *   useful, but generally only if the parser is smart about choosing them.
57  *
58  * - In LZX, offset slots 0 through 2 actually represent entries in an LRU queue
59  *   of match offsets.  This is very useful for certain types of files, such as
60  *   binary files that have repeating records.
61  */
62
63 #ifdef HAVE_CONFIG_H
64 #  include "config.h"
65 #endif
66
67 /*
68  * Start a new LZX block (with new Huffman codes) after this many bytes.
69  *
70  * Note: actual block sizes may slightly exceed this value.
71  *
72  * TODO: recursive splitting and cost evaluation might be good for an extremely
73  * high compression mode, but otherwise it is almost always far too slow for how
74  * much it helps.  Perhaps some sort of heuristic would be useful?
75  */
76 #define LZX_DIV_BLOCK_SIZE      32768
77
78 /*
79  * LZX_CACHE_PER_POS is the number of lz_match structures to reserve in the
80  * match cache for each byte position.  This value should be high enough so that
81  * nearly the time, all matches found in a given block can fit in the match
82  * cache.  However, fallback behavior (immediately terminating the block) on
83  * cache overflow is still required.
84  */
85 #define LZX_CACHE_PER_POS       6
86
87 /*
88  * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
89  * excluding the extra "overflow" entries.  The per-position multiplier is '1 +
90  * LZX_CACHE_PER_POS' instead of 'LZX_CACHE_PER_POS' because there is an
91  * overhead of one lz_match per position, used to hold the match count at that
92  * position.
93  */
94 #define LZX_CACHE_LENGTH        (LZX_DIV_BLOCK_SIZE * (1 + LZX_CACHE_PER_POS))
95
96 /*
97  * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
98  * ever be saved in the match cache for a single position.  Since each match we
99  * save for a single position has a distinct length, we can use the number of
100  * possible match lengths in LZX as this bound.  This bound is guaranteed to be
101  * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
102  * it will never actually be reached.
103  */
104 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
105
106 /*
107  * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
108  * THis makes it possible to consider fractional bit costs.
109  *
110  * Note: this is only useful as a statistical trick for when the true costs are
111  * unknown.  In reality, each token in LZX requires a whole number of bits to
112  * output.
113  */
114 #define LZX_BIT_COST            16
115
116 /*
117  * Consideration of aligned offset costs is disabled for now, due to
118  * insufficient benefit gained from the time spent.
119  */
120 #define LZX_CONSIDER_ALIGNED_COSTS      0
121
122 /*
123  * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
124  * faster algorithm.
125  */
126 #define LZX_MAX_FAST_LEVEL      34
127
128 /*
129  * LZX_HASH2_ORDER is the log base 2 of the number of entries in the hash table
130  * for finding length 2 matches.  This can be as high as 16 (in which case the
131  * hash function is trivial), but using a smaller hash table actually speeds up
132  * compression due to reduced cache pressure.
133  */
134 #define LZX_HASH2_ORDER         12
135 #define LZX_HASH2_LENGTH        (1UL << LZX_HASH2_ORDER)
136
137 #include "wimlib/lzx_common.h"
138
139 /*
140  * The maximum allowed window order for the matchfinder.
141  */
142 #define MATCHFINDER_MAX_WINDOW_ORDER    LZX_MAX_WINDOW_ORDER
143
144 #include <string.h>
145
146 #include "wimlib/bt_matchfinder.h"
147 #include "wimlib/compress_common.h"
148 #include "wimlib/compressor_ops.h"
149 #include "wimlib/error.h"
150 #include "wimlib/hc_matchfinder.h"
151 #include "wimlib/lz_extend.h"
152 #include "wimlib/unaligned.h"
153 #include "wimlib/util.h"
154
155 struct lzx_output_bitstream;
156
157 /* Codewords for the LZX Huffman codes.  */
158 struct lzx_codewords {
159         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
160         u32 len[LZX_LENCODE_NUM_SYMBOLS];
161         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
162 };
163
164 /* Codeword lengths (in bits) for the LZX Huffman codes.
165  * A zero length means the corresponding codeword has zero frequency.  */
166 struct lzx_lens {
167         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
168         u8 len[LZX_LENCODE_NUM_SYMBOLS];
169         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
170 };
171
172 /* Cost model for near-optimal parsing  */
173 struct lzx_costs {
174
175         /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
176          * length 'len' match that has an offset belonging to 'offset_slot'.  */
177         u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
178
179         /* Cost for each symbol in the main code  */
180         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
181
182         /* Cost for each symbol in the length code  */
183         u32 len[LZX_LENCODE_NUM_SYMBOLS];
184
185 #if LZX_CONSIDER_ALIGNED_COSTS
186         /* Cost for each symbol in the aligned code  */
187         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
188 #endif
189 };
190
191 /* Codewords and lengths for the LZX Huffman codes.  */
192 struct lzx_codes {
193         struct lzx_codewords codewords;
194         struct lzx_lens lens;
195 };
196
197 /* Symbol frequency counters for the LZX Huffman codes.  */
198 struct lzx_freqs {
199         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
200         u32 len[LZX_LENCODE_NUM_SYMBOLS];
201         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
202 };
203
204 /* Intermediate LZX match/literal format  */
205 struct lzx_item {
206
207         /* Bits 0  -  9: Main symbol
208          * Bits 10 - 17: Length symbol
209          * Bits 18 - 22: Number of extra offset bits
210          * Bits 23+    : Extra offset bits  */
211         u64 data;
212 };
213
214 /*
215  * This structure represents a byte position in the input buffer and a node in
216  * the graph of possible match/literal choices.
217  *
218  * Logically, each incoming edge to this node is labeled with a literal or a
219  * match that can be taken to reach this position from an earlier position; and
220  * each outgoing edge from this node is labeled with a literal or a match that
221  * can be taken to advance from this position to a later position.
222  */
223 struct lzx_optimum_node {
224
225         /* The cost, in bits, of the lowest-cost path that has been found to
226          * reach this position.  This can change as progressively lower cost
227          * paths are found to reach this position.  */
228         u32 cost;
229
230         /*
231          * The match or literal that was taken to reach this position.  This can
232          * change as progressively lower cost paths are found to reach this
233          * position.
234          *
235          * This variable is divided into two bitfields.
236          *
237          * Literals:
238          *      Low bits are 1, high bits are the literal.
239          *
240          * Explicit offset matches:
241          *      Low bits are the match length, high bits are the offset plus 2.
242          *
243          * Repeat offset matches:
244          *      Low bits are the match length, high bits are the queue index.
245          */
246         u32 item;
247 #define OPTIMUM_OFFSET_SHIFT 9
248 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
249 } _aligned_attribute(8);
250
251 /*
252  * Least-recently-used queue for match offsets.
253  *
254  * This is represented as a 64-bit integer for efficiency.  There are three
255  * offsets of 21 bits each.  Bit 64 is garbage.
256  */
257 struct lzx_lru_queue {
258         u64 R;
259 };
260
261 #define LZX_QUEUE64_OFFSET_SHIFT 21
262 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
263
264 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
265 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
266 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
267
268 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
269 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
270 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
271
272 static inline void
273 lzx_lru_queue_init(struct lzx_lru_queue *queue)
274 {
275         queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
276                    ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
277                    ((u64)1 << LZX_QUEUE64_R2_SHIFT);
278 }
279
280 static inline u64
281 lzx_lru_queue_R0(struct lzx_lru_queue queue)
282 {
283         return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
284 }
285
286 static inline u64
287 lzx_lru_queue_R1(struct lzx_lru_queue queue)
288 {
289         return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
290 }
291
292 static inline u64
293 lzx_lru_queue_R2(struct lzx_lru_queue queue)
294 {
295         return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
296 }
297
298 /* Push a match offset onto the front (most recently used) end of the queue.  */
299 static inline struct lzx_lru_queue
300 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
301 {
302         return (struct lzx_lru_queue) {
303                 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
304         };
305 }
306
307 /* Pop a match offset off the front (most recently used) end of the queue.  */
308 static inline u32
309 lzx_lru_queue_pop(struct lzx_lru_queue *queue_p)
310 {
311         u32 offset = queue_p->R & LZX_QUEUE64_OFFSET_MASK;
312         queue_p->R >>= LZX_QUEUE64_OFFSET_SHIFT;
313         return offset;
314 }
315
316 /* Swap a match offset to the front of the queue.  */
317 static inline struct lzx_lru_queue
318 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
319 {
320         if (idx == 0)
321                 return queue;
322
323         if (idx == 1)
324                 return (struct lzx_lru_queue) {
325                         .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
326                              (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
327                              (queue.R & LZX_QUEUE64_R2_MASK),
328                 };
329
330         return (struct lzx_lru_queue) {
331                 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
332                      (queue.R & LZX_QUEUE64_R1_MASK) |
333                      (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
334         };
335 }
336
337 /* The main LZX compressor structure  */
338 struct lzx_compressor {
339
340         /* The "nice" match length: if a match of this length is found, then
341          * choose it immediately without further consideration.  */
342         unsigned nice_match_length;
343
344         /* The maximum search depth: consider at most this many potential
345          * matches at each position.  */
346         unsigned max_search_depth;
347
348         /* The log base 2 of the LZX window size for LZ match offset encoding
349          * purposes.  This will be >= LZX_MIN_WINDOW_ORDER and <=
350          * LZX_MAX_WINDOW_ORDER.  */
351         unsigned window_order;
352
353         /* The number of symbols in the main alphabet.  This depends on
354          * @window_order, since @window_order determines the maximum possible
355          * offset.  */
356         unsigned num_main_syms;
357
358         /* Number of optimization passes per block  */
359         unsigned num_optim_passes;
360
361         /* The preprocessed buffer of data being compressed  */
362         u8 *in_buffer;
363
364         /* The number of bytes of data to be compressed, which is the number of
365          * bytes of data in @in_buffer that are actually valid.  */
366         size_t in_nbytes;
367
368         /* Pointer to the compress() implementation chosen at allocation time */
369         void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
370
371         /* The Huffman symbol frequency counters for the current block.  */
372         struct lzx_freqs freqs;
373
374         /* The Huffman codes for the current and previous blocks.  The one with
375          * index 'codes_index' is for the current block, and the other one is
376          * for the previous block.  */
377         struct lzx_codes codes[2];
378         unsigned codes_index;
379
380         /*
381          * The match/literal sequence the algorithm chose for the current block.
382          *
383          * Notes on how large this array actually needs to be:
384          *
385          * - In lzx_compress_near_optimal(), the maximum block size is
386          *   'LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1' bytes.  This occurs if
387          *   a match of the maximum length is found on the last byte.  Although
388          *   it is impossible for this particular case to actually result in a
389          *   parse of all literals, we reserve this many spaces anyway.
390          *
391          * - The worst case for lzx_compress_lazy() is a block of almost all
392          *   literals that ends with a series of matches of increasing scores,
393          *   causing a sequence of literals to be chosen before the last match
394          *   is finally chosen.  The number of items actually chosen in this
395          *   scenario is limited by the number of distinct match scores that
396          *   exist for matches shorter than 'nice_match_length'.  Having
397          *   'LZX_MAX_MATCH_LEN - 1' extra spaces is plenty for now.
398          */
399         struct lzx_item chosen_items[LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1];
400
401         /* Table mapping match offset => offset slot for small offsets  */
402 #define LZX_NUM_FAST_OFFSETS 32768
403         u8 offset_slot_fast[LZX_NUM_FAST_OFFSETS];
404
405         union {
406                 /* Data for greedy or lazy parsing  */
407                 struct {
408                         /* Hash chains matchfinder (MUST BE LAST!!!)  */
409                         struct hc_matchfinder hc_mf;
410                 };
411
412                 /* Data for near-optimal parsing  */
413                 struct {
414                         /*
415                          * The graph nodes for the current block.
416                          *
417                          * We need at least 'LZX_DIV_BLOCK_SIZE +
418                          * LZX_MAX_MATCH_LEN - 1' nodes because that is the
419                          * maximum block size that may be used.  Add 1 because
420                          * we need a node to represent end-of-block.
421                          *
422                          * It is possible that nodes past end-of-block are
423                          * accessed during match consideration, but this can
424                          * only occur if the block was truncated at
425                          * LZX_DIV_BLOCK_SIZE.  So the same bound still applies.
426                          * Note that since nodes past the end of the block will
427                          * never actually have an effect on the items that are
428                          * chosen for the block, it makes no difference what
429                          * their costs are initialized to (if anything).
430                          */
431                         struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
432                                                               LZX_MAX_MATCH_LEN - 1 + 1];
433
434                         /* The cost model for the current block  */
435                         struct lzx_costs costs;
436
437                         /*
438                          * Cached matches for the current block.  This array
439                          * contains the matches that were found at each position
440                          * in the block.  Specifically, for each position, there
441                          * is a special 'struct lz_match' whose 'length' field
442                          * contains the number of matches that were found at
443                          * that position; this is followed by the matches
444                          * themselves, if any, sorted by strictly increasing
445                          * length and strictly increasing offset.
446                          *
447                          * Note: in rare cases, there will be a very high number
448                          * of matches in the block and this array will overflow.
449                          * If this happens, we force the end of the current
450                          * block.  LZX_CACHE_LENGTH is the length at which we
451                          * actually check for overflow.  The extra slots beyond
452                          * this are enough to absorb the worst case overflow,
453                          * which occurs if starting at
454                          * &match_cache[LZX_CACHE_LENGTH - 1], we write the
455                          * match count header, then write
456                          * LZX_MAX_MATCHES_PER_POS matches, then skip searching
457                          * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
458                          * write the match count header for each.
459                          */
460                         struct lz_match match_cache[LZX_CACHE_LENGTH +
461                                                     LZX_MAX_MATCHES_PER_POS +
462                                                     LZX_MAX_MATCH_LEN - 1];
463
464                         /* Hash table for finding length 2 matches  */
465                         pos_t hash2_tab[LZX_HASH2_LENGTH]
466                                 _aligned_attribute(MATCHFINDER_ALIGNMENT);
467
468                         /* Binary trees matchfinder (MUST BE LAST!!!)  */
469                         struct bt_matchfinder bt_mf;
470                 };
471         };
472 };
473
474 /*
475  * Structure to keep track of the current state of sending bits to the
476  * compressed output buffer.
477  *
478  * The LZX bitstream is encoded as a sequence of 16-bit coding units.
479  */
480 struct lzx_output_bitstream {
481
482         /* Bits that haven't yet been written to the output buffer.  */
483         u32 bitbuf;
484
485         /* Number of bits currently held in @bitbuf.  */
486         u32 bitcount;
487
488         /* Pointer to the start of the output buffer.  */
489         u8 *start;
490
491         /* Pointer to the position in the output buffer at which the next coding
492          * unit should be written.  */
493         u8 *next;
494
495         /* Pointer just past the end of the output buffer, rounded down to a
496          * 2-byte boundary.  */
497         u8 *end;
498 };
499
500 /*
501  * Initialize the output bitstream.
502  *
503  * @os
504  *      The output bitstream structure to initialize.
505  * @buffer
506  *      The buffer being written to.
507  * @size
508  *      Size of @buffer, in bytes.
509  */
510 static void
511 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
512 {
513         os->bitbuf = 0;
514         os->bitcount = 0;
515         os->start = buffer;
516         os->next = os->start;
517         os->end = os->start + (size & ~1);
518 }
519
520 /*
521  * Write some bits to the output bitstream.
522  *
523  * The bits are given by the low-order @num_bits bits of @bits.  Higher-order
524  * bits in @bits cannot be set.  At most 17 bits can be written at once.
525  *
526  * @max_num_bits is a compile-time constant that specifies the maximum number of
527  * bits that can ever be written at the call site.  It is used to optimize away
528  * the conditional code for writing a second 16-bit coding unit when writing
529  * fewer than 17 bits.
530  *
531  * If the output buffer space is exhausted, then the bits will be ignored, and
532  * lzx_flush_output() will return 0 when it gets called.
533  */
534 static inline void
535 lzx_write_varbits(struct lzx_output_bitstream *os,
536                   const u32 bits, const unsigned num_bits,
537                   const unsigned max_num_bits)
538 {
539         /* This code is optimized for LZX, which never needs to write more than
540          * 17 bits at once.  */
541         LZX_ASSERT(num_bits <= 17);
542         LZX_ASSERT(num_bits <= max_num_bits);
543         LZX_ASSERT(os->bitcount <= 15);
544
545         /* Add the bits to the bit buffer variable.  @bitcount will be at most
546          * 15, so there will be just enough space for the maximum possible
547          * @num_bits of 17.  */
548         os->bitcount += num_bits;
549         os->bitbuf = (os->bitbuf << num_bits) | bits;
550
551         /* Check whether any coding units need to be written.  */
552         if (os->bitcount >= 16) {
553
554                 os->bitcount -= 16;
555
556                 /* Write a coding unit, unless it would overflow the buffer.  */
557                 if (os->next != os->end) {
558                         put_unaligned_u16_le(os->bitbuf >> os->bitcount, os->next);
559                         os->next += 2;
560                 }
561
562                 /* If writing 17 bits, a second coding unit might need to be
563                  * written.  But because 'max_num_bits' is a compile-time
564                  * constant, the compiler will optimize away this code at most
565                  * call sites.  */
566                 if (max_num_bits == 17 && os->bitcount == 16) {
567                         if (os->next != os->end) {
568                                 put_unaligned_u16_le(os->bitbuf, os->next);
569                                 os->next += 2;
570                         }
571                         os->bitcount = 0;
572                 }
573         }
574 }
575
576 /* Use when @num_bits is a compile-time constant.  Otherwise use
577  * lzx_write_varbits().  */
578 static inline void
579 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
580 {
581         lzx_write_varbits(os, bits, num_bits, num_bits);
582 }
583
584 /*
585  * Flush the last coding unit to the output buffer if needed.  Return the total
586  * number of bytes written to the output buffer, or 0 if an overflow occurred.
587  */
588 static u32
589 lzx_flush_output(struct lzx_output_bitstream *os)
590 {
591         if (os->next == os->end)
592                 return 0;
593
594         if (os->bitcount != 0) {
595                 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next);
596                 os->next += 2;
597         }
598
599         return os->next - os->start;
600 }
601
602 /* Build the main, length, and aligned offset Huffman codes used in LZX.
603  *
604  * This takes as input the frequency tables for each code and produces as output
605  * a set of tables that map symbols to codewords and codeword lengths.  */
606 static void
607 lzx_make_huffman_codes(struct lzx_compressor *c)
608 {
609         const struct lzx_freqs *freqs = &c->freqs;
610         struct lzx_codes *codes = &c->codes[c->codes_index];
611
612         make_canonical_huffman_code(c->num_main_syms,
613                                     LZX_MAX_MAIN_CODEWORD_LEN,
614                                     freqs->main,
615                                     codes->lens.main,
616                                     codes->codewords.main);
617
618         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
619                                     LZX_MAX_LEN_CODEWORD_LEN,
620                                     freqs->len,
621                                     codes->lens.len,
622                                     codes->codewords.len);
623
624         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
625                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
626                                     freqs->aligned,
627                                     codes->lens.aligned,
628                                     codes->codewords.aligned);
629 }
630
631 /* Reset the symbol frequencies for the LZX Huffman codes.  */
632 static void
633 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
634 {
635         memset(&c->freqs, 0, sizeof(c->freqs));
636 }
637
638 static unsigned
639 lzx_compute_precode_items(const u8 lens[restrict],
640                           const u8 prev_lens[restrict],
641                           const unsigned num_lens,
642                           u32 precode_freqs[restrict],
643                           unsigned precode_items[restrict])
644 {
645         unsigned *itemptr;
646         unsigned run_start;
647         unsigned run_end;
648         unsigned extra_bits;
649         int delta;
650         u8 len;
651
652         itemptr = precode_items;
653         run_start = 0;
654         do {
655                 /* Find the next run of codeword lengths.  */
656
657                 /* len = the length being repeated  */
658                 len = lens[run_start];
659
660                 run_end = run_start + 1;
661
662                 /* Fast case for a single length.  */
663                 if (likely(run_end == num_lens || len != lens[run_end])) {
664                         delta = prev_lens[run_start] - len;
665                         if (delta < 0)
666                                 delta += 17;
667                         precode_freqs[delta]++;
668                         *itemptr++ = delta;
669                         run_start++;
670                         continue;
671                 }
672
673                 /* Extend the run.  */
674                 do {
675                         run_end++;
676                 } while (run_end != num_lens && len == lens[run_end]);
677
678                 if (len == 0) {
679                         /* Run of zeroes.  */
680
681                         /* Symbol 18: RLE 20 to 51 zeroes at a time.  */
682                         while ((run_end - run_start) >= 20) {
683                                 extra_bits = min((run_end - run_start) - 20, 0x1f);
684                                 precode_freqs[18]++;
685                                 *itemptr++ = 18 | (extra_bits << 5);
686                                 run_start += 20 + extra_bits;
687                         }
688
689                         /* Symbol 17: RLE 4 to 19 zeroes at a time.  */
690                         if ((run_end - run_start) >= 4) {
691                                 extra_bits = min((run_end - run_start) - 4, 0xf);
692                                 precode_freqs[17]++;
693                                 *itemptr++ = 17 | (extra_bits << 5);
694                                 run_start += 4 + extra_bits;
695                         }
696                 } else {
697
698                         /* A run of nonzero lengths. */
699
700                         /* Symbol 19: RLE 4 to 5 of any length at a time.  */
701                         while ((run_end - run_start) >= 4) {
702                                 extra_bits = (run_end - run_start) > 4;
703                                 delta = prev_lens[run_start] - len;
704                                 if (delta < 0)
705                                         delta += 17;
706                                 precode_freqs[19]++;
707                                 precode_freqs[delta]++;
708                                 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
709                                 run_start += 4 + extra_bits;
710                         }
711                 }
712
713                 /* Output any remaining lengths without RLE.  */
714                 while (run_start != run_end) {
715                         delta = prev_lens[run_start] - len;
716                         if (delta < 0)
717                                 delta += 17;
718                         precode_freqs[delta]++;
719                         *itemptr++ = delta;
720                         run_start++;
721                 }
722         } while (run_start != num_lens);
723
724         return itemptr - precode_items;
725 }
726
727 /*
728  * Output a Huffman code in the compressed form used in LZX.
729  *
730  * The Huffman code is represented in the output as a logical series of codeword
731  * lengths from which the Huffman code, which must be in canonical form, can be
732  * reconstructed.
733  *
734  * The codeword lengths are themselves compressed using a separate Huffman code,
735  * the "precode", which contains a symbol for each possible codeword length in
736  * the larger code as well as several special symbols to represent repeated
737  * codeword lengths (a form of run-length encoding).  The precode is itself
738  * constructed in canonical form, and its codeword lengths are represented
739  * literally in 20 4-bit fields that immediately precede the compressed codeword
740  * lengths of the larger code.
741  *
742  * Furthermore, the codeword lengths of the larger code are actually represented
743  * as deltas from the codeword lengths of the corresponding code in the previous
744  * block.
745  *
746  * @os:
747  *      Bitstream to which to write the compressed Huffman code.
748  * @lens:
749  *      The codeword lengths, indexed by symbol, in the Huffman code.
750  * @prev_lens:
751  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
752  *      code in the previous block, or all zeroes if this is the first block.
753  * @num_lens:
754  *      The number of symbols in the Huffman code.
755  */
756 static void
757 lzx_write_compressed_code(struct lzx_output_bitstream *os,
758                           const u8 lens[restrict],
759                           const u8 prev_lens[restrict],
760                           unsigned num_lens)
761 {
762         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
763         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
764         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
765         unsigned precode_items[num_lens];
766         unsigned num_precode_items;
767         unsigned precode_item;
768         unsigned precode_sym;
769         unsigned i;
770
771         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
772                 precode_freqs[i] = 0;
773
774         /* Compute the "items" (RLE / literal tokens and extra bits) with which
775          * the codeword lengths in the larger code will be output.  */
776         num_precode_items = lzx_compute_precode_items(lens,
777                                                       prev_lens,
778                                                       num_lens,
779                                                       precode_freqs,
780                                                       precode_items);
781
782         /* Build the precode.  */
783         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
784                                     LZX_MAX_PRE_CODEWORD_LEN,
785                                     precode_freqs, precode_lens,
786                                     precode_codewords);
787
788         /* Output the lengths of the codewords in the precode.  */
789         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
790                 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
791
792         /* Output the encoded lengths of the codewords in the larger code.  */
793         for (i = 0; i < num_precode_items; i++) {
794                 precode_item = precode_items[i];
795                 precode_sym = precode_item & 0x1F;
796                 lzx_write_varbits(os, precode_codewords[precode_sym],
797                                   precode_lens[precode_sym],
798                                   LZX_MAX_PRE_CODEWORD_LEN);
799                 if (precode_sym >= 17) {
800                         if (precode_sym == 17) {
801                                 lzx_write_bits(os, precode_item >> 5, 4);
802                         } else if (precode_sym == 18) {
803                                 lzx_write_bits(os, precode_item >> 5, 5);
804                         } else {
805                                 lzx_write_bits(os, (precode_item >> 5) & 1, 1);
806                                 precode_sym = precode_item >> 6;
807                                 lzx_write_varbits(os, precode_codewords[precode_sym],
808                                                   precode_lens[precode_sym],
809                                                   LZX_MAX_PRE_CODEWORD_LEN);
810                         }
811                 }
812         }
813 }
814
815 /* Output a match or literal.  */
816 static inline void
817 lzx_write_item(struct lzx_output_bitstream *os, struct lzx_item item,
818                unsigned ones_if_aligned, const struct lzx_codes *codes)
819 {
820         u64 data = item.data;
821         unsigned main_symbol;
822         unsigned len_symbol;
823         unsigned num_extra_bits;
824         u32 extra_bits;
825
826         main_symbol = data & 0x3FF;
827
828         lzx_write_varbits(os, codes->codewords.main[main_symbol],
829                           codes->lens.main[main_symbol],
830                           LZX_MAX_MAIN_CODEWORD_LEN);
831
832         if (main_symbol < LZX_NUM_CHARS)  /* Literal?  */
833                 return;
834
835         len_symbol = (data >> 10) & 0xFF;
836
837         if (len_symbol != LZX_LENCODE_NUM_SYMBOLS) {
838                 lzx_write_varbits(os, codes->codewords.len[len_symbol],
839                                   codes->lens.len[len_symbol],
840                                   LZX_MAX_LEN_CODEWORD_LEN);
841         }
842
843         num_extra_bits = (data >> 18) & 0x1F;
844         if (num_extra_bits == 0)  /* Small offset or repeat offset match?  */
845                 return;
846
847         extra_bits = data >> 23;
848
849         if ((num_extra_bits & ones_if_aligned) >= LZX_NUM_ALIGNED_OFFSET_BITS) {
850
851                 /* Aligned offset blocks: The low 3 bits of the extra offset
852                  * bits are Huffman-encoded using the aligned offset code.  The
853                  * remaining bits are output literally.  */
854
855                 lzx_write_varbits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
856                                   num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS,
857                                   17 - LZX_NUM_ALIGNED_OFFSET_BITS);
858
859                 lzx_write_varbits(os,
860                                   codes->codewords.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
861                                   codes->lens.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
862                                   LZX_MAX_ALIGNED_CODEWORD_LEN);
863         } else {
864                 /* Verbatim blocks, or fewer than 3 extra bits:  All extra
865                  * offset bits are output literally.  */
866                 lzx_write_varbits(os, extra_bits, num_extra_bits, 17);
867         }
868 }
869
870 /*
871  * Write all matches and literal bytes (which were precomputed) in an LZX
872  * compressed block to the output bitstream in the final compressed
873  * representation.
874  *
875  * @os
876  *      The output bitstream.
877  * @block_type
878  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
879  *      LZX_BLOCKTYPE_VERBATIM).
880  * @items
881  *      The array of matches/literals to output.
882  * @num_items
883  *      Number of matches/literals to output (length of @items).
884  * @codes
885  *      The main, length, and aligned offset Huffman codes for the current
886  *      LZX compressed block.
887  */
888 static void
889 lzx_write_items(struct lzx_output_bitstream *os, int block_type,
890                 const struct lzx_item items[], u32 num_items,
891                 const struct lzx_codes *codes)
892 {
893         unsigned ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
894
895         for (u32 i = 0; i < num_items; i++)
896                 lzx_write_item(os, items[i], ones_if_aligned, codes);
897 }
898
899 static void
900 lzx_write_compressed_block(int block_type,
901                            u32 block_size,
902                            unsigned window_order,
903                            unsigned num_main_syms,
904                            const struct lzx_item chosen_items[],
905                            u32 num_chosen_items,
906                            const struct lzx_codes * codes,
907                            const struct lzx_lens * prev_lens,
908                            struct lzx_output_bitstream * os)
909 {
910         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
911                    block_type == LZX_BLOCKTYPE_VERBATIM);
912
913         /* The first three bits indicate the type of block and are one of the
914          * LZX_BLOCKTYPE_* constants.  */
915         lzx_write_bits(os, block_type, 3);
916
917         /* Output the block size.
918          *
919          * The original LZX format seemed to always encode the block size in 3
920          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
921          * uses the first bit to indicate whether the block is the default size
922          * (32768) or a different size given explicitly by the next 16 bits.
923          *
924          * By default, this compressor uses a window size of 32768 and therefore
925          * follows the WIMGAPI behavior.  However, this compressor also supports
926          * window sizes greater than 32768 bytes, which do not appear to be
927          * supported by WIMGAPI.  In such cases, we retain the default size bit
928          * to mean a size of 32768 bytes but output non-default block size in 24
929          * bits rather than 16.  The compatibility of this behavior is unknown
930          * because WIMs created with chunk size greater than 32768 can seemingly
931          * only be opened by wimlib anyway.  */
932         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
933                 lzx_write_bits(os, 1, 1);
934         } else {
935                 lzx_write_bits(os, 0, 1);
936
937                 if (window_order >= 16)
938                         lzx_write_bits(os, block_size >> 16, 8);
939
940                 lzx_write_bits(os, block_size & 0xFFFF, 16);
941         }
942
943         /* If it's an aligned offset block, output the aligned offset code.  */
944         if (block_type == LZX_BLOCKTYPE_ALIGNED) {
945                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
946                         lzx_write_bits(os, codes->lens.aligned[i],
947                                        LZX_ALIGNEDCODE_ELEMENT_SIZE);
948                 }
949         }
950
951         /* Output the main code (two parts).  */
952         lzx_write_compressed_code(os, codes->lens.main,
953                                   prev_lens->main,
954                                   LZX_NUM_CHARS);
955         lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
956                                   prev_lens->main + LZX_NUM_CHARS,
957                                   num_main_syms - LZX_NUM_CHARS);
958
959         /* Output the length code.  */
960         lzx_write_compressed_code(os, codes->lens.len,
961                                   prev_lens->len,
962                                   LZX_LENCODE_NUM_SYMBOLS);
963
964         /* Output the compressed matches and literals.  */
965         lzx_write_items(os, block_type, chosen_items, num_chosen_items, codes);
966 }
967
968 /* Given the frequencies of symbols in an LZX-compressed block and the
969  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
970  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
971  * will take fewer bits to output.  */
972 static int
973 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
974                                const struct lzx_codes * codes)
975 {
976         u32 aligned_cost = 0;
977         u32 verbatim_cost = 0;
978
979         /* A verbatim block requires 3 bits in each place that an aligned symbol
980          * would be used in an aligned offset block.  */
981         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
982                 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
983                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
984         }
985
986         /* Account for output of the aligned offset code.  */
987         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
988
989         if (aligned_cost < verbatim_cost)
990                 return LZX_BLOCKTYPE_ALIGNED;
991         else
992                 return LZX_BLOCKTYPE_VERBATIM;
993 }
994
995 /*
996  * Finish an LZX block:
997  *
998  * - build the Huffman codes
999  * - decide whether to output the block as VERBATIM or ALIGNED
1000  * - output the block
1001  * - swap the indices of the current and previous Huffman codes
1002  */
1003 static void
1004 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1005                  u32 block_size, u32 num_chosen_items)
1006 {
1007         int block_type;
1008
1009         lzx_make_huffman_codes(c);
1010
1011         block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1012                                                     &c->codes[c->codes_index]);
1013         lzx_write_compressed_block(block_type,
1014                                    block_size,
1015                                    c->window_order,
1016                                    c->num_main_syms,
1017                                    c->chosen_items,
1018                                    num_chosen_items,
1019                                    &c->codes[c->codes_index],
1020                                    &c->codes[c->codes_index ^ 1].lens,
1021                                    os);
1022         c->codes_index ^= 1;
1023 }
1024
1025 /* Return the offset slot for the specified offset, which must be
1026  * less than LZX_NUM_FAST_OFFSETS.  */
1027 static inline unsigned
1028 lzx_get_offset_slot_fast(struct lzx_compressor *c, u32 offset)
1029 {
1030         LZX_ASSERT(offset < LZX_NUM_FAST_OFFSETS);
1031         return c->offset_slot_fast[offset];
1032 }
1033
1034 /* Tally, and optionally record, the specified literal byte.  */
1035 static inline void
1036 lzx_declare_literal(struct lzx_compressor *c, unsigned literal,
1037                     struct lzx_item **next_chosen_item)
1038 {
1039         unsigned main_symbol = lzx_main_symbol_for_literal(literal);
1040
1041         c->freqs.main[main_symbol]++;
1042
1043         if (next_chosen_item) {
1044                 *(*next_chosen_item)++ = (struct lzx_item) {
1045                         .data = main_symbol,
1046                 };
1047         }
1048 }
1049
1050 /* Tally, and optionally record, the specified repeat offset match.  */
1051 static inline void
1052 lzx_declare_repeat_offset_match(struct lzx_compressor *c,
1053                                 unsigned len, unsigned rep_index,
1054                                 struct lzx_item **next_chosen_item)
1055 {
1056         unsigned len_header;
1057         unsigned len_symbol;
1058         unsigned main_symbol;
1059
1060         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1061                 len_header = len - LZX_MIN_MATCH_LEN;
1062                 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1063         } else {
1064                 len_header = LZX_NUM_PRIMARY_LENS;
1065                 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1066                 c->freqs.len[len_symbol]++;
1067         }
1068
1069         main_symbol = lzx_main_symbol_for_match(rep_index, len_header);
1070
1071         c->freqs.main[main_symbol]++;
1072
1073         if (next_chosen_item) {
1074                 *(*next_chosen_item)++ = (struct lzx_item) {
1075                         .data = (u64)main_symbol | ((u64)len_symbol << 10),
1076                 };
1077         }
1078 }
1079
1080 /* Tally, and optionally record, the specified explicit offset match.  */
1081 static inline void
1082 lzx_declare_explicit_offset_match(struct lzx_compressor *c, unsigned len, u32 offset,
1083                                   struct lzx_item **next_chosen_item)
1084 {
1085         unsigned len_header;
1086         unsigned len_symbol;
1087         unsigned main_symbol;
1088         unsigned offset_slot;
1089         unsigned num_extra_bits;
1090         u32 extra_bits;
1091
1092         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1093                 len_header = len - LZX_MIN_MATCH_LEN;
1094                 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1095         } else {
1096                 len_header = LZX_NUM_PRIMARY_LENS;
1097                 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1098                 c->freqs.len[len_symbol]++;
1099         }
1100
1101         offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1102                         lzx_get_offset_slot_fast(c, offset) :
1103                         lzx_get_offset_slot(offset);
1104
1105         main_symbol = lzx_main_symbol_for_match(offset_slot, len_header);
1106
1107         c->freqs.main[main_symbol]++;
1108
1109         num_extra_bits = lzx_extra_offset_bits[offset_slot];
1110
1111         if (num_extra_bits >= LZX_NUM_ALIGNED_OFFSET_BITS)
1112                 c->freqs.aligned[(offset + LZX_OFFSET_ADJUSTMENT) &
1113                                  LZX_ALIGNED_OFFSET_BITMASK]++;
1114
1115         if (next_chosen_item) {
1116
1117                 extra_bits = (offset + LZX_OFFSET_ADJUSTMENT) -
1118                              lzx_offset_slot_base[offset_slot];
1119
1120                 BUILD_BUG_ON(LZX_MAINCODE_MAX_NUM_SYMBOLS > (1 << 10));
1121                 BUILD_BUG_ON(LZX_LENCODE_NUM_SYMBOLS > (1 << 8));
1122                 *(*next_chosen_item)++ = (struct lzx_item) {
1123                         .data = (u64)main_symbol |
1124                                 ((u64)len_symbol << 10) |
1125                                 ((u64)num_extra_bits << 18) |
1126                                 ((u64)extra_bits << 23),
1127                 };
1128         }
1129 }
1130
1131
1132 /* Tally, and optionally record, the specified match or literal.  */
1133 static inline void
1134 lzx_declare_item(struct lzx_compressor *c, u32 item,
1135                  struct lzx_item **next_chosen_item)
1136 {
1137         u32 len = item & OPTIMUM_LEN_MASK;
1138         u32 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1139
1140         if (len == 1)
1141                 lzx_declare_literal(c, offset_data, next_chosen_item);
1142         else if (offset_data < LZX_NUM_RECENT_OFFSETS)
1143                 lzx_declare_repeat_offset_match(c, len, offset_data,
1144                                                 next_chosen_item);
1145         else
1146                 lzx_declare_explicit_offset_match(c, len,
1147                                                   offset_data - LZX_OFFSET_ADJUSTMENT,
1148                                                   next_chosen_item);
1149 }
1150
1151 static inline void
1152 lzx_record_item_list(struct lzx_compressor *c,
1153                      struct lzx_optimum_node *cur_node,
1154                      struct lzx_item **next_chosen_item)
1155 {
1156         struct lzx_optimum_node *end_node;
1157         u32 saved_item;
1158         u32 item;
1159
1160         /* The list is currently in reverse order (last item to first item).
1161          * Reverse it.  */
1162         end_node = cur_node;
1163         saved_item = cur_node->item;
1164         do {
1165                 item = saved_item;
1166                 cur_node -= item & OPTIMUM_LEN_MASK;
1167                 saved_item = cur_node->item;
1168                 cur_node->item = item;
1169         } while (cur_node != c->optimum_nodes);
1170
1171         /* Walk the list of items from beginning to end, tallying and recording
1172          * each item.  */
1173         do {
1174                 lzx_declare_item(c, cur_node->item, next_chosen_item);
1175                 cur_node += (cur_node->item) & OPTIMUM_LEN_MASK;
1176         } while (cur_node != end_node);
1177 }
1178
1179 static inline void
1180 lzx_tally_item_list(struct lzx_compressor *c, struct lzx_optimum_node *cur_node)
1181 {
1182         /* Since we're just tallying the items, we don't need to reverse the
1183          * list.  Processing the items in reverse order is fine.  */
1184         do {
1185                 lzx_declare_item(c, cur_node->item, NULL);
1186                 cur_node -= (cur_node->item & OPTIMUM_LEN_MASK);
1187         } while (cur_node != c->optimum_nodes);
1188 }
1189
1190 /*
1191  * Find an inexpensive path through the graph of possible match/literal choices
1192  * for the current block.  The nodes of the graph are
1193  * c->optimum_nodes[0...block_size].  They correspond directly to the bytes in
1194  * the current block, plus one extra node for end-of-block.  The edges of the
1195  * graph are matches and literals.  The goal is to find the minimum cost path
1196  * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1197  *
1198  * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1199  * proceeding forwards one node at a time.  At each node, a selection of matches
1200  * (len >= 2), as well as the literal byte (len = 1), is considered.  An item of
1201  * length 'len' provides a new path to reach the node 'len' bytes later.  If
1202  * such a path is the lowest cost found so far to reach that later node, then
1203  * that later node is updated with the new path.
1204  *
1205  * Note that although this algorithm is based on minimum cost path search, due
1206  * to various simplifying assumptions the result is not guaranteed to be the
1207  * true minimum cost, or "optimal", path over the graph of all valid LZX
1208  * representations of this block.
1209  *
1210  * Also, note that because of the presence of the recent offsets queue (which is
1211  * a type of adaptive state), the algorithm cannot work backwards and compute
1212  * "cost to end" instead of "cost to beginning".  Furthermore, the way the
1213  * algorithm handles this adaptive state in the "minimum cost" parse is actually
1214  * only an approximation.  It's possible for the globally optimal, minimum cost
1215  * path to contain a prefix, ending at a position, where that path prefix is
1216  * *not* the minimum cost path to that position.  This can happen if such a path
1217  * prefix results in a different adaptive state which results in lower costs
1218  * later.  The algorithm does not solve this problem; it only considers the
1219  * lowest cost to reach each individual position.
1220  */
1221 static struct lzx_lru_queue
1222 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1223                        const u8 * const restrict block_begin,
1224                        const u32 block_size,
1225                        const struct lzx_lru_queue initial_queue)
1226 {
1227         struct lzx_optimum_node *cur_node = c->optimum_nodes;
1228         struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1229         struct lz_match *cache_ptr = c->match_cache;
1230         const u8 *in_next = block_begin;
1231         const u8 * const block_end = block_begin + block_size;
1232
1233         /* Instead of storing the match offset LRU queues in the
1234          * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1235          * storing them in a smaller array.  This works because the algorithm
1236          * only requires a limited history of the adaptive state.  Once a given
1237          * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1238          * it is no longer needed.  */
1239         struct lzx_lru_queue queues[512];
1240
1241         BUILD_BUG_ON(ARRAY_LEN(queues) < LZX_MAX_MATCH_LEN + 1);
1242 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1243
1244         /* Initially, the cost to reach each node is "infinity".  */
1245         memset(c->optimum_nodes, 0xFF,
1246                (block_size + 1) * sizeof(c->optimum_nodes[0]));
1247
1248         QUEUE(block_begin) = initial_queue;
1249
1250         /* The following loop runs 'block_size' iterations, one per node.  */
1251         do {
1252                 unsigned num_matches;
1253                 unsigned literal;
1254                 u32 cost;
1255
1256                 /*
1257                  * A selection of matches for the block was already saved in
1258                  * memory so that we don't have to run the uncompressed data
1259                  * through the matchfinder on every optimization pass.  However,
1260                  * we still search for repeat offset matches during each
1261                  * optimization pass because we cannot predict the state of the
1262                  * recent offsets queue.  But as a heuristic, we don't bother
1263                  * searching for repeat offset matches if the general-purpose
1264                  * matchfinder failed to find any matches.
1265                  *
1266                  * Note that a match of length n at some offset implies there is
1267                  * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1268                  * that same offset.  In other words, we don't necessarily need
1269                  * to use the full length of a match.  The key heuristic that
1270                  * saves a significicant amount of time is that for each
1271                  * distinct length, we only consider the smallest offset for
1272                  * which that length is available.  This heuristic also applies
1273                  * to repeat offsets, which we order specially: R0 < R1 < R2 <
1274                  * any explicit offset.  Of course, this heuristic may be
1275                  * produce suboptimal results because offset slots in LZX are
1276                  * subject to entropy encoding, but in practice this is a useful
1277                  * heuristic.
1278                  */
1279
1280                 num_matches = cache_ptr->length;
1281                 cache_ptr++;
1282
1283                 if (num_matches) {
1284                         struct lz_match *end_matches = cache_ptr + num_matches;
1285                         unsigned next_len = LZX_MIN_MATCH_LEN;
1286                         unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1287                         const u8 *matchptr;
1288
1289                         /* Consider R0 match  */
1290                         matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1291                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1292                                 goto R0_done;
1293                         BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1294                         do {
1295                                 u32 cost = cur_node->cost +
1296                                            c->costs.match_cost[0][
1297                                                         next_len - LZX_MIN_MATCH_LEN];
1298                                 if (cost <= (cur_node + next_len)->cost) {
1299                                         (cur_node + next_len)->cost = cost;
1300                                         (cur_node + next_len)->item =
1301                                                 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1302                                 }
1303                                 if (unlikely(++next_len > max_len)) {
1304                                         cache_ptr = end_matches;
1305                                         goto done_matches;
1306                                 }
1307                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1308
1309                 R0_done:
1310
1311                         /* Consider R1 match  */
1312                         matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1313                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1314                                 goto R1_done;
1315                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1316                                 goto R1_done;
1317                         for (unsigned len = 2; len < next_len - 1; len++)
1318                                 if (matchptr[len] != in_next[len])
1319                                         goto R1_done;
1320                         do {
1321                                 u32 cost = cur_node->cost +
1322                                            c->costs.match_cost[1][
1323                                                         next_len - LZX_MIN_MATCH_LEN];
1324                                 if (cost <= (cur_node + next_len)->cost) {
1325                                         (cur_node + next_len)->cost = cost;
1326                                         (cur_node + next_len)->item =
1327                                                 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1328                                 }
1329                                 if (unlikely(++next_len > max_len)) {
1330                                         cache_ptr = end_matches;
1331                                         goto done_matches;
1332                                 }
1333                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1334
1335                 R1_done:
1336
1337                         /* Consider R2 match  */
1338                         matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1339                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1340                                 goto R2_done;
1341                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1342                                 goto R2_done;
1343                         for (unsigned len = 2; len < next_len - 1; len++)
1344                                 if (matchptr[len] != in_next[len])
1345                                         goto R2_done;
1346                         do {
1347                                 u32 cost = cur_node->cost +
1348                                            c->costs.match_cost[2][
1349                                                         next_len - LZX_MIN_MATCH_LEN];
1350                                 if (cost <= (cur_node + next_len)->cost) {
1351                                         (cur_node + next_len)->cost = cost;
1352                                         (cur_node + next_len)->item =
1353                                                 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1354                                 }
1355                                 if (unlikely(++next_len > max_len)) {
1356                                         cache_ptr = end_matches;
1357                                         goto done_matches;
1358                                 }
1359                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1360
1361                 R2_done:
1362
1363                         while (next_len > cache_ptr->length)
1364                                 if (++cache_ptr == end_matches)
1365                                         goto done_matches;
1366
1367                         /* Consider explicit offset matches  */
1368                         do {
1369                                 u32 offset = cache_ptr->offset;
1370                                 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1371                                 unsigned offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1372                                                 lzx_get_offset_slot_fast(c, offset) :
1373                                                 lzx_get_offset_slot(offset);
1374                                 do {
1375                                         u32 cost = cur_node->cost +
1376                                                    c->costs.match_cost[offset_slot][
1377                                                                 next_len - LZX_MIN_MATCH_LEN];
1378                                 #if LZX_CONSIDER_ALIGNED_COSTS
1379                                         if (lzx_extra_offset_bits[offset_slot] >=
1380                                             LZX_NUM_ALIGNED_OFFSET_BITS)
1381                                                 cost += c->costs.aligned[offset_data &
1382                                                                          LZX_ALIGNED_OFFSET_BITMASK];
1383                                 #endif
1384                                         if (cost < (cur_node + next_len)->cost) {
1385                                                 (cur_node + next_len)->cost = cost;
1386                                                 (cur_node + next_len)->item =
1387                                                         (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1388                                         }
1389                                 } while (++next_len <= cache_ptr->length);
1390                         } while (++cache_ptr != end_matches);
1391                 }
1392
1393         done_matches:
1394
1395                 /* Consider coding a literal.
1396
1397                  * To avoid an extra branch, actually checking the preferability
1398                  * of coding the literal is integrated into the queue update
1399                  * code below.  */
1400                 literal = *in_next++;
1401                 cost = cur_node->cost +
1402                        c->costs.main[lzx_main_symbol_for_literal(literal)];
1403
1404                 /* Advance to the next position.  */
1405                 cur_node++;
1406
1407                 /* The lowest-cost path to the current position is now known.
1408                  * Finalize the recent offsets queue that results from taking
1409                  * this lowest-cost path.  */
1410
1411                 if (cost <= cur_node->cost) {
1412                         /* Literal: queue remains unchanged.  */
1413                         cur_node->cost = cost;
1414                         cur_node->item = (literal << OPTIMUM_OFFSET_SHIFT) | 1;
1415                         QUEUE(in_next) = QUEUE(in_next - 1);
1416                 } else {
1417                         /* Match: queue update is needed.  */
1418                         unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1419                         u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1420                         if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1421                                 /* Explicit offset match: insert offset at front  */
1422                                 QUEUE(in_next) =
1423                                         lzx_lru_queue_push(QUEUE(in_next - len),
1424                                                            offset_data - LZX_OFFSET_ADJUSTMENT);
1425                         } else {
1426                                 /* Repeat offset match: swap offset to front  */
1427                                 QUEUE(in_next) =
1428                                         lzx_lru_queue_swap(QUEUE(in_next - len),
1429                                                            offset_data);
1430                         }
1431                 }
1432         } while (cur_node != end_node);
1433
1434         /* Return the match offset queue at the end of the minimum cost path. */
1435         return QUEUE(block_end);
1436 }
1437
1438 /* Given the costs for the main and length codewords, compute 'match_costs'.  */
1439 static void
1440 lzx_compute_match_costs(struct lzx_compressor *c)
1441 {
1442         unsigned num_offset_slots = lzx_get_num_offset_slots(c->window_order);
1443         struct lzx_costs *costs = &c->costs;
1444
1445         for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1446
1447                 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1448                 unsigned main_symbol = lzx_main_symbol_for_match(offset_slot, 0);
1449                 unsigned i;
1450
1451         #if LZX_CONSIDER_ALIGNED_COSTS
1452                 if (lzx_extra_offset_bits[offset_slot] >= LZX_NUM_ALIGNED_OFFSET_BITS)
1453                         extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1454         #endif
1455
1456                 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1457                         costs->match_cost[offset_slot][i] =
1458                                 costs->main[main_symbol++] + extra_cost;
1459
1460                 extra_cost += costs->main[main_symbol];
1461
1462                 for (; i < LZX_NUM_LENS; i++)
1463                         costs->match_cost[offset_slot][i] =
1464                                 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1465         }
1466 }
1467
1468 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1469  * algorithm.  */
1470 static void
1471 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1472 {
1473         u32 i;
1474         bool have_byte[256];
1475         unsigned num_used_bytes;
1476
1477         /* The costs below are hard coded to use a scaling factor of 16.  */
1478         BUILD_BUG_ON(LZX_BIT_COST != 16);
1479
1480         /*
1481          * Heuristics:
1482          *
1483          * - Use smaller initial costs for literal symbols when the input buffer
1484          *   contains fewer distinct bytes.
1485          *
1486          * - Assume that match symbols are more costly than literal symbols.
1487          *
1488          * - Assume that length symbols for shorter lengths are less costly than
1489          *   length symbols for longer lengths.
1490          */
1491
1492         for (i = 0; i < 256; i++)
1493                 have_byte[i] = false;
1494
1495         for (i = 0; i < block_size; i++)
1496                 have_byte[block[i]] = true;
1497
1498         num_used_bytes = 0;
1499         for (i = 0; i < 256; i++)
1500                 num_used_bytes += have_byte[i];
1501
1502         for (i = 0; i < 256; i++)
1503                 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1504
1505         for (; i < c->num_main_syms; i++)
1506                 c->costs.main[i] = 170;
1507
1508         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1509                 c->costs.len[i] = 103 + (i / 4);
1510
1511 #if LZX_CONSIDER_ALIGNED_COSTS
1512         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1513                 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1514 #endif
1515
1516         lzx_compute_match_costs(c);
1517 }
1518
1519 /* Update the current cost model to reflect the computed Huffman codes.  */
1520 static void
1521 lzx_update_costs(struct lzx_compressor *c)
1522 {
1523         unsigned i;
1524         const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1525
1526         for (i = 0; i < c->num_main_syms; i++)
1527                 c->costs.main[i] = (lens->main[i] ? lens->main[i] : 15) * LZX_BIT_COST;
1528
1529         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1530                 c->costs.len[i] = (lens->len[i] ? lens->len[i] : 15) * LZX_BIT_COST;
1531
1532 #if LZX_CONSIDER_ALIGNED_COSTS
1533         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1534                 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] : 7) * LZX_BIT_COST;
1535 #endif
1536
1537         lzx_compute_match_costs(c);
1538 }
1539
1540 static struct lzx_lru_queue
1541 lzx_optimize_and_write_block(struct lzx_compressor *c,
1542                              struct lzx_output_bitstream *os,
1543                              const u8 *block_begin, const u32 block_size,
1544                              const struct lzx_lru_queue initial_queue)
1545 {
1546         unsigned num_passes_remaining = c->num_optim_passes;
1547         struct lzx_item *next_chosen_item;
1548         struct lzx_lru_queue new_queue;
1549
1550         /* The first optimization pass uses a default cost model.  Each
1551          * additional optimization pass uses a cost model derived from the
1552          * Huffman code computed in the previous pass.  */
1553
1554         lzx_set_default_costs(c, block_begin, block_size);
1555         lzx_reset_symbol_frequencies(c);
1556         do {
1557                 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1558                                                    initial_queue);
1559                 if (num_passes_remaining > 1) {
1560                         lzx_tally_item_list(c, c->optimum_nodes + block_size);
1561                         lzx_make_huffman_codes(c);
1562                         lzx_update_costs(c);
1563                         lzx_reset_symbol_frequencies(c);
1564                 }
1565         } while (--num_passes_remaining);
1566
1567         next_chosen_item = c->chosen_items;
1568         lzx_record_item_list(c, c->optimum_nodes + block_size, &next_chosen_item);
1569         lzx_finish_block(c, os, block_size, next_chosen_item - c->chosen_items);
1570         return new_queue;
1571 }
1572
1573 /*
1574  * This is the "near-optimal" LZX compressor.
1575  *
1576  * For each block, it performs a relatively thorough graph search to find an
1577  * inexpensive (in terms of compressed size) way to output that block.
1578  *
1579  * Note: there are actually many things this algorithm leaves on the table in
1580  * terms of compression ratio.  So although it may be "near-optimal", it is
1581  * certainly not "optimal".  The goal is not to produce the optimal compression
1582  * ratio, which for LZX is probably impossible within any practical amount of
1583  * time, but rather to produce a compression ratio significantly better than a
1584  * simpler "greedy" or "lazy" parse while still being relatively fast.
1585  */
1586 static void
1587 lzx_compress_near_optimal(struct lzx_compressor *c,
1588                           struct lzx_output_bitstream *os)
1589 {
1590         const u8 * const in_begin = c->in_buffer;
1591         const u8 *       in_next = in_begin;
1592         const u8 * const in_end  = in_begin + c->in_nbytes;
1593         unsigned max_len = LZX_MAX_MATCH_LEN;
1594         unsigned nice_len = min(c->nice_match_length, max_len);
1595         u32 next_hash;
1596         struct lzx_lru_queue queue;
1597
1598         bt_matchfinder_init(&c->bt_mf);
1599         matchfinder_init(c->hash2_tab, LZX_HASH2_LENGTH);
1600         next_hash = bt_matchfinder_hash_3_bytes(in_next);
1601         lzx_lru_queue_init(&queue);
1602
1603         do {
1604                 /* Starting a new block  */
1605                 const u8 * const in_block_begin = in_next;
1606                 const u8 * const in_block_end =
1607                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1608
1609                 /* Run the block through the matchfinder and cache the matches. */
1610                 struct lz_match *cache_ptr = c->match_cache;
1611                 do {
1612                         struct lz_match *lz_matchptr;
1613                         u32 hash2;
1614                         pos_t cur_match;
1615                         unsigned best_len;
1616
1617                         /* If approaching the end of the input buffer, adjust
1618                          * 'max_len' and 'nice_len' accordingly.  */
1619                         if (unlikely(max_len > in_end - in_next)) {
1620                                 max_len = in_end - in_next;
1621                                 nice_len = min(max_len, nice_len);
1622
1623                                 /* This extra check is needed to ensure that
1624                                  * reading the next 3 bytes when looking for a
1625                                  * length 2 match is valid.  In addition, we
1626                                  * cannot allow ourselves to find a length 2
1627                                  * match of the very last two bytes with the
1628                                  * very first two bytes, since such a match has
1629                                  * an offset too large to be represented.  */
1630                                 if (unlikely(max_len < 3)) {
1631                                         in_next++;
1632                                         cache_ptr->length = 0;
1633                                         cache_ptr++;
1634                                         continue;
1635                                 }
1636                         }
1637
1638                         lz_matchptr = cache_ptr + 1;
1639
1640                         /* Check for a length 2 match.  */
1641                         hash2 = lz_hash_2_bytes(in_next, LZX_HASH2_ORDER);
1642                         cur_match = c->hash2_tab[hash2];
1643                         c->hash2_tab[hash2] = in_next - in_begin;
1644                         if (matchfinder_node_valid(cur_match) &&
1645                             (LZX_HASH2_ORDER == 16 ||
1646                              load_u16_unaligned(&in_begin[cur_match]) ==
1647                              load_u16_unaligned(in_next)) &&
1648                             in_begin[cur_match + 2] != in_next[2])
1649                         {
1650                                 lz_matchptr->length = 2;
1651                                 lz_matchptr->offset = in_next - &in_begin[cur_match];
1652                                 lz_matchptr++;
1653                         }
1654
1655                         /* Check for matches of length >= 3.  */
1656                         lz_matchptr = bt_matchfinder_get_matches(&c->bt_mf,
1657                                                                  in_begin,
1658                                                                  in_next,
1659                                                                  3,
1660                                                                  max_len,
1661                                                                  nice_len,
1662                                                                  c->max_search_depth,
1663                                                                  &next_hash,
1664                                                                  &best_len,
1665                                                                  lz_matchptr);
1666                         in_next++;
1667                         cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1668                         cache_ptr = lz_matchptr;
1669
1670                         /*
1671                          * If there was a very long match found, then don't
1672                          * cache any matches for the bytes covered by that
1673                          * match.  This avoids degenerate behavior when
1674                          * compressing highly redundant data, where the number
1675                          * of matches can be very large.
1676                          *
1677                          * This heuristic doesn't actually hurt the compression
1678                          * ratio very much.  If there's a long match, then the
1679                          * data must be highly compressible, so it doesn't
1680                          * matter as much what we do.
1681                          */
1682                         if (best_len >= nice_len) {
1683                                 --best_len;
1684                                 do {
1685                                         if (unlikely(max_len > in_end - in_next)) {
1686                                                 max_len = in_end - in_next;
1687                                                 nice_len = min(max_len, nice_len);
1688                                                 if (unlikely(max_len < 3)) {
1689                                                         in_next++;
1690                                                         cache_ptr->length = 0;
1691                                                         cache_ptr++;
1692                                                         continue;
1693                                                 }
1694                                         }
1695                                         c->hash2_tab[lz_hash_2_bytes(in_next, LZX_HASH2_ORDER)] =
1696                                                 in_next - in_begin;
1697                                         bt_matchfinder_skip_position(&c->bt_mf,
1698                                                                      in_begin,
1699                                                                      in_next,
1700                                                                      in_end,
1701                                                                      nice_len,
1702                                                                      c->max_search_depth,
1703                                                                      &next_hash);
1704                                         in_next++;
1705                                         cache_ptr->length = 0;
1706                                         cache_ptr++;
1707                                 } while (--best_len);
1708                         }
1709                 } while (in_next < in_block_end &&
1710                          likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1711
1712                 /* We've finished running the block through the matchfinder.
1713                  * Now choose a match/literal sequence and write the block.  */
1714
1715                 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1716                                                      in_next - in_block_begin,
1717                                                      queue);
1718         } while (in_next != in_end);
1719 }
1720
1721 /*
1722  * Given a pointer to the current byte sequence and the current list of recent
1723  * match offsets, find the longest repeat offset match.
1724  *
1725  * If no match of at least 2 bytes is found, then return 0.
1726  *
1727  * If a match of at least 2 bytes is found, then return its length and set
1728  * *rep_max_idx_ret to the index of its offset in @queue.
1729 */
1730 static unsigned
1731 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1732                                      const u32 bytes_remaining,
1733                                      struct lzx_lru_queue queue,
1734                                      unsigned *rep_max_idx_ret)
1735 {
1736         BUILD_BUG_ON(LZX_NUM_RECENT_OFFSETS != 3);
1737         LZX_ASSERT(bytes_remaining >= 2);
1738
1739         const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1740         const u16 next_2_bytes = load_u16_unaligned(in_next);
1741         const u8 *matchptr;
1742         unsigned rep_max_len;
1743         unsigned rep_max_idx;
1744         unsigned rep_len;
1745
1746         matchptr = in_next - lzx_lru_queue_pop(&queue);
1747         if (load_u16_unaligned(matchptr) == next_2_bytes)
1748                 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1749         else
1750                 rep_max_len = 0;
1751         rep_max_idx = 0;
1752
1753         matchptr = in_next - lzx_lru_queue_pop(&queue);
1754         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1755                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1756                 if (rep_len > rep_max_len) {
1757                         rep_max_len = rep_len;
1758                         rep_max_idx = 1;
1759                 }
1760         }
1761
1762         matchptr = in_next - lzx_lru_queue_pop(&queue);
1763         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1764                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1765                 if (rep_len > rep_max_len) {
1766                         rep_max_len = rep_len;
1767                         rep_max_idx = 2;
1768                 }
1769         }
1770
1771         *rep_max_idx_ret = rep_max_idx;
1772         return rep_max_len;
1773 }
1774
1775 /* Fast heuristic scoring for lazy parsing: how "good" is this match?  */
1776 static inline unsigned
1777 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1778 {
1779         unsigned score = len;
1780
1781         if (adjusted_offset < 4096)
1782                 score++;
1783
1784         if (adjusted_offset < 256)
1785                 score++;
1786
1787         return score;
1788 }
1789
1790 static inline unsigned
1791 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1792 {
1793         return rep_len + 3;
1794 }
1795
1796 /* This is the "lazy" LZX compressor.  */
1797 static void
1798 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os)
1799 {
1800         const u8 * const in_begin = c->in_buffer;
1801         const u8 *       in_next = in_begin;
1802         const u8 * const in_end  = in_begin + c->in_nbytes;
1803         unsigned max_len = LZX_MAX_MATCH_LEN;
1804         unsigned nice_len = min(c->nice_match_length, max_len);
1805         struct lzx_lru_queue queue;
1806
1807         hc_matchfinder_init(&c->hc_mf);
1808         lzx_lru_queue_init(&queue);
1809
1810         do {
1811                 /* Starting a new block  */
1812
1813                 const u8 * const in_block_begin = in_next;
1814                 const u8 * const in_block_end =
1815                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1816                 struct lzx_item *next_chosen_item = c->chosen_items;
1817                 unsigned cur_len;
1818                 u32 cur_offset;
1819                 u32 cur_offset_data;
1820                 unsigned cur_score;
1821                 unsigned next_len;
1822                 u32 next_offset;
1823                 u32 next_offset_data;
1824                 unsigned next_score;
1825                 unsigned rep_max_len;
1826                 unsigned rep_max_idx;
1827                 unsigned rep_score;
1828                 unsigned skip_len;
1829
1830                 lzx_reset_symbol_frequencies(c);
1831
1832                 do {
1833                         if (unlikely(max_len > in_end - in_next)) {
1834                                 max_len = in_end - in_next;
1835                                 nice_len = min(max_len, nice_len);
1836                         }
1837
1838                         /* Find the longest match at the current position.  */
1839
1840                         cur_len = hc_matchfinder_longest_match(&c->hc_mf,
1841                                                                in_begin,
1842                                                                in_next,
1843                                                                2,
1844                                                                max_len,
1845                                                                nice_len,
1846                                                                c->max_search_depth,
1847                                                                &cur_offset);
1848                         if (cur_len < 3 ||
1849                             (cur_len == 3 &&
1850                              cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
1851                              cur_offset != lzx_lru_queue_R0(queue) &&
1852                              cur_offset != lzx_lru_queue_R1(queue) &&
1853                              cur_offset != lzx_lru_queue_R2(queue)))
1854                         {
1855                                 /* There was no match found, or the only match found
1856                                  * was a distant length 3 match.  Output a literal.  */
1857                                 lzx_declare_literal(c, *in_next++,
1858                                                     &next_chosen_item);
1859                                 continue;
1860                         }
1861
1862                         if (cur_offset == lzx_lru_queue_R0(queue)) {
1863                                 in_next++;
1864                                 cur_offset_data = 0;
1865                                 skip_len = cur_len - 1;
1866                                 goto choose_cur_match;
1867                         }
1868
1869                         cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
1870                         cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
1871
1872                         /* Consider a repeat offset match  */
1873                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1874                                                                            in_end - in_next,
1875                                                                            queue,
1876                                                                            &rep_max_idx);
1877                         in_next++;
1878
1879                         if (rep_max_len >= 3 &&
1880                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1881                                                                        rep_max_idx)) >= cur_score)
1882                         {
1883                                 cur_len = rep_max_len;
1884                                 cur_offset_data = rep_max_idx;
1885                                 skip_len = rep_max_len - 1;
1886                                 goto choose_cur_match;
1887                         }
1888
1889                 have_cur_match:
1890
1891                         /* We have a match at the current position.  */
1892
1893                         /* If we have a very long match, choose it immediately.  */
1894                         if (cur_len >= nice_len) {
1895                                 skip_len = cur_len - 1;
1896                                 goto choose_cur_match;
1897                         }
1898
1899                         /* See if there's a better match at the next position.  */
1900
1901                         if (unlikely(max_len > in_end - in_next)) {
1902                                 max_len = in_end - in_next;
1903                                 nice_len = min(max_len, nice_len);
1904                         }
1905
1906                         next_len = hc_matchfinder_longest_match(&c->hc_mf,
1907                                                                 in_begin,
1908                                                                 in_next,
1909                                                                 cur_len - 2,
1910                                                                 max_len,
1911                                                                 nice_len,
1912                                                                 c->max_search_depth / 2,
1913                                                                 &next_offset);
1914
1915                         if (next_len <= cur_len - 2) {
1916                                 in_next++;
1917                                 skip_len = cur_len - 2;
1918                                 goto choose_cur_match;
1919                         }
1920
1921                         next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
1922                         next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
1923
1924                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1925                                                                            in_end - in_next,
1926                                                                            queue,
1927                                                                            &rep_max_idx);
1928                         in_next++;
1929
1930                         if (rep_max_len >= 3 &&
1931                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1932                                                                        rep_max_idx)) >= next_score)
1933                         {
1934
1935                                 if (rep_score > cur_score) {
1936                                         /* The next match is better, and it's a
1937                                          * repeat offset match.  */
1938                                         lzx_declare_literal(c, *(in_next - 2),
1939                                                             &next_chosen_item);
1940                                         cur_len = rep_max_len;
1941                                         cur_offset_data = rep_max_idx;
1942                                         skip_len = cur_len - 1;
1943                                         goto choose_cur_match;
1944                                 }
1945                         } else {
1946                                 if (next_score > cur_score) {
1947                                         /* The next match is better, and it's an
1948                                          * explicit offset match.  */
1949                                         lzx_declare_literal(c, *(in_next - 2),
1950                                                             &next_chosen_item);
1951                                         cur_len = next_len;
1952                                         cur_offset_data = next_offset_data;
1953                                         cur_score = next_score;
1954                                         goto have_cur_match;
1955                                 }
1956                         }
1957
1958                         /* The original match was better.  */
1959                         skip_len = cur_len - 2;
1960
1961                 choose_cur_match:
1962                         if (cur_offset_data < LZX_NUM_RECENT_OFFSETS) {
1963                                 lzx_declare_repeat_offset_match(c, cur_len,
1964                                                                 cur_offset_data,
1965                                                                 &next_chosen_item);
1966                                 queue = lzx_lru_queue_swap(queue, cur_offset_data);
1967                         } else {
1968                                 lzx_declare_explicit_offset_match(c, cur_len,
1969                                                                   cur_offset_data - LZX_OFFSET_ADJUSTMENT,
1970                                                                   &next_chosen_item);
1971                                 queue = lzx_lru_queue_push(queue, cur_offset_data - LZX_OFFSET_ADJUSTMENT);
1972                         }
1973
1974                         hc_matchfinder_skip_positions(&c->hc_mf,
1975                                                       in_begin,
1976                                                       in_next,
1977                                                       in_end,
1978                                                       skip_len);
1979                         in_next += skip_len;
1980                 } while (in_next < in_block_end);
1981
1982                 lzx_finish_block(c, os, in_next - in_block_begin,
1983                                  next_chosen_item - c->chosen_items);
1984         } while (in_next != in_end);
1985 }
1986
1987 static void
1988 lzx_init_offset_slot_fast(struct lzx_compressor *c)
1989 {
1990         u8 slot = 0;
1991
1992         for (u32 offset = 0; offset < LZX_NUM_FAST_OFFSETS; offset++) {
1993
1994                 while (offset + LZX_OFFSET_ADJUSTMENT >= lzx_offset_slot_base[slot + 1])
1995                         slot++;
1996
1997                 c->offset_slot_fast[offset] = slot;
1998         }
1999 }
2000
2001 static size_t
2002 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2003 {
2004         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2005                 return offsetof(struct lzx_compressor, hc_mf) +
2006                         hc_matchfinder_size(max_bufsize);
2007         } else {
2008                 return offsetof(struct lzx_compressor, bt_mf) +
2009                         bt_matchfinder_size(max_bufsize);
2010         }
2011 }
2012
2013 static u64
2014 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level)
2015 {
2016         u64 size = 0;
2017
2018         if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2019                 return 0;
2020
2021         size += lzx_get_compressor_size(max_bufsize, compression_level);
2022         size += max_bufsize; /* in_buffer */
2023         return size;
2024 }
2025
2026 static int
2027 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2028                       void **c_ret)
2029 {
2030         unsigned window_order;
2031         struct lzx_compressor *c;
2032
2033         window_order = lzx_get_window_order(max_bufsize);
2034         if (window_order == 0)
2035                 return WIMLIB_ERR_INVALID_PARAM;
2036
2037         c = ALIGNED_MALLOC(lzx_get_compressor_size(max_bufsize,
2038                                                    compression_level),
2039                            MATCHFINDER_ALIGNMENT);
2040         if (!c)
2041                 goto oom0;
2042
2043         c->num_main_syms = lzx_get_num_main_syms(window_order);
2044         c->window_order = window_order;
2045
2046         c->in_buffer = MALLOC(max_bufsize);
2047         if (!c->in_buffer)
2048                 goto oom1;
2049
2050         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2051
2052                 /* Fast compression: Use lazy parsing.  */
2053
2054                 c->impl = lzx_compress_lazy;
2055                 c->max_search_depth = (36 * compression_level) / 20;
2056                 c->nice_match_length = (72 * compression_level) / 20;
2057
2058                 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2059                  * halves the max_search_depth when attempting a lazy match, and
2060                  * max_search_depth cannot be 0.  */
2061                 if (c->max_search_depth < 2)
2062                         c->max_search_depth = 2;
2063         } else {
2064
2065                 /* Normal / high compression: Use near-optimal parsing.  */
2066
2067                 c->impl = lzx_compress_near_optimal;
2068
2069                 /* Scale nice_match_length and max_search_depth with the
2070                  * compression level.  */
2071                 c->max_search_depth = (24 * compression_level) / 50;
2072                 c->nice_match_length = (32 * compression_level) / 50;
2073
2074                 /* Set a number of optimization passes appropriate for the
2075                  * compression level.  */
2076
2077                 c->num_optim_passes = 1;
2078
2079                 if (compression_level >= 45)
2080                         c->num_optim_passes++;
2081
2082                 /* Use more optimization passes for higher compression levels.
2083                  * But the more passes there are, the less they help --- so
2084                  * don't add them linearly.  */
2085                 if (compression_level >= 70) {
2086                         c->num_optim_passes++;
2087                         if (compression_level >= 100)
2088                                 c->num_optim_passes++;
2089                         if (compression_level >= 150)
2090                                 c->num_optim_passes++;
2091                         if (compression_level >= 200)
2092                                 c->num_optim_passes++;
2093                         if (compression_level >= 300)
2094                                 c->num_optim_passes++;
2095                 }
2096         }
2097
2098         /* max_search_depth == 0 is invalid.  */
2099         if (c->max_search_depth < 1)
2100                 c->max_search_depth = 1;
2101
2102         if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2103                 c->nice_match_length = LZX_MAX_MATCH_LEN;
2104
2105         lzx_init_offset_slot_fast(c);
2106         *c_ret = c;
2107         return 0;
2108
2109 oom1:
2110         ALIGNED_FREE(c);
2111 oom0:
2112         return WIMLIB_ERR_NOMEM;
2113 }
2114
2115 static size_t
2116 lzx_compress(const void *in, size_t in_nbytes,
2117              void *out, size_t out_nbytes_avail, void *_c)
2118 {
2119         struct lzx_compressor *c = _c;
2120         struct lzx_output_bitstream os;
2121
2122         /* Don't bother trying to compress very small inputs.  */
2123         if (in_nbytes < 100)
2124                 return 0;
2125
2126         /* Copy the input data into the internal buffer and preprocess it.  */
2127         memcpy(c->in_buffer, in, in_nbytes);
2128         c->in_nbytes = in_nbytes;
2129         lzx_do_e8_preprocessing(c->in_buffer, in_nbytes);
2130
2131         /* Initially, the previous Huffman codeword lengths are all zeroes.  */
2132         c->codes_index = 0;
2133         memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2134
2135         /* Initialize the output bitstream.  */
2136         lzx_init_output(&os, out, out_nbytes_avail);
2137
2138         /* Call the compression level-specific compress() function.  */
2139         (*c->impl)(c, &os);
2140
2141         /* Flush the output bitstream and return the compressed size or 0.  */
2142         return lzx_flush_output(&os);
2143 }
2144
2145 static void
2146 lzx_free_compressor(void *_c)
2147 {
2148         struct lzx_compressor *c = _c;
2149
2150         FREE(c->in_buffer);
2151         ALIGNED_FREE(c);
2152 }
2153
2154 const struct compressor_ops lzx_compressor_ops = {
2155         .get_needed_memory  = lzx_get_needed_memory,
2156         .create_compressor  = lzx_create_compressor,
2157         .compress           = lzx_compress,
2158         .free_compressor    = lzx_free_compressor,
2159 };