1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief LZ in window
6 // Authors: Igor Pavlov
9 // This file has been put into the public domain.
10 // You can do whatever you want with this file.
12 ///////////////////////////////////////////////////////////////////////////////
14 #include "lz_encoder.h"
15 #include "lz_encoder_hash.h"
20 /// LZ-based encoder e.g. LZMA
23 /// History buffer and match finder
26 /// Next coder in the chain
31 /// \brief Moves the data in the input window to free space for new data
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.
39 move_window(lzma_mf *mf)
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);
49 assert(mf->write_pos > move_offset);
50 const size_t move_size = mf->write_pos - move_offset;
52 assert(move_offset + move_size <= mf->size);
54 memmove(mf->buffer, mf->buffer + move_offset, move_size);
56 mf->offset += move_offset;
57 mf->read_pos -= move_offset;
58 mf->read_limit -= move_offset;
59 mf->write_pos -= move_offset;
65 /// \brief Tries to fill the input window (mf->buffer)
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.
71 /// This function must not be called once it has returned LZMA_STREAM_END.
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)
77 assert(coder->mf.read_pos <= coder->mf.write_pos);
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);
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;
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);
94 ret = action != LZMA_RUN && *in_pos == in_size
95 ? LZMA_STREAM_END : LZMA_OK;
98 const size_t in_start = *in_pos;
99 ret = coder->next.code(coder->next.coder, allocator,
101 coder->mf.buffer, &write_pos,
102 coder->mf.size, action);
103 in_used = *in_pos - in_start;
106 coder->mf.write_pos = write_pos;
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);
115 coder->mf.action = action;
116 coder->mf.read_limit = coder->mf.write_pos;
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;
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;
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;
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);
149 lz_encode(lzma_coder *coder, lzma_allocator *allocator,
150 const uint8_t *restrict in, size_t *restrict in_pos,
152 uint8_t *restrict out, size_t *restrict out_pos,
153 size_t out_size, lzma_action action)
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));
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;
180 lz_encoder_prepare(lzma_mf *mf, lzma_allocator *allocator,
181 const lzma_lz_options *lz_options)
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)
192 mf->keep_size_before = lz_options->before_size + lz_options->dict_size;
194 mf->keep_size_after = lz_options->after_size
195 + lz_options->match_len_max;
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.
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
206 // - Memory usage calculation needs something too, e.g. use uint64_t
208 uint32_t reserve = lz_options->dict_size / 2;
209 if (reserve > (UINT32_C(1) << 30))
212 reserve += (lz_options->before_size + lz_options->match_len_max
213 + lz_options->after_size) / 2 + (UINT32_C(1) << 19);
215 const uint32_t old_size = mf->size;
216 mf->size = mf->keep_size_before + reserve + mf->keep_size_after;
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);
225 // Match finder options
226 mf->match_len_max = lz_options->match_len_max;
227 mf->nice_len = lz_options->nice_len;
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.
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
244 mf->cyclic_size = lz_options->dict_size + 1;
246 // Validate the match finder ID and setup the function pointers.
247 switch (lz_options->match_finder) {
250 mf->find = &lzma_mf_hc3_find;
251 mf->skip = &lzma_mf_hc3_skip;
256 mf->find = &lzma_mf_hc4_find;
257 mf->skip = &lzma_mf_hc4_skip;
262 mf->find = &lzma_mf_bt2_find;
263 mf->skip = &lzma_mf_bt2_skip;
268 mf->find = &lzma_mf_bt3_find;
269 mf->skip = &lzma_mf_bt3_skip;
274 mf->find = &lzma_mf_bt4_find;
275 mf->skip = &lzma_mf_bt4_skip;
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)
289 const bool is_bt = (lz_options->match_finder & 0x10) != 0;
292 if (hash_bytes == 2) {
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;
305 if (hs > (UINT32_C(1) << 24)) {
307 hs = (UINT32_C(1) << 24) - 1;
321 No match finder uses this at the moment.
322 if (mf->hash_bytes > 4)
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);
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;
338 const uint32_t new_count = mf->hash_size_sum + mf->sons_count;
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);
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);
360 lz_encoder_init(lzma_mf *mf, lzma_allocator *allocator,
361 const lzma_lz_options *lz_options)
363 // Allocate the history buffer.
364 if (mf->buffer == NULL) {
365 mf->buffer = lzma_alloc(mf->size, allocator);
366 if (mf->buffer == NULL)
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;
381 // Allocate match finder's hash array.
382 const size_t alloc_count = mf->hash_size_sum + mf->sons_count;
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))
391 if (mf->hash == NULL) {
392 mf->hash = lzma_alloc(alloc_count * sizeof(uint32_t),
394 if (mf->hash == NULL)
398 mf->son = mf->hash + mf->hash_size_sum;
401 // Initialize the hash table. Since EMPTY_HASH_VALUE is zero, we
404 for (uint32_t i = 0; i < hash_size_sum; ++i)
405 mf->hash[i] = EMPTY_HASH_VALUE;
407 memzero(mf->hash, (size_t)(mf->hash_size_sum) * sizeof(uint32_t));
409 // We don't need to initialize mf->son, but not doing that will
410 // make Valgrind complain in normalization (see normalize() in
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));
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,
428 mf->action = LZMA_SYNC_FLUSH;
429 mf->skip(mf, mf->write_pos);
432 mf->action = LZMA_RUN;
439 lzma_lz_encoder_memusage(const lzma_lz_options *lz_options)
441 // Old buffers must not exist when calling lz_encoder_prepare().
447 // Setup the size information into mf.
448 if (lz_encoder_prepare(&mf, NULL, lz_options))
451 // Calculate the memory usage.
452 return (uint64_t)(mf.hash_size_sum + mf.sons_count)
454 + (uint64_t)(mf.size) + sizeof(lzma_coder);
459 lz_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
461 lzma_next_end(&coder->next, allocator);
463 lzma_free(coder->mf.hash, allocator);
464 lzma_free(coder->mf.buffer, allocator);
466 if (coder->lz.end != NULL)
467 coder->lz.end(coder->lz.coder, allocator);
469 lzma_free(coder->lz.coder, allocator);
471 lzma_free(coder, allocator);
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))
484 // We need that the CRC32 table has been initialized.
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;
494 next->code = &lz_encode;
495 next->end = &lz_encoder_end;
497 next->coder->lz.coder = NULL;
498 next->coder->lz.code = NULL;
499 next->coder->lz.end = NULL;
501 next->coder->mf.buffer = NULL;
502 next->coder->mf.hash = NULL;
504 next->coder->next = LZMA_NEXT_CODER_INIT;
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));
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;
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;
522 // Initialize the next filter in the chain, if any.
523 return lzma_next_filter_init(&next->coder->next, allocator,
528 extern LZMA_API(lzma_bool)
529 lzma_mf_is_supported(lzma_match_finder mf)
534 if (mf == LZMA_MF_HC3)
539 if (mf == LZMA_MF_HC4)
544 if (mf == LZMA_MF_BT2)
549 if (mf == LZMA_MF_BT3)
554 if (mf == LZMA_MF_BT4)