]> wimlib.net Git - wimlib/blob - src/xpress-compress.c
6b28cca1741989db6c711b4b7916ccfde43b40d2
[wimlib] / src / xpress-compress.c
1 /*
2  * xpress-compress.c
3  *
4  * XPRESS compression routines.
5  *
6  * See the comments in xpress-decompress.c about the XPRESS format.
7  */
8
9 /*
10  * Copyright (C) 2012, 2013 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU General Public License as published by the Free
16  * Software Foundation; either version 3 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #  include "config.h"
30 #endif
31
32 #include "wimlib.h"
33 #include "wimlib/assert.h"
34 #include "wimlib/compress.h"
35 #include "wimlib/util.h"
36 #include "wimlib/xpress.h"
37
38 #include <stdlib.h>
39 #include <string.h>
40
41 /*
42  * Writes @match, which is a match given in the intermediate representation for
43  * XPRESS matches, to the output stream @ostream.
44  *
45  * @codewords and @lens provide the Huffman code that is being used.
46  */
47 static int
48 xpress_write_match(struct output_bitstream *ostream, u32 match,
49                    const u16 codewords[], const u8 lens[])
50 {
51         u32 adjusted_match_len = match & 0xffff;
52         u32 match_offset = match >> 16;
53         u32 len_hdr = min(adjusted_match_len, 0xf);
54         u32 offset_bsr = bsr32(match_offset);
55         u32 sym = len_hdr | (offset_bsr << 4) | XPRESS_NUM_CHARS;
56         int ret;
57
58         ret = bitstream_put_bits(ostream, codewords[sym], lens[sym]);
59         if (ret != 0)
60                 return ret;
61
62         if (adjusted_match_len >= 0xf) {
63                 u8 byte1 = min(adjusted_match_len - 0xf, 0xff);
64                 ret = bitstream_put_byte(ostream, byte1);
65                 if (ret != 0)
66                         return ret;
67                 if (byte1 == 0xff) {
68                         ret = bitstream_put_two_bytes(ostream, adjusted_match_len);
69                         if (ret != 0)
70                                 return ret;
71                 }
72         }
73         return bitstream_put_bits(ostream,
74                                   match_offset ^ (1 << offset_bsr), offset_bsr);
75 }
76
77 static int
78 xpress_write_compressed_literals(struct output_bitstream *ostream,
79                                  const u32 match_tab[],
80                                  unsigned num_matches,
81                                  const u16 codewords[],
82                                  const u8 lens[])
83 {
84         for (unsigned i = 0; i < num_matches; i++) {
85                 int ret;
86                 u32 match = match_tab[i];
87
88                 if (match >= XPRESS_NUM_CHARS) /* match */
89                         ret = xpress_write_match(ostream, match, codewords,
90                                                  lens);
91                 else /* literal byte */
92                         ret = bitstream_put_bits(ostream, codewords[match],
93                                                  lens[match]);
94                 if (ret != 0)
95                         return ret;
96         }
97         return bitstream_put_bits(ostream, codewords[XPRESS_END_OF_DATA],
98                                   lens[XPRESS_END_OF_DATA]);
99 }
100
101 static u32
102 xpress_record_literal(u8 literal, void *__freq_tab)
103 {
104         freq_t *freq_tab = __freq_tab;
105         freq_tab[literal]++;
106         return literal;
107 }
108
109 static u32
110 xpress_record_match(unsigned match_offset, unsigned match_len,
111                     void *freq_tab, void *ignore)
112 {
113         wimlib_assert(match_len >= XPRESS_MIN_MATCH &&
114                       match_len <= XPRESS_MAX_MATCH);
115         wimlib_assert(match_offset >= XPRESS_MIN_OFFSET &&
116                       match_offset <= XPRESS_MAX_OFFSET);
117
118         /*
119          * The intermediate representation of XPRESS matches is as follows:
120          *
121          * bits    description
122          * ----    -----------------------------------------------------------
123          *
124          * 16-31   match offset (XPRESS_MIN_OFFSET < x < XPRESS_MAX_OFFSET)
125          *
126          * 0-15    adjusted match length (0 <= x <= XPRESS_MAX_MATCH - XPRESS_MIN_MATCH)
127          *
128          * Literals are simply represented as themselves and can be
129          * distinguished from matches by the fact that only literals will have
130          * the upper three bytes completely clear. */
131
132         u32 adjusted_match_len = match_len - XPRESS_MIN_MATCH;
133         u32 len_hdr = min(adjusted_match_len, 0xf);
134         u32 offset_bsr = bsr32(match_offset);
135         u32 sym = len_hdr | (offset_bsr << 4) | XPRESS_NUM_CHARS;
136         ((freq_t*)freq_tab)[sym]++;
137         return adjusted_match_len | (match_offset << 16);
138 }
139
140 static const struct lz_params xpress_lz_params = {
141         .min_match      = XPRESS_MIN_MATCH,
142         .max_match      = XPRESS_MAX_MATCH,
143         .good_match     = 16,
144         .nice_match     = 32,
145         .max_chain_len  = 16,
146         .max_lazy_match = 16,
147         .too_far        = 4096,
148 };
149
150 /* Documented in wimlib.h */
151 WIMLIBAPI unsigned
152 wimlib_xpress_compress(const void *__uncompressed_data,
153                        unsigned uncompressed_len, void *__compressed_data)
154 {
155         u8 *compressed_data = __compressed_data;
156         struct output_bitstream ostream;
157         u32 match_tab[uncompressed_len];
158         freq_t freq_tab[XPRESS_NUM_SYMBOLS];
159         u16 codewords[XPRESS_NUM_SYMBOLS];
160         u8 lens[XPRESS_NUM_SYMBOLS];
161         unsigned num_matches;
162         unsigned compressed_len;
163         unsigned i;
164         int ret;
165         u8 uncompressed_data[uncompressed_len + 8];
166
167         memcpy(uncompressed_data, __uncompressed_data, uncompressed_len);
168         memset(uncompressed_data + uncompressed_len, 0, 8);
169
170         wimlib_assert(uncompressed_len <= 32768);
171
172         /* XPRESS requires 256 bytes of overhead for the Huffman tables, so it's
173          * impossible cannot compress 256 bytes or less of data to less than the
174          * input size.
175          *
176          * +1 to take into account that the buffer for compressed data is 1 byte
177          * smaller than the buffer for uncompressed data.
178          *
179          * +4 to take into account that init_output_bitstream() requires at
180          * least 4 bytes of data. */
181         if (uncompressed_len < XPRESS_NUM_SYMBOLS / 2 + 1 + 4)
182                 return 0;
183
184         ZERO_ARRAY(freq_tab);
185         num_matches = lz_analyze_block(uncompressed_data, uncompressed_len,
186                                        match_tab, xpress_record_match,
187                                        xpress_record_literal, freq_tab,
188                                        NULL, freq_tab,
189                                        &xpress_lz_params);
190
191         freq_tab[XPRESS_END_OF_DATA]++;
192
193         make_canonical_huffman_code(XPRESS_NUM_SYMBOLS, XPRESS_MAX_CODEWORD_LEN,
194                                     freq_tab, lens, codewords);
195
196         /* IMPORTANT NOTE:
197          *
198          * It's tempting to output the 512 Huffman codeword lengths using the
199          * bitstream_put_bits() function.  However, this is NOT correct because
200          * bitstream_put_bits() will output 2 bytes at a time in little-endian
201          * order, which is the order that is needed for the compressed literals.
202          * However, the bytes in the lengths table are in order, so they need to
203          * be written one at a time without using bitstream_put_bits().
204          *
205          * Because of this, init_output_bitstream() is not called until after
206          * the lengths table is output.
207          */
208         for (i = 0; i < XPRESS_NUM_SYMBOLS; i += 2)
209                 *compressed_data++ = (lens[i] & 0xf) | (lens[i + 1] << 4);
210
211         init_output_bitstream(&ostream, compressed_data,
212                               uncompressed_len - XPRESS_NUM_SYMBOLS / 2 - 1);
213
214         ret = xpress_write_compressed_literals(&ostream, match_tab,
215                                                num_matches, codewords, lens);
216         if (ret)
217                 return 0;
218
219         /* Flush any bits that are buffered. */
220         ret = flush_output_bitstream(&ostream);
221         if (ret)
222                 return 0;
223
224         /* Assert that there are no output bytes between the ostream.output
225          * pointer and the ostream.next_bit_output pointer.  This can only
226          * happen if bytes had been written at the ostream.output pointer before
227          * the last bit word was written to the stream.  But, this does not
228          * occur since xpress_write_match() always finishes by writing some bits
229          * (a Huffman symbol), and the bitstream was just flushed. */
230         wimlib_assert(ostream.output - ostream.next_bit_output == 2);
231
232         /* The length of the compressed data is supposed to be the value of the
233          * ostream.output pointer before flushing, which is now the
234          * output.next_bit_output pointer after flushing.
235          *
236          * There will be an extra 2 bytes at the ostream.bit_output pointer,
237          * which is zeroed out.  (These 2 bytes may be either the last bytes in
238          * the compressed data, in which case they are actually unnecessary, or
239          * they may precede a number of bytes embedded into the bitstream.) */
240         if (ostream.bit_output >
241             (const u8*)__compressed_data + uncompressed_len - 3)
242                 return 0;
243         *(u16*)ostream.bit_output = cpu_to_le16(0);
244         compressed_len = ostream.next_bit_output - (const u8*)__compressed_data;
245
246         wimlib_assert(compressed_len <= uncompressed_len - 1);
247
248 #if defined(ENABLE_VERIFY_COMPRESSION)
249         /* Verify that we really get the same thing back when decompressing. */
250         {
251                 u8 buf[uncompressed_len];
252                 ret = wimlib_xpress_decompress(__compressed_data, compressed_len,
253                                                buf, uncompressed_len);
254                 if (ret) {
255                         ERROR("xpress_compress(): Failed to decompress data we "
256                               "compressed");
257                         abort();
258                 }
259                 for (i = 0; i < uncompressed_len; i++) {
260                         if (buf[i] != uncompressed_data[i]) {
261                                 ERROR("xpress_compress(): Data we compressed didn't "
262                                       "decompress to the original data (difference at "
263                                       "byte %u of %u)", i + 1, uncompressed_len);
264                                 abort();
265                         }
266                 }
267         }
268 #endif
269         return compressed_len;
270 }