]> icculus.org git repositories - icculus/xz.git/blob - src/liblzma/lz/lz_encoder.c
Fix a couple of warnings.
[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         lzma_ret ret;
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);
92
93                 ret = action != LZMA_RUN && *in_pos == in_size
94                                 ? LZMA_STREAM_END : LZMA_OK;
95
96         } else {
97                 ret = coder->next.code(coder->next.coder, allocator,
98                                 in, in_pos, in_size,
99                                 coder->mf.buffer, &write_pos,
100                                 coder->mf.size, action);
101         }
102
103         coder->mf.write_pos = write_pos;
104
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);
111                 ret = LZMA_OK;
112                 coder->mf.action = action;
113                 coder->mf.read_limit = coder->mf.write_pos;
114
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;
121         }
122
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;
130
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;
135
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);
139         }
140
141         return ret;
142 }
143
144
145 static lzma_ret
146 lz_encode(lzma_coder *coder, lzma_allocator *allocator,
147                 const uint8_t *restrict in, size_t *restrict in_pos,
148                 size_t in_size,
149                 uint8_t *restrict out, size_t *restrict out_pos,
150                 size_t out_size, lzma_action action)
151 {
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));
159
160                 // Encode
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;
168                         return ret;
169                 }
170         }
171
172         return LZMA_OK;
173 }
174
175
176 static bool
177 lz_encoder_prepare(lzma_mf *mf, lzma_allocator *allocator,
178                 const lzma_lz_options *lz_options)
179 {
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)
187                 return true;
188
189         mf->keep_size_before = lz_options->before_size + lz_options->dict_size;
190
191         mf->keep_size_after = lz_options->after_size
192                         + lz_options->match_len_max;
193
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.
198         //
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
202         //     to size_t.
203         //   - Memory usage calculation needs something too, e.g. use uint64_t
204         //     for mf->size.
205         uint32_t reserve = lz_options->dict_size / 2;
206         if (reserve > (UINT32_C(1) << 30))
207                 reserve /= 2;
208
209         reserve += (lz_options->before_size + lz_options->match_len_max
210                         + lz_options->after_size) / 2 + (UINT32_C(1) << 19);
211
212         const uint32_t old_size = mf->size;
213         mf->size = mf->keep_size_before + reserve + mf->keep_size_after;
214
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);
219                 mf->buffer = NULL;
220         }
221
222         // Match finder options
223         mf->match_len_max = lz_options->match_len_max;
224         mf->nice_len = lz_options->nice_len;
225
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.
231         //
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
240         // limits to change.
241         mf->cyclic_size = lz_options->dict_size + 1;
242
243         // Validate the match finder ID and setup the function pointers.
244         switch (lz_options->match_finder) {
245 #ifdef HAVE_MF_HC3
246         case LZMA_MF_HC3:
247                 mf->find = &lzma_mf_hc3_find;
248                 mf->skip = &lzma_mf_hc3_skip;
249                 break;
250 #endif
251 #ifdef HAVE_MF_HC4
252         case LZMA_MF_HC4:
253                 mf->find = &lzma_mf_hc4_find;
254                 mf->skip = &lzma_mf_hc4_skip;
255                 break;
256 #endif
257 #ifdef HAVE_MF_BT2
258         case LZMA_MF_BT2:
259                 mf->find = &lzma_mf_bt2_find;
260                 mf->skip = &lzma_mf_bt2_skip;
261                 break;
262 #endif
263 #ifdef HAVE_MF_BT3
264         case LZMA_MF_BT3:
265                 mf->find = &lzma_mf_bt3_find;
266                 mf->skip = &lzma_mf_bt3_skip;
267                 break;
268 #endif
269 #ifdef HAVE_MF_BT4
270         case LZMA_MF_BT4:
271                 mf->find = &lzma_mf_bt4_find;
272                 mf->skip = &lzma_mf_bt4_skip;
273                 break;
274 #endif
275
276         default:
277                 return true;
278         }
279
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)
284                 return true;
285
286         const bool is_bt = (lz_options->match_finder & 0x10) != 0;
287         uint32_t hs;
288
289         if (hash_bytes == 2) {
290                 hs = 0xFFFF;
291         } else {
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;
295                 hs |= hs >> 1;
296                 hs |= hs >> 2;
297                 hs |= hs >> 4;
298                 hs |= hs >> 8;
299                 hs >>= 1;
300                 hs |= 0xFFFF;
301
302                 if (hs > (UINT32_C(1) << 24)) {
303                         if (hash_bytes == 3)
304                                 hs = (UINT32_C(1) << 24) - 1;
305                         else
306                                 hs >>= 1;
307                 }
308         }
309
310         mf->hash_mask = hs;
311
312         ++hs;
313         if (hash_bytes > 2)
314                 hs += HASH_2_SIZE;
315         if (hash_bytes > 3)
316                 hs += HASH_3_SIZE;
317 /*
318         No match finder uses this at the moment.
319         if (mf->hash_bytes > 4)
320                 hs += HASH_4_SIZE;
321 */
322
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);
328
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;
332         if (is_bt)
333                 mf->sons_count *= 2;
334
335         const uint32_t new_count = mf->hash_size_sum + mf->sons_count;
336
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);
341                 mf->hash = NULL;
342         }
343
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);
348                 if (!is_bt)
349                         mf->depth /= 2;
350         }
351
352         return false;
353 }
354
355
356 static bool
357 lz_encoder_init(lzma_mf *mf, lzma_allocator *allocator,
358                 const lzma_lz_options *lz_options)
359 {
360         // Allocate the history buffer.
361         if (mf->buffer == NULL) {
362                 mf->buffer = lzma_alloc(mf->size, allocator);
363                 if (mf->buffer == NULL)
364                         return true;
365         }
366
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;
372         mf->read_pos = 0;
373         mf->read_ahead = 0;
374         mf->read_limit = 0;
375         mf->write_pos = 0;
376         mf->pending = 0;
377
378         // Allocate match finder's hash array.
379         const size_t alloc_count = mf->hash_size_sum + mf->sons_count;
380
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))
385                 return true;
386 #endif
387
388         if (mf->hash == NULL) {
389                 mf->hash = lzma_alloc(alloc_count * sizeof(uint32_t),
390                                 allocator);
391                 if (mf->hash == NULL)
392                         return true;
393         }
394
395         mf->son = mf->hash + mf->hash_size_sum;
396         mf->cyclic_pos = 0;
397
398         // Initialize the hash table. Since EMPTY_HASH_VALUE is zero, we
399         // can use memset().
400 /*
401         for (uint32_t i = 0; i < hash_size_sum; ++i)
402                 mf->hash[i] = EMPTY_HASH_VALUE;
403 */
404         memzero(mf->hash, (size_t)(mf->hash_size_sum) * sizeof(uint32_t));
405
406         // We don't need to initialize mf->son, but not doing that will
407         // make Valgrind complain in normalization (see normalize() in
408         // lz_encoder_mf.c).
409         //
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));
415
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,
424                                 mf->write_pos);
425                 mf->action = LZMA_SYNC_FLUSH;
426                 mf->skip(mf, mf->write_pos);
427         }
428
429         mf->action = LZMA_RUN;
430
431         return false;
432 }
433
434
435 extern uint64_t
436 lzma_lz_encoder_memusage(const lzma_lz_options *lz_options)
437 {
438         // Old buffers must not exist when calling lz_encoder_prepare().
439         lzma_mf mf = {
440                 .buffer = NULL,
441                 .hash = NULL,
442         };
443
444         // Setup the size information into mf.
445         if (lz_encoder_prepare(&mf, NULL, lz_options))
446                 return UINT64_MAX;
447
448         // Calculate the memory usage.
449         return (uint64_t)(mf.hash_size_sum + mf.sons_count)
450                                 * sizeof(uint32_t)
451                         + (uint64_t)(mf.size) + sizeof(lzma_coder);
452 }
453
454
455 static void
456 lz_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
457 {
458         lzma_next_end(&coder->next, allocator);
459
460         lzma_free(coder->mf.hash, allocator);
461         lzma_free(coder->mf.buffer, allocator);
462
463         if (coder->lz.end != NULL)
464                 coder->lz.end(coder->lz.coder, allocator);
465         else
466                 lzma_free(coder->lz.coder, allocator);
467
468         lzma_free(coder, allocator);
469         return;
470 }
471
472
473 extern lzma_ret
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))
479 {
480 #ifdef HAVE_SMALL
481         // We need that the CRC32 table has been initialized.
482         lzma_crc32_init();
483 #endif
484
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;
490
491                 next->code = &lz_encode;
492                 next->end = &lz_encoder_end;
493
494                 next->coder->lz.coder = NULL;
495                 next->coder->lz.code = NULL;
496                 next->coder->lz.end = NULL;
497
498                 next->coder->mf.buffer = NULL;
499                 next->coder->mf.hash = NULL;
500
501                 next->coder->next = LZMA_NEXT_CODER_INIT;
502         }
503
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));
508
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;
513
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;
518
519         // Initialize the next filter in the chain, if any.
520         return lzma_next_filter_init(&next->coder->next, allocator,
521                         filters + 1);
522 }
523
524
525 extern LZMA_API(lzma_bool)
526 lzma_mf_is_supported(lzma_match_finder mf)
527 {
528         bool ret = false;
529
530 #ifdef HAVE_MF_HC3
531         if (mf == LZMA_MF_HC3)
532                 ret = true;
533 #endif
534
535 #ifdef HAVE_MF_HC4
536         if (mf == LZMA_MF_HC4)
537                 ret = true;
538 #endif
539
540 #ifdef HAVE_MF_BT2
541         if (mf == LZMA_MF_BT2)
542                 ret = true;
543 #endif
544
545 #ifdef HAVE_MF_BT3
546         if (mf == LZMA_MF_BT3)
547                 ret = true;
548 #endif
549
550 #ifdef HAVE_MF_BT4
551         if (mf == LZMA_MF_BT4)
552                 ret = true;
553 #endif
554
555         return ret;
556 }