1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Compresses or uncompresses a file
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
16 enum operation_mode opt_mode = MODE_COMPRESS;
18 enum format_type opt_format = FORMAT_AUTO;
21 /// Stream used to communicate with liblzma
22 static lzma_stream strm = LZMA_STREAM_INIT;
24 /// Filters needed for all encoding all formats, and also decoding in raw data
25 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
27 /// Number of filters. Zero indicates that we are using a preset.
28 static size_t filters_count = 0;
30 /// Number of the preset (0-9)
31 static size_t preset_number = 6;
33 /// True if we should auto-adjust the compression settings to use less memory
34 /// if memory usage limit is too low for the original settings.
35 static bool auto_adjust = true;
37 /// Indicate if no preset has been explicitly given. In that case, if we need
38 /// to auto-adjust for lower memory usage, we won't print a warning.
39 static bool preset_default = true;
41 /// If a preset is used (no custom filter chain) and preset_extreme is true,
42 /// a significantly slower compression is used to achieve slightly better
43 /// compression ratio.
44 static bool preset_extreme = false;
46 /// Integrity check type
47 #ifdef HAVE_CHECK_CRC64
48 static lzma_check check = LZMA_CHECK_CRC64;
50 static lzma_check check = LZMA_CHECK_CRC32;
55 coder_set_check(lzma_check new_check)
63 coder_set_preset(size_t new_preset)
65 preset_number = new_preset;
66 preset_default = false;
72 coder_set_extreme(void)
74 preset_extreme = true;
80 coder_add_filter(lzma_vli id, void *options)
82 if (filters_count == LZMA_FILTERS_MAX)
83 message_fatal(_("Maximum number of filters is four"));
85 filters[filters_count].id = id;
86 filters[filters_count].options = options;
93 static void lzma_attribute((noreturn))
94 memlimit_too_small(uint64_t memory_usage, uint64_t memory_limit)
96 message_fatal(_("Memory usage limit (%" PRIu64 " MiB) is too small "
97 "for the given filter setup (%" PRIu64 " MiB)"),
98 memory_limit >> 20, memory_usage >> 20);
103 coder_set_compression_settings(void)
105 // Options for LZMA1 or LZMA2 in case we are using a preset.
106 static lzma_options_lzma opt_lzma;
108 if (filters_count == 0) {
109 // We are using a preset. This is not a good idea in raw mode
110 // except when playing around with things. Different versions
111 // of this software may use different options in presets, and
112 // thus make uncompressing the raw data difficult.
113 if (opt_format == FORMAT_RAW) {
114 // The message is shown only if warnings are allowed
115 // but the exit status isn't changed.
116 message(V_WARNING, _("Using a preset in raw mode "
118 message(V_WARNING, _("The exact options of the "
119 "presets may vary between software "
123 // Get the preset for LZMA1 or LZMA2.
125 preset_number |= LZMA_PRESET_EXTREME;
127 if (lzma_lzma_preset(&opt_lzma, preset_number))
130 // Use LZMA2 except with --format=lzma we use LZMA1.
131 filters[0].id = opt_format == FORMAT_LZMA
132 ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
133 filters[0].options = &opt_lzma;
136 preset_default = false;
139 // Terminate the filter options array.
140 filters[filters_count].id = LZMA_VLI_UNKNOWN;
142 // If we are using the LZMA_Alone format, allow exactly one filter
143 // which has to be LZMA.
144 if (opt_format == FORMAT_LZMA && (filters_count != 1
145 || filters[0].id != LZMA_FILTER_LZMA1))
146 message_fatal(_("With --format=lzma only the LZMA1 filter "
149 // Print the selected filter chain.
150 message_filters(V_DEBUG, filters);
152 // If using --format=raw, we can be decoding. The memusage function
153 // also validates the filter chain and the options used for the
155 const uint64_t memory_limit = hardware_memlimit_get();
156 uint64_t memory_usage;
157 if (opt_mode == MODE_COMPRESS)
158 memory_usage = lzma_raw_encoder_memusage(filters);
160 memory_usage = lzma_raw_decoder_memusage(filters);
162 if (memory_usage == UINT64_MAX)
163 message_fatal("Unsupported filter chain or filter options");
165 // Print memory usage info.
166 message(V_DEBUG, _("%s MiB (%s B) of memory is required per thread, "
167 "limit is %s MiB (%s B)"),
168 uint64_to_str(memory_usage >> 20, 0),
169 uint64_to_str(memory_usage, 1),
170 uint64_to_str(memory_limit >> 20, 2),
171 uint64_to_str(memory_limit, 3));
173 if (memory_usage > memory_limit) {
174 // If --no-auto-adjust was used or we didn't find LZMA1 or
175 // LZMA2 as the last filter, give an error immediatelly.
176 // --format=raw implies --no-auto-adjust.
177 if (!auto_adjust || opt_format == FORMAT_RAW)
178 memlimit_too_small(memory_usage, memory_limit);
180 assert(opt_mode == MODE_COMPRESS);
182 // Look for the last filter if it is LZMA2 or LZMA1, so
183 // we can make it use less RAM. With other filters we don't
186 while (filters[i].id != LZMA_FILTER_LZMA2
187 && filters[i].id != LZMA_FILTER_LZMA1) {
188 if (filters[i].id == LZMA_VLI_UNKNOWN)
189 memlimit_too_small(memory_usage, memory_limit);
194 // Decrease the dictionary size until we meet the memory
195 // usage limit. First round down to full mebibytes.
196 lzma_options_lzma *opt = filters[i].options;
197 const uint32_t orig_dict_size = opt->dict_size;
198 opt->dict_size &= ~((UINT32_C(1) << 20) - 1);
200 // If it is below 1 MiB, auto-adjusting failed. We
201 // could be more sophisticated and scale it down even
202 // more, but let's see if many complain about this
205 // FIXME: Displays the scaled memory usage instead
207 if (opt->dict_size < (UINT32_C(1) << 20))
208 memlimit_too_small(memory_usage, memory_limit);
210 memory_usage = lzma_raw_encoder_memusage(filters);
211 if (memory_usage == UINT64_MAX)
214 // Accept it if it is low enough.
215 if (memory_usage <= memory_limit)
218 // Otherwise 1 MiB down and try again. I hope this
219 // isn't too slow method for cases where the original
220 // dict_size is very big.
221 opt->dict_size -= UINT32_C(1) << 20;
224 // Tell the user that we decreased the dictionary size.
225 // However, omit the message if no preset or custom chain
226 // was given. FIXME: Always warn?
228 message(V_WARNING, "Adjusted LZMA%c dictionary size "
229 "from %s MiB to %s MiB to not exceed "
230 "the memory usage limit of %s MiB",
231 filters[i].id == LZMA_FILTER_LZMA2
233 uint64_to_str(orig_dict_size >> 20, 0),
234 uint64_to_str(opt->dict_size >> 20, 1),
235 uint64_to_str(memory_limit >> 20, 2));
239 // Limit the number of worker threads so that memory usage
240 // limit isn't exceeded.
241 assert(memory_usage > 0);
242 size_t thread_limit = memory_limit / memory_usage;
243 if (thread_limit == 0)
246 if (opt_threads > thread_limit)
247 opt_threads = thread_limit;
257 lzma_ret ret = LZMA_PROG_ERROR;
259 if (opt_mode == MODE_COMPRESS) {
260 switch (opt_format) {
262 // args.c ensures this.
267 ret = lzma_stream_encoder(&strm, filters, check);
271 ret = lzma_alone_encoder(&strm, filters[0].options);
275 ret = lzma_raw_encoder(&strm, filters);
279 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
282 switch (opt_format) {
284 ret = lzma_auto_decoder(&strm,
285 hardware_memlimit_get(), flags);
289 ret = lzma_stream_decoder(&strm,
290 hardware_memlimit_get(), flags);
294 ret = lzma_alone_decoder(&strm,
295 hardware_memlimit_get());
299 // Memory usage has already been checked in
300 // coder_set_compression_settings().
301 ret = lzma_raw_decoder(&strm, filters);
306 if (ret != LZMA_OK) {
307 if (ret == LZMA_MEM_ERROR)
308 message_error("%s", message_strm(LZMA_MEM_ERROR));
320 coder_main(file_pair *pair)
322 // Buffers to hold input and output data.
323 uint8_t in_buf[IO_BUFFER_SIZE];
324 uint8_t out_buf[IO_BUFFER_SIZE];
326 // Initialize the progress indicator.
327 const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
328 ? 0 : (uint64_t)(pair->src_st.st_size);
329 message_progress_start(&strm, pair->src_name, in_size);
331 lzma_action action = LZMA_RUN;
333 bool success = false; // Assume that something goes wrong.
336 strm.next_out = out_buf;
337 strm.avail_out = IO_BUFFER_SIZE;
339 while (!user_abort) {
340 // Fill the input buffer if it is empty and we haven't reached
342 if (strm.avail_in == 0 && !pair->src_eof) {
343 strm.next_in = in_buf;
344 strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
346 if (strm.avail_in == SIZE_MAX)
349 // Encoder needs to know when we have given all the
350 // input to it. The decoders need to know it too when
351 // we are using LZMA_CONCATENATED.
353 action = LZMA_FINISH;
356 // Let liblzma do the actual work.
357 ret = lzma_code(&strm, action);
359 // Write out if the output buffer became full.
360 if (strm.avail_out == 0) {
361 if (opt_mode != MODE_TEST && io_write(pair, out_buf,
362 IO_BUFFER_SIZE - strm.avail_out))
365 strm.next_out = out_buf;
366 strm.avail_out = IO_BUFFER_SIZE;
369 if (ret != LZMA_OK) {
370 // Determine if the return value indicates that we
371 // won't continue coding.
372 const bool stop = ret != LZMA_NO_CHECK
373 && ret != LZMA_UNSUPPORTED_CHECK;
376 // Write the remaining bytes even if something
377 // went wrong, because that way the user gets
378 // as much data as possible, which can be good
379 // when trying to get at least some useful
380 // data out of damaged files.
381 if (opt_mode != MODE_TEST && io_write(pair,
382 out_buf, IO_BUFFER_SIZE
387 if (ret == LZMA_STREAM_END) {
388 // Check that there is no trailing garbage.
389 // This is needed for LZMA_Alone and raw
391 if (strm.avail_in == 0 && !pair->src_eof) {
392 // Try reading one more byte.
393 // Hopefully we don't get any more
394 // input, and thus pair->src_eof
396 strm.avail_in = io_read(
398 if (strm.avail_in == SIZE_MAX)
401 assert(strm.avail_in == 0
402 || strm.avail_in == 1);
405 if (strm.avail_in == 0) {
406 assert(pair->src_eof);
411 // We hadn't reached the end of the file.
412 ret = LZMA_DATA_ERROR;
416 // If we get here and stop is true, something went
417 // wrong and we print an error. Otherwise it's just
418 // a warning and coding can continue.
420 message_error("%s: %s", pair->src_name,
423 message_warning("%s: %s", pair->src_name,
426 // When compressing, all possible errors set
428 assert(opt_mode != MODE_COMPRESS);
431 if (ret == LZMA_MEMLIMIT_ERROR) {
432 // Figure out how much memory it would have
434 uint64_t memusage = lzma_memusage(&strm);
435 uint64_t memlimit = hardware_memlimit_get();
437 // Round the memory limit down and usage up.
438 // This way we don't display a ridiculous
439 // message like "Limit was 9 MiB, but 9 MiB
440 // would have been needed".
441 memusage = (memusage + 1024 * 1024 - 1)
443 memlimit /= 1024 * 1024;
445 message_error(_("Limit was %s MiB, "
448 uint64_to_str(memlimit, 0),
449 uint64_to_str(memusage, 1));
456 // Show progress information under certain conditions.
457 message_progress_update();
460 message_progress_end(success);
467 coder_run(const char *filename)
469 // First try initializing the coder. If it fails, it's useless to try
470 // opening the file. Check also for user_abort just in case if we had
471 // got a signal while initializing the coder.
472 if (coder_init() || user_abort)
475 // Try to open the input and output files.
476 file_pair *pair = io_open(filename);
480 // Do the actual coding.
481 const bool success = coder_main(pair);
483 // Close the file pair. It needs to know if coding was successful to
484 // know if the source or target file should be unlinked.
485 io_close(pair, success);