]> wimlib.net Git - wimlib/blob - src/lzms-compress.c
cleanups
[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.h"
38 #include "wimlib/assert.h"
39 #include "wimlib/compiler.h"
40 #include "wimlib/compressor_ops.h"
41 #include "wimlib/compress_common.h"
42 #include "wimlib/endianness.h"
43 #include "wimlib/error.h"
44 #include "wimlib/lz_mf.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 struct lz_match
845 lzms_match_chooser_reverse_list(struct lzms_compressor *ctx, unsigned cur_pos)
846 {
847         unsigned prev_link, saved_prev_link;
848         unsigned prev_match_offset, saved_prev_match_offset;
849
850         ctx->optimum_end_idx = cur_pos;
851
852         saved_prev_link = ctx->optimum[cur_pos].prev.link;
853         saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
854
855         do {
856                 prev_link = saved_prev_link;
857                 prev_match_offset = saved_prev_match_offset;
858
859                 saved_prev_link = ctx->optimum[prev_link].prev.link;
860                 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
861
862                 ctx->optimum[prev_link].next.link = cur_pos;
863                 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
864
865                 cur_pos = prev_link;
866         } while (cur_pos != 0);
867
868         ctx->optimum_cur_idx = ctx->optimum[0].next.link;
869
870         return (struct lz_match)
871                 { .len = ctx->optimum_cur_idx,
872                   .offset = ctx->optimum[0].next.match_offset,
873                 };
874 }
875
876 /* This is similar to lzx_choose_near_optimal_item() in lzx-compress.c.
877  * Read that one if you want to understand it.  */
878 static struct lz_match
879 lzms_get_near_optimal_item(struct lzms_compressor *ctx)
880 {
881         u32 num_matches;
882         struct lz_match *matches;
883         struct lz_match match;
884         u32 longest_len;
885         u32 longest_rep_len;
886         u32 longest_rep_offset;
887         unsigned cur_pos;
888         unsigned end_pos;
889         struct lzms_adaptive_state initial_state;
890
891         if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
892                 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
893                                     ctx->optimum_cur_idx;
894                 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
895
896                 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
897                 return match;
898         }
899
900         ctx->optimum_cur_idx = 0;
901         ctx->optimum_end_idx = 0;
902
903         longest_rep_len = ctx->params.min_match_length - 1;
904         if (lz_mf_get_position(ctx->mf) >= LZMS_MAX_INIT_RECENT_OFFSET) {
905                 u32 limit = lz_mf_get_bytes_remaining(ctx->mf);
906                 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++) {
907                         u32 offset = ctx->lru.lz.recent_offsets[i];
908                         const u8 *strptr = lz_mf_get_window_ptr(ctx->mf);
909                         const u8 *matchptr = strptr - offset;
910                         u32 len = 0;
911                         while (len < limit && strptr[len] == matchptr[len])
912                                 len++;
913                         if (len > longest_rep_len) {
914                                 longest_rep_len = len;
915                                 longest_rep_offset = offset;
916                         }
917                 }
918         }
919
920         if (longest_rep_len >= ctx->params.nice_match_length) {
921                 lzms_skip_bytes(ctx, longest_rep_len);
922                 return (struct lz_match) {
923                         .len = longest_rep_len,
924                         .offset = longest_rep_offset,
925                 };
926         }
927
928         num_matches = lzms_get_matches(ctx, &matches);
929
930         if (num_matches) {
931                 longest_len = matches[num_matches - 1].len;
932                 if (longest_len >= ctx->params.nice_match_length) {
933                         lzms_skip_bytes(ctx, longest_len - 1);
934                         return matches[num_matches - 1];
935                 }
936         } else {
937                 longest_len = 1;
938         }
939
940         initial_state.lru = ctx->lru.lz;
941         initial_state.main_state = ctx->main_range_encoder.state;
942         initial_state.match_state = ctx->match_range_encoder.state;
943         initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
944         for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
945                 initial_state.lz_repeat_match_state[i] = ctx->lz_repeat_match_range_encoders[i].state;
946
947         ctx->optimum[1].state = initial_state;
948         ctx->optimum[1].cost = lzms_get_literal_cost(ctx,
949                                                      &ctx->optimum[1].state,
950                                                      *(lz_mf_get_window_ptr(ctx->mf) - 1));
951         ctx->optimum[1].prev.link = 0;
952
953         for (u32 i = 0, len = 2; i < num_matches; i++) {
954                 u32 offset = matches[i].offset;
955                 struct lzms_adaptive_state state;
956                 u32 position_cost;
957
958                 state = initial_state;
959                 position_cost = 0;
960                 position_cost += lzms_get_lz_match_cost_nolen(ctx, &state, offset);
961
962                 do {
963                         u32 cost;
964
965                         cost = position_cost;
966                         cost += lzms_get_length_cost(&ctx->length_encoder, len);
967
968                         ctx->optimum[len].state = state;
969                         ctx->optimum[len].prev.link = 0;
970                         ctx->optimum[len].prev.match_offset = offset;
971                         ctx->optimum[len].cost = cost;
972                 } while (++len <= matches[i].len);
973         }
974         end_pos = longest_len;
975
976         if (longest_rep_len >= ctx->params.min_match_length) {
977                 struct lzms_adaptive_state state;
978                 u32 cost;
979
980                 while (end_pos < longest_rep_len)
981                         ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
982
983                 state = initial_state;
984                 cost = lzms_get_lz_match_cost(ctx,
985                                               &state,
986                                               longest_rep_len,
987                                               longest_rep_offset);
988                 if (cost <= ctx->optimum[longest_rep_len].cost) {
989                         ctx->optimum[longest_rep_len].state = state;
990                         ctx->optimum[longest_rep_len].prev.link = 0;
991                         ctx->optimum[longest_rep_len].prev.match_offset = longest_rep_offset;
992                         ctx->optimum[longest_rep_len].cost = cost;
993                 }
994         }
995
996         cur_pos = 0;
997         for (;;) {
998                 u32 cost;
999                 struct lzms_adaptive_state state;
1000
1001                 cur_pos++;
1002
1003                 if (cur_pos == end_pos || cur_pos == ctx->params.optim_array_length)
1004                         return lzms_match_chooser_reverse_list(ctx, cur_pos);
1005
1006                 longest_rep_len = ctx->params.min_match_length - 1;
1007                 if (lz_mf_get_position(ctx->mf) >= LZMS_MAX_INIT_RECENT_OFFSET) {
1008                         u32 limit = lz_mf_get_bytes_remaining(ctx->mf);
1009                         for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++) {
1010                                 u32 offset = ctx->optimum[cur_pos].state.lru.recent_offsets[i];
1011                                 const u8 *strptr = lz_mf_get_window_ptr(ctx->mf);
1012                                 const u8 *matchptr = strptr - offset;
1013                                 u32 len = 0;
1014                                 while (len < limit && strptr[len] == matchptr[len])
1015                                         len++;
1016                                 if (len > longest_rep_len) {
1017                                         longest_rep_len = len;
1018                                         longest_rep_offset = offset;
1019                                 }
1020                         }
1021                 }
1022
1023                 if (longest_rep_len >= ctx->params.nice_match_length) {
1024                         match = lzms_match_chooser_reverse_list(ctx, cur_pos);
1025
1026                         ctx->optimum[cur_pos].next.match_offset = longest_rep_offset;
1027                         ctx->optimum[cur_pos].next.link = cur_pos + longest_rep_len;
1028                         ctx->optimum_end_idx = cur_pos + longest_rep_len;
1029
1030                         lzms_skip_bytes(ctx, longest_rep_len);
1031
1032                         return match;
1033                 }
1034
1035                 num_matches = lzms_get_matches(ctx, &matches);
1036
1037                 if (num_matches) {
1038                         longest_len = matches[num_matches - 1].len;
1039                         if (longest_len >= ctx->params.nice_match_length) {
1040                                 match = lzms_match_chooser_reverse_list(ctx, cur_pos);
1041
1042                                 ctx->optimum[cur_pos].next.match_offset =
1043                                         matches[num_matches - 1].offset;
1044                                 ctx->optimum[cur_pos].next.link = cur_pos + longest_len;
1045                                 ctx->optimum_end_idx = cur_pos + longest_len;
1046
1047                                 lzms_skip_bytes(ctx, longest_len - 1);
1048
1049                                 return match;
1050                         }
1051                 } else {
1052                         longest_len = 1;
1053                 }
1054
1055                 while (end_pos < cur_pos + longest_len)
1056                         ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1057
1058                 state = ctx->optimum[cur_pos].state;
1059                 cost = ctx->optimum[cur_pos].cost +
1060                         lzms_get_literal_cost(ctx,
1061                                               &state,
1062                                               *(lz_mf_get_window_ptr(ctx->mf) - 1));
1063                 if (cost < ctx->optimum[cur_pos + 1].cost) {
1064                         ctx->optimum[cur_pos + 1].state = state;
1065                         ctx->optimum[cur_pos + 1].cost = cost;
1066                         ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1067                 }
1068
1069                 for (u32 i = 0, len = 2; i < num_matches; i++) {
1070                         u32 offset = matches[i].offset;
1071                         struct lzms_adaptive_state state;
1072                         u32 position_cost;
1073
1074                         state = ctx->optimum[cur_pos].state;
1075                         position_cost = ctx->optimum[cur_pos].cost;
1076                         position_cost += lzms_get_lz_match_cost_nolen(ctx, &state, offset);
1077
1078                         do {
1079                                 u32 cost;
1080
1081                                 cost = position_cost;
1082                                 cost += lzms_get_length_cost(&ctx->length_encoder, len);
1083
1084                                 if (cost < ctx->optimum[cur_pos + len].cost) {
1085                                         ctx->optimum[cur_pos + len].state = state;
1086                                         ctx->optimum[cur_pos + len].prev.link = cur_pos;
1087                                         ctx->optimum[cur_pos + len].prev.match_offset = offset;
1088                                         ctx->optimum[cur_pos + len].cost = cost;
1089                                 }
1090                         } while (++len <= matches[i].len);
1091                 }
1092
1093                 if (longest_rep_len >= ctx->params.min_match_length) {
1094
1095                         while (end_pos < cur_pos + longest_rep_len)
1096                                 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1097
1098                         state = ctx->optimum[cur_pos].state;
1099
1100                         cost = ctx->optimum[cur_pos].cost +
1101                                 lzms_get_lz_match_cost(ctx,
1102                                                        &state,
1103                                                        longest_rep_len,
1104                                                        longest_rep_offset);
1105                         if (cost <= ctx->optimum[cur_pos + longest_rep_len].cost) {
1106                                 ctx->optimum[cur_pos + longest_rep_len].state =
1107                                         state;
1108                                 ctx->optimum[cur_pos + longest_rep_len].prev.link =
1109                                         cur_pos;
1110                                 ctx->optimum[cur_pos + longest_rep_len].prev.match_offset =
1111                                         longest_rep_offset;
1112                                 ctx->optimum[cur_pos + longest_rep_len].cost =
1113                                         cost;
1114                         }
1115                 }
1116         }
1117 }
1118
1119 /*
1120  * The main loop for the LZMS compressor.
1121  *
1122  * Notes:
1123  *
1124  * - This does not output any delta matches.
1125  *
1126  * - The costs of literals and matches are estimated using the range encoder
1127  *   states and the semi-adaptive Huffman codes.  Except for range encoding
1128  *   states, costs are assumed to be constant throughout a single run of the
1129  *   parsing algorithm, which can parse up to @optim_array_length bytes of data.
1130  *   This introduces a source of inaccuracy because the probabilities and
1131  *   Huffman codes can change over this part of the data.
1132  */
1133 static void
1134 lzms_encode(struct lzms_compressor *ctx)
1135 {
1136         struct lz_match item;
1137
1138         /* Load window into the match-finder.  */
1139         lz_mf_load_window(ctx->mf, ctx->window, ctx->window_size);
1140
1141         /* Reset the match-chooser.  */
1142         ctx->optimum_cur_idx = 0;
1143         ctx->optimum_end_idx = 0;
1144
1145         while (ctx->cur_window_pos != ctx->window_size) {
1146                 item = lzms_get_near_optimal_item(ctx);
1147                 if (item.len <= 1)
1148                         lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
1149                 else
1150                         lzms_encode_lz_match(ctx, item.len, item.offset);
1151         }
1152 }
1153
1154 static void
1155 lzms_init_range_encoder(struct lzms_range_encoder *enc,
1156                         struct lzms_range_encoder_raw *rc, u32 num_states)
1157 {
1158         enc->rc = rc;
1159         enc->state = 0;
1160         enc->mask = num_states - 1;
1161         for (u32 i = 0; i < num_states; i++) {
1162                 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
1163                 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
1164         }
1165 }
1166
1167 static void
1168 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
1169                           struct lzms_output_bitstream *os,
1170                           unsigned num_syms,
1171                           unsigned rebuild_freq)
1172 {
1173         enc->os = os;
1174         enc->num_syms_written = 0;
1175         enc->rebuild_freq = rebuild_freq;
1176         enc->num_syms = num_syms;
1177         for (unsigned i = 0; i < num_syms; i++)
1178                 enc->sym_freqs[i] = 1;
1179
1180         make_canonical_huffman_code(enc->num_syms,
1181                                     LZMS_MAX_CODEWORD_LEN,
1182                                     enc->sym_freqs,
1183                                     enc->lens,
1184                                     enc->codewords);
1185 }
1186
1187 /* Initialize the LZMS compressor.  */
1188 static void
1189 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
1190                      le16 *cdata, u32 clen16)
1191 {
1192         unsigned num_position_slots;
1193
1194         /* Copy the uncompressed data into the @ctx->window buffer.  */
1195         memcpy(ctx->window, udata, ulen);
1196         ctx->cur_window_pos = 0;
1197         ctx->window_size = ulen;
1198
1199         /* Initialize the raw range encoder (writing forwards).  */
1200         lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
1201
1202         /* Initialize the output bitstream for Huffman symbols and verbatim bits
1203          * (writing backwards).  */
1204         lzms_output_bitstream_init(&ctx->os, cdata, clen16);
1205
1206         /* Calculate the number of position slots needed for this compressed
1207          * block.  */
1208         num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
1209
1210         LZMS_DEBUG("Using %u position slots", num_position_slots);
1211
1212         /* Initialize Huffman encoders for each alphabet used in the compressed
1213          * representation.  */
1214         lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
1215                                   LZMS_NUM_LITERAL_SYMS,
1216                                   LZMS_LITERAL_CODE_REBUILD_FREQ);
1217
1218         lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
1219                                   num_position_slots,
1220                                   LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
1221
1222         lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
1223                                   LZMS_NUM_LEN_SYMS,
1224                                   LZMS_LENGTH_CODE_REBUILD_FREQ);
1225
1226         lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
1227                                   num_position_slots,
1228                                   LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
1229
1230         lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
1231                                   LZMS_NUM_DELTA_POWER_SYMS,
1232                                   LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
1233
1234         /* Initialize range encoders, all of which wrap around the same
1235          * lzms_range_encoder_raw.  */
1236         lzms_init_range_encoder(&ctx->main_range_encoder,
1237                                 &ctx->rc, LZMS_NUM_MAIN_STATES);
1238
1239         lzms_init_range_encoder(&ctx->match_range_encoder,
1240                                 &ctx->rc, LZMS_NUM_MATCH_STATES);
1241
1242         lzms_init_range_encoder(&ctx->lz_match_range_encoder,
1243                                 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
1244
1245         for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
1246                 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
1247                                         &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
1248
1249         lzms_init_range_encoder(&ctx->delta_match_range_encoder,
1250                                 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1251
1252         for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1253                 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1254                                         &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1255
1256         /* Initialize LRU match information.  */
1257         lzms_init_lru_queues(&ctx->lru);
1258 }
1259
1260 /* Flush the output streams, prepare the final compressed data, and return its
1261  * size in bytes.
1262  *
1263  * A return value of 0 indicates that the data could not be compressed to fit in
1264  * the available space.  */
1265 static size_t
1266 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1267 {
1268         size_t num_forwards_bytes;
1269         size_t num_backwards_bytes;
1270         size_t compressed_size;
1271
1272         /* Flush both the forwards and backwards streams, and make sure they
1273          * didn't cross each other and start overwriting each other's data.  */
1274         if (!lzms_output_bitstream_flush(&ctx->os)) {
1275                 LZMS_DEBUG("Backwards bitstream overrun.");
1276                 return 0;
1277         }
1278
1279         if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1280                 LZMS_DEBUG("Forwards bitstream overrun.");
1281                 return 0;
1282         }
1283
1284         if (ctx->rc.out > ctx->os.out) {
1285                 LZMS_DEBUG("Two bitstreams crossed.");
1286                 return 0;
1287         }
1288
1289         /* Now the compressed buffer contains the data output by the forwards
1290          * bitstream, then empty space, then data output by the backwards
1291          * bitstream.  Move the data output by the backwards bitstream to be
1292          * adjacent to the data output by the forward bitstream, and calculate
1293          * the compressed size that this results in.  */
1294         num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1295         num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1296
1297         memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1298
1299         compressed_size = num_forwards_bytes + num_backwards_bytes;
1300         LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1301                    "compressed_size=%zu",
1302                    num_forwards_bytes, num_backwards_bytes, compressed_size);
1303         LZMS_ASSERT(compressed_size % 2 == 0);
1304         return compressed_size;
1305 }
1306
1307
1308 static void
1309 lzms_build_params(unsigned int compression_level,
1310                   struct lzms_compressor_params *lzms_params)
1311 {
1312         lzms_params->min_match_length  = (compression_level >= 50) ? 2 : 3;
1313         lzms_params->nice_match_length = ((u64)compression_level * 32) / 50;
1314         lzms_params->max_search_depth  = ((u64)compression_level * 50) / 50;
1315         lzms_params->optim_array_length = 224 + compression_level * 16;
1316 }
1317
1318 static void
1319 lzms_build_mf_params(const struct lzms_compressor_params *lzms_params,
1320                      u32 max_window_size, struct lz_mf_params *mf_params)
1321 {
1322         memset(mf_params, 0, sizeof(*mf_params));
1323
1324         mf_params->algorithm = LZ_MF_DEFAULT;
1325         mf_params->max_window_size = max_window_size;
1326         mf_params->min_match_len = lzms_params->min_match_length;
1327         mf_params->max_search_depth = lzms_params->max_search_depth;
1328         mf_params->nice_match_len = lzms_params->nice_match_length;
1329 }
1330
1331 static void
1332 lzms_free_compressor(void *_ctx);
1333
1334 static u64
1335 lzms_get_needed_memory(size_t max_block_size, unsigned int compression_level)
1336 {
1337         struct lzms_compressor_params params;
1338
1339         lzms_build_params(compression_level, &params);
1340
1341         u64 size = 0;
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 };