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