1 /*
2 * jdhuff_opt.c
3 *
4 * This file was part of the Independent JPEG Group's software:
5 * Copyright (C) 1991-1997, Thomas G. Lane.
6 * libjpeg-turbo Modifications:
7 * Copyright (C) 2009-2011, 2016, 2018-2019, D. R. Commander.
8 * Copyright (C) 2018, Matthias Räncker.
9 * For conditions of distribution and use, see the accompanying README.ijg
10 * file.
11 *
12 * This file contains Huffman entropy decoding routines.
13 *
14 * Much of the complexity here has to do with supporting input suspension.
15 * If the data source module demands suspension, we want to be able to back
16 * up to the start of the current MCU. To do this, we copy state variables
17 * into local working storage, and update them back to the permanent
18 * storage only upon successful completion of an MCU.
19 *
20 * NOTE: All referenced figures are from
21 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
22 */
23
24 #define JPEG_INTERNALS
25 #include "jinclude.h"
26 #include "jpeglib.h"
27 #include "jdhuff.h" /* Declarations shared with jdphuff.c */
28 #include "jpegcomp.h"
29 #include "jstdhuff.c"
30
31
32 /*
33 * Expanded entropy decoder object for Huffman decoding.
34 *
35 * The savable_state subrecord contains fields that change within an MCU,
36 * but must not be updated permanently until we complete the MCU.
37 */
38
39 typedef struct {
40 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
41 } savable_state;
42
43 typedef struct {
44 struct jpeg_entropy_decoder pub; /* public fields */
45
46 /* These fields are loaded into local variables at start of each MCU.
47 * In case of suspension, we exit WITHOUT updating them.
48 */
49 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
50 savable_state saved; /* Other state at start of MCU */
51
52 /* These fields are NOT loaded into local working state. */
53 unsigned int restarts_to_go; /* MCUs left in this restart interval */
54
55 /* Pointers to derived tables (these workspaces have image lifespan) */
56 d_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
57 d_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
58
59 /* Precalculated info set up by start_pass for use in decode_mcu: */
60
61 /* Pointers to derived tables to be used for each block within an MCU */
62 d_derived_tbl *dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
63 d_derived_tbl *ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
64 /* Whether we care about the DC and AC coefficient values for each block */
65 boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
66 boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
67 } huff_entropy_decoder;
68
69 typedef huff_entropy_decoder *huff_entropy_ptr;
70
71 /*
72 * Figure F.12: extend sign bit.
73 * On some machines, a shift and add will be faster than a table lookup.
74 */
75
76 #define AVOID_TABLES
77 #ifdef AVOID_TABLES
78
79 #define NEG_1 ((unsigned int)-1)
80 #define HUFF_EXTEND(x, s) \
81 ((x) + ((((x) - (1 << ((s) - 1))) >> 31) & (((NEG_1) << (s)) + 1)))
82
83 #else
84
85 #define HUFF_EXTEND(x, s) \
86 ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
87
88 static const int extend_test[16] = { /* entry n is 2**(n-1) */
89 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
90 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000
91 };
92
93 static const int extend_offset[16] = { /* entry n is (-1 << n) + 1 */
94 0, ((-1) << 1) + 1, ((-1) << 2) + 1, ((-1) << 3) + 1, ((-1) << 4) + 1,
95 ((-1) << 5) + 1, ((-1) << 6) + 1, ((-1) << 7) + 1, ((-1) << 8) + 1,
96 ((-1) << 9) + 1, ((-1) << 10) + 1, ((-1) << 11) + 1, ((-1) << 12) + 1,
97 ((-1) << 13) + 1, ((-1) << 14) + 1, ((-1) << 15) + 1
98 };
99
100 #endif /* AVOID_TABLES */
101
102 /*
103 * Initialize for a Huffman-compressed scan.
104 */
105
106 METHODDEF(void)
start_pass_huff_decoder(j_decompress_ptr cinfo)107 start_pass_huff_decoder(j_decompress_ptr cinfo)
108 {
109 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
110 int ci, blkn, dctbl, actbl;
111 d_derived_tbl **pdtbl;
112 jpeg_component_info *compptr;
113
114 /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
115 * This ought to be an error condition, but we make it a warning because
116 * there are some baseline files out there with all zeroes in these bytes.
117 */
118 if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||
119 cinfo->Ah != 0 || cinfo->Al != 0)
120 WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
121
122 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
123 compptr = cinfo->cur_comp_info[ci];
124 dctbl = compptr->dc_tbl_no;
125 actbl = compptr->ac_tbl_no;
126 /* Compute derived values for Huffman tables */
127 /* We may do this more than once for a table, but it's not expensive */
128 pdtbl = (d_derived_tbl **)(entropy->dc_derived_tbls) + dctbl;
129 jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl, pdtbl);
130 pdtbl = (d_derived_tbl **)(entropy->ac_derived_tbls) + actbl;
131 jpeg_make_d_derived_tbl(cinfo, FALSE, actbl, pdtbl);
132 /* Initialize DC predictions to 0 */
133 entropy->saved.last_dc_val[ci] = 0;
134 }
135
136 /* Precalculate decoding info for each block in an MCU of this scan */
137 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
138 ci = cinfo->MCU_membership[blkn];
139 compptr = cinfo->cur_comp_info[ci];
140 /* Precalculate which table to use for each block */
141 entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
142 entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
143 /* Decide whether we really care about the coefficient values */
144 if (compptr->component_needed) {
145 entropy->dc_needed[blkn] = TRUE;
146 /* we don't need the ACs if producing a 1/8th-size image */
147 entropy->ac_needed[blkn] = (compptr->_DCT_scaled_size > 1);
148 } else {
149 entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
150 }
151 }
152
153 /* Initialize bitread state variables */
154 entropy->bitstate.bits_left = 0;
155 entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
156 entropy->pub.insufficient_data = FALSE;
157
158 /* Initialize restart counter */
159 entropy->restarts_to_go = cinfo->restart_interval;
160 }
161
162 LOCAL(void)
jpeg_make_d_ac_derived_tbl(JHUFF_TBL * htbl,d_derived_tbl * dtbl,const unsigned int * huffcode)163 jpeg_make_d_ac_derived_tbl(JHUFF_TBL *htbl, d_derived_tbl *dtbl, const unsigned int* huffcode)
164 {
165 // Look up tables for AC, index is huffman code, value is the symbol and the length
166 // htbl->bits[l], number of symbol that of which the code length is l
167 // htbl->huffval[l], symbol in order
168 int p, i, l, lookbits, ctr;
169 // nb <= LOOKAHEAD
170 p = 0;
171 int coef0;
172 for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
173 for (i = 1; i <= (int)htbl->bits[l]; i++, p++) {
174 /* l = current code's length, p = its index in huffcode[] & huffval[]. */
175 /* Generate left-justified code followed by all possible bit sequences */
176 UINT8 rs = htbl->huffval[p]; // run length symbol (zero num + coeff bits)
177 UINT8 coef_bits = rs & 0x0F;
178 if ((l + coef_bits) <= HUFF_LOOKAHEAD) {
179 // save DCT coeffs in higher bits
180 for (coef0 = 0; coef0 < (1 << coef_bits); coef0++) {
181 INT16 coef_value = HUFF_EXTEND(coef0, coef_bits); // save value after extended.
182 lookbits = (huffcode[p] << (HUFF_LOOKAHEAD - l)) | (coef0 << (HUFF_LOOKAHEAD - l - coef_bits));
183 for (ctr = 1 << (HUFF_LOOKAHEAD - l - coef_bits); ctr > 0; ctr--) {
184 if (coef_bits == 0 && (rs >> 4) != 0xF) { // the low 4 bits are number of coef bits
185 // use 63 to exit the loop when symbol is 00
186 dtbl->lookup[lookbits] = MAKE_COEF1(coef_value) | MAKE_NB(l + coef_bits) | MAKE_ZERO_NUM1(63);
187 } else { // F0 and other symbols
188 // save the low 4 bits
189 dtbl->lookup[lookbits] = MAKE_COEF1(coef_value) | MAKE_NB(l + coef_bits) | MAKE_ZERO_NUM1(rs >> 4);
190 }
191 lookbits++;
192 }
193 }
194 } else {
195 // same as the original lookup table
196 lookbits = huffcode[p] << (HUFF_LOOKAHEAD - l);
197 for (ctr = 1 << (HUFF_LOOKAHEAD - l); ctr > 0; ctr--) {
198 dtbl->lookup[lookbits] = MAKE_NB(l) | MAKE_SYM(rs);
199 lookbits++;
200 }
201 }
202 }
203 }
204 // nb > LOOKAHEAD
205 int offset = 0;
206 int base = 1 << HUFF_LOOKAHEAD;
207 int short_tbl_index = 0xFFFFFFFF;
208 int cur_long_tbl_base = 1 << HUFF_LOOKAHEAD;
209 int left;
210 int offset_bit = 0;
211 int first = p; // the index of the first code of this length.
212 int max_code_len;
213 for (max_code_len = MAX_HUFF_CODE_LEN; max_code_len >= 1; max_code_len--) {
214 if (htbl->bits[max_code_len]) {
215 break;
216 }
217 }
218 for (l = HUFF_LOOKAHEAD + 1; l <= MAX_HUFF_CODE_LEN; l++) {
219 for (i = 1; i <= (int)htbl->bits[l]; i++, p++) {
220 UINT8 rs = htbl->huffval[p]; // run length symbol (zero num + coeff bits)
221 UINT8 coef_bits = rs & 0x0f;
222 // similar as 1st table as before
223 lookbits = huffcode[p] >> (l - HUFF_LOOKAHEAD); // index in 1st table
224 // check if a new 2nd tbl should be created
225 if (lookbits != short_tbl_index) {
226 short_tbl_index = lookbits;
227 cur_long_tbl_base += offset;
228 offset = 0;
229 offset_bit = l - HUFF_LOOKAHEAD;
230 left = (1 << offset_bit) - (htbl->bits[l] - (p - first));
231 while (offset_bit + HUFF_LOOKAHEAD < max_code_len && left > 0) {
232 offset_bit++;
233 left = (left << 1) - htbl->bits[offset_bit + HUFF_LOOKAHEAD];
234 }
235 }
236 base = cur_long_tbl_base;
237 // set 1st table value
238 dtbl->lookup[lookbits] = MAKE_BASE(base) | MAKE_NB(l) | MAKE_EXTRA_BITS(offset_bit);
239 // set 2nd table value
240 // index is guarenteed to be valid
241 for (ctr = 0; ctr < (1 << (offset_bit - (l - HUFF_LOOKAHEAD))); ctr++) {
242 if (coef_bits == 0) {
243 dtbl->lookup[base + offset] = MAKE_NB(l) | MAKE_SYM(rs) | MAKE_COEF_BITS(0xF);
244 } else {
245 dtbl->lookup[base + offset] = MAKE_NB(l) | MAKE_SYM(rs);
246 }
247 offset++;
248 }
249 }
250 first = p;
251 }
252 }
253
254 /*
255 * Compute the derived values for a Huffman table.
256 * This routine also performs some validation checks on the table.
257 *
258 * Note this is also used by jdphuff.c.
259 */
260
261 GLOBAL(void)
jpeg_make_d_derived_tbl(j_decompress_ptr cinfo,boolean isDC,int tblno,d_derived_tbl ** pdtbl)262 jpeg_make_d_derived_tbl(j_decompress_ptr cinfo, boolean isDC, int tblno,
263 d_derived_tbl **pdtbl)
264 {
265 JHUFF_TBL *htbl;
266 d_derived_tbl *dtbl;
267 int p, i, l, si, numsymbols;
268 int lookbits, ctr;
269 char huffsize[257];
270 unsigned int huffcode[257];
271 unsigned int code;
272
273 /* Note that huffsize[] and huffcode[] are filled in code-length order,
274 * paralleling the order of the symbols themselves in htbl->huffval[].
275 */
276
277 /* Find the input Huffman table */
278 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
279 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
280 htbl =
281 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
282 if (htbl == NULL)
283 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
284
285 /* Allocate a workspace if we haven't already done so. */
286 if (*pdtbl == NULL)
287 *pdtbl = (d_derived_tbl *)
288 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
289 sizeof(d_derived_tbl));
290 dtbl = *pdtbl;
291 dtbl->pub = htbl; /* fill in back link */
292
293 /* Figure C.1: make table of Huffman code length for each symbol */
294
295 p = 0;
296 for (l = 1; l <= MAX_HUFF_CODE_LEN; l++) {
297 i = (int)htbl->bits[l];
298 if (i < 0 || p + i > 256) /* protect against table overrun, 256 is the max number of symbols */
299 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
300 while (i--)
301 huffsize[p++] = (char)l;
302 }
303 huffsize[p] = 0;
304 numsymbols = p;
305
306 /* Figure C.2: generate the codes themselves */
307 /* We also validate that the counts represent a legal Huffman code tree. */
308
309 code = 0;
310 si = huffsize[0];
311 p = 0;
312 while (huffsize[p]) {
313 while (((int)huffsize[p]) == si) {
314 huffcode[p++] = code;
315 code++;
316 }
317 /* code is now 1 more than the last code used for codelength si; but
318 * it must still fit in si bits, since no code is allowed to be all ones.
319 */
320 if (((JLONG)code) >= (((JLONG)1) << si))
321 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
322 code <<= 1;
323 si++;
324 }
325
326 /* Figure F.15: generate decoding tables for bit-sequential decoding */
327
328 p = 0;
329 for (l = 1; l <= MAX_HUFF_CODE_LEN; l++) {
330 if (htbl->bits[l]) {
331 /* valoffset[l] = huffval[] index of 1st symbol of code length l,
332 * minus the minimum code of length l
333 */
334 dtbl->valoffset[l] = (JLONG)p - (JLONG)huffcode[p];
335 p += htbl->bits[l];
336 dtbl->maxcode[l] = huffcode[p - 1]; /* maximum code of length l */
337 } else {
338 dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
339 }
340 }
341 dtbl->valoffset[17] = 0; /* 17 is always max symbol length in Huffman spec */
342 dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates, 17 has the same meaning above */
343
344 /* Compute lookahead tables to speed up decoding.
345 * First we set all the table entries to 0, indicating "too long";
346 * then we iterate through the Huffman codes that are short enough and
347 * fill in all the entries that correspond to bit sequences starting
348 * with that code.
349 */
350
351 for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++) {
352 dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;
353 }
354 if (!isDC) {
355 jpeg_make_d_ac_derived_tbl(htbl, dtbl, huffcode);
356 } else {
357 for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++)
358 dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;
359 p = 0;
360 for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
361 for (i = 1; i <= (int)htbl->bits[l]; i++, p++) {
362 /* l = current code's length, p = its index in huffcode[] & huffval[]. */
363 /* Generate left-justified code followed by all possible bit sequences */
364 lookbits = huffcode[p] << (HUFF_LOOKAHEAD - l);
365 for (ctr = 1 << (HUFF_LOOKAHEAD - l); ctr > 0; ctr--) {
366 dtbl->lookup[lookbits] = (l << HUFF_LOOKAHEAD) | htbl->huffval[p];
367 lookbits++;
368 }
369 }
370 }
371 }
372
373 /* Validate symbols as being reasonable.
374 * For AC tables, we make no check, but accept all byte values 0..255.
375 * For DC tables, we require the symbols to be in range 0..15.
376 * (Tighter bounds could be applied depending on the data depth and mode,
377 * but this is sufficient to ensure safe decoding.)
378 */
379 if (isDC) {
380 for (i = 0; i < numsymbols; i++) {
381 int sym = htbl->huffval[i];
382 if (sym < 0 || sym > 15) // 15 is the max value of DC symbol
383 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
384 }
385 }
386 }
387
388
389 /*
390 * Out-of-line code for bit fetching (shared with jdphuff.c).
391 * See jdhuff.h for info about usage.
392 * Note: current values of get_buffer and bits_left are passed as parameters,
393 * but are returned in the corresponding fields of the state struct.
394 *
395 * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
396 * of get_buffer to be used. (On machines with wider words, an even larger
397 * buffer could be used.) However, on some machines 32-bit shifts are
398 * quite slow and take time proportional to the number of places shifted.
399 * (This is true with most PC compilers, for instance.) In this case it may
400 * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
401 * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
402 */
403
404 #ifdef SLOW_SHIFT_32
405 #define MIN_GET_BITS 15 /* minimum allowable value */
406 #else
407 #define MIN_GET_BITS (BIT_BUF_SIZE - 7)
408 #endif
409
410
411 GLOBAL(boolean)
jpeg_fill_bit_buffer(bitread_working_state * state,register bit_buf_type get_buffer,register int bits_left,int nbits)412 jpeg_fill_bit_buffer(bitread_working_state *state,
413 register bit_buf_type get_buffer, register int bits_left,
414 int nbits)
415 /* Load up the bit buffer to a depth of at least nbits */
416 {
417 /* Copy heavily used state fields into locals (hopefully registers) */
418 register const JOCTET *next_input_byte = state->next_input_byte;
419 register size_t bytes_in_buffer = state->bytes_in_buffer;
420 j_decompress_ptr cinfo = state->cinfo;
421
422 /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
423 /* (It is assumed that no request will be for more than that many bits.) */
424 /* We fail to do so only if we hit a marker or are forced to suspend. */
425
426 if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
427 while (bits_left < MIN_GET_BITS) {
428 register int c;
429
430 /* Attempt to read a byte */
431 if (bytes_in_buffer == 0) {
432 if (!(*cinfo->src->fill_input_buffer) (cinfo))
433 return FALSE;
434 next_input_byte = cinfo->src->next_input_byte;
435 bytes_in_buffer = cinfo->src->bytes_in_buffer;
436 }
437 bytes_in_buffer--;
438 c = *next_input_byte++;
439
440 /* If it's 0xFF, check and discard stuffed zero byte */
441 if (c == 0xFF) {
442 /* Loop here to discard any padding FF's on terminating marker,
443 * so that we can save a valid unread_marker value. NOTE: we will
444 * accept multiple FF's followed by a 0 as meaning a single FF data
445 * byte. This data pattern is not valid according to the standard.
446 */
447 do {
448 if (bytes_in_buffer == 0) {
449 if (!(*cinfo->src->fill_input_buffer) (cinfo))
450 return FALSE;
451 next_input_byte = cinfo->src->next_input_byte;
452 bytes_in_buffer = cinfo->src->bytes_in_buffer;
453 }
454 bytes_in_buffer--;
455 c = *next_input_byte++;
456 } while (c == 0xFF);
457
458 if (c == 0) {
459 /* Found FF/00, which represents an FF data byte */
460 c = 0xFF;
461 } else {
462 /* Oops, it's actually a marker indicating end of compressed data.
463 * Save the marker code for later use.
464 * Fine point: it might appear that we should save the marker into
465 * bitread working state, not straight into permanent state. But
466 * once we have hit a marker, we cannot need to suspend within the
467 * current MCU, because we will read no more bytes from the data
468 * source. So it is OK to update permanent state right away.
469 */
470 cinfo->unread_marker = c;
471 /* See if we need to insert some fake zero bits. */
472 goto no_more_bytes;
473 }
474 }
475
476 /* OK, load c into get_buffer */
477 get_buffer = (get_buffer << 8) | c; // read 8 bits every time
478 bits_left += 8; // read 8 bits every time
479 } /* end while */
480 } else {
481 no_more_bytes:
482 /* We get here if we've read the marker that terminates the compressed
483 * data segment. There should be enough bits in the buffer register
484 * to satisfy the request; if so, no problem.
485 */
486 if (nbits > bits_left) {
487 /* Uh-oh. Report corrupted data to user and stuff zeroes into
488 * the data stream, so that we can produce some kind of image.
489 * We use a nonvolatile flag to ensure that only one warning message
490 * appears per data segment.
491 */
492 if (!cinfo->entropy->insufficient_data) {
493 WARNMS(cinfo, JWRN_HIT_MARKER);
494 cinfo->entropy->insufficient_data = TRUE;
495 }
496 /* Fill the buffer with zero bits */
497 get_buffer <<= MIN_GET_BITS - bits_left;
498 bits_left = MIN_GET_BITS;
499 }
500 }
501
502 /* Unload the local registers */
503 state->next_input_byte = next_input_byte;
504 state->bytes_in_buffer = bytes_in_buffer;
505 state->get_buffer = get_buffer;
506 state->bits_left = bits_left;
507
508 return TRUE;
509 }
510
511
512 /* Macro version of the above, which performs much better but does not
513 handle markers. We have to hand off any blocks with markers to the
514 slower routines. */
515
516 #define GET_BYTE { \
517 register int c0, c1; \
518 c0 = *buffer++; \
519 c1 = *buffer; \
520 /* Pre-execute most common case */ \
521 get_buffer = (get_buffer << 8) | c0; \
522 bits_left += 8; \
523 if (c0 == 0xFF) { \
524 /* Pre-execute case of FF/00, which represents an FF data byte */ \
525 buffer++; \
526 if (c1 != 0) { \
527 /* Oops, it's actually a marker indicating end of compressed data. */ \
528 cinfo->unread_marker = c1; \
529 /* Back out pre-execution and fill the buffer with zero bits */ \
530 buffer -= 2; \
531 get_buffer &= ~0xFF; \
532 } \
533 } \
534 }
535
536 #if SIZEOF_SIZE_T == 8 || defined(_WIN64) || (defined(__x86_64__) && defined(__ILP32__))
537
538 /* Pre-fetch 48 bytes, because the holding register is 64-bit */
539 #define FILL_BIT_BUFFER_FAST \
540 if (bits_left <= 16) { \
541 GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE \
542 }
543
544 #else
545
546 /* Pre-fetch 16 bytes, because the holding register is 32-bit */
547 #define FILL_BIT_BUFFER_FAST \
548 if (bits_left <= 16) { \
549 GET_BYTE GET_BYTE \
550 }
551
552 #endif
553
554
555 /*
556 * Out-of-line code for Huffman code decoding.
557 * See jdhuff.h for info about usage.
558 */
559
560 GLOBAL(int)
jpeg_huff_decode(bitread_working_state * state,register bit_buf_type get_buffer,register int bits_left,d_derived_tbl * htbl,int min_bits)561 jpeg_huff_decode(bitread_working_state *state,
562 register bit_buf_type get_buffer, register int bits_left,
563 d_derived_tbl *htbl, int min_bits)
564 {
565 register int l = min_bits;
566 register JLONG code;
567
568 /* HUFF_DECODE has determined that the code is at least min_bits */
569 /* bits long, so fetch that many bits in one swoop. */
570
571 CHECK_BIT_BUFFER(*state, l, return -1);
572 code = GET_BITS(l);
573
574 /* Collect the rest of the Huffman code one bit at a time. */
575 /* This is per Figure F.16. */
576
577 while (code > htbl->maxcode[l]) {
578 code <<= 1;
579 CHECK_BIT_BUFFER(*state, 1, return -1);
580 code |= GET_BITS(1);
581 l++;
582 }
583
584 /* Unload the local registers */
585 state->get_buffer = get_buffer;
586 state->bits_left = bits_left;
587
588 /* With garbage input we may reach the sentinel value l = 17. */
589
590 if (l > MAX_HUFF_CODE_LEN) {
591 WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
592 return 0; /* fake a zero as the safest result */
593 }
594
595 return htbl->pub->huffval[(int)(code + htbl->valoffset[l])];
596 }
597
598 /*
599 * Check for a restart marker & resynchronize decoder.
600 * Returns FALSE if must suspend.
601 */
602
603 LOCAL(boolean)
process_restart(j_decompress_ptr cinfo)604 process_restart(j_decompress_ptr cinfo)
605 {
606 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
607 int ci;
608
609 /* Throw away any unused bits remaining in bit buffer; */
610 /* include any full bytes in next_marker's count of discarded bytes */
611 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8; // 8 bits in a byte
612 entropy->bitstate.bits_left = 0;
613
614 /* Advance past the RSTn marker */
615 if (!(*cinfo->marker->read_restart_marker) (cinfo))
616 return FALSE;
617
618 /* Re-initialize DC predictions to 0 */
619 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
620 entropy->saved.last_dc_val[ci] = 0;
621
622 /* Reset restart counter */
623 entropy->restarts_to_go = cinfo->restart_interval;
624
625 /* Reset out-of-data flag, unless read_restart_marker left us smack up
626 * against a marker. In that case we will end up treating the next data
627 * segment as empty, and we can avoid producing bogus output pixels by
628 * leaving the flag set.
629 */
630 if (cinfo->unread_marker == 0)
631 entropy->pub.insufficient_data = FALSE;
632
633 return TRUE;
634 }
635
636
637 #if defined(__has_feature)
638 #if __has_feature(undefined_behavior_sanitizer)
639 __attribute__((no_sanitize("signed-integer-overflow"),
640 no_sanitize("unsigned-integer-overflow")))
641 #endif
642 #endif
643 LOCAL(boolean)
decode_mcu_slow(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)644 decode_mcu_slow(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
645 {
646 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
647 BITREAD_STATE_VARS;
648 int blkn;
649 savable_state state;
650 /* Outer loop handles each block in the MCU */
651
652 /* Load up working state */
653 BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
654 state = entropy->saved;
655
656 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
657 JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
658 d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
659 d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
660 register int s, k, r;
661
662 /* Decode a single block's worth of coefficients */
663
664 /* Section F.2.2.1: decode the DC coefficient difference */
665 HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
666 if (s) {
667 CHECK_BIT_BUFFER(br_state, s, return FALSE);
668 r = GET_BITS(s);
669 s = HUFF_EXTEND(r, s);
670 }
671
672 if (entropy->dc_needed[blkn]) {
673 /* Convert DC difference to actual value, update last_dc_val */
674 int ci = cinfo->MCU_membership[blkn];
675 /* Certain malformed JPEG images produce repeated DC coefficient
676 * differences of 2047 or -2047, which causes state.last_dc_val[ci] to
677 * grow until it overflows or underflows a 32-bit signed integer. This
678 * behavior is, to the best of our understanding, innocuous, and it is
679 * unclear how to work around it without potentially affecting
680 * performance. Thus, we (hopefully temporarily) suppress UBSan integer
681 * overflow errors for this function.
682 */
683 s += state.last_dc_val[ci];
684 state.last_dc_val[ci] = s;
685 if (block) {
686 /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
687 (*block)[0] = (JCOEF)s;
688 }
689 }
690
691 if (entropy->ac_needed[blkn] && block) {
692 /* Section F.2.2.2: decode the AC coefficients */
693 /* Since zeroes are skipped, output area must be cleared beforehand */
694 for (k = 1; k < DCTSIZE2; k++) {
695 register int nb, look;
696 if (bits_left < HUFF_LOOKAHEAD) {
697 if (!jpeg_fill_bit_buffer(&br_state, get_buffer, bits_left, 0)) {
698 return FALSE;
699 }
700 get_buffer = br_state.get_buffer;
701 bits_left = br_state.bits_left;
702 if (bits_left < HUFF_LOOKAHEAD) {
703 nb = 1;
704 goto slowlabel;
705 }
706 }
707 look = PEEK_BITS(HUFF_LOOKAHEAD);
708 r = actbl->lookup[look];
709 nb = GET_NB(r);
710 unsigned int zero_num;
711 unsigned int coef_bits = GET_COEF_BITS(r);
712 if (nb <= HUFF_LOOKAHEAD) {
713 DROP_BITS(nb);
714 s = actbl->lookup[look] & ((1 << HUFF_LOOKAHEAD) - 1);
715 zero_num = GET_ZERO_NUM1(r);
716 k += zero_num;
717 if (coef_bits == 0) {
718 s = GET_COEF1(r);
719 (*block)[jpeg_natural_order[k]] = (JCOEF)s;
720 } else {
721 CHECK_BIT_BUFFER(br_state, (int)coef_bits, return FALSE);
722 r = GET_BITS(coef_bits);
723 s = HUFF_EXTEND(r, coef_bits);
724 (*block)[jpeg_natural_order[k]] = (JCOEF)s;
725 }
726 } else {
727 slowlabel:
728 nb = 1;
729 if ((s = jpeg_huff_decode(&br_state, get_buffer, bits_left, actbl, nb)) < 0) { return FALSE; }
730 get_buffer = br_state.get_buffer;
731 bits_left = br_state.bits_left;
732
733 r = s >> 4; // get higher 4 bits
734 s &= 15; // use 15 as a mask to get the lower 4 bits
735
736 if (s) {
737 k += r;
738 CHECK_BIT_BUFFER(br_state, s, return FALSE);
739 r = GET_BITS(s);
740 s = HUFF_EXTEND(r, s);
741 /* Output coefficient in natural (dezigzagged) order.
742 * Note: the extra entries in jpeg_natural_order[] will save us
743 * if k >= DCTSIZE2, which could happen if the data is corrupted.
744 */
745 (*block)[jpeg_natural_order[k]] = (JCOEF)s;
746 } else {
747 if (r != 15) // 15 = 0xF0 is a special symbol means 16 zeros in RLE coding
748 break;
749 k += 15; // use 15 to skip DCT coef zero
750 }
751 }
752 }
753 } else {
754 /* Section F.2.2.2: decode the AC coefficients */
755 /* In this path we just discard the values */
756 for (k = 1; k < DCTSIZE2; k++) {
757 register int nb, look;
758 if (bits_left < HUFF_LOOKAHEAD) {
759 if (!jpeg_fill_bit_buffer(&br_state, get_buffer, bits_left, 0)) {
760 return FALSE;
761 }
762 get_buffer = br_state.get_buffer;
763 bits_left = br_state.bits_left;
764 if (bits_left < HUFF_LOOKAHEAD) {
765 nb = 1;
766 goto slowlabel2;
767 }
768 }
769 look = PEEK_BITS(HUFF_LOOKAHEAD);
770 r = actbl->lookup[look];
771 nb = GET_NB(r);
772 unsigned int zero_num;
773 unsigned int coef_bits = GET_COEF_BITS(r);
774 if (nb <= HUFF_LOOKAHEAD) {
775 DROP_BITS(nb);
776 s = actbl->lookup[look] & ((1 << HUFF_LOOKAHEAD) - 1);
777 zero_num = GET_ZERO_NUM1(r);
778 k += zero_num;
779 if (coef_bits != 0) {
780 CHECK_BIT_BUFFER(br_state, (int)coef_bits, return FALSE);
781 DROP_BITS(coef_bits);
782 }
783 } else {
784 slowlabel2:
785 nb = 1;
786 if ((s = jpeg_huff_decode(&br_state, get_buffer, bits_left, actbl, nb)) < 0) { return FALSE; }
787 get_buffer = br_state.get_buffer;
788 bits_left = br_state.bits_left;
789
790 r = s >> 4; // get higher 4 bits
791 s &= 15; // use 15 as a mask to get the lower 4 bits
792
793 if (s) {
794 k += r;
795 CHECK_BIT_BUFFER(br_state, s, return FALSE);
796 DROP_BITS(s);
797 } else {
798 if (r != 15) // 15 = 0xF0 is a special symbol means 16 zeros in RLE coding
799 break;
800 k += 15; // use 15 to skip DCT coef zero
801 }
802 }
803 }
804 }
805 }
806
807 /* Completed MCU, so update state */
808 BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
809 entropy->saved = state;
810 return TRUE;
811 }
812
813
814 LOCAL(boolean)
decode_mcu_fast(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)815 decode_mcu_fast(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
816 {
817 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
818 BITREAD_STATE_VARS;
819 JOCTET *buffer;
820 int blkn;
821 savable_state state;
822 /* Outer loop handles each block in the MCU */
823
824 /* Load up working state */
825 BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
826 buffer = (JOCTET *)br_state.next_input_byte;
827 state = entropy->saved;
828
829 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
830 JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
831 d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
832 d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
833 register int s, k, r, l;
834
835 HUFF_DECODE_FAST(s, l, dctbl);
836 if (s) {
837 FILL_BIT_BUFFER_FAST
838 r = GET_BITS(s);
839 s = HUFF_EXTEND(r, s);
840 }
841
842 if (entropy->dc_needed[blkn]) {
843 int ci = cinfo->MCU_membership[blkn];
844 s += state.last_dc_val[ci];
845 state.last_dc_val[ci] = s;
846 if (block)
847 (*block)[0] = (JCOEF)s;
848 }
849
850 if (entropy->ac_needed[blkn] && block) {
851 for (k = 1; k < DCTSIZE2; k++) {
852 FILL_BIT_BUFFER_FAST;
853 r = PEEK_BITS(HUFF_LOOKAHEAD);
854 r = actbl->lookup[r];
855 l = GET_NB(r);
856 unsigned int zero_num;
857 unsigned int coef_bits = GET_COEF_BITS(r);
858
859 if (l <= HUFF_LOOKAHEAD) {
860 zero_num = GET_ZERO_NUM1(r);
861 DROP_BITS(l);
862 if (coef_bits == 0) {
863 s = GET_COEF1(r);
864 k += zero_num;
865 (*block)[jpeg_natural_order[k]] = (JCOEF)s;
866 } else {
867 FILL_BIT_BUFFER_FAST
868 r = GET_BITS(coef_bits);
869 s = HUFF_EXTEND(r, coef_bits);
870 k += zero_num;
871 (*block)[jpeg_natural_order[k]] = (JCOEF)s;
872 }
873 } else {
874 unsigned int base = GET_BASE(r); // base, higher 16 bits
875 unsigned int offset_bits = GET_EXTRA_BITS(r); // l = nb, the max code length in 2nd table
876 r = PEEK_BITS(l); // offset_bits as the index of 2nd table
877 s = actbl->lookup[base + (r & ((1 << offset_bits) - 1))];
878 l = GET_NB(s); // actual huff code length
879 coef_bits = GET_COEF_BITS(s);
880 zero_num = GET_ZERO_NUM1(s);
881 DROP_BITS(l);
882 if (coef_bits == 0xF) {
883 if (zero_num != 0xF) {
884 break;
885 } else {
886 k += 15; // use 15 to skip DCT coef zero
887 }
888 } else {
889 FILL_BIT_BUFFER_FAST
890 r = GET_BITS(coef_bits);
891 s = HUFF_EXTEND(r, coef_bits);
892 k += zero_num;
893 (*block)[jpeg_natural_order[k]] = (JCOEF)s;
894 }
895 }
896 }
897 } else {
898 for (k = 1; k < DCTSIZE2; k++) {
899 FILL_BIT_BUFFER_FAST;
900 r = PEEK_BITS(HUFF_LOOKAHEAD);
901 r = actbl->lookup[r];
902 l = GET_NB(r);
903 unsigned int zero_num;
904 unsigned int coef_bits = GET_COEF_BITS(r);
905
906 if (l <= HUFF_LOOKAHEAD) {
907 zero_num = GET_ZERO_NUM1(r);
908 DROP_BITS(l);
909 if (coef_bits == 0) {
910 s = GET_COEF1(r);
911 k += zero_num;
912 } else {
913 FILL_BIT_BUFFER_FAST
914 DROP_BITS(coef_bits);
915 k += zero_num;
916 }
917 } else {
918 unsigned int base = GET_BASE(r); // base, higher 16 bits
919 unsigned int offset_bits = GET_EXTRA_BITS(r); // l = nb, the max code length in 2nd table
920 r = PEEK_BITS(l); // offset_bits as the index of 2nd table
921 s = actbl->lookup[base + (r & ((1 << offset_bits) - 1))];
922 l = GET_NB(s); // actual huff code length
923 coef_bits = GET_COEF_BITS(s);
924 zero_num = GET_ZERO_NUM1(s);
925 DROP_BITS(l);
926 if (coef_bits == 0xF) {
927 if (zero_num != 0xF) {
928 break;
929 } else {
930 k += 15; // use 15 to skip DCT coef zero
931 }
932 } else {
933 FILL_BIT_BUFFER_FAST
934 DROP_BITS(coef_bits);
935 k += zero_num;
936 }
937 }
938 }
939 }
940 }
941
942 if (cinfo->unread_marker != 0) {
943 cinfo->unread_marker = 0;
944 return FALSE;
945 }
946
947 br_state.bytes_in_buffer -= (buffer - br_state.next_input_byte);
948 br_state.next_input_byte = buffer;
949 BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
950 entropy->saved = state;
951 return TRUE;
952 }
953
954
955 /*
956 * Decode and return one MCU's worth of Huffman-compressed coefficients.
957 * The coefficients are reordered from zigzag order into natural array order,
958 * but are not dequantized.
959 *
960 * The i'th block of the MCU is stored into the block pointed to by
961 * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
962 * (Wholesale zeroing is usually a little faster than retail...)
963 *
964 * Returns FALSE if data source requested suspension. In that case no
965 * changes have been made to permanent state. (Exception: some output
966 * coefficients may already have been assigned. This is harmless for
967 * this module, since we'll just re-assign them on the next call.)
968 */
969
970 #define BUFSIZE (DCTSIZE2 * 8)
971
972 METHODDEF(boolean)
decode_mcu(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)973 decode_mcu(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
974 {
975 huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
976 int usefast = 1;
977
978 /* Process restart marker if needed; may have to suspend */
979 if (cinfo->restart_interval) {
980 if (entropy->restarts_to_go == 0)
981 if (!process_restart(cinfo))
982 return FALSE;
983 usefast = 0;
984 }
985
986 if (cinfo->src->bytes_in_buffer < BUFSIZE * (size_t)cinfo->blocks_in_MCU ||
987 cinfo->unread_marker != 0)
988 usefast = 0;
989
990 /* If we've run out of data, just leave the MCU set to zeroes.
991 * This way, we return uniform gray for the remainder of the segment.
992 */
993 if (!entropy->pub.insufficient_data) {
994 if (usefast) {
995 if (!decode_mcu_fast(cinfo, MCU_data)) goto use_slow;
996 } else {
997 use_slow:
998 if (!decode_mcu_slow(cinfo, MCU_data)) return FALSE;
999 }
1000 }
1001
1002 /* Account for restart interval (no-op if not using restarts) */
1003 if (cinfo->restart_interval)
1004 entropy->restarts_to_go--;
1005
1006 return TRUE;
1007 }
1008
1009
1010 /*
1011 * Module initialization routine for Huffman entropy decoding.
1012 */
1013
1014 GLOBAL(void)
jinit_huff_decoder(j_decompress_ptr cinfo)1015 jinit_huff_decoder(j_decompress_ptr cinfo)
1016 {
1017 huff_entropy_ptr entropy;
1018 int i;
1019
1020 /* Motion JPEG frames typically do not include the Huffman tables if they
1021 are the default tables. Thus, if the tables are not set by the time
1022 the Huffman decoder is initialized (usually within the body of
1023 jpeg_start_decompress()), we set them to default values. */
1024 std_huff_tables((j_common_ptr)cinfo);
1025
1026 entropy = (huff_entropy_ptr)
1027 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
1028 sizeof(huff_entropy_decoder));
1029 cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
1030 entropy->pub.start_pass = start_pass_huff_decoder;
1031 entropy->pub.decode_mcu = decode_mcu;
1032
1033 /* Mark tables unallocated */
1034 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1035 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1036 }
1037 }
1038