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