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