xref: /reactos/dll/3rdparty/libjpeg/jdhuff.c (revision 1d574191)
1 /*
2  * jdhuff.c
3  *
4  * Copyright (C) 1991-1997, Thomas G. Lane.
5  * Modified 2006-2019 by Guido Vollbeding.
6  * This file is part of the Independent JPEG Group's software.
7  * For conditions of distribution and use, see the accompanying README file.
8  *
9  * This file contains Huffman entropy decoding routines.
10  * Both sequential and progressive modes are supported in this single module.
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 
23 
24 /* Derived data constructed for each Huffman table */
25 
26 #define HUFF_LOOKAHEAD	8	/* # of bits of lookahead */
27 
28 typedef struct {
29   /* Basic tables: (element [0] of each array is unused) */
30   INT32 maxcode[18];		/* largest code of length k (-1 if none) */
31   /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
32   INT32 valoffset[17];		/* huffval[] offset for codes of length k */
33   /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
34    * the smallest code of length k; so given a code of length k, the
35    * corresponding symbol is huffval[code + valoffset[k]]
36    */
37 
38   /* Link to public Huffman table (needed only in jpeg_huff_decode) */
39   JHUFF_TBL *pub;
40 
41   /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
42    * the input data stream.  If the next Huffman code is no more
43    * than HUFF_LOOKAHEAD bits long, we can obtain its length and
44    * the corresponding symbol directly from these tables.
45    */
46   int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
47   UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
48 } d_derived_tbl;
49 
50 
51 /*
52  * Fetching the next N bits from the input stream is a time-critical operation
53  * for the Huffman decoders.  We implement it with a combination of inline
54  * macros and out-of-line subroutines.  Note that N (the number of bits
55  * demanded at one time) never exceeds 15 for JPEG use.
56  *
57  * We read source bytes into get_buffer and dole out bits as needed.
58  * If get_buffer already contains enough bits, they are fetched in-line
59  * by the macros CHECK_BIT_BUFFER and GET_BITS.  When there aren't enough
60  * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
61  * as full as possible (not just to the number of bits needed; this
62  * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
63  * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
64  * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
65  * at least the requested number of bits --- dummy zeroes are inserted if
66  * necessary.
67  */
68 
69 typedef INT32 bit_buf_type;	/* type of bit-extraction buffer */
70 #define BIT_BUF_SIZE  32	/* size of buffer in bits */
71 
72 /* If long is > 32 bits on your machine, and shifting/masking longs is
73  * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
74  * appropriately should be a win.  Unfortunately we can't define the size
75  * with something like  #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
76  * because not all machines measure sizeof in 8-bit bytes.
77  */
78 
79 typedef struct {		/* Bitreading state saved across MCUs */
80   bit_buf_type get_buffer;	/* current bit-extraction buffer */
81   int bits_left;		/* # of unused bits in it */
82 } bitread_perm_state;
83 
84 typedef struct {		/* Bitreading working state within an MCU */
85   /* Current data source location */
86   /* We need a copy, rather than munging the original, in case of suspension */
87   const JOCTET * next_input_byte; /* => next byte to read from source */
88   size_t bytes_in_buffer;	/* # of bytes remaining in source buffer */
89   /* Bit input buffer --- note these values are kept in register variables,
90    * not in this struct, inside the inner loops.
91    */
92   bit_buf_type get_buffer;	/* current bit-extraction buffer */
93   int bits_left;		/* # of unused bits in it */
94   /* Pointer needed by jpeg_fill_bit_buffer. */
95   j_decompress_ptr cinfo;	/* back link to decompress master record */
96 } bitread_working_state;
97 
98 /* Macros to declare and load/save bitread local variables. */
99 #define BITREAD_STATE_VARS  \
100 	register bit_buf_type get_buffer;  \
101 	register int bits_left;  \
102 	bitread_working_state br_state
103 
104 #define BITREAD_LOAD_STATE(cinfop,permstate)  \
105 	br_state.cinfo = cinfop; \
106 	br_state.next_input_byte = cinfop->src->next_input_byte; \
107 	br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
108 	get_buffer = permstate.get_buffer; \
109 	bits_left = permstate.bits_left;
110 
111 #define BITREAD_SAVE_STATE(cinfop,permstate)  \
112 	cinfop->src->next_input_byte = br_state.next_input_byte; \
113 	cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
114 	permstate.get_buffer = get_buffer; \
115 	permstate.bits_left = bits_left
116 
117 /*
118  * These macros provide the in-line portion of bit fetching.
119  * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
120  * before using GET_BITS, PEEK_BITS, or DROP_BITS.
121  * The variables get_buffer and bits_left are assumed to be locals,
122  * but the state struct might not be (jpeg_huff_decode needs this).
123  *	CHECK_BIT_BUFFER(state,n,action);
124  *		Ensure there are N bits in get_buffer; if suspend, take action.
125  *      val = GET_BITS(n);
126  *		Fetch next N bits.
127  *      val = PEEK_BITS(n);
128  *		Fetch next N bits without removing them from the buffer.
129  *	DROP_BITS(n);
130  *		Discard next N bits.
131  * The value N should be a simple variable, not an expression, because it
132  * is evaluated multiple times.
133  */
134 
135 #define CHECK_BIT_BUFFER(state,nbits,action) \
136 	{ if (bits_left < (nbits)) {  \
137 	    if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits))  \
138 	      { action; }  \
139 	    get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
140 
141 #define GET_BITS(nbits) \
142 	(((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits))
143 
144 #define PEEK_BITS(nbits) \
145 	(((int) (get_buffer >> (bits_left -  (nbits)))) & BIT_MASK(nbits))
146 
147 #define DROP_BITS(nbits) \
148 	(bits_left -= (nbits))
149 
150 
151 /*
152  * Code for extracting next Huffman-coded symbol from input bit stream.
153  * Again, this is time-critical and we make the main paths be macros.
154  *
155  * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
156  * without looping.  Usually, more than 95% of the Huffman codes will be 8
157  * or fewer bits long.  The few overlength codes are handled with a loop,
158  * which need not be inline code.
159  *
160  * Notes about the HUFF_DECODE macro:
161  * 1. Near the end of the data segment, we may fail to get enough bits
162  *    for a lookahead.  In that case, we do it the hard way.
163  * 2. If the lookahead table contains no entry, the next code must be
164  *    more than HUFF_LOOKAHEAD bits long.
165  * 3. jpeg_huff_decode returns -1 if forced to suspend.
166  */
167 
168 #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
169 { register int nb, look; \
170   if (bits_left < HUFF_LOOKAHEAD) { \
171     if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
172     get_buffer = state.get_buffer; bits_left = state.bits_left; \
173     if (bits_left < HUFF_LOOKAHEAD) { \
174       nb = 1; goto slowlabel; \
175     } \
176   } \
177   look = PEEK_BITS(HUFF_LOOKAHEAD); \
178   if ((nb = htbl->look_nbits[look]) != 0) { \
179     DROP_BITS(nb); \
180     result = htbl->look_sym[look]; \
181   } else { \
182     nb = HUFF_LOOKAHEAD+1; \
183 slowlabel: \
184     if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
185 	{ failaction; } \
186     get_buffer = state.get_buffer; bits_left = state.bits_left; \
187   } \
188 }
189 
190 
191 /*
192  * Expanded entropy decoder object for Huffman decoding.
193  *
194  * The savable_state subrecord contains fields that change within an MCU,
195  * but must not be updated permanently until we complete the MCU.
196  */
197 
198 typedef struct {
199   unsigned int EOBRUN;			/* remaining EOBs in EOBRUN */
200   int last_dc_val[MAX_COMPS_IN_SCAN];	/* last DC coef for each component */
201 } savable_state;
202 
203 /* This macro is to work around compilers with missing or broken
204  * structure assignment.  You'll need to fix this code if you have
205  * such a compiler and you change MAX_COMPS_IN_SCAN.
206  */
207 
208 #ifndef NO_STRUCT_ASSIGN
209 #define ASSIGN_STATE(dest,src)  ((dest) = (src))
210 #else
211 #if MAX_COMPS_IN_SCAN == 4
212 #define ASSIGN_STATE(dest,src)  \
213 	((dest).EOBRUN = (src).EOBRUN, \
214 	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
215 	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
216 	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
217 	 (dest).last_dc_val[3] = (src).last_dc_val[3])
218 #endif
219 #endif
220 
221 
222 typedef struct {
223   struct jpeg_entropy_decoder pub; /* public fields */
224 
225   /* These fields are loaded into local variables at start of each MCU.
226    * In case of suspension, we exit WITHOUT updating them.
227    */
228   bitread_perm_state bitstate;	/* Bit buffer at start of MCU */
229   savable_state saved;		/* Other state at start of MCU */
230 
231   /* These fields are NOT loaded into local working state. */
232   boolean insufficient_data;	/* set TRUE after emitting warning */
233   unsigned int restarts_to_go;	/* MCUs left in this restart interval */
234 
235   /* Following two fields used only in progressive mode */
236 
237   /* Pointers to derived tables (these workspaces have image lifespan) */
238   d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
239 
240   d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
241 
242   /* Following fields used only in sequential mode */
243 
244   /* Pointers to derived tables (these workspaces have image lifespan) */
245   d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
246   d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
247 
248   /* Precalculated info set up by start_pass for use in decode_mcu: */
249 
250   /* Pointers to derived tables to be used for each block within an MCU */
251   d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
252   d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
253   /* Whether we care about the DC and AC coefficient values for each block */
254   int coef_limit[D_MAX_BLOCKS_IN_MCU];
255 } huff_entropy_decoder;
256 
257 typedef huff_entropy_decoder * huff_entropy_ptr;
258 
259 
260 static const int jpeg_zigzag_order[8][8] = {
261   {  0,  1,  5,  6, 14, 15, 27, 28 },
262   {  2,  4,  7, 13, 16, 26, 29, 42 },
263   {  3,  8, 12, 17, 25, 30, 41, 43 },
264   {  9, 11, 18, 24, 31, 40, 44, 53 },
265   { 10, 19, 23, 32, 39, 45, 52, 54 },
266   { 20, 22, 33, 38, 46, 51, 55, 60 },
267   { 21, 34, 37, 47, 50, 56, 59, 61 },
268   { 35, 36, 48, 49, 57, 58, 62, 63 }
269 };
270 
271 static const int jpeg_zigzag_order7[7][7] = {
272   {  0,  1,  5,  6, 14, 15, 27 },
273   {  2,  4,  7, 13, 16, 26, 28 },
274   {  3,  8, 12, 17, 25, 29, 38 },
275   {  9, 11, 18, 24, 30, 37, 39 },
276   { 10, 19, 23, 31, 36, 40, 45 },
277   { 20, 22, 32, 35, 41, 44, 46 },
278   { 21, 33, 34, 42, 43, 47, 48 }
279 };
280 
281 static const int jpeg_zigzag_order6[6][6] = {
282   {  0,  1,  5,  6, 14, 15 },
283   {  2,  4,  7, 13, 16, 25 },
284   {  3,  8, 12, 17, 24, 26 },
285   {  9, 11, 18, 23, 27, 32 },
286   { 10, 19, 22, 28, 31, 33 },
287   { 20, 21, 29, 30, 34, 35 }
288 };
289 
290 static const int jpeg_zigzag_order5[5][5] = {
291   {  0,  1,  5,  6, 14 },
292   {  2,  4,  7, 13, 15 },
293   {  3,  8, 12, 16, 21 },
294   {  9, 11, 17, 20, 22 },
295   { 10, 18, 19, 23, 24 }
296 };
297 
298 static const int jpeg_zigzag_order4[4][4] = {
299   { 0,  1,  5,  6 },
300   { 2,  4,  7, 12 },
301   { 3,  8, 11, 13 },
302   { 9, 10, 14, 15 }
303 };
304 
305 static const int jpeg_zigzag_order3[3][3] = {
306   { 0, 1, 5 },
307   { 2, 4, 6 },
308   { 3, 7, 8 }
309 };
310 
311 static const int jpeg_zigzag_order2[2][2] = {
312   { 0, 1 },
313   { 2, 3 }
314 };
315 
316 
317 /*
318  * Compute the derived values for a Huffman table.
319  * This routine also performs some validation checks on the table.
320  */
321 
322 LOCAL(void)
jpeg_make_d_derived_tbl(j_decompress_ptr cinfo,boolean isDC,int tblno,d_derived_tbl ** pdtbl)323 jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
324 			 d_derived_tbl ** pdtbl)
325 {
326   JHUFF_TBL *htbl;
327   d_derived_tbl *dtbl;
328   int p, i, l, si, numsymbols;
329   int lookbits, ctr;
330   char huffsize[257];
331   unsigned int huffcode[257];
332   unsigned int code;
333 
334   /* Note that huffsize[] and huffcode[] are filled in code-length order,
335    * paralleling the order of the symbols themselves in htbl->huffval[].
336    */
337 
338   /* Find the input Huffman table */
339   if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
340     ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
341   htbl =
342     isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
343   if (htbl == NULL)
344     htbl = jpeg_std_huff_table((j_common_ptr) cinfo, isDC, tblno);
345 
346   /* Allocate a workspace if we haven't already done so. */
347   if (*pdtbl == NULL)
348     *pdtbl = (d_derived_tbl *) (*cinfo->mem->alloc_small)
349       ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(d_derived_tbl));
350   dtbl = *pdtbl;
351   dtbl->pub = htbl;		/* fill in back link */
352 
353   /* Figure C.1: make table of Huffman code length for each symbol */
354 
355   p = 0;
356   for (l = 1; l <= 16; l++) {
357     i = (int) htbl->bits[l];
358     if (i < 0 || p + i > 256)	/* protect against table overrun */
359       ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
360     while (i--)
361       huffsize[p++] = (char) l;
362   }
363   huffsize[p] = 0;
364   numsymbols = p;
365 
366   /* Figure C.2: generate the codes themselves */
367   /* We also validate that the counts represent a legal Huffman code tree. */
368 
369   code = 0;
370   si = huffsize[0];
371   p = 0;
372   while (huffsize[p]) {
373     while (((int) huffsize[p]) == si) {
374       huffcode[p++] = code;
375       code++;
376     }
377     /* code is now 1 more than the last code used for codelength si; but
378      * it must still fit in si bits, since no code is allowed to be all ones.
379      */
380     if (((INT32) code) >= (((INT32) 1) << si))
381       ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
382     code <<= 1;
383     si++;
384   }
385 
386   /* Figure F.15: generate decoding tables for bit-sequential decoding */
387 
388   p = 0;
389   for (l = 1; l <= 16; l++) {
390     if (htbl->bits[l]) {
391       /* valoffset[l] = huffval[] index of 1st symbol of code length l,
392        * minus the minimum code of length l
393        */
394       dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
395       p += htbl->bits[l];
396       dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
397     } else {
398       dtbl->maxcode[l] = -1;	/* -1 if no codes of this length */
399     }
400   }
401   dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
402 
403   /* Compute lookahead tables to speed up decoding.
404    * First we set all the table entries to 0, indicating "too long";
405    * then we iterate through the Huffman codes that are short enough and
406    * fill in all the entries that correspond to bit sequences starting
407    * with that code.
408    */
409 
410   MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
411 
412   p = 0;
413   for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
414     for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
415       /* l = current code's length, p = its index in huffcode[] & huffval[]. */
416       /* Generate left-justified code followed by all possible bit sequences */
417       lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
418       for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
419 	dtbl->look_nbits[lookbits] = l;
420 	dtbl->look_sym[lookbits] = htbl->huffval[p];
421 	lookbits++;
422       }
423     }
424   }
425 
426   /* Validate symbols as being reasonable.
427    * For AC tables, we make no check, but accept all byte values 0..255.
428    * For DC tables, we require the symbols to be in range 0..15.
429    * (Tighter bounds could be applied depending on the data depth and mode,
430    * but this is sufficient to ensure safe decoding.)
431    */
432   if (isDC) {
433     for (i = 0; i < numsymbols; i++) {
434       int sym = htbl->huffval[i];
435       if (sym < 0 || sym > 15)
436 	ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
437     }
438   }
439 }
440 
441 
442 /*
443  * Out-of-line code for bit fetching.
444  * Note: current values of get_buffer and bits_left are passed as parameters,
445  * but are returned in the corresponding fields of the state struct.
446  *
447  * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
448  * of get_buffer to be used.  (On machines with wider words, an even larger
449  * buffer could be used.)  However, on some machines 32-bit shifts are
450  * quite slow and take time proportional to the number of places shifted.
451  * (This is true with most PC compilers, for instance.)  In this case it may
452  * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
453  * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
454  */
455 
456 #ifdef SLOW_SHIFT_32
457 #define MIN_GET_BITS  15	/* minimum allowable value */
458 #else
459 #define MIN_GET_BITS  (BIT_BUF_SIZE-7)
460 #endif
461 
462 
463 LOCAL(boolean)
jpeg_fill_bit_buffer(bitread_working_state * state,register bit_buf_type get_buffer,register int bits_left,int nbits)464 jpeg_fill_bit_buffer (bitread_working_state * state,
465 		      register bit_buf_type get_buffer, register int bits_left,
466 		      int nbits)
467 /* Load up the bit buffer to a depth of at least nbits */
468 {
469   /* Copy heavily used state fields into locals (hopefully registers) */
470   register const JOCTET * next_input_byte = state->next_input_byte;
471   register size_t bytes_in_buffer = state->bytes_in_buffer;
472   j_decompress_ptr cinfo = state->cinfo;
473 
474   /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
475   /* (It is assumed that no request will be for more than that many bits.) */
476   /* We fail to do so only if we hit a marker or are forced to suspend. */
477 
478   if (cinfo->unread_marker == 0) {	/* cannot advance past a marker */
479     while (bits_left < MIN_GET_BITS) {
480       register int c;
481 
482       /* Attempt to read a byte */
483       if (bytes_in_buffer == 0) {
484 	if (! (*cinfo->src->fill_input_buffer) (cinfo))
485 	  return FALSE;
486 	next_input_byte = cinfo->src->next_input_byte;
487 	bytes_in_buffer = cinfo->src->bytes_in_buffer;
488       }
489       bytes_in_buffer--;
490       c = GETJOCTET(*next_input_byte++);
491 
492       /* If it's 0xFF, check and discard stuffed zero byte */
493       if (c == 0xFF) {
494 	/* Loop here to discard any padding FF's on terminating marker,
495 	 * so that we can save a valid unread_marker value.  NOTE: we will
496 	 * accept multiple FF's followed by a 0 as meaning a single FF data
497 	 * byte.  This data pattern is not valid according to the standard.
498 	 */
499 	do {
500 	  if (bytes_in_buffer == 0) {
501 	    if (! (*cinfo->src->fill_input_buffer) (cinfo))
502 	      return FALSE;
503 	    next_input_byte = cinfo->src->next_input_byte;
504 	    bytes_in_buffer = cinfo->src->bytes_in_buffer;
505 	  }
506 	  bytes_in_buffer--;
507 	  c = GETJOCTET(*next_input_byte++);
508 	} while (c == 0xFF);
509 
510 	if (c == 0) {
511 	  /* Found FF/00, which represents an FF data byte */
512 	  c = 0xFF;
513 	} else {
514 	  /* Oops, it's actually a marker indicating end of compressed data.
515 	   * Save the marker code for later use.
516 	   * Fine point: it might appear that we should save the marker into
517 	   * bitread working state, not straight into permanent state.  But
518 	   * once we have hit a marker, we cannot need to suspend within the
519 	   * current MCU, because we will read no more bytes from the data
520 	   * source.  So it is OK to update permanent state right away.
521 	   */
522 	  cinfo->unread_marker = c;
523 	  /* See if we need to insert some fake zero bits. */
524 	  goto no_more_bytes;
525 	}
526       }
527 
528       /* OK, load c into get_buffer */
529       get_buffer = (get_buffer << 8) | c;
530       bits_left += 8;
531     } /* end while */
532   } else {
533   no_more_bytes:
534     /* We get here if we've read the marker that terminates the compressed
535      * data segment.  There should be enough bits in the buffer register
536      * to satisfy the request; if so, no problem.
537      */
538     if (nbits > bits_left) {
539       /* Uh-oh.  Report corrupted data to user and stuff zeroes into
540        * the data stream, so that we can produce some kind of image.
541        * We use a nonvolatile flag to ensure that only one warning message
542        * appears per data segment.
543        */
544       if (! ((huff_entropy_ptr) cinfo->entropy)->insufficient_data) {
545 	WARNMS(cinfo, JWRN_HIT_MARKER);
546 	((huff_entropy_ptr) cinfo->entropy)->insufficient_data = TRUE;
547       }
548       /* Fill the buffer with zero bits */
549       get_buffer <<= MIN_GET_BITS - bits_left;
550       bits_left = MIN_GET_BITS;
551     }
552   }
553 
554   /* Unload the local registers */
555   state->next_input_byte = next_input_byte;
556   state->bytes_in_buffer = bytes_in_buffer;
557   state->get_buffer = get_buffer;
558   state->bits_left = bits_left;
559 
560   return TRUE;
561 }
562 
563 
564 /*
565  * Figure F.12: extend sign bit.
566  * On some machines, a shift and sub will be faster than a table lookup.
567  */
568 
569 #ifdef AVOID_TABLES
570 
571 #define BIT_MASK(nbits)   ((1<<(nbits))-1)
572 #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
573 
574 #else
575 
576 #define BIT_MASK(nbits)   bmask[nbits]
577 #define HUFF_EXTEND(x,s)  ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
578 
579 static const int bmask[16] =	/* bmask[n] is mask for n rightmost bits */
580   { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
581     0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
582 
583 #endif /* AVOID_TABLES */
584 
585 
586 /*
587  * Out-of-line code for Huffman code decoding.
588  */
589 
590 LOCAL(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)591 jpeg_huff_decode (bitread_working_state * state,
592 		  register bit_buf_type get_buffer, register int bits_left,
593 		  d_derived_tbl * htbl, int min_bits)
594 {
595   register int l = min_bits;
596   register INT32 code;
597 
598   /* HUFF_DECODE has determined that the code is at least min_bits */
599   /* bits long, so fetch that many bits in one swoop. */
600 
601   CHECK_BIT_BUFFER(*state, l, return -1);
602   code = GET_BITS(l);
603 
604   /* Collect the rest of the Huffman code one bit at a time. */
605   /* This is per Figure F.16 in the JPEG spec. */
606 
607   while (code > htbl->maxcode[l]) {
608     code <<= 1;
609     CHECK_BIT_BUFFER(*state, 1, return -1);
610     code |= GET_BITS(1);
611     l++;
612   }
613 
614   /* Unload the local registers */
615   state->get_buffer = get_buffer;
616   state->bits_left = bits_left;
617 
618   /* With garbage input we may reach the sentinel value l = 17. */
619 
620   if (l > 16) {
621     WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
622     return 0;			/* fake a zero as the safest result */
623   }
624 
625   return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
626 }
627 
628 
629 /*
630  * Finish up at the end of a Huffman-compressed scan.
631  */
632 
633 METHODDEF(void)
finish_pass_huff(j_decompress_ptr cinfo)634 finish_pass_huff (j_decompress_ptr cinfo)
635 {
636   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
637 
638   /* Throw away any unused bits remaining in bit buffer; */
639   /* include any full bytes in next_marker's count of discarded bytes */
640   cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
641   entropy->bitstate.bits_left = 0;
642 }
643 
644 
645 /*
646  * Check for a restart marker & resynchronize decoder.
647  * Returns FALSE if must suspend.
648  */
649 
650 LOCAL(boolean)
process_restart(j_decompress_ptr cinfo)651 process_restart (j_decompress_ptr cinfo)
652 {
653   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
654   int ci;
655 
656   finish_pass_huff(cinfo);
657 
658   /* Advance past the RSTn marker */
659   if (! (*cinfo->marker->read_restart_marker) (cinfo))
660     return FALSE;
661 
662   /* Re-initialize DC predictions to 0 */
663   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
664     entropy->saved.last_dc_val[ci] = 0;
665   /* Re-init EOB run count, too */
666   entropy->saved.EOBRUN = 0;
667 
668   /* Reset restart counter */
669   entropy->restarts_to_go = cinfo->restart_interval;
670 
671   /* Reset out-of-data flag, unless read_restart_marker left us smack up
672    * against a marker.  In that case we will end up treating the next data
673    * segment as empty, and we can avoid producing bogus output pixels by
674    * leaving the flag set.
675    */
676   if (cinfo->unread_marker == 0)
677     entropy->insufficient_data = FALSE;
678 
679   return TRUE;
680 }
681 
682 
683 /*
684  * Huffman MCU decoding.
685  * Each of these routines decodes and returns one MCU's worth of
686  * Huffman-compressed coefficients.
687  * The coefficients are reordered from zigzag order into natural array order,
688  * but are not dequantized.
689  *
690  * The i'th block of the MCU is stored into the block pointed to by
691  * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
692  * (Wholesale zeroing is usually a little faster than retail...)
693  *
694  * We return FALSE if data source requested suspension.  In that case no
695  * changes have been made to permanent state.  (Exception: some output
696  * coefficients may already have been assigned.  This is harmless for
697  * spectral selection, since we'll just re-assign them on the next call.
698  * Successive approximation AC refinement has to be more careful, however.)
699  */
700 
701 /*
702  * MCU decoding for DC initial scan (either spectral selection,
703  * or first pass of successive approximation).
704  */
705 
706 METHODDEF(boolean)
decode_mcu_DC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)707 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
708 {
709   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
710   int Al = cinfo->Al;
711   register int s, r;
712   int blkn, ci;
713   JBLOCKROW block;
714   BITREAD_STATE_VARS;
715   savable_state state;
716   d_derived_tbl * tbl;
717   jpeg_component_info * compptr;
718 
719   /* Process restart marker if needed; may have to suspend */
720   if (cinfo->restart_interval) {
721     if (entropy->restarts_to_go == 0)
722       if (! process_restart(cinfo))
723 	return FALSE;
724   }
725 
726   /* If we've run out of data, just leave the MCU set to zeroes.
727    * This way, we return uniform gray for the remainder of the segment.
728    */
729   if (! entropy->insufficient_data) {
730 
731     /* Load up working state */
732     BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
733     ASSIGN_STATE(state, entropy->saved);
734 
735     /* Outer loop handles each block in the MCU */
736 
737     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
738       block = MCU_data[blkn];
739       ci = cinfo->MCU_membership[blkn];
740       compptr = cinfo->cur_comp_info[ci];
741       tbl = entropy->derived_tbls[compptr->dc_tbl_no];
742 
743       /* Decode a single block's worth of coefficients */
744 
745       /* Section F.2.2.1: decode the DC coefficient difference */
746       HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
747       if (s) {
748 	CHECK_BIT_BUFFER(br_state, s, return FALSE);
749 	r = GET_BITS(s);
750 	s = HUFF_EXTEND(r, s);
751       }
752 
753       /* Convert DC difference to actual value, update last_dc_val */
754       s += state.last_dc_val[ci];
755       state.last_dc_val[ci] = s;
756       /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
757       (*block)[0] = (JCOEF) (s << Al);
758     }
759 
760     /* Completed MCU, so update state */
761     BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
762     ASSIGN_STATE(entropy->saved, state);
763   }
764 
765   /* Account for restart interval if using restarts */
766   if (cinfo->restart_interval)
767     entropy->restarts_to_go--;
768 
769   return TRUE;
770 }
771 
772 
773 /*
774  * MCU decoding for AC initial scan (either spectral selection,
775  * or first pass of successive approximation).
776  */
777 
778 METHODDEF(boolean)
decode_mcu_AC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)779 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
780 {
781   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
782   register int s, k, r;
783   unsigned int EOBRUN;
784   int Se, Al;
785   const int * natural_order;
786   JBLOCKROW block;
787   BITREAD_STATE_VARS;
788   d_derived_tbl * tbl;
789 
790   /* Process restart marker if needed; may have to suspend */
791   if (cinfo->restart_interval) {
792     if (entropy->restarts_to_go == 0)
793       if (! process_restart(cinfo))
794 	return FALSE;
795   }
796 
797   /* If we've run out of data, just leave the MCU set to zeroes.
798    * This way, we return uniform gray for the remainder of the segment.
799    */
800   if (! entropy->insufficient_data) {
801 
802     /* Load up working state.
803      * We can avoid loading/saving bitread state if in an EOB run.
804      */
805     EOBRUN = entropy->saved.EOBRUN;	/* only part of saved state we need */
806 
807     /* There is always only one block per MCU */
808 
809     if (EOBRUN)			/* if it's a band of zeroes... */
810       EOBRUN--;			/* ...process it now (we do nothing) */
811     else {
812       BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
813       Se = cinfo->Se;
814       Al = cinfo->Al;
815       natural_order = cinfo->natural_order;
816       block = MCU_data[0];
817       tbl = entropy->ac_derived_tbl;
818 
819       for (k = cinfo->Ss; k <= Se; k++) {
820 	HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
821 	r = s >> 4;
822 	s &= 15;
823 	if (s) {
824 	  k += r;
825 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
826 	  r = GET_BITS(s);
827 	  s = HUFF_EXTEND(r, s);
828 	  /* Scale and output coefficient in natural (dezigzagged) order */
829 	  (*block)[natural_order[k]] = (JCOEF) (s << Al);
830 	} else {
831 	  if (r != 15) {	/* EOBr, run length is 2^r + appended bits */
832 	    if (r) {		/* EOBr, r > 0 */
833 	      EOBRUN = 1 << r;
834 	      CHECK_BIT_BUFFER(br_state, r, return FALSE);
835 	      r = GET_BITS(r);
836 	      EOBRUN += r;
837 	      EOBRUN--;		/* this band is processed at this moment */
838 	    }
839 	    break;		/* force end-of-band */
840 	  }
841 	  k += 15;		/* ZRL: skip 15 zeroes in band */
842 	}
843       }
844 
845       BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
846     }
847 
848     /* Completed MCU, so update state */
849     entropy->saved.EOBRUN = EOBRUN;	/* only part of saved state we need */
850   }
851 
852   /* Account for restart interval if using restarts */
853   if (cinfo->restart_interval)
854     entropy->restarts_to_go--;
855 
856   return TRUE;
857 }
858 
859 
860 /*
861  * MCU decoding for DC successive approximation refinement scan.
862  * Note: we assume such scans can be multi-component,
863  * although the spec is not very clear on the point.
864  */
865 
866 METHODDEF(boolean)
decode_mcu_DC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)867 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
868 {
869   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
870   JCOEF p1;
871   int blkn;
872   BITREAD_STATE_VARS;
873 
874   /* Process restart marker if needed; may have to suspend */
875   if (cinfo->restart_interval) {
876     if (entropy->restarts_to_go == 0)
877       if (! process_restart(cinfo))
878 	return FALSE;
879   }
880 
881   /* Not worth the cycles to check insufficient_data here,
882    * since we will not change the data anyway if we read zeroes.
883    */
884 
885   /* Load up working state */
886   BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
887 
888   p1 = 1 << cinfo->Al;		/* 1 in the bit position being coded */
889 
890   /* Outer loop handles each block in the MCU */
891 
892   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
893     /* Encoded data is simply the next bit of the two's-complement DC value */
894     CHECK_BIT_BUFFER(br_state, 1, return FALSE);
895     if (GET_BITS(1))
896       MCU_data[blkn][0][0] |= p1;
897     /* Note: since we use |=, repeating the assignment later is safe */
898   }
899 
900   /* Completed MCU, so update state */
901   BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
902 
903   /* Account for restart interval if using restarts */
904   if (cinfo->restart_interval)
905     entropy->restarts_to_go--;
906 
907   return TRUE;
908 }
909 
910 
911 /*
912  * MCU decoding for AC successive approximation refinement scan.
913  */
914 
915 METHODDEF(boolean)
decode_mcu_AC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)916 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
917 {
918   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
919   register int s, k, r;
920   unsigned int EOBRUN;
921   int Se;
922   JCOEF p1, m1;
923   const int * natural_order;
924   JBLOCKROW block;
925   JCOEFPTR thiscoef;
926   BITREAD_STATE_VARS;
927   d_derived_tbl * tbl;
928   int num_newnz;
929   int newnz_pos[DCTSIZE2];
930 
931   /* Process restart marker if needed; may have to suspend */
932   if (cinfo->restart_interval) {
933     if (entropy->restarts_to_go == 0)
934       if (! process_restart(cinfo))
935 	return FALSE;
936   }
937 
938   /* If we've run out of data, don't modify the MCU.
939    */
940   if (! entropy->insufficient_data) {
941 
942     Se = cinfo->Se;
943     p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
944     m1 = -p1;			/* -1 in the bit position being coded */
945     natural_order = cinfo->natural_order;
946 
947     /* Load up working state */
948     BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
949     EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
950 
951     /* There is always only one block per MCU */
952     block = MCU_data[0];
953     tbl = entropy->ac_derived_tbl;
954 
955     /* If we are forced to suspend, we must undo the assignments to any newly
956      * nonzero coefficients in the block, because otherwise we'd get confused
957      * next time about which coefficients were already nonzero.
958      * But we need not undo addition of bits to already-nonzero coefficients;
959      * instead, we can test the current bit to see if we already did it.
960      */
961     num_newnz = 0;
962 
963     /* initialize coefficient loop counter to start of band */
964     k = cinfo->Ss;
965 
966     if (EOBRUN == 0) {
967       do {
968 	HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
969 	r = s >> 4;
970 	s &= 15;
971 	if (s) {
972 	  if (s != 1)		/* size of new coef should always be 1 */
973 	    WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
974 	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
975 	  if (GET_BITS(1))
976 	    s = p1;		/* newly nonzero coef is positive */
977 	  else
978 	    s = m1;		/* newly nonzero coef is negative */
979 	} else {
980 	  if (r != 15) {
981 	    EOBRUN = 1 << r;	/* EOBr, run length is 2^r + appended bits */
982 	    if (r) {
983 	      CHECK_BIT_BUFFER(br_state, r, goto undoit);
984 	      r = GET_BITS(r);
985 	      EOBRUN += r;
986 	    }
987 	    break;		/* rest of block is handled by EOB logic */
988 	  }
989 	  /* note s = 0 for processing ZRL */
990 	}
991 	/* Advance over already-nonzero coefs and r still-zero coefs,
992 	 * appending correction bits to the nonzeroes.  A correction bit is 1
993 	 * if the absolute value of the coefficient must be increased.
994 	 */
995 	do {
996 	  thiscoef = *block + natural_order[k];
997 	  if (*thiscoef) {
998 	    CHECK_BIT_BUFFER(br_state, 1, goto undoit);
999 	    if (GET_BITS(1)) {
1000 	      if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
1001 		if (*thiscoef >= 0)
1002 		  *thiscoef += p1;
1003 		else
1004 		  *thiscoef += m1;
1005 	      }
1006 	    }
1007 	  } else {
1008 	    if (--r < 0)
1009 	      break;		/* reached target zero coefficient */
1010 	  }
1011 	  k++;
1012 	} while (k <= Se);
1013 	if (s) {
1014 	  int pos = natural_order[k];
1015 	  /* Output newly nonzero coefficient */
1016 	  (*block)[pos] = (JCOEF) s;
1017 	  /* Remember its position in case we have to suspend */
1018 	  newnz_pos[num_newnz++] = pos;
1019 	}
1020 	k++;
1021       } while (k <= Se);
1022     }
1023 
1024     if (EOBRUN) {
1025       /* Scan any remaining coefficient positions after the end-of-band
1026        * (the last newly nonzero coefficient, if any).  Append a correction
1027        * bit to each already-nonzero coefficient.  A correction bit is 1
1028        * if the absolute value of the coefficient must be increased.
1029        */
1030       do {
1031 	thiscoef = *block + natural_order[k];
1032 	if (*thiscoef) {
1033 	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
1034 	  if (GET_BITS(1)) {
1035 	    if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
1036 	      if (*thiscoef >= 0)
1037 		*thiscoef += p1;
1038 	      else
1039 		*thiscoef += m1;
1040 	    }
1041 	  }
1042 	}
1043 	k++;
1044       } while (k <= Se);
1045       /* Count one block completed in EOB run */
1046       EOBRUN--;
1047     }
1048 
1049     /* Completed MCU, so update state */
1050     BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
1051     entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
1052   }
1053 
1054   /* Account for restart interval if using restarts */
1055   if (cinfo->restart_interval)
1056     entropy->restarts_to_go--;
1057 
1058   return TRUE;
1059 
1060 undoit:
1061   /* Re-zero any output coefficients that we made newly nonzero */
1062   while (num_newnz)
1063     (*block)[newnz_pos[--num_newnz]] = 0;
1064 
1065   return FALSE;
1066 }
1067 
1068 
1069 /*
1070  * Decode one MCU's worth of Huffman-compressed coefficients,
1071  * partial blocks.
1072  */
1073 
1074 METHODDEF(boolean)
decode_mcu_sub(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)1075 decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
1076 {
1077   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1078   const int * natural_order;
1079   int Se, blkn;
1080   BITREAD_STATE_VARS;
1081   savable_state state;
1082 
1083   /* Process restart marker if needed; may have to suspend */
1084   if (cinfo->restart_interval) {
1085     if (entropy->restarts_to_go == 0)
1086       if (! process_restart(cinfo))
1087 	return FALSE;
1088   }
1089 
1090   /* If we've run out of data, just leave the MCU set to zeroes.
1091    * This way, we return uniform gray for the remainder of the segment.
1092    */
1093   if (! entropy->insufficient_data) {
1094 
1095     natural_order = cinfo->natural_order;
1096     Se = cinfo->lim_Se;
1097 
1098     /* Load up working state */
1099     BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
1100     ASSIGN_STATE(state, entropy->saved);
1101 
1102     /* Outer loop handles each block in the MCU */
1103 
1104     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1105       JBLOCKROW block = MCU_data[blkn];
1106       d_derived_tbl * htbl;
1107       register int s, k, r;
1108       int coef_limit, ci;
1109 
1110       /* Decode a single block's worth of coefficients */
1111 
1112       /* Section F.2.2.1: decode the DC coefficient difference */
1113       htbl = entropy->dc_cur_tbls[blkn];
1114       HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
1115 
1116       htbl = entropy->ac_cur_tbls[blkn];
1117       k = 1;
1118       coef_limit = entropy->coef_limit[blkn];
1119       if (coef_limit) {
1120 	/* Convert DC difference to actual value, update last_dc_val */
1121 	if (s) {
1122 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
1123 	  r = GET_BITS(s);
1124 	  s = HUFF_EXTEND(r, s);
1125 	}
1126 	ci = cinfo->MCU_membership[blkn];
1127 	s += state.last_dc_val[ci];
1128 	state.last_dc_val[ci] = s;
1129 	/* Output the DC coefficient */
1130 	(*block)[0] = (JCOEF) s;
1131 
1132 	/* Section F.2.2.2: decode the AC coefficients */
1133 	/* Since zeroes are skipped, output area must be cleared beforehand */
1134 	for (; k < coef_limit; k++) {
1135 	  HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
1136 
1137 	  r = s >> 4;
1138 	  s &= 15;
1139 
1140 	  if (s) {
1141 	    k += r;
1142 	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
1143 	    r = GET_BITS(s);
1144 	    s = HUFF_EXTEND(r, s);
1145 	    /* Output coefficient in natural (dezigzagged) order.
1146 	     * Note: the extra entries in natural_order[] will save us
1147 	     * if k > Se, which could happen if the data is corrupted.
1148 	     */
1149 	    (*block)[natural_order[k]] = (JCOEF) s;
1150 	  } else {
1151 	    if (r != 15)
1152 	      goto EndOfBlock;
1153 	    k += 15;
1154 	  }
1155 	}
1156       } else {
1157 	if (s) {
1158 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
1159 	  DROP_BITS(s);
1160 	}
1161       }
1162 
1163       /* Section F.2.2.2: decode the AC coefficients */
1164       /* In this path we just discard the values */
1165       for (; k <= Se; k++) {
1166 	HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
1167 
1168 	r = s >> 4;
1169 	s &= 15;
1170 
1171 	if (s) {
1172 	  k += r;
1173 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
1174 	  DROP_BITS(s);
1175 	} else {
1176 	  if (r != 15)
1177 	    break;
1178 	  k += 15;
1179 	}
1180       }
1181 
1182       EndOfBlock: ;
1183     }
1184 
1185     /* Completed MCU, so update state */
1186     BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
1187     ASSIGN_STATE(entropy->saved, state);
1188   }
1189 
1190   /* Account for restart interval if using restarts */
1191   if (cinfo->restart_interval)
1192     entropy->restarts_to_go--;
1193 
1194   return TRUE;
1195 }
1196 
1197 
1198 /*
1199  * Decode one MCU's worth of Huffman-compressed coefficients,
1200  * full-size blocks.
1201  */
1202 
1203 METHODDEF(boolean)
decode_mcu(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)1204 decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
1205 {
1206   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1207   int blkn;
1208   BITREAD_STATE_VARS;
1209   savable_state state;
1210 
1211   /* Process restart marker if needed; may have to suspend */
1212   if (cinfo->restart_interval) {
1213     if (entropy->restarts_to_go == 0)
1214       if (! process_restart(cinfo))
1215 	return FALSE;
1216   }
1217 
1218   /* If we've run out of data, just leave the MCU set to zeroes.
1219    * This way, we return uniform gray for the remainder of the segment.
1220    */
1221   if (! entropy->insufficient_data) {
1222 
1223     /* Load up working state */
1224     BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
1225     ASSIGN_STATE(state, entropy->saved);
1226 
1227     /* Outer loop handles each block in the MCU */
1228 
1229     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1230       JBLOCKROW block = MCU_data[blkn];
1231       d_derived_tbl * htbl;
1232       register int s, k, r;
1233       int coef_limit, ci;
1234 
1235       /* Decode a single block's worth of coefficients */
1236 
1237       /* Section F.2.2.1: decode the DC coefficient difference */
1238       htbl = entropy->dc_cur_tbls[blkn];
1239       HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
1240 
1241       htbl = entropy->ac_cur_tbls[blkn];
1242       k = 1;
1243       coef_limit = entropy->coef_limit[blkn];
1244       if (coef_limit) {
1245 	/* Convert DC difference to actual value, update last_dc_val */
1246 	if (s) {
1247 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
1248 	  r = GET_BITS(s);
1249 	  s = HUFF_EXTEND(r, s);
1250 	}
1251 	ci = cinfo->MCU_membership[blkn];
1252 	s += state.last_dc_val[ci];
1253 	state.last_dc_val[ci] = s;
1254 	/* Output the DC coefficient */
1255 	(*block)[0] = (JCOEF) s;
1256 
1257 	/* Section F.2.2.2: decode the AC coefficients */
1258 	/* Since zeroes are skipped, output area must be cleared beforehand */
1259 	for (; k < coef_limit; k++) {
1260 	  HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
1261 
1262 	  r = s >> 4;
1263 	  s &= 15;
1264 
1265 	  if (s) {
1266 	    k += r;
1267 	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
1268 	    r = GET_BITS(s);
1269 	    s = HUFF_EXTEND(r, s);
1270 	    /* Output coefficient in natural (dezigzagged) order.
1271 	     * Note: the extra entries in jpeg_natural_order[] will save us
1272 	     * if k >= DCTSIZE2, which could happen if the data is corrupted.
1273 	     */
1274 	    (*block)[jpeg_natural_order[k]] = (JCOEF) s;
1275 	  } else {
1276 	    if (r != 15)
1277 	      goto EndOfBlock;
1278 	    k += 15;
1279 	  }
1280 	}
1281       } else {
1282 	if (s) {
1283 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
1284 	  DROP_BITS(s);
1285 	}
1286       }
1287 
1288       /* Section F.2.2.2: decode the AC coefficients */
1289       /* In this path we just discard the values */
1290       for (; k < DCTSIZE2; k++) {
1291 	HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
1292 
1293 	r = s >> 4;
1294 	s &= 15;
1295 
1296 	if (s) {
1297 	  k += r;
1298 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
1299 	  DROP_BITS(s);
1300 	} else {
1301 	  if (r != 15)
1302 	    break;
1303 	  k += 15;
1304 	}
1305       }
1306 
1307       EndOfBlock: ;
1308     }
1309 
1310     /* Completed MCU, so update state */
1311     BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
1312     ASSIGN_STATE(entropy->saved, state);
1313   }
1314 
1315   /* Account for restart interval if using restarts */
1316   if (cinfo->restart_interval)
1317     entropy->restarts_to_go--;
1318 
1319   return TRUE;
1320 }
1321 
1322 
1323 /*
1324  * Initialize for a Huffman-compressed scan.
1325  */
1326 
1327 METHODDEF(void)
start_pass_huff_decoder(j_decompress_ptr cinfo)1328 start_pass_huff_decoder (j_decompress_ptr cinfo)
1329 {
1330   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1331   int ci, blkn, tbl, i;
1332   jpeg_component_info * compptr;
1333 
1334   if (cinfo->progressive_mode) {
1335     /* Validate progressive scan parameters */
1336     if (cinfo->Ss == 0) {
1337       if (cinfo->Se != 0)
1338 	goto bad;
1339     } else {
1340       /* need not check Ss/Se < 0 since they came from unsigned bytes */
1341       if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)
1342 	goto bad;
1343       /* AC scans may have only one component */
1344       if (cinfo->comps_in_scan != 1)
1345 	goto bad;
1346     }
1347     if (cinfo->Ah != 0) {
1348       /* Successive approximation refinement scan: must have Al = Ah-1. */
1349       if (cinfo->Ah-1 != cinfo->Al)
1350 	goto bad;
1351     }
1352     if (cinfo->Al > 13) {	/* need not check for < 0 */
1353       /* Arguably the maximum Al value should be less than 13 for 8-bit
1354        * precision, but the spec doesn't say so, and we try to be liberal
1355        * about what we accept.  Note: large Al values could result in
1356        * out-of-range DC coefficients during early scans, leading to bizarre
1357        * displays due to overflows in the IDCT math.  But we won't crash.
1358        */
1359       bad:
1360       ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
1361 	       cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
1362     }
1363     /* Update progression status, and verify that scan order is legal.
1364      * Note that inter-scan inconsistencies are treated as warnings
1365      * not fatal errors ... not clear if this is right way to behave.
1366      */
1367     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1368       int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
1369       int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
1370       if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
1371 	WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
1372       for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
1373 	int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
1374 	if (cinfo->Ah != expected)
1375 	  WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
1376 	coef_bit_ptr[coefi] = cinfo->Al;
1377       }
1378     }
1379 
1380     /* Select MCU decoding routine */
1381     if (cinfo->Ah == 0) {
1382       if (cinfo->Ss == 0)
1383 	entropy->pub.decode_mcu = decode_mcu_DC_first;
1384       else
1385 	entropy->pub.decode_mcu = decode_mcu_AC_first;
1386     } else {
1387       if (cinfo->Ss == 0)
1388 	entropy->pub.decode_mcu = decode_mcu_DC_refine;
1389       else
1390 	entropy->pub.decode_mcu = decode_mcu_AC_refine;
1391     }
1392 
1393     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1394       compptr = cinfo->cur_comp_info[ci];
1395       /* Make sure requested tables are present, and compute derived tables.
1396        * We may build same derived table more than once, but it's not expensive.
1397        */
1398       if (cinfo->Ss == 0) {
1399 	if (cinfo->Ah == 0) {	/* DC refinement needs no table */
1400 	  tbl = compptr->dc_tbl_no;
1401 	  jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
1402 				  & entropy->derived_tbls[tbl]);
1403 	}
1404       } else {
1405 	tbl = compptr->ac_tbl_no;
1406 	jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
1407 				& entropy->derived_tbls[tbl]);
1408 	/* remember the single active table */
1409 	entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
1410       }
1411       /* Initialize DC predictions to 0 */
1412       entropy->saved.last_dc_val[ci] = 0;
1413     }
1414 
1415     /* Initialize private state variables */
1416     entropy->saved.EOBRUN = 0;
1417   } else {
1418     /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
1419      * This ought to be an error condition, but we make it a warning because
1420      * there are some baseline files out there with all zeroes in these bytes.
1421      */
1422     if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
1423 	((cinfo->is_baseline || cinfo->Se < DCTSIZE2) &&
1424 	cinfo->Se != cinfo->lim_Se))
1425       WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
1426 
1427     /* Select MCU decoding routine */
1428     /* We retain the hard-coded case for full-size blocks.
1429      * This is not necessary, but it appears that this version is slightly
1430      * more performant in the given implementation.
1431      * With an improved implementation we would prefer a single optimized
1432      * function.
1433      */
1434     if (cinfo->lim_Se != DCTSIZE2-1)
1435       entropy->pub.decode_mcu = decode_mcu_sub;
1436     else
1437       entropy->pub.decode_mcu = decode_mcu;
1438 
1439     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1440       compptr = cinfo->cur_comp_info[ci];
1441       /* Compute derived values for Huffman tables */
1442       /* We may do this more than once for a table, but it's not expensive */
1443       tbl = compptr->dc_tbl_no;
1444       jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
1445 			      & entropy->dc_derived_tbls[tbl]);
1446       if (cinfo->lim_Se) {	/* AC needs no table when not present */
1447 	tbl = compptr->ac_tbl_no;
1448 	jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
1449 				& entropy->ac_derived_tbls[tbl]);
1450       }
1451       /* Initialize DC predictions to 0 */
1452       entropy->saved.last_dc_val[ci] = 0;
1453     }
1454 
1455     /* Precalculate decoding info for each block in an MCU of this scan */
1456     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1457       ci = cinfo->MCU_membership[blkn];
1458       compptr = cinfo->cur_comp_info[ci];
1459       /* Precalculate which table to use for each block */
1460       entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
1461       entropy->ac_cur_tbls[blkn] =	/* AC needs no table when not present */
1462 	cinfo->lim_Se ? entropy->ac_derived_tbls[compptr->ac_tbl_no] : NULL;
1463       /* Decide whether we really care about the coefficient values */
1464       if (compptr->component_needed) {
1465 	ci = compptr->DCT_v_scaled_size;
1466 	i = compptr->DCT_h_scaled_size;
1467 	switch (cinfo->lim_Se) {
1468 	case (1*1-1):
1469 	  entropy->coef_limit[blkn] = 1;
1470 	  break;
1471 	case (2*2-1):
1472 	  if (ci <= 0 || ci > 2) ci = 2;
1473 	  if (i <= 0 || i > 2) i = 2;
1474 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1];
1475 	  break;
1476 	case (3*3-1):
1477 	  if (ci <= 0 || ci > 3) ci = 3;
1478 	  if (i <= 0 || i > 3) i = 3;
1479 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1];
1480 	  break;
1481 	case (4*4-1):
1482 	  if (ci <= 0 || ci > 4) ci = 4;
1483 	  if (i <= 0 || i > 4) i = 4;
1484 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1];
1485 	  break;
1486 	case (5*5-1):
1487 	  if (ci <= 0 || ci > 5) ci = 5;
1488 	  if (i <= 0 || i > 5) i = 5;
1489 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1];
1490 	  break;
1491 	case (6*6-1):
1492 	  if (ci <= 0 || ci > 6) ci = 6;
1493 	  if (i <= 0 || i > 6) i = 6;
1494 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1];
1495 	  break;
1496 	case (7*7-1):
1497 	  if (ci <= 0 || ci > 7) ci = 7;
1498 	  if (i <= 0 || i > 7) i = 7;
1499 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1];
1500 	  break;
1501 	default:
1502 	  if (ci <= 0 || ci > 8) ci = 8;
1503 	  if (i <= 0 || i > 8) i = 8;
1504 	  entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
1505 	}
1506       } else {
1507 	entropy->coef_limit[blkn] = 0;
1508       }
1509     }
1510   }
1511 
1512   /* Initialize bitread state variables */
1513   entropy->bitstate.bits_left = 0;
1514   entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
1515   entropy->insufficient_data = FALSE;
1516 
1517   /* Initialize restart counter */
1518   entropy->restarts_to_go = cinfo->restart_interval;
1519 }
1520 
1521 
1522 /*
1523  * Module initialization routine for Huffman entropy decoding.
1524  */
1525 
1526 GLOBAL(void)
jinit_huff_decoder(j_decompress_ptr cinfo)1527 jinit_huff_decoder (j_decompress_ptr cinfo)
1528 {
1529   huff_entropy_ptr entropy;
1530   int i;
1531 
1532   entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small)
1533     ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_decoder));
1534   cinfo->entropy = &entropy->pub;
1535   entropy->pub.start_pass = start_pass_huff_decoder;
1536   entropy->pub.finish_pass = finish_pass_huff;
1537 
1538   if (cinfo->progressive_mode) {
1539     /* Create progression status table */
1540     int *coef_bit_ptr, ci;
1541     cinfo->coef_bits = (int (*)[DCTSIZE2]) (*cinfo->mem->alloc_small)
1542       ((j_common_ptr) cinfo, JPOOL_IMAGE,
1543        cinfo->num_components * DCTSIZE2 * SIZEOF(int));
1544     coef_bit_ptr = & cinfo->coef_bits[0][0];
1545     for (ci = 0; ci < cinfo->num_components; ci++)
1546       for (i = 0; i < DCTSIZE2; i++)
1547 	*coef_bit_ptr++ = -1;
1548 
1549     /* Mark derived tables unallocated */
1550     for (i = 0; i < NUM_HUFF_TBLS; i++) {
1551       entropy->derived_tbls[i] = NULL;
1552     }
1553   } else {
1554     /* Mark derived tables unallocated */
1555     for (i = 0; i < NUM_HUFF_TBLS; i++) {
1556       entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1557     }
1558   }
1559 }
1560