f6b29b3009686b9eb3e324e1ee24fb542e7f6d8f
[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       7
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  * Should the compressor take into account the costs of aligned offset symbols?
118  */
119 #define LZX_CONSIDER_ALIGNED_COSTS      1
120
121 /*
122  * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
123  * faster algorithm.
124  */
125 #define LZX_MAX_FAST_LEVEL      34
126
127 /*
128  * BT_MATCHFINDER_HASH2_ORDER is the log base 2 of the number of entries in the
129  * hash table for finding length 2 matches.  This could be as high as 16, but
130  * using a smaller hash table speeds up compression due to reduced cache
131  * pressure.
132  */
133 #define BT_MATCHFINDER_HASH2_ORDER      12
134
135 /*
136  * These are the compressor-side limits on the codeword lengths for each Huffman
137  * code.  To make outputting bits slightly faster, some of these limits are
138  * lower than the limits defined by the LZX format.  This does not significantly
139  * affect the compression ratio, at least for the block sizes we use.
140  */
141 #define MAIN_CODEWORD_LIMIT     12      /* 64-bit: can buffer 4 main symbols  */
142 #define LENGTH_CODEWORD_LIMIT   12
143 #define ALIGNED_CODEWORD_LIMIT  7
144 #define PRE_CODEWORD_LIMIT      7
145
146 #include "wimlib/compress_common.h"
147 #include "wimlib/compressor_ops.h"
148 #include "wimlib/error.h"
149 #include "wimlib/lz_extend.h"
150 #include "wimlib/lzx_common.h"
151 #include "wimlib/unaligned.h"
152 #include "wimlib/util.h"
153
154 /* Matchfinders with 16-bit positions  */
155 #define mf_pos_t        u16
156 #define MF_SUFFIX       _16
157 #include "wimlib/bt_matchfinder.h"
158 #include "wimlib/hc_matchfinder.h"
159
160 /* Matchfinders with 32-bit positions  */
161 #undef mf_pos_t
162 #undef MF_SUFFIX
163 #define mf_pos_t        u32
164 #define MF_SUFFIX       _32
165 #include "wimlib/bt_matchfinder.h"
166 #include "wimlib/hc_matchfinder.h"
167
168 struct lzx_output_bitstream;
169
170 /* Codewords for the LZX Huffman codes.  */
171 struct lzx_codewords {
172         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
173         u32 len[LZX_LENCODE_NUM_SYMBOLS];
174         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
175 };
176
177 /* Codeword lengths (in bits) for the LZX Huffman codes.
178  * A zero length means the corresponding codeword has zero frequency.  */
179 struct lzx_lens {
180         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS + 1];
181         u8 len[LZX_LENCODE_NUM_SYMBOLS + 1];
182         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
183 };
184
185 /* Cost model for near-optimal parsing  */
186 struct lzx_costs {
187
188         /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
189          * length 'len' match that has an offset belonging to 'offset_slot'.  */
190         u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
191
192         /* Cost for each symbol in the main code  */
193         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
194
195         /* Cost for each symbol in the length code  */
196         u32 len[LZX_LENCODE_NUM_SYMBOLS];
197
198 #if LZX_CONSIDER_ALIGNED_COSTS
199         /* Cost for each symbol in the aligned code  */
200         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
201 #endif
202 };
203
204 /* Codewords and lengths for the LZX Huffman codes.  */
205 struct lzx_codes {
206         struct lzx_codewords codewords;
207         struct lzx_lens lens;
208 };
209
210 /* Symbol frequency counters for the LZX Huffman codes.  */
211 struct lzx_freqs {
212         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
213         u32 len[LZX_LENCODE_NUM_SYMBOLS];
214         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
215 };
216
217 /*
218  * Represents a run of literals followed by a match or end-of-block.  This
219  * struct is needed to temporarily store items chosen by the parser, since items
220  * cannot be written until all items for the block have been chosen and the
221  * block's Huffman codes have been computed.
222  */
223 struct lzx_sequence {
224
225         /* The number of literals in the run.  This may be 0.  The literals are
226          * not stored explicitly in this structure; instead, they are read
227          * directly from the uncompressed data.  */
228         u16 litrunlen;
229
230         /* If the next field doesn't indicate end-of-block, then this is the
231          * match length minus LZX_MIN_MATCH_LEN.  */
232         u16 adjusted_length;
233
234         /* If bit 31 is clear, then this field contains the match header in bits
235          * 0-8 and the match offset minus LZX_OFFSET_ADJUSTMENT in bits 9-30.
236          * Otherwise, this sequence's literal run was the last literal run in
237          * the block, so there is no match that follows it.  */
238         u32 adjusted_offset_and_match_hdr;
239 };
240
241 /*
242  * This structure represents a byte position in the input buffer and a node in
243  * the graph of possible match/literal choices.
244  *
245  * Logically, each incoming edge to this node is labeled with a literal or a
246  * match that can be taken to reach this position from an earlier position; and
247  * each outgoing edge from this node is labeled with a literal or a match that
248  * can be taken to advance from this position to a later position.
249  */
250 struct lzx_optimum_node {
251
252         /* The cost, in bits, of the lowest-cost path that has been found to
253          * reach this position.  This can change as progressively lower cost
254          * paths are found to reach this position.  */
255         u32 cost;
256
257         /*
258          * The match or literal that was taken to reach this position.  This can
259          * change as progressively lower cost paths are found to reach this
260          * position.
261          *
262          * This variable is divided into two bitfields.
263          *
264          * Literals:
265          *      Low bits are 0, high bits are the literal.
266          *
267          * Explicit offset matches:
268          *      Low bits are the match length, high bits are the offset plus 2.
269          *
270          * Repeat offset matches:
271          *      Low bits are the match length, high bits are the queue index.
272          */
273         u32 item;
274 #define OPTIMUM_OFFSET_SHIFT 9
275 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
276 } _aligned_attribute(8);
277
278 /*
279  * Least-recently-used queue for match offsets.
280  *
281  * This is represented as a 64-bit integer for efficiency.  There are three
282  * offsets of 21 bits each.  Bit 64 is garbage.
283  */
284 struct lzx_lru_queue {
285         u64 R;
286 };
287
288 #define LZX_QUEUE64_OFFSET_SHIFT 21
289 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
290
291 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
292 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
293 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
294
295 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
296 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
297 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
298
299 static inline void
300 lzx_lru_queue_init(struct lzx_lru_queue *queue)
301 {
302         queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
303                    ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
304                    ((u64)1 << LZX_QUEUE64_R2_SHIFT);
305 }
306
307 static inline u64
308 lzx_lru_queue_R0(struct lzx_lru_queue queue)
309 {
310         return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
311 }
312
313 static inline u64
314 lzx_lru_queue_R1(struct lzx_lru_queue queue)
315 {
316         return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
317 }
318
319 static inline u64
320 lzx_lru_queue_R2(struct lzx_lru_queue queue)
321 {
322         return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
323 }
324
325 /* Push a match offset onto the front (most recently used) end of the queue.  */
326 static inline struct lzx_lru_queue
327 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
328 {
329         return (struct lzx_lru_queue) {
330                 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
331         };
332 }
333
334 /* Pop a match offset off the front (most recently used) end of the queue.  */
335 static inline u32
336 lzx_lru_queue_pop(struct lzx_lru_queue *queue_p)
337 {
338         u32 offset = queue_p->R & LZX_QUEUE64_OFFSET_MASK;
339         queue_p->R >>= LZX_QUEUE64_OFFSET_SHIFT;
340         return offset;
341 }
342
343 /* Swap a match offset to the front of the queue.  */
344 static inline struct lzx_lru_queue
345 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
346 {
347         if (idx == 0)
348                 return queue;
349
350         if (idx == 1)
351                 return (struct lzx_lru_queue) {
352                         .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
353                              (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
354                              (queue.R & LZX_QUEUE64_R2_MASK),
355                 };
356
357         return (struct lzx_lru_queue) {
358                 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
359                      (queue.R & LZX_QUEUE64_R1_MASK) |
360                      (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
361         };
362 }
363
364 /* The main LZX compressor structure  */
365 struct lzx_compressor {
366
367         /* The "nice" match length: if a match of this length is found, then
368          * choose it immediately without further consideration.  */
369         unsigned nice_match_length;
370
371         /* The maximum search depth: consider at most this many potential
372          * matches at each position.  */
373         unsigned max_search_depth;
374
375         /* The log base 2 of the LZX window size for LZ match offset encoding
376          * purposes.  This will be >= LZX_MIN_WINDOW_ORDER and <=
377          * LZX_MAX_WINDOW_ORDER.  */
378         unsigned window_order;
379
380         /* The number of symbols in the main alphabet.  This depends on
381          * @window_order, since @window_order determines the maximum possible
382          * offset.  */
383         unsigned num_main_syms;
384
385         /* Number of optimization passes per block  */
386         unsigned num_optim_passes;
387
388         /* The preprocessed buffer of data being compressed  */
389         u8 *in_buffer;
390
391         /* The number of bytes of data to be compressed, which is the number of
392          * bytes of data in @in_buffer that are actually valid.  */
393         size_t in_nbytes;
394
395         /* Pointer to the compress() implementation chosen at allocation time */
396         void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
397
398         /* If true, the compressor need not preserve the input buffer if it
399          * compresses the data successfully.  */
400         bool destructive;
401
402         /* The Huffman symbol frequency counters for the current block.  */
403         struct lzx_freqs freqs;
404
405         /* The Huffman codes for the current and previous blocks.  The one with
406          * index 'codes_index' is for the current block, and the other one is
407          * for the previous block.  */
408         struct lzx_codes codes[2];
409         unsigned codes_index;
410
411         /* The matches and literals that the parser has chosen for the current
412          * block.  The required length of this array is limited by the maximum
413          * number of matches that can ever be chosen for a single block, plus
414          * one for the special entry at the end.  */
415         struct lzx_sequence chosen_sequences[
416                        DIV_ROUND_UP(LZX_DIV_BLOCK_SIZE, LZX_MIN_MATCH_LEN) + 1];
417
418         /* Tables for mapping adjusted offsets to offset slots  */
419
420         /* offset slots [0, 29]  */
421         u8 offset_slot_tab_1[32768];
422
423         /* offset slots [30, 49]  */
424         u8 offset_slot_tab_2[128];
425
426         union {
427                 /* Data for greedy or lazy parsing  */
428                 struct {
429                         /* Hash chains matchfinder (MUST BE LAST!!!)  */
430                         union {
431                                 struct hc_matchfinder_16 hc_mf_16;
432                                 struct hc_matchfinder_32 hc_mf_32;
433                         };
434                 };
435
436                 /* Data for near-optimal parsing  */
437                 struct {
438                         /*
439                          * The graph nodes for the current block.
440                          *
441                          * We need at least 'LZX_DIV_BLOCK_SIZE +
442                          * LZX_MAX_MATCH_LEN - 1' nodes because that is the
443                          * maximum block size that may be used.  Add 1 because
444                          * we need a node to represent end-of-block.
445                          *
446                          * It is possible that nodes past end-of-block are
447                          * accessed during match consideration, but this can
448                          * only occur if the block was truncated at
449                          * LZX_DIV_BLOCK_SIZE.  So the same bound still applies.
450                          * Note that since nodes past the end of the block will
451                          * never actually have an effect on the items that are
452                          * chosen for the block, it makes no difference what
453                          * their costs are initialized to (if anything).
454                          */
455                         struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
456                                                               LZX_MAX_MATCH_LEN - 1 + 1];
457
458                         /* The cost model for the current block  */
459                         struct lzx_costs costs;
460
461                         /*
462                          * Cached matches for the current block.  This array
463                          * contains the matches that were found at each position
464                          * in the block.  Specifically, for each position, there
465                          * is a special 'struct lz_match' whose 'length' field
466                          * contains the number of matches that were found at
467                          * that position; this is followed by the matches
468                          * themselves, if any, sorted by strictly increasing
469                          * length.
470                          *
471                          * Note: in rare cases, there will be a very high number
472                          * of matches in the block and this array will overflow.
473                          * If this happens, we force the end of the current
474                          * block.  LZX_CACHE_LENGTH is the length at which we
475                          * actually check for overflow.  The extra slots beyond
476                          * this are enough to absorb the worst case overflow,
477                          * which occurs if starting at
478                          * &match_cache[LZX_CACHE_LENGTH - 1], we write the
479                          * match count header, then write
480                          * LZX_MAX_MATCHES_PER_POS matches, then skip searching
481                          * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
482                          * write the match count header for each.
483                          */
484                         struct lz_match match_cache[LZX_CACHE_LENGTH +
485                                                     LZX_MAX_MATCHES_PER_POS +
486                                                     LZX_MAX_MATCH_LEN - 1];
487
488                         /* Binary trees matchfinder (MUST BE LAST!!!)  */
489                         union {
490                                 struct bt_matchfinder_16 bt_mf_16;
491                                 struct bt_matchfinder_32 bt_mf_32;
492                         };
493                 };
494         };
495 };
496
497 /*
498  * Will a matchfinder using 16-bit positions be sufficient for compressing
499  * buffers of up to the specified size?  The limit could be 65536 bytes, but we
500  * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
501  * This requires that the limit be no more than the length of offset_slot_tab_1
502  * (currently 32768).
503  */
504 static inline bool
505 lzx_is_16_bit(size_t max_bufsize)
506 {
507         STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
508         return max_bufsize <= 32768;
509 }
510
511 /*
512  * The following macros call either the 16-bit or the 32-bit version of a
513  * matchfinder function based on the value of 'is_16_bit', which will be known
514  * at compilation time.
515  */
516
517 #define CALL_HC_MF(is_16_bit, c, funcname, ...)                               \
518         ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
519                        CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
520
521 #define CALL_BT_MF(is_16_bit, c, funcname, ...)                               \
522         ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->bt_mf_16, ##__VA_ARGS__) : \
523                        CONCAT(funcname, _32)(&(c)->bt_mf_32, ##__VA_ARGS__));
524
525 /*
526  * Structure to keep track of the current state of sending bits to the
527  * compressed output buffer.
528  *
529  * The LZX bitstream is encoded as a sequence of 16-bit coding units.
530  */
531 struct lzx_output_bitstream {
532
533         /* Bits that haven't yet been written to the output buffer.  */
534         machine_word_t bitbuf;
535
536         /* Number of bits currently held in @bitbuf.  */
537         u32 bitcount;
538
539         /* Pointer to the start of the output buffer.  */
540         u8 *start;
541
542         /* Pointer to the position in the output buffer at which the next coding
543          * unit should be written.  */
544         u8 *next;
545
546         /* Pointer just past the end of the output buffer, rounded down to a
547          * 2-byte boundary.  */
548         u8 *end;
549 };
550
551 /* Can the specified number of bits always be added to 'bitbuf' after any
552  * pending 16-bit coding units have been flushed?  */
553 #define CAN_BUFFER(n)   ((n) <= (8 * sizeof(machine_word_t)) - 15)
554
555 /*
556  * Initialize the output bitstream.
557  *
558  * @os
559  *      The output bitstream structure to initialize.
560  * @buffer
561  *      The buffer being written to.
562  * @size
563  *      Size of @buffer, in bytes.
564  */
565 static void
566 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
567 {
568         os->bitbuf = 0;
569         os->bitcount = 0;
570         os->start = buffer;
571         os->next = os->start;
572         os->end = os->start + (size & ~1);
573 }
574
575 /* Add some bits to the bitbuffer variable of the output bitstream.  The caller
576  * must make sure there is enough room.  */
577 static inline void
578 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
579 {
580         os->bitbuf = (os->bitbuf << num_bits) | bits;
581         os->bitcount += num_bits;
582 }
583
584 /* Flush bits from the bitbuffer variable to the output buffer.  'max_num_bits'
585  * specifies the maximum number of bits that may have been added since the last
586  * flush.  */
587 static inline void
588 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
589 {
590         /* Masking the number of bits to shift is only needed to avoid undefined
591          * behavior; we don't actually care about the results of bad shifts.  On
592          * x86, the explicit masking generates no extra code.  */
593         const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
594
595         if (os->end - os->next < 6)
596                 return;
597         put_unaligned_u16_le(os->bitbuf >> ((os->bitcount - 16) &
598                                             shift_mask), os->next + 0);
599         if (max_num_bits > 16)
600                 put_unaligned_u16_le(os->bitbuf >> ((os->bitcount - 32) &
601                                                 shift_mask), os->next + 2);
602         if (max_num_bits > 32)
603                 put_unaligned_u16_le(os->bitbuf >> ((os->bitcount - 48) &
604                                                 shift_mask), os->next + 4);
605         os->next += (os->bitcount >> 4) << 1;
606         os->bitcount &= 15;
607 }
608
609 /* Add at most 16 bits to the bitbuffer and flush it.  */
610 static inline void
611 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
612 {
613         lzx_add_bits(os, bits, num_bits);
614         lzx_flush_bits(os, 16);
615 }
616
617 /*
618  * Flush the last coding unit to the output buffer if needed.  Return the total
619  * number of bytes written to the output buffer, or 0 if an overflow occurred.
620  */
621 static u32
622 lzx_flush_output(struct lzx_output_bitstream *os)
623 {
624         if (os->end - os->next < 6)
625                 return 0;
626
627         if (os->bitcount != 0) {
628                 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next);
629                 os->next += 2;
630         }
631
632         return os->next - os->start;
633 }
634
635 /* Build the main, length, and aligned offset Huffman codes used in LZX.
636  *
637  * This takes as input the frequency tables for each code and produces as output
638  * a set of tables that map symbols to codewords and codeword lengths.  */
639 static void
640 lzx_make_huffman_codes(struct lzx_compressor *c)
641 {
642         const struct lzx_freqs *freqs = &c->freqs;
643         struct lzx_codes *codes = &c->codes[c->codes_index];
644
645         STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
646                       MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
647         STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
648                       LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
649         STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
650                       ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
651
652         make_canonical_huffman_code(c->num_main_syms,
653                                     MAIN_CODEWORD_LIMIT,
654                                     freqs->main,
655                                     codes->lens.main,
656                                     codes->codewords.main);
657
658         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
659                                     LENGTH_CODEWORD_LIMIT,
660                                     freqs->len,
661                                     codes->lens.len,
662                                     codes->codewords.len);
663
664         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
665                                     ALIGNED_CODEWORD_LIMIT,
666                                     freqs->aligned,
667                                     codes->lens.aligned,
668                                     codes->codewords.aligned);
669 }
670
671 /* Reset the symbol frequencies for the LZX Huffman codes.  */
672 static void
673 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
674 {
675         memset(&c->freqs, 0, sizeof(c->freqs));
676 }
677
678 static unsigned
679 lzx_compute_precode_items(const u8 lens[restrict],
680                           const u8 prev_lens[restrict],
681                           u32 precode_freqs[restrict],
682                           unsigned precode_items[restrict])
683 {
684         unsigned *itemptr;
685         unsigned run_start;
686         unsigned run_end;
687         unsigned extra_bits;
688         int delta;
689         u8 len;
690
691         itemptr = precode_items;
692         run_start = 0;
693
694         while (!((len = lens[run_start]) & 0x80)) {
695
696                 /* len = the length being repeated  */
697
698                 /* Find the next run of codeword lengths.  */
699
700                 run_end = run_start + 1;
701
702                 /* Fast case for a single length.  */
703                 if (likely(len != lens[run_end])) {
704                         delta = prev_lens[run_start] - len;
705                         if (delta < 0)
706                                 delta += 17;
707                         precode_freqs[delta]++;
708                         *itemptr++ = delta;
709                         run_start++;
710                         continue;
711                 }
712
713                 /* Extend the run.  */
714                 do {
715                         run_end++;
716                 } while (len == lens[run_end]);
717
718                 if (len == 0) {
719                         /* Run of zeroes.  */
720
721                         /* Symbol 18: RLE 20 to 51 zeroes at a time.  */
722                         while ((run_end - run_start) >= 20) {
723                                 extra_bits = min((run_end - run_start) - 20, 0x1f);
724                                 precode_freqs[18]++;
725                                 *itemptr++ = 18 | (extra_bits << 5);
726                                 run_start += 20 + extra_bits;
727                         }
728
729                         /* Symbol 17: RLE 4 to 19 zeroes at a time.  */
730                         if ((run_end - run_start) >= 4) {
731                                 extra_bits = min((run_end - run_start) - 4, 0xf);
732                                 precode_freqs[17]++;
733                                 *itemptr++ = 17 | (extra_bits << 5);
734                                 run_start += 4 + extra_bits;
735                         }
736                 } else {
737
738                         /* A run of nonzero lengths. */
739
740                         /* Symbol 19: RLE 4 to 5 of any length at a time.  */
741                         while ((run_end - run_start) >= 4) {
742                                 extra_bits = (run_end - run_start) > 4;
743                                 delta = prev_lens[run_start] - len;
744                                 if (delta < 0)
745                                         delta += 17;
746                                 precode_freqs[19]++;
747                                 precode_freqs[delta]++;
748                                 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
749                                 run_start += 4 + extra_bits;
750                         }
751                 }
752
753                 /* Output any remaining lengths without RLE.  */
754                 while (run_start != run_end) {
755                         delta = prev_lens[run_start] - len;
756                         if (delta < 0)
757                                 delta += 17;
758                         precode_freqs[delta]++;
759                         *itemptr++ = delta;
760                         run_start++;
761                 }
762         }
763
764         return itemptr - precode_items;
765 }
766
767 /*
768  * Output a Huffman code in the compressed form used in LZX.
769  *
770  * The Huffman code is represented in the output as a logical series of codeword
771  * lengths from which the Huffman code, which must be in canonical form, can be
772  * reconstructed.
773  *
774  * The codeword lengths are themselves compressed using a separate Huffman code,
775  * the "precode", which contains a symbol for each possible codeword length in
776  * the larger code as well as several special symbols to represent repeated
777  * codeword lengths (a form of run-length encoding).  The precode is itself
778  * constructed in canonical form, and its codeword lengths are represented
779  * literally in 20 4-bit fields that immediately precede the compressed codeword
780  * lengths of the larger code.
781  *
782  * Furthermore, the codeword lengths of the larger code are actually represented
783  * as deltas from the codeword lengths of the corresponding code in the previous
784  * block.
785  *
786  * @os:
787  *      Bitstream to which to write the compressed Huffman code.
788  * @lens:
789  *      The codeword lengths, indexed by symbol, in the Huffman code.
790  * @prev_lens:
791  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
792  *      code in the previous block, or all zeroes if this is the first block.
793  * @num_lens:
794  *      The number of symbols in the Huffman code.
795  */
796 static void
797 lzx_write_compressed_code(struct lzx_output_bitstream *os,
798                           const u8 lens[restrict],
799                           const u8 prev_lens[restrict],
800                           unsigned num_lens)
801 {
802         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
803         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
804         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
805         unsigned precode_items[num_lens];
806         unsigned num_precode_items;
807         unsigned precode_item;
808         unsigned precode_sym;
809         unsigned i;
810         u8 saved = lens[num_lens];
811         *(u8 *)(lens + num_lens) = 0x80;
812
813         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
814                 precode_freqs[i] = 0;
815
816         /* Compute the "items" (RLE / literal tokens and extra bits) with which
817          * the codeword lengths in the larger code will be output.  */
818         num_precode_items = lzx_compute_precode_items(lens,
819                                                       prev_lens,
820                                                       precode_freqs,
821                                                       precode_items);
822
823         /* Build the precode.  */
824         STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
825                       PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
826         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
827                                     PRE_CODEWORD_LIMIT,
828                                     precode_freqs, precode_lens,
829                                     precode_codewords);
830
831         /* Output the lengths of the codewords in the precode.  */
832         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
833                 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
834
835         /* Output the encoded lengths of the codewords in the larger code.  */
836         for (i = 0; i < num_precode_items; i++) {
837                 precode_item = precode_items[i];
838                 precode_sym = precode_item & 0x1F;
839                 lzx_add_bits(os, precode_codewords[precode_sym],
840                              precode_lens[precode_sym]);
841                 if (precode_sym >= 17) {
842                         if (precode_sym == 17) {
843                                 lzx_add_bits(os, precode_item >> 5, 4);
844                         } else if (precode_sym == 18) {
845                                 lzx_add_bits(os, precode_item >> 5, 5);
846                         } else {
847                                 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
848                                 precode_sym = precode_item >> 6;
849                                 lzx_add_bits(os, precode_codewords[precode_sym],
850                                              precode_lens[precode_sym]);
851                         }
852                 }
853                 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
854                 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
855         }
856
857         *(u8 *)(lens + num_lens) = saved;
858 }
859
860 /*
861  * Write all matches and literal bytes (which were precomputed) in an LZX
862  * compressed block to the output bitstream in the final compressed
863  * representation.
864  *
865  * @os
866  *      The output bitstream.
867  * @block_type
868  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
869  *      LZX_BLOCKTYPE_VERBATIM).
870  * @block_data
871  *      The uncompressed data of the block.
872  * @sequences
873  *      The matches and literals to output, given as a series of sequences.
874  * @codes
875  *      The main, length, and aligned offset Huffman codes for the current
876  *      LZX compressed block.
877  */
878 static void
879 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
880                     const u8 *block_data, const struct lzx_sequence sequences[],
881                     const struct lzx_codes *codes)
882 {
883         const struct lzx_sequence *seq = sequences;
884         u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
885
886         for (;;) {
887                 /* Output the next sequence.  */
888
889                 unsigned litrunlen = seq->litrunlen;
890                 unsigned match_hdr;
891                 unsigned main_symbol;
892                 unsigned adjusted_length;
893                 u32 adjusted_offset;
894                 unsigned offset_slot;
895                 unsigned num_extra_bits;
896                 u32 extra_bits;
897
898                 /* Output the literal run of the sequence.  */
899
900                 if (litrunlen) {  /* Is the literal run nonempty?  */
901
902                         /* Verify optimization is enabled on 64-bit  */
903                         STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
904                                       CAN_BUFFER(4 * MAIN_CODEWORD_LIMIT));
905
906                         if (CAN_BUFFER(4 * MAIN_CODEWORD_LIMIT)) {
907
908                                 /* 64-bit: write 4 literals at a time.  */
909                                 while (litrunlen >= 4) {
910                                         unsigned lit0 = block_data[0];
911                                         unsigned lit1 = block_data[1];
912                                         unsigned lit2 = block_data[2];
913                                         unsigned lit3 = block_data[3];
914                                         lzx_add_bits(os, codes->codewords.main[lit0],
915                                                      codes->lens.main[lit0]);
916                                         lzx_add_bits(os, codes->codewords.main[lit1],
917                                                      codes->lens.main[lit1]);
918                                         lzx_add_bits(os, codes->codewords.main[lit2],
919                                                      codes->lens.main[lit2]);
920                                         lzx_add_bits(os, codes->codewords.main[lit3],
921                                                      codes->lens.main[lit3]);
922                                         lzx_flush_bits(os, 4 * MAIN_CODEWORD_LIMIT);
923                                         block_data += 4;
924                                         litrunlen -= 4;
925                                 }
926                                 if (litrunlen--) {
927                                         unsigned lit = *block_data++;
928                                         lzx_add_bits(os, codes->codewords.main[lit],
929                                                      codes->lens.main[lit]);
930                                         if (litrunlen--) {
931                                                 unsigned lit = *block_data++;
932                                                 lzx_add_bits(os, codes->codewords.main[lit],
933                                                              codes->lens.main[lit]);
934                                                 if (litrunlen--) {
935                                                         unsigned lit = *block_data++;
936                                                         lzx_add_bits(os, codes->codewords.main[lit],
937                                                                      codes->lens.main[lit]);
938                                                         lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
939                                                 } else {
940                                                         lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
941                                                 }
942                                         } else {
943                                                 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
944                                         }
945                                 }
946                         } else {
947                                 /* 32-bit: write 1 literal at a time.  */
948                                 do {
949                                         unsigned lit = *block_data++;
950                                         lzx_add_bits(os, codes->codewords.main[lit],
951                                                      codes->lens.main[lit]);
952                                         lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
953                                 } while (--litrunlen);
954                         }
955                 }
956
957                 /* Was this the last literal run?  */
958                 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
959                         return;
960
961                 /* Nope; output the match.  */
962
963                 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
964                 main_symbol = LZX_NUM_CHARS + match_hdr;
965                 adjusted_length = seq->adjusted_length;
966
967                 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
968
969                 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
970                 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
971
972                 num_extra_bits = lzx_extra_offset_bits[offset_slot];
973                 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
974
975         #define MAX_MATCH_BITS  (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
976                                  14 + ALIGNED_CODEWORD_LIMIT)
977
978                 /* Verify optimization is enabled on 64-bit  */
979                 STATIC_ASSERT(sizeof(machine_word_t) < 8 || CAN_BUFFER(MAX_MATCH_BITS));
980
981                 /* Output the main symbol for the match.  */
982
983                 lzx_add_bits(os, codes->codewords.main[main_symbol],
984                              codes->lens.main[main_symbol]);
985                 if (!CAN_BUFFER(MAX_MATCH_BITS))
986                         lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
987
988                 /* If needed, output the length symbol for the match.  */
989
990                 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
991                         lzx_add_bits(os, codes->codewords.len[adjusted_length -
992                                                               LZX_NUM_PRIMARY_LENS],
993                                      codes->lens.len[adjusted_length -
994                                                      LZX_NUM_PRIMARY_LENS]);
995                         if (!CAN_BUFFER(MAX_MATCH_BITS))
996                                 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
997                 }
998
999                 /* Output the extra offset bits for the match.  In aligned
1000                  * offset blocks, the lowest 3 bits of the adjusted offset are
1001                  * Huffman-encoded using the aligned offset code, provided that
1002                  * there are at least extra 3 offset bits required.  All other
1003                  * extra offset bits are output verbatim.  */
1004
1005                 if ((adjusted_offset & ones_if_aligned) >= 16) {
1006
1007                         lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
1008                                      num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
1009                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1010                                 lzx_flush_bits(os, 14);
1011
1012                         lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
1013                                                                   LZX_ALIGNED_OFFSET_BITMASK],
1014                                      codes->lens.aligned[adjusted_offset &
1015                                                          LZX_ALIGNED_OFFSET_BITMASK]);
1016                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1017                                 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1018                 } else {
1019                         STATIC_ASSERT(CAN_BUFFER(17));
1020
1021                         lzx_add_bits(os, extra_bits, num_extra_bits);
1022                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1023                                 lzx_flush_bits(os, 17);
1024                 }
1025
1026                 if (CAN_BUFFER(MAX_MATCH_BITS))
1027                         lzx_flush_bits(os, MAX_MATCH_BITS);
1028
1029                 /* Advance to the next sequence.  */
1030                 seq++;
1031         }
1032 }
1033
1034 static void
1035 lzx_write_compressed_block(const u8 *block_begin,
1036                            int block_type,
1037                            u32 block_size,
1038                            unsigned window_order,
1039                            unsigned num_main_syms,
1040                            const struct lzx_sequence sequences[],
1041                            const struct lzx_codes * codes,
1042                            const struct lzx_lens * prev_lens,
1043                            struct lzx_output_bitstream * os)
1044 {
1045         /* The first three bits indicate the type of block and are one of the
1046          * LZX_BLOCKTYPE_* constants.  */
1047         lzx_write_bits(os, block_type, 3);
1048
1049         /* Output the block size.
1050          *
1051          * The original LZX format seemed to always encode the block size in 3
1052          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
1053          * uses the first bit to indicate whether the block is the default size
1054          * (32768) or a different size given explicitly by the next 16 bits.
1055          *
1056          * By default, this compressor uses a window size of 32768 and therefore
1057          * follows the WIMGAPI behavior.  However, this compressor also supports
1058          * window sizes greater than 32768 bytes, which do not appear to be
1059          * supported by WIMGAPI.  In such cases, we retain the default size bit
1060          * to mean a size of 32768 bytes but output non-default block size in 24
1061          * bits rather than 16.  The compatibility of this behavior is unknown
1062          * because WIMs created with chunk size greater than 32768 can seemingly
1063          * only be opened by wimlib anyway.  */
1064         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1065                 lzx_write_bits(os, 1, 1);
1066         } else {
1067                 lzx_write_bits(os, 0, 1);
1068
1069                 if (window_order >= 16)
1070                         lzx_write_bits(os, block_size >> 16, 8);
1071
1072                 lzx_write_bits(os, block_size & 0xFFFF, 16);
1073         }
1074
1075         /* If it's an aligned offset block, output the aligned offset code.  */
1076         if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1077                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1078                         lzx_write_bits(os, codes->lens.aligned[i],
1079                                        LZX_ALIGNEDCODE_ELEMENT_SIZE);
1080                 }
1081         }
1082
1083         /* Output the main code (two parts).  */
1084         lzx_write_compressed_code(os, codes->lens.main,
1085                                   prev_lens->main,
1086                                   LZX_NUM_CHARS);
1087         lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1088                                   prev_lens->main + LZX_NUM_CHARS,
1089                                   num_main_syms - LZX_NUM_CHARS);
1090
1091         /* Output the length code.  */
1092         lzx_write_compressed_code(os, codes->lens.len,
1093                                   prev_lens->len,
1094                                   LZX_LENCODE_NUM_SYMBOLS);
1095
1096         /* Output the compressed matches and literals.  */
1097         lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1098 }
1099
1100 /* Given the frequencies of symbols in an LZX-compressed block and the
1101  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1102  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1103  * will take fewer bits to output.  */
1104 static int
1105 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1106                                const struct lzx_codes * codes)
1107 {
1108         u32 aligned_cost = 0;
1109         u32 verbatim_cost = 0;
1110
1111         /* A verbatim block requires 3 bits in each place that an aligned symbol
1112          * would be used in an aligned offset block.  */
1113         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1114                 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1115                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1116         }
1117
1118         /* Account for output of the aligned offset code.  */
1119         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1120
1121         if (aligned_cost < verbatim_cost)
1122                 return LZX_BLOCKTYPE_ALIGNED;
1123         else
1124                 return LZX_BLOCKTYPE_VERBATIM;
1125 }
1126
1127 /*
1128  * Return the offset slot for the specified adjusted match offset, using the
1129  * compressor's acceleration tables to speed up the mapping.
1130  */
1131 static inline unsigned
1132 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1133                          bool is_16_bit)
1134 {
1135         if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1136                 return c->offset_slot_tab_1[adjusted_offset];
1137         return c->offset_slot_tab_2[adjusted_offset >> 14];
1138 }
1139
1140 /*
1141  * Finish an LZX block:
1142  *
1143  * - build the Huffman codes
1144  * - decide whether to output the block as VERBATIM or ALIGNED
1145  * - output the block
1146  * - swap the indices of the current and previous Huffman codes
1147  */
1148 static void
1149 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1150                  const u8 *block_begin, u32 block_size, u32 seq_idx)
1151 {
1152         int block_type;
1153
1154         lzx_make_huffman_codes(c);
1155
1156         block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1157                                                     &c->codes[c->codes_index]);
1158         lzx_write_compressed_block(block_begin,
1159                                    block_type,
1160                                    block_size,
1161                                    c->window_order,
1162                                    c->num_main_syms,
1163                                    &c->chosen_sequences[seq_idx],
1164                                    &c->codes[c->codes_index],
1165                                    &c->codes[c->codes_index ^ 1].lens,
1166                                    os);
1167         c->codes_index ^= 1;
1168 }
1169
1170 /* Tally the Huffman symbol for a literal and increment the literal run length.
1171  */
1172 static inline void
1173 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1174 {
1175         c->freqs.main[literal]++;
1176         ++*litrunlen_p;
1177 }
1178
1179 /* Tally the Huffman symbol for a match, save the match data and the length of
1180  * the preceding literal run in the next lzx_sequence, and update the recent
1181  * offsets queue.  */
1182 static inline void
1183 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1184                  u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1185                  u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1186 {
1187         u32 litrunlen = *litrunlen_p;
1188         struct lzx_sequence *next_seq = *next_seq_p;
1189         unsigned offset_slot;
1190         unsigned v;
1191
1192         v = length - LZX_MIN_MATCH_LEN;
1193
1194         /* Save the literal run length and adjusted length.  */
1195         next_seq->litrunlen = litrunlen;
1196         next_seq->adjusted_length = v;
1197
1198         /* Compute the length header and tally the length symbol if needed  */
1199         if (v >= LZX_NUM_PRIMARY_LENS) {
1200                 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1201                 v = LZX_NUM_PRIMARY_LENS;
1202         }
1203
1204         /* Compute the offset slot  */
1205         offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1206
1207         /* Compute the match header.  */
1208         v += offset_slot * LZX_NUM_LEN_HEADERS;
1209
1210         /* Save the adjusted offset and match header.  */
1211         next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1212
1213         /* Tally the main symbol.  */
1214         c->freqs.main[LZX_NUM_CHARS + v]++;
1215
1216         /* Update the recent offsets queue.  */
1217         if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1218                 /* Repeat offset match  */
1219                 swap(recent_offsets[0], recent_offsets[offset_data]);
1220         } else {
1221                 /* Explicit offset match  */
1222
1223                 /* Tally the aligned offset symbol if needed  */
1224                 if (offset_data >= 16)
1225                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1226
1227                 recent_offsets[2] = recent_offsets[1];
1228                 recent_offsets[1] = recent_offsets[0];
1229                 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1230         }
1231
1232         /* Reset the literal run length and advance to the next sequence.  */
1233         *next_seq_p = next_seq + 1;
1234         *litrunlen_p = 0;
1235 }
1236
1237 /* Finish the last lzx_sequence.  The last lzx_sequence is just a literal run;
1238  * there is no match.  This literal run may be empty.  */
1239 static inline void
1240 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1241 {
1242         last_seq->litrunlen = litrunlen;
1243
1244         /* Special value to mark last sequence  */
1245         last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1246 }
1247
1248 /*
1249  * Given the minimum-cost path computed through the item graph for the current
1250  * block, walk the path and count how many of each symbol in each Huffman-coded
1251  * alphabet would be required to output the items (matches and literals) along
1252  * the path.
1253  *
1254  * Note that the path will be walked backwards (from the end of the block to the
1255  * beginning of the block), but this doesn't matter because this function only
1256  * computes frequencies.
1257  */
1258 static inline void
1259 lzx_tally_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1260 {
1261         u32 node_idx = block_size;
1262         for (;;) {
1263                 u32 len;
1264                 u32 offset_data;
1265                 unsigned v;
1266                 unsigned offset_slot;
1267
1268                 /* Tally literals until either a match or the beginning of the
1269                  * block is reached.  */
1270                 for (;;) {
1271                         u32 item = c->optimum_nodes[node_idx].item;
1272
1273                         len = item & OPTIMUM_LEN_MASK;
1274                         offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1275
1276                         if (len != 0)  /* Not a literal?  */
1277                                 break;
1278
1279                         /* Tally the main symbol for the literal.  */
1280                         c->freqs.main[offset_data]++;
1281
1282                         if (--node_idx == 0) /* Beginning of block was reached?  */
1283                                 return;
1284                 }
1285
1286                 node_idx -= len;
1287
1288                 /* Tally a match.  */
1289
1290                 /* Tally the aligned offset symbol if needed.  */
1291                 if (offset_data >= 16)
1292                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1293
1294                 /* Tally the length symbol if needed.  */
1295                 v = len - LZX_MIN_MATCH_LEN;;
1296                 if (v >= LZX_NUM_PRIMARY_LENS) {
1297                         c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1298                         v = LZX_NUM_PRIMARY_LENS;
1299                 }
1300
1301                 /* Tally the main symbol.  */
1302                 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1303                 v += offset_slot * LZX_NUM_LEN_HEADERS;
1304                 c->freqs.main[LZX_NUM_CHARS + v]++;
1305
1306                 if (node_idx == 0) /* Beginning of block was reached?  */
1307                         return;
1308         }
1309 }
1310
1311 /*
1312  * Like lzx_tally_item_list(), but this function also generates the list of
1313  * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1314  * ready to be output to the bitstream after the Huffman codes are computed.
1315  * The lzx_sequences will be written to decreasing memory addresses as the path
1316  * is walked backwards, which means they will end up in the expected
1317  * first-to-last order.  The return value is the index in c->chosen_sequences at
1318  * which the lzx_sequences begin.
1319  */
1320 static inline u32
1321 lzx_record_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1322 {
1323         u32 node_idx = block_size;
1324         u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1325         u32 lit_start_node;
1326
1327         /* Special value to mark last sequence  */
1328         c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1329
1330         lit_start_node = node_idx;
1331         for (;;) {
1332                 u32 len;
1333                 u32 offset_data;
1334                 unsigned v;
1335                 unsigned offset_slot;
1336
1337                 /* Record literals until either a match or the beginning of the
1338                  * block is reached.  */
1339                 for (;;) {
1340                         u32 item = c->optimum_nodes[node_idx].item;
1341
1342                         len = item & OPTIMUM_LEN_MASK;
1343                         offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1344
1345                         if (len != 0) /* Not a literal?  */
1346                                 break;
1347
1348                         /* Tally the main symbol for the literal.  */
1349                         c->freqs.main[offset_data]++;
1350
1351                         if (--node_idx == 0) /* Beginning of block was reached?  */
1352                                 goto out;
1353                 }
1354
1355                 /* Save the literal run length for the next sequence (the
1356                  * "previous sequence" when walking backwards).  */
1357                 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1358                 node_idx -= len;
1359                 lit_start_node = node_idx;
1360
1361                 /* Record a match.  */
1362
1363                 /* Tally the aligned offset symbol if needed.  */
1364                 if (offset_data >= 16)
1365                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1366
1367                 /* Save the adjusted length.  */
1368                 v = len - LZX_MIN_MATCH_LEN;
1369                 c->chosen_sequences[seq_idx].adjusted_length = v;
1370
1371                 /* Tally the length symbol if needed.  */
1372                 if (v >= LZX_NUM_PRIMARY_LENS) {
1373                         c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1374                         v = LZX_NUM_PRIMARY_LENS;
1375                 }
1376
1377                 /* Tally the main symbol.  */
1378                 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1379                 v += offset_slot * LZX_NUM_LEN_HEADERS;
1380                 c->freqs.main[LZX_NUM_CHARS + v]++;
1381
1382                 /* Save the adjusted offset and match header.  */
1383                 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1384                                 (offset_data << 9) | v;
1385
1386                 if (node_idx == 0) /* Beginning of block was reached?  */
1387                         goto out;
1388         }
1389
1390 out:
1391         /* Save the literal run length for the first sequence.  */
1392         c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1393
1394         /* Return the index in c->chosen_sequences at which the lzx_sequences
1395          * begin.  */
1396         return seq_idx;
1397 }
1398
1399 /*
1400  * Find an inexpensive path through the graph of possible match/literal choices
1401  * for the current block.  The nodes of the graph are
1402  * c->optimum_nodes[0...block_size].  They correspond directly to the bytes in
1403  * the current block, plus one extra node for end-of-block.  The edges of the
1404  * graph are matches and literals.  The goal is to find the minimum cost path
1405  * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1406  *
1407  * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1408  * proceeding forwards one node at a time.  At each node, a selection of matches
1409  * (len >= 2), as well as the literal byte (len = 1), is considered.  An item of
1410  * length 'len' provides a new path to reach the node 'len' bytes later.  If
1411  * such a path is the lowest cost found so far to reach that later node, then
1412  * that later node is updated with the new path.
1413  *
1414  * Note that although this algorithm is based on minimum cost path search, due
1415  * to various simplifying assumptions the result is not guaranteed to be the
1416  * true minimum cost, or "optimal", path over the graph of all valid LZX
1417  * representations of this block.
1418  *
1419  * Also, note that because of the presence of the recent offsets queue (which is
1420  * a type of adaptive state), the algorithm cannot work backwards and compute
1421  * "cost to end" instead of "cost to beginning".  Furthermore, the way the
1422  * algorithm handles this adaptive state in the "minimum cost" parse is actually
1423  * only an approximation.  It's possible for the globally optimal, minimum cost
1424  * path to contain a prefix, ending at a position, where that path prefix is
1425  * *not* the minimum cost path to that position.  This can happen if such a path
1426  * prefix results in a different adaptive state which results in lower costs
1427  * later.  The algorithm does not solve this problem; it only considers the
1428  * lowest cost to reach each individual position.
1429  */
1430 static inline struct lzx_lru_queue
1431 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1432                        const u8 * const restrict block_begin,
1433                        const u32 block_size,
1434                        const struct lzx_lru_queue initial_queue,
1435                        bool is_16_bit)
1436 {
1437         struct lzx_optimum_node *cur_node = c->optimum_nodes;
1438         struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1439         struct lz_match *cache_ptr = c->match_cache;
1440         const u8 *in_next = block_begin;
1441         const u8 * const block_end = block_begin + block_size;
1442
1443         /* Instead of storing the match offset LRU queues in the
1444          * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1445          * storing them in a smaller array.  This works because the algorithm
1446          * only requires a limited history of the adaptive state.  Once a given
1447          * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1448          * it is no longer needed.  */
1449         struct lzx_lru_queue queues[512];
1450
1451         STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1452 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1453
1454         /* Initially, the cost to reach each node is "infinity".  */
1455         memset(c->optimum_nodes, 0xFF,
1456                (block_size + 1) * sizeof(c->optimum_nodes[0]));
1457
1458         QUEUE(block_begin) = initial_queue;
1459
1460         /* The following loop runs 'block_size' iterations, one per node.  */
1461         do {
1462                 unsigned num_matches;
1463                 unsigned literal;
1464                 u32 cost;
1465
1466                 /*
1467                  * A selection of matches for the block was already saved in
1468                  * memory so that we don't have to run the uncompressed data
1469                  * through the matchfinder on every optimization pass.  However,
1470                  * we still search for repeat offset matches during each
1471                  * optimization pass because we cannot predict the state of the
1472                  * recent offsets queue.  But as a heuristic, we don't bother
1473                  * searching for repeat offset matches if the general-purpose
1474                  * matchfinder failed to find any matches.
1475                  *
1476                  * Note that a match of length n at some offset implies there is
1477                  * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1478                  * that same offset.  In other words, we don't necessarily need
1479                  * to use the full length of a match.  The key heuristic that
1480                  * saves a significicant amount of time is that for each
1481                  * distinct length, we only consider the smallest offset for
1482                  * which that length is available.  This heuristic also applies
1483                  * to repeat offsets, which we order specially: R0 < R1 < R2 <
1484                  * any explicit offset.  Of course, this heuristic may be
1485                  * produce suboptimal results because offset slots in LZX are
1486                  * subject to entropy encoding, but in practice this is a useful
1487                  * heuristic.
1488                  */
1489
1490                 num_matches = cache_ptr->length;
1491                 cache_ptr++;
1492
1493                 if (num_matches) {
1494                         struct lz_match *end_matches = cache_ptr + num_matches;
1495                         unsigned next_len = LZX_MIN_MATCH_LEN;
1496                         unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1497                         const u8 *matchptr;
1498
1499                         /* Consider R0 match  */
1500                         matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1501                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1502                                 goto R0_done;
1503                         STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1504                         do {
1505                                 u32 cost = cur_node->cost +
1506                                            c->costs.match_cost[0][
1507                                                         next_len - LZX_MIN_MATCH_LEN];
1508                                 if (cost <= (cur_node + next_len)->cost) {
1509                                         (cur_node + next_len)->cost = cost;
1510                                         (cur_node + next_len)->item =
1511                                                 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1512                                 }
1513                                 if (unlikely(++next_len > max_len)) {
1514                                         cache_ptr = end_matches;
1515                                         goto done_matches;
1516                                 }
1517                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1518
1519                 R0_done:
1520
1521                         /* Consider R1 match  */
1522                         matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1523                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1524                                 goto R1_done;
1525                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1526                                 goto R1_done;
1527                         for (unsigned len = 2; len < next_len - 1; len++)
1528                                 if (matchptr[len] != in_next[len])
1529                                         goto R1_done;
1530                         do {
1531                                 u32 cost = cur_node->cost +
1532                                            c->costs.match_cost[1][
1533                                                         next_len - LZX_MIN_MATCH_LEN];
1534                                 if (cost <= (cur_node + next_len)->cost) {
1535                                         (cur_node + next_len)->cost = cost;
1536                                         (cur_node + next_len)->item =
1537                                                 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1538                                 }
1539                                 if (unlikely(++next_len > max_len)) {
1540                                         cache_ptr = end_matches;
1541                                         goto done_matches;
1542                                 }
1543                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1544
1545                 R1_done:
1546
1547                         /* Consider R2 match  */
1548                         matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1549                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1550                                 goto R2_done;
1551                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1552                                 goto R2_done;
1553                         for (unsigned len = 2; len < next_len - 1; len++)
1554                                 if (matchptr[len] != in_next[len])
1555                                         goto R2_done;
1556                         do {
1557                                 u32 cost = cur_node->cost +
1558                                            c->costs.match_cost[2][
1559                                                         next_len - LZX_MIN_MATCH_LEN];
1560                                 if (cost <= (cur_node + next_len)->cost) {
1561                                         (cur_node + next_len)->cost = cost;
1562                                         (cur_node + next_len)->item =
1563                                                 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1564                                 }
1565                                 if (unlikely(++next_len > max_len)) {
1566                                         cache_ptr = end_matches;
1567                                         goto done_matches;
1568                                 }
1569                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1570
1571                 R2_done:
1572
1573                         while (next_len > cache_ptr->length)
1574                                 if (++cache_ptr == end_matches)
1575                                         goto done_matches;
1576
1577                         /* Consider explicit offset matches  */
1578                         do {
1579                                 u32 offset = cache_ptr->offset;
1580                                 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1581                                 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1582                                                                                 is_16_bit);
1583                                 u32 base_cost = cur_node->cost;
1584
1585                         #if LZX_CONSIDER_ALIGNED_COSTS
1586                                 if (offset_data >= 16)
1587                                         base_cost += c->costs.aligned[offset_data &
1588                                                                       LZX_ALIGNED_OFFSET_BITMASK];
1589                         #endif
1590
1591                                 do {
1592                                         u32 cost = base_cost +
1593                                                    c->costs.match_cost[offset_slot][
1594                                                                 next_len - LZX_MIN_MATCH_LEN];
1595                                         if (cost < (cur_node + next_len)->cost) {
1596                                                 (cur_node + next_len)->cost = cost;
1597                                                 (cur_node + next_len)->item =
1598                                                         (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1599                                         }
1600                                 } while (++next_len <= cache_ptr->length);
1601                         } while (++cache_ptr != end_matches);
1602                 }
1603
1604         done_matches:
1605
1606                 /* Consider coding a literal.
1607
1608                  * To avoid an extra branch, actually checking the preferability
1609                  * of coding the literal is integrated into the queue update
1610                  * code below.  */
1611                 literal = *in_next++;
1612                 cost = cur_node->cost + c->costs.main[literal];
1613
1614                 /* Advance to the next position.  */
1615                 cur_node++;
1616
1617                 /* The lowest-cost path to the current position is now known.
1618                  * Finalize the recent offsets queue that results from taking
1619                  * this lowest-cost path.  */
1620
1621                 if (cost <= cur_node->cost) {
1622                         /* Literal: queue remains unchanged.  */
1623                         cur_node->cost = cost;
1624                         cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1625                         QUEUE(in_next) = QUEUE(in_next - 1);
1626                 } else {
1627                         /* Match: queue update is needed.  */
1628                         unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1629                         u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1630                         if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1631                                 /* Explicit offset match: insert offset at front  */
1632                                 QUEUE(in_next) =
1633                                         lzx_lru_queue_push(QUEUE(in_next - len),
1634                                                            offset_data - LZX_OFFSET_ADJUSTMENT);
1635                         } else {
1636                                 /* Repeat offset match: swap offset to front  */
1637                                 QUEUE(in_next) =
1638                                         lzx_lru_queue_swap(QUEUE(in_next - len),
1639                                                            offset_data);
1640                         }
1641                 }
1642         } while (cur_node != end_node);
1643
1644         /* Return the match offset queue at the end of the minimum cost path. */
1645         return QUEUE(block_end);
1646 }
1647
1648 /* Given the costs for the main and length codewords, compute 'match_costs'.  */
1649 static void
1650 lzx_compute_match_costs(struct lzx_compressor *c)
1651 {
1652         unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1653                                         LZX_NUM_LEN_HEADERS;
1654         struct lzx_costs *costs = &c->costs;
1655
1656         for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1657
1658                 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1659                 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1660                                                         LZX_NUM_LEN_HEADERS);
1661                 unsigned i;
1662
1663         #if LZX_CONSIDER_ALIGNED_COSTS
1664                 if (offset_slot >= 8)
1665                         extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1666         #endif
1667
1668                 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1669                         costs->match_cost[offset_slot][i] =
1670                                 costs->main[main_symbol++] + extra_cost;
1671
1672                 extra_cost += costs->main[main_symbol];
1673
1674                 for (; i < LZX_NUM_LENS; i++)
1675                         costs->match_cost[offset_slot][i] =
1676                                 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1677         }
1678 }
1679
1680 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1681  * algorithm.  */
1682 static void
1683 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1684 {
1685         u32 i;
1686         bool have_byte[256];
1687         unsigned num_used_bytes;
1688
1689         /* The costs below are hard coded to use a scaling factor of 16.  */
1690         STATIC_ASSERT(LZX_BIT_COST == 16);
1691
1692         /*
1693          * Heuristics:
1694          *
1695          * - Use smaller initial costs for literal symbols when the input buffer
1696          *   contains fewer distinct bytes.
1697          *
1698          * - Assume that match symbols are more costly than literal symbols.
1699          *
1700          * - Assume that length symbols for shorter lengths are less costly than
1701          *   length symbols for longer lengths.
1702          */
1703
1704         for (i = 0; i < 256; i++)
1705                 have_byte[i] = false;
1706
1707         for (i = 0; i < block_size; i++)
1708                 have_byte[block[i]] = true;
1709
1710         num_used_bytes = 0;
1711         for (i = 0; i < 256; i++)
1712                 num_used_bytes += have_byte[i];
1713
1714         for (i = 0; i < 256; i++)
1715                 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1716
1717         for (; i < c->num_main_syms; i++)
1718                 c->costs.main[i] = 170;
1719
1720         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1721                 c->costs.len[i] = 103 + (i / 4);
1722
1723 #if LZX_CONSIDER_ALIGNED_COSTS
1724         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1725                 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1726 #endif
1727
1728         lzx_compute_match_costs(c);
1729 }
1730
1731 /* Update the current cost model to reflect the computed Huffman codes.  */
1732 static void
1733 lzx_update_costs(struct lzx_compressor *c)
1734 {
1735         unsigned i;
1736         const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1737
1738         for (i = 0; i < c->num_main_syms; i++) {
1739                 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1740                                     MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1741         }
1742
1743         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1744                 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1745                                    LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1746         }
1747
1748 #if LZX_CONSIDER_ALIGNED_COSTS
1749         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1750                 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1751                                        ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1752         }
1753 #endif
1754
1755         lzx_compute_match_costs(c);
1756 }
1757
1758 static inline struct lzx_lru_queue
1759 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1760                              struct lzx_output_bitstream * const restrict os,
1761                              const u8 * const restrict block_begin,
1762                              const u32 block_size,
1763                              const struct lzx_lru_queue initial_queue,
1764                              bool is_16_bit)
1765 {
1766         unsigned num_passes_remaining = c->num_optim_passes;
1767         struct lzx_lru_queue new_queue;
1768         u32 seq_idx;
1769
1770         /* The first optimization pass uses a default cost model.  Each
1771          * additional optimization pass uses a cost model derived from the
1772          * Huffman code computed in the previous pass.  */
1773
1774         lzx_set_default_costs(c, block_begin, block_size);
1775         lzx_reset_symbol_frequencies(c);
1776         do {
1777                 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1778                                                    initial_queue, is_16_bit);
1779                 if (num_passes_remaining > 1) {
1780                         lzx_tally_item_list(c, block_size, is_16_bit);
1781                         lzx_make_huffman_codes(c);
1782                         lzx_update_costs(c);
1783                         lzx_reset_symbol_frequencies(c);
1784                 }
1785         } while (--num_passes_remaining);
1786
1787         seq_idx = lzx_record_item_list(c, block_size, is_16_bit);
1788         lzx_finish_block(c, os, block_begin, block_size, seq_idx);
1789         return new_queue;
1790 }
1791
1792 /*
1793  * This is the "near-optimal" LZX compressor.
1794  *
1795  * For each block, it performs a relatively thorough graph search to find an
1796  * inexpensive (in terms of compressed size) way to output that block.
1797  *
1798  * Note: there are actually many things this algorithm leaves on the table in
1799  * terms of compression ratio.  So although it may be "near-optimal", it is
1800  * certainly not "optimal".  The goal is not to produce the optimal compression
1801  * ratio, which for LZX is probably impossible within any practical amount of
1802  * time, but rather to produce a compression ratio significantly better than a
1803  * simpler "greedy" or "lazy" parse while still being relatively fast.
1804  */
1805 static inline void
1806 lzx_compress_near_optimal(struct lzx_compressor *c,
1807                           struct lzx_output_bitstream *os,
1808                           bool is_16_bit)
1809 {
1810         const u8 * const in_begin = c->in_buffer;
1811         const u8 *       in_next = in_begin;
1812         const u8 * const in_end  = in_begin + c->in_nbytes;
1813         u32 max_len = LZX_MAX_MATCH_LEN;
1814         u32 nice_len = min(c->nice_match_length, max_len);
1815         u32 next_hashes[2] = {};
1816         struct lzx_lru_queue queue;
1817
1818         CALL_BT_MF(is_16_bit, c, bt_matchfinder_init);
1819         lzx_lru_queue_init(&queue);
1820
1821         do {
1822                 /* Starting a new block  */
1823                 const u8 * const in_block_begin = in_next;
1824                 const u8 * const in_block_end =
1825                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1826
1827                 /* Run the block through the matchfinder and cache the matches. */
1828                 struct lz_match *cache_ptr = c->match_cache;
1829                 do {
1830                         struct lz_match *lz_matchptr;
1831                         u32 best_len;
1832
1833                         /* If approaching the end of the input buffer, adjust
1834                          * 'max_len' and 'nice_len' accordingly.  */
1835                         if (unlikely(max_len > in_end - in_next)) {
1836                                 max_len = in_end - in_next;
1837                                 nice_len = min(max_len, nice_len);
1838                                 if (unlikely(max_len <
1839                                              BT_MATCHFINDER_REQUIRED_NBYTES))
1840                                 {
1841                                         in_next++;
1842                                         cache_ptr->length = 0;
1843                                         cache_ptr++;
1844                                         continue;
1845                                 }
1846                         }
1847
1848                         /* Check for matches.  */
1849                         lz_matchptr = CALL_BT_MF(is_16_bit, c,
1850                                                  bt_matchfinder_get_matches,
1851                                                  in_begin,
1852                                                  in_next - in_begin,
1853                                                  max_len,
1854                                                  nice_len,
1855                                                  c->max_search_depth,
1856                                                  next_hashes,
1857                                                  &best_len,
1858                                                  cache_ptr + 1);
1859                         in_next++;
1860                         cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1861                         cache_ptr = lz_matchptr;
1862
1863                         /*
1864                          * If there was a very long match found, then don't
1865                          * cache any matches for the bytes covered by that
1866                          * match.  This avoids degenerate behavior when
1867                          * compressing highly redundant data, where the number
1868                          * of matches can be very large.
1869                          *
1870                          * This heuristic doesn't actually hurt the compression
1871                          * ratio very much.  If there's a long match, then the
1872                          * data must be highly compressible, so it doesn't
1873                          * matter as much what we do.
1874                          */
1875                         if (best_len >= nice_len) {
1876                                 --best_len;
1877                                 do {
1878                                         if (unlikely(max_len > in_end - in_next)) {
1879                                                 max_len = in_end - in_next;
1880                                                 nice_len = min(max_len, nice_len);
1881                                                 if (unlikely(max_len <
1882                                                              BT_MATCHFINDER_REQUIRED_NBYTES))
1883                                                 {
1884                                                         in_next++;
1885                                                         cache_ptr->length = 0;
1886                                                         cache_ptr++;
1887                                                         continue;
1888                                                 }
1889                                         }
1890                                         CALL_BT_MF(is_16_bit, c,
1891                                                    bt_matchfinder_skip_position,
1892                                                    in_begin,
1893                                                    in_next - in_begin,
1894                                                    max_len,
1895                                                    nice_len,
1896                                                    c->max_search_depth,
1897                                                    next_hashes);
1898                                         in_next++;
1899                                         cache_ptr->length = 0;
1900                                         cache_ptr++;
1901                                 } while (--best_len);
1902                         }
1903                 } while (in_next < in_block_end &&
1904                          likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1905
1906                 /* We've finished running the block through the matchfinder.
1907                  * Now choose a match/literal sequence and write the block.  */
1908
1909                 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1910                                                      in_next - in_block_begin,
1911                                                      queue, is_16_bit);
1912         } while (in_next != in_end);
1913 }
1914
1915 static void
1916 lzx_compress_near_optimal_16(struct lzx_compressor *c,
1917                              struct lzx_output_bitstream *os)
1918 {
1919         lzx_compress_near_optimal(c, os, true);
1920 }
1921
1922 static void
1923 lzx_compress_near_optimal_32(struct lzx_compressor *c,
1924                              struct lzx_output_bitstream *os)
1925 {
1926         lzx_compress_near_optimal(c, os, false);
1927 }
1928
1929 /*
1930  * Given a pointer to the current byte sequence and the current list of recent
1931  * match offsets, find the longest repeat offset match.
1932  *
1933  * If no match of at least 2 bytes is found, then return 0.
1934  *
1935  * If a match of at least 2 bytes is found, then return its length and set
1936  * *rep_max_idx_ret to the index of its offset in @queue.
1937 */
1938 static unsigned
1939 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1940                                      const u32 bytes_remaining,
1941                                      const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
1942                                      unsigned *rep_max_idx_ret)
1943 {
1944         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
1945
1946         const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1947         const u16 next_2_bytes = load_u16_unaligned(in_next);
1948         const u8 *matchptr;
1949         unsigned rep_max_len;
1950         unsigned rep_max_idx;
1951         unsigned rep_len;
1952
1953         matchptr = in_next - recent_offsets[0];
1954         if (load_u16_unaligned(matchptr) == next_2_bytes)
1955                 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1956         else
1957                 rep_max_len = 0;
1958         rep_max_idx = 0;
1959
1960         matchptr = in_next - recent_offsets[1];
1961         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1962                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1963                 if (rep_len > rep_max_len) {
1964                         rep_max_len = rep_len;
1965                         rep_max_idx = 1;
1966                 }
1967         }
1968
1969         matchptr = in_next - recent_offsets[2];
1970         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1971                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1972                 if (rep_len > rep_max_len) {
1973                         rep_max_len = rep_len;
1974                         rep_max_idx = 2;
1975                 }
1976         }
1977
1978         *rep_max_idx_ret = rep_max_idx;
1979         return rep_max_len;
1980 }
1981
1982 /* Fast heuristic scoring for lazy parsing: how "good" is this match?  */
1983 static inline unsigned
1984 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1985 {
1986         unsigned score = len;
1987
1988         if (adjusted_offset < 4096)
1989                 score++;
1990
1991         if (adjusted_offset < 256)
1992                 score++;
1993
1994         return score;
1995 }
1996
1997 static inline unsigned
1998 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1999 {
2000         return rep_len + 3;
2001 }
2002
2003 /* This is the "lazy" LZX compressor.  */
2004 static inline void
2005 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
2006                   bool is_16_bit)
2007 {
2008         const u8 * const in_begin = c->in_buffer;
2009         const u8 *       in_next = in_begin;
2010         const u8 * const in_end  = in_begin + c->in_nbytes;
2011         unsigned max_len = LZX_MAX_MATCH_LEN;
2012         unsigned nice_len = min(c->nice_match_length, max_len);
2013         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2014         u32 recent_offsets[3] = {1, 1, 1};
2015         u32 next_hashes[2] = {};
2016
2017         CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2018
2019         do {
2020                 /* Starting a new block  */
2021
2022                 const u8 * const in_block_begin = in_next;
2023                 const u8 * const in_block_end =
2024                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
2025                 struct lzx_sequence *next_seq = c->chosen_sequences;
2026                 unsigned cur_len;
2027                 u32 cur_offset;
2028                 u32 cur_offset_data;
2029                 unsigned cur_score;
2030                 unsigned next_len;
2031                 u32 next_offset;
2032                 u32 next_offset_data;
2033                 unsigned next_score;
2034                 unsigned rep_max_len;
2035                 unsigned rep_max_idx;
2036                 unsigned rep_score;
2037                 unsigned skip_len;
2038                 u32 litrunlen = 0;
2039
2040                 lzx_reset_symbol_frequencies(c);
2041
2042                 do {
2043                         if (unlikely(max_len > in_end - in_next)) {
2044                                 max_len = in_end - in_next;
2045                                 nice_len = min(max_len, nice_len);
2046                         }
2047
2048                         /* Find the longest match at the current position.  */
2049
2050                         cur_len = CALL_HC_MF(is_16_bit, c,
2051                                              hc_matchfinder_longest_match,
2052                                              in_begin,
2053                                              in_next - in_begin,
2054                                              2,
2055                                              max_len,
2056                                              nice_len,
2057                                              c->max_search_depth,
2058                                              next_hashes,
2059                                              &cur_offset);
2060                         if (cur_len < 3 ||
2061                             (cur_len == 3 &&
2062                              cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2063                              cur_offset != recent_offsets[0] &&
2064                              cur_offset != recent_offsets[1] &&
2065                              cur_offset != recent_offsets[2]))
2066                         {
2067                                 /* There was no match found, or the only match found
2068                                  * was a distant length 3 match.  Output a literal.  */
2069                                 lzx_record_literal(c, *in_next++, &litrunlen);
2070                                 continue;
2071                         }
2072
2073                         if (cur_offset == recent_offsets[0]) {
2074                                 in_next++;
2075                                 cur_offset_data = 0;
2076                                 skip_len = cur_len - 1;
2077                                 goto choose_cur_match;
2078                         }
2079
2080                         cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2081                         cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2082
2083                         /* Consider a repeat offset match  */
2084                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2085                                                                            in_end - in_next,
2086                                                                            recent_offsets,
2087                                                                            &rep_max_idx);
2088                         in_next++;
2089
2090                         if (rep_max_len >= 3 &&
2091                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2092                                                                        rep_max_idx)) >= cur_score)
2093                         {
2094                                 cur_len = rep_max_len;
2095                                 cur_offset_data = rep_max_idx;
2096                                 skip_len = rep_max_len - 1;
2097                                 goto choose_cur_match;
2098                         }
2099
2100                 have_cur_match:
2101
2102                         /* We have a match at the current position.  */
2103
2104                         /* If we have a very long match, choose it immediately.  */
2105                         if (cur_len >= nice_len) {
2106                                 skip_len = cur_len - 1;
2107                                 goto choose_cur_match;
2108                         }
2109
2110                         /* See if there's a better match at the next position.  */
2111
2112                         if (unlikely(max_len > in_end - in_next)) {
2113                                 max_len = in_end - in_next;
2114                                 nice_len = min(max_len, nice_len);
2115                         }
2116
2117                         next_len = CALL_HC_MF(is_16_bit, c,
2118                                               hc_matchfinder_longest_match,
2119                                               in_begin,
2120                                               in_next - in_begin,
2121                                               cur_len - 2,
2122                                               max_len,
2123                                               nice_len,
2124                                               c->max_search_depth / 2,
2125                                               next_hashes,
2126                                               &next_offset);
2127
2128                         if (next_len <= cur_len - 2) {
2129                                 in_next++;
2130                                 skip_len = cur_len - 2;
2131                                 goto choose_cur_match;
2132                         }
2133
2134                         next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2135                         next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2136
2137                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2138                                                                            in_end - in_next,
2139                                                                            recent_offsets,
2140                                                                            &rep_max_idx);
2141                         in_next++;
2142
2143                         if (rep_max_len >= 3 &&
2144                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2145                                                                        rep_max_idx)) >= next_score)
2146                         {
2147
2148                                 if (rep_score > cur_score) {
2149                                         /* The next match is better, and it's a
2150                                          * repeat offset match.  */
2151                                         lzx_record_literal(c, *(in_next - 2),
2152                                                            &litrunlen);
2153                                         cur_len = rep_max_len;
2154                                         cur_offset_data = rep_max_idx;
2155                                         skip_len = cur_len - 1;
2156                                         goto choose_cur_match;
2157                                 }
2158                         } else {
2159                                 if (next_score > cur_score) {
2160                                         /* The next match is better, and it's an
2161                                          * explicit offset match.  */
2162                                         lzx_record_literal(c, *(in_next - 2),
2163                                                            &litrunlen);
2164                                         cur_len = next_len;
2165                                         cur_offset_data = next_offset_data;
2166                                         cur_score = next_score;
2167                                         goto have_cur_match;
2168                                 }
2169                         }
2170
2171                         /* The original match was better.  */
2172                         skip_len = cur_len - 2;
2173
2174                 choose_cur_match:
2175                         lzx_record_match(c, cur_len, cur_offset_data,
2176                                          recent_offsets, is_16_bit,
2177                                          &litrunlen, &next_seq);
2178                         in_next = CALL_HC_MF(is_16_bit, c,
2179                                              hc_matchfinder_skip_positions,
2180                                              in_begin,
2181                                              in_next - in_begin,
2182                                              in_end - in_begin,
2183                                              skip_len,
2184                                              next_hashes);
2185                 } while (in_next < in_block_end);
2186
2187                 lzx_finish_sequence(next_seq, litrunlen);
2188
2189                 lzx_finish_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2190
2191         } while (in_next != in_end);
2192 }
2193
2194 static void
2195 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2196 {
2197         lzx_compress_lazy(c, os, true);
2198 }
2199
2200 static void
2201 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2202 {
2203         lzx_compress_lazy(c, os, false);
2204 }
2205
2206 /* Generate the acceleration tables for offset slots.  */
2207 static void
2208 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2209 {
2210         u32 adjusted_offset = 0;
2211         unsigned slot = 0;
2212
2213         /* slots [0, 29]  */
2214         for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2215              adjusted_offset++)
2216         {
2217                 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2218                         slot++;
2219                 c->offset_slot_tab_1[adjusted_offset] = slot;
2220         }
2221
2222         /* slots [30, 49]  */
2223         for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2224              adjusted_offset += (u32)1 << 14)
2225         {
2226                 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2227                         slot++;
2228                 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2229         }
2230 }
2231
2232 static size_t
2233 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2234 {
2235         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2236                 if (lzx_is_16_bit(max_bufsize))
2237                         return offsetof(struct lzx_compressor, hc_mf_16) +
2238                                hc_matchfinder_size_16(max_bufsize);
2239                 else
2240                         return offsetof(struct lzx_compressor, hc_mf_32) +
2241                                hc_matchfinder_size_32(max_bufsize);
2242         } else {
2243                 if (lzx_is_16_bit(max_bufsize))
2244                         return offsetof(struct lzx_compressor, bt_mf_16) +
2245                                bt_matchfinder_size_16(max_bufsize);
2246                 else
2247                         return offsetof(struct lzx_compressor, bt_mf_32) +
2248                                bt_matchfinder_size_32(max_bufsize);
2249         }
2250 }
2251
2252 static u64
2253 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2254                       bool destructive)
2255 {
2256         u64 size = 0;
2257
2258         if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2259                 return 0;
2260
2261         size += lzx_get_compressor_size(max_bufsize, compression_level);
2262         if (!destructive)
2263                 size += max_bufsize; /* in_buffer */
2264         return size;
2265 }
2266
2267 static int
2268 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2269                       bool destructive, void **c_ret)
2270 {
2271         unsigned window_order;
2272         struct lzx_compressor *c;
2273
2274         window_order = lzx_get_window_order(max_bufsize);
2275         if (window_order == 0)
2276                 return WIMLIB_ERR_INVALID_PARAM;
2277
2278         c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2279         if (!c)
2280                 goto oom0;
2281
2282         c->destructive = destructive;
2283
2284         c->num_main_syms = lzx_get_num_main_syms(window_order);
2285         c->window_order = window_order;
2286
2287         if (!c->destructive) {
2288                 c->in_buffer = MALLOC(max_bufsize);
2289                 if (!c->in_buffer)
2290                         goto oom1;
2291         }
2292
2293         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2294
2295                 /* Fast compression: Use lazy parsing.  */
2296
2297                 if (lzx_is_16_bit(max_bufsize))
2298                         c->impl = lzx_compress_lazy_16;
2299                 else
2300                         c->impl = lzx_compress_lazy_32;
2301                 c->max_search_depth = (60 * compression_level) / 20;
2302                 c->nice_match_length = (80 * compression_level) / 20;
2303
2304                 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2305                  * halves the max_search_depth when attempting a lazy match, and
2306                  * max_search_depth cannot be 0.  */
2307                 if (c->max_search_depth < 2)
2308                         c->max_search_depth = 2;
2309         } else {
2310
2311                 /* Normal / high compression: Use near-optimal parsing.  */
2312
2313                 if (lzx_is_16_bit(max_bufsize))
2314                         c->impl = lzx_compress_near_optimal_16;
2315                 else
2316                         c->impl = lzx_compress_near_optimal_32;
2317
2318                 /* Scale nice_match_length and max_search_depth with the
2319                  * compression level.  */
2320                 c->max_search_depth = (24 * compression_level) / 50;
2321                 c->nice_match_length = (48 * compression_level) / 50;
2322
2323                 /* Set a number of optimization passes appropriate for the
2324                  * compression level.  */
2325
2326                 c->num_optim_passes = 1;
2327
2328                 if (compression_level >= 45)
2329                         c->num_optim_passes++;
2330
2331                 /* Use more optimization passes for higher compression levels.
2332                  * But the more passes there are, the less they help --- so
2333                  * don't add them linearly.  */
2334                 if (compression_level >= 70) {
2335                         c->num_optim_passes++;
2336                         if (compression_level >= 100)
2337                                 c->num_optim_passes++;
2338                         if (compression_level >= 150)
2339                                 c->num_optim_passes++;
2340                         if (compression_level >= 200)
2341                                 c->num_optim_passes++;
2342                         if (compression_level >= 300)
2343                                 c->num_optim_passes++;
2344                 }
2345         }
2346
2347         /* max_search_depth == 0 is invalid.  */
2348         if (c->max_search_depth < 1)
2349                 c->max_search_depth = 1;
2350
2351         if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2352                 c->nice_match_length = LZX_MAX_MATCH_LEN;
2353
2354         lzx_init_offset_slot_tabs(c);
2355         *c_ret = c;
2356         return 0;
2357
2358 oom1:
2359         FREE(c);
2360 oom0:
2361         return WIMLIB_ERR_NOMEM;
2362 }
2363
2364 static size_t
2365 lzx_compress(const void *restrict in, size_t in_nbytes,
2366              void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2367 {
2368         struct lzx_compressor *c = _c;
2369         struct lzx_output_bitstream os;
2370         size_t result;
2371
2372         /* Don't bother trying to compress very small inputs.  */
2373         if (in_nbytes < 100)
2374                 return 0;
2375
2376         /* Copy the input data into the internal buffer and preprocess it.  */
2377         if (c->destructive)
2378                 c->in_buffer = (void *)in;
2379         else
2380                 memcpy(c->in_buffer, in, in_nbytes);
2381         c->in_nbytes = in_nbytes;
2382         lzx_preprocess(c->in_buffer, in_nbytes);
2383
2384         /* Initially, the previous Huffman codeword lengths are all zeroes.  */
2385         c->codes_index = 0;
2386         memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2387
2388         /* Initialize the output bitstream.  */
2389         lzx_init_output(&os, out, out_nbytes_avail);
2390
2391         /* Call the compression level-specific compress() function.  */
2392         (*c->impl)(c, &os);
2393
2394         /* Flush the output bitstream and return the compressed size or 0.  */
2395         result = lzx_flush_output(&os);
2396         if (!result && c->destructive)
2397                 lzx_postprocess(c->in_buffer, c->in_nbytes);
2398         return result;
2399 }
2400
2401 static void
2402 lzx_free_compressor(void *_c)
2403 {
2404         struct lzx_compressor *c = _c;
2405
2406         if (!c->destructive)
2407                 FREE(c->in_buffer);
2408         FREE(c);
2409 }
2410
2411 const struct compressor_ops lzx_compressor_ops = {
2412         .get_needed_memory  = lzx_get_needed_memory,
2413         .create_compressor  = lzx_create_compressor,
2414         .compress           = lzx_compress,
2415         .free_compressor    = lzx_free_compressor,
2416 };