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