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