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