1 ///////////////////////////////////////////////////////////////////////////////
4 /// \brief Compresses or uncompresses a file
6 // Copyright (C) 2007 Lasse Collin
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.
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.
18 ///////////////////////////////////////////////////////////////////////////////
23 enum operation_mode opt_mode = MODE_COMPRESS;
25 enum format_type opt_format = FORMAT_AUTO;
28 /// Stream used to communicate with liblzma
29 static lzma_stream strm = LZMA_STREAM_INIT;
31 /// Filters needed for all encoding all formats, and also decoding in raw data
32 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
34 /// Number of filters. Zero indicates that we are using a preset.
35 static size_t filters_count = 0;
37 /// Number of the preset (1-9)
38 static size_t preset_number = 7;
40 /// Indicate if no preset has been given. In that case, we will auto-adjust
41 /// the compression preset so that it doesn't use too much RAM.
43 static bool preset_default = true;
45 /// Integrity check type
46 static lzma_check check = LZMA_CHECK_CRC64;
50 coder_set_check(lzma_check new_check)
58 coder_set_preset(size_t new_preset)
60 preset_number = new_preset;
61 preset_default = false;
67 coder_add_filter(lzma_vli id, void *options)
69 if (filters_count == LZMA_FILTERS_MAX)
70 message_fatal(_("Maximum number of filters is four"));
72 filters[filters_count].id = id;
73 filters[filters_count].options = options;
81 coder_set_compression_settings(void)
83 // Options for LZMA1 or LZMA2 in case we are using a preset.
84 static lzma_options_lzma opt_lzma;
86 if (filters_count == 0) {
87 // We are using a preset. This is not a good idea in raw mode
88 // except when playing around with things. Different versions
89 // of this software may use different options in presets, and
90 // thus make uncompressing the raw data difficult.
91 if (opt_format == FORMAT_RAW) {
92 // The message is shown only if warnings are allowed
93 // but the exit status isn't changed.
94 message(V_WARNING, _("Using a preset in raw mode "
96 message(V_WARNING, _("The exact options of the "
97 "presets may vary between software "
101 // Get the preset for LZMA1 or LZMA2.
102 if (lzma_lzma_preset(&opt_lzma, preset_number))
105 // Use LZMA2 except with --format=lzma we use LZMA1.
106 filters[0].id = opt_format == FORMAT_LZMA
107 ? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
108 filters[0].options = &opt_lzma;
112 // Terminate the filter options array.
113 filters[filters_count].id = LZMA_VLI_UNKNOWN;
115 // If we are using the LZMA_Alone format, allow exactly one filter
116 // which has to be LZMA.
117 if (opt_format == FORMAT_LZMA && (filters_count != 1
118 || filters[0].id != LZMA_FILTER_LZMA1))
119 message_fatal(_("With --format=lzma only the LZMA1 filter "
122 // TODO: liblzma probably needs an API to validate the filter chain.
124 // If using --format=raw, we can be decoding.
125 uint64_t memory_usage;
126 uint64_t memory_limit;
127 if (opt_mode == MODE_COMPRESS) {
128 memory_usage = lzma_memusage_encoder(filters);
129 memory_limit = hardware_memlimit_encoder();
131 memory_usage = lzma_memusage_decoder(filters);
132 memory_limit = hardware_memlimit_decoder();
135 if (memory_usage == UINT64_MAX)
138 if (preset_default) {
139 // When no preset was explicitly requested, we use the default
140 // preset only if the memory usage limit allows. Otherwise we
141 // select a lower preset automatically.
142 while (memory_usage > memory_limit) {
143 if (preset_number == 1)
144 message_fatal(_("Memory usage limit is too "
145 "small for any internal "
148 if (lzma_lzma_preset(&opt_lzma, --preset_number))
151 memory_usage = lzma_memusage_encoder(filters);
154 if (memory_usage > memory_limit)
155 message_fatal(_("Memory usage limit is too small "
156 "for the given filter setup"));
159 // Limit the number of worked threads so that memory usage
160 // limit isn't exceeded.
161 assert(memory_usage > 0);
162 size_t thread_limit = memory_limit / memory_usage;
163 if (thread_limit == 0)
166 if (opt_threads > thread_limit)
167 opt_threads = thread_limit;
176 lzma_ret ret = LZMA_PROG_ERROR;
178 if (opt_mode == MODE_COMPRESS) {
179 switch (opt_format) {
181 // args.c ensures this.
186 ret = lzma_stream_encoder(&strm, filters, check);
190 ret = lzma_alone_encoder(&strm, filters[0].options);
194 ret = lzma_raw_encoder(&strm, filters);
198 const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
201 switch (opt_format) {
203 ret = lzma_auto_decoder(&strm,
204 hardware_memlimit_decoder(), flags);
208 ret = lzma_stream_decoder(&strm,
209 hardware_memlimit_decoder(), flags);
213 ret = lzma_alone_decoder(&strm,
214 hardware_memlimit_decoder());
218 // Memory usage has already been checked in args.c.
220 ret = lzma_raw_decoder(&strm, filters);
225 if (ret != LZMA_OK) {
226 if (ret == LZMA_MEM_ERROR)
227 message_error("%s", message_strm(LZMA_MEM_ERROR));
239 coder_run(file_pair *pair)
241 // Buffers to hold input and output data.
242 uint8_t in_buf[IO_BUFFER_SIZE];
243 uint8_t out_buf[IO_BUFFER_SIZE];
245 // Initialize the progress indicator.
246 const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
247 ? 0 : (uint64_t)(pair->src_st.st_size);
248 message_progress_start(pair->src_name, in_size);
250 lzma_action action = LZMA_RUN;
254 strm.next_out = out_buf;
255 strm.avail_out = IO_BUFFER_SIZE;
257 while (!user_abort) {
258 // Fill the input buffer if it is empty and we haven't reached
260 if (strm.avail_in == 0 && !pair->src_eof) {
261 strm.next_in = in_buf;
262 strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
264 if (strm.avail_in == SIZE_MAX)
267 // Encoder needs to know when we have given all the
268 // input to it. The decoders need to know it too when
269 // we are using LZMA_CONCATENATED.
271 action = LZMA_FINISH;
274 // Let liblzma do the actual work.
275 ret = lzma_code(&strm, action);
277 // Write out if the output buffer became full.
278 if (strm.avail_out == 0) {
279 if (opt_mode != MODE_TEST && io_write(pair, out_buf,
280 IO_BUFFER_SIZE - strm.avail_out))
283 strm.next_out = out_buf;
284 strm.avail_out = IO_BUFFER_SIZE;
287 if (ret != LZMA_OK) {
288 // Determine if the return value indicates that we
289 // won't continue coding.
290 const bool stop = ret != LZMA_NO_CHECK
291 && ret != LZMA_UNSUPPORTED_CHECK;
294 // First print the final progress info.
295 // This way the user sees more accurately
296 // where the error occurred. Note that we
297 // print this *before* the possible error
300 // FIXME: What if something goes wrong
302 message_progress_end(strm.total_in,
304 ret == LZMA_STREAM_END);
306 // Write the remaining bytes even if something
307 // went wrong, because that way the user gets
308 // as much data as possible, which can be good
309 // when trying to get at least some useful
310 // data out of damaged files.
311 if (opt_mode != MODE_TEST && io_write(pair,
312 out_buf, IO_BUFFER_SIZE
317 if (ret == LZMA_STREAM_END) {
318 // Check that there is no trailing garbage.
319 // This is needed for LZMA_Alone and raw
321 if (strm.avail_in == 0 && (pair->src_eof
322 || io_read(pair, in_buf, 1)
324 assert(pair->src_eof);
328 // FIXME: What about io_read() failing?
330 // We hadn't reached the end of the file.
331 ret = LZMA_DATA_ERROR;
335 // If we get here and stop is true, something went
336 // wrong and we print an error. Otherwise it's just
337 // a warning and coding can continue.
339 message_error("%s: %s", pair->src_name,
342 message_warning("%s: %s", pair->src_name,
345 // When compressing, all possible errors set
347 assert(opt_mode != MODE_COMPRESS);
350 if (ret == LZMA_MEMLIMIT_ERROR) {
351 // Figure out how much memory would have
360 // Show progress information if --verbose was specified and
361 // stderr is a terminal.
362 message_progress_update(strm.total_in, strm.total_out);
370 process_file(const char *filename)
372 // First try initializing the coder. If it fails, it's useless to try
373 // opening the file. Check also for user_abort just in case if we had
374 // got a signal while initializing the coder.
375 if (coder_init() || user_abort)
378 // Try to open the input and output files.
379 file_pair *pair = io_open(filename);
383 // Do the actual coding.
384 const bool success = coder_run(pair);
386 // Close the file pair. It needs to know if coding was successful to
387 // know if the source or target file should be unlinked.
388 io_close(pair, success);