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