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