]> wimlib.net Git - wimlib/blob - src/lzms-compress.c
Compression updates
[wimlib] / src / lzms-compress.c
1 /*
2  * lzms-compress.c
3  *
4  * A compressor that produces output compatible with the LZMS compression format.
5  */
6
7 /*
8  * Copyright (C) 2013, 2014 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "wimlib/compress_common.h"
31 #include "wimlib/compressor_ops.h"
32 #include "wimlib/endianness.h"
33 #include "wimlib/error.h"
34 #include "wimlib/lz_mf.h"
35 #include "wimlib/lz_repsearch.h"
36 #include "wimlib/lzms.h"
37 #include "wimlib/util.h"
38
39 #include <string.h>
40 #include <limits.h>
41 #include <pthread.h>
42
43 /* Stucture used for writing raw bits as a series of 16-bit little endian coding
44  * units.  This starts at the *end* of the compressed data buffer and proceeds
45  * backwards.  */
46 struct lzms_output_bitstream {
47
48         /* Bits that haven't yet been written to the output buffer.  */
49         u64 bitbuf;
50
51         /* Number of bits currently held in @bitbuf.  */
52         unsigned bitcount;
53
54         /* Pointer to one past the next position in the compressed data buffer
55          * at which to output a 16-bit coding unit.  */
56         le16 *next;
57
58         /* Pointer to the beginning of the output buffer.  (The "end" when
59          * writing backwards!)  */
60         le16 *begin;
61 };
62
63 /* Stucture used for range encoding (raw version).  This starts at the
64  * *beginning* of the compressed data buffer and proceeds forward.  */
65 struct lzms_range_encoder_raw {
66
67         /* A 33-bit variable that holds the low boundary of the current range.
68          * The 33rd bit is needed to catch carries.  */
69         u64 low;
70
71         /* Size of the current range.  */
72         u32 range;
73
74         /* Next 16-bit coding unit to output.  */
75         u16 cache;
76
77         /* Number of 16-bit coding units whose output has been delayed due to
78          * possible carrying.  The first such coding unit is @cache; all
79          * subsequent such coding units are 0xffff.  */
80         u32 cache_size;
81
82         /* Pointer to the beginning of the output buffer.  */
83         le16 *begin;
84
85         /* Pointer to the position in the output buffer at which the next coding
86          * unit must be written.  */
87         le16 *next;
88
89         /* Pointer just past the end of the output buffer.  */
90         le16 *end;
91 };
92
93 /* Structure used for range encoding.  This wraps around `struct
94  * lzms_range_encoder_raw' to use and maintain probability entries.  */
95 struct lzms_range_encoder {
96
97         /* Pointer to the raw range encoder, which has no persistent knowledge
98          * of probabilities.  Multiple lzms_range_encoder's share the same
99          * lzms_range_encoder_raw.  */
100         struct lzms_range_encoder_raw *rc;
101
102         /* Bits recently encoded by this range encoder.  This is used as an
103          * index into @prob_entries.  */
104         u32 state;
105
106         /* Bitmask for @state to prevent its value from exceeding the number of
107          * probability entries.  */
108         u32 mask;
109
110         /* Probability entries being used for this range encoder.  */
111         struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
112 };
113
114 /* Structure used for Huffman encoding.  */
115 struct lzms_huffman_encoder {
116
117         /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
118          * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
119          */
120         struct lzms_output_bitstream *os;
121
122         /* Number of symbols that have been written using this code far.  Reset
123          * to 0 whenever the code is rebuilt.  */
124         u32 num_syms_written;
125
126         /* When @num_syms_written reaches this number, the Huffman code must be
127          * rebuilt.  */
128         u32 rebuild_freq;
129
130         /* Number of symbols in the represented Huffman code.  */
131         unsigned num_syms;
132
133         /* Running totals of symbol frequencies.  These are diluted slightly
134          * whenever the code is rebuilt.  */
135         u32 sym_freqs[LZMS_MAX_NUM_SYMS];
136
137         /* The length, in bits, of each symbol in the Huffman code.  */
138         u8 lens[LZMS_MAX_NUM_SYMS];
139
140         /* The codeword of each symbol in the Huffman code.  */
141         u32 codewords[LZMS_MAX_NUM_SYMS];
142 };
143
144 /* Internal compression parameters  */
145 struct lzms_compressor_params {
146         u32 min_match_length;
147         u32 nice_match_length;
148         u32 max_search_depth;
149         u32 optim_array_length;
150 };
151
152 /* State of the LZMS compressor  */
153 struct lzms_compressor {
154
155         /* Internal compression parameters  */
156         struct lzms_compressor_params params;
157
158         /* Data currently being compressed  */
159         u8 *cur_window;
160         u32 cur_window_size;
161
162         /* Lempel-Ziv match-finder  */
163         struct lz_mf *mf;
164
165         /* Temporary space to store found matches  */
166         struct lz_match *matches;
167
168         /* Per-position data for near-optimal parsing  */
169         struct lzms_mc_pos_data *optimum;
170         struct lzms_mc_pos_data *optimum_end;
171
172         /* Raw range encoder which outputs to the beginning of the compressed
173          * data buffer, proceeding forwards  */
174         struct lzms_range_encoder_raw rc;
175
176         /* Bitstream which outputs to the end of the compressed data buffer,
177          * proceeding backwards  */
178         struct lzms_output_bitstream os;
179
180         /* Range encoders  */
181         struct lzms_range_encoder main_range_encoder;
182         struct lzms_range_encoder match_range_encoder;
183         struct lzms_range_encoder lz_match_range_encoder;
184         struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
185         struct lzms_range_encoder delta_match_range_encoder;
186         struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
187
188         /* Huffman encoders  */
189         struct lzms_huffman_encoder literal_encoder;
190         struct lzms_huffman_encoder lz_offset_encoder;
191         struct lzms_huffman_encoder length_encoder;
192         struct lzms_huffman_encoder delta_power_encoder;
193         struct lzms_huffman_encoder delta_offset_encoder;
194
195         /* Used for preprocessing  */
196         s32 last_target_usages[65536];
197
198 #define LZMS_NUM_FAST_LENGTHS 256
199         /* Table: length => length slot for small lengths  */
200         u8 length_slot_fast[LZMS_NUM_FAST_LENGTHS];
201
202         /* Table: length => current cost for small match lengths  */
203         u32 length_cost_fast[LZMS_NUM_FAST_LENGTHS];
204
205 #define LZMS_NUM_FAST_OFFSETS 32768
206         /* Table: offset => offset slot for small offsets  */
207         u8 offset_slot_fast[LZMS_NUM_FAST_OFFSETS];
208 };
209
210 /*
211  * Match chooser position data:
212  *
213  * An array of these structures is used during the near-optimal match-choosing
214  * algorithm.  They correspond to consecutive positions in the window and are
215  * used to keep track of the cost to reach each position, and the match/literal
216  * choices that need to be chosen to reach that position.
217  */
218 struct lzms_mc_pos_data {
219
220         /* The cost, in bits, of the lowest-cost path that has been found to
221          * reach this position.  This can change as progressively lower cost
222          * paths are found to reach this position.  */
223         u32 cost;
224 #define MC_INFINITE_COST UINT32_MAX
225
226         /* The match or literal that was taken to reach this position.  This can
227          * change as progressively lower cost paths are found to reach this
228          * position.
229          *
230          * This variable is divided into two bitfields.
231          *
232          * Literals:
233          *      Low bits are 1, high bits are the literal.
234          *
235          * Explicit offset matches:
236          *      Low bits are the match length, high bits are the offset plus 2.
237          *
238          * Repeat offset matches:
239          *      Low bits are the match length, high bits are the queue index.
240          */
241         u64 mc_item_data;
242 #define MC_OFFSET_SHIFT 32
243 #define MC_LEN_MASK (((u64)1 << MC_OFFSET_SHIFT) - 1)
244
245         /* The LZMS adaptive state that exists at this position.  This is filled
246          * in lazily, only after the minimum-cost path to this position is
247          * found.
248          *
249          * Note: the way we handle this adaptive state in the "minimum-cost"
250          * parse is actually only an approximation.  It's possible for the
251          * globally optimal, minimum cost path to contain a prefix, ending at a
252          * position, where that path prefix is *not* the minimum cost path to
253          * that position.  This can happen if such a path prefix results in a
254          * different adaptive state which results in lower costs later.  We do
255          * not solve this problem; we only consider the lowest cost to reach
256          * each position, which seems to be an acceptable approximation.
257          *
258          * Note: this adaptive state also does not include the probability
259          * entries or current Huffman codewords.  Those aren't maintained
260          * per-position and are only updated occassionally.  */
261         struct lzms_adaptive_state {
262                 struct lzms_lz_lru_queues lru;
263                 u8 main_state;
264                 u8 match_state;
265                 u8 lz_match_state;
266                 u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
267         } state;
268 };
269
270 static void
271 lzms_init_fast_slots(struct lzms_compressor *c)
272 {
273         /* Create table mapping small lengths to length slots.  */
274         for (unsigned slot = 0, i = 0; i < LZMS_NUM_FAST_LENGTHS; i++) {
275                 while (i >= lzms_length_slot_base[slot + 1])
276                         slot++;
277                 c->length_slot_fast[i] = slot;
278         }
279
280         /* Create table mapping small offsets to offset slots.  */
281         for (unsigned slot = 0, i = 0; i < LZMS_NUM_FAST_OFFSETS; i++) {
282                 while (i >= lzms_offset_slot_base[slot + 1])
283                         slot++;
284                 c->offset_slot_fast[i] = slot;
285         }
286 }
287
288 static inline unsigned
289 lzms_get_length_slot_fast(const struct lzms_compressor *c, u32 length)
290 {
291         if (likely(length < LZMS_NUM_FAST_LENGTHS))
292                 return c->length_slot_fast[length];
293         else
294                 return lzms_get_length_slot(length);
295 }
296
297 static inline unsigned
298 lzms_get_offset_slot_fast(const struct lzms_compressor *c, u32 offset)
299 {
300         if (offset < LZMS_NUM_FAST_OFFSETS)
301                 return c->offset_slot_fast[offset];
302         else
303                 return lzms_get_offset_slot(offset);
304 }
305
306 /* Initialize the output bitstream @os to write backwards to the specified
307  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
308 static void
309 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
310                            le16 *out, size_t out_limit)
311 {
312         os->bitbuf = 0;
313         os->bitcount = 0;
314         os->next = out + out_limit;
315         os->begin = out;
316 }
317
318 /*
319  * Write some bits, contained in the low @num_bits bits of @bits (ordered from
320  * high-order to low-order), to the output bitstream @os.
321  *
322  * @max_num_bits is a compile-time constant that specifies the maximum number of
323  * bits that can ever be written at this call site.
324  */
325 static inline void
326 lzms_output_bitstream_put_varbits(struct lzms_output_bitstream *os,
327                                   u32 bits, unsigned num_bits,
328                                   unsigned max_num_bits)
329 {
330         LZMS_ASSERT(num_bits <= 48);
331
332         /* Add the bits to the bit buffer variable.  */
333         os->bitcount += num_bits;
334         os->bitbuf = (os->bitbuf << num_bits) | bits;
335
336         /* Check whether any coding units need to be written.  */
337         while (os->bitcount >= 16) {
338
339                 os->bitcount -= 16;
340
341                 /* Write a coding unit, unless it would underflow the buffer. */
342                 if (os->next != os->begin)
343                         *--os->next = cpu_to_le16(os->bitbuf >> os->bitcount);
344
345                 /* Optimization for call sites that never write more than 16
346                  * bits at once.  */
347                 if (max_num_bits <= 16)
348                         break;
349         }
350 }
351
352 /* Use when @num_bits is a compile-time constant.  Otherwise use
353  * lzms_output_bitstream_put_bits().  */
354 static inline void
355 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
356                                u32 bits, unsigned num_bits)
357 {
358         lzms_output_bitstream_put_varbits(os, bits, num_bits, num_bits);
359 }
360
361 /* Flush the output bitstream, ensuring that all bits written to it have been
362  * written to memory.  Returns %true if all bits have been output successfully,
363  * or %false if an overrun occurred.  */
364 static bool
365 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
366 {
367         if (os->next == os->begin)
368                 return false;
369
370         if (os->bitcount != 0)
371                 *--os->next = cpu_to_le16(os->bitbuf << (16 - os->bitcount));
372
373         return true;
374 }
375
376 /* Initialize the range encoder @rc to write forwards to the specified
377  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
378 static void
379 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
380                             le16 *out, size_t out_limit)
381 {
382         rc->low = 0;
383         rc->range = 0xffffffff;
384         rc->cache = 0;
385         rc->cache_size = 1;
386         rc->begin = out;
387         rc->next = out - 1;
388         rc->end = out + out_limit;
389 }
390
391 /*
392  * Attempt to flush bits from the range encoder.
393  *
394  * Note: this is based on the public domain code for LZMA written by Igor
395  * Pavlov.  The only differences in this function are that in LZMS the bits must
396  * be output in 16-bit coding units instead of 8-bit coding units, and that in
397  * LZMS the first coding unit is not ignored by the decompressor, so the encoder
398  * cannot output a dummy value to that position.
399  *
400  * The basic idea is that we're writing bits from @rc->low to the output.
401  * However, due to carrying, the writing of coding units with value 0xffff, as
402  * well as one prior coding unit, must be delayed until it is determined whether
403  * a carry is needed.
404  */
405 static void
406 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
407 {
408         if ((u32)(rc->low) < 0xffff0000 ||
409             (u32)(rc->low >> 32) != 0)
410         {
411                 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
412                  * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1).  */
413                 do {
414                         if (likely(rc->next >= rc->begin)) {
415                                 if (rc->next != rc->end)
416                                         *rc->next++ = cpu_to_le16(rc->cache +
417                                                                   (u16)(rc->low >> 32));
418                         } else {
419                                 rc->next++;
420                         }
421                         rc->cache = 0xffff;
422                 } while (--rc->cache_size != 0);
423
424                 rc->cache = (rc->low >> 16) & 0xffff;
425         }
426         ++rc->cache_size;
427         rc->low = (rc->low & 0xffff) << 16;
428 }
429
430 static void
431 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
432 {
433         if (rc->range <= 0xffff) {
434                 rc->range <<= 16;
435                 lzms_range_encoder_raw_shift_low(rc);
436         }
437 }
438
439 static bool
440 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
441 {
442         for (unsigned i = 0; i < 4; i++)
443                 lzms_range_encoder_raw_shift_low(rc);
444         return rc->next != rc->end;
445 }
446
447 /* Encode the next bit using the range encoder (raw version).
448  *
449  * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0.  */
450 static inline void
451 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc,
452                                   int bit, u32 prob)
453 {
454         lzms_range_encoder_raw_normalize(rc);
455
456         u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
457         if (bit == 0) {
458                 rc->range = bound;
459         } else {
460                 rc->low += bound;
461                 rc->range -= bound;
462         }
463 }
464
465 /* Encode a bit using the specified range encoder. This wraps around
466  * lzms_range_encoder_raw_encode_bit() to handle using and updating the
467  * appropriate state and probability entry.  */
468 static void
469 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
470 {
471         struct lzms_probability_entry *prob_entry;
472         u32 prob;
473
474         /* Load the probability entry corresponding to the current state.  */
475         prob_entry = &enc->prob_entries[enc->state];
476
477         /* Update the state based on the next bit.  */
478         enc->state = ((enc->state << 1) | bit) & enc->mask;
479
480         /* Get the probability that the bit is 0.  */
481         prob = lzms_get_probability(prob_entry);
482
483         /* Update the probability entry.  */
484         lzms_update_probability_entry(prob_entry, bit);
485
486         /* Encode the bit.  */
487         lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
488 }
489
490 /* Called when an adaptive Huffman code needs to be rebuilt.  */
491 static void
492 lzms_rebuild_huffman_code(struct lzms_huffman_encoder *enc)
493 {
494         make_canonical_huffman_code(enc->num_syms,
495                                     LZMS_MAX_CODEWORD_LEN,
496                                     enc->sym_freqs,
497                                     enc->lens,
498                                     enc->codewords);
499
500         /* Dilute the frequencies.  */
501         for (unsigned i = 0; i < enc->num_syms; i++) {
502                 enc->sym_freqs[i] >>= 1;
503                 enc->sym_freqs[i] += 1;
504         }
505         enc->num_syms_written = 0;
506 }
507
508 /* Encode a symbol using the specified Huffman encoder.  */
509 static inline void
510 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, unsigned sym)
511 {
512         lzms_output_bitstream_put_varbits(enc->os,
513                                           enc->codewords[sym],
514                                           enc->lens[sym],
515                                           LZMS_MAX_CODEWORD_LEN);
516         ++enc->sym_freqs[sym];
517         if (++enc->num_syms_written == enc->rebuild_freq)
518                 lzms_rebuild_huffman_code(enc);
519 }
520
521 static void
522 lzms_update_fast_length_costs(struct lzms_compressor *c);
523
524 /* Encode a match length.  */
525 static void
526 lzms_encode_length(struct lzms_compressor *c, u32 length)
527 {
528         unsigned slot;
529         unsigned num_extra_bits;
530         u32 extra_bits;
531
532         slot = lzms_get_length_slot_fast(c, length);
533
534         extra_bits = length - lzms_length_slot_base[slot];
535         num_extra_bits = lzms_extra_length_bits[slot];
536
537         lzms_huffman_encode_symbol(&c->length_encoder, slot);
538         if (c->length_encoder.num_syms_written == 0)
539                 lzms_update_fast_length_costs(c);
540
541         lzms_output_bitstream_put_varbits(c->length_encoder.os,
542                                           extra_bits, num_extra_bits, 30);
543 }
544
545 /* Encode an LZ match offset.  */
546 static void
547 lzms_encode_lz_offset(struct lzms_compressor *c, u32 offset)
548 {
549         unsigned slot;
550         unsigned num_extra_bits;
551         u32 extra_bits;
552
553         slot = lzms_get_offset_slot_fast(c, offset);
554
555         extra_bits = offset - lzms_offset_slot_base[slot];
556         num_extra_bits = lzms_extra_offset_bits[slot];
557
558         lzms_huffman_encode_symbol(&c->lz_offset_encoder, slot);
559         lzms_output_bitstream_put_varbits(c->lz_offset_encoder.os,
560                                           extra_bits, num_extra_bits, 30);
561 }
562
563 /* Encode a literal byte.  */
564 static void
565 lzms_encode_literal(struct lzms_compressor *c, unsigned literal)
566 {
567         /* Main bit: 0 = a literal, not a match.  */
568         lzms_range_encode_bit(&c->main_range_encoder, 0);
569
570         /* Encode the literal using the current literal Huffman code.  */
571         lzms_huffman_encode_symbol(&c->literal_encoder, literal);
572 }
573
574 /* Encode an LZ repeat offset match.  */
575 static void
576 lzms_encode_lz_repeat_offset_match(struct lzms_compressor *c,
577                                    u32 length, unsigned rep_index)
578 {
579         unsigned i;
580
581         /* Main bit: 1 = a match, not a literal.  */
582         lzms_range_encode_bit(&c->main_range_encoder, 1);
583
584         /* Match bit: 0 = an LZ match, not a delta match.  */
585         lzms_range_encode_bit(&c->match_range_encoder, 0);
586
587         /* LZ match bit: 1 = repeat offset, not an explicit offset.  */
588         lzms_range_encode_bit(&c->lz_match_range_encoder, 1);
589
590         /* Encode the repeat offset index.  A 1 bit is encoded for each index
591          * passed up.  This sequence of 1 bits is terminated by a 0 bit, or
592          * automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1 bits have been
593          * encoded.  */
594         for (i = 0; i < rep_index; i++)
595                 lzms_range_encode_bit(&c->lz_repeat_match_range_encoders[i], 1);
596
597         if (i < LZMS_NUM_RECENT_OFFSETS - 1)
598                 lzms_range_encode_bit(&c->lz_repeat_match_range_encoders[i], 0);
599
600         /* Encode the match length.  */
601         lzms_encode_length(c, length);
602 }
603
604 /* Encode an LZ explicit offset match.  */
605 static void
606 lzms_encode_lz_explicit_offset_match(struct lzms_compressor *c,
607                                      u32 length, u32 offset)
608 {
609         /* Main bit: 1 = a match, not a literal.  */
610         lzms_range_encode_bit(&c->main_range_encoder, 1);
611
612         /* Match bit: 0 = an LZ match, not a delta match.  */
613         lzms_range_encode_bit(&c->match_range_encoder, 0);
614
615         /* LZ match bit: 0 = explicit offset, not a repeat offset.  */
616         lzms_range_encode_bit(&c->lz_match_range_encoder, 0);
617
618         /* Encode the match offset.  */
619         lzms_encode_lz_offset(c, offset);
620
621         /* Encode the match length.  */
622         lzms_encode_length(c, length);
623 }
624
625 static void
626 lzms_encode_item(struct lzms_compressor *c, u64 mc_item_data)
627 {
628         u32 len = mc_item_data & MC_LEN_MASK;
629         u32 offset_data = mc_item_data >> MC_OFFSET_SHIFT;
630
631         if (len == 1)
632                 lzms_encode_literal(c, offset_data);
633         else if (offset_data < LZMS_NUM_RECENT_OFFSETS)
634                 lzms_encode_lz_repeat_offset_match(c, len, offset_data);
635         else
636                 lzms_encode_lz_explicit_offset_match(c, len, offset_data - LZMS_OFFSET_OFFSET);
637 }
638
639 /* Encode a list of matches and literals chosen by the parsing algorithm.  */
640 static void
641 lzms_encode_item_list(struct lzms_compressor *c,
642                       struct lzms_mc_pos_data *cur_optimum_ptr)
643 {
644         struct lzms_mc_pos_data *end_optimum_ptr;
645         u64 saved_item;
646         u64 item;
647
648         /* The list is currently in reverse order (last item to first item).
649          * Reverse it.  */
650         end_optimum_ptr = cur_optimum_ptr;
651         saved_item = cur_optimum_ptr->mc_item_data;
652         do {
653                 item = saved_item;
654                 cur_optimum_ptr -= item & MC_LEN_MASK;
655                 saved_item = cur_optimum_ptr->mc_item_data;
656                 cur_optimum_ptr->mc_item_data = item;
657         } while (cur_optimum_ptr != c->optimum);
658
659         /* Walk the list of items from beginning to end, encoding each item.  */
660         do {
661                 lzms_encode_item(c, cur_optimum_ptr->mc_item_data);
662                 cur_optimum_ptr += (cur_optimum_ptr->mc_item_data) & MC_LEN_MASK;
663         } while (cur_optimum_ptr != end_optimum_ptr);
664 }
665
666 /* Each bit costs 1 << LZMS_COST_SHIFT units.  */
667 #define LZMS_COST_SHIFT 6
668
669 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
670
671 static u32
672 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
673
674 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
675 #  include <math.h>
676 #endif
677
678 static void
679 lzms_do_init_rc_costs(void)
680 {
681         /* Fill in a table that maps range coding probabilities needed to code a
682          * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
683          * handle fractional costs) needed to code that bit X.
684          *
685          * Consider the range of the range decoder.  To eliminate exactly half
686          * the range (logical probability of 0.5), we need exactly 1 bit.  For
687          * lower probabilities we need more bits and for higher probabilities we
688          * need fewer bits.  In general, a logical probability of N will
689          * eliminate the proportion 1 - N of the range; this information takes
690          * log2(1 / N) bits to encode.
691          *
692          * The below loop is simply calculating this number of bits for each
693          * possible probability allowed by the LZMS compression format, but
694          * without using real numbers.  To handle fractional probabilities, each
695          * cost is multiplied by (1 << LZMS_COST_SHIFT).  These techniques are
696          * based on those used by LZMA.
697          *
698          * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
699          * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
700          * 63 / 64.
701          */
702         for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
703                 u32 prob = i;
704
705                 if (prob == 0)
706                         prob = 1;
707                 else if (prob == LZMS_PROBABILITY_MAX)
708                         prob = LZMS_PROBABILITY_MAX - 1;
709
710         #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
711                 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
712                                         (1 << LZMS_COST_SHIFT);
713         #else
714                 u32 w = prob;
715                 u32 bit_count = 0;
716                 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
717                         w *= w;
718                         bit_count <<= 1;
719                         while (w >= (1U << 16)) {
720                                 w >>= 1;
721                                 ++bit_count;
722                         }
723                 }
724                 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
725                                    (15 + bit_count);
726         #endif
727         }
728 }
729
730 static void
731 lzms_init_rc_costs(void)
732 {
733         static pthread_once_t once = PTHREAD_ONCE_INIT;
734
735         pthread_once(&once, lzms_do_init_rc_costs);
736 }
737
738 /* Return the cost to range-encode the specified bit from the specified state.*/
739 static inline u32
740 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 cur_state, int bit)
741 {
742         u32 prob_zero;
743         u32 prob_correct;
744
745         prob_zero = enc->prob_entries[cur_state].num_recent_zero_bits;
746
747         if (bit == 0)
748                 prob_correct = prob_zero;
749         else
750                 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
751
752         return lzms_rc_costs[prob_correct];
753 }
754
755 /* Return the cost to Huffman-encode the specified symbol.  */
756 static inline u32
757 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, unsigned sym)
758 {
759         return (u32)enc->lens[sym] << LZMS_COST_SHIFT;
760 }
761
762 /* Return the cost to encode the specified literal byte.  */
763 static inline u32
764 lzms_literal_cost(const struct lzms_compressor *c, unsigned literal,
765                   const struct lzms_adaptive_state *state)
766 {
767         return lzms_rc_bit_cost(&c->main_range_encoder, state->main_state, 0) +
768                lzms_huffman_symbol_cost(&c->literal_encoder, literal);
769 }
770
771 /* Update the table that directly provides the costs for small lengths.  */
772 static void
773 lzms_update_fast_length_costs(struct lzms_compressor *c)
774 {
775         u32 len;
776         int slot = -1;
777         u32 cost = 0;
778
779         for (len = 1; len < LZMS_NUM_FAST_LENGTHS; len++) {
780
781                 while (len >= lzms_length_slot_base[slot + 1]) {
782                         slot++;
783                         cost = (u32)(c->length_encoder.lens[slot] +
784                                      lzms_extra_length_bits[slot]) << LZMS_COST_SHIFT;
785                 }
786
787                 c->length_cost_fast[len] = cost;
788         }
789 }
790
791 /* Return the cost to encode the specified match length, which must be less than
792  * LZMS_NUM_FAST_LENGTHS.  */
793 static inline u32
794 lzms_fast_length_cost(const struct lzms_compressor *c, u32 length)
795 {
796         LZMS_ASSERT(length < LZMS_NUM_FAST_LENGTHS);
797         return c->length_cost_fast[length];
798 }
799
800 /* Return the cost to encode the specified LZ match offset.  */
801 static inline u32
802 lzms_lz_offset_cost(const struct lzms_compressor *c, u32 offset)
803 {
804         unsigned slot = lzms_get_offset_slot_fast(c, offset);
805
806         return (u32)(c->lz_offset_encoder.lens[slot] +
807                      lzms_extra_offset_bits[slot]) << LZMS_COST_SHIFT;
808 }
809
810 /*
811  * Consider coding the match at repeat offset index @rep_idx.  Consider each
812  * length from the minimum (2) to the full match length (@rep_len).
813  */
814 static inline void
815 lzms_consider_lz_repeat_offset_match(const struct lzms_compressor *c,
816                                      struct lzms_mc_pos_data *cur_optimum_ptr,
817                                      u32 rep_len, unsigned rep_idx)
818 {
819         u32 len;
820         u32 base_cost;
821         u32 cost;
822         unsigned i;
823
824         base_cost = cur_optimum_ptr->cost;
825
826         base_cost += lzms_rc_bit_cost(&c->main_range_encoder,
827                                       cur_optimum_ptr->state.main_state, 1);
828
829         base_cost += lzms_rc_bit_cost(&c->match_range_encoder,
830                                       cur_optimum_ptr->state.match_state, 0);
831
832         base_cost += lzms_rc_bit_cost(&c->lz_match_range_encoder,
833                                       cur_optimum_ptr->state.lz_match_state, 1);
834
835         for (i = 0; i < rep_idx; i++)
836                 base_cost += lzms_rc_bit_cost(&c->lz_repeat_match_range_encoders[i],
837                                               cur_optimum_ptr->state.lz_repeat_match_state[i], 1);
838
839         if (i < LZMS_NUM_RECENT_OFFSETS - 1)
840                 base_cost += lzms_rc_bit_cost(&c->lz_repeat_match_range_encoders[i],
841                                               cur_optimum_ptr->state.lz_repeat_match_state[i], 0);
842
843         len = 2;
844         do {
845                 cost = base_cost + lzms_fast_length_cost(c, len);
846                 if (cost < (cur_optimum_ptr + len)->cost) {
847                         (cur_optimum_ptr + len)->mc_item_data =
848                                 ((u64)rep_idx << MC_OFFSET_SHIFT) | len;
849                         (cur_optimum_ptr + len)->cost = cost;
850                 }
851         } while (++len <= rep_len);
852 }
853
854 /*
855  * Consider coding each match in @matches as an explicit offset match.
856  *
857  * @matches must be sorted by strictly increasing length and strictly increasing
858  * offset.  This is guaranteed by the match-finder.
859  *
860  * We consider each length from the minimum (2) to the longest
861  * (matches[num_matches - 1].len).  For each length, we consider only the
862  * smallest offset for which that length is available.  Although this is not
863  * guaranteed to be optimal due to the possibility of a larger offset costing
864  * less than a smaller offset to code, this is a very useful heuristic.
865  */
866 static inline void
867 lzms_consider_lz_explicit_offset_matches(const struct lzms_compressor *c,
868                                          struct lzms_mc_pos_data *cur_optimum_ptr,
869                                          const struct lz_match matches[],
870                                          u32 num_matches)
871 {
872         u32 len;
873         u32 i;
874         u32 base_cost;
875         u32 position_cost;
876         u32 cost;
877
878         base_cost = cur_optimum_ptr->cost;
879
880         base_cost += lzms_rc_bit_cost(&c->main_range_encoder,
881                                       cur_optimum_ptr->state.main_state, 1);
882
883         base_cost += lzms_rc_bit_cost(&c->match_range_encoder,
884                                       cur_optimum_ptr->state.match_state, 0);
885
886         base_cost += lzms_rc_bit_cost(&c->lz_match_range_encoder,
887                                       cur_optimum_ptr->state.lz_match_state, 0);
888         len = 2;
889         i = 0;
890         do {
891                 position_cost = base_cost + lzms_lz_offset_cost(c,
892                                                                 matches[i].offset);
893                 do {
894                         cost = position_cost + lzms_fast_length_cost(c, len);
895                         if (cost < (cur_optimum_ptr + len)->cost) {
896                                 (cur_optimum_ptr + len)->mc_item_data =
897                                         ((u64)(matches[i].offset + LZMS_OFFSET_OFFSET)
898                                                 << MC_OFFSET_SHIFT) | len;
899                                 (cur_optimum_ptr + len)->cost = cost;
900                         }
901                 } while (++len <= matches[i].len);
902         } while (++i != num_matches);
903 }
904
905 static void
906 lzms_init_adaptive_state(struct lzms_adaptive_state *state)
907 {
908         unsigned i;
909
910         lzms_init_lz_lru_queues(&state->lru);
911         state->main_state = 0;
912         state->match_state = 0;
913         state->lz_match_state = 0;
914         for (i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
915                 state->lz_repeat_match_state[i] = 0;
916 }
917
918 static inline void
919 lzms_update_main_state(struct lzms_adaptive_state *state, int is_match)
920 {
921         state->main_state = ((state->main_state << 1) | is_match) % LZMS_NUM_MAIN_STATES;
922 }
923
924 static inline void
925 lzms_update_match_state(struct lzms_adaptive_state *state, int is_delta)
926 {
927         state->match_state = ((state->match_state << 1) | is_delta) % LZMS_NUM_MATCH_STATES;
928 }
929
930 static inline void
931 lzms_update_lz_match_state(struct lzms_adaptive_state *state, int is_repeat_offset)
932 {
933         state->lz_match_state = ((state->lz_match_state << 1) | is_repeat_offset) % LZMS_NUM_LZ_MATCH_STATES;
934 }
935
936 static inline void
937 lzms_update_lz_repeat_match_state(struct lzms_adaptive_state *state, int rep_idx)
938 {
939         int i;
940
941         for (i = 0; i < rep_idx; i++)
942                 state->lz_repeat_match_state[i] =
943                         ((state->lz_repeat_match_state[i] << 1) | 1) %
944                                 LZMS_NUM_LZ_REPEAT_MATCH_STATES;
945
946         if (i < LZMS_NUM_RECENT_OFFSETS - 1)
947                 state->lz_repeat_match_state[i] =
948                         ((state->lz_repeat_match_state[i] << 1) | 0) %
949                                 LZMS_NUM_LZ_REPEAT_MATCH_STATES;
950 }
951
952 /*
953  * The main near-optimal parsing routine.
954  *
955  * Briefly, the algorithm does an approximate minimum-cost path search to find a
956  * "near-optimal" sequence of matches and literals to output, based on the
957  * current cost model.  The algorithm steps forward, position by position (byte
958  * by byte), and updates the minimum cost path to reach each later position that
959  * can be reached using a match or literal from the current position.  This is
960  * essentially Dijkstra's algorithm in disguise: the graph nodes are positions,
961  * the graph edges are possible matches/literals to code, and the cost of each
962  * edge is the estimated number of bits that will be required to output the
963  * corresponding match or literal.  But one difference is that we actually
964  * compute the lowest-cost path in pieces, where each piece is terminated when
965  * there are no choices to be made.
966  *
967  * Notes:
968  *
969  * - This does not output any delta matches.
970  *
971  * - The costs of literals and matches are estimated using the range encoder
972  *   states and the semi-adaptive Huffman codes.  Except for range encoding
973  *   states, costs are assumed to be constant throughout a single run of the
974  *   parsing algorithm, which can parse up to @optim_array_length bytes of data.
975  *   This introduces a source of inaccuracy because the probabilities and
976  *   Huffman codes can change over this part of the data.
977  */
978 static void
979 lzms_near_optimal_parse(struct lzms_compressor *c)
980 {
981         const u8 *window_ptr;
982         const u8 *window_end;
983         struct lzms_mc_pos_data *cur_optimum_ptr;
984         struct lzms_mc_pos_data *end_optimum_ptr;
985         u32 num_matches;
986         u32 longest_len;
987         u32 rep_max_len;
988         unsigned rep_max_idx;
989         unsigned literal;
990         unsigned i;
991         u32 cost;
992         u32 len;
993         u32 offset_data;
994
995         window_ptr = c->cur_window;
996         window_end = window_ptr + c->cur_window_size;
997
998         lzms_init_adaptive_state(&c->optimum[0].state);
999
1000 begin:
1001         /* Start building a new list of items, which will correspond to the next
1002          * piece of the overall minimum-cost path.  */
1003
1004         cur_optimum_ptr = c->optimum;
1005         cur_optimum_ptr->cost = 0;
1006         end_optimum_ptr = cur_optimum_ptr;
1007
1008         /* States should currently be consistent with the encoders.  */
1009         LZMS_ASSERT(cur_optimum_ptr->state.main_state == c->main_range_encoder.state);
1010         LZMS_ASSERT(cur_optimum_ptr->state.match_state == c->match_range_encoder.state);
1011         LZMS_ASSERT(cur_optimum_ptr->state.lz_match_state == c->lz_match_range_encoder.state);
1012         for (i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
1013                 LZMS_ASSERT(cur_optimum_ptr->state.lz_repeat_match_state[i] ==
1014                             c->lz_repeat_match_range_encoders[i].state);
1015
1016         if (window_ptr == window_end)
1017                 return;
1018
1019         /* The following loop runs once for each per byte in the window, except
1020          * in a couple shortcut cases.  */
1021         for (;;) {
1022
1023                 /* Find explicit offset matches with the current position.  */
1024                 num_matches = lz_mf_get_matches(c->mf, c->matches);
1025
1026                 if (num_matches) {
1027                         /*
1028                          * Find the longest repeat offset match with the current
1029                          * position.
1030                          *
1031                          * Heuristics:
1032                          *
1033                          * - Only search for repeat offset matches if the
1034                          *   match-finder already found at least one match.
1035                          *
1036                          * - Only consider the longest repeat offset match.  It
1037                          *   seems to be rare for the optimal parse to include a
1038                          *   repeat offset match that doesn't have the longest
1039                          *   length (allowing for the possibility that not all
1040                          *   of that length is actually used).
1041                          */
1042                         if (likely(window_ptr - c->cur_window >= LZMS_MAX_INIT_RECENT_OFFSET)) {
1043                                 BUILD_BUG_ON(LZMS_NUM_RECENT_OFFSETS != 3);
1044                                 rep_max_len = lz_repsearch3(window_ptr,
1045                                                             window_end - window_ptr,
1046                                                             cur_optimum_ptr->state.lru.recent_offsets,
1047                                                             &rep_max_idx);
1048                         } else {
1049                                 rep_max_len = 0;
1050                         }
1051
1052                         if (rep_max_len) {
1053                                 /* If there's a very long repeat offset match,
1054                                  * choose it immediately.  */
1055                                 if (rep_max_len >= c->params.nice_match_length) {
1056
1057                                         lz_mf_skip_positions(c->mf, rep_max_len - 1);
1058                                         window_ptr += rep_max_len;
1059
1060                                         if (cur_optimum_ptr != c->optimum)
1061                                                 lzms_encode_item_list(c, cur_optimum_ptr);
1062
1063                                         lzms_encode_lz_repeat_offset_match(c, rep_max_len,
1064                                                                            rep_max_idx);
1065
1066                                         c->optimum[0].state = cur_optimum_ptr->state;
1067
1068                                         lzms_update_main_state(&c->optimum[0].state, 1);
1069                                         lzms_update_match_state(&c->optimum[0].state, 0);
1070                                         lzms_update_lz_match_state(&c->optimum[0].state, 1);
1071                                         lzms_update_lz_repeat_match_state(&c->optimum[0].state,
1072                                                                           rep_max_idx);
1073
1074                                         c->optimum[0].state.lru.upcoming_offset =
1075                                                 c->optimum[0].state.lru.recent_offsets[rep_max_idx];
1076
1077                                         for (i = rep_max_idx; i < LZMS_NUM_RECENT_OFFSETS; i++)
1078                                                 c->optimum[0].state.lru.recent_offsets[i] =
1079                                                         c->optimum[0].state.lru.recent_offsets[i + 1];
1080
1081                                         lzms_update_lz_lru_queue(&c->optimum[0].state.lru);
1082                                         goto begin;
1083                                 }
1084
1085                                 /* If reaching any positions for the first time,
1086                                  * initialize their costs to "infinity".  */
1087                                 while (end_optimum_ptr < cur_optimum_ptr + rep_max_len)
1088                                         (++end_optimum_ptr)->cost = MC_INFINITE_COST;
1089
1090                                 /* Consider coding a repeat offset match.  */
1091                                 lzms_consider_lz_repeat_offset_match(c, cur_optimum_ptr,
1092                                                                      rep_max_len, rep_max_idx);
1093                         }
1094
1095                         longest_len = c->matches[num_matches - 1].len;
1096
1097                         /* If there's a very long explicit offset match, choose
1098                          * it immediately.  */
1099                         if (longest_len >= c->params.nice_match_length) {
1100
1101                                 lz_mf_skip_positions(c->mf, longest_len - 1);
1102                                 window_ptr += longest_len;
1103
1104                                 if (cur_optimum_ptr != c->optimum)
1105                                         lzms_encode_item_list(c, cur_optimum_ptr);
1106
1107                                 lzms_encode_lz_explicit_offset_match(c, longest_len,
1108                                                                      c->matches[num_matches - 1].offset);
1109
1110                                 c->optimum[0].state = cur_optimum_ptr->state;
1111
1112                                 lzms_update_main_state(&c->optimum[0].state, 1);
1113                                 lzms_update_match_state(&c->optimum[0].state, 0);
1114                                 lzms_update_lz_match_state(&c->optimum[0].state, 0);
1115
1116                                 c->optimum[0].state.lru.upcoming_offset =
1117                                         c->matches[num_matches - 1].offset;
1118
1119                                 lzms_update_lz_lru_queue(&c->optimum[0].state.lru);
1120                                 goto begin;
1121                         }
1122
1123                         /* If reaching any positions for the first time,
1124                          * initialize their costs to "infinity".  */
1125                         while (end_optimum_ptr < cur_optimum_ptr + longest_len)
1126                                 (++end_optimum_ptr)->cost = MC_INFINITE_COST;
1127
1128                         /* Consider coding an explicit offset match.  */
1129                         lzms_consider_lz_explicit_offset_matches(c, cur_optimum_ptr,
1130                                                                  c->matches, num_matches);
1131                 } else {
1132                         /* No matches found.  The only choice at this position
1133                          * is to code a literal.  */
1134
1135                         if (end_optimum_ptr == cur_optimum_ptr)
1136                                 (++end_optimum_ptr)->cost = MC_INFINITE_COST;
1137                 }
1138
1139                 /* Consider coding a literal.
1140
1141                  * To avoid an extra unpredictable brench, actually checking the
1142                  * preferability of coding a literal is integrated into the
1143                  * adaptive state update code below.  */
1144                 literal = *window_ptr++;
1145                 cost = cur_optimum_ptr->cost +
1146                        lzms_literal_cost(c, literal, &cur_optimum_ptr->state);
1147
1148                 /* Advance to the next position.  */
1149                 cur_optimum_ptr++;
1150
1151                 /* The lowest-cost path to the current position is now known.
1152                  * Finalize the adaptive state that results from taking this
1153                  * lowest-cost path.  */
1154
1155                 if (cost < cur_optimum_ptr->cost) {
1156                         /* Literal  */
1157                         cur_optimum_ptr->cost = cost;
1158                         cur_optimum_ptr->mc_item_data = ((u64)literal << MC_OFFSET_SHIFT) | 1;
1159
1160                         cur_optimum_ptr->state = (cur_optimum_ptr - 1)->state;
1161
1162                         lzms_update_main_state(&cur_optimum_ptr->state, 0);
1163
1164                         cur_optimum_ptr->state.lru.upcoming_offset = 0;
1165                 } else {
1166                         /* LZ match  */
1167                         len = cur_optimum_ptr->mc_item_data & MC_LEN_MASK;
1168                         offset_data = cur_optimum_ptr->mc_item_data >> MC_OFFSET_SHIFT;
1169
1170                         cur_optimum_ptr->state = (cur_optimum_ptr - len)->state;
1171
1172                         lzms_update_main_state(&cur_optimum_ptr->state, 1);
1173                         lzms_update_match_state(&cur_optimum_ptr->state, 0);
1174
1175                         if (offset_data >= LZMS_NUM_RECENT_OFFSETS) {
1176
1177                                 /* Explicit offset LZ match  */
1178
1179                                 lzms_update_lz_match_state(&cur_optimum_ptr->state, 0);
1180
1181                                 cur_optimum_ptr->state.lru.upcoming_offset =
1182                                         offset_data - LZMS_OFFSET_OFFSET;
1183                         } else {
1184                                 /* Repeat offset LZ match  */
1185
1186                                 lzms_update_lz_match_state(&cur_optimum_ptr->state, 1);
1187                                 lzms_update_lz_repeat_match_state(&cur_optimum_ptr->state,
1188                                                                   offset_data);
1189
1190                                 cur_optimum_ptr->state.lru.upcoming_offset =
1191                                         cur_optimum_ptr->state.lru.recent_offsets[offset_data];
1192
1193                                 for (i = offset_data; i < LZMS_NUM_RECENT_OFFSETS; i++)
1194                                         cur_optimum_ptr->state.lru.recent_offsets[i] =
1195                                                 cur_optimum_ptr->state.lru.recent_offsets[i + 1];
1196                         }
1197                 }
1198
1199                 lzms_update_lz_lru_queue(&cur_optimum_ptr->state.lru);
1200
1201                 /*
1202                  * This loop will terminate when either of the following
1203                  * conditions is true:
1204                  *
1205                  * (1) cur_optimum_ptr == end_optimum_ptr
1206                  *
1207                  *      There are no paths that extend beyond the current
1208                  *      position.  In this case, any path to a later position
1209                  *      must pass through the current position, so we can go
1210                  *      ahead and choose the list of items that led to this
1211                  *      position.
1212                  *
1213                  * (2) cur_optimum_ptr == c->optimum_end
1214                  *
1215                  *      This bounds the number of times the algorithm can step
1216                  *      forward before it is guaranteed to start choosing items.
1217                  *      This limits the memory usage.  It also guarantees that
1218                  *      the parser will not go too long without updating the
1219                  *      probability tables.
1220                  *
1221                  * Note: no check for end-of-block is needed because
1222                  * end-of-block will trigger condition (1).
1223                  */
1224                 if (cur_optimum_ptr == end_optimum_ptr ||
1225                     cur_optimum_ptr == c->optimum_end)
1226                 {
1227                         c->optimum[0].state = cur_optimum_ptr->state;
1228                         break;
1229                 }
1230         }
1231
1232         /* Output the current list of items that constitute the minimum-cost
1233          * path to the current position.  */
1234         lzms_encode_item_list(c, cur_optimum_ptr);
1235         goto begin;
1236 }
1237
1238 static void
1239 lzms_init_range_encoder(struct lzms_range_encoder *enc,
1240                         struct lzms_range_encoder_raw *rc, u32 num_states)
1241 {
1242         enc->rc = rc;
1243         enc->state = 0;
1244         LZMS_ASSERT(is_power_of_2(num_states));
1245         enc->mask = num_states - 1;
1246         for (u32 i = 0; i < num_states; i++) {
1247                 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
1248                 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
1249         }
1250 }
1251
1252 static void
1253 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
1254                           struct lzms_output_bitstream *os,
1255                           unsigned num_syms,
1256                           unsigned rebuild_freq)
1257 {
1258         enc->os = os;
1259         enc->num_syms_written = 0;
1260         enc->rebuild_freq = rebuild_freq;
1261         enc->num_syms = num_syms;
1262         for (unsigned i = 0; i < num_syms; i++)
1263                 enc->sym_freqs[i] = 1;
1264
1265         make_canonical_huffman_code(enc->num_syms,
1266                                     LZMS_MAX_CODEWORD_LEN,
1267                                     enc->sym_freqs,
1268                                     enc->lens,
1269                                     enc->codewords);
1270 }
1271
1272 /* Prepare the LZMS compressor for compressing a block of data.  */
1273 static void
1274 lzms_prepare_compressor(struct lzms_compressor *c, const u8 *udata, u32 ulen,
1275                         le16 *cdata, u32 clen16)
1276 {
1277         unsigned num_offset_slots;
1278
1279         /* Copy the uncompressed data into the @c->cur_window buffer.  */
1280         memcpy(c->cur_window, udata, ulen);
1281         c->cur_window_size = ulen;
1282
1283         /* Initialize the raw range encoder (writing forwards).  */
1284         lzms_range_encoder_raw_init(&c->rc, cdata, clen16);
1285
1286         /* Initialize the output bitstream for Huffman symbols and verbatim bits
1287          * (writing backwards).  */
1288         lzms_output_bitstream_init(&c->os, cdata, clen16);
1289
1290         /* Calculate the number of offset slots required.  */
1291         num_offset_slots = lzms_get_offset_slot(ulen - 1) + 1;
1292
1293         /* Initialize a Huffman encoder for each alphabet.  */
1294         lzms_init_huffman_encoder(&c->literal_encoder, &c->os,
1295                                   LZMS_NUM_LITERAL_SYMS,
1296                                   LZMS_LITERAL_CODE_REBUILD_FREQ);
1297
1298         lzms_init_huffman_encoder(&c->lz_offset_encoder, &c->os,
1299                                   num_offset_slots,
1300                                   LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
1301
1302         lzms_init_huffman_encoder(&c->length_encoder, &c->os,
1303                                   LZMS_NUM_LEN_SYMS,
1304                                   LZMS_LENGTH_CODE_REBUILD_FREQ);
1305
1306         lzms_init_huffman_encoder(&c->delta_offset_encoder, &c->os,
1307                                   num_offset_slots,
1308                                   LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
1309
1310         lzms_init_huffman_encoder(&c->delta_power_encoder, &c->os,
1311                                   LZMS_NUM_DELTA_POWER_SYMS,
1312                                   LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
1313
1314         /* Initialize range encoders, all of which wrap around the same
1315          * lzms_range_encoder_raw.  */
1316         lzms_init_range_encoder(&c->main_range_encoder,
1317                                 &c->rc, LZMS_NUM_MAIN_STATES);
1318
1319         lzms_init_range_encoder(&c->match_range_encoder,
1320                                 &c->rc, LZMS_NUM_MATCH_STATES);
1321
1322         lzms_init_range_encoder(&c->lz_match_range_encoder,
1323                                 &c->rc, LZMS_NUM_LZ_MATCH_STATES);
1324
1325         for (unsigned i = 0; i < ARRAY_LEN(c->lz_repeat_match_range_encoders); i++)
1326                 lzms_init_range_encoder(&c->lz_repeat_match_range_encoders[i],
1327                                         &c->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
1328
1329         lzms_init_range_encoder(&c->delta_match_range_encoder,
1330                                 &c->rc, LZMS_NUM_DELTA_MATCH_STATES);
1331
1332         for (unsigned i = 0; i < ARRAY_LEN(c->delta_repeat_match_range_encoders); i++)
1333                 lzms_init_range_encoder(&c->delta_repeat_match_range_encoders[i],
1334                                         &c->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1335
1336         /* Set initial length costs for lengths < LZMS_NUM_FAST_LENGTHS.  */
1337         lzms_update_fast_length_costs(c);
1338 }
1339
1340 /* Flush the output streams, prepare the final compressed data, and return its
1341  * size in bytes.
1342  *
1343  * A return value of 0 indicates that the data could not be compressed to fit in
1344  * the available space.  */
1345 static size_t
1346 lzms_finalize(struct lzms_compressor *c, u8 *cdata, size_t csize_avail)
1347 {
1348         size_t num_forwards_bytes;
1349         size_t num_backwards_bytes;
1350
1351         /* Flush both the forwards and backwards streams, and make sure they
1352          * didn't cross each other and start overwriting each other's data.  */
1353         if (!lzms_output_bitstream_flush(&c->os))
1354                 return 0;
1355
1356         if (!lzms_range_encoder_raw_flush(&c->rc))
1357                 return 0;
1358
1359         if (c->rc.next > c->os.next)
1360                 return 0;
1361
1362         /* Now the compressed buffer contains the data output by the forwards
1363          * bitstream, then empty space, then data output by the backwards
1364          * bitstream.  Move the data output by the backwards bitstream to be
1365          * adjacent to the data output by the forward bitstream, and calculate
1366          * the compressed size that this results in.  */
1367         num_forwards_bytes = (u8*)c->rc.next - (u8*)cdata;
1368         num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)c->os.next;
1369
1370         memmove(cdata + num_forwards_bytes, c->os.next, num_backwards_bytes);
1371
1372         return num_forwards_bytes + num_backwards_bytes;
1373 }
1374
1375 /* Set internal compression parameters for the specified compression level and
1376  * maximum window size.  */
1377 static void
1378 lzms_build_params(unsigned int compression_level,
1379                   struct lzms_compressor_params *lzms_params)
1380 {
1381         /* Allow length 2 matches if the compression level is sufficiently high.
1382          */
1383         if (compression_level >= 45)
1384                 lzms_params->min_match_length = 2;
1385         else
1386                 lzms_params->min_match_length = 3;
1387
1388         /* Scale nice_match_length and max_search_depth with the compression
1389          * level.  But to allow an optimization on length cost calculations,
1390          * don't allow nice_match_length to exceed LZMS_NUM_FAST_LENGTH.  */
1391         lzms_params->nice_match_length = ((u64)compression_level * 32) / 50;
1392         if (lzms_params->nice_match_length < lzms_params->min_match_length)
1393                 lzms_params->nice_match_length = lzms_params->min_match_length;
1394         if (lzms_params->nice_match_length > LZMS_NUM_FAST_LENGTHS)
1395                 lzms_params->nice_match_length = LZMS_NUM_FAST_LENGTHS;
1396         lzms_params->max_search_depth = compression_level;
1397
1398         lzms_params->optim_array_length = 1024;
1399 }
1400
1401 /* Given the internal compression parameters and maximum window size, build the
1402  * Lempel-Ziv match-finder parameters.  */
1403 static void
1404 lzms_build_mf_params(const struct lzms_compressor_params *lzms_params,
1405                      u32 max_window_size, struct lz_mf_params *mf_params)
1406 {
1407         memset(mf_params, 0, sizeof(*mf_params));
1408
1409         /* Choose an appropriate match-finding algorithm.  */
1410         if (max_window_size <= 2097152)
1411                 mf_params->algorithm = LZ_MF_BINARY_TREES;
1412         else if (max_window_size <= 33554432)
1413                 mf_params->algorithm = LZ_MF_LCP_INTERVAL_TREE;
1414         else
1415                 mf_params->algorithm = LZ_MF_LINKED_SUFFIX_ARRAY;
1416
1417         mf_params->max_window_size = max_window_size;
1418         mf_params->min_match_len = lzms_params->min_match_length;
1419         mf_params->max_search_depth = lzms_params->max_search_depth;
1420         mf_params->nice_match_len = lzms_params->nice_match_length;
1421 }
1422
1423 static void
1424 lzms_free_compressor(void *_c);
1425
1426 static u64
1427 lzms_get_needed_memory(size_t max_block_size, unsigned int compression_level)
1428 {
1429         struct lzms_compressor_params params;
1430         struct lz_mf_params mf_params;
1431         u64 size = 0;
1432
1433         if (max_block_size >= INT32_MAX)
1434                 return 0;
1435
1436         lzms_build_params(compression_level, &params);
1437         lzms_build_mf_params(&params, max_block_size, &mf_params);
1438
1439         size += sizeof(struct lzms_compressor);
1440
1441         /* cur_window */
1442         size += max_block_size;
1443
1444         /* mf */
1445         size += lz_mf_get_needed_memory(mf_params.algorithm, max_block_size);
1446
1447         /* matches */
1448         size += min(params.max_search_depth, params.nice_match_length) *
1449                 sizeof(struct lz_match);
1450
1451         /* optimum */
1452         size += (params.optim_array_length + params.nice_match_length) *
1453                 sizeof(struct lzms_mc_pos_data);
1454
1455         return size;
1456 }
1457
1458 static int
1459 lzms_create_compressor(size_t max_block_size, unsigned int compression_level,
1460                        void **ctx_ret)
1461 {
1462         struct lzms_compressor *c;
1463         struct lzms_compressor_params params;
1464         struct lz_mf_params mf_params;
1465
1466         if (max_block_size >= INT32_MAX)
1467                 return WIMLIB_ERR_INVALID_PARAM;
1468
1469         lzms_build_params(compression_level, &params);
1470         lzms_build_mf_params(&params, max_block_size, &mf_params);
1471         if (!lz_mf_params_valid(&mf_params))
1472                 return WIMLIB_ERR_INVALID_PARAM;
1473
1474         c = CALLOC(1, sizeof(struct lzms_compressor));
1475         if (!c)
1476                 goto oom;
1477
1478         c->params = params;
1479
1480         c->cur_window = MALLOC(max_block_size);
1481         if (!c->cur_window)
1482                 goto oom;
1483
1484         c->mf = lz_mf_alloc(&mf_params);
1485         if (!c->mf)
1486                 goto oom;
1487
1488         c->matches = MALLOC(min(params.max_search_depth,
1489                                 params.nice_match_length) *
1490                             sizeof(struct lz_match));
1491         if (!c->matches)
1492                 goto oom;
1493
1494         c->optimum = MALLOC((params.optim_array_length +
1495                              params.nice_match_length) *
1496                             sizeof(struct lzms_mc_pos_data));
1497         if (!c->optimum)
1498                 goto oom;
1499         c->optimum_end = &c->optimum[params.optim_array_length];
1500
1501         lzms_init_slots();
1502
1503         lzms_init_rc_costs();
1504
1505         lzms_init_fast_slots(c);
1506
1507         *ctx_ret = c;
1508         return 0;
1509
1510 oom:
1511         lzms_free_compressor(c);
1512         return WIMLIB_ERR_NOMEM;
1513 }
1514
1515 static size_t
1516 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1517               void *compressed_data, size_t compressed_size_avail, void *_c)
1518 {
1519         struct lzms_compressor *c = _c;
1520
1521         /* Don't bother compressing extremely small inputs.  */
1522         if (uncompressed_size < 4)
1523                 return 0;
1524
1525         /* Cap the available compressed size to a 32-bit integer and round it
1526          * down to the nearest multiple of 2.  */
1527         if (compressed_size_avail > UINT32_MAX)
1528                 compressed_size_avail = UINT32_MAX;
1529         if (compressed_size_avail & 1)
1530                 compressed_size_avail--;
1531
1532         /* Initialize the compressor structures.  */
1533         lzms_prepare_compressor(c, uncompressed_data, uncompressed_size,
1534                                 compressed_data, compressed_size_avail / 2);
1535
1536         /* Preprocess the uncompressed data.  */
1537         lzms_x86_filter(c->cur_window, c->cur_window_size,
1538                         c->last_target_usages, false);
1539
1540         /* Load the window into the match-finder.  */
1541         lz_mf_load_window(c->mf, c->cur_window, c->cur_window_size);
1542
1543         /* Compute and encode a literal/match sequence that decompresses to the
1544          * preprocessed data.  */
1545         lzms_near_optimal_parse(c);
1546
1547         /* Return the compressed data size or 0.  */
1548         return lzms_finalize(c, compressed_data, compressed_size_avail);
1549 }
1550
1551 static void
1552 lzms_free_compressor(void *_c)
1553 {
1554         struct lzms_compressor *c = _c;
1555
1556         if (c) {
1557                 FREE(c->cur_window);
1558                 lz_mf_free(c->mf);
1559                 FREE(c->matches);
1560                 FREE(c->optimum);
1561                 FREE(c);
1562         }
1563 }
1564
1565 const struct compressor_ops lzms_compressor_ops = {
1566         .get_needed_memory  = lzms_get_needed_memory,
1567         .create_compressor  = lzms_create_compressor,
1568         .compress           = lzms_compress,
1569         .free_compressor    = lzms_free_compressor,
1570 };