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