]> icculus.org git repositories - icculus/xz.git/blob - src/xz/process.c
Move some LZMA2 constants to lzma2_encoder.h so that they
[icculus/xz.git] / src / xz / process.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       process.c
4 /// \brief      Compresses or uncompresses a file
5 //
6 //  Copyright (C) 2007 Lasse Collin
7 //
8 //  This program is free software; you can redistribute it and/or
9 //  modify it under the terms of the GNU Lesser General Public
10 //  License as published by the Free Software Foundation; either
11 //  version 2.1 of the License, or (at your option) any later version.
12 //
13 //  This program is distributed in the hope that it will be useful,
14 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 //  Lesser General Public License for more details.
17 //
18 ///////////////////////////////////////////////////////////////////////////////
19
20 #include "private.h"
21
22
23 enum operation_mode opt_mode = MODE_COMPRESS;
24
25 enum format_type opt_format = FORMAT_AUTO;
26
27
28 /// Stream used to communicate with liblzma
29 static lzma_stream strm = LZMA_STREAM_INIT;
30
31 /// Filters needed for all encoding all formats, and also decoding in raw data
32 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
33
34 /// Number of filters. Zero indicates that we are using a preset.
35 static size_t filters_count = 0;
36
37 /// Number of the preset (0-9)
38 static size_t preset_number = 6;
39
40 /// True if we should auto-adjust the compression settings to use less memory
41 /// if memory usage limit is too low for the original settings.
42 static bool auto_adjust = true;
43
44 /// Indicate if no preset has been explicitly given. In that case, if we need
45 /// to auto-adjust for lower memory usage, we won't print a warning.
46 static bool preset_default = true;
47
48 /// If a preset is used (no custom filter chain) and preset_extreme is true,
49 /// a significantly slower compression is used to achieve slightly better
50 /// compression ratio.
51 static bool preset_extreme = false;
52
53 /// Integrity check type
54 static lzma_check check = LZMA_CHECK_CRC64;
55
56
57 extern void
58 coder_set_check(lzma_check new_check)
59 {
60         check = new_check;
61         return;
62 }
63
64
65 extern void
66 coder_set_preset(size_t new_preset)
67 {
68         preset_number = new_preset;
69         preset_default = false;
70         return;
71 }
72
73
74 extern void
75 coder_set_extreme(void)
76 {
77         preset_extreme = true;
78         return;
79 }
80
81
82 extern void
83 coder_add_filter(lzma_vli id, void *options)
84 {
85         if (filters_count == LZMA_FILTERS_MAX)
86                 message_fatal(_("Maximum number of filters is four"));
87
88         filters[filters_count].id = id;
89         filters[filters_count].options = options;
90         ++filters_count;
91
92         return;
93 }
94
95
96 static void lzma_attribute((noreturn))
97 memlimit_too_small(uint64_t memory_usage, uint64_t memory_limit)
98 {
99         message_fatal(_("Memory usage limit (%" PRIu64 " MiB) is too small "
100                         "for the given filter setup (%" PRIu64 " MiB)"),
101                         memory_limit >> 20, memory_usage >> 20);
102 }
103
104
105 extern void
106 coder_set_compression_settings(void)
107 {
108         // Options for LZMA1 or LZMA2 in case we are using a preset.
109         static lzma_options_lzma opt_lzma;
110
111         if (filters_count == 0) {
112                 // We are using a preset. This is not a good idea in raw mode
113                 // except when playing around with things. Different versions
114                 // of this software may use different options in presets, and
115                 // thus make uncompressing the raw data difficult.
116                 if (opt_format == FORMAT_RAW) {
117                         // The message is shown only if warnings are allowed
118                         // but the exit status isn't changed.
119                         message(V_WARNING, _("Using a preset in raw mode "
120                                         "is discouraged."));
121                         message(V_WARNING, _("The exact options of the "
122                                         "presets may vary between software "
123                                         "versions."));
124                 }
125
126                 // Get the preset for LZMA1 or LZMA2.
127                 if (preset_extreme)
128                         preset_number |= LZMA_PRESET_EXTREME;
129
130                 if (lzma_lzma_preset(&opt_lzma, preset_number))
131                         message_bug();
132
133                 // Use LZMA2 except with --format=lzma we use LZMA1.
134                 filters[0].id = opt_format == FORMAT_LZMA
135                                 ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
136                 filters[0].options = &opt_lzma;
137                 filters_count = 1;
138         } else {
139                 preset_default = false;
140         }
141
142         // Terminate the filter options array.
143         filters[filters_count].id = LZMA_VLI_UNKNOWN;
144
145         // If we are using the LZMA_Alone format, allow exactly one filter
146         // which has to be LZMA.
147         if (opt_format == FORMAT_LZMA && (filters_count != 1
148                         || filters[0].id != LZMA_FILTER_LZMA1))
149                 message_fatal(_("With --format=lzma only the LZMA1 filter "
150                                 "is supported"));
151
152         // Print the selected filter chain.
153         message_filters(V_DEBUG, filters);
154
155         // If using --format=raw, we can be decoding. The memusage function
156         // also validates the filter chain and the options used for the
157         // filters.
158         uint64_t memory_usage;
159         uint64_t memory_limit;
160         if (opt_mode == MODE_COMPRESS) {
161                 memory_usage = lzma_raw_encoder_memusage(filters);
162                 memory_limit = hardware_memlimit_encoder();
163         } else {
164                 memory_usage = lzma_raw_decoder_memusage(filters);
165                 memory_limit = hardware_memlimit_decoder();
166         }
167
168         if (memory_usage == UINT64_MAX)
169                 message_fatal("Unsupported filter chain or filter options");
170
171         // Print memory usage info.
172         message(V_DEBUG, _("%'" PRIu64 " MiB (%'" PRIu64 " B) of memory is "
173                         "required per thread, "
174                         "limit is %'" PRIu64 " MiB (%'" PRIu64 " B)"),
175                         memory_usage >> 20, memory_usage,
176                         memory_limit >> 20, memory_limit);
177
178         if (memory_usage > memory_limit) {
179                 // If --no-auto-adjust was used or we didn't find LZMA1 or
180                 // LZMA2 as the last filter, give an error immediatelly.
181                 // --format=raw implies --no-auto-adjust.
182                 if (!auto_adjust || opt_format == FORMAT_RAW)
183                         memlimit_too_small(memory_usage, memory_limit);
184
185                 assert(opt_mode == MODE_COMPRESS);
186
187                 // Look for the last filter if it is LZMA2 or LZMA1, so
188                 // we can make it use less RAM. With other filters we don't
189                 // know what to do.
190                 size_t i = 0;
191                 while (filters[i].id != LZMA_FILTER_LZMA2
192                                 && filters[i].id != LZMA_FILTER_LZMA1) {
193                         if (filters[i].id == LZMA_VLI_UNKNOWN)
194                                 memlimit_too_small(memory_usage, memory_limit);
195
196                         ++i;
197                 }
198
199                 // Decrease the dictionary size until we meet the memory
200                 // usage limit. First round down to full mebibytes.
201                 lzma_options_lzma *opt = filters[i].options;
202                 const uint32_t orig_dict_size = opt->dict_size;
203                 opt->dict_size &= ~((UINT32_C(1) << 20) - 1);
204                 while (true) {
205                         // If it is below 1 MiB, auto-adjusting failed. We
206                         // could be more sophisticated and scale it down even
207                         // more, but let's see if many complain about this
208                         // version.
209                         //
210                         // FIXME: Displays the scaled memory usage instead
211                         // of the original.
212                         if (opt->dict_size < (UINT32_C(1) << 20))
213                                 memlimit_too_small(memory_usage, memory_limit);
214
215                         memory_usage = lzma_raw_encoder_memusage(filters);
216                         if (memory_usage == UINT64_MAX)
217                                 message_bug();
218
219                         // Accept it if it is low enough.
220                         if (memory_usage <= memory_limit)
221                                 break;
222
223                         // Otherwise 1 MiB down and try again. I hope this
224                         // isn't too slow method for cases where the original
225                         // dict_size is very big.
226                         opt->dict_size -= UINT32_C(1) << 20;
227                 }
228
229                 // Tell the user that we decreased the dictionary size.
230                 // However, omit the message if no preset or custom chain
231                 // was given. FIXME: Always warn?
232                 if (!preset_default)
233                         message(V_WARNING, "Adjusted LZMA%c dictionary size "
234                                         "from %'" PRIu32 " MiB to "
235                                         "%'" PRIu32 " MiB to not exceed "
236                                         "the memory usage limit of "
237                                         "%'" PRIu64 " MiB",
238                                         filters[i].id == LZMA_FILTER_LZMA2
239                                                 ? '2' : '1',
240                                         orig_dict_size >> 20,
241                                         opt->dict_size >> 20,
242                                         memory_limit >> 20);
243         }
244
245         // Limit the number of worker threads so that memory usage
246         // limit isn't exceeded.
247         assert(memory_usage > 0);
248         size_t thread_limit = memory_limit / memory_usage;
249         if (thread_limit == 0)
250                 thread_limit = 1;
251
252         if (opt_threads > thread_limit)
253                 opt_threads = thread_limit;
254
255         return;
256 }
257
258
259 static bool
260 coder_init(void)
261 {
262         lzma_ret ret = LZMA_PROG_ERROR;
263
264         if (opt_mode == MODE_COMPRESS) {
265                 switch (opt_format) {
266                 case FORMAT_AUTO:
267                         // args.c ensures this.
268                         assert(0);
269                         break;
270
271                 case FORMAT_XZ:
272                         ret = lzma_stream_encoder(&strm, filters, check);
273                         break;
274
275                 case FORMAT_LZMA:
276                         ret = lzma_alone_encoder(&strm, filters[0].options);
277                         break;
278
279                 case FORMAT_RAW:
280                         ret = lzma_raw_encoder(&strm, filters);
281                         break;
282                 }
283         } else {
284                 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
285                                 | LZMA_CONCATENATED;
286
287                 switch (opt_format) {
288                 case FORMAT_AUTO:
289                         ret = lzma_auto_decoder(&strm,
290                                         hardware_memlimit_decoder(), flags);
291                         break;
292
293                 case FORMAT_XZ:
294                         ret = lzma_stream_decoder(&strm,
295                                         hardware_memlimit_decoder(), flags);
296                         break;
297
298                 case FORMAT_LZMA:
299                         ret = lzma_alone_decoder(&strm,
300                                         hardware_memlimit_decoder());
301                         break;
302
303                 case FORMAT_RAW:
304                         // Memory usage has already been checked in
305                         // coder_set_compression_settings().
306                         ret = lzma_raw_decoder(&strm, filters);
307                         break;
308                 }
309         }
310
311         if (ret != LZMA_OK) {
312                 if (ret == LZMA_MEM_ERROR)
313                         message_error("%s", message_strm(LZMA_MEM_ERROR));
314                 else
315                         message_bug();
316
317                 return true;
318         }
319
320         return false;
321 }
322
323
324 static bool
325 coder_run(file_pair *pair)
326 {
327         // Buffers to hold input and output data.
328         uint8_t in_buf[IO_BUFFER_SIZE];
329         uint8_t out_buf[IO_BUFFER_SIZE];
330
331         // Initialize the progress indicator.
332         const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
333                         ? 0 : (uint64_t)(pair->src_st.st_size);
334         message_progress_start(pair->src_name, in_size);
335
336         lzma_action action = LZMA_RUN;
337         lzma_ret ret;
338
339         strm.avail_in = 0;
340         strm.next_out = out_buf;
341         strm.avail_out = IO_BUFFER_SIZE;
342
343         while (!user_abort) {
344                 // Fill the input buffer if it is empty and we haven't reached
345                 // end of file yet.
346                 if (strm.avail_in == 0 && !pair->src_eof) {
347                         strm.next_in = in_buf;
348                         strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
349
350                         if (strm.avail_in == SIZE_MAX)
351                                 break;
352
353                         // Encoder needs to know when we have given all the
354                         // input to it. The decoders need to know it too when
355                         // we are using LZMA_CONCATENATED.
356                         if (pair->src_eof)
357                                 action = LZMA_FINISH;
358                 }
359
360                 // Let liblzma do the actual work.
361                 ret = lzma_code(&strm, action);
362
363                 // Write out if the output buffer became full.
364                 if (strm.avail_out == 0) {
365                         if (opt_mode != MODE_TEST && io_write(pair, out_buf,
366                                         IO_BUFFER_SIZE - strm.avail_out))
367                                 return false;
368
369                         strm.next_out = out_buf;
370                         strm.avail_out = IO_BUFFER_SIZE;
371                 }
372
373                 if (ret != LZMA_OK) {
374                         // Determine if the return value indicates that we
375                         // won't continue coding.
376                         const bool stop = ret != LZMA_NO_CHECK
377                                         && ret != LZMA_UNSUPPORTED_CHECK;
378
379                         if (stop) {
380                                 // First print the final progress info.
381                                 // This way the user sees more accurately
382                                 // where the error occurred. Note that we
383                                 // print this *before* the possible error
384                                 // message.
385                                 //
386                                 // FIXME: What if something goes wrong
387                                 // after this?
388                                 message_progress_end(strm.total_in,
389                                                 strm.total_out,
390                                                 ret == LZMA_STREAM_END);
391
392                                 // Write the remaining bytes even if something
393                                 // went wrong, because that way the user gets
394                                 // as much data as possible, which can be good
395                                 // when trying to get at least some useful
396                                 // data out of damaged files.
397                                 if (opt_mode != MODE_TEST && io_write(pair,
398                                                 out_buf, IO_BUFFER_SIZE
399                                                         - strm.avail_out))
400                                         return false;
401                         }
402
403                         if (ret == LZMA_STREAM_END) {
404                                 // Check that there is no trailing garbage.
405                                 // This is needed for LZMA_Alone and raw
406                                 // streams.
407                                 if (strm.avail_in == 0 && (pair->src_eof
408                                                 || io_read(pair, in_buf, 1)
409                                                         == 0)) {
410                                         assert(pair->src_eof);
411                                         return true;
412                                 }
413
414                                 // FIXME: What about io_read() failing?
415
416                                 // We hadn't reached the end of the file.
417                                 ret = LZMA_DATA_ERROR;
418                                 assert(stop);
419                         }
420
421                         // If we get here and stop is true, something went
422                         // wrong and we print an error. Otherwise it's just
423                         // a warning and coding can continue.
424                         if (stop) {
425                                 message_error("%s: %s", pair->src_name,
426                                                 message_strm(ret));
427                         } else {
428                                 message_warning("%s: %s", pair->src_name,
429                                                 message_strm(ret));
430
431                                 // When compressing, all possible errors set
432                                 // stop to true.
433                                 assert(opt_mode != MODE_COMPRESS);
434                         }
435
436                         if (ret == LZMA_MEMLIMIT_ERROR) {
437                                 // Figure out how much memory it would have
438                                 // actually needed.
439                                 uint64_t memusage = lzma_memusage(&strm);
440                                 uint64_t memlimit
441                                                 = hardware_memlimit_decoder();
442
443                                 // Round the memory limit down and usage up.
444                                 // This way we don't display a ridiculous
445                                 // message like "Limit was 9 MiB, but 9 MiB
446                                 // would have been needed".
447                                 memusage = (memusage + 1024 * 1024 - 1)
448                                                 / (1024 * 1024);
449                                 memlimit /= 1024 * 1024;
450
451                                 message_error(_("Limit was %'" PRIu64 " MiB, "
452                                                 "but %'" PRIu64 " MiB would "
453                                                 "have been needed"),
454                                                 memlimit, memusage);
455                         }
456
457                         if (stop)
458                                 return false;
459                 }
460
461                 // Show progress information if --verbose was specified and
462                 // stderr is a terminal.
463                 message_progress_update(strm.total_in, strm.total_out);
464         }
465
466         return false;
467 }
468
469
470 extern void
471 process_file(const char *filename)
472 {
473         // First try initializing the coder. If it fails, it's useless to try
474         // opening the file. Check also for user_abort just in case if we had
475         // got a signal while initializing the coder.
476         if (coder_init() || user_abort)
477                 return;
478
479         // Try to open the input and output files.
480         file_pair *pair = io_open(filename);
481         if (pair == NULL)
482                 return;
483
484         // Do the actual coding.
485         const bool success = coder_run(pair);
486
487         // Close the file pair. It needs to know if coding was successful to
488         // know if the source or target file should be unlinked.
489         io_close(pair, success);
490
491         return;
492 }