1207753Smm///////////////////////////////////////////////////////////////////////////////
2207753Smm//
3207753Smm/// \file       lzma2_encoder.c
4207753Smm/// \brief      LZMA2 encoder
5207753Smm///
6207753Smm//  Authors:    Igor Pavlov
7207753Smm//              Lasse Collin
8207753Smm//
9207753Smm//  This file has been put into the public domain.
10207753Smm//  You can do whatever you want with this file.
11207753Smm//
12207753Smm///////////////////////////////////////////////////////////////////////////////
13207753Smm
14207753Smm#include "lz_encoder.h"
15207753Smm#include "lzma_encoder.h"
16207753Smm#include "fastpos.h"
17207753Smm#include "lzma2_encoder.h"
18207753Smm
19207753Smm
20207753Smmstruct lzma_coder_s {
21207753Smm	enum {
22207753Smm		SEQ_INIT,
23207753Smm		SEQ_LZMA_ENCODE,
24207753Smm		SEQ_LZMA_COPY,
25207753Smm		SEQ_UNCOMPRESSED_HEADER,
26207753Smm		SEQ_UNCOMPRESSED_COPY,
27207753Smm	} sequence;
28207753Smm
29207753Smm	/// LZMA encoder
30207753Smm	lzma_coder *lzma;
31207753Smm
32207753Smm	/// LZMA options currently in use.
33207753Smm	lzma_options_lzma opt_cur;
34207753Smm
35207753Smm	bool need_properties;
36207753Smm	bool need_state_reset;
37207753Smm	bool need_dictionary_reset;
38207753Smm
39207753Smm	/// Uncompressed size of a chunk
40207753Smm	size_t uncompressed_size;
41207753Smm
42207753Smm	/// Compressed size of a chunk (excluding headers); this is also used
43207753Smm	/// to indicate the end of buf[] in SEQ_LZMA_COPY.
44207753Smm	size_t compressed_size;
45207753Smm
46207753Smm	/// Read position in buf[]
47207753Smm	size_t buf_pos;
48207753Smm
49207753Smm	/// Buffer to hold the chunk header and LZMA compressed data
50207753Smm	uint8_t buf[LZMA2_HEADER_MAX + LZMA2_CHUNK_MAX];
51207753Smm};
52207753Smm
53207753Smm
54207753Smmstatic void
55207753Smmlzma2_header_lzma(lzma_coder *coder)
56207753Smm{
57207753Smm	assert(coder->uncompressed_size > 0);
58207753Smm	assert(coder->uncompressed_size <= LZMA2_UNCOMPRESSED_MAX);
59207753Smm	assert(coder->compressed_size > 0);
60207753Smm	assert(coder->compressed_size <= LZMA2_CHUNK_MAX);
61207753Smm
62207753Smm	size_t pos;
63207753Smm
64207753Smm	if (coder->need_properties) {
65207753Smm		pos = 0;
66207753Smm
67207753Smm		if (coder->need_dictionary_reset)
68207753Smm			coder->buf[pos] = 0x80 + (3 << 5);
69207753Smm		else
70207753Smm			coder->buf[pos] = 0x80 + (2 << 5);
71207753Smm	} else {
72207753Smm		pos = 1;
73207753Smm
74207753Smm		if (coder->need_state_reset)
75207753Smm			coder->buf[pos] = 0x80 + (1 << 5);
76207753Smm		else
77207753Smm			coder->buf[pos] = 0x80;
78207753Smm	}
79207753Smm
80207753Smm	// Set the start position for copying.
81207753Smm	coder->buf_pos = pos;
82207753Smm
83207753Smm	// Uncompressed size
84207753Smm	size_t size = coder->uncompressed_size - 1;
85207753Smm	coder->buf[pos++] += size >> 16;
86207753Smm	coder->buf[pos++] = (size >> 8) & 0xFF;
87207753Smm	coder->buf[pos++] = size & 0xFF;
88207753Smm
89207753Smm	// Compressed size
90207753Smm	size = coder->compressed_size - 1;
91207753Smm	coder->buf[pos++] = size >> 8;
92207753Smm	coder->buf[pos++] = size & 0xFF;
93207753Smm
94207753Smm	// Properties, if needed
95207753Smm	if (coder->need_properties)
96207753Smm		lzma_lzma_lclppb_encode(&coder->opt_cur, coder->buf + pos);
97207753Smm
98207753Smm	coder->need_properties = false;
99207753Smm	coder->need_state_reset = false;
100207753Smm	coder->need_dictionary_reset = false;
101207753Smm
102207753Smm	// The copying code uses coder->compressed_size to indicate the end
103207753Smm	// of coder->buf[], so we need add the maximum size of the header here.
104207753Smm	coder->compressed_size += LZMA2_HEADER_MAX;
105207753Smm
106207753Smm	return;
107207753Smm}
108207753Smm
109207753Smm
110207753Smmstatic void
111207753Smmlzma2_header_uncompressed(lzma_coder *coder)
112207753Smm{
113207753Smm	assert(coder->uncompressed_size > 0);
114207753Smm	assert(coder->uncompressed_size <= LZMA2_CHUNK_MAX);
115207753Smm
116207753Smm	// If this is the first chunk, we need to include dictionary
117207753Smm	// reset indicator.
118207753Smm	if (coder->need_dictionary_reset)
119207753Smm		coder->buf[0] = 1;
120207753Smm	else
121207753Smm		coder->buf[0] = 2;
122207753Smm
123207753Smm	coder->need_dictionary_reset = false;
124207753Smm
125207753Smm	// "Compressed" size
126207753Smm	coder->buf[1] = (coder->uncompressed_size - 1) >> 8;
127207753Smm	coder->buf[2] = (coder->uncompressed_size - 1) & 0xFF;
128207753Smm
129207753Smm	// Set the start position for copying.
130207753Smm	coder->buf_pos = 0;
131207753Smm	return;
132207753Smm}
133207753Smm
134207753Smm
135207753Smmstatic lzma_ret
136207753Smmlzma2_encode(lzma_coder *restrict coder, lzma_mf *restrict mf,
137207753Smm		uint8_t *restrict out, size_t *restrict out_pos,
138207753Smm		size_t out_size)
139207753Smm{
140207753Smm	while (*out_pos < out_size)
141207753Smm	switch (coder->sequence) {
142207753Smm	case SEQ_INIT:
143207753Smm		// If there's no input left and we are flushing or finishing,
144207753Smm		// don't start a new chunk.
145207753Smm		if (mf_unencoded(mf) == 0) {
146207753Smm			// Write end of payload marker if finishing.
147207753Smm			if (mf->action == LZMA_FINISH)
148207753Smm				out[(*out_pos)++] = 0;
149207753Smm
150207753Smm			return mf->action == LZMA_RUN
151207753Smm					? LZMA_OK : LZMA_STREAM_END;
152207753Smm		}
153207753Smm
154207753Smm		if (coder->need_state_reset)
155207753Smm			return_if_error(lzma_lzma_encoder_reset(
156207753Smm					coder->lzma, &coder->opt_cur));
157207753Smm
158207753Smm		coder->uncompressed_size = 0;
159207753Smm		coder->compressed_size = 0;
160207753Smm		coder->sequence = SEQ_LZMA_ENCODE;
161207753Smm
162207753Smm	// Fall through
163207753Smm
164207753Smm	case SEQ_LZMA_ENCODE: {
165207753Smm		// Calculate how much more uncompressed data this chunk
166207753Smm		// could accept.
167207753Smm		const uint32_t left = LZMA2_UNCOMPRESSED_MAX
168207753Smm				- coder->uncompressed_size;
169207753Smm		uint32_t limit;
170207753Smm
171207753Smm		if (left < mf->match_len_max) {
172207753Smm			// Must flush immediately since the next LZMA symbol
173207753Smm			// could make the uncompressed size of the chunk too
174207753Smm			// big.
175207753Smm			limit = 0;
176207753Smm		} else {
177207753Smm			// Calculate maximum read_limit that is OK from point
178207753Smm			// of view of LZMA2 chunk size.
179207753Smm			limit = mf->read_pos - mf->read_ahead
180207753Smm					+ left - mf->match_len_max;
181207753Smm		}
182207753Smm
183207753Smm		// Save the start position so that we can update
184207753Smm		// coder->uncompressed_size.
185207753Smm		const uint32_t read_start = mf->read_pos - mf->read_ahead;
186207753Smm
187207753Smm		// Call the LZMA encoder until the chunk is finished.
188207753Smm		const lzma_ret ret = lzma_lzma_encode(coder->lzma, mf,
189207753Smm				coder->buf + LZMA2_HEADER_MAX,
190207753Smm				&coder->compressed_size,
191207753Smm				LZMA2_CHUNK_MAX, limit);
192207753Smm
193207753Smm		coder->uncompressed_size += mf->read_pos - mf->read_ahead
194207753Smm				- read_start;
195207753Smm
196207753Smm		assert(coder->compressed_size <= LZMA2_CHUNK_MAX);
197207753Smm		assert(coder->uncompressed_size <= LZMA2_UNCOMPRESSED_MAX);
198207753Smm
199207753Smm		if (ret != LZMA_STREAM_END)
200207753Smm			return LZMA_OK;
201207753Smm
202207753Smm		// See if the chunk compressed. If it didn't, we encode it
203207753Smm		// as uncompressed chunk. This saves a few bytes of space
204207753Smm		// and makes decoding faster.
205207753Smm		if (coder->compressed_size >= coder->uncompressed_size) {
206207753Smm			coder->uncompressed_size += mf->read_ahead;
207207753Smm			assert(coder->uncompressed_size
208207753Smm					<= LZMA2_UNCOMPRESSED_MAX);
209207753Smm			mf->read_ahead = 0;
210207753Smm			lzma2_header_uncompressed(coder);
211207753Smm			coder->need_state_reset = true;
212207753Smm			coder->sequence = SEQ_UNCOMPRESSED_HEADER;
213207753Smm			break;
214207753Smm		}
215207753Smm
216207753Smm		// The chunk did compress at least by one byte, so we store
217207753Smm		// the chunk as LZMA.
218207753Smm		lzma2_header_lzma(coder);
219207753Smm
220207753Smm		coder->sequence = SEQ_LZMA_COPY;
221207753Smm	}
222207753Smm
223207753Smm	// Fall through
224207753Smm
225207753Smm	case SEQ_LZMA_COPY:
226207753Smm		// Copy the compressed chunk along its headers to the
227207753Smm		// output buffer.
228207753Smm		lzma_bufcpy(coder->buf, &coder->buf_pos,
229207753Smm				coder->compressed_size,
230207753Smm				out, out_pos, out_size);
231207753Smm		if (coder->buf_pos != coder->compressed_size)
232207753Smm			return LZMA_OK;
233207753Smm
234207753Smm		coder->sequence = SEQ_INIT;
235207753Smm		break;
236207753Smm
237207753Smm	case SEQ_UNCOMPRESSED_HEADER:
238207753Smm		// Copy the three-byte header to indicate uncompressed chunk.
239207753Smm		lzma_bufcpy(coder->buf, &coder->buf_pos,
240207753Smm				LZMA2_HEADER_UNCOMPRESSED,
241207753Smm				out, out_pos, out_size);
242207753Smm		if (coder->buf_pos != LZMA2_HEADER_UNCOMPRESSED)
243207753Smm			return LZMA_OK;
244207753Smm
245207753Smm		coder->sequence = SEQ_UNCOMPRESSED_COPY;
246207753Smm
247207753Smm	// Fall through
248207753Smm
249207753Smm	case SEQ_UNCOMPRESSED_COPY:
250207753Smm		// Copy the uncompressed data as is from the dictionary
251207753Smm		// to the output buffer.
252207753Smm		mf_read(mf, out, out_pos, out_size, &coder->uncompressed_size);
253207753Smm		if (coder->uncompressed_size != 0)
254207753Smm			return LZMA_OK;
255207753Smm
256207753Smm		coder->sequence = SEQ_INIT;
257207753Smm		break;
258207753Smm	}
259207753Smm
260207753Smm	return LZMA_OK;
261207753Smm}
262207753Smm
263207753Smm
264207753Smmstatic void
265207753Smmlzma2_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
266207753Smm{
267207753Smm	lzma_free(coder->lzma, allocator);
268207753Smm	lzma_free(coder, allocator);
269207753Smm	return;
270207753Smm}
271207753Smm
272207753Smm
273207753Smmstatic lzma_ret
274207753Smmlzma2_encoder_options_update(lzma_coder *coder, const lzma_filter *filter)
275207753Smm{
276207753Smm	// New options can be set only when there is no incomplete chunk.
277207753Smm	// This is the case at the beginning of the raw stream and right
278207753Smm	// after LZMA_SYNC_FLUSH.
279207753Smm	if (filter->options == NULL || coder->sequence != SEQ_INIT)
280207753Smm		return LZMA_PROG_ERROR;
281207753Smm
282207753Smm	// Look if there are new options. At least for now,
283207753Smm	// only lc/lp/pb can be changed.
284207753Smm	const lzma_options_lzma *opt = filter->options;
285207753Smm	if (coder->opt_cur.lc != opt->lc || coder->opt_cur.lp != opt->lp
286207753Smm			|| coder->opt_cur.pb != opt->pb) {
287207753Smm		// Validate the options.
288207753Smm		if (opt->lc > LZMA_LCLP_MAX || opt->lp > LZMA_LCLP_MAX
289207753Smm				|| opt->lc + opt->lp > LZMA_LCLP_MAX
290207753Smm				|| opt->pb > LZMA_PB_MAX)
291207753Smm			return LZMA_OPTIONS_ERROR;
292207753Smm
293207753Smm		// The new options will be used when the encoder starts
294207753Smm		// a new LZMA2 chunk.
295207753Smm		coder->opt_cur.lc = opt->lc;
296207753Smm		coder->opt_cur.lp = opt->lp;
297207753Smm		coder->opt_cur.pb = opt->pb;
298207753Smm		coder->need_properties = true;
299207753Smm		coder->need_state_reset = true;
300207753Smm	}
301207753Smm
302207753Smm	return LZMA_OK;
303207753Smm}
304207753Smm
305207753Smm
306207753Smmstatic lzma_ret
307207753Smmlzma2_encoder_init(lzma_lz_encoder *lz, lzma_allocator *allocator,
308207753Smm		const void *options, lzma_lz_options *lz_options)
309207753Smm{
310207753Smm	if (options == NULL)
311207753Smm		return LZMA_PROG_ERROR;
312207753Smm
313207753Smm	if (lz->coder == NULL) {
314207753Smm		lz->coder = lzma_alloc(sizeof(lzma_coder), allocator);
315207753Smm		if (lz->coder == NULL)
316207753Smm			return LZMA_MEM_ERROR;
317207753Smm
318207753Smm		lz->code = &lzma2_encode;
319207753Smm		lz->end = &lzma2_encoder_end;
320207753Smm		lz->options_update = &lzma2_encoder_options_update;
321207753Smm
322207753Smm		lz->coder->lzma = NULL;
323207753Smm	}
324207753Smm
325207753Smm	lz->coder->opt_cur = *(const lzma_options_lzma *)(options);
326207753Smm
327207753Smm	lz->coder->sequence = SEQ_INIT;
328207753Smm	lz->coder->need_properties = true;
329207753Smm	lz->coder->need_state_reset = false;
330207753Smm	lz->coder->need_dictionary_reset
331207753Smm			= lz->coder->opt_cur.preset_dict == NULL
332207753Smm			|| lz->coder->opt_cur.preset_dict_size == 0;
333207753Smm
334207753Smm	// Initialize LZMA encoder
335207753Smm	return_if_error(lzma_lzma_encoder_create(&lz->coder->lzma, allocator,
336207753Smm			&lz->coder->opt_cur, lz_options));
337207753Smm
338207753Smm	// Make sure that we will always have enough history available in
339207753Smm	// case we need to use uncompressed chunks. They are used when the
340207753Smm	// compressed size of a chunk is not smaller than the uncompressed
341207753Smm	// size, so we need to have at least LZMA2_COMPRESSED_MAX bytes
342207753Smm	// history available.
343207753Smm	if (lz_options->before_size + lz_options->dict_size < LZMA2_CHUNK_MAX)
344207753Smm		lz_options->before_size
345207753Smm				= LZMA2_CHUNK_MAX - lz_options->dict_size;
346207753Smm
347207753Smm	return LZMA_OK;
348207753Smm}
349207753Smm
350207753Smm
351207753Smmextern lzma_ret
352207753Smmlzma_lzma2_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
353207753Smm		const lzma_filter_info *filters)
354207753Smm{
355207753Smm	return lzma_lz_encoder_init(
356207753Smm			next, allocator, filters, &lzma2_encoder_init);
357207753Smm}
358207753Smm
359207753Smm
360207753Smmextern uint64_t
361207753Smmlzma_lzma2_encoder_memusage(const void *options)
362207753Smm{
363207753Smm	const uint64_t lzma_mem = lzma_lzma_encoder_memusage(options);
364207753Smm	if (lzma_mem == UINT64_MAX)
365207753Smm		return UINT64_MAX;
366207753Smm
367207753Smm	return sizeof(lzma_coder) + lzma_mem;
368207753Smm}
369207753Smm
370207753Smm
371207753Smmextern lzma_ret
372207753Smmlzma_lzma2_props_encode(const void *options, uint8_t *out)
373207753Smm{
374207753Smm	const lzma_options_lzma *const opt = options;
375213700Smm	uint32_t d = my_max(opt->dict_size, LZMA_DICT_SIZE_MIN);
376207753Smm
377223935Smm	// Round up to the next 2^n - 1 or 2^n + 2^(n - 1) - 1 depending
378207753Smm	// on which one is the next:
379207753Smm	--d;
380207753Smm	d |= d >> 2;
381207753Smm	d |= d >> 3;
382207753Smm	d |= d >> 4;
383207753Smm	d |= d >> 8;
384207753Smm	d |= d >> 16;
385207753Smm
386207753Smm	// Get the highest two bits using the proper encoding:
387207753Smm	if (d == UINT32_MAX)
388207753Smm		out[0] = 40;
389207753Smm	else
390207753Smm		out[0] = get_pos_slot(d + 1) - 24;
391207753Smm
392207753Smm	return LZMA_OK;
393207753Smm}
394