/src/libjxl/third_party/brotli/c/dec/decode.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* Copyright 2013 Google Inc. All Rights Reserved. |
2 | | |
3 | | Distributed under MIT license. |
4 | | See file LICENSE for detail or copy at https://opensource.org/licenses/MIT |
5 | | */ |
6 | | |
7 | | #include <brotli/decode.h> |
8 | | |
9 | | #include <stdlib.h> /* free, malloc */ |
10 | | #include <string.h> /* memcpy, memset */ |
11 | | |
12 | | #include "../common/constants.h" |
13 | | #include "../common/context.h" |
14 | | #include "../common/dictionary.h" |
15 | | #include "../common/platform.h" |
16 | | #include "../common/shared_dictionary_internal.h" |
17 | | #include "../common/transform.h" |
18 | | #include "../common/version.h" |
19 | | #include "bit_reader.h" |
20 | | #include "huffman.h" |
21 | | #include "prefix.h" |
22 | | #include "state.h" |
23 | | |
24 | | #if defined(BROTLI_TARGET_NEON) |
25 | | #include <arm_neon.h> |
26 | | #endif |
27 | | |
28 | | #if defined(__cplusplus) || defined(c_plusplus) |
29 | | extern "C" { |
30 | | #endif |
31 | | |
32 | 0 | #define BROTLI_FAILURE(CODE) (BROTLI_DUMP(), CODE) |
33 | | |
34 | | #define BROTLI_LOG_UINT(name) \ |
35 | | BROTLI_LOG(("[%s] %s = %lu\n", __func__, #name, (unsigned long)(name))) |
36 | | #define BROTLI_LOG_ARRAY_INDEX(array_name, idx) \ |
37 | | BROTLI_LOG(("[%s] %s[%lu] = %lu\n", __func__, #array_name, \ |
38 | | (unsigned long)(idx), (unsigned long)array_name[idx])) |
39 | | |
40 | 0 | #define HUFFMAN_TABLE_BITS 8U |
41 | 0 | #define HUFFMAN_TABLE_MASK 0xFF |
42 | | |
43 | | /* We need the slack region for the following reasons: |
44 | | - doing up to two 16-byte copies for fast backward copying |
45 | | - inserting transformed dictionary word: |
46 | | 255 prefix + 32 base + 255 suffix */ |
47 | | static const uint32_t kRingBufferWriteAheadSlack = 542; |
48 | | |
49 | | static const uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES] = { |
50 | | 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15, |
51 | | }; |
52 | | |
53 | | /* Static prefix code for the complex code length code lengths. */ |
54 | | static const uint8_t kCodeLengthPrefixLength[16] = { |
55 | | 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4, |
56 | | }; |
57 | | |
58 | | static const uint8_t kCodeLengthPrefixValue[16] = { |
59 | | 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5, |
60 | | }; |
61 | | |
62 | | BROTLI_BOOL BrotliDecoderSetParameter( |
63 | 0 | BrotliDecoderState* state, BrotliDecoderParameter p, uint32_t value) { |
64 | 0 | if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE; |
65 | 0 | switch (p) { |
66 | 0 | case BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: |
67 | 0 | state->canny_ringbuffer_allocation = !!value ? 0 : 1; |
68 | 0 | return BROTLI_TRUE; |
69 | | |
70 | 0 | case BROTLI_DECODER_PARAM_LARGE_WINDOW: |
71 | 0 | state->large_window = TO_BROTLI_BOOL(!!value); |
72 | 0 | return BROTLI_TRUE; |
73 | | |
74 | 0 | default: return BROTLI_FALSE; |
75 | 0 | } |
76 | 0 | } |
77 | | |
78 | | BrotliDecoderState* BrotliDecoderCreateInstance( |
79 | 0 | brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) { |
80 | 0 | BrotliDecoderState* state = 0; |
81 | 0 | if (!alloc_func && !free_func) { |
82 | 0 | state = (BrotliDecoderState*)malloc(sizeof(BrotliDecoderState)); |
83 | 0 | } else if (alloc_func && free_func) { |
84 | 0 | state = (BrotliDecoderState*)alloc_func(opaque, sizeof(BrotliDecoderState)); |
85 | 0 | } |
86 | 0 | if (state == 0) { |
87 | 0 | BROTLI_DUMP(); |
88 | 0 | return 0; |
89 | 0 | } |
90 | 0 | if (!BrotliDecoderStateInit(state, alloc_func, free_func, opaque)) { |
91 | 0 | BROTLI_DUMP(); |
92 | 0 | if (!alloc_func && !free_func) { |
93 | 0 | free(state); |
94 | 0 | } else if (alloc_func && free_func) { |
95 | 0 | free_func(opaque, state); |
96 | 0 | } |
97 | 0 | return 0; |
98 | 0 | } |
99 | 0 | return state; |
100 | 0 | } |
101 | | |
102 | | /* Deinitializes and frees BrotliDecoderState instance. */ |
103 | 0 | void BrotliDecoderDestroyInstance(BrotliDecoderState* state) { |
104 | 0 | if (!state) { |
105 | 0 | return; |
106 | 0 | } else { |
107 | 0 | brotli_free_func free_func = state->free_func; |
108 | 0 | void* opaque = state->memory_manager_opaque; |
109 | 0 | BrotliDecoderStateCleanup(state); |
110 | 0 | free_func(opaque, state); |
111 | 0 | } |
112 | 0 | } |
113 | | |
114 | | /* Saves error code and converts it to BrotliDecoderResult. */ |
115 | | static BROTLI_NOINLINE BrotliDecoderResult SaveErrorCode( |
116 | 0 | BrotliDecoderState* s, BrotliDecoderErrorCode e, size_t consumed_input) { |
117 | 0 | s->error_code = (int)e; |
118 | 0 | s->used_input += consumed_input; |
119 | 0 | switch (e) { |
120 | 0 | case BROTLI_DECODER_SUCCESS: |
121 | 0 | return BROTLI_DECODER_RESULT_SUCCESS; |
122 | | |
123 | 0 | case BROTLI_DECODER_NEEDS_MORE_INPUT: |
124 | 0 | return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; |
125 | | |
126 | 0 | case BROTLI_DECODER_NEEDS_MORE_OUTPUT: |
127 | 0 | return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; |
128 | | |
129 | 0 | default: |
130 | 0 | return BROTLI_DECODER_RESULT_ERROR; |
131 | 0 | } |
132 | 0 | } |
133 | | |
134 | | /* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli". |
135 | | Precondition: bit-reader accumulator has at least 8 bits. */ |
136 | | static BrotliDecoderErrorCode DecodeWindowBits(BrotliDecoderState* s, |
137 | 0 | BrotliBitReader* br) { |
138 | 0 | uint32_t n; |
139 | 0 | BROTLI_BOOL large_window = s->large_window; |
140 | 0 | s->large_window = BROTLI_FALSE; |
141 | 0 | BrotliTakeBits(br, 1, &n); |
142 | 0 | if (n == 0) { |
143 | 0 | s->window_bits = 16; |
144 | 0 | return BROTLI_DECODER_SUCCESS; |
145 | 0 | } |
146 | 0 | BrotliTakeBits(br, 3, &n); |
147 | 0 | if (n != 0) { |
148 | 0 | s->window_bits = 17 + n; |
149 | 0 | return BROTLI_DECODER_SUCCESS; |
150 | 0 | } |
151 | 0 | BrotliTakeBits(br, 3, &n); |
152 | 0 | if (n == 1) { |
153 | 0 | if (large_window) { |
154 | 0 | BrotliTakeBits(br, 1, &n); |
155 | 0 | if (n == 1) { |
156 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS); |
157 | 0 | } |
158 | 0 | s->large_window = BROTLI_TRUE; |
159 | 0 | return BROTLI_DECODER_SUCCESS; |
160 | 0 | } else { |
161 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS); |
162 | 0 | } |
163 | 0 | } |
164 | 0 | if (n != 0) { |
165 | 0 | s->window_bits = 8 + n; |
166 | 0 | return BROTLI_DECODER_SUCCESS; |
167 | 0 | } |
168 | 0 | s->window_bits = 17; |
169 | 0 | return BROTLI_DECODER_SUCCESS; |
170 | 0 | } |
171 | | |
172 | 0 | static BROTLI_INLINE void memmove16(uint8_t* dst, uint8_t* src) { |
173 | | #if defined(BROTLI_TARGET_NEON) |
174 | | vst1q_u8(dst, vld1q_u8(src)); |
175 | | #else |
176 | 0 | uint32_t buffer[4]; |
177 | 0 | memcpy(buffer, src, 16); |
178 | 0 | memcpy(dst, buffer, 16); |
179 | 0 | #endif |
180 | 0 | } |
181 | | |
182 | | /* Decodes a number in the range [0..255], by reading 1 - 11 bits. */ |
183 | | static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeVarLenUint8( |
184 | 0 | BrotliDecoderState* s, BrotliBitReader* br, uint32_t* value) { |
185 | 0 | uint32_t bits; |
186 | 0 | switch (s->substate_decode_uint8) { |
187 | 0 | case BROTLI_STATE_DECODE_UINT8_NONE: |
188 | 0 | if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) { |
189 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
190 | 0 | } |
191 | 0 | if (bits == 0) { |
192 | 0 | *value = 0; |
193 | 0 | return BROTLI_DECODER_SUCCESS; |
194 | 0 | } |
195 | | /* Fall through. */ |
196 | | |
197 | 0 | case BROTLI_STATE_DECODE_UINT8_SHORT: |
198 | 0 | if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) { |
199 | 0 | s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT; |
200 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
201 | 0 | } |
202 | 0 | if (bits == 0) { |
203 | 0 | *value = 1; |
204 | 0 | s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE; |
205 | 0 | return BROTLI_DECODER_SUCCESS; |
206 | 0 | } |
207 | | /* Use output value as a temporary storage. It MUST be persisted. */ |
208 | 0 | *value = bits; |
209 | | /* Fall through. */ |
210 | |
|
211 | 0 | case BROTLI_STATE_DECODE_UINT8_LONG: |
212 | 0 | if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) { |
213 | 0 | s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG; |
214 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
215 | 0 | } |
216 | 0 | *value = (1U << *value) + bits; |
217 | 0 | s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE; |
218 | 0 | return BROTLI_DECODER_SUCCESS; |
219 | | |
220 | 0 | default: |
221 | 0 | return |
222 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */ |
223 | 0 | } |
224 | 0 | } |
225 | | |
226 | | /* Decodes a metablock length and flags by reading 2 - 31 bits. */ |
227 | | static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength( |
228 | 0 | BrotliDecoderState* s, BrotliBitReader* br) { |
229 | 0 | uint32_t bits; |
230 | 0 | int i; |
231 | 0 | for (;;) { |
232 | 0 | switch (s->substate_metablock_header) { |
233 | 0 | case BROTLI_STATE_METABLOCK_HEADER_NONE: |
234 | 0 | if (!BrotliSafeReadBits(br, 1, &bits)) { |
235 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
236 | 0 | } |
237 | 0 | s->is_last_metablock = bits ? 1 : 0; |
238 | 0 | s->meta_block_remaining_len = 0; |
239 | 0 | s->is_uncompressed = 0; |
240 | 0 | s->is_metadata = 0; |
241 | 0 | if (!s->is_last_metablock) { |
242 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES; |
243 | 0 | break; |
244 | 0 | } |
245 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_EMPTY; |
246 | | /* Fall through. */ |
247 | |
|
248 | 0 | case BROTLI_STATE_METABLOCK_HEADER_EMPTY: |
249 | 0 | if (!BrotliSafeReadBits(br, 1, &bits)) { |
250 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
251 | 0 | } |
252 | 0 | if (bits) { |
253 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; |
254 | 0 | return BROTLI_DECODER_SUCCESS; |
255 | 0 | } |
256 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES; |
257 | | /* Fall through. */ |
258 | |
|
259 | 0 | case BROTLI_STATE_METABLOCK_HEADER_NIBBLES: |
260 | 0 | if (!BrotliSafeReadBits(br, 2, &bits)) { |
261 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
262 | 0 | } |
263 | 0 | s->size_nibbles = (uint8_t)(bits + 4); |
264 | 0 | s->loop_counter = 0; |
265 | 0 | if (bits == 3) { |
266 | 0 | s->is_metadata = 1; |
267 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_RESERVED; |
268 | 0 | break; |
269 | 0 | } |
270 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_SIZE; |
271 | | /* Fall through. */ |
272 | |
|
273 | 0 | case BROTLI_STATE_METABLOCK_HEADER_SIZE: |
274 | 0 | i = s->loop_counter; |
275 | 0 | for (; i < (int)s->size_nibbles; ++i) { |
276 | 0 | if (!BrotliSafeReadBits(br, 4, &bits)) { |
277 | 0 | s->loop_counter = i; |
278 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
279 | 0 | } |
280 | 0 | if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 4 && |
281 | 0 | bits == 0) { |
282 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE); |
283 | 0 | } |
284 | 0 | s->meta_block_remaining_len |= (int)(bits << (i * 4)); |
285 | 0 | } |
286 | 0 | s->substate_metablock_header = |
287 | 0 | BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED; |
288 | | /* Fall through. */ |
289 | |
|
290 | 0 | case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED: |
291 | 0 | if (!s->is_last_metablock) { |
292 | 0 | if (!BrotliSafeReadBits(br, 1, &bits)) { |
293 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
294 | 0 | } |
295 | 0 | s->is_uncompressed = bits ? 1 : 0; |
296 | 0 | } |
297 | 0 | ++s->meta_block_remaining_len; |
298 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; |
299 | 0 | return BROTLI_DECODER_SUCCESS; |
300 | | |
301 | 0 | case BROTLI_STATE_METABLOCK_HEADER_RESERVED: |
302 | 0 | if (!BrotliSafeReadBits(br, 1, &bits)) { |
303 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
304 | 0 | } |
305 | 0 | if (bits != 0) { |
306 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED); |
307 | 0 | } |
308 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES; |
309 | | /* Fall through. */ |
310 | |
|
311 | 0 | case BROTLI_STATE_METABLOCK_HEADER_BYTES: |
312 | 0 | if (!BrotliSafeReadBits(br, 2, &bits)) { |
313 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
314 | 0 | } |
315 | 0 | if (bits == 0) { |
316 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; |
317 | 0 | return BROTLI_DECODER_SUCCESS; |
318 | 0 | } |
319 | 0 | s->size_nibbles = (uint8_t)bits; |
320 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_METADATA; |
321 | | /* Fall through. */ |
322 | |
|
323 | 0 | case BROTLI_STATE_METABLOCK_HEADER_METADATA: |
324 | 0 | i = s->loop_counter; |
325 | 0 | for (; i < (int)s->size_nibbles; ++i) { |
326 | 0 | if (!BrotliSafeReadBits(br, 8, &bits)) { |
327 | 0 | s->loop_counter = i; |
328 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
329 | 0 | } |
330 | 0 | if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 1 && |
331 | 0 | bits == 0) { |
332 | 0 | return BROTLI_FAILURE( |
333 | 0 | BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE); |
334 | 0 | } |
335 | 0 | s->meta_block_remaining_len |= (int)(bits << (i * 8)); |
336 | 0 | } |
337 | 0 | ++s->meta_block_remaining_len; |
338 | 0 | s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; |
339 | 0 | return BROTLI_DECODER_SUCCESS; |
340 | | |
341 | 0 | default: |
342 | 0 | return |
343 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */ |
344 | 0 | } |
345 | 0 | } |
346 | 0 | } |
347 | | |
348 | | /* Decodes the Huffman code. |
349 | | This method doesn't read data from the bit reader, BUT drops the amount of |
350 | | bits that correspond to the decoded symbol. |
351 | | bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */ |
352 | | static BROTLI_INLINE uint32_t DecodeSymbol(uint32_t bits, |
353 | | const HuffmanCode* table, |
354 | 0 | BrotliBitReader* br) { |
355 | 0 | BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table); |
356 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(table, bits & HUFFMAN_TABLE_MASK); |
357 | 0 | if (BROTLI_HC_FAST_LOAD_BITS(table) > HUFFMAN_TABLE_BITS) { |
358 | 0 | uint32_t nbits = BROTLI_HC_FAST_LOAD_BITS(table) - HUFFMAN_TABLE_BITS; |
359 | 0 | BrotliDropBits(br, HUFFMAN_TABLE_BITS); |
360 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(table, |
361 | 0 | BROTLI_HC_FAST_LOAD_VALUE(table) + |
362 | 0 | ((bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits))); |
363 | 0 | } |
364 | 0 | BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table)); |
365 | 0 | return BROTLI_HC_FAST_LOAD_VALUE(table); |
366 | 0 | } |
367 | | |
368 | | /* Reads and decodes the next Huffman code from bit-stream. |
369 | | This method peeks 16 bits of input and drops 0 - 15 of them. */ |
370 | | static BROTLI_INLINE uint32_t ReadSymbol(const HuffmanCode* table, |
371 | 0 | BrotliBitReader* br) { |
372 | 0 | return DecodeSymbol(BrotliGet16BitsUnmasked(br), table, br); |
373 | 0 | } |
374 | | |
375 | | /* Same as DecodeSymbol, but it is known that there is less than 15 bits of |
376 | | input are currently available. */ |
377 | | static BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol( |
378 | 0 | const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) { |
379 | 0 | uint32_t val; |
380 | 0 | uint32_t available_bits = BrotliGetAvailableBits(br); |
381 | 0 | BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table); |
382 | 0 | if (available_bits == 0) { |
383 | 0 | if (BROTLI_HC_FAST_LOAD_BITS(table) == 0) { |
384 | 0 | *result = BROTLI_HC_FAST_LOAD_VALUE(table); |
385 | 0 | return BROTLI_TRUE; |
386 | 0 | } |
387 | 0 | return BROTLI_FALSE; /* No valid bits at all. */ |
388 | 0 | } |
389 | 0 | val = (uint32_t)BrotliGetBitsUnmasked(br); |
390 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(table, val & HUFFMAN_TABLE_MASK); |
391 | 0 | if (BROTLI_HC_FAST_LOAD_BITS(table) <= HUFFMAN_TABLE_BITS) { |
392 | 0 | if (BROTLI_HC_FAST_LOAD_BITS(table) <= available_bits) { |
393 | 0 | BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table)); |
394 | 0 | *result = BROTLI_HC_FAST_LOAD_VALUE(table); |
395 | 0 | return BROTLI_TRUE; |
396 | 0 | } else { |
397 | 0 | return BROTLI_FALSE; /* Not enough bits for the first level. */ |
398 | 0 | } |
399 | 0 | } |
400 | 0 | if (available_bits <= HUFFMAN_TABLE_BITS) { |
401 | 0 | return BROTLI_FALSE; /* Not enough bits to move to the second level. */ |
402 | 0 | } |
403 | | |
404 | | /* Speculatively drop HUFFMAN_TABLE_BITS. */ |
405 | 0 | val = (val & BitMask(BROTLI_HC_FAST_LOAD_BITS(table))) >> HUFFMAN_TABLE_BITS; |
406 | 0 | available_bits -= HUFFMAN_TABLE_BITS; |
407 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + val); |
408 | 0 | if (available_bits < BROTLI_HC_FAST_LOAD_BITS(table)) { |
409 | 0 | return BROTLI_FALSE; /* Not enough bits for the second level. */ |
410 | 0 | } |
411 | | |
412 | 0 | BrotliDropBits(br, HUFFMAN_TABLE_BITS + BROTLI_HC_FAST_LOAD_BITS(table)); |
413 | 0 | *result = BROTLI_HC_FAST_LOAD_VALUE(table); |
414 | 0 | return BROTLI_TRUE; |
415 | 0 | } |
416 | | |
417 | | static BROTLI_INLINE BROTLI_BOOL SafeReadSymbol( |
418 | 0 | const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) { |
419 | 0 | uint32_t val; |
420 | 0 | if (BROTLI_PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) { |
421 | 0 | *result = DecodeSymbol(val, table, br); |
422 | 0 | return BROTLI_TRUE; |
423 | 0 | } |
424 | 0 | return SafeDecodeSymbol(table, br, result); |
425 | 0 | } |
426 | | |
427 | | /* Makes a look-up in first level Huffman table. Peeks 8 bits. */ |
428 | | static BROTLI_INLINE void PreloadSymbol(int safe, |
429 | | const HuffmanCode* table, |
430 | | BrotliBitReader* br, |
431 | | uint32_t* bits, |
432 | 0 | uint32_t* value) { |
433 | 0 | if (safe) { |
434 | 0 | return; |
435 | 0 | } |
436 | 0 | BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table); |
437 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(table, BrotliGetBits(br, HUFFMAN_TABLE_BITS)); |
438 | 0 | *bits = BROTLI_HC_FAST_LOAD_BITS(table); |
439 | 0 | *value = BROTLI_HC_FAST_LOAD_VALUE(table); |
440 | 0 | } |
441 | | |
442 | | /* Decodes the next Huffman code using data prepared by PreloadSymbol. |
443 | | Reads 0 - 15 bits. Also peeks 8 following bits. */ |
444 | | static BROTLI_INLINE uint32_t ReadPreloadedSymbol(const HuffmanCode* table, |
445 | | BrotliBitReader* br, |
446 | | uint32_t* bits, |
447 | 0 | uint32_t* value) { |
448 | 0 | uint32_t result = *value; |
449 | 0 | if (BROTLI_PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) { |
450 | 0 | uint32_t val = BrotliGet16BitsUnmasked(br); |
451 | 0 | const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value; |
452 | 0 | uint32_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS)); |
453 | 0 | BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(ext); |
454 | 0 | BrotliDropBits(br, HUFFMAN_TABLE_BITS); |
455 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(ext, (val >> HUFFMAN_TABLE_BITS) & mask); |
456 | 0 | BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(ext)); |
457 | 0 | result = BROTLI_HC_FAST_LOAD_VALUE(ext); |
458 | 0 | } else { |
459 | 0 | BrotliDropBits(br, *bits); |
460 | 0 | } |
461 | 0 | PreloadSymbol(0, table, br, bits, value); |
462 | 0 | return result; |
463 | 0 | } |
464 | | |
465 | 0 | static BROTLI_INLINE uint32_t Log2Floor(uint32_t x) { |
466 | 0 | uint32_t result = 0; |
467 | 0 | while (x) { |
468 | 0 | x >>= 1; |
469 | 0 | ++result; |
470 | 0 | } |
471 | 0 | return result; |
472 | 0 | } |
473 | | |
474 | | /* Reads (s->symbol + 1) symbols. |
475 | | Totally 1..4 symbols are read, 1..11 bits each. |
476 | | The list of symbols MUST NOT contain duplicates. */ |
477 | | static BrotliDecoderErrorCode ReadSimpleHuffmanSymbols( |
478 | | uint32_t alphabet_size_max, uint32_t alphabet_size_limit, |
479 | 0 | BrotliDecoderState* s) { |
480 | | /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */ |
481 | 0 | BrotliBitReader* br = &s->br; |
482 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
483 | 0 | uint32_t max_bits = Log2Floor(alphabet_size_max - 1); |
484 | 0 | uint32_t i = h->sub_loop_counter; |
485 | 0 | uint32_t num_symbols = h->symbol; |
486 | 0 | while (i <= num_symbols) { |
487 | 0 | uint32_t v; |
488 | 0 | if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) { |
489 | 0 | h->sub_loop_counter = i; |
490 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ; |
491 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
492 | 0 | } |
493 | 0 | if (v >= alphabet_size_limit) { |
494 | 0 | return |
495 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET); |
496 | 0 | } |
497 | 0 | h->symbols_lists_array[i] = (uint16_t)v; |
498 | 0 | BROTLI_LOG_UINT(h->symbols_lists_array[i]); |
499 | 0 | ++i; |
500 | 0 | } |
501 | | |
502 | 0 | for (i = 0; i < num_symbols; ++i) { |
503 | 0 | uint32_t k = i + 1; |
504 | 0 | for (; k <= num_symbols; ++k) { |
505 | 0 | if (h->symbols_lists_array[i] == h->symbols_lists_array[k]) { |
506 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME); |
507 | 0 | } |
508 | 0 | } |
509 | 0 | } |
510 | | |
511 | 0 | return BROTLI_DECODER_SUCCESS; |
512 | 0 | } |
513 | | |
514 | | /* Process single decoded symbol code length: |
515 | | A) reset the repeat variable |
516 | | B) remember code length (if it is not 0) |
517 | | C) extend corresponding index-chain |
518 | | D) reduce the Huffman space |
519 | | E) update the histogram */ |
520 | | static BROTLI_INLINE void ProcessSingleCodeLength(uint32_t code_len, |
521 | | uint32_t* symbol, uint32_t* repeat, uint32_t* space, |
522 | | uint32_t* prev_code_len, uint16_t* symbol_lists, |
523 | 0 | uint16_t* code_length_histo, int* next_symbol) { |
524 | 0 | *repeat = 0; |
525 | 0 | if (code_len != 0) { /* code_len == 1..15 */ |
526 | 0 | symbol_lists[next_symbol[code_len]] = (uint16_t)(*symbol); |
527 | 0 | next_symbol[code_len] = (int)(*symbol); |
528 | 0 | *prev_code_len = code_len; |
529 | 0 | *space -= 32768U >> code_len; |
530 | 0 | code_length_histo[code_len]++; |
531 | 0 | BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n", |
532 | 0 | (int)*symbol, (int)code_len)); |
533 | 0 | } |
534 | 0 | (*symbol)++; |
535 | 0 | } |
536 | | |
537 | | /* Process repeated symbol code length. |
538 | | A) Check if it is the extension of previous repeat sequence; if the decoded |
539 | | value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new |
540 | | symbol-skip |
541 | | B) Update repeat variable |
542 | | C) Check if operation is feasible (fits alphabet) |
543 | | D) For each symbol do the same operations as in ProcessSingleCodeLength |
544 | | |
545 | | PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or |
546 | | code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH */ |
547 | | static BROTLI_INLINE void ProcessRepeatedCodeLength(uint32_t code_len, |
548 | | uint32_t repeat_delta, uint32_t alphabet_size, uint32_t* symbol, |
549 | | uint32_t* repeat, uint32_t* space, uint32_t* prev_code_len, |
550 | | uint32_t* repeat_code_len, uint16_t* symbol_lists, |
551 | 0 | uint16_t* code_length_histo, int* next_symbol) { |
552 | 0 | uint32_t old_repeat; |
553 | 0 | uint32_t extra_bits = 3; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */ |
554 | 0 | uint32_t new_len = 0; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */ |
555 | 0 | if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) { |
556 | 0 | new_len = *prev_code_len; |
557 | 0 | extra_bits = 2; |
558 | 0 | } |
559 | 0 | if (*repeat_code_len != new_len) { |
560 | 0 | *repeat = 0; |
561 | 0 | *repeat_code_len = new_len; |
562 | 0 | } |
563 | 0 | old_repeat = *repeat; |
564 | 0 | if (*repeat > 0) { |
565 | 0 | *repeat -= 2; |
566 | 0 | *repeat <<= extra_bits; |
567 | 0 | } |
568 | 0 | *repeat += repeat_delta + 3U; |
569 | 0 | repeat_delta = *repeat - old_repeat; |
570 | 0 | if (*symbol + repeat_delta > alphabet_size) { |
571 | 0 | BROTLI_DUMP(); |
572 | 0 | *symbol = alphabet_size; |
573 | 0 | *space = 0xFFFFF; |
574 | 0 | return; |
575 | 0 | } |
576 | 0 | BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n", |
577 | 0 | (int)*symbol, (int)(*symbol + repeat_delta - 1), (int)*repeat_code_len)); |
578 | 0 | if (*repeat_code_len != 0) { |
579 | 0 | unsigned last = *symbol + repeat_delta; |
580 | 0 | int next = next_symbol[*repeat_code_len]; |
581 | 0 | do { |
582 | 0 | symbol_lists[next] = (uint16_t)*symbol; |
583 | 0 | next = (int)*symbol; |
584 | 0 | } while (++(*symbol) != last); |
585 | 0 | next_symbol[*repeat_code_len] = next; |
586 | 0 | *space -= repeat_delta << (15 - *repeat_code_len); |
587 | 0 | code_length_histo[*repeat_code_len] = |
588 | 0 | (uint16_t)(code_length_histo[*repeat_code_len] + repeat_delta); |
589 | 0 | } else { |
590 | 0 | *symbol += repeat_delta; |
591 | 0 | } |
592 | 0 | } |
593 | | |
594 | | /* Reads and decodes symbol codelengths. */ |
595 | | static BrotliDecoderErrorCode ReadSymbolCodeLengths( |
596 | 0 | uint32_t alphabet_size, BrotliDecoderState* s) { |
597 | 0 | BrotliBitReader* br = &s->br; |
598 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
599 | 0 | uint32_t symbol = h->symbol; |
600 | 0 | uint32_t repeat = h->repeat; |
601 | 0 | uint32_t space = h->space; |
602 | 0 | uint32_t prev_code_len = h->prev_code_len; |
603 | 0 | uint32_t repeat_code_len = h->repeat_code_len; |
604 | 0 | uint16_t* symbol_lists = h->symbol_lists; |
605 | 0 | uint16_t* code_length_histo = h->code_length_histo; |
606 | 0 | int* next_symbol = h->next_symbol; |
607 | 0 | if (!BrotliWarmupBitReader(br)) { |
608 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
609 | 0 | } |
610 | 0 | while (symbol < alphabet_size && space > 0) { |
611 | 0 | const HuffmanCode* p = h->table; |
612 | 0 | uint32_t code_len; |
613 | 0 | BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p); |
614 | 0 | if (!BrotliCheckInputAmount(br, BROTLI_SHORT_FILL_BIT_WINDOW_READ)) { |
615 | 0 | h->symbol = symbol; |
616 | 0 | h->repeat = repeat; |
617 | 0 | h->prev_code_len = prev_code_len; |
618 | 0 | h->repeat_code_len = repeat_code_len; |
619 | 0 | h->space = space; |
620 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
621 | 0 | } |
622 | 0 | BrotliFillBitWindow16(br); |
623 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(p, BrotliGetBitsUnmasked(br) & |
624 | 0 | BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH)); |
625 | 0 | BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)); /* Use 1..5 bits. */ |
626 | 0 | code_len = BROTLI_HC_FAST_LOAD_VALUE(p); /* code_len == 0..17 */ |
627 | 0 | if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) { |
628 | 0 | ProcessSingleCodeLength(code_len, &symbol, &repeat, &space, |
629 | 0 | &prev_code_len, symbol_lists, code_length_histo, next_symbol); |
630 | 0 | } else { /* code_len == 16..17, extra_bits == 2..3 */ |
631 | 0 | uint32_t extra_bits = |
632 | 0 | (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) ? 2 : 3; |
633 | 0 | uint32_t repeat_delta = |
634 | 0 | (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(extra_bits); |
635 | 0 | BrotliDropBits(br, extra_bits); |
636 | 0 | ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size, |
637 | 0 | &symbol, &repeat, &space, &prev_code_len, &repeat_code_len, |
638 | 0 | symbol_lists, code_length_histo, next_symbol); |
639 | 0 | } |
640 | 0 | } |
641 | 0 | h->space = space; |
642 | 0 | return BROTLI_DECODER_SUCCESS; |
643 | 0 | } |
644 | | |
645 | | static BrotliDecoderErrorCode SafeReadSymbolCodeLengths( |
646 | 0 | uint32_t alphabet_size, BrotliDecoderState* s) { |
647 | 0 | BrotliBitReader* br = &s->br; |
648 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
649 | 0 | BROTLI_BOOL get_byte = BROTLI_FALSE; |
650 | 0 | while (h->symbol < alphabet_size && h->space > 0) { |
651 | 0 | const HuffmanCode* p = h->table; |
652 | 0 | uint32_t code_len; |
653 | 0 | uint32_t available_bits; |
654 | 0 | uint32_t bits = 0; |
655 | 0 | BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p); |
656 | 0 | if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT; |
657 | 0 | get_byte = BROTLI_FALSE; |
658 | 0 | available_bits = BrotliGetAvailableBits(br); |
659 | 0 | if (available_bits != 0) { |
660 | 0 | bits = (uint32_t)BrotliGetBitsUnmasked(br); |
661 | 0 | } |
662 | 0 | BROTLI_HC_ADJUST_TABLE_INDEX(p, |
663 | 0 | bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH)); |
664 | 0 | if (BROTLI_HC_FAST_LOAD_BITS(p) > available_bits) { |
665 | 0 | get_byte = BROTLI_TRUE; |
666 | 0 | continue; |
667 | 0 | } |
668 | 0 | code_len = BROTLI_HC_FAST_LOAD_VALUE(p); /* code_len == 0..17 */ |
669 | 0 | if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) { |
670 | 0 | BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)); |
671 | 0 | ProcessSingleCodeLength(code_len, &h->symbol, &h->repeat, &h->space, |
672 | 0 | &h->prev_code_len, h->symbol_lists, h->code_length_histo, |
673 | 0 | h->next_symbol); |
674 | 0 | } else { /* code_len == 16..17, extra_bits == 2..3 */ |
675 | 0 | uint32_t extra_bits = code_len - 14U; |
676 | 0 | uint32_t repeat_delta = (bits >> BROTLI_HC_FAST_LOAD_BITS(p)) & |
677 | 0 | BitMask(extra_bits); |
678 | 0 | if (available_bits < BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits) { |
679 | 0 | get_byte = BROTLI_TRUE; |
680 | 0 | continue; |
681 | 0 | } |
682 | 0 | BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits); |
683 | 0 | ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size, |
684 | 0 | &h->symbol, &h->repeat, &h->space, &h->prev_code_len, |
685 | 0 | &h->repeat_code_len, h->symbol_lists, h->code_length_histo, |
686 | 0 | h->next_symbol); |
687 | 0 | } |
688 | 0 | } |
689 | 0 | return BROTLI_DECODER_SUCCESS; |
690 | 0 | } |
691 | | |
692 | | /* Reads and decodes 15..18 codes using static prefix code. |
693 | | Each code is 2..4 bits long. In total 30..72 bits are used. */ |
694 | 0 | static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) { |
695 | 0 | BrotliBitReader* br = &s->br; |
696 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
697 | 0 | uint32_t num_codes = h->repeat; |
698 | 0 | unsigned space = h->space; |
699 | 0 | uint32_t i = h->sub_loop_counter; |
700 | 0 | for (; i < BROTLI_CODE_LENGTH_CODES; ++i) { |
701 | 0 | const uint8_t code_len_idx = kCodeLengthCodeOrder[i]; |
702 | 0 | uint32_t ix; |
703 | 0 | uint32_t v; |
704 | 0 | if (BROTLI_PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) { |
705 | 0 | uint32_t available_bits = BrotliGetAvailableBits(br); |
706 | 0 | if (available_bits != 0) { |
707 | 0 | ix = BrotliGetBitsUnmasked(br) & 0xF; |
708 | 0 | } else { |
709 | 0 | ix = 0; |
710 | 0 | } |
711 | 0 | if (kCodeLengthPrefixLength[ix] > available_bits) { |
712 | 0 | h->sub_loop_counter = i; |
713 | 0 | h->repeat = num_codes; |
714 | 0 | h->space = space; |
715 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX; |
716 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
717 | 0 | } |
718 | 0 | } |
719 | 0 | v = kCodeLengthPrefixValue[ix]; |
720 | 0 | BrotliDropBits(br, kCodeLengthPrefixLength[ix]); |
721 | 0 | h->code_length_code_lengths[code_len_idx] = (uint8_t)v; |
722 | 0 | BROTLI_LOG_ARRAY_INDEX(h->code_length_code_lengths, code_len_idx); |
723 | 0 | if (v != 0) { |
724 | 0 | space = space - (32U >> v); |
725 | 0 | ++num_codes; |
726 | 0 | ++h->code_length_histo[v]; |
727 | 0 | if (space - 1U >= 32U) { |
728 | | /* space is 0 or wrapped around. */ |
729 | 0 | break; |
730 | 0 | } |
731 | 0 | } |
732 | 0 | } |
733 | 0 | if (!(num_codes == 1 || space == 0)) { |
734 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE); |
735 | 0 | } |
736 | 0 | return BROTLI_DECODER_SUCCESS; |
737 | 0 | } |
738 | | |
739 | | /* Decodes the Huffman tables. |
740 | | There are 2 scenarios: |
741 | | A) Huffman code contains only few symbols (1..4). Those symbols are read |
742 | | directly; their code lengths are defined by the number of symbols. |
743 | | For this scenario 4 - 49 bits will be read. |
744 | | |
745 | | B) 2-phase decoding: |
746 | | B.1) Small Huffman table is decoded; it is specified with code lengths |
747 | | encoded with predefined entropy code. 32 - 74 bits are used. |
748 | | B.2) Decoded table is used to decode code lengths of symbols in resulting |
749 | | Huffman table. In worst case 3520 bits are read. */ |
750 | | static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size_max, |
751 | | uint32_t alphabet_size_limit, |
752 | | HuffmanCode* table, |
753 | | uint32_t* opt_table_size, |
754 | 0 | BrotliDecoderState* s) { |
755 | 0 | BrotliBitReader* br = &s->br; |
756 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
757 | | /* State machine. */ |
758 | 0 | for (;;) { |
759 | 0 | switch (h->substate_huffman) { |
760 | 0 | case BROTLI_STATE_HUFFMAN_NONE: |
761 | 0 | if (!BrotliSafeReadBits(br, 2, &h->sub_loop_counter)) { |
762 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
763 | 0 | } |
764 | 0 | BROTLI_LOG_UINT(h->sub_loop_counter); |
765 | | /* The value is used as follows: |
766 | | 1 for simple code; |
767 | | 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */ |
768 | 0 | if (h->sub_loop_counter != 1) { |
769 | 0 | h->space = 32; |
770 | 0 | h->repeat = 0; /* num_codes */ |
771 | 0 | memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo[0]) * |
772 | 0 | (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1)); |
773 | 0 | memset(&h->code_length_code_lengths[0], 0, |
774 | 0 | sizeof(h->code_length_code_lengths)); |
775 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX; |
776 | 0 | continue; |
777 | 0 | } |
778 | | /* Fall through. */ |
779 | | |
780 | 0 | case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE: |
781 | | /* Read symbols, codes & code lengths directly. */ |
782 | 0 | if (!BrotliSafeReadBits(br, 2, &h->symbol)) { /* num_symbols */ |
783 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE; |
784 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
785 | 0 | } |
786 | 0 | h->sub_loop_counter = 0; |
787 | | /* Fall through. */ |
788 | |
|
789 | 0 | case BROTLI_STATE_HUFFMAN_SIMPLE_READ: { |
790 | 0 | BrotliDecoderErrorCode result = |
791 | 0 | ReadSimpleHuffmanSymbols(alphabet_size_max, alphabet_size_limit, s); |
792 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
793 | 0 | return result; |
794 | 0 | } |
795 | 0 | } |
796 | | /* Fall through. */ |
797 | | |
798 | 0 | case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: { |
799 | 0 | uint32_t table_size; |
800 | 0 | if (h->symbol == 3) { |
801 | 0 | uint32_t bits; |
802 | 0 | if (!BrotliSafeReadBits(br, 1, &bits)) { |
803 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD; |
804 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
805 | 0 | } |
806 | 0 | h->symbol += bits; |
807 | 0 | } |
808 | 0 | BROTLI_LOG_UINT(h->symbol); |
809 | 0 | table_size = BrotliBuildSimpleHuffmanTable( |
810 | 0 | table, HUFFMAN_TABLE_BITS, h->symbols_lists_array, h->symbol); |
811 | 0 | if (opt_table_size) { |
812 | 0 | *opt_table_size = table_size; |
813 | 0 | } |
814 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; |
815 | 0 | return BROTLI_DECODER_SUCCESS; |
816 | 0 | } |
817 | | |
818 | | /* Decode Huffman-coded code lengths. */ |
819 | 0 | case BROTLI_STATE_HUFFMAN_COMPLEX: { |
820 | 0 | uint32_t i; |
821 | 0 | BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s); |
822 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
823 | 0 | return result; |
824 | 0 | } |
825 | 0 | BrotliBuildCodeLengthsHuffmanTable(h->table, |
826 | 0 | h->code_length_code_lengths, |
827 | 0 | h->code_length_histo); |
828 | 0 | memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo)); |
829 | 0 | for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) { |
830 | 0 | h->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1); |
831 | 0 | h->symbol_lists[h->next_symbol[i]] = 0xFFFF; |
832 | 0 | } |
833 | |
|
834 | 0 | h->symbol = 0; |
835 | 0 | h->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH; |
836 | 0 | h->repeat = 0; |
837 | 0 | h->repeat_code_len = 0; |
838 | 0 | h->space = 32768; |
839 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS; |
840 | 0 | } |
841 | | /* Fall through. */ |
842 | | |
843 | 0 | case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: { |
844 | 0 | uint32_t table_size; |
845 | 0 | BrotliDecoderErrorCode result = ReadSymbolCodeLengths( |
846 | 0 | alphabet_size_limit, s); |
847 | 0 | if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) { |
848 | 0 | result = SafeReadSymbolCodeLengths(alphabet_size_limit, s); |
849 | 0 | } |
850 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
851 | 0 | return result; |
852 | 0 | } |
853 | | |
854 | 0 | if (h->space != 0) { |
855 | 0 | BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)h->space)); |
856 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE); |
857 | 0 | } |
858 | 0 | table_size = BrotliBuildHuffmanTable( |
859 | 0 | table, HUFFMAN_TABLE_BITS, h->symbol_lists, h->code_length_histo); |
860 | 0 | if (opt_table_size) { |
861 | 0 | *opt_table_size = table_size; |
862 | 0 | } |
863 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; |
864 | 0 | return BROTLI_DECODER_SUCCESS; |
865 | 0 | } |
866 | | |
867 | 0 | default: |
868 | 0 | return |
869 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */ |
870 | 0 | } |
871 | 0 | } |
872 | 0 | } |
873 | | |
874 | | /* Decodes a block length by reading 3..39 bits. */ |
875 | | static BROTLI_INLINE uint32_t ReadBlockLength(const HuffmanCode* table, |
876 | 0 | BrotliBitReader* br) { |
877 | 0 | uint32_t code; |
878 | 0 | uint32_t nbits; |
879 | 0 | code = ReadSymbol(table, br); |
880 | 0 | nbits = _kBrotliPrefixCodeRanges[code].nbits; /* nbits == 2..24 */ |
881 | 0 | return _kBrotliPrefixCodeRanges[code].offset + BrotliReadBits24(br, nbits); |
882 | 0 | } |
883 | | |
884 | | /* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then |
885 | | reading can't be continued with ReadBlockLength. */ |
886 | | static BROTLI_INLINE BROTLI_BOOL SafeReadBlockLength( |
887 | | BrotliDecoderState* s, uint32_t* result, const HuffmanCode* table, |
888 | 0 | BrotliBitReader* br) { |
889 | 0 | uint32_t index; |
890 | 0 | if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) { |
891 | 0 | if (!SafeReadSymbol(table, br, &index)) { |
892 | 0 | return BROTLI_FALSE; |
893 | 0 | } |
894 | 0 | } else { |
895 | 0 | index = s->block_length_index; |
896 | 0 | } |
897 | 0 | { |
898 | 0 | uint32_t bits; |
899 | 0 | uint32_t nbits = _kBrotliPrefixCodeRanges[index].nbits; |
900 | 0 | uint32_t offset = _kBrotliPrefixCodeRanges[index].offset; |
901 | 0 | if (!BrotliSafeReadBits(br, nbits, &bits)) { |
902 | 0 | s->block_length_index = index; |
903 | 0 | s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX; |
904 | 0 | return BROTLI_FALSE; |
905 | 0 | } |
906 | 0 | *result = offset + bits; |
907 | 0 | s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; |
908 | 0 | return BROTLI_TRUE; |
909 | 0 | } |
910 | 0 | } |
911 | | |
912 | | /* Transform: |
913 | | 1) initialize list L with values 0, 1,... 255 |
914 | | 2) For each input element X: |
915 | | 2.1) let Y = L[X] |
916 | | 2.2) remove X-th element from L |
917 | | 2.3) prepend Y to L |
918 | | 2.4) append Y to output |
919 | | |
920 | | In most cases max(Y) <= 7, so most of L remains intact. |
921 | | To reduce the cost of initialization, we reuse L, remember the upper bound |
922 | | of Y values, and reinitialize only first elements in L. |
923 | | |
924 | | Most of input values are 0 and 1. To reduce number of branches, we replace |
925 | | inner for loop with do-while. */ |
926 | | static BROTLI_NOINLINE void InverseMoveToFrontTransform( |
927 | 0 | uint8_t* v, uint32_t v_len, BrotliDecoderState* state) { |
928 | | /* Reinitialize elements that could have been changed. */ |
929 | 0 | uint32_t i = 1; |
930 | 0 | uint32_t upper_bound = state->mtf_upper_bound; |
931 | 0 | uint32_t* mtf = &state->mtf[1]; /* Make mtf[-1] addressable. */ |
932 | 0 | uint8_t* mtf_u8 = (uint8_t*)mtf; |
933 | | /* Load endian-aware constant. */ |
934 | 0 | const uint8_t b0123[4] = {0, 1, 2, 3}; |
935 | 0 | uint32_t pattern; |
936 | 0 | memcpy(&pattern, &b0123, 4); |
937 | | |
938 | | /* Initialize list using 4 consequent values pattern. */ |
939 | 0 | mtf[0] = pattern; |
940 | 0 | do { |
941 | 0 | pattern += 0x04040404; /* Advance all 4 values by 4. */ |
942 | 0 | mtf[i] = pattern; |
943 | 0 | i++; |
944 | 0 | } while (i <= upper_bound); |
945 | | |
946 | | /* Transform the input. */ |
947 | 0 | upper_bound = 0; |
948 | 0 | for (i = 0; i < v_len; ++i) { |
949 | 0 | int index = v[i]; |
950 | 0 | uint8_t value = mtf_u8[index]; |
951 | 0 | upper_bound |= v[i]; |
952 | 0 | v[i] = value; |
953 | 0 | mtf_u8[-1] = value; |
954 | 0 | do { |
955 | 0 | index--; |
956 | 0 | mtf_u8[index + 1] = mtf_u8[index]; |
957 | 0 | } while (index >= 0); |
958 | 0 | } |
959 | | /* Remember amount of elements to be reinitialized. */ |
960 | 0 | state->mtf_upper_bound = upper_bound >> 2; |
961 | 0 | } |
962 | | |
963 | | /* Decodes a series of Huffman table using ReadHuffmanCode function. */ |
964 | | static BrotliDecoderErrorCode HuffmanTreeGroupDecode( |
965 | 0 | HuffmanTreeGroup* group, BrotliDecoderState* s) { |
966 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
967 | 0 | if (h->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) { |
968 | 0 | h->next = group->codes; |
969 | 0 | h->htree_index = 0; |
970 | 0 | h->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP; |
971 | 0 | } |
972 | 0 | while (h->htree_index < group->num_htrees) { |
973 | 0 | uint32_t table_size; |
974 | 0 | BrotliDecoderErrorCode result = ReadHuffmanCode(group->alphabet_size_max, |
975 | 0 | group->alphabet_size_limit, h->next, &table_size, s); |
976 | 0 | if (result != BROTLI_DECODER_SUCCESS) return result; |
977 | 0 | group->htrees[h->htree_index] = h->next; |
978 | 0 | h->next += table_size; |
979 | 0 | ++h->htree_index; |
980 | 0 | } |
981 | 0 | h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE; |
982 | 0 | return BROTLI_DECODER_SUCCESS; |
983 | 0 | } |
984 | | |
985 | | /* Decodes a context map. |
986 | | Decoding is done in 4 phases: |
987 | | 1) Read auxiliary information (6..16 bits) and allocate memory. |
988 | | In case of trivial context map, decoding is finished at this phase. |
989 | | 2) Decode Huffman table using ReadHuffmanCode function. |
990 | | This table will be used for reading context map items. |
991 | | 3) Read context map items; "0" values could be run-length encoded. |
992 | | 4) Optionally, apply InverseMoveToFront transform to the resulting map. */ |
993 | | static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size, |
994 | | uint32_t* num_htrees, |
995 | | uint8_t** context_map_arg, |
996 | 0 | BrotliDecoderState* s) { |
997 | 0 | BrotliBitReader* br = &s->br; |
998 | 0 | BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS; |
999 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
1000 | |
|
1001 | 0 | switch ((int)h->substate_context_map) { |
1002 | 0 | case BROTLI_STATE_CONTEXT_MAP_NONE: |
1003 | 0 | result = DecodeVarLenUint8(s, br, num_htrees); |
1004 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
1005 | 0 | return result; |
1006 | 0 | } |
1007 | 0 | (*num_htrees)++; |
1008 | 0 | h->context_index = 0; |
1009 | 0 | BROTLI_LOG_UINT(context_map_size); |
1010 | 0 | BROTLI_LOG_UINT(*num_htrees); |
1011 | 0 | *context_map_arg = |
1012 | 0 | (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)context_map_size); |
1013 | 0 | if (*context_map_arg == 0) { |
1014 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP); |
1015 | 0 | } |
1016 | 0 | if (*num_htrees <= 1) { |
1017 | 0 | memset(*context_map_arg, 0, (size_t)context_map_size); |
1018 | 0 | return BROTLI_DECODER_SUCCESS; |
1019 | 0 | } |
1020 | 0 | h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX; |
1021 | | /* Fall through. */ |
1022 | |
|
1023 | 0 | case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: { |
1024 | 0 | uint32_t bits; |
1025 | | /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe |
1026 | | to peek 4 bits ahead. */ |
1027 | 0 | if (!BrotliSafeGetBits(br, 5, &bits)) { |
1028 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
1029 | 0 | } |
1030 | 0 | if ((bits & 1) != 0) { /* Use RLE for zeros. */ |
1031 | 0 | h->max_run_length_prefix = (bits >> 1) + 1; |
1032 | 0 | BrotliDropBits(br, 5); |
1033 | 0 | } else { |
1034 | 0 | h->max_run_length_prefix = 0; |
1035 | 0 | BrotliDropBits(br, 1); |
1036 | 0 | } |
1037 | 0 | BROTLI_LOG_UINT(h->max_run_length_prefix); |
1038 | 0 | h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN; |
1039 | 0 | } |
1040 | | /* Fall through. */ |
1041 | | |
1042 | 0 | case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: { |
1043 | 0 | uint32_t alphabet_size = *num_htrees + h->max_run_length_prefix; |
1044 | 0 | result = ReadHuffmanCode(alphabet_size, alphabet_size, |
1045 | 0 | h->context_map_table, NULL, s); |
1046 | 0 | if (result != BROTLI_DECODER_SUCCESS) return result; |
1047 | 0 | h->code = 0xFFFF; |
1048 | 0 | h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE; |
1049 | 0 | } |
1050 | | /* Fall through. */ |
1051 | | |
1052 | 0 | case BROTLI_STATE_CONTEXT_MAP_DECODE: { |
1053 | 0 | uint32_t context_index = h->context_index; |
1054 | 0 | uint32_t max_run_length_prefix = h->max_run_length_prefix; |
1055 | 0 | uint8_t* context_map = *context_map_arg; |
1056 | 0 | uint32_t code = h->code; |
1057 | 0 | BROTLI_BOOL skip_preamble = (code != 0xFFFF); |
1058 | 0 | while (context_index < context_map_size || skip_preamble) { |
1059 | 0 | if (!skip_preamble) { |
1060 | 0 | if (!SafeReadSymbol(h->context_map_table, br, &code)) { |
1061 | 0 | h->code = 0xFFFF; |
1062 | 0 | h->context_index = context_index; |
1063 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
1064 | 0 | } |
1065 | 0 | BROTLI_LOG_UINT(code); |
1066 | |
|
1067 | 0 | if (code == 0) { |
1068 | 0 | context_map[context_index++] = 0; |
1069 | 0 | continue; |
1070 | 0 | } |
1071 | 0 | if (code > max_run_length_prefix) { |
1072 | 0 | context_map[context_index++] = |
1073 | 0 | (uint8_t)(code - max_run_length_prefix); |
1074 | 0 | continue; |
1075 | 0 | } |
1076 | 0 | } else { |
1077 | 0 | skip_preamble = BROTLI_FALSE; |
1078 | 0 | } |
1079 | | /* RLE sub-stage. */ |
1080 | 0 | { |
1081 | 0 | uint32_t reps; |
1082 | 0 | if (!BrotliSafeReadBits(br, code, &reps)) { |
1083 | 0 | h->code = code; |
1084 | 0 | h->context_index = context_index; |
1085 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
1086 | 0 | } |
1087 | 0 | reps += 1U << code; |
1088 | 0 | BROTLI_LOG_UINT(reps); |
1089 | 0 | if (context_index + reps > context_map_size) { |
1090 | 0 | return |
1091 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT); |
1092 | 0 | } |
1093 | 0 | do { |
1094 | 0 | context_map[context_index++] = 0; |
1095 | 0 | } while (--reps); |
1096 | 0 | } |
1097 | 0 | } |
1098 | 0 | } |
1099 | | /* Fall through. */ |
1100 | | |
1101 | 0 | case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: { |
1102 | 0 | uint32_t bits; |
1103 | 0 | if (!BrotliSafeReadBits(br, 1, &bits)) { |
1104 | 0 | h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM; |
1105 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
1106 | 0 | } |
1107 | 0 | if (bits != 0) { |
1108 | 0 | InverseMoveToFrontTransform(*context_map_arg, context_map_size, s); |
1109 | 0 | } |
1110 | 0 | h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; |
1111 | 0 | return BROTLI_DECODER_SUCCESS; |
1112 | 0 | } |
1113 | | |
1114 | 0 | default: |
1115 | 0 | return |
1116 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */ |
1117 | 0 | } |
1118 | 0 | } |
1119 | | |
1120 | | /* Decodes a command or literal and updates block type ring-buffer. |
1121 | | Reads 3..54 bits. */ |
1122 | | static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength( |
1123 | 0 | int safe, BrotliDecoderState* s, int tree_type) { |
1124 | 0 | uint32_t max_block_type = s->num_block_types[tree_type]; |
1125 | 0 | const HuffmanCode* type_tree = &s->block_type_trees[ |
1126 | 0 | tree_type * BROTLI_HUFFMAN_MAX_SIZE_258]; |
1127 | 0 | const HuffmanCode* len_tree = &s->block_len_trees[ |
1128 | 0 | tree_type * BROTLI_HUFFMAN_MAX_SIZE_26]; |
1129 | 0 | BrotliBitReader* br = &s->br; |
1130 | 0 | uint32_t* ringbuffer = &s->block_type_rb[tree_type * 2]; |
1131 | 0 | uint32_t block_type; |
1132 | 0 | if (max_block_type <= 1) { |
1133 | 0 | return BROTLI_FALSE; |
1134 | 0 | } |
1135 | | |
1136 | | /* Read 0..15 + 3..39 bits. */ |
1137 | 0 | if (!safe) { |
1138 | 0 | block_type = ReadSymbol(type_tree, br); |
1139 | 0 | s->block_length[tree_type] = ReadBlockLength(len_tree, br); |
1140 | 0 | } else { |
1141 | 0 | BrotliBitReaderState memento; |
1142 | 0 | BrotliBitReaderSaveState(br, &memento); |
1143 | 0 | if (!SafeReadSymbol(type_tree, br, &block_type)) return BROTLI_FALSE; |
1144 | 0 | if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) { |
1145 | 0 | s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; |
1146 | 0 | BrotliBitReaderRestoreState(br, &memento); |
1147 | 0 | return BROTLI_FALSE; |
1148 | 0 | } |
1149 | 0 | } |
1150 | | |
1151 | 0 | if (block_type == 1) { |
1152 | 0 | block_type = ringbuffer[1] + 1; |
1153 | 0 | } else if (block_type == 0) { |
1154 | 0 | block_type = ringbuffer[0]; |
1155 | 0 | } else { |
1156 | 0 | block_type -= 2; |
1157 | 0 | } |
1158 | 0 | if (block_type >= max_block_type) { |
1159 | 0 | block_type -= max_block_type; |
1160 | 0 | } |
1161 | 0 | ringbuffer[0] = ringbuffer[1]; |
1162 | 0 | ringbuffer[1] = block_type; |
1163 | 0 | return BROTLI_TRUE; |
1164 | 0 | } |
1165 | | |
1166 | | static BROTLI_INLINE void DetectTrivialLiteralBlockTypes( |
1167 | 0 | BrotliDecoderState* s) { |
1168 | 0 | size_t i; |
1169 | 0 | for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0; |
1170 | 0 | for (i = 0; i < s->num_block_types[0]; i++) { |
1171 | 0 | size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS; |
1172 | 0 | size_t error = 0; |
1173 | 0 | size_t sample = s->context_map[offset]; |
1174 | 0 | size_t j; |
1175 | 0 | for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS);) { |
1176 | 0 | BROTLI_REPEAT_4({ error |= s->context_map[offset + j++] ^ sample; }) |
1177 | 0 | } |
1178 | 0 | if (error == 0) { |
1179 | 0 | s->trivial_literal_contexts[i >> 5] |= 1u << (i & 31); |
1180 | 0 | } |
1181 | 0 | } |
1182 | 0 | } |
1183 | | |
1184 | 0 | static BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState* s) { |
1185 | 0 | uint8_t context_mode; |
1186 | 0 | size_t trivial; |
1187 | 0 | uint32_t block_type = s->block_type_rb[1]; |
1188 | 0 | uint32_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS; |
1189 | 0 | s->context_map_slice = s->context_map + context_offset; |
1190 | 0 | trivial = s->trivial_literal_contexts[block_type >> 5]; |
1191 | 0 | s->trivial_literal_context = (trivial >> (block_type & 31)) & 1; |
1192 | 0 | s->literal_htree = s->literal_hgroup.htrees[s->context_map_slice[0]]; |
1193 | 0 | context_mode = s->context_modes[block_type] & 3; |
1194 | 0 | s->context_lookup = BROTLI_CONTEXT_LUT(context_mode); |
1195 | 0 | } |
1196 | | |
1197 | | /* Decodes the block type and updates the state for literal context. |
1198 | | Reads 3..54 bits. */ |
1199 | | static BROTLI_INLINE BROTLI_BOOL DecodeLiteralBlockSwitchInternal( |
1200 | 0 | int safe, BrotliDecoderState* s) { |
1201 | 0 | if (!DecodeBlockTypeAndLength(safe, s, 0)) { |
1202 | 0 | return BROTLI_FALSE; |
1203 | 0 | } |
1204 | 0 | PrepareLiteralDecoding(s); |
1205 | 0 | return BROTLI_TRUE; |
1206 | 0 | } |
1207 | | |
1208 | 0 | static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState* s) { |
1209 | 0 | DecodeLiteralBlockSwitchInternal(0, s); |
1210 | 0 | } |
1211 | | |
1212 | | static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch( |
1213 | 0 | BrotliDecoderState* s) { |
1214 | 0 | return DecodeLiteralBlockSwitchInternal(1, s); |
1215 | 0 | } |
1216 | | |
1217 | | /* Block switch for insert/copy length. |
1218 | | Reads 3..54 bits. */ |
1219 | | static BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal( |
1220 | 0 | int safe, BrotliDecoderState* s) { |
1221 | 0 | if (!DecodeBlockTypeAndLength(safe, s, 1)) { |
1222 | 0 | return BROTLI_FALSE; |
1223 | 0 | } |
1224 | 0 | s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]]; |
1225 | 0 | return BROTLI_TRUE; |
1226 | 0 | } |
1227 | | |
1228 | 0 | static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState* s) { |
1229 | 0 | DecodeCommandBlockSwitchInternal(0, s); |
1230 | 0 | } |
1231 | | |
1232 | | static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch( |
1233 | 0 | BrotliDecoderState* s) { |
1234 | 0 | return DecodeCommandBlockSwitchInternal(1, s); |
1235 | 0 | } |
1236 | | |
1237 | | /* Block switch for distance codes. |
1238 | | Reads 3..54 bits. */ |
1239 | | static BROTLI_INLINE BROTLI_BOOL DecodeDistanceBlockSwitchInternal( |
1240 | 0 | int safe, BrotliDecoderState* s) { |
1241 | 0 | if (!DecodeBlockTypeAndLength(safe, s, 2)) { |
1242 | 0 | return BROTLI_FALSE; |
1243 | 0 | } |
1244 | 0 | s->dist_context_map_slice = s->dist_context_map + |
1245 | 0 | (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS); |
1246 | 0 | s->dist_htree_index = s->dist_context_map_slice[s->distance_context]; |
1247 | 0 | return BROTLI_TRUE; |
1248 | 0 | } |
1249 | | |
1250 | 0 | static void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliDecoderState* s) { |
1251 | 0 | DecodeDistanceBlockSwitchInternal(0, s); |
1252 | 0 | } |
1253 | | |
1254 | | static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch( |
1255 | 0 | BrotliDecoderState* s) { |
1256 | 0 | return DecodeDistanceBlockSwitchInternal(1, s); |
1257 | 0 | } |
1258 | | |
1259 | 0 | static size_t UnwrittenBytes(const BrotliDecoderState* s, BROTLI_BOOL wrap) { |
1260 | 0 | size_t pos = wrap && s->pos > s->ringbuffer_size ? |
1261 | 0 | (size_t)s->ringbuffer_size : (size_t)(s->pos); |
1262 | 0 | size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos; |
1263 | 0 | return partial_pos_rb - s->partial_pos_out; |
1264 | 0 | } |
1265 | | |
1266 | | /* Dumps output. |
1267 | | Returns BROTLI_DECODER_NEEDS_MORE_OUTPUT only if there is more output to push |
1268 | | and either ring-buffer is as big as window size, or |force| is true. */ |
1269 | | static BrotliDecoderErrorCode BROTLI_NOINLINE WriteRingBuffer( |
1270 | | BrotliDecoderState* s, size_t* available_out, uint8_t** next_out, |
1271 | 0 | size_t* total_out, BROTLI_BOOL force) { |
1272 | 0 | uint8_t* start = |
1273 | 0 | s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask); |
1274 | 0 | size_t to_write = UnwrittenBytes(s, BROTLI_TRUE); |
1275 | 0 | size_t num_written = *available_out; |
1276 | 0 | if (num_written > to_write) { |
1277 | 0 | num_written = to_write; |
1278 | 0 | } |
1279 | 0 | if (s->meta_block_remaining_len < 0) { |
1280 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1); |
1281 | 0 | } |
1282 | 0 | if (next_out && !*next_out) { |
1283 | 0 | *next_out = start; |
1284 | 0 | } else { |
1285 | 0 | if (next_out) { |
1286 | 0 | memcpy(*next_out, start, num_written); |
1287 | 0 | *next_out += num_written; |
1288 | 0 | } |
1289 | 0 | } |
1290 | 0 | *available_out -= num_written; |
1291 | 0 | BROTLI_LOG_UINT(to_write); |
1292 | 0 | BROTLI_LOG_UINT(num_written); |
1293 | 0 | s->partial_pos_out += num_written; |
1294 | 0 | if (total_out) { |
1295 | 0 | *total_out = s->partial_pos_out; |
1296 | 0 | } |
1297 | 0 | if (num_written < to_write) { |
1298 | 0 | if (s->ringbuffer_size == (1 << s->window_bits) || force) { |
1299 | 0 | return BROTLI_DECODER_NEEDS_MORE_OUTPUT; |
1300 | 0 | } else { |
1301 | 0 | return BROTLI_DECODER_SUCCESS; |
1302 | 0 | } |
1303 | 0 | } |
1304 | | /* Wrap ring buffer only if it has reached its maximal size. */ |
1305 | 0 | if (s->ringbuffer_size == (1 << s->window_bits) && |
1306 | 0 | s->pos >= s->ringbuffer_size) { |
1307 | 0 | s->pos -= s->ringbuffer_size; |
1308 | 0 | s->rb_roundtrips++; |
1309 | 0 | s->should_wrap_ringbuffer = (size_t)s->pos != 0 ? 1 : 0; |
1310 | 0 | } |
1311 | 0 | return BROTLI_DECODER_SUCCESS; |
1312 | 0 | } |
1313 | | |
1314 | 0 | static void BROTLI_NOINLINE WrapRingBuffer(BrotliDecoderState* s) { |
1315 | 0 | if (s->should_wrap_ringbuffer) { |
1316 | 0 | memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos); |
1317 | 0 | s->should_wrap_ringbuffer = 0; |
1318 | 0 | } |
1319 | 0 | } |
1320 | | |
1321 | | /* Allocates ring-buffer. |
1322 | | |
1323 | | s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before |
1324 | | this function is called. |
1325 | | |
1326 | | Last two bytes of ring-buffer are initialized to 0, so context calculation |
1327 | | could be done uniformly for the first two and all other positions. */ |
1328 | | static BROTLI_BOOL BROTLI_NOINLINE BrotliEnsureRingBuffer( |
1329 | 0 | BrotliDecoderState* s) { |
1330 | 0 | uint8_t* old_ringbuffer = s->ringbuffer; |
1331 | 0 | if (s->ringbuffer_size == s->new_ringbuffer_size) { |
1332 | 0 | return BROTLI_TRUE; |
1333 | 0 | } |
1334 | | |
1335 | 0 | s->ringbuffer = (uint8_t*)BROTLI_DECODER_ALLOC(s, |
1336 | 0 | (size_t)(s->new_ringbuffer_size) + kRingBufferWriteAheadSlack); |
1337 | 0 | if (s->ringbuffer == 0) { |
1338 | | /* Restore previous value. */ |
1339 | 0 | s->ringbuffer = old_ringbuffer; |
1340 | 0 | return BROTLI_FALSE; |
1341 | 0 | } |
1342 | 0 | s->ringbuffer[s->new_ringbuffer_size - 2] = 0; |
1343 | 0 | s->ringbuffer[s->new_ringbuffer_size - 1] = 0; |
1344 | |
|
1345 | 0 | if (!!old_ringbuffer) { |
1346 | 0 | memcpy(s->ringbuffer, old_ringbuffer, (size_t)s->pos); |
1347 | 0 | BROTLI_DECODER_FREE(s, old_ringbuffer); |
1348 | 0 | } |
1349 | |
|
1350 | 0 | s->ringbuffer_size = s->new_ringbuffer_size; |
1351 | 0 | s->ringbuffer_mask = s->new_ringbuffer_size - 1; |
1352 | 0 | s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size; |
1353 | |
|
1354 | 0 | return BROTLI_TRUE; |
1355 | 0 | } |
1356 | | |
1357 | | static BrotliDecoderErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput( |
1358 | | size_t* available_out, uint8_t** next_out, size_t* total_out, |
1359 | 0 | BrotliDecoderState* s) { |
1360 | | /* TODO(eustas): avoid allocation for single uncompressed block. */ |
1361 | 0 | if (!BrotliEnsureRingBuffer(s)) { |
1362 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1); |
1363 | 0 | } |
1364 | | |
1365 | | /* State machine */ |
1366 | 0 | for (;;) { |
1367 | 0 | switch (s->substate_uncompressed) { |
1368 | 0 | case BROTLI_STATE_UNCOMPRESSED_NONE: { |
1369 | 0 | int nbytes = (int)BrotliGetRemainingBytes(&s->br); |
1370 | 0 | if (nbytes > s->meta_block_remaining_len) { |
1371 | 0 | nbytes = s->meta_block_remaining_len; |
1372 | 0 | } |
1373 | 0 | if (s->pos + nbytes > s->ringbuffer_size) { |
1374 | 0 | nbytes = s->ringbuffer_size - s->pos; |
1375 | 0 | } |
1376 | | /* Copy remaining bytes from s->br.buf_ to ring-buffer. */ |
1377 | 0 | BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes); |
1378 | 0 | s->pos += nbytes; |
1379 | 0 | s->meta_block_remaining_len -= nbytes; |
1380 | 0 | if (s->pos < 1 << s->window_bits) { |
1381 | 0 | if (s->meta_block_remaining_len == 0) { |
1382 | 0 | return BROTLI_DECODER_SUCCESS; |
1383 | 0 | } |
1384 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
1385 | 0 | } |
1386 | 0 | s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE; |
1387 | 0 | } |
1388 | | /* Fall through. */ |
1389 | | |
1390 | 0 | case BROTLI_STATE_UNCOMPRESSED_WRITE: { |
1391 | 0 | BrotliDecoderErrorCode result; |
1392 | 0 | result = WriteRingBuffer( |
1393 | 0 | s, available_out, next_out, total_out, BROTLI_FALSE); |
1394 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
1395 | 0 | return result; |
1396 | 0 | } |
1397 | 0 | if (s->ringbuffer_size == 1 << s->window_bits) { |
1398 | 0 | s->max_distance = s->max_backward_distance; |
1399 | 0 | } |
1400 | 0 | s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE; |
1401 | 0 | break; |
1402 | 0 | } |
1403 | 0 | } |
1404 | 0 | } |
1405 | 0 | BROTLI_DCHECK(0); /* Unreachable */ |
1406 | 0 | } |
1407 | | |
1408 | | static BROTLI_BOOL AttachCompoundDictionary( |
1409 | 0 | BrotliDecoderState* state, const uint8_t* data, size_t size) { |
1410 | 0 | BrotliDecoderCompoundDictionary* addon = state->compound_dictionary; |
1411 | 0 | if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE; |
1412 | 0 | if (!addon) { |
1413 | 0 | addon = (BrotliDecoderCompoundDictionary*)BROTLI_DECODER_ALLOC( |
1414 | 0 | state, sizeof(BrotliDecoderCompoundDictionary)); |
1415 | 0 | if (!addon) return BROTLI_FALSE; |
1416 | 0 | addon->num_chunks = 0; |
1417 | 0 | addon->total_size = 0; |
1418 | 0 | addon->br_length = 0; |
1419 | 0 | addon->br_copied = 0; |
1420 | 0 | addon->block_bits = -1; |
1421 | 0 | addon->chunk_offsets[0] = 0; |
1422 | 0 | state->compound_dictionary = addon; |
1423 | 0 | } |
1424 | 0 | if (addon->num_chunks == 15) return BROTLI_FALSE; |
1425 | 0 | addon->chunks[addon->num_chunks] = data; |
1426 | 0 | addon->num_chunks++; |
1427 | 0 | addon->total_size += (int)size; |
1428 | 0 | addon->chunk_offsets[addon->num_chunks] = addon->total_size; |
1429 | 0 | return BROTLI_TRUE; |
1430 | 0 | } |
1431 | | |
1432 | 0 | static void EnsureCoumpoundDictionaryInitialized(BrotliDecoderState* state) { |
1433 | 0 | BrotliDecoderCompoundDictionary* addon = state->compound_dictionary; |
1434 | | /* 256 = (1 << 8) slots in block map. */ |
1435 | 0 | int block_bits = 8; |
1436 | 0 | int cursor = 0; |
1437 | 0 | int index = 0; |
1438 | 0 | if (addon->block_bits != -1) return; |
1439 | 0 | while (((addon->total_size - 1) >> block_bits) != 0) block_bits++; |
1440 | 0 | block_bits -= 8; |
1441 | 0 | addon->block_bits = block_bits; |
1442 | 0 | while (cursor < addon->total_size) { |
1443 | 0 | while (addon->chunk_offsets[index + 1] < cursor) index++; |
1444 | 0 | addon->block_map[cursor >> block_bits] = (uint8_t)index; |
1445 | 0 | cursor += 1 << block_bits; |
1446 | 0 | } |
1447 | 0 | } |
1448 | | |
1449 | | static BROTLI_BOOL InitializeCompoundDictionaryCopy(BrotliDecoderState* s, |
1450 | 0 | int address, int length) { |
1451 | 0 | BrotliDecoderCompoundDictionary* addon = s->compound_dictionary; |
1452 | 0 | int index; |
1453 | 0 | EnsureCoumpoundDictionaryInitialized(s); |
1454 | 0 | index = addon->block_map[address >> addon->block_bits]; |
1455 | 0 | while (address >= addon->chunk_offsets[index + 1]) index++; |
1456 | 0 | if (addon->total_size < address + length) return BROTLI_FALSE; |
1457 | | /* Update the recent distances cache. */ |
1458 | 0 | s->dist_rb[s->dist_rb_idx & 3] = s->distance_code; |
1459 | 0 | ++s->dist_rb_idx; |
1460 | 0 | s->meta_block_remaining_len -= length; |
1461 | 0 | addon->br_index = index; |
1462 | 0 | addon->br_offset = address - addon->chunk_offsets[index]; |
1463 | 0 | addon->br_length = length; |
1464 | 0 | addon->br_copied = 0; |
1465 | 0 | return BROTLI_TRUE; |
1466 | 0 | } |
1467 | | |
1468 | 0 | static int GetCompoundDictionarySize(BrotliDecoderState* s) { |
1469 | 0 | return s->compound_dictionary ? s->compound_dictionary->total_size : 0; |
1470 | 0 | } |
1471 | | |
1472 | 0 | static int CopyFromCompoundDictionary(BrotliDecoderState* s, int pos) { |
1473 | 0 | BrotliDecoderCompoundDictionary* addon = s->compound_dictionary; |
1474 | 0 | int orig_pos = pos; |
1475 | 0 | while (addon->br_length != addon->br_copied) { |
1476 | 0 | uint8_t* copy_dst = &s->ringbuffer[pos]; |
1477 | 0 | const uint8_t* copy_src = |
1478 | 0 | addon->chunks[addon->br_index] + addon->br_offset; |
1479 | 0 | int space = s->ringbuffer_size - pos; |
1480 | 0 | int rem_chunk_length = (addon->chunk_offsets[addon->br_index + 1] - |
1481 | 0 | addon->chunk_offsets[addon->br_index]) - addon->br_offset; |
1482 | 0 | int length = addon->br_length - addon->br_copied; |
1483 | 0 | if (length > rem_chunk_length) length = rem_chunk_length; |
1484 | 0 | if (length > space) length = space; |
1485 | 0 | memcpy(copy_dst, copy_src, (size_t)length); |
1486 | 0 | pos += length; |
1487 | 0 | addon->br_offset += length; |
1488 | 0 | addon->br_copied += length; |
1489 | 0 | if (length == rem_chunk_length) { |
1490 | 0 | addon->br_index++; |
1491 | 0 | addon->br_offset = 0; |
1492 | 0 | } |
1493 | 0 | if (pos == s->ringbuffer_size) break; |
1494 | 0 | } |
1495 | 0 | return pos - orig_pos; |
1496 | 0 | } |
1497 | | |
1498 | | BROTLI_BOOL BrotliDecoderAttachDictionary( |
1499 | | BrotliDecoderState* state, BrotliSharedDictionaryType type, |
1500 | 0 | size_t data_size, const uint8_t data[BROTLI_ARRAY_PARAM(data_size)]) { |
1501 | 0 | uint32_t i; |
1502 | 0 | uint32_t num_prefix_before = state->dictionary->num_prefix; |
1503 | 0 | if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE; |
1504 | 0 | if (!BrotliSharedDictionaryAttach(state->dictionary, type, data_size, data)) { |
1505 | 0 | return BROTLI_FALSE; |
1506 | 0 | } |
1507 | 0 | for (i = num_prefix_before; i < state->dictionary->num_prefix; i++) { |
1508 | 0 | if (!AttachCompoundDictionary( |
1509 | 0 | state, state->dictionary->prefix[i], |
1510 | 0 | state->dictionary->prefix_size[i])) { |
1511 | 0 | return BROTLI_FALSE; |
1512 | 0 | } |
1513 | 0 | } |
1514 | 0 | return BROTLI_TRUE; |
1515 | 0 | } |
1516 | | |
1517 | | /* Calculates the smallest feasible ring buffer. |
1518 | | |
1519 | | If we know the data size is small, do not allocate more ring buffer |
1520 | | size than needed to reduce memory usage. |
1521 | | |
1522 | | When this method is called, metablock size and flags MUST be decoded. */ |
1523 | | static void BROTLI_NOINLINE BrotliCalculateRingBufferSize( |
1524 | 0 | BrotliDecoderState* s) { |
1525 | 0 | int window_size = 1 << s->window_bits; |
1526 | 0 | int new_ringbuffer_size = window_size; |
1527 | | /* We need at least 2 bytes of ring buffer size to get the last two |
1528 | | bytes for context from there */ |
1529 | 0 | int min_size = s->ringbuffer_size ? s->ringbuffer_size : 1024; |
1530 | 0 | int output_size; |
1531 | | |
1532 | | /* If maximum is already reached, no further extension is retired. */ |
1533 | 0 | if (s->ringbuffer_size == window_size) { |
1534 | 0 | return; |
1535 | 0 | } |
1536 | | |
1537 | | /* Metadata blocks does not touch ring buffer. */ |
1538 | 0 | if (s->is_metadata) { |
1539 | 0 | return; |
1540 | 0 | } |
1541 | | |
1542 | 0 | if (!s->ringbuffer) { |
1543 | 0 | output_size = 0; |
1544 | 0 | } else { |
1545 | 0 | output_size = s->pos; |
1546 | 0 | } |
1547 | 0 | output_size += s->meta_block_remaining_len; |
1548 | 0 | min_size = min_size < output_size ? output_size : min_size; |
1549 | |
|
1550 | 0 | if (!!s->canny_ringbuffer_allocation) { |
1551 | | /* Reduce ring buffer size to save memory when server is unscrupulous. |
1552 | | In worst case memory usage might be 1.5x bigger for a short period of |
1553 | | ring buffer reallocation. */ |
1554 | 0 | while ((new_ringbuffer_size >> 1) >= min_size) { |
1555 | 0 | new_ringbuffer_size >>= 1; |
1556 | 0 | } |
1557 | 0 | } |
1558 | |
|
1559 | 0 | s->new_ringbuffer_size = new_ringbuffer_size; |
1560 | 0 | } |
1561 | | |
1562 | | /* Reads 1..256 2-bit context modes. */ |
1563 | 0 | static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) { |
1564 | 0 | BrotliBitReader* br = &s->br; |
1565 | 0 | int i = s->loop_counter; |
1566 | |
|
1567 | 0 | while (i < (int)s->num_block_types[0]) { |
1568 | 0 | uint32_t bits; |
1569 | 0 | if (!BrotliSafeReadBits(br, 2, &bits)) { |
1570 | 0 | s->loop_counter = i; |
1571 | 0 | return BROTLI_DECODER_NEEDS_MORE_INPUT; |
1572 | 0 | } |
1573 | 0 | s->context_modes[i] = (uint8_t)bits; |
1574 | 0 | BROTLI_LOG_ARRAY_INDEX(s->context_modes, i); |
1575 | 0 | i++; |
1576 | 0 | } |
1577 | 0 | return BROTLI_DECODER_SUCCESS; |
1578 | 0 | } |
1579 | | |
1580 | 0 | static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) { |
1581 | 0 | int offset = s->distance_code - 3; |
1582 | 0 | if (s->distance_code <= 3) { |
1583 | | /* Compensate double distance-ring-buffer roll for dictionary items. */ |
1584 | 0 | s->distance_context = 1 >> s->distance_code; |
1585 | 0 | s->distance_code = s->dist_rb[(s->dist_rb_idx - offset) & 3]; |
1586 | 0 | s->dist_rb_idx -= s->distance_context; |
1587 | 0 | } else { |
1588 | 0 | int index_delta = 3; |
1589 | 0 | int delta; |
1590 | 0 | int base = s->distance_code - 10; |
1591 | 0 | if (s->distance_code < 10) { |
1592 | 0 | base = s->distance_code - 4; |
1593 | 0 | } else { |
1594 | 0 | index_delta = 2; |
1595 | 0 | } |
1596 | | /* Unpack one of six 4-bit values. */ |
1597 | 0 | delta = ((0x605142 >> (4 * base)) & 0xF) - 3; |
1598 | 0 | s->distance_code = s->dist_rb[(s->dist_rb_idx + index_delta) & 0x3] + delta; |
1599 | 0 | if (s->distance_code <= 0) { |
1600 | | /* A huge distance will cause a BROTLI_FAILURE() soon. |
1601 | | This is a little faster than failing here. */ |
1602 | 0 | s->distance_code = 0x7FFFFFFF; |
1603 | 0 | } |
1604 | 0 | } |
1605 | 0 | } |
1606 | | |
1607 | | static BROTLI_INLINE BROTLI_BOOL SafeReadBits( |
1608 | 0 | BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) { |
1609 | 0 | if (n_bits != 0) { |
1610 | 0 | return BrotliSafeReadBits(br, n_bits, val); |
1611 | 0 | } else { |
1612 | 0 | *val = 0; |
1613 | 0 | return BROTLI_TRUE; |
1614 | 0 | } |
1615 | 0 | } |
1616 | | |
1617 | | static BROTLI_INLINE BROTLI_BOOL SafeReadBits32( |
1618 | 0 | BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) { |
1619 | 0 | if (n_bits != 0) { |
1620 | 0 | return BrotliSafeReadBits32(br, n_bits, val); |
1621 | 0 | } else { |
1622 | 0 | *val = 0; |
1623 | 0 | return BROTLI_TRUE; |
1624 | 0 | } |
1625 | 0 | } |
1626 | | |
1627 | | /* |
1628 | | RFC 7932 Section 4 with "..." shortenings and "[]" emendations. |
1629 | | |
1630 | | Each distance ... is represented with a pair <distance code, extra bits>... |
1631 | | The distance code is encoded using a prefix code... The number of extra bits |
1632 | | can be 0..24... Two additional parameters: NPOSTFIX (0..3), and ... |
1633 | | NDIRECT (0..120) ... are encoded in the meta-block header... |
1634 | | |
1635 | | The first 16 distance symbols ... reference past distances... ring buffer ... |
1636 | | Next NDIRECT distance symbols ... represent distances from 1 to NDIRECT... |
1637 | | [For] distance symbols 16 + NDIRECT and greater ... the number of extra bits |
1638 | | ... is given by the following formula: |
1639 | | |
1640 | | [ xcode = dcode - NDIRECT - 16 ] |
1641 | | ndistbits = 1 + [ xcode ] >> (NPOSTFIX + 1) |
1642 | | |
1643 | | ... |
1644 | | */ |
1645 | | |
1646 | | /* |
1647 | | RFC 7932 Section 9.2 with "..." shortenings and "[]" emendations. |
1648 | | |
1649 | | ... to get the actual value of the parameter NDIRECT, left-shift this |
1650 | | four-bit number by NPOSTFIX bits ... |
1651 | | */ |
1652 | | |
1653 | | /* Remaining formulas from RFC 7932 Section 4 could be rewritten as following: |
1654 | | |
1655 | | alphabet_size = 16 + NDIRECT + (max_distbits << (NPOSTFIX + 1)) |
1656 | | |
1657 | | half = ((xcode >> NPOSTFIX) & 1) << ndistbits |
1658 | | postfix = xcode & ((1 << NPOSTFIX) - 1) |
1659 | | range_start = 2 * (1 << ndistbits - 1 - 1) |
1660 | | |
1661 | | distance = (range_start + half + extra) << NPOSTFIX + postfix + NDIRECT + 1 |
1662 | | |
1663 | | NB: ndistbits >= 1 -> range_start >= 0 |
1664 | | NB: range_start has factor 2, as the range is covered by 2 "halves" |
1665 | | NB: extra -1 offset in range_start formula covers the absence of |
1666 | | ndistbits = 0 case |
1667 | | NB: when NPOSTFIX = 0, NDIRECT is not greater than 15 |
1668 | | |
1669 | | In other words, xcode has the following binary structure - XXXHPPP: |
1670 | | - XXX represent the number of extra distance bits |
1671 | | - H selects upper / lower range of distances |
1672 | | - PPP represent "postfix" |
1673 | | |
1674 | | "Regular" distance encoding has NPOSTFIX = 0; omitting the postfix part |
1675 | | simplifies distance calculation. |
1676 | | |
1677 | | Using NPOSTFIX > 0 allows cheaper encoding of regular structures, e.g. where |
1678 | | most of distances have the same reminder of division by 2/4/8. For example, |
1679 | | the table of int32_t values that come from different sources; if it is likely |
1680 | | that 3 highest bytes of values from the same source are the same, then |
1681 | | copy distance often looks like 4x + y. |
1682 | | |
1683 | | Distance calculation could be rewritten to: |
1684 | | |
1685 | | ndistbits = NDISTBITS(NDIRECT, NPOSTFIX)[dcode] |
1686 | | distance = OFFSET(NDIRECT, NPOSTFIX)[dcode] + extra << NPOSTFIX |
1687 | | |
1688 | | NDISTBITS and OFFSET could be pre-calculated, as NDIRECT and NPOSTFIX could |
1689 | | change only once per meta-block. |
1690 | | */ |
1691 | | |
1692 | | /* Calculates distance lookup table. |
1693 | | NB: it is possible to have all 64 tables precalculated. */ |
1694 | 0 | static void CalculateDistanceLut(BrotliDecoderState* s) { |
1695 | 0 | BrotliMetablockBodyArena* b = &s->arena.body; |
1696 | 0 | uint32_t npostfix = s->distance_postfix_bits; |
1697 | 0 | uint32_t ndirect = s->num_direct_distance_codes; |
1698 | 0 | uint32_t alphabet_size_limit = s->distance_hgroup.alphabet_size_limit; |
1699 | 0 | uint32_t postfix = 1u << npostfix; |
1700 | 0 | uint32_t j; |
1701 | 0 | uint32_t bits = 1; |
1702 | 0 | uint32_t half = 0; |
1703 | | |
1704 | | /* Skip short codes. */ |
1705 | 0 | uint32_t i = BROTLI_NUM_DISTANCE_SHORT_CODES; |
1706 | | |
1707 | | /* Fill direct codes. */ |
1708 | 0 | for (j = 0; j < ndirect; ++j) { |
1709 | 0 | b->dist_extra_bits[i] = 0; |
1710 | 0 | b->dist_offset[i] = j + 1; |
1711 | 0 | ++i; |
1712 | 0 | } |
1713 | | |
1714 | | /* Fill regular distance codes. */ |
1715 | 0 | while (i < alphabet_size_limit) { |
1716 | 0 | uint32_t base = ndirect + ((((2 + half) << bits) - 4) << npostfix) + 1; |
1717 | | /* Always fill the complete group. */ |
1718 | 0 | for (j = 0; j < postfix; ++j) { |
1719 | 0 | b->dist_extra_bits[i] = (uint8_t)bits; |
1720 | 0 | b->dist_offset[i] = base + j; |
1721 | 0 | ++i; |
1722 | 0 | } |
1723 | 0 | bits = bits + half; |
1724 | 0 | half = half ^ 1; |
1725 | 0 | } |
1726 | 0 | } |
1727 | | |
1728 | | /* Precondition: s->distance_code < 0. */ |
1729 | | static BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal( |
1730 | 0 | int safe, BrotliDecoderState* s, BrotliBitReader* br) { |
1731 | 0 | BrotliMetablockBodyArena* b = &s->arena.body; |
1732 | 0 | uint32_t code; |
1733 | 0 | uint32_t bits; |
1734 | 0 | BrotliBitReaderState memento; |
1735 | 0 | HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index]; |
1736 | 0 | if (!safe) { |
1737 | 0 | code = ReadSymbol(distance_tree, br); |
1738 | 0 | } else { |
1739 | 0 | BrotliBitReaderSaveState(br, &memento); |
1740 | 0 | if (!SafeReadSymbol(distance_tree, br, &code)) { |
1741 | 0 | return BROTLI_FALSE; |
1742 | 0 | } |
1743 | 0 | } |
1744 | 0 | --s->block_length[2]; |
1745 | | /* Convert the distance code to the actual distance by possibly |
1746 | | looking up past distances from the s->dist_rb. */ |
1747 | 0 | s->distance_context = 0; |
1748 | 0 | if ((code & ~0xFu) == 0) { |
1749 | 0 | s->distance_code = (int)code; |
1750 | 0 | TakeDistanceFromRingBuffer(s); |
1751 | 0 | return BROTLI_TRUE; |
1752 | 0 | } |
1753 | 0 | if (!safe) { |
1754 | 0 | bits = BrotliReadBits32(br, b->dist_extra_bits[code]); |
1755 | 0 | } else { |
1756 | 0 | if (!SafeReadBits32(br, b->dist_extra_bits[code], &bits)) { |
1757 | 0 | ++s->block_length[2]; |
1758 | 0 | BrotliBitReaderRestoreState(br, &memento); |
1759 | 0 | return BROTLI_FALSE; |
1760 | 0 | } |
1761 | 0 | } |
1762 | 0 | s->distance_code = |
1763 | 0 | (int)(b->dist_offset[code] + (bits << s->distance_postfix_bits)); |
1764 | 0 | return BROTLI_TRUE; |
1765 | 0 | } |
1766 | | |
1767 | | static BROTLI_INLINE void ReadDistance( |
1768 | 0 | BrotliDecoderState* s, BrotliBitReader* br) { |
1769 | 0 | ReadDistanceInternal(0, s, br); |
1770 | 0 | } |
1771 | | |
1772 | | static BROTLI_INLINE BROTLI_BOOL SafeReadDistance( |
1773 | 0 | BrotliDecoderState* s, BrotliBitReader* br) { |
1774 | 0 | return ReadDistanceInternal(1, s, br); |
1775 | 0 | } |
1776 | | |
1777 | | static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal( |
1778 | 0 | int safe, BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) { |
1779 | 0 | uint32_t cmd_code; |
1780 | 0 | uint32_t insert_len_extra = 0; |
1781 | 0 | uint32_t copy_length; |
1782 | 0 | CmdLutElement v; |
1783 | 0 | BrotliBitReaderState memento; |
1784 | 0 | if (!safe) { |
1785 | 0 | cmd_code = ReadSymbol(s->htree_command, br); |
1786 | 0 | } else { |
1787 | 0 | BrotliBitReaderSaveState(br, &memento); |
1788 | 0 | if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) { |
1789 | 0 | return BROTLI_FALSE; |
1790 | 0 | } |
1791 | 0 | } |
1792 | 0 | v = kCmdLut[cmd_code]; |
1793 | 0 | s->distance_code = v.distance_code; |
1794 | 0 | s->distance_context = v.context; |
1795 | 0 | s->dist_htree_index = s->dist_context_map_slice[s->distance_context]; |
1796 | 0 | *insert_length = v.insert_len_offset; |
1797 | 0 | if (!safe) { |
1798 | 0 | if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)) { |
1799 | 0 | insert_len_extra = BrotliReadBits24(br, v.insert_len_extra_bits); |
1800 | 0 | } |
1801 | 0 | copy_length = BrotliReadBits24(br, v.copy_len_extra_bits); |
1802 | 0 | } else { |
1803 | 0 | if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) || |
1804 | 0 | !SafeReadBits(br, v.copy_len_extra_bits, ©_length)) { |
1805 | 0 | BrotliBitReaderRestoreState(br, &memento); |
1806 | 0 | return BROTLI_FALSE; |
1807 | 0 | } |
1808 | 0 | } |
1809 | 0 | s->copy_length = (int)copy_length + v.copy_len_offset; |
1810 | 0 | --s->block_length[1]; |
1811 | 0 | *insert_length += (int)insert_len_extra; |
1812 | 0 | return BROTLI_TRUE; |
1813 | 0 | } |
1814 | | |
1815 | | static BROTLI_INLINE void ReadCommand( |
1816 | 0 | BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) { |
1817 | 0 | ReadCommandInternal(0, s, br, insert_length); |
1818 | 0 | } |
1819 | | |
1820 | | static BROTLI_INLINE BROTLI_BOOL SafeReadCommand( |
1821 | 0 | BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) { |
1822 | 0 | return ReadCommandInternal(1, s, br, insert_length); |
1823 | 0 | } |
1824 | | |
1825 | | static BROTLI_INLINE BROTLI_BOOL CheckInputAmount( |
1826 | 0 | int safe, BrotliBitReader* const br, size_t num) { |
1827 | 0 | if (safe) { |
1828 | 0 | return BROTLI_TRUE; |
1829 | 0 | } |
1830 | 0 | return BrotliCheckInputAmount(br, num); |
1831 | 0 | } |
1832 | | |
1833 | | #define BROTLI_SAFE(METHOD) \ |
1834 | 0 | { \ |
1835 | 0 | if (safe) { \ |
1836 | 0 | if (!Safe##METHOD) { \ |
1837 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; \ |
1838 | 0 | goto saveStateAndReturn; \ |
1839 | 0 | } \ |
1840 | 0 | } else { \ |
1841 | 0 | METHOD; \ |
1842 | 0 | } \ |
1843 | 0 | } |
1844 | | |
1845 | | static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal( |
1846 | 0 | int safe, BrotliDecoderState* s) { |
1847 | 0 | int pos = s->pos; |
1848 | 0 | int i = s->loop_counter; |
1849 | 0 | BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS; |
1850 | 0 | BrotliBitReader* br = &s->br; |
1851 | 0 | int compound_dictionary_size = GetCompoundDictionarySize(s); |
1852 | |
|
1853 | 0 | if (!CheckInputAmount(safe, br, 28)) { |
1854 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
1855 | 0 | goto saveStateAndReturn; |
1856 | 0 | } |
1857 | 0 | if (!safe) { |
1858 | 0 | BROTLI_UNUSED(BrotliWarmupBitReader(br)); |
1859 | 0 | } |
1860 | | |
1861 | | /* Jump into state machine. */ |
1862 | 0 | if (s->state == BROTLI_STATE_COMMAND_BEGIN) { |
1863 | 0 | goto CommandBegin; |
1864 | 0 | } else if (s->state == BROTLI_STATE_COMMAND_INNER) { |
1865 | 0 | goto CommandInner; |
1866 | 0 | } else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) { |
1867 | 0 | goto CommandPostDecodeLiterals; |
1868 | 0 | } else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) { |
1869 | 0 | goto CommandPostWrapCopy; |
1870 | 0 | } else { |
1871 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); /* COV_NF_LINE */ |
1872 | 0 | } |
1873 | | |
1874 | 0 | CommandBegin: |
1875 | 0 | if (safe) { |
1876 | 0 | s->state = BROTLI_STATE_COMMAND_BEGIN; |
1877 | 0 | } |
1878 | 0 | if (!CheckInputAmount(safe, br, 28)) { /* 156 bits + 7 bytes */ |
1879 | 0 | s->state = BROTLI_STATE_COMMAND_BEGIN; |
1880 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
1881 | 0 | goto saveStateAndReturn; |
1882 | 0 | } |
1883 | 0 | if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)) { |
1884 | 0 | BROTLI_SAFE(DecodeCommandBlockSwitch(s)); |
1885 | 0 | goto CommandBegin; |
1886 | 0 | } |
1887 | | /* Read the insert/copy length in the command. */ |
1888 | 0 | BROTLI_SAFE(ReadCommand(s, br, &i)); |
1889 | 0 | BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n", |
1890 | 0 | pos, i, s->copy_length)); |
1891 | 0 | if (i == 0) { |
1892 | 0 | goto CommandPostDecodeLiterals; |
1893 | 0 | } |
1894 | 0 | s->meta_block_remaining_len -= i; |
1895 | |
|
1896 | 0 | CommandInner: |
1897 | 0 | if (safe) { |
1898 | 0 | s->state = BROTLI_STATE_COMMAND_INNER; |
1899 | 0 | } |
1900 | | /* Read the literals in the command. */ |
1901 | 0 | if (s->trivial_literal_context) { |
1902 | 0 | uint32_t bits; |
1903 | 0 | uint32_t value; |
1904 | 0 | PreloadSymbol(safe, s->literal_htree, br, &bits, &value); |
1905 | 0 | do { |
1906 | 0 | if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */ |
1907 | 0 | s->state = BROTLI_STATE_COMMAND_INNER; |
1908 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
1909 | 0 | goto saveStateAndReturn; |
1910 | 0 | } |
1911 | 0 | if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) { |
1912 | 0 | BROTLI_SAFE(DecodeLiteralBlockSwitch(s)); |
1913 | 0 | PreloadSymbol(safe, s->literal_htree, br, &bits, &value); |
1914 | 0 | if (!s->trivial_literal_context) goto CommandInner; |
1915 | 0 | } |
1916 | 0 | if (!safe) { |
1917 | 0 | s->ringbuffer[pos] = |
1918 | 0 | (uint8_t)ReadPreloadedSymbol(s->literal_htree, br, &bits, &value); |
1919 | 0 | } else { |
1920 | 0 | uint32_t literal; |
1921 | 0 | if (!SafeReadSymbol(s->literal_htree, br, &literal)) { |
1922 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
1923 | 0 | goto saveStateAndReturn; |
1924 | 0 | } |
1925 | 0 | s->ringbuffer[pos] = (uint8_t)literal; |
1926 | 0 | } |
1927 | 0 | --s->block_length[0]; |
1928 | 0 | BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos); |
1929 | 0 | ++pos; |
1930 | 0 | if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) { |
1931 | 0 | s->state = BROTLI_STATE_COMMAND_INNER_WRITE; |
1932 | 0 | --i; |
1933 | 0 | goto saveStateAndReturn; |
1934 | 0 | } |
1935 | 0 | } while (--i != 0); |
1936 | 0 | } else { |
1937 | 0 | uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask]; |
1938 | 0 | uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask]; |
1939 | 0 | do { |
1940 | 0 | const HuffmanCode* hc; |
1941 | 0 | uint8_t context; |
1942 | 0 | if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */ |
1943 | 0 | s->state = BROTLI_STATE_COMMAND_INNER; |
1944 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
1945 | 0 | goto saveStateAndReturn; |
1946 | 0 | } |
1947 | 0 | if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) { |
1948 | 0 | BROTLI_SAFE(DecodeLiteralBlockSwitch(s)); |
1949 | 0 | if (s->trivial_literal_context) goto CommandInner; |
1950 | 0 | } |
1951 | 0 | context = BROTLI_CONTEXT(p1, p2, s->context_lookup); |
1952 | 0 | BROTLI_LOG_UINT(context); |
1953 | 0 | hc = s->literal_hgroup.htrees[s->context_map_slice[context]]; |
1954 | 0 | p2 = p1; |
1955 | 0 | if (!safe) { |
1956 | 0 | p1 = (uint8_t)ReadSymbol(hc, br); |
1957 | 0 | } else { |
1958 | 0 | uint32_t literal; |
1959 | 0 | if (!SafeReadSymbol(hc, br, &literal)) { |
1960 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
1961 | 0 | goto saveStateAndReturn; |
1962 | 0 | } |
1963 | 0 | p1 = (uint8_t)literal; |
1964 | 0 | } |
1965 | 0 | s->ringbuffer[pos] = p1; |
1966 | 0 | --s->block_length[0]; |
1967 | 0 | BROTLI_LOG_UINT(s->context_map_slice[context]); |
1968 | 0 | BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask); |
1969 | 0 | ++pos; |
1970 | 0 | if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) { |
1971 | 0 | s->state = BROTLI_STATE_COMMAND_INNER_WRITE; |
1972 | 0 | --i; |
1973 | 0 | goto saveStateAndReturn; |
1974 | 0 | } |
1975 | 0 | } while (--i != 0); |
1976 | 0 | } |
1977 | 0 | BROTLI_LOG_UINT(s->meta_block_remaining_len); |
1978 | 0 | if (BROTLI_PREDICT_FALSE(s->meta_block_remaining_len <= 0)) { |
1979 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
1980 | 0 | goto saveStateAndReturn; |
1981 | 0 | } |
1982 | | |
1983 | 0 | CommandPostDecodeLiterals: |
1984 | 0 | if (safe) { |
1985 | 0 | s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS; |
1986 | 0 | } |
1987 | 0 | if (s->distance_code >= 0) { |
1988 | | /* Implicit distance case. */ |
1989 | 0 | s->distance_context = s->distance_code ? 0 : 1; |
1990 | 0 | --s->dist_rb_idx; |
1991 | 0 | s->distance_code = s->dist_rb[s->dist_rb_idx & 3]; |
1992 | 0 | } else { |
1993 | | /* Read distance code in the command, unless it was implicitly zero. */ |
1994 | 0 | if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)) { |
1995 | 0 | BROTLI_SAFE(DecodeDistanceBlockSwitch(s)); |
1996 | 0 | } |
1997 | 0 | BROTLI_SAFE(ReadDistance(s, br)); |
1998 | 0 | } |
1999 | 0 | BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n", |
2000 | 0 | pos, s->distance_code)); |
2001 | 0 | if (s->max_distance != s->max_backward_distance) { |
2002 | 0 | s->max_distance = |
2003 | 0 | (pos < s->max_backward_distance) ? pos : s->max_backward_distance; |
2004 | 0 | } |
2005 | 0 | i = s->copy_length; |
2006 | | /* Apply copy of LZ77 back-reference, or static dictionary reference if |
2007 | | the distance is larger than the max LZ77 distance */ |
2008 | 0 | if (s->distance_code > s->max_distance) { |
2009 | | /* The maximum allowed distance is BROTLI_MAX_ALLOWED_DISTANCE = 0x7FFFFFFC. |
2010 | | With this choice, no signed overflow can occur after decoding |
2011 | | a special distance code (e.g., after adding 3 to the last distance). */ |
2012 | 0 | if (s->distance_code > BROTLI_MAX_ALLOWED_DISTANCE) { |
2013 | 0 | BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " |
2014 | 0 | "len: %d bytes left: %d\n", |
2015 | 0 | pos, s->distance_code, i, s->meta_block_remaining_len)); |
2016 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DISTANCE); |
2017 | 0 | } |
2018 | 0 | if (s->distance_code - s->max_distance - 1 < compound_dictionary_size) { |
2019 | 0 | int address = compound_dictionary_size - |
2020 | 0 | (s->distance_code - s->max_distance); |
2021 | 0 | if (!InitializeCompoundDictionaryCopy(s, address, i)) { |
2022 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_COMPOUND_DICTIONARY); |
2023 | 0 | } |
2024 | 0 | pos += CopyFromCompoundDictionary(s, pos); |
2025 | 0 | if (pos >= s->ringbuffer_size) { |
2026 | 0 | s->state = BROTLI_STATE_COMMAND_POST_WRITE_1; |
2027 | 0 | goto saveStateAndReturn; |
2028 | 0 | } |
2029 | 0 | } else if (i >= SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH && |
2030 | 0 | i <= SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH) { |
2031 | 0 | uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask]; |
2032 | 0 | uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask]; |
2033 | 0 | uint8_t dict_id = s->dictionary->context_based ? |
2034 | 0 | s->dictionary->context_map[BROTLI_CONTEXT(p1, p2, s->context_lookup)] |
2035 | 0 | : 0; |
2036 | 0 | const BrotliDictionary* words = s->dictionary->words[dict_id]; |
2037 | 0 | const BrotliTransforms* transforms = s->dictionary->transforms[dict_id]; |
2038 | 0 | int offset = (int)words->offsets_by_length[i]; |
2039 | 0 | uint32_t shift = words->size_bits_by_length[i]; |
2040 | 0 | int address = |
2041 | 0 | s->distance_code - s->max_distance - 1 - compound_dictionary_size; |
2042 | 0 | int mask = (int)BitMask(shift); |
2043 | 0 | int word_idx = address & mask; |
2044 | 0 | int transform_idx = address >> shift; |
2045 | | /* Compensate double distance-ring-buffer roll. */ |
2046 | 0 | s->dist_rb_idx += s->distance_context; |
2047 | 0 | offset += word_idx * i; |
2048 | | /* If the distance is out of bound, select a next static dictionary if |
2049 | | there exist multiple. */ |
2050 | 0 | if ((transform_idx >= (int)transforms->num_transforms || |
2051 | 0 | words->size_bits_by_length[i] == 0) && |
2052 | 0 | s->dictionary->num_dictionaries > 1) { |
2053 | 0 | uint8_t dict_id2; |
2054 | 0 | int dist_remaining = address - |
2055 | 0 | (int)(((1u << shift) & ~1u)) * (int)transforms->num_transforms; |
2056 | 0 | for (dict_id2 = 0; dict_id2 < s->dictionary->num_dictionaries; |
2057 | 0 | dict_id2++) { |
2058 | 0 | const BrotliDictionary* words2 = s->dictionary->words[dict_id2]; |
2059 | 0 | if (dict_id2 != dict_id && words2->size_bits_by_length[i] != 0) { |
2060 | 0 | const BrotliTransforms* transforms2 = |
2061 | 0 | s->dictionary->transforms[dict_id2]; |
2062 | 0 | uint32_t shift2 = words2->size_bits_by_length[i]; |
2063 | 0 | int num = (int)((1u << shift2) & ~1u) * |
2064 | 0 | (int)transforms2->num_transforms; |
2065 | 0 | if (dist_remaining < num) { |
2066 | 0 | dict_id = dict_id2; |
2067 | 0 | words = words2; |
2068 | 0 | transforms = transforms2; |
2069 | 0 | address = dist_remaining; |
2070 | 0 | shift = shift2; |
2071 | 0 | mask = (int)BitMask(shift); |
2072 | 0 | word_idx = address & mask; |
2073 | 0 | transform_idx = address >> shift; |
2074 | 0 | offset = (int)words->offsets_by_length[i] + word_idx * i; |
2075 | 0 | break; |
2076 | 0 | } |
2077 | 0 | dist_remaining -= num; |
2078 | 0 | } |
2079 | 0 | } |
2080 | 0 | } |
2081 | 0 | if (BROTLI_PREDICT_FALSE(words->size_bits_by_length[i] == 0)) { |
2082 | 0 | BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " |
2083 | 0 | "len: %d bytes left: %d\n", |
2084 | 0 | pos, s->distance_code, i, s->meta_block_remaining_len)); |
2085 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY); |
2086 | 0 | } |
2087 | 0 | if (BROTLI_PREDICT_FALSE(!words->data)) { |
2088 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET); |
2089 | 0 | } |
2090 | 0 | if (transform_idx < (int)transforms->num_transforms) { |
2091 | 0 | const uint8_t* word = &words->data[offset]; |
2092 | 0 | int len = i; |
2093 | 0 | if (transform_idx == transforms->cutOffTransforms[0]) { |
2094 | 0 | memcpy(&s->ringbuffer[pos], word, (size_t)len); |
2095 | 0 | BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]\n", |
2096 | 0 | len, word)); |
2097 | 0 | } else { |
2098 | 0 | len = BrotliTransformDictionaryWord(&s->ringbuffer[pos], word, len, |
2099 | 0 | transforms, transform_idx); |
2100 | 0 | BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]," |
2101 | 0 | " transform_idx = %d, transformed: [%.*s]\n", |
2102 | 0 | i, word, transform_idx, len, &s->ringbuffer[pos])); |
2103 | 0 | if (len == 0 && s->distance_code <= 120) { |
2104 | 0 | BROTLI_LOG(("Invalid length-0 dictionary word after transform\n")); |
2105 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM); |
2106 | 0 | } |
2107 | 0 | } |
2108 | 0 | pos += len; |
2109 | 0 | s->meta_block_remaining_len -= len; |
2110 | 0 | if (pos >= s->ringbuffer_size) { |
2111 | 0 | s->state = BROTLI_STATE_COMMAND_POST_WRITE_1; |
2112 | 0 | goto saveStateAndReturn; |
2113 | 0 | } |
2114 | 0 | } else { |
2115 | 0 | BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " |
2116 | 0 | "len: %d bytes left: %d\n", |
2117 | 0 | pos, s->distance_code, i, s->meta_block_remaining_len)); |
2118 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM); |
2119 | 0 | } |
2120 | 0 | } else { |
2121 | 0 | BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " |
2122 | 0 | "len: %d bytes left: %d\n", |
2123 | 0 | pos, s->distance_code, i, s->meta_block_remaining_len)); |
2124 | 0 | return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY); |
2125 | 0 | } |
2126 | 0 | } else { |
2127 | 0 | int src_start = (pos - s->distance_code) & s->ringbuffer_mask; |
2128 | 0 | uint8_t* copy_dst = &s->ringbuffer[pos]; |
2129 | 0 | uint8_t* copy_src = &s->ringbuffer[src_start]; |
2130 | 0 | int dst_end = pos + i; |
2131 | 0 | int src_end = src_start + i; |
2132 | | /* Update the recent distances cache. */ |
2133 | 0 | s->dist_rb[s->dist_rb_idx & 3] = s->distance_code; |
2134 | 0 | ++s->dist_rb_idx; |
2135 | 0 | s->meta_block_remaining_len -= i; |
2136 | | /* There are 32+ bytes of slack in the ring-buffer allocation. |
2137 | | Also, we have 16 short codes, that make these 16 bytes irrelevant |
2138 | | in the ring-buffer. Let's copy over them as a first guess. */ |
2139 | 0 | memmove16(copy_dst, copy_src); |
2140 | 0 | if (src_end > pos && dst_end > src_start) { |
2141 | | /* Regions intersect. */ |
2142 | 0 | goto CommandPostWrapCopy; |
2143 | 0 | } |
2144 | 0 | if (dst_end >= s->ringbuffer_size || src_end >= s->ringbuffer_size) { |
2145 | | /* At least one region wraps. */ |
2146 | 0 | goto CommandPostWrapCopy; |
2147 | 0 | } |
2148 | 0 | pos += i; |
2149 | 0 | if (i > 16) { |
2150 | 0 | if (i > 32) { |
2151 | 0 | memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16)); |
2152 | 0 | } else { |
2153 | | /* This branch covers about 45% cases. |
2154 | | Fixed size short copy allows more compiler optimizations. */ |
2155 | 0 | memmove16(copy_dst + 16, copy_src + 16); |
2156 | 0 | } |
2157 | 0 | } |
2158 | 0 | } |
2159 | 0 | BROTLI_LOG_UINT(s->meta_block_remaining_len); |
2160 | 0 | if (s->meta_block_remaining_len <= 0) { |
2161 | | /* Next metablock, if any. */ |
2162 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2163 | 0 | goto saveStateAndReturn; |
2164 | 0 | } else { |
2165 | 0 | goto CommandBegin; |
2166 | 0 | } |
2167 | 0 | CommandPostWrapCopy: |
2168 | 0 | { |
2169 | 0 | int wrap_guard = s->ringbuffer_size - pos; |
2170 | 0 | while (--i >= 0) { |
2171 | 0 | s->ringbuffer[pos] = |
2172 | 0 | s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask]; |
2173 | 0 | ++pos; |
2174 | 0 | if (BROTLI_PREDICT_FALSE(--wrap_guard == 0)) { |
2175 | 0 | s->state = BROTLI_STATE_COMMAND_POST_WRITE_2; |
2176 | 0 | goto saveStateAndReturn; |
2177 | 0 | } |
2178 | 0 | } |
2179 | 0 | } |
2180 | 0 | if (s->meta_block_remaining_len <= 0) { |
2181 | | /* Next metablock, if any. */ |
2182 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2183 | 0 | goto saveStateAndReturn; |
2184 | 0 | } else { |
2185 | 0 | goto CommandBegin; |
2186 | 0 | } |
2187 | | |
2188 | 0 | saveStateAndReturn: |
2189 | 0 | s->pos = pos; |
2190 | 0 | s->loop_counter = i; |
2191 | 0 | return result; |
2192 | 0 | } |
2193 | | |
2194 | | #undef BROTLI_SAFE |
2195 | | |
2196 | | static BROTLI_NOINLINE BrotliDecoderErrorCode ProcessCommands( |
2197 | 0 | BrotliDecoderState* s) { |
2198 | 0 | return ProcessCommandsInternal(0, s); |
2199 | 0 | } |
2200 | | |
2201 | | static BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands( |
2202 | 0 | BrotliDecoderState* s) { |
2203 | 0 | return ProcessCommandsInternal(1, s); |
2204 | 0 | } |
2205 | | |
2206 | | BrotliDecoderResult BrotliDecoderDecompress( |
2207 | | size_t encoded_size, |
2208 | | const uint8_t encoded_buffer[BROTLI_ARRAY_PARAM(encoded_size)], |
2209 | | size_t* decoded_size, |
2210 | 0 | uint8_t decoded_buffer[BROTLI_ARRAY_PARAM(*decoded_size)]) { |
2211 | 0 | BrotliDecoderState s; |
2212 | 0 | BrotliDecoderResult result; |
2213 | 0 | size_t total_out = 0; |
2214 | 0 | size_t available_in = encoded_size; |
2215 | 0 | const uint8_t* next_in = encoded_buffer; |
2216 | 0 | size_t available_out = *decoded_size; |
2217 | 0 | uint8_t* next_out = decoded_buffer; |
2218 | 0 | if (!BrotliDecoderStateInit(&s, 0, 0, 0)) { |
2219 | 0 | return BROTLI_DECODER_RESULT_ERROR; |
2220 | 0 | } |
2221 | 0 | result = BrotliDecoderDecompressStream( |
2222 | 0 | &s, &available_in, &next_in, &available_out, &next_out, &total_out); |
2223 | 0 | *decoded_size = total_out; |
2224 | 0 | BrotliDecoderStateCleanup(&s); |
2225 | 0 | if (result != BROTLI_DECODER_RESULT_SUCCESS) { |
2226 | 0 | result = BROTLI_DECODER_RESULT_ERROR; |
2227 | 0 | } |
2228 | 0 | return result; |
2229 | 0 | } |
2230 | | |
2231 | | /* Invariant: input stream is never overconsumed: |
2232 | | - invalid input implies that the whole stream is invalid -> any amount of |
2233 | | input could be read and discarded |
2234 | | - when result is "needs more input", then at least one more byte is REQUIRED |
2235 | | to complete decoding; all input data MUST be consumed by decoder, so |
2236 | | client could swap the input buffer |
2237 | | - when result is "needs more output" decoder MUST ensure that it doesn't |
2238 | | hold more than 7 bits in bit reader; this saves client from swapping input |
2239 | | buffer ahead of time |
2240 | | - when result is "success" decoder MUST return all unused data back to input |
2241 | | buffer; this is possible because the invariant is held on enter */ |
2242 | | BrotliDecoderResult BrotliDecoderDecompressStream( |
2243 | | BrotliDecoderState* s, size_t* available_in, const uint8_t** next_in, |
2244 | 0 | size_t* available_out, uint8_t** next_out, size_t* total_out) { |
2245 | 0 | BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS; |
2246 | 0 | BrotliBitReader* br = &s->br; |
2247 | 0 | size_t input_size = *available_in; |
2248 | 0 | #define BROTLI_SAVE_ERROR_CODE(code) \ |
2249 | 0 | SaveErrorCode(s, (code), input_size - *available_in) |
2250 | | /* Ensure that |total_out| is set, even if no data will ever be pushed out. */ |
2251 | 0 | if (total_out) { |
2252 | 0 | *total_out = s->partial_pos_out; |
2253 | 0 | } |
2254 | | /* Do not try to process further in a case of unrecoverable error. */ |
2255 | 0 | if ((int)s->error_code < 0) { |
2256 | 0 | return BROTLI_DECODER_RESULT_ERROR; |
2257 | 0 | } |
2258 | 0 | if (*available_out && (!next_out || !*next_out)) { |
2259 | 0 | return BROTLI_SAVE_ERROR_CODE( |
2260 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_INVALID_ARGUMENTS)); |
2261 | 0 | } |
2262 | 0 | if (!*available_out) next_out = 0; |
2263 | 0 | if (s->buffer_length == 0) { /* Just connect bit reader to input stream. */ |
2264 | 0 | br->avail_in = *available_in; |
2265 | 0 | br->next_in = *next_in; |
2266 | 0 | } else { |
2267 | | /* At least one byte of input is required. More than one byte of input may |
2268 | | be required to complete the transaction -> reading more data must be |
2269 | | done in a loop -> do it in a main loop. */ |
2270 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
2271 | 0 | br->next_in = &s->buffer.u8[0]; |
2272 | 0 | } |
2273 | | /* State machine */ |
2274 | 0 | for (;;) { |
2275 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2276 | | /* Error, needs more input/output. */ |
2277 | 0 | if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) { |
2278 | 0 | if (s->ringbuffer != 0) { /* Pro-actively push output. */ |
2279 | 0 | BrotliDecoderErrorCode intermediate_result = WriteRingBuffer(s, |
2280 | 0 | available_out, next_out, total_out, BROTLI_TRUE); |
2281 | | /* WriteRingBuffer checks s->meta_block_remaining_len validity. */ |
2282 | 0 | if ((int)intermediate_result < 0) { |
2283 | 0 | result = intermediate_result; |
2284 | 0 | break; |
2285 | 0 | } |
2286 | 0 | } |
2287 | 0 | if (s->buffer_length != 0) { /* Used with internal buffer. */ |
2288 | 0 | if (br->avail_in == 0) { |
2289 | | /* Successfully finished read transaction. |
2290 | | Accumulator contains less than 8 bits, because internal buffer |
2291 | | is expanded byte-by-byte until it is enough to complete read. */ |
2292 | 0 | s->buffer_length = 0; |
2293 | | /* Switch to input stream and restart. */ |
2294 | 0 | result = BROTLI_DECODER_SUCCESS; |
2295 | 0 | br->avail_in = *available_in; |
2296 | 0 | br->next_in = *next_in; |
2297 | 0 | continue; |
2298 | 0 | } else if (*available_in != 0) { |
2299 | | /* Not enough data in buffer, but can take one more byte from |
2300 | | input stream. */ |
2301 | 0 | result = BROTLI_DECODER_SUCCESS; |
2302 | 0 | s->buffer.u8[s->buffer_length] = **next_in; |
2303 | 0 | s->buffer_length++; |
2304 | 0 | br->avail_in = s->buffer_length; |
2305 | 0 | (*next_in)++; |
2306 | 0 | (*available_in)--; |
2307 | | /* Retry with more data in buffer. */ |
2308 | 0 | continue; |
2309 | 0 | } |
2310 | | /* Can't finish reading and no more input. */ |
2311 | 0 | break; |
2312 | 0 | } else { /* Input stream doesn't contain enough input. */ |
2313 | | /* Copy tail to internal buffer and return. */ |
2314 | 0 | *next_in = br->next_in; |
2315 | 0 | *available_in = br->avail_in; |
2316 | 0 | while (*available_in) { |
2317 | 0 | s->buffer.u8[s->buffer_length] = **next_in; |
2318 | 0 | s->buffer_length++; |
2319 | 0 | (*next_in)++; |
2320 | 0 | (*available_in)--; |
2321 | 0 | } |
2322 | 0 | break; |
2323 | 0 | } |
2324 | | /* Unreachable. */ |
2325 | 0 | } |
2326 | | |
2327 | | /* Fail or needs more output. */ |
2328 | | |
2329 | 0 | if (s->buffer_length != 0) { |
2330 | | /* Just consumed the buffered input and produced some output. Otherwise |
2331 | | it would result in "needs more input". Reset internal buffer. */ |
2332 | 0 | s->buffer_length = 0; |
2333 | 0 | } else { |
2334 | | /* Using input stream in last iteration. When decoder switches to input |
2335 | | stream it has less than 8 bits in accumulator, so it is safe to |
2336 | | return unused accumulator bits there. */ |
2337 | 0 | BrotliBitReaderUnload(br); |
2338 | 0 | *available_in = br->avail_in; |
2339 | 0 | *next_in = br->next_in; |
2340 | 0 | } |
2341 | 0 | break; |
2342 | 0 | } |
2343 | 0 | switch (s->state) { |
2344 | 0 | case BROTLI_STATE_UNINITED: |
2345 | | /* Prepare to the first read. */ |
2346 | 0 | if (!BrotliWarmupBitReader(br)) { |
2347 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
2348 | 0 | break; |
2349 | 0 | } |
2350 | | /* Decode window size. */ |
2351 | 0 | result = DecodeWindowBits(s, br); /* Reads 1..8 bits. */ |
2352 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2353 | 0 | break; |
2354 | 0 | } |
2355 | 0 | if (s->large_window) { |
2356 | 0 | s->state = BROTLI_STATE_LARGE_WINDOW_BITS; |
2357 | 0 | break; |
2358 | 0 | } |
2359 | 0 | s->state = BROTLI_STATE_INITIALIZE; |
2360 | 0 | break; |
2361 | | |
2362 | 0 | case BROTLI_STATE_LARGE_WINDOW_BITS: |
2363 | 0 | if (!BrotliSafeReadBits(br, 6, &s->window_bits)) { |
2364 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
2365 | 0 | break; |
2366 | 0 | } |
2367 | 0 | if (s->window_bits < BROTLI_LARGE_MIN_WBITS || |
2368 | 0 | s->window_bits > BROTLI_LARGE_MAX_WBITS) { |
2369 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS); |
2370 | 0 | break; |
2371 | 0 | } |
2372 | 0 | s->state = BROTLI_STATE_INITIALIZE; |
2373 | | /* Fall through. */ |
2374 | |
|
2375 | 0 | case BROTLI_STATE_INITIALIZE: |
2376 | 0 | BROTLI_LOG_UINT(s->window_bits); |
2377 | | /* Maximum distance, see section 9.1. of the spec. */ |
2378 | 0 | s->max_backward_distance = (1 << s->window_bits) - BROTLI_WINDOW_GAP; |
2379 | | |
2380 | | /* Allocate memory for both block_type_trees and block_len_trees. */ |
2381 | 0 | s->block_type_trees = (HuffmanCode*)BROTLI_DECODER_ALLOC(s, |
2382 | 0 | sizeof(HuffmanCode) * 3 * |
2383 | 0 | (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26)); |
2384 | 0 | if (s->block_type_trees == 0) { |
2385 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES); |
2386 | 0 | break; |
2387 | 0 | } |
2388 | 0 | s->block_len_trees = |
2389 | 0 | s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_SIZE_258; |
2390 | |
|
2391 | 0 | s->state = BROTLI_STATE_METABLOCK_BEGIN; |
2392 | | /* Fall through. */ |
2393 | |
|
2394 | 0 | case BROTLI_STATE_METABLOCK_BEGIN: |
2395 | 0 | BrotliDecoderStateMetablockBegin(s); |
2396 | 0 | BROTLI_LOG_UINT(s->pos); |
2397 | 0 | s->state = BROTLI_STATE_METABLOCK_HEADER; |
2398 | | /* Fall through. */ |
2399 | |
|
2400 | 0 | case BROTLI_STATE_METABLOCK_HEADER: |
2401 | 0 | result = DecodeMetaBlockLength(s, br); /* Reads 2 - 31 bits. */ |
2402 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2403 | 0 | break; |
2404 | 0 | } |
2405 | 0 | BROTLI_LOG_UINT(s->is_last_metablock); |
2406 | 0 | BROTLI_LOG_UINT(s->meta_block_remaining_len); |
2407 | 0 | BROTLI_LOG_UINT(s->is_metadata); |
2408 | 0 | BROTLI_LOG_UINT(s->is_uncompressed); |
2409 | 0 | if (s->is_metadata || s->is_uncompressed) { |
2410 | 0 | if (!BrotliJumpToByteBoundary(br)) { |
2411 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1); |
2412 | 0 | break; |
2413 | 0 | } |
2414 | 0 | } |
2415 | 0 | if (s->is_metadata) { |
2416 | 0 | s->state = BROTLI_STATE_METADATA; |
2417 | 0 | break; |
2418 | 0 | } |
2419 | 0 | if (s->meta_block_remaining_len == 0) { |
2420 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2421 | 0 | break; |
2422 | 0 | } |
2423 | 0 | BrotliCalculateRingBufferSize(s); |
2424 | 0 | if (s->is_uncompressed) { |
2425 | 0 | s->state = BROTLI_STATE_UNCOMPRESSED; |
2426 | 0 | break; |
2427 | 0 | } |
2428 | 0 | s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER; |
2429 | | /* Fall through. */ |
2430 | |
|
2431 | 0 | case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER: { |
2432 | 0 | BrotliMetablockHeaderArena* h = &s->arena.header; |
2433 | 0 | s->loop_counter = 0; |
2434 | | /* Initialize compressed metablock header arena. */ |
2435 | 0 | h->sub_loop_counter = 0; |
2436 | | /* Make small negative indexes addressable. */ |
2437 | 0 | h->symbol_lists = |
2438 | 0 | &h->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1]; |
2439 | 0 | h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; |
2440 | 0 | h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE; |
2441 | 0 | h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; |
2442 | 0 | s->state = BROTLI_STATE_HUFFMAN_CODE_0; |
2443 | 0 | } |
2444 | | /* Fall through. */ |
2445 | |
|
2446 | 0 | case BROTLI_STATE_HUFFMAN_CODE_0: |
2447 | 0 | if (s->loop_counter >= 3) { |
2448 | 0 | s->state = BROTLI_STATE_METABLOCK_HEADER_2; |
2449 | 0 | break; |
2450 | 0 | } |
2451 | | /* Reads 1..11 bits. */ |
2452 | 0 | result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]); |
2453 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2454 | 0 | break; |
2455 | 0 | } |
2456 | 0 | s->num_block_types[s->loop_counter]++; |
2457 | 0 | BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]); |
2458 | 0 | if (s->num_block_types[s->loop_counter] < 2) { |
2459 | 0 | s->loop_counter++; |
2460 | 0 | break; |
2461 | 0 | } |
2462 | 0 | s->state = BROTLI_STATE_HUFFMAN_CODE_1; |
2463 | | /* Fall through. */ |
2464 | |
|
2465 | 0 | case BROTLI_STATE_HUFFMAN_CODE_1: { |
2466 | 0 | uint32_t alphabet_size = s->num_block_types[s->loop_counter] + 2; |
2467 | 0 | int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_258; |
2468 | 0 | result = ReadHuffmanCode(alphabet_size, alphabet_size, |
2469 | 0 | &s->block_type_trees[tree_offset], NULL, s); |
2470 | 0 | if (result != BROTLI_DECODER_SUCCESS) break; |
2471 | 0 | s->state = BROTLI_STATE_HUFFMAN_CODE_2; |
2472 | 0 | } |
2473 | | /* Fall through. */ |
2474 | | |
2475 | 0 | case BROTLI_STATE_HUFFMAN_CODE_2: { |
2476 | 0 | uint32_t alphabet_size = BROTLI_NUM_BLOCK_LEN_SYMBOLS; |
2477 | 0 | int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26; |
2478 | 0 | result = ReadHuffmanCode(alphabet_size, alphabet_size, |
2479 | 0 | &s->block_len_trees[tree_offset], NULL, s); |
2480 | 0 | if (result != BROTLI_DECODER_SUCCESS) break; |
2481 | 0 | s->state = BROTLI_STATE_HUFFMAN_CODE_3; |
2482 | 0 | } |
2483 | | /* Fall through. */ |
2484 | | |
2485 | 0 | case BROTLI_STATE_HUFFMAN_CODE_3: { |
2486 | 0 | int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26; |
2487 | 0 | if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter], |
2488 | 0 | &s->block_len_trees[tree_offset], br)) { |
2489 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
2490 | 0 | break; |
2491 | 0 | } |
2492 | 0 | BROTLI_LOG_UINT(s->block_length[s->loop_counter]); |
2493 | 0 | s->loop_counter++; |
2494 | 0 | s->state = BROTLI_STATE_HUFFMAN_CODE_0; |
2495 | 0 | break; |
2496 | 0 | } |
2497 | | |
2498 | 0 | case BROTLI_STATE_UNCOMPRESSED: { |
2499 | 0 | result = CopyUncompressedBlockToOutput( |
2500 | 0 | available_out, next_out, total_out, s); |
2501 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2502 | 0 | break; |
2503 | 0 | } |
2504 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2505 | 0 | break; |
2506 | 0 | } |
2507 | | |
2508 | 0 | case BROTLI_STATE_METADATA: |
2509 | 0 | for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) { |
2510 | 0 | uint32_t bits; |
2511 | | /* Read one byte and ignore it. */ |
2512 | 0 | if (!BrotliSafeReadBits(br, 8, &bits)) { |
2513 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
2514 | 0 | break; |
2515 | 0 | } |
2516 | 0 | } |
2517 | 0 | if (result == BROTLI_DECODER_SUCCESS) { |
2518 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2519 | 0 | } |
2520 | 0 | break; |
2521 | | |
2522 | 0 | case BROTLI_STATE_METABLOCK_HEADER_2: { |
2523 | 0 | uint32_t bits; |
2524 | 0 | if (!BrotliSafeReadBits(br, 6, &bits)) { |
2525 | 0 | result = BROTLI_DECODER_NEEDS_MORE_INPUT; |
2526 | 0 | break; |
2527 | 0 | } |
2528 | 0 | s->distance_postfix_bits = bits & BitMask(2); |
2529 | 0 | bits >>= 2; |
2530 | 0 | s->num_direct_distance_codes = bits << s->distance_postfix_bits; |
2531 | 0 | BROTLI_LOG_UINT(s->num_direct_distance_codes); |
2532 | 0 | BROTLI_LOG_UINT(s->distance_postfix_bits); |
2533 | 0 | s->context_modes = |
2534 | 0 | (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)s->num_block_types[0]); |
2535 | 0 | if (s->context_modes == 0) { |
2536 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES); |
2537 | 0 | break; |
2538 | 0 | } |
2539 | 0 | s->loop_counter = 0; |
2540 | 0 | s->state = BROTLI_STATE_CONTEXT_MODES; |
2541 | 0 | } |
2542 | | /* Fall through. */ |
2543 | | |
2544 | 0 | case BROTLI_STATE_CONTEXT_MODES: |
2545 | 0 | result = ReadContextModes(s); |
2546 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2547 | 0 | break; |
2548 | 0 | } |
2549 | 0 | s->state = BROTLI_STATE_CONTEXT_MAP_1; |
2550 | | /* Fall through. */ |
2551 | |
|
2552 | 0 | case BROTLI_STATE_CONTEXT_MAP_1: |
2553 | 0 | result = DecodeContextMap( |
2554 | 0 | s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS, |
2555 | 0 | &s->num_literal_htrees, &s->context_map, s); |
2556 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2557 | 0 | break; |
2558 | 0 | } |
2559 | 0 | DetectTrivialLiteralBlockTypes(s); |
2560 | 0 | s->state = BROTLI_STATE_CONTEXT_MAP_2; |
2561 | | /* Fall through. */ |
2562 | |
|
2563 | 0 | case BROTLI_STATE_CONTEXT_MAP_2: { |
2564 | 0 | uint32_t npostfix = s->distance_postfix_bits; |
2565 | 0 | uint32_t ndirect = s->num_direct_distance_codes; |
2566 | 0 | uint32_t distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE( |
2567 | 0 | npostfix, ndirect, BROTLI_MAX_DISTANCE_BITS); |
2568 | 0 | uint32_t distance_alphabet_size_limit = distance_alphabet_size_max; |
2569 | 0 | BROTLI_BOOL allocation_success = BROTLI_TRUE; |
2570 | 0 | if (s->large_window) { |
2571 | 0 | BrotliDistanceCodeLimit limit = BrotliCalculateDistanceCodeLimit( |
2572 | 0 | BROTLI_MAX_ALLOWED_DISTANCE, npostfix, ndirect); |
2573 | 0 | distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE( |
2574 | 0 | npostfix, ndirect, BROTLI_LARGE_MAX_DISTANCE_BITS); |
2575 | 0 | distance_alphabet_size_limit = limit.max_alphabet_size; |
2576 | 0 | } |
2577 | 0 | result = DecodeContextMap( |
2578 | 0 | s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS, |
2579 | 0 | &s->num_dist_htrees, &s->dist_context_map, s); |
2580 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2581 | 0 | break; |
2582 | 0 | } |
2583 | 0 | allocation_success &= BrotliDecoderHuffmanTreeGroupInit( |
2584 | 0 | s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS, |
2585 | 0 | BROTLI_NUM_LITERAL_SYMBOLS, s->num_literal_htrees); |
2586 | 0 | allocation_success &= BrotliDecoderHuffmanTreeGroupInit( |
2587 | 0 | s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS, |
2588 | 0 | BROTLI_NUM_COMMAND_SYMBOLS, s->num_block_types[1]); |
2589 | 0 | allocation_success &= BrotliDecoderHuffmanTreeGroupInit( |
2590 | 0 | s, &s->distance_hgroup, distance_alphabet_size_max, |
2591 | 0 | distance_alphabet_size_limit, s->num_dist_htrees); |
2592 | 0 | if (!allocation_success) { |
2593 | 0 | return BROTLI_SAVE_ERROR_CODE( |
2594 | 0 | BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS)); |
2595 | 0 | } |
2596 | 0 | s->loop_counter = 0; |
2597 | 0 | s->state = BROTLI_STATE_TREE_GROUP; |
2598 | 0 | } |
2599 | | /* Fall through. */ |
2600 | | |
2601 | 0 | case BROTLI_STATE_TREE_GROUP: { |
2602 | 0 | HuffmanTreeGroup* hgroup = NULL; |
2603 | 0 | switch (s->loop_counter) { |
2604 | 0 | case 0: hgroup = &s->literal_hgroup; break; |
2605 | 0 | case 1: hgroup = &s->insert_copy_hgroup; break; |
2606 | 0 | case 2: hgroup = &s->distance_hgroup; break; |
2607 | 0 | default: return BROTLI_SAVE_ERROR_CODE(BROTLI_FAILURE( |
2608 | 0 | BROTLI_DECODER_ERROR_UNREACHABLE)); /* COV_NF_LINE */ |
2609 | 0 | } |
2610 | 0 | result = HuffmanTreeGroupDecode(hgroup, s); |
2611 | 0 | if (result != BROTLI_DECODER_SUCCESS) break; |
2612 | 0 | s->loop_counter++; |
2613 | 0 | if (s->loop_counter < 3) { |
2614 | 0 | break; |
2615 | 0 | } |
2616 | 0 | s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY; |
2617 | 0 | } |
2618 | | /* Fall through. */ |
2619 | | |
2620 | 0 | case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY: |
2621 | 0 | PrepareLiteralDecoding(s); |
2622 | 0 | s->dist_context_map_slice = s->dist_context_map; |
2623 | 0 | s->htree_command = s->insert_copy_hgroup.htrees[0]; |
2624 | 0 | if (!BrotliEnsureRingBuffer(s)) { |
2625 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2); |
2626 | 0 | break; |
2627 | 0 | } |
2628 | 0 | CalculateDistanceLut(s); |
2629 | 0 | s->state = BROTLI_STATE_COMMAND_BEGIN; |
2630 | | /* Fall through. */ |
2631 | |
|
2632 | 0 | case BROTLI_STATE_COMMAND_BEGIN: |
2633 | | /* Fall through. */ |
2634 | 0 | case BROTLI_STATE_COMMAND_INNER: |
2635 | | /* Fall through. */ |
2636 | 0 | case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS: |
2637 | | /* Fall through. */ |
2638 | 0 | case BROTLI_STATE_COMMAND_POST_WRAP_COPY: |
2639 | 0 | result = ProcessCommands(s); |
2640 | 0 | if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) { |
2641 | 0 | result = SafeProcessCommands(s); |
2642 | 0 | } |
2643 | 0 | break; |
2644 | | |
2645 | 0 | case BROTLI_STATE_COMMAND_INNER_WRITE: |
2646 | | /* Fall through. */ |
2647 | 0 | case BROTLI_STATE_COMMAND_POST_WRITE_1: |
2648 | | /* Fall through. */ |
2649 | 0 | case BROTLI_STATE_COMMAND_POST_WRITE_2: |
2650 | 0 | result = WriteRingBuffer( |
2651 | 0 | s, available_out, next_out, total_out, BROTLI_FALSE); |
2652 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2653 | 0 | break; |
2654 | 0 | } |
2655 | 0 | WrapRingBuffer(s); |
2656 | 0 | if (s->ringbuffer_size == 1 << s->window_bits) { |
2657 | 0 | s->max_distance = s->max_backward_distance; |
2658 | 0 | } |
2659 | 0 | if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) { |
2660 | 0 | BrotliDecoderCompoundDictionary* addon = s->compound_dictionary; |
2661 | 0 | if (addon && (addon->br_length != addon->br_copied)) { |
2662 | 0 | s->pos += CopyFromCompoundDictionary(s, s->pos); |
2663 | 0 | if (s->pos >= s->ringbuffer_size) continue; |
2664 | 0 | } |
2665 | 0 | if (s->meta_block_remaining_len == 0) { |
2666 | | /* Next metablock, if any. */ |
2667 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2668 | 0 | } else { |
2669 | 0 | s->state = BROTLI_STATE_COMMAND_BEGIN; |
2670 | 0 | } |
2671 | 0 | break; |
2672 | 0 | } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) { |
2673 | 0 | s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY; |
2674 | 0 | } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */ |
2675 | 0 | if (s->loop_counter == 0) { |
2676 | 0 | if (s->meta_block_remaining_len == 0) { |
2677 | 0 | s->state = BROTLI_STATE_METABLOCK_DONE; |
2678 | 0 | } else { |
2679 | 0 | s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS; |
2680 | 0 | } |
2681 | 0 | break; |
2682 | 0 | } |
2683 | 0 | s->state = BROTLI_STATE_COMMAND_INNER; |
2684 | 0 | } |
2685 | 0 | break; |
2686 | | |
2687 | 0 | case BROTLI_STATE_METABLOCK_DONE: |
2688 | 0 | if (s->meta_block_remaining_len < 0) { |
2689 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2); |
2690 | 0 | break; |
2691 | 0 | } |
2692 | 0 | BrotliDecoderStateCleanupAfterMetablock(s); |
2693 | 0 | if (!s->is_last_metablock) { |
2694 | 0 | s->state = BROTLI_STATE_METABLOCK_BEGIN; |
2695 | 0 | break; |
2696 | 0 | } |
2697 | 0 | if (!BrotliJumpToByteBoundary(br)) { |
2698 | 0 | result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2); |
2699 | 0 | break; |
2700 | 0 | } |
2701 | 0 | if (s->buffer_length == 0) { |
2702 | 0 | BrotliBitReaderUnload(br); |
2703 | 0 | *available_in = br->avail_in; |
2704 | 0 | *next_in = br->next_in; |
2705 | 0 | } |
2706 | 0 | s->state = BROTLI_STATE_DONE; |
2707 | | /* Fall through. */ |
2708 | |
|
2709 | 0 | case BROTLI_STATE_DONE: |
2710 | 0 | if (s->ringbuffer != 0) { |
2711 | 0 | result = WriteRingBuffer( |
2712 | 0 | s, available_out, next_out, total_out, BROTLI_TRUE); |
2713 | 0 | if (result != BROTLI_DECODER_SUCCESS) { |
2714 | 0 | break; |
2715 | 0 | } |
2716 | 0 | } |
2717 | 0 | return BROTLI_SAVE_ERROR_CODE(result); |
2718 | 0 | } |
2719 | 0 | } |
2720 | 0 | return BROTLI_SAVE_ERROR_CODE(result); |
2721 | 0 | #undef BROTLI_SAVE_ERROR_CODE |
2722 | 0 | } |
2723 | | |
2724 | 0 | BROTLI_BOOL BrotliDecoderHasMoreOutput(const BrotliDecoderState* s) { |
2725 | | /* After unrecoverable error remaining output is considered nonsensical. */ |
2726 | 0 | if ((int)s->error_code < 0) { |
2727 | 0 | return BROTLI_FALSE; |
2728 | 0 | } |
2729 | 0 | return TO_BROTLI_BOOL( |
2730 | 0 | s->ringbuffer != 0 && UnwrittenBytes(s, BROTLI_FALSE) != 0); |
2731 | 0 | } |
2732 | | |
2733 | 0 | const uint8_t* BrotliDecoderTakeOutput(BrotliDecoderState* s, size_t* size) { |
2734 | 0 | uint8_t* result = 0; |
2735 | 0 | size_t available_out = *size ? *size : 1u << 24; |
2736 | 0 | size_t requested_out = available_out; |
2737 | 0 | BrotliDecoderErrorCode status; |
2738 | 0 | if ((s->ringbuffer == 0) || ((int)s->error_code < 0)) { |
2739 | 0 | *size = 0; |
2740 | 0 | return 0; |
2741 | 0 | } |
2742 | 0 | WrapRingBuffer(s); |
2743 | 0 | status = WriteRingBuffer(s, &available_out, &result, 0, BROTLI_TRUE); |
2744 | | /* Either WriteRingBuffer returns those "success" codes... */ |
2745 | 0 | if (status == BROTLI_DECODER_SUCCESS || |
2746 | 0 | status == BROTLI_DECODER_NEEDS_MORE_OUTPUT) { |
2747 | 0 | *size = requested_out - available_out; |
2748 | 0 | } else { |
2749 | | /* ... or stream is broken. Normally this should be caught by |
2750 | | BrotliDecoderDecompressStream, this is just a safeguard. */ |
2751 | 0 | if ((int)status < 0) SaveErrorCode(s, status, 0); |
2752 | 0 | *size = 0; |
2753 | 0 | result = 0; |
2754 | 0 | } |
2755 | 0 | return result; |
2756 | 0 | } |
2757 | | |
2758 | 0 | BROTLI_BOOL BrotliDecoderIsUsed(const BrotliDecoderState* s) { |
2759 | 0 | return TO_BROTLI_BOOL(s->state != BROTLI_STATE_UNINITED || |
2760 | 0 | BrotliGetAvailableBits(&s->br) != 0); |
2761 | 0 | } |
2762 | | |
2763 | 0 | BROTLI_BOOL BrotliDecoderIsFinished(const BrotliDecoderState* s) { |
2764 | 0 | return TO_BROTLI_BOOL(s->state == BROTLI_STATE_DONE) && |
2765 | 0 | !BrotliDecoderHasMoreOutput(s); |
2766 | 0 | } |
2767 | | |
2768 | 0 | BrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderState* s) { |
2769 | 0 | return (BrotliDecoderErrorCode)s->error_code; |
2770 | 0 | } |
2771 | | |
2772 | 0 | const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) { |
2773 | 0 | switch (c) { |
2774 | 0 | #define BROTLI_ERROR_CODE_CASE_(PREFIX, NAME, CODE) \ |
2775 | 0 | case BROTLI_DECODER ## PREFIX ## NAME: return #NAME; |
2776 | 0 | #define BROTLI_NOTHING_ |
2777 | 0 | BROTLI_DECODER_ERROR_CODES_LIST(BROTLI_ERROR_CODE_CASE_, BROTLI_NOTHING_) |
2778 | 0 | #undef BROTLI_ERROR_CODE_CASE_ |
2779 | 0 | #undef BROTLI_NOTHING_ |
2780 | 0 | default: return "INVALID"; |
2781 | 0 | } |
2782 | 0 | } |
2783 | | |
2784 | 0 | uint32_t BrotliDecoderVersion(void) { |
2785 | 0 | return BROTLI_VERSION; |
2786 | 0 | } |
2787 | | |
2788 | | /* Escalate internal functions visibility; for testing purposes only. */ |
2789 | | #if defined(BROTLI_TEST) |
2790 | | BROTLI_BOOL SafeReadSymbolForTest( |
2791 | | const HuffmanCode*, BrotliBitReader*, uint32_t*); |
2792 | | BROTLI_BOOL SafeReadSymbolForTest( |
2793 | | const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) { |
2794 | | return SafeReadSymbol(table, br, result); |
2795 | | } |
2796 | | |
2797 | | void InverseMoveToFrontTransformForTest( |
2798 | | uint8_t*, uint32_t, BrotliDecoderState*); |
2799 | | void InverseMoveToFrontTransformForTest( |
2800 | | uint8_t* v, uint32_t l, BrotliDecoderState* s) { |
2801 | | InverseMoveToFrontTransform(v, l, s); |
2802 | | } |
2803 | | #endif |
2804 | | |
2805 | | #if defined(__cplusplus) || defined(c_plusplus) |
2806 | | } /* extern "C" */ |
2807 | | #endif |