]> icculus.org git repositories - icculus/xz.git/blob - src/liblzma/lz/lz_encoder.c
Imported to git.
[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         // Set uncompressed size.
145         lz->uncompressed_size = uncompressed_size;
146
147         ///////////////
148         // In Window //
149         ///////////////
150
151         // Validate history size.
152         if (history_size < LZMA_DICTIONARY_SIZE_MIN
153                         || history_size > LZMA_DICTIONARY_SIZE_MAX) {
154                 lzma_lz_encoder_end(lz, allocator);
155                 return LZMA_HEADER_ERROR;
156         }
157
158         assert(history_size <= MAX_VAL_FOR_NORMALIZE - 256);
159         assert(LZMA_DICTIONARY_SIZE_MAX <= MAX_VAL_FOR_NORMALIZE - 256);
160
161         // Calculate the size of the history buffer to allocate.
162         // TODO: Get a reason for magic constant of 256.
163         const size_t size_reserv = (history_size + additional_buffer_before
164                         + match_max_len + additional_buffer_after) / 2 + 256;
165
166         lz->keep_size_before = history_size + additional_buffer_before;
167         lz->keep_size_after = match_max_len + additional_buffer_after;
168
169         const size_t buffer_size = lz->keep_size_before + lz->keep_size_after
170                         + size_reserv;
171
172         // Allocate history buffer if its size has changed.
173         if (buffer_size != lz->size) {
174                 lzma_free(lz->buffer, allocator);
175                 lz->buffer = lzma_alloc(buffer_size, allocator);
176                 if (lz->buffer == NULL) {
177                         lzma_lz_encoder_end(lz, allocator);
178                         return LZMA_MEM_ERROR;
179                 }
180         }
181
182         // Allocation successful. Store the new size and calculate
183         // must_move_pos.
184         lz->size = buffer_size;
185         lz->must_move_pos = lz->size - lz->keep_size_after;
186
187         // Reset in window variables.
188         lz->offset = 0;
189         lz->read_pos = 0;
190         lz->read_limit = 0;
191         lz->write_pos = 0;
192         lz->stream_end_was_reached = false;
193
194
195         //////////////////
196         // Match Finder //
197         //////////////////
198
199         // Validate match_finder, set function pointers and a few match
200         // finder specific variables.
201         switch (match_finder) {
202 #ifdef HAVE_HC3
203         case LZMA_MF_HC3:
204                 lz->get_matches = &lzma_hc3_get_matches;
205                 lz->skip = &lzma_hc3_skip;
206                 lz->cut_value = 8 + (match_max_len >> 2);
207                 break;
208 #endif
209 #ifdef HAVE_HC4
210         case LZMA_MF_HC4:
211                 lz->get_matches = &lzma_hc4_get_matches;
212                 lz->skip = &lzma_hc4_skip;
213                 lz->cut_value = 8 + (match_max_len >> 2);
214                 break;
215 #endif
216 #ifdef HAVE_BT2
217         case LZMA_MF_BT2:
218                 lz->get_matches = &lzma_bt2_get_matches;
219                 lz->skip = &lzma_bt2_skip;
220                 lz->cut_value = 16 + (match_max_len >> 1);
221                 break;
222 #endif
223 #ifdef HAVE_BT3
224         case LZMA_MF_BT3:
225                 lz->get_matches = &lzma_bt3_get_matches;
226                 lz->skip = &lzma_bt3_skip;
227                 lz->cut_value = 16 + (match_max_len >> 1);
228                 break;
229 #endif
230 #ifdef HAVE_BT4
231         case LZMA_MF_BT4:
232                 lz->get_matches = &lzma_bt4_get_matches;
233                 lz->skip = &lzma_bt4_skip;
234                 lz->cut_value = 16 + (match_max_len >> 1);
235                 break;
236 #endif
237         default:
238                 lzma_lz_encoder_end(lz, allocator);
239                 return LZMA_HEADER_ERROR;
240         }
241
242         // Check if we have been requested to use a non-default cut_value.
243         if (match_finder_cycles > 0)
244                 lz->cut_value = match_finder_cycles;
245
246         lz->match_max_len = match_max_len;
247         lz->cyclic_buffer_size = get_cyclic_buffer_size(history_size);
248
249         uint32_t hash_size_sum;
250         uint32_t num_items;
251         if (lzma_lz_encoder_hash_properties(match_finder, history_size,
252                         &lz->hash_mask, &hash_size_sum, &num_items)) {
253                 lzma_lz_encoder_end(lz, allocator);
254                 return LZMA_HEADER_ERROR;
255         }
256
257         if (num_items != lz->num_items) {
258 #if UINT32_MAX >= SIZE_MAX / 4
259                 // Check for integer overflow. (Huge dictionaries are not
260                 // possible on 32-bit CPU.)
261                 if (num_items > SIZE_MAX / sizeof(uint32_t)) {
262                         lzma_lz_encoder_end(lz, allocator);
263                         return LZMA_MEM_ERROR;
264                 }
265 #endif
266
267                 const size_t size_in_bytes
268                                 = (size_t)(num_items) * sizeof(uint32_t);
269
270                 lzma_free(lz->hash, allocator);
271                 lz->hash = lzma_alloc(size_in_bytes, allocator);
272                 if (lz->hash == NULL) {
273                         lzma_lz_encoder_end(lz, allocator);
274                         return LZMA_MEM_ERROR;
275                 }
276
277                 lz->num_items = num_items;
278         }
279
280         lz->son = lz->hash + hash_size_sum;
281
282         // Reset the hash table to empty hash values.
283         {
284                 uint32_t *restrict items = lz->hash;
285
286                 for (uint32_t i = 0; i < hash_size_sum; ++i)
287                         items[i] = EMPTY_HASH_VALUE;
288         }
289
290         lz->cyclic_buffer_pos = 0;
291
292         // Because zero is used as empty hash value, make the first byte
293         // appear at buffer[1 - offset].
294         ++lz->offset;
295
296         // If we are using a preset dictionary, read it now.
297         // TODO: This isn't implemented yet so return LZMA_HEADER_ERROR.
298         if (preset_dictionary != NULL && preset_dictionary_size > 0) {
299                 lzma_lz_encoder_end(lz, allocator);
300                 return LZMA_HEADER_ERROR;
301         }
302
303         // Set the process function pointer.
304         lz->process = process;
305
306         return LZMA_OK;
307 }
308
309
310 extern void
311 lzma_lz_encoder_end(lzma_lz_encoder *lz, lzma_allocator *allocator)
312 {
313         lzma_free(lz->hash, allocator);
314         lz->hash = NULL;
315         lz->num_items = 0;
316
317         lzma_free(lz->buffer, allocator);
318         lz->buffer = NULL;
319         lz->size = 0;
320
321         return;
322 }
323
324
325 /// \brief      Moves the data in the input window to free space for new data
326 ///
327 /// lz->buffer is a sliding input window, which keeps lz->keep_size_before
328 /// bytes of input history available all the time. Now and then we need to
329 /// "slide" the buffer to make space for the new data to the end of the
330 /// buffer. At the same time, data older than keep_size_before is dropped.
331 ///
332 static void
333 move_window(lzma_lz_encoder *lz)
334 {
335         // buffer[move_offset] will become buffer[0].
336         assert(lz->read_pos > lz->keep_size_after);
337         size_t move_offset = lz->read_pos - lz->keep_size_before;
338
339         // We need one additional byte, since move_pos() moves on 1 byte.
340         // TODO: Clean up? At least document more.
341         if (move_offset > 0)
342                 --move_offset;
343
344         assert(lz->write_pos > move_offset);
345         const size_t move_size = lz->write_pos - move_offset;
346
347         assert(move_offset + move_size <= lz->size);
348
349         memmove(lz->buffer, lz->buffer + move_offset, move_size);
350
351         lz->offset += move_offset;
352         lz->read_pos -= move_offset;
353         lz->read_limit -= move_offset;
354         lz->write_pos -= move_offset;
355
356         return;
357 }
358
359
360 /// \brief      Tries to fill the input window (lz->buffer)
361 ///
362 /// If we are the last encoder in the chain, our input data is in in[].
363 /// Otherwise we call the next filter in the chain to process in[] and
364 /// write its output to lz->buffer.
365 ///
366 /// This function must not be called once it has returned LZMA_STREAM_END.
367 ///
368 static lzma_ret
369 fill_window(lzma_coder *coder, lzma_allocator *allocator, const uint8_t *in,
370                 size_t *in_pos, size_t in_size, lzma_action action)
371 {
372         assert(coder->lz.read_pos <= coder->lz.write_pos);
373         lzma_ret ret;
374
375         // Move the sliding window if needed.
376         if (coder->lz.read_pos >= coder->lz.must_move_pos)
377                 move_window(&coder->lz);
378
379         if (coder->next.code == NULL) {
380                 // Not using a filter, simply memcpy() as much as possible.
381                 bufcpy(in, in_pos, in_size, coder->lz.buffer,
382                                 &coder->lz.write_pos, coder->lz.size);
383
384                 if (action == LZMA_FINISH && *in_pos == in_size)
385                         ret = LZMA_STREAM_END;
386                 else
387                         ret = LZMA_OK;
388
389         } else {
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         }
395
396         // If end of stream has been reached, we allow the encoder to process
397         // all the input (that is, read_pos is allowed to reach write_pos).
398         // Otherwise we keep keep_size_after bytes available as prebuffer.
399         if (ret == LZMA_STREAM_END) {
400                 coder->lz.stream_end_was_reached = true;
401                 coder->lz.read_limit = coder->lz.write_pos;
402
403         } else if (coder->lz.write_pos > coder->lz.keep_size_after) {
404                 // This needs to be done conditionally, because if we got
405                 // only little new input, there may be too little input
406                 // to do any encoding yet.
407                 coder->lz.read_limit = coder->lz.write_pos
408                                 - coder->lz.keep_size_after;
409         }
410
411         return ret;
412 }
413
414
415 extern lzma_ret
416 lzma_lz_encode(lzma_coder *coder, lzma_allocator *allocator,
417                 const uint8_t *restrict in, size_t *restrict in_pos,
418                 size_t in_size,
419                 uint8_t *restrict out, size_t *restrict out_pos,
420                 size_t out_size, lzma_action action)
421 {
422         while (*out_pos < out_size
423                         && (*in_pos < in_size || action == LZMA_FINISH)) {
424                 // Fill the input window if there is no more usable data.
425                 if (!coder->lz.stream_end_was_reached && coder->lz.read_pos
426                                 >= coder->lz.read_limit) {
427                         const lzma_ret ret = fill_window(coder, allocator,
428                                         in, in_pos, in_size, action);
429                         if (ret != LZMA_OK && ret != LZMA_STREAM_END)
430                                 return ret;
431                 }
432
433                 // Encode
434                 if (coder->lz.process(coder, out, out_pos, out_size))
435                         return LZMA_STREAM_END;
436         }
437
438         return LZMA_OK;
439 }
440
441
442 /// \brief      Normalizes hash values
443 ///
444 /// lzma_lz_normalize is called when lz->pos hits MAX_VAL_FOR_NORMALIZE,
445 /// which currently happens once every 2 GiB of input data (to be exact,
446 /// after the first 2 GiB it happens once every 2 GiB minus dictionary_size
447 /// bytes). lz->pos is incremented by lzma_lz_move_pos().
448 ///
449 /// lz->hash contains big amount of offsets relative to lz->buffer.
450 /// The offsets are stored as uint32_t, which is the only reasonable
451 /// datatype for these offsets; uint64_t would waste far too much RAM
452 /// and uint16_t would limit the dictionary to 64 KiB (far too small).
453 ///
454 /// When compressing files over 2 GiB, lz->buffer needs to be moved forward
455 /// to avoid integer overflows. We scan the lz->hash array and fix every
456 /// value to match the updated lz->buffer.
457 extern void
458 lzma_lz_encoder_normalize(lzma_lz_encoder *lz)
459 {
460         const uint32_t subvalue = lz->read_pos - lz->cyclic_buffer_size;
461         assert(subvalue <= INT32_MAX);
462
463         {
464                 const uint32_t num_items = lz->num_items;
465                 uint32_t *restrict items = lz->hash;
466
467                 for (uint32_t i = 0; i < num_items; ++i) {
468                         // If the distance is greater than the dictionary
469                         // size, we can simply mark the item as empty.
470                         if (items[i] <= subvalue)
471                                 items[i] = EMPTY_HASH_VALUE;
472                         else
473                                 items[i] -= subvalue;
474                 }
475         }
476
477         // Update offset to match the new locations.
478         lz->offset -= subvalue;
479
480         return;
481 }