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