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