]> icculus.org git repositories - icculus/xz.git/blob - src/liblzma/lz/lz_encoder.c
Major changes to LZ encoder, LZMA encoder, and range encoder.
[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-2006 Igor Pavlov
7 //  Copyright (C) 2007 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_private.h"
22
23 // Hash Chains
24 #ifdef HAVE_HC3
25 #       include "hc3.h"
26 #endif
27 #ifdef HAVE_HC4
28 #       include "hc4.h"
29 #endif
30
31 // Binary Trees
32 #ifdef HAVE_BT2
33 #       include "bt2.h"
34 #endif
35 #ifdef HAVE_BT3
36 #       include "bt3.h"
37 #endif
38 #ifdef HAVE_BT4
39 #       include "bt4.h"
40 #endif
41
42
43 /// This is needed in two places so provide a macro.
44 #define get_cyclic_buffer_size(history_size) ((history_size) + 1)
45
46
47 /// Calculate certain match finder properties and validate the calculated
48 /// values. This is as its own function, because *num_items is needed to
49 /// calculate memory requirements in common/memory.c.
50 extern uint32_t
51 lzma_lz_encoder_hash_properties(lzma_match_finder match_finder,
52                 uint32_t history_size, uint32_t *restrict hash_mask,
53                 uint32_t *restrict hash_size_sum, uint32_t *restrict num_items)
54 {
55         uint32_t fix_hash_size;
56         uint32_t sons;
57
58         switch (match_finder) {
59 #ifdef HAVE_HC3
60         case LZMA_MF_HC3:
61                 fix_hash_size = LZMA_HC3_FIX_HASH_SIZE;
62                 sons = 1;
63                 break;
64 #endif
65 #ifdef HAVE_HC4
66         case LZMA_MF_HC4:
67                 fix_hash_size = LZMA_HC4_FIX_HASH_SIZE;
68                 sons = 1;
69                 break;
70 #endif
71 #ifdef HAVE_BT2
72         case LZMA_MF_BT2:
73                 fix_hash_size = LZMA_BT2_FIX_HASH_SIZE;
74                 sons = 2;
75                 break;
76 #endif
77 #ifdef HAVE_BT3
78         case LZMA_MF_BT3:
79                 fix_hash_size = LZMA_BT3_FIX_HASH_SIZE;
80                 sons = 2;
81                 break;
82 #endif
83 #ifdef HAVE_BT4
84         case LZMA_MF_BT4:
85                 fix_hash_size = LZMA_BT4_FIX_HASH_SIZE;
86                 sons = 2;
87                 break;
88 #endif
89         default:
90                 return true;
91         }
92
93         uint32_t hs;
94
95 #ifdef HAVE_LZMA_BT2
96         if (match_finder == LZMA_BT2) {
97                 // NOTE: hash_mask is not used by the BT2 match finder,
98                 // but it is initialized just in case.
99                 hs = LZMA_BT2_HASH_SIZE;
100                 *hash_mask = 0;
101         } else
102 #endif
103         {
104                 hs = history_size - 1;
105                 hs |= (hs >> 1);
106                 hs |= (hs >> 2);
107                 hs |= (hs >> 4);
108                 hs |= (hs >> 8);
109                 hs >>= 1;
110                 hs |= 0xFFFF;
111
112                 if (hs > (UINT32_C(1) << 24)) {
113                         if (match_finder == LZMA_MF_HC4
114                                         || match_finder == LZMA_MF_BT4)
115                                 hs >>= 1;
116                         else
117                                 hs = (1 << 24) - 1;
118                 }
119
120                 *hash_mask = hs;
121                 ++hs;
122         }
123
124         *hash_size_sum = hs + fix_hash_size;
125
126         *num_items = *hash_size_sum
127                         + get_cyclic_buffer_size(history_size) * sons;
128
129         return false;
130 }
131
132
133 extern lzma_ret
134 lzma_lz_encoder_reset(lzma_lz_encoder *lz, lzma_allocator *allocator,
135                 bool (*process)(lzma_coder *coder, uint8_t *restrict out,
136                         size_t *restrict out_pos, size_t out_size),
137                 lzma_vli uncompressed_size,
138                 size_t history_size, size_t additional_buffer_before,
139                 size_t match_max_len, size_t additional_buffer_after,
140                 lzma_match_finder match_finder, uint32_t match_finder_cycles,
141                 const uint8_t *preset_dictionary,
142                 size_t preset_dictionary_size)
143 {
144         lz->sequence = SEQ_RUN;
145         lz->uncompressed_size = uncompressed_size;
146         lz->temp_size = 0;
147
148         ///////////////
149         // In Window //
150         ///////////////
151
152         // Validate history size.
153         if (history_size < LZMA_DICTIONARY_SIZE_MIN
154                         || history_size > LZMA_DICTIONARY_SIZE_MAX) {
155                 lzma_lz_encoder_end(lz, allocator);
156                 return LZMA_HEADER_ERROR;
157         }
158
159         assert(history_size <= MAX_VAL_FOR_NORMALIZE - 256);
160         assert(LZMA_DICTIONARY_SIZE_MAX <= MAX_VAL_FOR_NORMALIZE - 256);
161
162         // Calculate the size of the history buffer to allocate.
163         // TODO: Get a reason for magic constant of 256.
164         const size_t size_reserv = (history_size + additional_buffer_before
165                         + match_max_len + additional_buffer_after) / 2 + 256;
166
167         lz->keep_size_before = history_size + additional_buffer_before;
168         lz->keep_size_after = match_max_len + additional_buffer_after;
169
170         const size_t buffer_size = lz->keep_size_before + lz->keep_size_after
171                         + size_reserv;
172
173         // Allocate history buffer if its size has changed.
174         if (buffer_size != lz->size) {
175                 lzma_free(lz->buffer, allocator);
176                 lz->buffer = lzma_alloc(buffer_size, allocator);
177                 if (lz->buffer == NULL) {
178                         lzma_lz_encoder_end(lz, allocator);
179                         return LZMA_MEM_ERROR;
180                 }
181         }
182
183         // Allocation successful. Store the new size.
184         lz->size = buffer_size;
185
186         // Reset in window variables.
187         lz->offset = 0;
188         lz->read_pos = 0;
189         lz->read_limit = 0;
190         lz->write_pos = 0;
191
192
193         //////////////////
194         // Match Finder //
195         //////////////////
196
197         // Validate match_finder, set function pointers and a few match
198         // finder specific variables.
199         switch (match_finder) {
200 #ifdef HAVE_HC3
201         case LZMA_MF_HC3:
202                 lz->get_matches = &lzma_hc3_get_matches;
203                 lz->skip = &lzma_hc3_skip;
204                 lz->cut_value = 8 + (match_max_len >> 2);
205                 break;
206 #endif
207 #ifdef HAVE_HC4
208         case LZMA_MF_HC4:
209                 lz->get_matches = &lzma_hc4_get_matches;
210                 lz->skip = &lzma_hc4_skip;
211                 lz->cut_value = 8 + (match_max_len >> 2);
212                 break;
213 #endif
214 #ifdef HAVE_BT2
215         case LZMA_MF_BT2:
216                 lz->get_matches = &lzma_bt2_get_matches;
217                 lz->skip = &lzma_bt2_skip;
218                 lz->cut_value = 16 + (match_max_len >> 1);
219                 break;
220 #endif
221 #ifdef HAVE_BT3
222         case LZMA_MF_BT3:
223                 lz->get_matches = &lzma_bt3_get_matches;
224                 lz->skip = &lzma_bt3_skip;
225                 lz->cut_value = 16 + (match_max_len >> 1);
226                 break;
227 #endif
228 #ifdef HAVE_BT4
229         case LZMA_MF_BT4:
230                 lz->get_matches = &lzma_bt4_get_matches;
231                 lz->skip = &lzma_bt4_skip;
232                 lz->cut_value = 16 + (match_max_len >> 1);
233                 break;
234 #endif
235         default:
236                 lzma_lz_encoder_end(lz, allocator);
237                 return LZMA_HEADER_ERROR;
238         }
239
240         // Check if we have been requested to use a non-default cut_value.
241         if (match_finder_cycles > 0)
242                 lz->cut_value = match_finder_cycles;
243
244         lz->match_max_len = match_max_len;
245         lz->cyclic_buffer_size = get_cyclic_buffer_size(history_size);
246
247         uint32_t hash_size_sum;
248         uint32_t num_items;
249         if (lzma_lz_encoder_hash_properties(match_finder, history_size,
250                         &lz->hash_mask, &hash_size_sum, &num_items)) {
251                 lzma_lz_encoder_end(lz, allocator);
252                 return LZMA_HEADER_ERROR;
253         }
254
255         if (num_items != lz->num_items) {
256 #if UINT32_MAX >= SIZE_MAX / 4
257                 // Check for integer overflow. (Huge dictionaries are not
258                 // possible on 32-bit CPU.)
259                 if (num_items > SIZE_MAX / sizeof(uint32_t)) {
260                         lzma_lz_encoder_end(lz, allocator);
261                         return LZMA_MEM_ERROR;
262                 }
263 #endif
264
265                 const size_t size_in_bytes
266                                 = (size_t)(num_items) * sizeof(uint32_t);
267
268                 lzma_free(lz->hash, allocator);
269                 lz->hash = lzma_alloc(size_in_bytes, allocator);
270                 if (lz->hash == NULL) {
271                         lzma_lz_encoder_end(lz, allocator);
272                         return LZMA_MEM_ERROR;
273                 }
274
275                 lz->num_items = num_items;
276         }
277
278         lz->son = lz->hash + hash_size_sum;
279
280         // Reset the hash table to empty hash values.
281         {
282                 uint32_t *restrict items = lz->hash;
283
284                 for (uint32_t i = 0; i < hash_size_sum; ++i)
285                         items[i] = EMPTY_HASH_VALUE;
286         }
287
288         lz->cyclic_buffer_pos = 0;
289
290         // Because zero is used as empty hash value, make the first byte
291         // appear at buffer[1 - offset].
292         ++lz->offset;
293
294         // If we are using a preset dictionary, read it now.
295         // TODO: This isn't implemented yet so return LZMA_HEADER_ERROR.
296         if (preset_dictionary != NULL && preset_dictionary_size > 0) {
297                 lzma_lz_encoder_end(lz, allocator);
298                 return LZMA_HEADER_ERROR;
299         }
300
301         // Set the process function pointer.
302         lz->process = process;
303
304         return LZMA_OK;
305 }
306
307
308 extern void
309 lzma_lz_encoder_end(lzma_lz_encoder *lz, lzma_allocator *allocator)
310 {
311         lzma_free(lz->hash, allocator);
312         lz->hash = NULL;
313         lz->num_items = 0;
314
315         lzma_free(lz->buffer, allocator);
316         lz->buffer = NULL;
317         lz->size = 0;
318
319         return;
320 }
321
322
323 /// \brief      Moves the data in the input window to free space for new data
324 ///
325 /// lz->buffer is a sliding input window, which keeps lz->keep_size_before
326 /// bytes of input history available all the time. Now and then we need to
327 /// "slide" the buffer to make space for the new data to the end of the
328 /// buffer. At the same time, data older than keep_size_before is dropped.
329 ///
330 static void
331 move_window(lzma_lz_encoder *lz)
332 {
333         // buffer[move_offset] will become buffer[0].
334         assert(lz->read_pos > lz->keep_size_after);
335         size_t move_offset = lz->read_pos - lz->keep_size_before;
336
337         // We need one additional byte, since move_pos() moves on 1 byte.
338         // TODO: Clean up? At least document more.
339         if (move_offset > 0)
340                 --move_offset;
341
342         assert(lz->write_pos > move_offset);
343         const size_t move_size = lz->write_pos - move_offset;
344
345         assert(move_offset + move_size <= lz->size);
346
347         memmove(lz->buffer, lz->buffer + move_offset, move_size);
348
349         lz->offset += move_offset;
350         lz->read_pos -= move_offset;
351         lz->read_limit -= move_offset;
352         lz->write_pos -= move_offset;
353
354         return;
355 }
356
357
358 /// \brief      Tries to fill the input window (lz->buffer)
359 ///
360 /// If we are the last encoder in the chain, our input data is in in[].
361 /// Otherwise we call the next filter in the chain to process in[] and
362 /// write its output to lz->buffer.
363 ///
364 /// This function must not be called once it has returned LZMA_STREAM_END.
365 ///
366 static lzma_ret
367 fill_window(lzma_coder *coder, lzma_allocator *allocator, const uint8_t *in,
368                 size_t *in_pos, size_t in_size, lzma_action action)
369 {
370         assert(coder->lz.read_pos <= coder->lz.write_pos);
371
372         // Move the sliding window if needed.
373         if (coder->lz.read_pos >= coder->lz.size - coder->lz.keep_size_after)
374                 move_window(&coder->lz);
375
376         size_t in_used;
377         lzma_ret ret;
378         if (coder->next.code == NULL) {
379                 // Not using a filter, simply memcpy() as much as possible.
380                 in_used = bufcpy(in, in_pos, in_size, coder->lz.buffer,
381                                 &coder->lz.write_pos, coder->lz.size);
382
383                 if (action != LZMA_RUN && *in_pos == in_size)
384                         ret = LZMA_STREAM_END;
385                 else
386                         ret = LZMA_OK;
387
388         } else {
389                 const size_t in_start = *in_pos;
390                 ret = coder->next.code(coder->next.coder, allocator,
391                                 in, in_pos, in_size,
392                                 coder->lz.buffer, &coder->lz.write_pos,
393                                 coder->lz.size, action);
394                 in_used = *in_pos - in_start;
395         }
396
397         assert(coder->lz.uncompressed_size >= in_used);
398         if (coder->lz.uncompressed_size != LZMA_VLI_VALUE_UNKNOWN)
399                 coder->lz.uncompressed_size -= in_used;
400
401         // If end of stream has been reached or flushing completed, we allow
402         // the encoder to process all the input (that is, read_pos is allowed
403         // to reach write_pos). Otherwise we keep keep_size_after bytes
404         // available as prebuffer.
405         if (ret == LZMA_STREAM_END) {
406                 assert(*in_pos == in_size);
407                 coder->lz.read_limit = coder->lz.write_pos;
408                 ret = LZMA_OK;
409
410                 switch (action) {
411                 case LZMA_SYNC_FLUSH:
412                         coder->lz.sequence = SEQ_FLUSH;
413                         break;
414
415                 case LZMA_FINISH:
416                         coder->lz.sequence = SEQ_FINISH;
417                         break;
418
419                 default:
420                         assert(0);
421                         ret = LZMA_PROG_ERROR;
422                         break;
423                 }
424
425         } else if (coder->lz.write_pos > coder->lz.keep_size_after) {
426                 // This needs to be done conditionally, because if we got
427                 // only little new input, there may be too little input
428                 // to do any encoding yet.
429                 coder->lz.read_limit = coder->lz.write_pos
430                                 - coder->lz.keep_size_after;
431         }
432
433         // Switch to finishing mode if we have got all the input data.
434         // lzma_lz_encode() won't return LZMA_STREAM_END until LZMA_FINISH
435         // is used.
436         //
437         // NOTE: When LZMA is used together with other filters, it is possible
438         // that coder->lz.sequence gets set to SEQ_FINISH before the next
439         // encoder has returned LZMA_STREAM_END. This is somewhat ugly, but
440         // works correctly, because the next encoder cannot have any more
441         // output left to be produced. If it had, then our known Uncompressed
442         // Size would be invalid, which would mean that we have a bad bug.
443         if (ret == LZMA_OK && coder->lz.uncompressed_size == 0)
444                 coder->lz.sequence = SEQ_FINISH;
445
446         return ret;
447 }
448
449
450 extern lzma_ret
451 lzma_lz_encode(lzma_coder *coder, lzma_allocator *allocator,
452                 const uint8_t *restrict in, size_t *restrict in_pos,
453                 size_t in_size,
454                 uint8_t *restrict out, size_t *restrict out_pos,
455                 size_t out_size, lzma_action action)
456 {
457         // Flush the temporary output buffer, which may be used when the
458         // encoder runs of out of space in primary output buffer (the out,
459         // *out_pos, and out_size variables).
460         if (coder->lz.temp_size > 0) {
461                 const size_t out_avail = out_size - *out_pos;
462                 if (out_avail < coder->lz.temp_size) {
463                         // Cannot copy everything. Copy as much as possible
464                         // and move the data in lz.temp to the beginning of
465                         // that buffer.
466                         memcpy(out + *out_pos, coder->lz.temp, out_avail);
467                         *out_pos += out_avail;
468                         memmove(coder->lz.temp, coder->lz.temp + out_avail,
469                                         coder->lz.temp_size - out_avail);
470                         coder->lz.temp_size -= out_avail;
471                         return LZMA_OK;
472                 }
473
474                 // We can copy everything from coder->lz.temp to out.
475                 memcpy(out + *out_pos, coder->lz.temp, coder->lz.temp_size);
476                 *out_pos += coder->lz.temp_size;
477                 coder->lz.temp_size = 0;
478         }
479
480         if (coder->lz.sequence == SEQ_FLUSH_END) {
481                 // During an earlier call to this function, flushing was
482                 // otherwise finished except some data was left pending
483                 // in coder->lz.buffer. Now we have copied all that data
484                 // to the output buffer and can return LZMA_STREAM_END.
485                 coder->lz.sequence = SEQ_RUN;
486                 assert(action == LZMA_SYNC_FLUSH);
487                 return LZMA_STREAM_END;
488         }
489
490         if (coder->lz.sequence == SEQ_END) {
491                 // This is like the above flushing case, but for finishing
492                 // the encoding.
493                 //
494                 // NOTE: action is not necesarily LZMA_FINISH; it can
495                 // be LZMA_SYNC_FLUSH too in case it is used at the
496                 // end of the stream with known Uncompressed Size.
497                 return action != LZMA_RUN ? LZMA_STREAM_END : LZMA_OK;
498         }
499
500         while (*out_pos < out_size
501                         && (*in_pos < in_size || action != LZMA_RUN)) {
502                 // Read more data to coder->lz.buffer if needed.
503                 if (coder->lz.sequence == SEQ_RUN
504                                 && coder->lz.read_pos >= coder->lz.read_limit)
505                         return_if_error(fill_window(coder, allocator,
506                                         in, in_pos, in_size, action));
507
508                 // Encode
509                 if (coder->lz.process(coder, out, out_pos, out_size)) {
510                         if (coder->lz.sequence == SEQ_FLUSH) {
511                                 assert(action == LZMA_SYNC_FLUSH);
512                                 if (coder->lz.temp_size == 0) {
513                                         // Flushing was finished successfully.
514                                         coder->lz.sequence = SEQ_RUN;
515                                 } else {
516                                         // Flushing was otherwise finished,
517                                         // except that some data was left
518                                         // into coder->lz.buffer.
519                                         coder->lz.sequence = SEQ_FLUSH_END;
520                                 }
521                         } else {
522                                 // NOTE: action may be LZMA_RUN here in case
523                                 // Uncompressed Size is known and we have
524                                 // processed all the data already.
525                                 assert(coder->lz.sequence == SEQ_FINISH);
526                                 coder->lz.sequence = SEQ_END;
527                         }
528
529                         return action != LZMA_RUN && coder->lz.temp_size == 0
530                                         ? LZMA_STREAM_END : LZMA_OK;
531                 }
532         }
533
534         return LZMA_OK;
535 }
536
537
538 /// \brief      Normalizes hash values
539 ///
540 /// lzma_lz_normalize is called when lz->pos hits MAX_VAL_FOR_NORMALIZE,
541 /// which currently happens once every 2 GiB of input data (to be exact,
542 /// after the first 2 GiB it happens once every 2 GiB minus dictionary_size
543 /// bytes). lz->pos is incremented by lzma_lz_move_pos().
544 ///
545 /// lz->hash contains big amount of offsets relative to lz->buffer.
546 /// The offsets are stored as uint32_t, which is the only reasonable
547 /// datatype for these offsets; uint64_t would waste far too much RAM
548 /// and uint16_t would limit the dictionary to 64 KiB (far too small).
549 ///
550 /// When compressing files over 2 GiB, lz->buffer needs to be moved forward
551 /// to avoid integer overflows. We scan the lz->hash array and fix every
552 /// value to match the updated lz->buffer.
553 extern void
554 lzma_lz_encoder_normalize(lzma_lz_encoder *lz)
555 {
556         const uint32_t subvalue = lz->read_pos - lz->cyclic_buffer_size;
557         assert(subvalue <= INT32_MAX);
558
559         {
560                 const uint32_t num_items = lz->num_items;
561                 uint32_t *restrict items = lz->hash;
562
563                 for (uint32_t i = 0; i < num_items; ++i) {
564                         // If the distance is greater than the dictionary
565                         // size, we can simply mark the item as empty.
566                         if (items[i] <= subvalue)
567                                 items[i] = EMPTY_HASH_VALUE;
568                         else
569                                 items[i] -= subvalue;
570                 }
571         }
572
573         // Update offset to match the new locations.
574         lz->offset -= subvalue;
575
576         return;
577 }