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