]> wimlib.net Git - wimlib/blob - src/lzms-compress.c
a696e261a3d331b88084f037af6124f6485f6c0a
[wimlib] / src / lzms-compress.c
1 /*
2  * lzms-compress.c
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 /* This a compressor for the LZMS compression format.  More details about this
25  * format can be found in lzms-decompress.c.
26  *
27  * NOTE: this compressor currently does not code any delta matches.
28  */
29
30 #ifdef HAVE_CONFIG_H
31 #  include "config.h"
32 #endif
33
34 #include "wimlib.h"
35 #include "wimlib/compiler.h"
36 #include "wimlib/compressor_ops.h"
37 #include "wimlib/compress_common.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/lz_sarray.h"
41 #include "wimlib/lzms.h"
42 #include "wimlib/util.h"
43
44 #include <string.h>
45 #include <limits.h>
46 #include <pthread.h>
47
48 #define LZMS_OPTIM_ARRAY_SIZE   1024
49
50 struct lzms_compressor;
51 struct lzms_adaptive_state {
52         struct lzms_lz_lru_queues lru;
53         u8 main_state;
54         u8 match_state;
55         u8 lz_match_state;
56         u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
57 };
58 #define LZ_ADAPTIVE_STATE struct lzms_adaptive_state
59 #define LZ_COMPRESSOR     struct lzms_compressor
60 #include "wimlib/lz_optimal.h"
61
62 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
63  * a series of 16-bit little endian coding units.  */
64 struct lzms_output_bitstream {
65         /* Buffer variable containing zero or more bits that have been logically
66          * written to the bitstream but not yet written to memory.  This must be
67          * at least as large as the coding unit size.  */
68         u16 bitbuf;
69
70         /* Number of bits in @bitbuf that are valid.  */
71         unsigned num_free_bits;
72
73         /* Pointer to one past the next position in the compressed data buffer
74          * at which to output a 16-bit coding unit.  */
75         le16 *out;
76
77         /* Maximum number of 16-bit coding units that can still be output to
78          * the compressed data buffer.  */
79         size_t num_le16_remaining;
80
81         /* Set to %true if not all coding units could be output due to
82          * insufficient space.  */
83         bool overrun;
84 };
85
86 /* Stucture used for range encoding (raw version).  */
87 struct lzms_range_encoder_raw {
88
89         /* A 33-bit variable that holds the low boundary of the current range.
90          * The 33rd bit is needed to catch carries.  */
91         u64 low;
92
93         /* Size of the current range.  */
94         u32 range;
95
96         /* Next 16-bit coding unit to output.  */
97         u16 cache;
98
99         /* Number of 16-bit coding units whose output has been delayed due to
100          * possible carrying.  The first such coding unit is @cache; all
101          * subsequent such coding units are 0xffff.  */
102         u32 cache_size;
103
104         /* Pointer to the next position in the compressed data buffer at which
105          * to output a 16-bit coding unit.  */
106         le16 *out;
107
108         /* Maximum number of 16-bit coding units that can still be output to
109          * the compressed data buffer.  */
110         size_t num_le16_remaining;
111
112         /* %true when the very first coding unit has not yet been output.  */
113         bool first;
114
115         /* Set to %true if not all coding units could be output due to
116          * insufficient space.  */
117         bool overrun;
118 };
119
120 /* Structure used for range encoding.  This wraps around `struct
121  * lzms_range_encoder_raw' to use and maintain probability entries.  */
122 struct lzms_range_encoder {
123         /* Pointer to the raw range encoder, which has no persistent knowledge
124          * of probabilities.  Multiple lzms_range_encoder's share the same
125          * lzms_range_encoder_raw.  */
126         struct lzms_range_encoder_raw *rc;
127
128         /* Bits recently encoded by this range encoder.  This are used as in
129          * index into @prob_entries.  */
130         u32 state;
131
132         /* Bitmask for @state to prevent its value from exceeding the number of
133          * probability entries.  */
134         u32 mask;
135
136         /* Probability entries being used for this range encoder.  */
137         struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
138 };
139
140 /* Structure used for Huffman encoding.  */
141 struct lzms_huffman_encoder {
142
143         /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
144          * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
145          */
146         struct lzms_output_bitstream *os;
147
148         /* Number of symbols that have been written using this code far.  Reset
149          * to 0 whenever the code is rebuilt.  */
150         u32 num_syms_written;
151
152         /* When @num_syms_written reaches this number, the Huffman code must be
153          * rebuilt.  */
154         u32 rebuild_freq;
155
156         /* Number of symbols in the represented Huffman code.  */
157         unsigned num_syms;
158
159         /* Running totals of symbol frequencies.  These are diluted slightly
160          * whenever the code is rebuilt.  */
161         u32 sym_freqs[LZMS_MAX_NUM_SYMS];
162
163         /* The length, in bits, of each symbol in the Huffman code.  */
164         u8 lens[LZMS_MAX_NUM_SYMS];
165
166         /* The codeword of each symbol in the Huffman code.  */
167         u16 codewords[LZMS_MAX_NUM_SYMS];
168 };
169
170 /* State of the LZMS compressor.  */
171 struct lzms_compressor {
172         /* Pointer to a buffer holding the preprocessed data to compress.  */
173         u8 *window;
174
175         /* Current position in @buffer.  */
176         u32 cur_window_pos;
177
178         /* Size of the data in @buffer.  */
179         u32 window_size;
180
181         /* Suffix array match-finder.  */
182         struct lz_sarray lz_sarray;
183
184         /* Temporary space to store found matches.  */
185         struct raw_match *matches;
186
187         /* Match-chooser.  */
188         struct lz_match_chooser mc;
189
190         /* Maximum block size this compressor instantiation allows.  This is the
191          * allocated size of @window.  */
192         u32 max_block_size;
193
194         /* Raw range encoder which outputs to the beginning of the compressed
195          * data buffer, proceeding forwards.  */
196         struct lzms_range_encoder_raw rc;
197
198         /* Bitstream which outputs to the end of the compressed data buffer,
199          * proceeding backwards.  */
200         struct lzms_output_bitstream os;
201
202         /* Range encoders.  */
203         struct lzms_range_encoder main_range_encoder;
204         struct lzms_range_encoder match_range_encoder;
205         struct lzms_range_encoder lz_match_range_encoder;
206         struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
207         struct lzms_range_encoder delta_match_range_encoder;
208         struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
209
210         /* Huffman encoders.  */
211         struct lzms_huffman_encoder literal_encoder;
212         struct lzms_huffman_encoder lz_offset_encoder;
213         struct lzms_huffman_encoder length_encoder;
214         struct lzms_huffman_encoder delta_power_encoder;
215         struct lzms_huffman_encoder delta_offset_encoder;
216
217         /* LRU (least-recently-used) queues for match information.  */
218         struct lzms_lru_queues lru;
219
220         /* Used for preprocessing.  */
221         s32 last_target_usages[65536];
222 };
223
224 /* Initialize the output bitstream @os to write forwards to the specified
225  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
226 static void
227 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
228                            le16 *out, size_t out_limit)
229 {
230         os->bitbuf = 0;
231         os->num_free_bits = 16;
232         os->out = out + out_limit;
233         os->num_le16_remaining = out_limit;
234         os->overrun = false;
235 }
236
237 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
238  * from high-order to low-order), to the output bitstream @os.  */
239 static void
240 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
241                                u32 bits, unsigned num_bits)
242 {
243         bits &= (1U << num_bits) - 1;
244
245         while (num_bits > os->num_free_bits) {
246
247                 if (unlikely(os->num_le16_remaining == 0)) {
248                         os->overrun = true;
249                         return;
250                 }
251
252                 unsigned num_fill_bits = os->num_free_bits;
253
254                 os->bitbuf <<= num_fill_bits;
255                 os->bitbuf |= bits >> (num_bits - num_fill_bits);
256
257                 *--os->out = cpu_to_le16(os->bitbuf);
258                 --os->num_le16_remaining;
259
260                 os->num_free_bits = 16;
261                 num_bits -= num_fill_bits;
262                 bits &= (1U << num_bits) - 1;
263         }
264         os->bitbuf <<= num_bits;
265         os->bitbuf |= bits;
266         os->num_free_bits -= num_bits;
267 }
268
269 /* Flush the output bitstream, ensuring that all bits written to it have been
270  * written to memory.  Returns %true if all bits were output successfully, or
271  * %false if an overrun occurred.  */
272 static bool
273 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
274 {
275         if (os->num_free_bits != 16)
276                 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
277         return !os->overrun;
278 }
279
280 /* Initialize the range encoder @rc to write forwards to the specified
281  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
282 static void
283 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
284                             le16 *out, size_t out_limit)
285 {
286         rc->low = 0;
287         rc->range = 0xffffffff;
288         rc->cache = 0;
289         rc->cache_size = 1;
290         rc->out = out;
291         rc->num_le16_remaining = out_limit;
292         rc->first = true;
293         rc->overrun = false;
294 }
295
296 /*
297  * Attempt to flush bits from the range encoder.
298  *
299  * Note: this is based on the public domain code for LZMA written by Igor
300  * Pavlov.  The only differences in this function are that in LZMS the bits must
301  * be output in 16-bit coding units instead of 8-bit coding units, and that in
302  * LZMS the first coding unit is not ignored by the decompressor, so the encoder
303  * cannot output a dummy value to that position.
304  *
305  * The basic idea is that we're writing bits from @rc->low to the output.
306  * However, due to carrying, the writing of coding units with value 0xffff, as
307  * well as one prior coding unit, must be delayed until it is determined whether
308  * a carry is needed.
309  */
310 static void
311 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
312 {
313         LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
314                    rc->low, rc->cache, rc->cache_size);
315         if ((u32)(rc->low) < 0xffff0000 ||
316             (u32)(rc->low >> 32) != 0)
317         {
318                 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
319                  * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1).  */
320                 do {
321                         if (!rc->first) {
322                                 if (rc->num_le16_remaining == 0) {
323                                         rc->overrun = true;
324                                         return;
325                                 }
326                                 *rc->out++ = cpu_to_le16(rc->cache +
327                                                          (u16)(rc->low >> 32));
328                                 --rc->num_le16_remaining;
329                         } else {
330                                 rc->first = false;
331                         }
332
333                         rc->cache = 0xffff;
334                 } while (--rc->cache_size != 0);
335
336                 rc->cache = (rc->low >> 16) & 0xffff;
337         }
338         ++rc->cache_size;
339         rc->low = (rc->low & 0xffff) << 16;
340 }
341
342 static void
343 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
344 {
345         if (rc->range <= 0xffff) {
346                 rc->range <<= 16;
347                 lzms_range_encoder_raw_shift_low(rc);
348         }
349 }
350
351 static bool
352 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
353 {
354         for (unsigned i = 0; i < 4; i++)
355                 lzms_range_encoder_raw_shift_low(rc);
356         return !rc->overrun;
357 }
358
359 /* Encode the next bit using the range encoder (raw version).
360  *
361  * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0.  */
362 static void
363 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
364                                   u32 prob)
365 {
366         lzms_range_encoder_raw_normalize(rc);
367
368         u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
369         if (bit == 0) {
370                 rc->range = bound;
371         } else {
372                 rc->low += bound;
373                 rc->range -= bound;
374         }
375 }
376
377 /* Encode a bit using the specified range encoder. This wraps around
378  * lzms_range_encoder_raw_encode_bit() to handle using and updating the
379  * appropriate probability table.  */
380 static void
381 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
382 {
383         struct lzms_probability_entry *prob_entry;
384         u32 prob;
385
386         /* Load the probability entry corresponding to the current state.  */
387         prob_entry = &enc->prob_entries[enc->state];
388
389         /* Treat the number of zero bits in the most recently encoded
390          * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
391          * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0.  However,
392          * don't allow 0% or 100% probabilities.  */
393         prob = prob_entry->num_recent_zero_bits;
394         if (prob == 0)
395                 prob = 1;
396         else if (prob == LZMS_PROBABILITY_MAX)
397                 prob = LZMS_PROBABILITY_MAX - 1;
398
399         /* Encode the next bit.  */
400         lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
401
402         /* Update the state based on the newly encoded bit.  */
403         enc->state = ((enc->state << 1) | bit) & enc->mask;
404
405         /* Update the recent bits, including the cached count of 0's.  */
406         BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
407         if (bit == 0) {
408                 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
409                         /* Replacing 1 bit with 0 bit; increment the zero count.
410                          */
411                         prob_entry->num_recent_zero_bits++;
412                 }
413         } else {
414                 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
415                         /* Replacing 0 bit with 1 bit; decrement the zero count.
416                          */
417                         prob_entry->num_recent_zero_bits--;
418                 }
419         }
420         prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
421 }
422
423 /* Encode a symbol using the specified Huffman encoder.  */
424 static void
425 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
426 {
427         LZMS_ASSERT(sym < enc->num_syms);
428         lzms_output_bitstream_put_bits(enc->os,
429                                        enc->codewords[sym],
430                                        enc->lens[sym]);
431         ++enc->sym_freqs[sym];
432         if (++enc->num_syms_written == enc->rebuild_freq) {
433                 /* Adaptive code needs to be rebuilt.  */
434                 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
435                 make_canonical_huffman_code(enc->num_syms,
436                                             LZMS_MAX_CODEWORD_LEN,
437                                             enc->sym_freqs,
438                                             enc->lens,
439                                             enc->codewords);
440
441                 /* Dilute the frequencies.  */
442                 for (unsigned i = 0; i < enc->num_syms; i++) {
443                         enc->sym_freqs[i] >>= 1;
444                         enc->sym_freqs[i] += 1;
445                 }
446                 enc->num_syms_written = 0;
447         }
448 }
449
450 static void
451 lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
452 {
453         unsigned slot;
454         unsigned num_extra_bits;
455         u32 extra_bits;
456
457         slot = lzms_get_length_slot(length);
458
459         num_extra_bits = lzms_extra_length_bits[slot];
460
461         extra_bits = length - lzms_length_slot_base[slot];
462
463         lzms_huffman_encode_symbol(enc, slot);
464         lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
465 }
466
467 static void
468 lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
469 {
470         unsigned slot;
471         unsigned num_extra_bits;
472         u32 extra_bits;
473
474         slot = lzms_get_position_slot(offset);
475
476         num_extra_bits = lzms_extra_position_bits[slot];
477
478         extra_bits = offset - lzms_position_slot_base[slot];
479
480         lzms_huffman_encode_symbol(enc, slot);
481         lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
482 }
483
484 static void
485 lzms_begin_encode_item(struct lzms_compressor *ctx)
486 {
487         ctx->lru.lz.upcoming_offset = 0;
488         ctx->lru.delta.upcoming_offset = 0;
489         ctx->lru.delta.upcoming_power = 0;
490 }
491
492 static void
493 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
494 {
495         LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
496         ctx->cur_window_pos += length;
497         lzms_update_lru_queues(&ctx->lru);
498 }
499
500 /* Encode a literal byte.  */
501 static void
502 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
503 {
504         LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
505                    ctx->cur_window_pos, literal, literal);
506
507         lzms_begin_encode_item(ctx);
508
509         /* Main bit: 0 = a literal, not a match.  */
510         lzms_range_encode_bit(&ctx->main_range_encoder, 0);
511
512         /* Encode the literal using the current literal Huffman code.  */
513         lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
514
515         lzms_end_encode_item(ctx, 1);
516 }
517
518 /* Encode a (length, offset) pair (LZ match).  */
519 static void
520 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
521 {
522         int recent_offset_idx;
523
524         LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
525                    ctx->cur_window_pos, length, offset);
526
527         LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
528         LZMS_ASSERT(offset <= ctx->cur_window_pos);
529         LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
530                             &ctx->window[ctx->cur_window_pos - offset],
531                             length));
532
533         lzms_begin_encode_item(ctx);
534
535         /* Main bit: 1 = a match, not a literal.  */
536         lzms_range_encode_bit(&ctx->main_range_encoder, 1);
537
538         /* Match bit: 0 = a LZ match, not a delta match.  */
539         lzms_range_encode_bit(&ctx->match_range_encoder, 0);
540
541         /* Determine if the offset can be represented as a recent offset.  */
542         for (recent_offset_idx = 0;
543              recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
544              recent_offset_idx++)
545                 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
546                         break;
547
548         if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
549                 /* Explicit offset.  */
550
551                 /* LZ match bit: 0 = explicit offset, not a recent offset.  */
552                 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
553
554                 /* Encode the match offset.  */
555                 lzms_encode_offset(&ctx->lz_offset_encoder, offset);
556         } else {
557                 int i;
558
559                 /* Recent offset.  */
560
561                 /* LZ match bit: 1 = recent offset, not an explicit offset.  */
562                 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
563
564                 /* Encode the recent offset index.  A 1 bit is encoded for each
565                  * index passed up.  This sequence of 1 bits is terminated by a
566                  * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
567                  * bits have been encoded.  */
568                 for (i = 0; i < recent_offset_idx; i++)
569                         lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
570
571                 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
572                         lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
573
574                 /* Initial update of the LZ match offset LRU queue.  */
575                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
576                         ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
577         }
578
579         /* Encode the match length.  */
580         lzms_encode_length(&ctx->length_encoder, length);
581
582         /* Save the match offset for later insertion at the front of the LZ
583          * match offset LRU queue.  */
584         ctx->lru.lz.upcoming_offset = offset;
585
586         lzms_end_encode_item(ctx, length);
587 }
588
589 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
590  * Unlike lzms_get_lz_match_cost(), which does a true cost evaluation, this
591  * simply prioritize matches based on their offset.  */
592 static input_idx_t
593 lzms_lz_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
594 {
595         const struct lzms_lz_lru_queues *lru = _lru;
596
597         for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
598                 if (offset == lru->recent_offsets[i])
599                         return i;
600
601         return offset;
602 }
603
604 #define LZMS_COST_SHIFT 5
605
606 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
607
608 static u32
609 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
610
611 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
612 #  include <math.h>
613 #endif
614
615 static void
616 lzms_do_init_rc_costs(void)
617 {
618         /* Fill in a table that maps range coding probabilities needed to code a
619          * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
620          * handle fractional costs) needed to code that bit X.
621          *
622          * Consider the range of the range decoder.  To eliminate exactly half
623          * the range (logical probability of 0.5), we need exactly 1 bit.  For
624          * lower probabilities we need more bits and for higher probabilities we
625          * need fewer bits.  In general, a logical probability of N will
626          * eliminate the proportion 1 - N of the range; this information takes
627          * log2(1 / N) bits to encode.
628          *
629          * The below loop is simply calculating this number of bits for each
630          * possible probability allowed by the LZMS compression format, but
631          * without using real numbers.  To handle fractional probabilities, each
632          * cost is multiplied by (1 << LZMS_COST_SHIFT).  These techniques are
633          * based on those used by LZMA.
634          *
635          * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
636          * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
637          * 63 / 64.
638          */
639         for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
640                 u32 prob = i;
641
642                 if (prob == 0)
643                         prob = 1;
644                 else if (prob == LZMS_PROBABILITY_MAX)
645                         prob = LZMS_PROBABILITY_MAX - 1;
646
647         #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
648                 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
649                                         (1 << LZMS_COST_SHIFT);
650         #else
651                 u32 w = prob;
652                 u32 bit_count = 0;
653                 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
654                         w *= w;
655                         bit_count <<= 1;
656                         while (w >= (1U << 16)) {
657                                 w >>= 1;
658                                 ++bit_count;
659                         }
660                 }
661                 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
662                                    (15 + bit_count);
663         #endif
664         }
665 }
666
667 static void
668 lzms_init_rc_costs(void)
669 {
670         static bool done = false;
671         static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
672
673         if (unlikely(!done)) {
674                 pthread_mutex_lock(&mutex);
675                 if (!done) {
676                         lzms_do_init_rc_costs();
677                         done = true;
678                 }
679                 pthread_mutex_unlock(&mutex);
680         }
681 }
682
683 /*
684  * Return the cost to range-encode the specified bit when in the specified
685  * state.
686  *
687  * @enc         The range encoder to use.
688  * @cur_state   Current state, which indicates the probability entry to choose.
689  *              Updated by this function.
690  * @bit         The bit to encode (0 or 1).
691  */
692 static u32
693 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
694 {
695         u32 prob_zero;
696         u32 prob_correct;
697
698         prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
699
700         *cur_state = (*cur_state << 1) | bit;
701
702         if (bit == 0)
703                 prob_correct = prob_zero;
704         else
705                 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
706
707         return lzms_rc_costs[prob_correct];
708 }
709
710 static u32
711 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
712 {
713         return enc->lens[sym] << LZMS_COST_SHIFT;
714 }
715
716 static u32
717 lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
718 {
719         u32 slot;
720         u32 num_extra_bits;
721         u32 cost = 0;
722
723         slot = lzms_get_position_slot(offset);
724
725         cost += lzms_huffman_symbol_cost(enc, slot);
726
727         num_extra_bits = lzms_extra_position_bits[slot];
728
729         cost += num_extra_bits << LZMS_COST_SHIFT;
730
731         return cost;
732 }
733
734 static u32
735 lzms_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
736 {
737         u32 slot;
738         u32 num_extra_bits;
739         u32 cost = 0;
740
741         slot = lzms_get_length_slot(length);
742
743         cost += lzms_huffman_symbol_cost(enc, slot);
744
745         num_extra_bits = lzms_extra_length_bits[slot];
746
747         cost += num_extra_bits << LZMS_COST_SHIFT;
748
749         return cost;
750 }
751
752 static u32
753 lzms_get_matches(struct lzms_compressor *ctx,
754                  const struct lzms_adaptive_state *state,
755                  struct raw_match **matches_ret)
756 {
757         *matches_ret = ctx->matches;
758         return lz_sarray_get_matches(&ctx->lz_sarray,
759                                      ctx->matches,
760                                      lzms_lz_match_cost_fast,
761                                      &state->lru);
762 }
763
764 static void
765 lzms_skip_bytes(struct lzms_compressor *ctx, input_idx_t n)
766 {
767         while (n--)
768                 lz_sarray_skip_position(&ctx->lz_sarray);
769 }
770
771 static u32
772 lzms_get_prev_literal_cost(struct lzms_compressor *ctx,
773                            struct lzms_adaptive_state *state)
774 {
775         u8 literal = ctx->window[lz_sarray_get_pos(&ctx->lz_sarray) - 1];
776         u32 cost = 0;
777
778         state->lru.upcoming_offset = 0;
779         lzms_update_lz_lru_queues(&state->lru);
780
781         cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
782                                  &state->main_state, 0);
783
784         cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
785
786         return cost;
787 }
788
789 static u32
790 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
791                        struct lzms_adaptive_state *state,
792                        input_idx_t length, input_idx_t offset)
793 {
794         u32 cost = 0;
795         int recent_offset_idx;
796
797         cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
798                                  &state->main_state, 1);
799         cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
800                                  &state->match_state, 0);
801
802         for (recent_offset_idx = 0;
803              recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
804              recent_offset_idx++)
805                 if (offset == state->lru.recent_offsets[recent_offset_idx])
806                         break;
807
808         if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
809                 /* Explicit offset.  */
810                 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
811                                          &state->lz_match_state, 0);
812
813                 cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
814         } else {
815                 int i;
816
817                 /* Recent offset.  */
818                 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
819                                          &state->lz_match_state, 1);
820
821                 for (i = 0; i < recent_offset_idx; i++)
822                         cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
823                                                  &state->lz_repeat_match_state[i], 0);
824
825                 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
826                         cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
827                                                  &state->lz_repeat_match_state[i], 1);
828
829
830                 /* Initial update of the LZ match offset LRU queue.  */
831                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
832                         state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
833         }
834
835         cost += lzms_length_cost(&ctx->length_encoder, length);
836
837         state->lru.upcoming_offset = offset;
838         lzms_update_lz_lru_queues(&state->lru);
839
840         return cost;
841 }
842
843 static struct raw_match
844 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
845 {
846         struct lzms_adaptive_state initial_state;
847
848         initial_state.lru = ctx->lru.lz;
849         initial_state.main_state = ctx->main_range_encoder.state;
850         initial_state.match_state = ctx->match_range_encoder.state;
851         initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
852         for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
853                 initial_state.lz_repeat_match_state[i] =
854                         ctx->lz_repeat_match_range_encoders[i].state;
855         return lz_get_near_optimal_match(&ctx->mc,
856                                          lzms_get_matches,
857                                          lzms_skip_bytes,
858                                          lzms_get_prev_literal_cost,
859                                          lzms_get_lz_match_cost,
860                                          ctx,
861                                          &initial_state);
862 }
863
864 /*
865  * The main loop for the LZMS compressor.
866  *
867  * Notes:
868  *
869  * - This uses near-optimal LZ parsing backed by a suffix-array match-finder.
870  *   More details can be found in the corresponding files (lz_optimal.h,
871  *   lz_sarray.{h,c}).
872  *
873  * - This does not output any delta matches.  It would take a specialized
874  *   algorithm to find them, then more code in lz_optimal.h and here to handle
875  *   evaluating and outputting them.
876  *
877  * - The costs of literals and matches are estimated using the range encoder
878  *   states and the semi-adaptive Huffman codes.  Except for range encoding
879  *   states, costs are assumed to be constant throughout a single run of the
880  *   parsing algorithm, which can parse up to LZMS_OPTIM_ARRAY_SIZE bytes of
881  *   data.  This introduces a source of inaccuracy because the probabilities and
882  *   Huffman codes can change over this part of the data.
883  */
884 static void
885 lzms_encode(struct lzms_compressor *ctx)
886 {
887         struct raw_match match;
888
889         /* Load window into suffix array match-finder.  */
890         lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
891
892         /* Reset the match-chooser.  */
893         lz_match_chooser_begin(&ctx->mc);
894
895         while (ctx->cur_window_pos != ctx->window_size) {
896                 match = lzms_get_near_optimal_match(ctx);
897                 if (match.len <= 1)
898                         lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
899                 else
900                         lzms_encode_lz_match(ctx, match.len, match.offset);
901         }
902 }
903
904 static void
905 lzms_init_range_encoder(struct lzms_range_encoder *enc,
906                         struct lzms_range_encoder_raw *rc, u32 num_states)
907 {
908         enc->rc = rc;
909         enc->state = 0;
910         enc->mask = num_states - 1;
911         for (u32 i = 0; i < num_states; i++) {
912                 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
913                 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
914         }
915 }
916
917 static void
918 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
919                           struct lzms_output_bitstream *os,
920                           unsigned num_syms,
921                           unsigned rebuild_freq)
922 {
923         enc->os = os;
924         enc->num_syms_written = 0;
925         enc->rebuild_freq = rebuild_freq;
926         enc->num_syms = num_syms;
927         for (unsigned i = 0; i < num_syms; i++)
928                 enc->sym_freqs[i] = 1;
929
930         make_canonical_huffman_code(enc->num_syms,
931                                     LZMS_MAX_CODEWORD_LEN,
932                                     enc->sym_freqs,
933                                     enc->lens,
934                                     enc->codewords);
935 }
936
937 /* Initialize the LZMS compressor.  */
938 static void
939 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
940                      le16 *cdata, u32 clen16)
941 {
942         unsigned num_position_slots;
943
944         /* Copy the uncompressed data into the @ctx->window buffer.  */
945         memcpy(ctx->window, udata, ulen);
946         ctx->cur_window_pos = 0;
947         ctx->window_size = ulen;
948
949         /* Initialize the raw range encoder (writing forwards).  */
950         lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
951
952         /* Initialize the output bitstream for Huffman symbols and verbatim bits
953          * (writing backwards).  */
954         lzms_output_bitstream_init(&ctx->os, cdata, clen16);
955
956         /* Calculate the number of position slots needed for this compressed
957          * block.  */
958         num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
959
960         LZMS_DEBUG("Using %u position slots", num_position_slots);
961
962         /* Initialize Huffman encoders for each alphabet used in the compressed
963          * representation.  */
964         lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
965                                   LZMS_NUM_LITERAL_SYMS,
966                                   LZMS_LITERAL_CODE_REBUILD_FREQ);
967
968         lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
969                                   num_position_slots,
970                                   LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
971
972         lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
973                                   LZMS_NUM_LEN_SYMS,
974                                   LZMS_LENGTH_CODE_REBUILD_FREQ);
975
976         lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
977                                   num_position_slots,
978                                   LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
979
980         lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
981                                   LZMS_NUM_DELTA_POWER_SYMS,
982                                   LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
983
984         /* Initialize range encoders, all of which wrap around the same
985          * lzms_range_encoder_raw.  */
986         lzms_init_range_encoder(&ctx->main_range_encoder,
987                                 &ctx->rc, LZMS_NUM_MAIN_STATES);
988
989         lzms_init_range_encoder(&ctx->match_range_encoder,
990                                 &ctx->rc, LZMS_NUM_MATCH_STATES);
991
992         lzms_init_range_encoder(&ctx->lz_match_range_encoder,
993                                 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
994
995         for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
996                 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
997                                         &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
998
999         lzms_init_range_encoder(&ctx->delta_match_range_encoder,
1000                                 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1001
1002         for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1003                 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1004                                         &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1005
1006         /* Initialize LRU match information.  */
1007         lzms_init_lru_queues(&ctx->lru);
1008 }
1009
1010 /* Flush the output streams, prepare the final compressed data, and return its
1011  * size in bytes.
1012  *
1013  * A return value of 0 indicates that the data could not be compressed to fit in
1014  * the available space.  */
1015 static size_t
1016 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1017 {
1018         size_t num_forwards_bytes;
1019         size_t num_backwards_bytes;
1020         size_t compressed_size;
1021
1022         /* Flush both the forwards and backwards streams, and make sure they
1023          * didn't cross each other and start overwriting each other's data.  */
1024         if (!lzms_output_bitstream_flush(&ctx->os)) {
1025                 LZMS_DEBUG("Backwards bitstream overrun.");
1026                 return 0;
1027         }
1028
1029         if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1030                 LZMS_DEBUG("Forwards bitstream overrun.");
1031                 return 0;
1032         }
1033
1034         if (ctx->rc.out > ctx->os.out) {
1035                 LZMS_DEBUG("Two bitstreams crossed.");
1036                 return 0;
1037         }
1038
1039         /* Now the compressed buffer contains the data output by the forwards
1040          * bitstream, then empty space, then data output by the backwards
1041          * bitstream.  Move the data output by the backwards bitstream to be
1042          * adjacent to the data output by the forward bitstream, and calculate
1043          * the compressed size that this results in.  */
1044         num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1045         num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1046
1047         memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1048
1049         compressed_size = num_forwards_bytes + num_backwards_bytes;
1050         LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1051                    "compressed_size=%zu",
1052                    num_forwards_bytes, num_backwards_bytes, compressed_size);
1053         LZMS_ASSERT(compressed_size % 2 == 0);
1054         return compressed_size;
1055 }
1056
1057 static size_t
1058 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1059               void *compressed_data, size_t compressed_size_avail, void *_ctx)
1060 {
1061         struct lzms_compressor *ctx = _ctx;
1062         size_t compressed_size;
1063
1064         LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1065                    uncompressed_size, compressed_size_avail);
1066
1067         /* Make sure the uncompressed size is compatible with this compressor.
1068          */
1069         if (uncompressed_size > ctx->max_block_size) {
1070                 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
1071                            "only supports %u bytes",
1072                            uncompressed_size, ctx->max_block_size);
1073                 return 0;
1074         }
1075
1076         /* Don't bother compressing extremely small inputs.  */
1077         if (uncompressed_size < 4) {
1078                 LZMS_DEBUG("Input too small to bother compressing.");
1079                 return 0;
1080         }
1081
1082         /* Cap the available compressed size to a 32-bit integer and round it
1083          * down to the nearest multiple of 2.  */
1084         if (compressed_size_avail > UINT32_MAX)
1085                 compressed_size_avail = UINT32_MAX;
1086         if (compressed_size_avail & 1)
1087                 compressed_size_avail--;
1088
1089         /* Initialize the compressor structures.  */
1090         lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1091                              compressed_data, compressed_size_avail / 2);
1092
1093         /* Preprocess the uncompressed data.  */
1094         lzms_x86_filter(ctx->window, ctx->window_size,
1095                         ctx->last_target_usages, false);
1096
1097         /* Compute and encode a literal/match sequence that decompresses to the
1098          * preprocessed data.  */
1099         lzms_encode(ctx);
1100
1101         /* Get and return the compressed data size.  */
1102         compressed_size = lzms_finalize(ctx, compressed_data,
1103                                         compressed_size_avail);
1104
1105         if (compressed_size == 0) {
1106                 LZMS_DEBUG("Data did not compress to requested size or less.");
1107                 return 0;
1108         }
1109
1110         LZMS_DEBUG("Compressed %zu => %zu bytes",
1111                    uncompressed_size, compressed_size);
1112
1113 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
1114         /* Verify that we really get the same thing back when decompressing.  */
1115         {
1116                 struct wimlib_decompressor *decompressor;
1117
1118                 LZMS_DEBUG("Verifying LZMS compression.");
1119
1120                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
1121                                                     ctx->max_block_size,
1122                                                     NULL,
1123                                                     &decompressor))
1124                 {
1125                         int ret;
1126                         ret = wimlib_decompress(compressed_data,
1127                                                 compressed_size,
1128                                                 ctx->window,
1129                                                 uncompressed_size,
1130                                                 decompressor);
1131                         wimlib_free_decompressor(decompressor);
1132
1133                         if (ret) {
1134                                 ERROR("Failed to decompress data we "
1135                                       "compressed using LZMS algorithm");
1136                                 wimlib_assert(0);
1137                                 return 0;
1138                         }
1139                         if (memcmp(uncompressed_data, ctx->window,
1140                                    uncompressed_size))
1141                         {
1142                                 ERROR("Data we compressed using LZMS algorithm "
1143                                       "didn't decompress to original");
1144                                 wimlib_assert(0);
1145                                 return 0;
1146                         }
1147                 } else {
1148                         WARNING("Failed to create decompressor for "
1149                                 "data verification!");
1150                 }
1151         }
1152 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION  */
1153
1154         return compressed_size;
1155 }
1156
1157 static void
1158 lzms_free_compressor(void *_ctx)
1159 {
1160         struct lzms_compressor *ctx = _ctx;
1161
1162         if (ctx) {
1163                 FREE(ctx->window);
1164                 FREE(ctx->matches);
1165                 lz_sarray_destroy(&ctx->lz_sarray);
1166                 lz_match_chooser_destroy(&ctx->mc);
1167                 FREE(ctx);
1168         }
1169 }
1170
1171 static const struct wimlib_lzms_compressor_params lzms_default = {
1172         .hdr = sizeof(struct wimlib_lzms_compressor_params),
1173         .min_match_length = 2,
1174         .max_match_length = UINT32_MAX,
1175         .nice_match_length = 32,
1176         .max_search_depth = 50,
1177         .max_matches_per_pos = 3,
1178         .optim_array_length = 1024,
1179 };
1180
1181 static const struct wimlib_lzms_compressor_params *
1182 lzms_get_params(const struct wimlib_compressor_params_header *_params)
1183 {
1184         const struct wimlib_lzms_compressor_params *params =
1185                 (const struct wimlib_lzms_compressor_params*)_params;
1186
1187         if (params == NULL)
1188                 params = &lzms_default;
1189
1190         return params;
1191 }
1192
1193 static int
1194 lzms_create_compressor(size_t max_block_size,
1195                        const struct wimlib_compressor_params_header *_params,
1196                        void **ctx_ret)
1197 {
1198         struct lzms_compressor *ctx;
1199         const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1200
1201         if (max_block_size == 0 || max_block_size >= INT32_MAX) {
1202                 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
1203                 return WIMLIB_ERR_INVALID_PARAM;
1204         }
1205
1206         ctx = CALLOC(1, sizeof(struct lzms_compressor));
1207         if (ctx == NULL)
1208                 goto oom;
1209
1210         ctx->window = MALLOC(max_block_size);
1211         if (ctx->window == NULL)
1212                 goto oom;
1213
1214         ctx->matches = MALLOC(min(params->max_match_length -
1215                                         params->min_match_length + 1,
1216                                   params->max_matches_per_pos) *
1217                                 sizeof(ctx->matches[0]));
1218         if (ctx->matches == NULL)
1219                 goto oom;
1220
1221         if (!lz_sarray_init(&ctx->lz_sarray, max_block_size,
1222                             params->min_match_length,
1223                             params->max_match_length,
1224                             params->max_search_depth,
1225                             params->max_matches_per_pos))
1226                 goto oom;
1227
1228         if (!lz_match_chooser_init(&ctx->mc,
1229                                    params->optim_array_length,
1230                                    params->nice_match_length,
1231                                    params->max_match_length))
1232                 goto oom;
1233
1234         /* Initialize position and length slot data if not done already.  */
1235         lzms_init_slots();
1236
1237         /* Initialize range encoding cost table if not done already.  */
1238         lzms_init_rc_costs();
1239
1240         ctx->max_block_size = max_block_size;
1241
1242         *ctx_ret = ctx;
1243         return 0;
1244
1245 oom:
1246         lzms_free_compressor(ctx);
1247         return WIMLIB_ERR_NOMEM;
1248 }
1249
1250 static u64
1251 lzms_get_needed_memory(size_t max_block_size,
1252                        const struct wimlib_compressor_params_header *_params)
1253 {
1254         const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1255
1256         u64 size = 0;
1257
1258         size += max_block_size;
1259         size += sizeof(struct lzms_compressor);
1260         size += lz_sarray_get_needed_memory(max_block_size);
1261         size += lz_match_chooser_get_needed_memory(params->optim_array_length,
1262                                                    params->nice_match_length,
1263                                                    params->max_match_length);
1264         size += min(params->max_match_length -
1265                     params->min_match_length + 1,
1266                     params->max_matches_per_pos) *
1267                 sizeof(((struct lzms_compressor*)0)->matches[0]);
1268         return size;
1269 }
1270
1271 static bool
1272 lzms_params_valid(const struct wimlib_compressor_params_header *_params)
1273 {
1274         const struct wimlib_lzms_compressor_params *params =
1275                 (const struct wimlib_lzms_compressor_params*)_params;
1276
1277         if (params->hdr.size != sizeof(*params) ||
1278             params->max_match_length < params->min_match_length ||
1279             params->min_match_length < 2 ||
1280             params->optim_array_length == 0 ||
1281             min(params->max_match_length, params->nice_match_length) > 65536)
1282                 return false;
1283
1284         return true;
1285 }
1286
1287 const struct compressor_ops lzms_compressor_ops = {
1288         .params_valid       = lzms_params_valid,
1289         .get_needed_memory  = lzms_get_needed_memory,
1290         .create_compressor  = lzms_create_compressor,
1291         .compress           = lzms_compress,
1292         .free_compressor    = lzms_free_compressor,
1293 };