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