aboutsummaryrefslogtreecommitdiff
path: root/src/liblzma/lz/lz_encoder.c
blob: d5f84826d2f8b9e0669e4c10fb74324f26d7ba4a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
///////////////////////////////////////////////////////////////////////////////
//
/// \file       lz_encoder.c
/// \brief      LZ in window
//
//  Copyright (C) 1999-2008 Igor Pavlov
//  Copyright (C) 2007-2008 Lasse Collin
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
///////////////////////////////////////////////////////////////////////////////

#include "lz_encoder.h"
#include "lz_encoder_hash.h"


struct lzma_coder_s {
	/// LZ-based encoder e.g. LZMA
	lzma_lz_encoder lz;

	/// History buffer and match finder
	lzma_mf mf;

	/// Next coder in the chain
	lzma_next_coder next;
};


/// \brief      Moves the data in the input window to free space for new data
///
/// mf->buffer is a sliding input window, which keeps mf->keep_size_before
/// bytes of input history available all the time. Now and then we need to
/// "slide" the buffer to make space for the new data to the end of the
/// buffer. At the same time, data older than keep_size_before is dropped.
///
static void
move_window(lzma_mf *mf)
{
	// Align the move to a multiple of 16 bytes. Some LZ-based encoders
	// like LZMA use the lowest bits of mf->read_pos to know the
	// alignment of the uncompressed data. We also get better speed
	// for memmove() with aligned buffers.
	assert(mf->read_pos > mf->keep_size_before);
	const uint32_t move_offset
		= (mf->read_pos - mf->keep_size_before) & ~UINT32_C(15);

	assert(mf->write_pos > move_offset);
	const size_t move_size = mf->write_pos - move_offset;

	assert(move_offset + move_size <= mf->size);

	memmove(mf->buffer, mf->buffer + move_offset, move_size);

	mf->offset += move_offset;
	mf->read_pos -= move_offset;
	mf->read_limit -= move_offset;
	mf->write_pos -= move_offset;

	return;
}


/// \brief      Tries to fill the input window (mf->buffer)
///
/// If we are the last encoder in the chain, our input data is in in[].
/// Otherwise we call the next filter in the chain to process in[] and
/// write its output to mf->buffer.
///
/// This function must not be called once it has returned LZMA_STREAM_END.
///
static lzma_ret
fill_window(lzma_coder *coder, lzma_allocator *allocator, const uint8_t *in,
		size_t *in_pos, size_t in_size, lzma_action action)
{
	assert(coder->mf.read_pos <= coder->mf.write_pos);

	// Move the sliding window if needed.
	if (coder->mf.read_pos >= coder->mf.size - coder->mf.keep_size_after)
		move_window(&coder->mf);

	size_t in_used;
	lzma_ret ret;
	if (coder->next.code == NULL) {
		// Not using a filter, simply memcpy() as much as possible.
		in_used = lzma_bufcpy(in, in_pos, in_size, coder->mf.buffer,
				&coder->mf.write_pos, coder->mf.size);

		ret = action != LZMA_RUN && *in_pos == in_size
				? LZMA_STREAM_END : LZMA_OK;

	} else {
		const size_t in_start = *in_pos;
		ret = coder->next.code(coder->next.coder, allocator,
				in, in_pos, in_size,
				coder->mf.buffer, &coder->mf.write_pos,
				coder->mf.size, action);
		in_used = *in_pos - in_start;
	}

	// If end of stream has been reached or flushing completed, we allow
	// the encoder to process all the input (that is, read_pos is allowed
	// to reach write_pos). Otherwise we keep keep_size_after bytes
	// available as prebuffer.
	if (ret == LZMA_STREAM_END) {
		assert(*in_pos == in_size);
		ret = LZMA_OK;
		coder->mf.action = action;
		coder->mf.read_limit = coder->mf.write_pos;

	} else if (coder->mf.write_pos > coder->mf.keep_size_after) {
		// This needs to be done conditionally, because if we got
		// only little new input, there may be too little input
		// to do any encoding yet.
		coder->mf.read_limit = coder->mf.write_pos
				- coder->mf.keep_size_after;
	}

	// Restart the match finder after finished LZMA_SYNC_FLUSH.
	if (coder->mf.pending > 0
			&& coder->mf.read_pos < coder->mf.read_limit) {
		// Match finder may update coder->pending and expects it to
		// start from zero, so use a temporary variable.
		const size_t pending = coder->mf.pending;
		coder->mf.pending = 0;

		// Rewind read_pos so that the match finder can hash
		// the pending bytes.
		assert(coder->mf.read_pos >= pending);
		coder->mf.read_pos -= pending;

		// Call the skip function directly instead of using
		// lz_dict_skip(), since we don't want to touch
		// mf->read_ahead.
		coder->mf.skip(&coder->mf, pending);
	}

	return ret;
}


static lzma_ret
lz_encode(lzma_coder *coder, lzma_allocator *allocator,
		const uint8_t *restrict in, size_t *restrict in_pos,
		size_t in_size,
		uint8_t *restrict out, size_t *restrict out_pos,
		size_t out_size, lzma_action action)
{
	while (*out_pos < out_size
			&& (*in_pos < in_size || action != LZMA_RUN)) {
		// Read more data to coder->mf.buffer if needed.
		if (coder->mf.action == LZMA_RUN && coder->mf.read_pos
				>= coder->mf.read_limit)
			return_if_error(fill_window(coder, allocator,
					in, in_pos, in_size, action));

		// Encode
		const lzma_ret ret = coder->lz.code(coder->lz.coder,
				&coder->mf, out, out_pos, out_size);
		if (ret != LZMA_OK) {
			// Setting this to LZMA_RUN for cases when we are
			// flushing. It doesn't matter when finishing or if
			// an error occurred.
			coder->mf.action = LZMA_RUN;
			return ret;
		}
	}

	return LZMA_OK;
}


static bool
lz_encoder_prepare(lzma_mf *mf, lzma_allocator *allocator,
		const lzma_lz_options *lz_options)
{
	if (lz_options->dictionary_size < LZMA_DICTIONARY_SIZE_MIN
			|| lz_options->dictionary_size
				> LZMA_DICTIONARY_SIZE_MAX
			|| lz_options->find_len_max
				> lz_options->match_len_max)
		return true;

	mf->keep_size_before = lz_options->before_size
			+ lz_options->dictionary_size;

	mf->keep_size_after = lz_options->after_size
			+ lz_options->match_len_max;

	// To avoid constant memmove()s, allocate some extra space. Since
	// memmove()s become more expensive when the size of the buffer
	// increases, we reserve more space when a large dictionary is
	// used to make the memmove() calls rarer.
	uint32_t reserve = lz_options->dictionary_size / 2;
	if (reserve > (UINT32_C(1) << 30))
		reserve /= 2;

	reserve += (lz_options->before_size + lz_options->match_len_max
			+ lz_options->after_size) / 2 + (UINT32_C(1) << 19);

	const uint32_t old_size = mf->size;
	mf->size = mf->keep_size_before + reserve + mf->keep_size_after;

	// FIXME Integer overflows

	// Deallocate the old history buffer if it exists but has different
	// size than what is needed now.
	if (mf->buffer != NULL && old_size != mf->size) {
		lzma_free(mf->buffer, allocator);
		mf->buffer = NULL;
	}

	// Match finder options
	mf->match_len_max = lz_options->match_len_max;
	mf->find_len_max = lz_options->find_len_max;
	mf->cyclic_buffer_size = lz_options->dictionary_size + 1;

	// Validate the match finder ID and setup the function pointers.
	switch (lz_options->match_finder) {
#ifdef HAVE_MF_HC3
	case LZMA_MF_HC3:
		mf->find = &lzma_mf_hc3_find;
		mf->skip = &lzma_mf_hc3_skip;
		break;
#endif
#ifdef HAVE_MF_HC4
	case LZMA_MF_HC4:
		mf->find = &lzma_mf_hc4_find;
		mf->skip = &lzma_mf_hc4_skip;
		break;
#endif
#ifdef HAVE_MF_BT2
	case LZMA_MF_BT2:
		mf->find = &lzma_mf_bt2_find;
		mf->skip = &lzma_mf_bt2_skip;
		break;
#endif
#ifdef HAVE_MF_BT3
	case LZMA_MF_BT3:
		mf->find = &lzma_mf_bt3_find;
		mf->skip = &lzma_mf_bt3_skip;
		break;
#endif
#ifdef HAVE_MF_BT4
	case LZMA_MF_BT4:
		mf->find = &lzma_mf_bt4_find;
		mf->skip = &lzma_mf_bt4_skip;
		break;
#endif

	default:
		return true;
	}

	// Calculate the sizes of mf->hash and mf->son.
	const uint32_t hash_bytes = lz_options->match_finder & 0x0F;
	const bool is_bt = (lz_options->match_finder & 0x10) != 0;
	uint32_t hs;

	if (hash_bytes == 2) {
		hs = 0xFFFF;
	} else {
		// Round dictionary size up to the next 2^n - 1 so it can
		// be used as a hash mask.
		hs = lz_options->dictionary_size - 1;
		hs |= hs >> 1;
		hs |= hs >> 2;
		hs |= hs >> 4;
		hs |= hs >> 8;
		hs >>= 1;
		hs |= 0xFFFF;

		if (hs > (UINT32_C(1) << 24)) {
			if (hash_bytes == 3)
				hs = (UINT32_C(1) << 24) - 1;
			else
				hs >>= 1;
		}
	}

	mf->hash_mask = hs;

	++hs;
	if (hash_bytes > 2)
		hs += HASH_2_SIZE;
	if (hash_bytes > 3)
		hs += HASH_3_SIZE;
/*
	No match finder uses this at the moment.
	if (mf->hash_bytes > 4)
		hs += HASH_4_SIZE;
*/

	const uint32_t old_count = mf->hash_size_sum + mf->sons_count;
	mf->hash_size_sum = hs;
	mf->sons_count = mf->cyclic_buffer_size;
	if (is_bt)
		mf->sons_count *= 2;

	const uint32_t new_count = mf->hash_size_sum + mf->sons_count;

	// Deallocate the old hash array if it exists and has different size
	// than what is needed now.
	if (mf->hash != NULL && old_count != new_count) {
		lzma_free(mf->hash, allocator);
		mf->hash = NULL;
	}

	// Maximum number of match finder cycles
	mf->loops = lz_options->match_finder_cycles;
	if (mf->loops == 0) {
		mf->loops = 16 + (lz_options->find_len_max / 2);
		if (!is_bt)
			mf->loops /= 2;
	}

	return false;
}


static bool
lz_encoder_init(lzma_mf *mf, lzma_allocator *allocator)
{
	// Allocate the history buffer.
	if (mf->buffer == NULL) {
		mf->buffer = lzma_alloc(mf->size, allocator);
		if (mf->buffer == NULL)
			return true;
	}

	// Use cyclic_buffer_size as initial mf->offset. This allows
	// avoiding a few branches in the match finders. The downside is
	// that match finder needs to be normalized more often, which may
	// hurt performance with huge dictionaries.
	mf->offset = mf->cyclic_buffer_size;
	mf->read_pos = 0;
	mf->read_ahead = 0;
	mf->read_limit = 0;
	mf->write_pos = 0;
	mf->pending = 0;

	// Allocate match finder's hash array.
	const size_t alloc_count = mf->hash_size_sum + mf->sons_count;

#if UINT32_MAX >= SIZE_MAX / 4
	// Check for integer overflow. (Huge dictionaries are not
	// possible on 32-bit CPU.)
	if (alloc_count > SIZE_MAX / sizeof(uint32_t))
		return true;
#endif

	if (mf->hash == NULL) {
		mf->hash = lzma_alloc(alloc_count * sizeof(uint32_t),
				allocator);
		if (mf->hash == NULL)
			return true;
	}

	mf->son = mf->hash + mf->hash_size_sum;
	mf->cyclic_buffer_pos = 0;

	// Initialize the hash table. Since EMPTY_HASH_VALUE is zero, we
	// can use memset().
/*
	for (uint32_t i = 0; i < hash_size_sum; ++i)
		mf->hash[i] = EMPTY_HASH_VALUE;
*/
	memzero(mf->hash, (size_t)(mf->hash_size_sum) * sizeof(uint32_t));

	// We don't need to initialize mf->son, but not doing that will
	// make Valgrind complain in normalization (see normalize() in
	// lz_encoder_mf.c).
	//
	// Skipping this initialization is *very* good when big dictionary is
	// used but only small amount of data gets actually compressed: most
	// of the mf->hash won't get actually allocated by the kernel, so
	// we avoid wasting RAM and improve initialization speed a lot.
	//memzero(mf->son, (size_t)(mf->sons_count) * sizeof(uint32_t));

	mf->action = LZMA_RUN;

	return false;
}


extern uint64_t
lzma_lz_encoder_memusage(const lzma_lz_options *lz_options)
{
	// Old buffers must not exist when calling lz_encoder_prepare().
	lzma_mf mf = {
		.buffer = NULL,
		.hash = NULL,
	};

	// Setup the size information into mf.
	if (lz_encoder_prepare(&mf, NULL, lz_options))
		return UINT64_MAX;

	// Calculate the memory usage.
	return (uint64_t)(mf.hash_size_sum + mf.sons_count)
				* sizeof(uint32_t)
			+ (uint64_t)(mf.size) + sizeof(lzma_coder);
}


static void
lz_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
{
	lzma_next_end(&coder->next, allocator);

	lzma_free(coder->mf.hash, allocator);
	lzma_free(coder->mf.buffer, allocator);

	if (coder->lz.end != NULL)
		coder->lz.end(coder->lz.coder, allocator);
	else
		lzma_free(coder->lz.coder, allocator);

	lzma_free(coder, allocator);
	return;
}


extern lzma_ret
lzma_lz_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
		const lzma_filter_info *filters,
		lzma_ret (*lz_init)(lzma_lz_encoder *lz,
			lzma_allocator *allocator, const void *options,
			lzma_lz_options *lz_options))
{
	// Allocate and initialize the base data structure.
	if (next->coder == NULL) {
		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
		if (next->coder == NULL)
			return LZMA_MEM_ERROR;

		next->code = &lz_encode;
		next->end = &lz_encoder_end;

		next->coder->lz.coder = NULL;
		next->coder->lz.code = NULL;
		next->coder->lz.end = NULL;

		next->coder->mf.buffer = NULL;
		next->coder->mf.hash = NULL;

		next->coder->next = LZMA_NEXT_CODER_INIT;
	}

	// Initialize the LZ-based encoder.
	lzma_lz_options lz_options;
	return_if_error(lz_init(&next->coder->lz, allocator,
			filters[0].options, &lz_options));

	// Setup the size information into next->coder->mf and deallocate
	// old buffers if they have wrong size.
	if (lz_encoder_prepare(&next->coder->mf, allocator, &lz_options))
		return LZMA_HEADER_ERROR;

	// Allocate new buffers if needed, and do the rest of
	// the initialization.
	if (lz_encoder_init(&next->coder->mf, allocator))
		return LZMA_MEM_ERROR;

	// Initialize the next filter in the chain, if any.
	return lzma_next_filter_init(&next->coder->next, allocator,
			filters + 1);
}


extern LZMA_API lzma_bool
lzma_mf_is_supported(lzma_match_finder mf)
{
	bool ret = false;

#ifdef HAVE_MF_HC3
	if (mf == LZMA_MF_HC3)
		ret = true;
#endif

#ifdef HAVE_MF_HC4
	if (mf == LZMA_MF_HC4)
		ret = true;
#endif

#ifdef HAVE_MF_BT2
	if (mf == LZMA_MF_BT2)
		ret = true;
#endif

#ifdef HAVE_MF_BT3
	if (mf == LZMA_MF_BT3)
		ret = true;
#endif

#ifdef HAVE_MF_BT4
	if (mf == LZMA_MF_BT4)
		ret = true;
#endif

	return ret;
}