]> icculus.org git repositories - icculus/xz.git/blob - src/liblzma/lz/lz_encoder.c
Put the interesting parts of XZ Utils into the public domain.
[icculus/xz.git] / src / liblzma / lz / lz_encoder.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       lz_encoder.c
4 /// \brief      LZ in window
5 ///
6 //  Authors:    Igor Pavlov
7 //              Lasse Collin
8 //
9 //  This file has been put into the public domain.
10 //  You can do whatever you want with this file.
11 //
12 ///////////////////////////////////////////////////////////////////////////////
13
14 #include "lz_encoder.h"
15 #include "lz_encoder_hash.h"
16 #include "check.h"
17
18
19 struct lzma_coder_s {
20         /// LZ-based encoder e.g. LZMA
21         lzma_lz_encoder lz;
22
23         /// History buffer and match finder
24         lzma_mf mf;
25
26         /// Next coder in the chain
27         lzma_next_coder next;
28 };
29
30
31 /// \brief      Moves the data in the input window to free space for new data
32 ///
33 /// mf->buffer is a sliding input window, which keeps mf->keep_size_before
34 /// bytes of input history available all the time. Now and then we need to
35 /// "slide" the buffer to make space for the new data to the end of the
36 /// buffer. At the same time, data older than keep_size_before is dropped.
37 ///
38 static void
39 move_window(lzma_mf *mf)
40 {
41         // Align the move to a multiple of 16 bytes. Some LZ-based encoders
42         // like LZMA use the lowest bits of mf->read_pos to know the
43         // alignment of the uncompressed data. We also get better speed
44         // for memmove() with aligned buffers.
45         assert(mf->read_pos > mf->keep_size_before);
46         const uint32_t move_offset
47                 = (mf->read_pos - mf->keep_size_before) & ~UINT32_C(15);
48
49         assert(mf->write_pos > move_offset);
50         const size_t move_size = mf->write_pos - move_offset;
51
52         assert(move_offset + move_size <= mf->size);
53
54         memmove(mf->buffer, mf->buffer + move_offset, move_size);
55
56         mf->offset += move_offset;
57         mf->read_pos -= move_offset;
58         mf->read_limit -= move_offset;
59         mf->write_pos -= move_offset;
60
61         return;
62 }
63
64
65 /// \brief      Tries to fill the input window (mf->buffer)
66 ///
67 /// If we are the last encoder in the chain, our input data is in in[].
68 /// Otherwise we call the next filter in the chain to process in[] and
69 /// write its output to mf->buffer.
70 ///
71 /// This function must not be called once it has returned LZMA_STREAM_END.
72 ///
73 static lzma_ret
74 fill_window(lzma_coder *coder, lzma_allocator *allocator, const uint8_t *in,
75                 size_t *in_pos, size_t in_size, lzma_action action)
76 {
77         assert(coder->mf.read_pos <= coder->mf.write_pos);
78
79         // Move the sliding window if needed.
80         if (coder->mf.read_pos >= coder->mf.size - coder->mf.keep_size_after)
81                 move_window(&coder->mf);
82
83         // Maybe this is ugly, but lzma_mf uses uint32_t for most things
84         // (which I find cleanest), but we need size_t here when filling
85         // the history window.
86         size_t write_pos = coder->mf.write_pos;
87         size_t in_used;
88         lzma_ret ret;
89         if (coder->next.code == NULL) {
90                 // Not using a filter, simply memcpy() as much as possible.
91                 in_used = lzma_bufcpy(in, in_pos, in_size, coder->mf.buffer,
92                                 &write_pos, coder->mf.size);
93
94                 ret = action != LZMA_RUN && *in_pos == in_size
95                                 ? LZMA_STREAM_END : LZMA_OK;
96
97         } else {
98                 const size_t in_start = *in_pos;
99                 ret = coder->next.code(coder->next.coder, allocator,
100                                 in, in_pos, in_size,
101                                 coder->mf.buffer, &write_pos,
102                                 coder->mf.size, action);
103                 in_used = *in_pos - in_start;
104         }
105
106         coder->mf.write_pos = write_pos;
107
108         // If end of stream has been reached or flushing completed, we allow
109         // the encoder to process all the input (that is, read_pos is allowed
110         // to reach write_pos). Otherwise we keep keep_size_after bytes
111         // available as prebuffer.
112         if (ret == LZMA_STREAM_END) {
113                 assert(*in_pos == in_size);
114                 ret = LZMA_OK;
115                 coder->mf.action = action;
116                 coder->mf.read_limit = coder->mf.write_pos;
117
118         } else if (coder->mf.write_pos > coder->mf.keep_size_after) {
119                 // This needs to be done conditionally, because if we got
120                 // only little new input, there may be too little input
121                 // to do any encoding yet.
122                 coder->mf.read_limit = coder->mf.write_pos
123                                 - coder->mf.keep_size_after;
124         }
125
126         // Restart the match finder after finished LZMA_SYNC_FLUSH.
127         if (coder->mf.pending > 0
128                         && coder->mf.read_pos < coder->mf.read_limit) {
129                 // Match finder may update coder->pending and expects it to
130                 // start from zero, so use a temporary variable.
131                 const size_t pending = coder->mf.pending;
132                 coder->mf.pending = 0;
133
134                 // Rewind read_pos so that the match finder can hash
135                 // the pending bytes.
136                 assert(coder->mf.read_pos >= pending);
137                 coder->mf.read_pos -= pending;
138
139                 // Call the skip function directly instead of using
140                 // mf_skip(), since we don't want to touch mf->read_ahead.
141                 coder->mf.skip(&coder->mf, pending);
142         }
143
144         return ret;
145 }
146
147
148 static lzma_ret
149 lz_encode(lzma_coder *coder, lzma_allocator *allocator,
150                 const uint8_t *restrict in, size_t *restrict in_pos,
151                 size_t in_size,
152                 uint8_t *restrict out, size_t *restrict out_pos,
153                 size_t out_size, lzma_action action)
154 {
155         while (*out_pos < out_size
156                         && (*in_pos < in_size || action != LZMA_RUN)) {
157                 // Read more data to coder->mf.buffer if needed.
158                 if (coder->mf.action == LZMA_RUN && coder->mf.read_pos
159                                 >= coder->mf.read_limit)
160                         return_if_error(fill_window(coder, allocator,
161                                         in, in_pos, in_size, action));
162
163                 // Encode
164                 const lzma_ret ret = coder->lz.code(coder->lz.coder,
165                                 &coder->mf, out, out_pos, out_size);
166                 if (ret != LZMA_OK) {
167                         // Setting this to LZMA_RUN for cases when we are
168                         // flushing. It doesn't matter when finishing or if
169                         // an error occurred.
170                         coder->mf.action = LZMA_RUN;
171                         return ret;
172                 }
173         }
174
175         return LZMA_OK;
176 }
177
178
179 static bool
180 lz_encoder_prepare(lzma_mf *mf, lzma_allocator *allocator,
181                 const lzma_lz_options *lz_options)
182 {
183         // For now, the dictionary size is limited to 1.5 GiB. This may grow
184         // in the future if needed, but it needs a little more work than just
185         // changing this check.
186         if (lz_options->dict_size < LZMA_DICT_SIZE_MIN
187                         || lz_options->dict_size
188                                 > (UINT32_C(1) << 30) + (UINT32_C(1) << 29)
189                         || lz_options->nice_len > lz_options->match_len_max)
190                 return true;
191
192         mf->keep_size_before = lz_options->before_size + lz_options->dict_size;
193
194         mf->keep_size_after = lz_options->after_size
195                         + lz_options->match_len_max;
196
197         // To avoid constant memmove()s, allocate some extra space. Since
198         // memmove()s become more expensive when the size of the buffer
199         // increases, we reserve more space when a large dictionary is
200         // used to make the memmove() calls rarer.
201         //
202         // This works with dictionaries up to about 3 GiB. If bigger
203         // dictionary is wanted, some extra work is needed:
204         //   - Several variables in lzma_mf have to be changed from uint32_t
205         //     to size_t.
206         //   - Memory usage calculation needs something too, e.g. use uint64_t
207         //     for mf->size.
208         uint32_t reserve = lz_options->dict_size / 2;
209         if (reserve > (UINT32_C(1) << 30))
210                 reserve /= 2;
211
212         reserve += (lz_options->before_size + lz_options->match_len_max
213                         + lz_options->after_size) / 2 + (UINT32_C(1) << 19);
214
215         const uint32_t old_size = mf->size;
216         mf->size = mf->keep_size_before + reserve + mf->keep_size_after;
217
218         // Deallocate the old history buffer if it exists but has different
219         // size than what is needed now.
220         if (mf->buffer != NULL && old_size != mf->size) {
221                 lzma_free(mf->buffer, allocator);
222                 mf->buffer = NULL;
223         }
224
225         // Match finder options
226         mf->match_len_max = lz_options->match_len_max;
227         mf->nice_len = lz_options->nice_len;
228
229         // cyclic_size has to stay smaller than 2 Gi. Note that this doesn't
230         // mean limitting dictionary size to less than 2 GiB. With a match
231         // finder that uses multibyte resolution (hashes start at e.g. every
232         // fourth byte), cyclic_size would stay below 2 Gi even when
233         // dictionary size is greater than 2 GiB.
234         //
235         // It would be possible to allow cyclic_size >= 2 Gi, but then we
236         // would need to be careful to use 64-bit types in various places
237         // (size_t could do since we would need bigger than 32-bit address
238         // space anyway). It would also require either zeroing a multigigabyte
239         // buffer at initialization (waste of time and RAM) or allow
240         // normalization in lz_encoder_mf.c to access uninitialized
241         // memory to keep the code simpler. The current way is simple and
242         // still allows pretty big dictionaries, so I don't expect these
243         // limits to change.
244         mf->cyclic_size = lz_options->dict_size + 1;
245
246         // Validate the match finder ID and setup the function pointers.
247         switch (lz_options->match_finder) {
248 #ifdef HAVE_MF_HC3
249         case LZMA_MF_HC3:
250                 mf->find = &lzma_mf_hc3_find;
251                 mf->skip = &lzma_mf_hc3_skip;
252                 break;
253 #endif
254 #ifdef HAVE_MF_HC4
255         case LZMA_MF_HC4:
256                 mf->find = &lzma_mf_hc4_find;
257                 mf->skip = &lzma_mf_hc4_skip;
258                 break;
259 #endif
260 #ifdef HAVE_MF_BT2
261         case LZMA_MF_BT2:
262                 mf->find = &lzma_mf_bt2_find;
263                 mf->skip = &lzma_mf_bt2_skip;
264                 break;
265 #endif
266 #ifdef HAVE_MF_BT3
267         case LZMA_MF_BT3:
268                 mf->find = &lzma_mf_bt3_find;
269                 mf->skip = &lzma_mf_bt3_skip;
270                 break;
271 #endif
272 #ifdef HAVE_MF_BT4
273         case LZMA_MF_BT4:
274                 mf->find = &lzma_mf_bt4_find;
275                 mf->skip = &lzma_mf_bt4_skip;
276                 break;
277 #endif
278
279         default:
280                 return true;
281         }
282
283         // Calculate the sizes of mf->hash and mf->son and check that
284         // nice_len is big enough for the selected match finder.
285         const uint32_t hash_bytes = lz_options->match_finder & 0x0F;
286         if (hash_bytes > mf->nice_len)
287                 return true;
288
289         const bool is_bt = (lz_options->match_finder & 0x10) != 0;
290         uint32_t hs;
291
292         if (hash_bytes == 2) {
293                 hs = 0xFFFF;
294         } else {
295                 // Round dictionary size up to the next 2^n - 1 so it can
296                 // be used as a hash mask.
297                 hs = lz_options->dict_size - 1;
298                 hs |= hs >> 1;
299                 hs |= hs >> 2;
300                 hs |= hs >> 4;
301                 hs |= hs >> 8;
302                 hs >>= 1;
303                 hs |= 0xFFFF;
304
305                 if (hs > (UINT32_C(1) << 24)) {
306                         if (hash_bytes == 3)
307                                 hs = (UINT32_C(1) << 24) - 1;
308                         else
309                                 hs >>= 1;
310                 }
311         }
312
313         mf->hash_mask = hs;
314
315         ++hs;
316         if (hash_bytes > 2)
317                 hs += HASH_2_SIZE;
318         if (hash_bytes > 3)
319                 hs += HASH_3_SIZE;
320 /*
321         No match finder uses this at the moment.
322         if (mf->hash_bytes > 4)
323                 hs += HASH_4_SIZE;
324 */
325
326         // If the above code calculating hs is modified, make sure that
327         // this assertion stays valid (UINT32_MAX / 5 is not strictly the
328         // exact limit). If it doesn't, you need to calculate that
329         // hash_size_sum + sons_count cannot overflow.
330         assert(hs < UINT32_MAX / 5);
331
332         const uint32_t old_count = mf->hash_size_sum + mf->sons_count;
333         mf->hash_size_sum = hs;
334         mf->sons_count = mf->cyclic_size;
335         if (is_bt)
336                 mf->sons_count *= 2;
337
338         const uint32_t new_count = mf->hash_size_sum + mf->sons_count;
339
340         // Deallocate the old hash array if it exists and has different size
341         // than what is needed now.
342         if (mf->hash != NULL && old_count != new_count) {
343                 lzma_free(mf->hash, allocator);
344                 mf->hash = NULL;
345         }
346
347         // Maximum number of match finder cycles
348         mf->depth = lz_options->depth;
349         if (mf->depth == 0) {
350                 mf->depth = 16 + (mf->nice_len / 2);
351                 if (!is_bt)
352                         mf->depth /= 2;
353         }
354
355         return false;
356 }
357
358
359 static bool
360 lz_encoder_init(lzma_mf *mf, lzma_allocator *allocator,
361                 const lzma_lz_options *lz_options)
362 {
363         // Allocate the history buffer.
364         if (mf->buffer == NULL) {
365                 mf->buffer = lzma_alloc(mf->size, allocator);
366                 if (mf->buffer == NULL)
367                         return true;
368         }
369
370         // Use cyclic_size as initial mf->offset. This allows
371         // avoiding a few branches in the match finders. The downside is
372         // that match finder needs to be normalized more often, which may
373         // hurt performance with huge dictionaries.
374         mf->offset = mf->cyclic_size;
375         mf->read_pos = 0;
376         mf->read_ahead = 0;
377         mf->read_limit = 0;
378         mf->write_pos = 0;
379         mf->pending = 0;
380
381         // Allocate match finder's hash array.
382         const size_t alloc_count = mf->hash_size_sum + mf->sons_count;
383
384 #if UINT32_MAX >= SIZE_MAX / 4
385         // Check for integer overflow. (Huge dictionaries are not
386         // possible on 32-bit CPU.)
387         if (alloc_count > SIZE_MAX / sizeof(uint32_t))
388                 return true;
389 #endif
390
391         if (mf->hash == NULL) {
392                 mf->hash = lzma_alloc(alloc_count * sizeof(uint32_t),
393                                 allocator);
394                 if (mf->hash == NULL)
395                         return true;
396         }
397
398         mf->son = mf->hash + mf->hash_size_sum;
399         mf->cyclic_pos = 0;
400
401         // Initialize the hash table. Since EMPTY_HASH_VALUE is zero, we
402         // can use memset().
403 /*
404         for (uint32_t i = 0; i < hash_size_sum; ++i)
405                 mf->hash[i] = EMPTY_HASH_VALUE;
406 */
407         memzero(mf->hash, (size_t)(mf->hash_size_sum) * sizeof(uint32_t));
408
409         // We don't need to initialize mf->son, but not doing that will
410         // make Valgrind complain in normalization (see normalize() in
411         // lz_encoder_mf.c).
412         //
413         // Skipping this initialization is *very* good when big dictionary is
414         // used but only small amount of data gets actually compressed: most
415         // of the mf->hash won't get actually allocated by the kernel, so
416         // we avoid wasting RAM and improve initialization speed a lot.
417         //memzero(mf->son, (size_t)(mf->sons_count) * sizeof(uint32_t));
418
419         // Handle preset dictionary.
420         if (lz_options->preset_dict != NULL
421                         && lz_options->preset_dict_size > 0) {
422                 // If the preset dictionary is bigger than the actual
423                 // dictionary, use only the tail.
424                 mf->write_pos = MIN(lz_options->preset_dict_size, mf->size);
425                 memcpy(mf->buffer, lz_options->preset_dict
426                                 + lz_options->preset_dict_size - mf->write_pos,
427                                 mf->write_pos);
428                 mf->action = LZMA_SYNC_FLUSH;
429                 mf->skip(mf, mf->write_pos);
430         }
431
432         mf->action = LZMA_RUN;
433
434         return false;
435 }
436
437
438 extern uint64_t
439 lzma_lz_encoder_memusage(const lzma_lz_options *lz_options)
440 {
441         // Old buffers must not exist when calling lz_encoder_prepare().
442         lzma_mf mf = {
443                 .buffer = NULL,
444                 .hash = NULL,
445         };
446
447         // Setup the size information into mf.
448         if (lz_encoder_prepare(&mf, NULL, lz_options))
449                 return UINT64_MAX;
450
451         // Calculate the memory usage.
452         return (uint64_t)(mf.hash_size_sum + mf.sons_count)
453                                 * sizeof(uint32_t)
454                         + (uint64_t)(mf.size) + sizeof(lzma_coder);
455 }
456
457
458 static void
459 lz_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
460 {
461         lzma_next_end(&coder->next, allocator);
462
463         lzma_free(coder->mf.hash, allocator);
464         lzma_free(coder->mf.buffer, allocator);
465
466         if (coder->lz.end != NULL)
467                 coder->lz.end(coder->lz.coder, allocator);
468         else
469                 lzma_free(coder->lz.coder, allocator);
470
471         lzma_free(coder, allocator);
472         return;
473 }
474
475
476 extern lzma_ret
477 lzma_lz_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
478                 const lzma_filter_info *filters,
479                 lzma_ret (*lz_init)(lzma_lz_encoder *lz,
480                         lzma_allocator *allocator, const void *options,
481                         lzma_lz_options *lz_options))
482 {
483 #ifdef HAVE_SMALL
484         // We need that the CRC32 table has been initialized.
485         lzma_crc32_init();
486 #endif
487
488         // Allocate and initialize the base data structure.
489         if (next->coder == NULL) {
490                 next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
491                 if (next->coder == NULL)
492                         return LZMA_MEM_ERROR;
493
494                 next->code = &lz_encode;
495                 next->end = &lz_encoder_end;
496
497                 next->coder->lz.coder = NULL;
498                 next->coder->lz.code = NULL;
499                 next->coder->lz.end = NULL;
500
501                 next->coder->mf.buffer = NULL;
502                 next->coder->mf.hash = NULL;
503
504                 next->coder->next = LZMA_NEXT_CODER_INIT;
505         }
506
507         // Initialize the LZ-based encoder.
508         lzma_lz_options lz_options;
509         return_if_error(lz_init(&next->coder->lz, allocator,
510                         filters[0].options, &lz_options));
511
512         // Setup the size information into next->coder->mf and deallocate
513         // old buffers if they have wrong size.
514         if (lz_encoder_prepare(&next->coder->mf, allocator, &lz_options))
515                 return LZMA_OPTIONS_ERROR;
516
517         // Allocate new buffers if needed, and do the rest of
518         // the initialization.
519         if (lz_encoder_init(&next->coder->mf, allocator, &lz_options))
520                 return LZMA_MEM_ERROR;
521
522         // Initialize the next filter in the chain, if any.
523         return lzma_next_filter_init(&next->coder->next, allocator,
524                         filters + 1);
525 }
526
527
528 extern LZMA_API(lzma_bool)
529 lzma_mf_is_supported(lzma_match_finder mf)
530 {
531         bool ret = false;
532
533 #ifdef HAVE_MF_HC3
534         if (mf == LZMA_MF_HC3)
535                 ret = true;
536 #endif
537
538 #ifdef HAVE_MF_HC4
539         if (mf == LZMA_MF_HC4)
540                 ret = true;
541 #endif
542
543 #ifdef HAVE_MF_BT2
544         if (mf == LZMA_MF_BT2)
545                 ret = true;
546 #endif
547
548 #ifdef HAVE_MF_BT3
549         if (mf == LZMA_MF_BT3)
550                 ret = true;
551 #endif
552
553 #ifdef HAVE_MF_BT4
554         if (mf == LZMA_MF_BT4)
555                 ret = true;
556 #endif
557
558         return ret;
559 }