]> wimlib.net Git - wimlib/blob - src/lzms-compress.c
9373dc22bf2e2aec93d7a764a9d7122676b052e3
[wimlib] / src / lzms-compress.c
1 /*
2  * lzms-compress.c
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 /* This a compressor for the LZMS compression format.  More details about this
25  * format can be found in lzms-decompress.c.
26  *
27  * This is currently an unsophisticated implementation that is fast but does not
28  * attain the best compression ratios allowed by the format.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #  include "config.h"
33 #endif
34
35 #include "wimlib.h"
36 #include "wimlib/assert.h"
37 #include "wimlib/compiler.h"
38 #include "wimlib/compressor_ops.h"
39 #include "wimlib/compress_common.h"
40 #include "wimlib/endianness.h"
41 #include "wimlib/error.h"
42 #include "wimlib/lz_hash.h"
43 #include "wimlib/lz_sarray.h"
44 #include "wimlib/lzms.h"
45 #include "wimlib/util.h"
46
47 #include <string.h>
48 #include <limits.h>
49
50 #define LZMS_OPTIM_ARRAY_SIZE   1024
51
52 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
53  * a series of 16-bit little endian coding units.  */
54 struct lzms_output_bitstream {
55         /* Buffer variable containing zero or more bits that have been logically
56          * written to the bitstream but not yet written to memory.  This must be
57          * at least as large as the coding unit size.  */
58         u16 bitbuf;
59
60         /* Number of bits in @bitbuf that are valid.  */
61         unsigned num_free_bits;
62
63         /* Pointer to one past the next position in the compressed data buffer
64          * at which to output a 16-bit coding unit.  */
65         le16 *out;
66
67         /* Maximum number of 16-bit coding units that can still be output to
68          * the compressed data buffer.  */
69         size_t num_le16_remaining;
70
71         /* Set to %true if not all coding units could be output due to
72          * insufficient space.  */
73         bool overrun;
74 };
75
76 /* Stucture used for range encoding (raw version).  */
77 struct lzms_range_encoder_raw {
78
79         /* A 33-bit variable that holds the low boundary of the current range.
80          * The 33rd bit is needed to catch carries.  */
81         u64 low;
82
83         /* Size of the current range.  */
84         u32 range;
85
86         /* Next 16-bit coding unit to output.  */
87         u16 cache;
88
89         /* Number of 16-bit coding units whose output has been delayed due to
90          * possible carrying.  The first such coding unit is @cache; all
91          * subsequent such coding units are 0xffff.  */
92         u32 cache_size;
93
94         /* Pointer to the next position in the compressed data buffer at which
95          * to output a 16-bit coding unit.  */
96         le16 *out;
97
98         /* Maximum number of 16-bit coding units that can still be output to
99          * the compressed data buffer.  */
100         size_t num_le16_remaining;
101
102         /* %true when the very first coding unit has not yet been output.  */
103         bool first;
104
105         /* Set to %true if not all coding units could be output due to
106          * insufficient space.  */
107         bool overrun;
108 };
109
110 /* Structure used for range encoding.  This wraps around `struct
111  * lzms_range_encoder_raw' to use and maintain probability entries.  */
112 struct lzms_range_encoder {
113         /* Pointer to the raw range encoder, which has no persistent knowledge
114          * of probabilities.  Multiple lzms_range_encoder's share the same
115          * lzms_range_encoder_raw.  */
116         struct lzms_range_encoder_raw *rc;
117
118         /* Bits recently encoded by this range encoder.  This are used as in
119          * index into @prob_entries.  */
120         u32 state;
121
122         /* Bitmask for @state to prevent its value from exceeding the number of
123          * probability entries.  */
124         u32 mask;
125
126         /* Probability entries being used for this range encoder.  */
127         struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
128 };
129
130 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
131  * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
132  * */
133 struct lzms_huffman_encoder {
134
135         /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
136          * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
137          */
138         struct lzms_output_bitstream *os;
139
140         /* Pointer to the slot base table to use.  */
141         const u32 *slot_base_tab;
142
143         /* Number of symbols that have been written using this code far.  Reset
144          * to 0 whenever the code is rebuilt.  */
145         u32 num_syms_written;
146
147         /* When @num_syms_written reaches this number, the Huffman code must be
148          * rebuilt.  */
149         u32 rebuild_freq;
150
151         /* Number of symbols in the represented Huffman code.  */
152         unsigned num_syms;
153
154         /* Running totals of symbol frequencies.  These are diluted slightly
155          * whenever the code is rebuilt.  */
156         u32 sym_freqs[LZMS_MAX_NUM_SYMS];
157
158         /* The length, in bits, of each symbol in the Huffman code.  */
159         u8 lens[LZMS_MAX_NUM_SYMS];
160
161         /* The codeword of each symbol in the Huffman code.  */
162         u16 codewords[LZMS_MAX_NUM_SYMS];
163 };
164
165 /* State of the LZMS compressor.  */
166 struct lzms_compressor {
167         /* Pointer to a buffer holding the preprocessed data to compress.  */
168         u8 *window;
169
170         /* Current position in @buffer.  */
171         u32 cur_window_pos;
172
173         /* Size of the data in @buffer.  */
174         u32 window_size;
175
176         /* Temporary array used by lz_analyze_block(); must be at least as long
177          * as the window.  */
178         u32 *prev_tab;
179
180         /* Suffix array match-finder.  */
181         struct lz_sarray lz_sarray;
182
183         /* Maximum block size this compressor instantiation allows.  This is the
184          * allocated size of @window.  */
185         u32 max_block_size;
186
187         /* Raw range encoder which outputs to the beginning of the compressed
188          * data buffer, proceeding forwards.  */
189         struct lzms_range_encoder_raw rc;
190
191         /* Bitstream which outputs to the end of the compressed data buffer,
192          * proceeding backwards.  */
193         struct lzms_output_bitstream os;
194
195         /* Range encoders.  */
196         struct lzms_range_encoder main_range_encoder;
197         struct lzms_range_encoder match_range_encoder;
198         struct lzms_range_encoder lz_match_range_encoder;
199         struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
200         struct lzms_range_encoder delta_match_range_encoder;
201         struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
202
203         /* Huffman encoders.  */
204         struct lzms_huffman_encoder literal_encoder;
205         struct lzms_huffman_encoder lz_offset_encoder;
206         struct lzms_huffman_encoder length_encoder;
207         struct lzms_huffman_encoder delta_power_encoder;
208         struct lzms_huffman_encoder delta_offset_encoder;
209
210         /* LRU (least-recently-used) queues for match information.  */
211         struct lzms_lru_queues lru;
212
213         /* Used for preprocessing.  */
214         s32 last_target_usages[65536];
215 };
216
217 /* Initialize the output bitstream @os to write forwards to the specified
218  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
219 static void
220 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
221                            le16 *out, size_t out_limit)
222 {
223         os->bitbuf = 0;
224         os->num_free_bits = 16;
225         os->out = out + out_limit;
226         os->num_le16_remaining = out_limit;
227         os->overrun = false;
228 }
229
230 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
231  * from high-order to low-order), to the output bitstream @os.  */
232 static void
233 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
234                                u32 bits, unsigned num_bits)
235 {
236         bits &= (1U << num_bits) - 1;
237
238         while (num_bits > os->num_free_bits) {
239
240                 if (unlikely(os->num_le16_remaining == 0)) {
241                         os->overrun = true;
242                         return;
243                 }
244
245                 unsigned num_fill_bits = os->num_free_bits;
246
247                 os->bitbuf <<= num_fill_bits;
248                 os->bitbuf |= bits >> (num_bits - num_fill_bits);
249
250                 *--os->out = cpu_to_le16(os->bitbuf);
251                 --os->num_le16_remaining;
252
253                 os->num_free_bits = 16;
254                 num_bits -= num_fill_bits;
255                 bits &= (1U << num_bits) - 1;
256         }
257         os->bitbuf <<= num_bits;
258         os->bitbuf |= bits;
259         os->num_free_bits -= num_bits;
260 }
261
262 /* Flush the output bitstream, ensuring that all bits written to it have been
263  * written to memory.  Returns %true if all bits were output successfully, or
264  * %false if an overrun occurred.  */
265 static bool
266 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
267 {
268         if (os->num_free_bits != 16)
269                 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
270         return !os->overrun;
271 }
272
273 /* Initialize the range encoder @rc to write forwards to the specified
274  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
275 static void
276 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
277                             le16 *out, size_t out_limit)
278 {
279         rc->low = 0;
280         rc->range = 0xffffffff;
281         rc->cache = 0;
282         rc->cache_size = 1;
283         rc->out = out;
284         rc->num_le16_remaining = out_limit;
285         rc->first = true;
286         rc->overrun = false;
287 }
288
289 /*
290  * Attempt to flush bits from the range encoder.
291  *
292  * Note: this is based on the public domain code for LZMA written by Igor
293  * Pavlov.  The only differences in this function are that in LZMS the bits must
294  * be output in 16-bit coding units instead of 8-bit coding units, and that in
295  * LZMS the first coding unit is not ignored by the decompressor, so the encoder
296  * cannot output a dummy value to that position.
297  *
298  * The basic idea is that we're writing bits from @rc->low to the output.
299  * However, due to carrying, the writing of coding units with value 0xffff, as
300  * well as one prior coding unit, must be delayed until it is determined whether
301  * a carry is needed.
302  */
303 static void
304 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
305 {
306         LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
307                    rc->low, rc->cache, rc->cache_size);
308         if ((u32)(rc->low) < 0xffff0000 ||
309             (u32)(rc->low >> 32) != 0)
310         {
311                 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
312                  * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1).  */
313                 do {
314                         if (!rc->first) {
315                                 if (rc->num_le16_remaining == 0) {
316                                         rc->overrun = true;
317                                         return;
318                                 }
319                                 *rc->out++ = cpu_to_le16(rc->cache +
320                                                          (u16)(rc->low >> 32));
321                                 --rc->num_le16_remaining;
322                         } else {
323                                 rc->first = false;
324                         }
325
326                         rc->cache = 0xffff;
327                 } while (--rc->cache_size != 0);
328
329                 rc->cache = (rc->low >> 16) & 0xffff;
330         }
331         ++rc->cache_size;
332         rc->low = (rc->low & 0xffff) << 16;
333 }
334
335 static void
336 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
337 {
338         if (rc->range <= 0xffff) {
339                 rc->range <<= 16;
340                 lzms_range_encoder_raw_shift_low(rc);
341         }
342 }
343
344 static bool
345 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
346 {
347         for (unsigned i = 0; i < 4; i++)
348                 lzms_range_encoder_raw_shift_low(rc);
349         return !rc->overrun;
350 }
351
352 /* Encode the next bit using the range encoder (raw version).
353  *
354  * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0.  */
355 static void
356 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
357                                   u32 prob)
358 {
359         lzms_range_encoder_raw_normalize(rc);
360
361         u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
362         if (bit == 0) {
363                 rc->range = bound;
364         } else {
365                 rc->low += bound;
366                 rc->range -= bound;
367         }
368 }
369
370 /* Encode a bit using the specified range encoder. This wraps around
371  * lzms_range_encoder_raw_encode_bit() to handle using and updating the
372  * appropriate probability table.  */
373 static void
374 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
375 {
376         struct lzms_probability_entry *prob_entry;
377         u32 prob;
378
379         /* Load the probability entry corresponding to the current state.  */
380         prob_entry = &enc->prob_entries[enc->state];
381
382         /* Treat the number of zero bits in the most recently encoded
383          * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
384          * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0.  However,
385          * don't allow 0% or 100% probabilities.  */
386         prob = prob_entry->num_recent_zero_bits;
387         if (prob == 0)
388                 prob = 1;
389         else if (prob == LZMS_PROBABILITY_MAX)
390                 prob = LZMS_PROBABILITY_MAX - 1;
391
392         /* Encode the next bit.  */
393         lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
394
395         /* Update the state based on the newly encoded bit.  */
396         enc->state = ((enc->state << 1) | bit) & enc->mask;
397
398         /* Update the recent bits, including the cached count of 0's.  */
399         BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
400         if (bit == 0) {
401                 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
402                         /* Replacing 1 bit with 0 bit; increment the zero count.
403                          */
404                         prob_entry->num_recent_zero_bits++;
405                 }
406         } else {
407                 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
408                         /* Replacing 0 bit with 1 bit; decrement the zero count.
409                          */
410                         prob_entry->num_recent_zero_bits--;
411                 }
412         }
413         prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
414 }
415
416 /* Encode a symbol using the specified Huffman encoder.  */
417 static void
418 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
419 {
420         LZMS_ASSERT(sym < enc->num_syms);
421         if (enc->num_syms_written == enc->rebuild_freq) {
422                 /* Adaptive code needs to be rebuilt.  */
423                 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
424                 make_canonical_huffman_code(enc->num_syms,
425                                             LZMS_MAX_CODEWORD_LEN,
426                                             enc->sym_freqs,
427                                             enc->lens,
428                                             enc->codewords);
429
430                 /* Dilute the frequencies.  */
431                 for (unsigned i = 0; i < enc->num_syms; i++) {
432                         enc->sym_freqs[i] >>= 1;
433                         enc->sym_freqs[i] += 1;
434                 }
435                 enc->num_syms_written = 0;
436         }
437         lzms_output_bitstream_put_bits(enc->os,
438                                        enc->codewords[sym],
439                                        enc->lens[sym]);
440         ++enc->num_syms_written;
441         ++enc->sym_freqs[sym];
442 }
443
444 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
445  * slot-dependent extra bits.  */
446 static void
447 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
448 {
449         unsigned slot;
450         unsigned num_extra_bits;
451         u32 extra_bits;
452
453         LZMS_ASSERT(enc->slot_base_tab != NULL);
454
455         slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
456
457         /* Get the number of extra bits needed to represent the range of values
458          * that share the slot.  */
459         num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
460                                enc->slot_base_tab[slot]);
461
462         /* Calculate the extra bits as the offset from the slot base.  */
463         extra_bits = value - enc->slot_base_tab[slot];
464
465         /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
466          */
467         lzms_huffman_encode_symbol(enc, slot);
468         lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
469 }
470
471 static void
472 lzms_begin_encode_item(struct lzms_compressor *ctx)
473 {
474         ctx->lru.lz.upcoming_offset = 0;
475         ctx->lru.delta.upcoming_offset = 0;
476         ctx->lru.delta.upcoming_power = 0;
477 }
478
479 static void
480 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
481 {
482         LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
483         ctx->cur_window_pos += length;
484         lzms_update_lru_queues(&ctx->lru);
485 }
486
487 /* Encode a literal byte.  */
488 static void
489 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
490 {
491         LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
492                    ctx->cur_window_pos, literal, literal);
493
494         lzms_begin_encode_item(ctx);
495
496         /* Main bit: 0 = a literal, not a match.  */
497         lzms_range_encode_bit(&ctx->main_range_encoder, 0);
498
499         /* Encode the literal using the current literal Huffman code.  */
500         lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
501
502         lzms_end_encode_item(ctx, 1);
503 }
504
505 /* Encode a (length, offset) pair (LZ match).  */
506 static void
507 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
508 {
509         int recent_offset_idx;
510
511         lzms_begin_encode_item(ctx);
512
513         LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
514                    ctx->cur_window_pos, length, offset);
515
516         /* Main bit: 1 = a match, not a literal.  */
517         lzms_range_encode_bit(&ctx->main_range_encoder, 1);
518
519         /* Match bit: 0 = a LZ match, not a delta match.  */
520         lzms_range_encode_bit(&ctx->match_range_encoder, 0);
521
522         /* Determine if the offset can be represented as a recent offset.  */
523         for (recent_offset_idx = 0;
524              recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
525              recent_offset_idx++)
526                 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
527                         break;
528
529         if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
530                 /* Explicit offset.  */
531
532                 /* LZ match bit: 0 = explicit offset, not a repeat offset.  */
533                 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
534
535                 /* Encode the match offset.  */
536                 lzms_encode_value(&ctx->lz_offset_encoder, offset);
537         } else {
538                 int i;
539
540                 /* Repeat offset.  */
541
542                 /* LZ match bit: 1 = repeat offset, not an explicit offset.  */
543                 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
544
545                 /* Encode the recent offset index.  A 1 bit is encoded for each
546                  * index passed up.  This sequence of 1 bits is terminated by a
547                  * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
548                  * bits have been encoded.  */
549                 for (i = 0; i < recent_offset_idx; i++)
550                         lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
551
552                 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
553                         lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
554
555                 /* Initial update of the LZ match offset LRU queue.  */
556                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
557                         ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
558         }
559
560         /* Encode the match length.  */
561         lzms_encode_value(&ctx->length_encoder, length);
562
563         /* Save the match offset for later insertion at the front of the LZ
564          * match offset LRU queue.  */
565         ctx->lru.lz.upcoming_offset = offset;
566
567         lzms_end_encode_item(ctx, length);
568 }
569
570 static void
571 lzms_record_literal(u8 literal, void *_ctx)
572 {
573         struct lzms_compressor *ctx = _ctx;
574
575         lzms_encode_literal(ctx, literal);
576 }
577
578 static void
579 lzms_record_match(unsigned length, unsigned offset, void *_ctx)
580 {
581         struct lzms_compressor *ctx = _ctx;
582
583         lzms_encode_lz_match(ctx, length, offset);
584 }
585
586 static void
587 lzms_fast_encode(struct lzms_compressor *ctx)
588 {
589         static const struct lz_params lzms_lz_params = {
590                 .min_match      = 3,
591                 .max_match      = UINT_MAX,
592                 .max_offset     = UINT_MAX,
593                 .nice_match     = 64,
594                 .good_match     = 32,
595                 .max_chain_len  = 64,
596                 .max_lazy_match = 258,
597                 .too_far        = 4096,
598         };
599
600         lz_analyze_block(ctx->window,
601                          ctx->window_size,
602                          lzms_record_match,
603                          lzms_record_literal,
604                          ctx,
605                          &lzms_lz_params,
606                          ctx->prev_tab);
607
608 }
609
610 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
611  * Unlike lzms_match_cost() which does a true cost evaluation, this simply
612  * prioritize matches based on their offset.  */
613 static input_idx_t
614 lzms_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
615 {
616         const struct lzms_lz_lru_queues *lru = _lru;
617
618
619         /* It seems well worth it to take the time to give priority to recently
620          * used offsets.  */
621         for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
622                 if (offset == lru->recent_offsets[i])
623                         return i;
624
625         return offset;
626 }
627
628 static void
629 lzms_lz_skip_bytes(struct lzms_compressor *ctx, u32 n)
630 {
631         while (n--)
632                 lz_sarray_skip_position(&ctx->lz_sarray);
633 }
634
635 static struct raw_match
636 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
637 {
638         struct raw_match matches[10];
639         u32 num_matches;
640
641         num_matches = lz_sarray_get_matches(&ctx->lz_sarray,
642                                             matches,
643                                             lzms_match_cost_fast,
644                                             &ctx->lru.lz);
645         if (num_matches == 0)
646                 return (struct raw_match) { .len = 0 };
647
648 #if 0
649         fprintf(stderr, "Pos %u/%u: %u matches\n",
650                 lz_sarray_get_pos(&ctx->lz_sarray) - 1,
651                 ctx->window_size, num_matches);
652         for (u32 i = 0; i < num_matches; i++)
653                 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
654 #endif
655
656         lzms_lz_skip_bytes(ctx, matches[0].len - 1);
657         return matches[0];
658 }
659
660 static void
661 lzms_slow_encode(struct lzms_compressor *ctx)
662 {
663         struct raw_match match;
664
665         /* Load window into suffix array match-finder.  */
666         lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
667
668         /* TODO */
669         while (ctx->cur_window_pos != ctx->window_size) {
670
671                 match = lzms_get_near_optimal_match(ctx);
672                 if (match.len == 0) {
673                         /* Literal  */
674                         lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
675                 } else {
676                         /* LZ match  */
677                         lzms_encode_lz_match(ctx, match.len, match.offset);
678                 }
679         }
680 }
681
682 static void
683 lzms_init_range_encoder(struct lzms_range_encoder *enc,
684                         struct lzms_range_encoder_raw *rc, u32 num_states)
685 {
686         enc->rc = rc;
687         enc->state = 0;
688         enc->mask = num_states - 1;
689         for (u32 i = 0; i < num_states; i++) {
690                 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
691                 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
692         }
693 }
694
695 static void
696 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
697                           struct lzms_output_bitstream *os,
698                           const u32 *slot_base_tab,
699                           unsigned num_syms,
700                           unsigned rebuild_freq)
701 {
702         enc->os = os;
703         enc->slot_base_tab = slot_base_tab;
704         enc->num_syms_written = rebuild_freq;
705         enc->rebuild_freq = rebuild_freq;
706         enc->num_syms = num_syms;
707         for (unsigned i = 0; i < num_syms; i++)
708                 enc->sym_freqs[i] = 1;
709 }
710
711 /* Initialize the LZMS compressor.  */
712 static void
713 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
714                      le16 *cdata, u32 clen16)
715 {
716         unsigned num_position_slots;
717
718         /* Copy the uncompressed data into the @ctx->window buffer.  */
719         memcpy(ctx->window, udata, ulen);
720         memset(&ctx->window[ulen], 0, 8);
721         ctx->cur_window_pos = 0;
722         ctx->window_size = ulen;
723
724         /* Initialize the raw range encoder (writing forwards).  */
725         lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
726
727         /* Initialize the output bitstream for Huffman symbols and verbatim bits
728          * (writing backwards).  */
729         lzms_output_bitstream_init(&ctx->os, cdata, clen16);
730
731         /* Initialize position and length slot bases if not done already.  */
732         lzms_init_slot_bases();
733
734         /* Calculate the number of position slots needed for this compressed
735          * block.  */
736         num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
737
738         LZMS_DEBUG("Using %u position slots", num_position_slots);
739
740         /* Initialize Huffman encoders for each alphabet used in the compressed
741          * representation.  */
742         lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
743                                   NULL, LZMS_NUM_LITERAL_SYMS,
744                                   LZMS_LITERAL_CODE_REBUILD_FREQ);
745
746         lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
747                                   lzms_position_slot_base, num_position_slots,
748                                   LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
749
750         lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
751                                   lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
752                                   LZMS_LENGTH_CODE_REBUILD_FREQ);
753
754         lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
755                                   lzms_position_slot_base, num_position_slots,
756                                   LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
757
758         lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
759                                   NULL, LZMS_NUM_DELTA_POWER_SYMS,
760                                   LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
761
762         /* Initialize range encoders, all of which wrap around the same
763          * lzms_range_encoder_raw.  */
764         lzms_init_range_encoder(&ctx->main_range_encoder,
765                                 &ctx->rc, LZMS_NUM_MAIN_STATES);
766
767         lzms_init_range_encoder(&ctx->match_range_encoder,
768                                 &ctx->rc, LZMS_NUM_MATCH_STATES);
769
770         lzms_init_range_encoder(&ctx->lz_match_range_encoder,
771                                 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
772
773         for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
774                 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
775                                         &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
776
777         lzms_init_range_encoder(&ctx->delta_match_range_encoder,
778                                 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
779
780         for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
781                 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
782                                         &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
783
784         /* Initialize LRU match information.  */
785         lzms_init_lru_queues(&ctx->lru);
786 }
787
788 /* Flush the output streams, prepare the final compressed data, and return its
789  * size in bytes.
790  *
791  * A return value of 0 indicates that the data could not be compressed to fit in
792  * the available space.  */
793 static size_t
794 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
795 {
796         size_t num_forwards_bytes;
797         size_t num_backwards_bytes;
798         size_t compressed_size;
799
800         /* Flush both the forwards and backwards streams, and make sure they
801          * didn't cross each other and start overwriting each other's data.  */
802         if (!lzms_output_bitstream_flush(&ctx->os)) {
803                 LZMS_DEBUG("Backwards bitstream overrun.");
804                 return 0;
805         }
806
807         if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
808                 LZMS_DEBUG("Forwards bitstream overrun.");
809                 return 0;
810         }
811
812         if (ctx->rc.out > ctx->os.out) {
813                 LZMS_DEBUG("Two bitstreams crossed.");
814                 return 0;
815         }
816
817         /* Now the compressed buffer contains the data output by the forwards
818          * bitstream, then empty space, then data output by the backwards
819          * bitstream.  Move the data output by the forwards bitstream to be
820          * adjacent to the data output by the backwards bitstream, and calculate
821          * the compressed size that this results in.  */
822         num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
823         num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
824
825         memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
826
827         compressed_size = num_forwards_bytes + num_backwards_bytes;
828         LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
829                    "compressed_size=%zu",
830                    num_forwards_bytes, num_backwards_bytes, compressed_size);
831         LZMS_ASSERT(!(compressed_size & 1));
832         return compressed_size;
833 }
834
835 static size_t
836 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
837               void *compressed_data, size_t compressed_size_avail, void *_ctx)
838 {
839         struct lzms_compressor *ctx = _ctx;
840         size_t compressed_size;
841
842         LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
843                    uncompressed_size, compressed_size_avail);
844
845         /* Make sure the uncompressed size is compatible with this compressor.
846          */
847         if (uncompressed_size > ctx->max_block_size) {
848                 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
849                            "only supports %u bytes",
850                            uncompressed_size, ctx->max_block_size);
851                 return 0;
852         }
853
854         /* Don't bother compressing extremely small inputs.  */
855         if (uncompressed_size < 4)
856                 return 0;
857
858         /* Cap the available compressed size to a 32-bit integer, and round it
859          * down to the nearest multiple of 2.  */
860         if (compressed_size_avail > UINT32_MAX)
861                 compressed_size_avail = UINT32_MAX;
862         if (compressed_size_avail & 1)
863                 compressed_size_avail--;
864
865         /* Initialize the compressor structures.  */
866         lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
867                              compressed_data, compressed_size_avail / 2);
868
869         /* Preprocess the uncompressed data.  */
870         lzms_x86_filter(ctx->window, ctx->window_size,
871                         ctx->last_target_usages, false);
872
873         /* Determine and output a literal/match sequence that decompresses to
874          * the preprocessed data.  */
875         if (1)
876                 lzms_slow_encode(ctx);
877         else
878                 lzms_fast_encode(ctx);
879
880         /* Get and return the compressed data size.  */
881         compressed_size = lzms_finalize(ctx, compressed_data,
882                                         compressed_size_avail);
883
884         if (compressed_size == 0) {
885                 LZMS_DEBUG("Data did not compress to requested size or less.");
886                 return 0;
887         }
888
889         LZMS_DEBUG("Compressed %zu => %zu bytes",
890                    uncompressed_size, compressed_size);
891
892 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
893         /* Verify that we really get the same thing back when decompressing.  */
894         {
895                 struct wimlib_decompressor *decompressor;
896
897                 LZMS_DEBUG("Verifying LZMS compression.");
898
899                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
900                                                     ctx->max_block_size,
901                                                     NULL,
902                                                     &decompressor))
903                 {
904                         int ret;
905                         ret = wimlib_decompress(compressed_data,
906                                                 compressed_size,
907                                                 ctx->window,
908                                                 uncompressed_size,
909                                                 decompressor);
910                         wimlib_free_decompressor(decompressor);
911
912                         if (ret) {
913                                 ERROR("Failed to decompress data we "
914                                       "compressed using LZMS algorithm");
915                                 wimlib_assert(0);
916                                 return 0;
917                         }
918                         if (memcmp(uncompressed_data, ctx->window,
919                                    uncompressed_size))
920                         {
921                                 ERROR("Data we compressed using LZMS algorithm "
922                                       "didn't decompress to original");
923                                 wimlib_assert(0);
924                                 return 0;
925                         }
926                 } else {
927                         WARNING("Failed to create decompressor for "
928                                 "data verification!");
929                 }
930         }
931 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION  */
932
933         return compressed_size;
934 }
935
936 static void
937 lzms_free_compressor(void *_ctx)
938 {
939         struct lzms_compressor *ctx = _ctx;
940
941         if (ctx) {
942                 FREE(ctx->window);
943                 FREE(ctx->prev_tab);
944                 lz_sarray_destroy(&ctx->lz_sarray);
945                 FREE(ctx);
946         }
947 }
948
949 static int
950 lzms_create_compressor(size_t max_block_size,
951                        const struct wimlib_compressor_params_header *params,
952                        void **ctx_ret)
953 {
954         struct lzms_compressor *ctx;
955
956         if (max_block_size == 0 || max_block_size >= INT32_MAX) {
957                 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
958                 return WIMLIB_ERR_INVALID_PARAM;
959         }
960
961         ctx = CALLOC(1, sizeof(struct lzms_compressor));
962         if (ctx == NULL)
963                 goto oom;
964
965         ctx->window = MALLOC(max_block_size + 8);
966         if (ctx->window == NULL)
967                 goto oom;
968
969         ctx->prev_tab = MALLOC(max_block_size * sizeof(ctx->prev_tab[0]));
970         if (ctx->prev_tab == NULL)
971                 goto oom;
972
973         if (!lz_sarray_init(&ctx->lz_sarray,
974                             max_block_size,
975                             2,
976                             max_block_size,
977                             100,
978                             10))
979                 goto oom;
980
981
982         ctx->max_block_size = max_block_size;
983
984         *ctx_ret = ctx;
985         return 0;
986
987 oom:
988         lzms_free_compressor(ctx);
989         return WIMLIB_ERR_NOMEM;
990 }
991
992 const struct compressor_ops lzms_compressor_ops = {
993         .create_compressor  = lzms_create_compressor,
994         .compress           = lzms_compress,
995         .free_compressor    = lzms_free_compressor,
996 };