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