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