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;
88 if (coder->next.code == NULL) {
89 // Not using a filter, simply memcpy() as much as possible.
90 lzma_bufcpy(in, in_pos, in_size, coder->mf.buffer,
91 &write_pos, coder->mf.size);
93 ret = action != LZMA_RUN && *in_pos == in_size
94 ? LZMA_STREAM_END : LZMA_OK;
97 ret = coder->next.code(coder->next.coder, allocator,
99 coder->mf.buffer, &write_pos,
100 coder->mf.size, action);
103 coder->mf.write_pos = write_pos;
105 // If end of stream has been reached or flushing completed, we allow
106 // the encoder to process all the input (that is, read_pos is allowed
107 // to reach write_pos). Otherwise we keep keep_size_after bytes
108 // available as prebuffer.
109 if (ret == LZMA_STREAM_END) {
110 assert(*in_pos == in_size);
112 coder->mf.action = action;
113 coder->mf.read_limit = coder->mf.write_pos;
115 } else if (coder->mf.write_pos > coder->mf.keep_size_after) {
116 // This needs to be done conditionally, because if we got
117 // only little new input, there may be too little input
118 // to do any encoding yet.
119 coder->mf.read_limit = coder->mf.write_pos
120 - coder->mf.keep_size_after;
123 // Restart the match finder after finished LZMA_SYNC_FLUSH.
124 if (coder->mf.pending > 0
125 && coder->mf.read_pos < coder->mf.read_limit) {
126 // Match finder may update coder->pending and expects it to
127 // start from zero, so use a temporary variable.
128 const size_t pending = coder->mf.pending;
129 coder->mf.pending = 0;
131 // Rewind read_pos so that the match finder can hash
132 // the pending bytes.
133 assert(coder->mf.read_pos >= pending);
134 coder->mf.read_pos -= pending;
136 // Call the skip function directly instead of using
137 // mf_skip(), since we don't want to touch mf->read_ahead.
138 coder->mf.skip(&coder->mf, pending);
146 lz_encode(lzma_coder *coder, lzma_allocator *allocator,
147 const uint8_t *restrict in, size_t *restrict in_pos,
149 uint8_t *restrict out, size_t *restrict out_pos,
150 size_t out_size, lzma_action action)
152 while (*out_pos < out_size
153 && (*in_pos < in_size || action != LZMA_RUN)) {
154 // Read more data to coder->mf.buffer if needed.
155 if (coder->mf.action == LZMA_RUN && coder->mf.read_pos
156 >= coder->mf.read_limit)
157 return_if_error(fill_window(coder, allocator,
158 in, in_pos, in_size, action));
161 const lzma_ret ret = coder->lz.code(coder->lz.coder,
162 &coder->mf, out, out_pos, out_size);
163 if (ret != LZMA_OK) {
164 // Setting this to LZMA_RUN for cases when we are
165 // flushing. It doesn't matter when finishing or if
166 // an error occurred.
167 coder->mf.action = LZMA_RUN;
177 lz_encoder_prepare(lzma_mf *mf, lzma_allocator *allocator,
178 const lzma_lz_options *lz_options)
180 // For now, the dictionary size is limited to 1.5 GiB. This may grow
181 // in the future if needed, but it needs a little more work than just
182 // changing this check.
183 if (lz_options->dict_size < LZMA_DICT_SIZE_MIN
184 || lz_options->dict_size
185 > (UINT32_C(1) << 30) + (UINT32_C(1) << 29)
186 || lz_options->nice_len > lz_options->match_len_max)
189 mf->keep_size_before = lz_options->before_size + lz_options->dict_size;
191 mf->keep_size_after = lz_options->after_size
192 + lz_options->match_len_max;
194 // To avoid constant memmove()s, allocate some extra space. Since
195 // memmove()s become more expensive when the size of the buffer
196 // increases, we reserve more space when a large dictionary is
197 // used to make the memmove() calls rarer.
199 // This works with dictionaries up to about 3 GiB. If bigger
200 // dictionary is wanted, some extra work is needed:
201 // - Several variables in lzma_mf have to be changed from uint32_t
203 // - Memory usage calculation needs something too, e.g. use uint64_t
205 uint32_t reserve = lz_options->dict_size / 2;
206 if (reserve > (UINT32_C(1) << 30))
209 reserve += (lz_options->before_size + lz_options->match_len_max
210 + lz_options->after_size) / 2 + (UINT32_C(1) << 19);
212 const uint32_t old_size = mf->size;
213 mf->size = mf->keep_size_before + reserve + mf->keep_size_after;
215 // Deallocate the old history buffer if it exists but has different
216 // size than what is needed now.
217 if (mf->buffer != NULL && old_size != mf->size) {
218 lzma_free(mf->buffer, allocator);
222 // Match finder options
223 mf->match_len_max = lz_options->match_len_max;
224 mf->nice_len = lz_options->nice_len;
226 // cyclic_size has to stay smaller than 2 Gi. Note that this doesn't
227 // mean limitting dictionary size to less than 2 GiB. With a match
228 // finder that uses multibyte resolution (hashes start at e.g. every
229 // fourth byte), cyclic_size would stay below 2 Gi even when
230 // dictionary size is greater than 2 GiB.
232 // It would be possible to allow cyclic_size >= 2 Gi, but then we
233 // would need to be careful to use 64-bit types in various places
234 // (size_t could do since we would need bigger than 32-bit address
235 // space anyway). It would also require either zeroing a multigigabyte
236 // buffer at initialization (waste of time and RAM) or allow
237 // normalization in lz_encoder_mf.c to access uninitialized
238 // memory to keep the code simpler. The current way is simple and
239 // still allows pretty big dictionaries, so I don't expect these
241 mf->cyclic_size = lz_options->dict_size + 1;
243 // Validate the match finder ID and setup the function pointers.
244 switch (lz_options->match_finder) {
247 mf->find = &lzma_mf_hc3_find;
248 mf->skip = &lzma_mf_hc3_skip;
253 mf->find = &lzma_mf_hc4_find;
254 mf->skip = &lzma_mf_hc4_skip;
259 mf->find = &lzma_mf_bt2_find;
260 mf->skip = &lzma_mf_bt2_skip;
265 mf->find = &lzma_mf_bt3_find;
266 mf->skip = &lzma_mf_bt3_skip;
271 mf->find = &lzma_mf_bt4_find;
272 mf->skip = &lzma_mf_bt4_skip;
280 // Calculate the sizes of mf->hash and mf->son and check that
281 // nice_len is big enough for the selected match finder.
282 const uint32_t hash_bytes = lz_options->match_finder & 0x0F;
283 if (hash_bytes > mf->nice_len)
286 const bool is_bt = (lz_options->match_finder & 0x10) != 0;
289 if (hash_bytes == 2) {
292 // Round dictionary size up to the next 2^n - 1 so it can
293 // be used as a hash mask.
294 hs = lz_options->dict_size - 1;
302 if (hs > (UINT32_C(1) << 24)) {
304 hs = (UINT32_C(1) << 24) - 1;
318 No match finder uses this at the moment.
319 if (mf->hash_bytes > 4)
323 // If the above code calculating hs is modified, make sure that
324 // this assertion stays valid (UINT32_MAX / 5 is not strictly the
325 // exact limit). If it doesn't, you need to calculate that
326 // hash_size_sum + sons_count cannot overflow.
327 assert(hs < UINT32_MAX / 5);
329 const uint32_t old_count = mf->hash_size_sum + mf->sons_count;
330 mf->hash_size_sum = hs;
331 mf->sons_count = mf->cyclic_size;
335 const uint32_t new_count = mf->hash_size_sum + mf->sons_count;
337 // Deallocate the old hash array if it exists and has different size
338 // than what is needed now.
339 if (mf->hash != NULL && old_count != new_count) {
340 lzma_free(mf->hash, allocator);
344 // Maximum number of match finder cycles
345 mf->depth = lz_options->depth;
346 if (mf->depth == 0) {
347 mf->depth = 16 + (mf->nice_len / 2);
357 lz_encoder_init(lzma_mf *mf, lzma_allocator *allocator,
358 const lzma_lz_options *lz_options)
360 // Allocate the history buffer.
361 if (mf->buffer == NULL) {
362 mf->buffer = lzma_alloc(mf->size, allocator);
363 if (mf->buffer == NULL)
367 // Use cyclic_size as initial mf->offset. This allows
368 // avoiding a few branches in the match finders. The downside is
369 // that match finder needs to be normalized more often, which may
370 // hurt performance with huge dictionaries.
371 mf->offset = mf->cyclic_size;
378 // Allocate match finder's hash array.
379 const size_t alloc_count = mf->hash_size_sum + mf->sons_count;
381 #if UINT32_MAX >= SIZE_MAX / 4
382 // Check for integer overflow. (Huge dictionaries are not
383 // possible on 32-bit CPU.)
384 if (alloc_count > SIZE_MAX / sizeof(uint32_t))
388 if (mf->hash == NULL) {
389 mf->hash = lzma_alloc(alloc_count * sizeof(uint32_t),
391 if (mf->hash == NULL)
395 mf->son = mf->hash + mf->hash_size_sum;
398 // Initialize the hash table. Since EMPTY_HASH_VALUE is zero, we
401 for (uint32_t i = 0; i < hash_size_sum; ++i)
402 mf->hash[i] = EMPTY_HASH_VALUE;
404 memzero(mf->hash, (size_t)(mf->hash_size_sum) * sizeof(uint32_t));
406 // We don't need to initialize mf->son, but not doing that will
407 // make Valgrind complain in normalization (see normalize() in
410 // Skipping this initialization is *very* good when big dictionary is
411 // used but only small amount of data gets actually compressed: most
412 // of the mf->hash won't get actually allocated by the kernel, so
413 // we avoid wasting RAM and improve initialization speed a lot.
414 //memzero(mf->son, (size_t)(mf->sons_count) * sizeof(uint32_t));
416 // Handle preset dictionary.
417 if (lz_options->preset_dict != NULL
418 && lz_options->preset_dict_size > 0) {
419 // If the preset dictionary is bigger than the actual
420 // dictionary, use only the tail.
421 mf->write_pos = MIN(lz_options->preset_dict_size, mf->size);
422 memcpy(mf->buffer, lz_options->preset_dict
423 + lz_options->preset_dict_size - mf->write_pos,
425 mf->action = LZMA_SYNC_FLUSH;
426 mf->skip(mf, mf->write_pos);
429 mf->action = LZMA_RUN;
436 lzma_lz_encoder_memusage(const lzma_lz_options *lz_options)
438 // Old buffers must not exist when calling lz_encoder_prepare().
444 // Setup the size information into mf.
445 if (lz_encoder_prepare(&mf, NULL, lz_options))
448 // Calculate the memory usage.
449 return (uint64_t)(mf.hash_size_sum + mf.sons_count)
451 + (uint64_t)(mf.size) + sizeof(lzma_coder);
456 lz_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
458 lzma_next_end(&coder->next, allocator);
460 lzma_free(coder->mf.hash, allocator);
461 lzma_free(coder->mf.buffer, allocator);
463 if (coder->lz.end != NULL)
464 coder->lz.end(coder->lz.coder, allocator);
466 lzma_free(coder->lz.coder, allocator);
468 lzma_free(coder, allocator);
474 lzma_lz_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
475 const lzma_filter_info *filters,
476 lzma_ret (*lz_init)(lzma_lz_encoder *lz,
477 lzma_allocator *allocator, const void *options,
478 lzma_lz_options *lz_options))
481 // We need that the CRC32 table has been initialized.
485 // Allocate and initialize the base data structure.
486 if (next->coder == NULL) {
487 next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
488 if (next->coder == NULL)
489 return LZMA_MEM_ERROR;
491 next->code = &lz_encode;
492 next->end = &lz_encoder_end;
494 next->coder->lz.coder = NULL;
495 next->coder->lz.code = NULL;
496 next->coder->lz.end = NULL;
498 next->coder->mf.buffer = NULL;
499 next->coder->mf.hash = NULL;
501 next->coder->next = LZMA_NEXT_CODER_INIT;
504 // Initialize the LZ-based encoder.
505 lzma_lz_options lz_options;
506 return_if_error(lz_init(&next->coder->lz, allocator,
507 filters[0].options, &lz_options));
509 // Setup the size information into next->coder->mf and deallocate
510 // old buffers if they have wrong size.
511 if (lz_encoder_prepare(&next->coder->mf, allocator, &lz_options))
512 return LZMA_OPTIONS_ERROR;
514 // Allocate new buffers if needed, and do the rest of
515 // the initialization.
516 if (lz_encoder_init(&next->coder->mf, allocator, &lz_options))
517 return LZMA_MEM_ERROR;
519 // Initialize the next filter in the chain, if any.
520 return lzma_next_filter_init(&next->coder->next, allocator,
525 extern LZMA_API(lzma_bool)
526 lzma_mf_is_supported(lzma_match_finder mf)
531 if (mf == LZMA_MF_HC3)
536 if (mf == LZMA_MF_HC4)
541 if (mf == LZMA_MF_BT2)
546 if (mf == LZMA_MF_BT3)
551 if (mf == LZMA_MF_BT4)