Home | History | Annotate | Download | only in jpeg
      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)
     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)
    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)
    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   j_decompress_ptr cinfo = state->cinfo;
    299   if (cinfo->tile_decode &&
    300       cinfo->restart_interval == 0 &&
    301       cinfo->unread_marker >= 0xd0 &&
    302       cinfo->unread_marker <= 0xd7 &&
    303       nbits > bits_left
    304       ) {
    305       // Skip the restart marker.
    306     cinfo->marker->next_restart_num = cinfo->unread_marker - 0xd0;
    307     process_restart(cinfo);
    308   }
    309   /* Copy heavily used state fields into locals (hopefully registers) */
    310   register const JOCTET * next_input_byte = state->next_input_byte;
    311   register size_t bytes_in_buffer = state->bytes_in_buffer;
    312 
    313   /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
    314   /* (It is assumed that no request will be for more than that many bits.) */
    315   /* We fail to do so only if we hit a marker or are forced to suspend. */
    316 
    317   if (cinfo->unread_marker == 0) {	/* cannot advance past a marker */
    318     while (bits_left < MIN_GET_BITS) {
    319       register int c;
    320 
    321       /* Attempt to read a byte */
    322       if (bytes_in_buffer == 0) {
    323 	if (! (*cinfo->src->fill_input_buffer) (cinfo))
    324 	  return FALSE;
    325 	next_input_byte = cinfo->src->next_input_byte;
    326 	bytes_in_buffer = cinfo->src->bytes_in_buffer;
    327       }
    328       bytes_in_buffer--;
    329       c = GETJOCTET(*next_input_byte++);
    330 
    331       /* If it's 0xFF, check and discard stuffed zero byte */
    332       if (c == 0xFF) {
    333 	/* Loop here to discard any padding FF's on terminating marker,
    334 	 * so that we can save a valid unread_marker value.  NOTE: we will
    335 	 * accept multiple FF's followed by a 0 as meaning a single FF data
    336 	 * byte.  This data pattern is not valid according to the standard.
    337 	 */
    338 	do {
    339 	  if (bytes_in_buffer == 0) {
    340 	    if (! (*cinfo->src->fill_input_buffer) (cinfo))
    341 	      return FALSE;
    342 	    next_input_byte = cinfo->src->next_input_byte;
    343 	    bytes_in_buffer = cinfo->src->bytes_in_buffer;
    344 	  }
    345 	  bytes_in_buffer--;
    346 	  c = GETJOCTET(*next_input_byte++);
    347 	} while (c == 0xFF);
    348 
    349 	if (c == 0) {
    350 	  /* Found FF/00, which represents an FF data byte */
    351 	  c = 0xFF;
    352 	} else {
    353 	  /* Oops, it's actually a marker indicating end of compressed data.
    354 	   * Save the marker code for later use.
    355 	   * Fine point: it might appear that we should save the marker into
    356 	   * bitread working state, not straight into permanent state.  But
    357 	   * once we have hit a marker, we cannot need to suspend within the
    358 	   * current MCU, because we will read no more bytes from the data
    359 	   * source.  So it is OK to update permanent state right away.
    360 	   */
    361 	  cinfo->unread_marker = c;
    362 	  /* See if we need to insert some fake zero bits. */
    363 	  goto no_more_bytes;
    364 	}
    365       }
    366 
    367       /* OK, load c into get_buffer */
    368       get_buffer = (get_buffer << 8) | c;
    369       bits_left += 8;
    370     } /* end while */
    371   } else {
    372   no_more_bytes:
    373     /* We get here if we've read the marker that terminates the compressed
    374      * data segment.  There should be enough bits in the buffer register
    375      * to satisfy the request; if so, no problem.
    376      */
    377     if (nbits > bits_left) {
    378       /* Uh-oh.  Report corrupted data to user and stuff zeroes into
    379        * the data stream, so that we can produce some kind of image.
    380        * We use a nonvolatile flag to ensure that only one warning message
    381        * appears per data segment.
    382        */
    383       if (! cinfo->entropy->insufficient_data) {
    384 	WARNMS(cinfo, JWRN_HIT_MARKER);
    385 	cinfo->entropy->insufficient_data = TRUE;
    386       }
    387       /* Fill the buffer with zero bits */
    388       get_buffer <<= MIN_GET_BITS - bits_left;
    389       bits_left = MIN_GET_BITS;
    390     }
    391   }
    392 
    393   /* Unload the local registers */
    394   state->next_input_byte = next_input_byte;
    395   state->bytes_in_buffer = bytes_in_buffer;
    396   state->get_buffer = get_buffer;
    397   state->bits_left = bits_left;
    398 
    399   return TRUE;
    400 }
    401 
    402 
    403 /*
    404  * Out-of-line code for Huffman code decoding.
    405  * See jdhuff.h for info about usage.
    406  */
    407 
    408 GLOBAL(int)
    409 jpeg_huff_decode (bitread_working_state * state,
    410 		  register bit_buf_type get_buffer, register int bits_left,
    411 		  d_derived_tbl * htbl, int min_bits)
    412 {
    413   register int l = min_bits;
    414   register INT32 code;
    415 
    416   /* HUFF_DECODE has determined that the code is at least min_bits */
    417   /* bits long, so fetch that many bits in one swoop. */
    418 
    419   CHECK_BIT_BUFFER(*state, l, return -1);
    420   code = GET_BITS(l);
    421 
    422   /* Collect the rest of the Huffman code one bit at a time. */
    423   /* This is per Figure F.16 in the JPEG spec. */
    424 
    425   while (code > htbl->maxcode[l]) {
    426     code <<= 1;
    427     CHECK_BIT_BUFFER(*state, 1, return -1);
    428     code |= GET_BITS(1);
    429     l++;
    430   }
    431 
    432   /* Unload the local registers */
    433   state->get_buffer = get_buffer;
    434   state->bits_left = bits_left;
    435 
    436   /* With garbage input we may reach the sentinel value l = 17. */
    437 
    438   if (l > 16) {
    439     WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
    440     return 0;			/* fake a zero as the safest result */
    441   }
    442 
    443   return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
    444 }
    445 
    446 
    447 /*
    448  * Figure F.12: extend sign bit.
    449  * On some machines, a shift and add will be faster than a table lookup.
    450  */
    451 
    452 #ifdef AVOID_TABLES
    453 
    454 #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
    455 
    456 #else
    457 
    458 #define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
    459 
    460 static const int extend_test[16] =   /* entry n is 2**(n-1) */
    461   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
    462     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
    463 
    464 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
    465   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
    466     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
    467     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
    468     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
    469 
    470 #endif /* AVOID_TABLES */
    471 
    472 
    473 /*
    474  * Check for a restart marker & resynchronize decoder.
    475  * Returns FALSE if must suspend.
    476  */
    477 
    478 LOCAL(boolean)
    479 process_restart (j_decompress_ptr cinfo)
    480 {
    481   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    482   int ci;
    483 
    484   /* Throw away any unused bits remaining in bit buffer; */
    485   /* include any full bytes in next_marker's count of discarded bytes */
    486   cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
    487   entropy->bitstate.bits_left = 0;
    488 
    489   /* Advance past the RSTn marker */
    490   if (! (*cinfo->marker->read_restart_marker) (cinfo))
    491     return FALSE;
    492 
    493   /* Re-initialize DC predictions to 0 */
    494   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
    495     entropy->saved.last_dc_val[ci] = 0;
    496 
    497   /* Reset restart counter */
    498   entropy->restarts_to_go = cinfo->restart_interval;
    499 
    500   /* Reset out-of-data flag, unless read_restart_marker left us smack up
    501    * against a marker.  In that case we will end up treating the next data
    502    * segment as empty, and we can avoid producing bogus output pixels by
    503    * leaving the flag set.
    504    */
    505   if (cinfo->unread_marker == 0)
    506     entropy->pub.insufficient_data = FALSE;
    507 
    508   return TRUE;
    509 }
    510 
    511 /*
    512  * Configure the Huffman decoder reader position and bit buffer.
    513  */
    514 GLOBAL(void)
    515 jpeg_configure_huffman_decoder(j_decompress_ptr cinfo,
    516         huffman_offset_data offset)
    517 {
    518   unsigned int bitstream_offset = offset.bitstream_offset;
    519   int blkn, i;
    520 
    521   cinfo->restart_interval = 0;
    522   cinfo->unread_marker = 0;
    523 
    524   unsigned int byte_offset = bitstream_offset >> LOG_TWO_BIT_BUF_SIZE;
    525   unsigned int bit_in_bit_buffer =
    526       bitstream_offset & ((1 << LOG_TWO_BIT_BUF_SIZE) - 1);
    527 
    528   jset_input_stream_position_bit(cinfo, byte_offset,
    529           bit_in_bit_buffer, offset.get_buffer);
    530 }
    531 
    532 /*
    533  * Save the current Huffman decoder position and the bit buffer
    534  * into bitstream_offset and get_buffer, respectively.
    535  */
    536 GLOBAL(void)
    537 jpeg_get_huffman_decoder_configuration(j_decompress_ptr cinfo,
    538         huffman_offset_data *offset)
    539 {
    540   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    541 
    542   if (cinfo->restart_interval) {
    543     // We are at the end of a data segment
    544     if (entropy->restarts_to_go == 0)
    545       if (! process_restart(cinfo))
    546 	return;
    547   }
    548 
    549   offset->bitstream_offset =
    550       (jget_input_stream_position(cinfo) << LOG_TWO_BIT_BUF_SIZE)
    551       + entropy->bitstate.bits_left;
    552 
    553   offset->get_buffer = entropy->bitstate.get_buffer;
    554 }
    555 
    556 /*
    557  * Configure the Huffman decoder to decode the image
    558  * starting from the bitstream position recorded in offset.
    559  */
    560 METHODDEF(void)
    561 configure_huffman_decoder(j_decompress_ptr cinfo, huffman_offset_data offset)
    562 {
    563   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    564   short int *dc_info = offset.prev_dc;
    565   int i;
    566   jpeg_configure_huffman_decoder(cinfo, offset);
    567   for (i = 0; i < cinfo->comps_in_scan; i++) {
    568     entropy->saved.last_dc_val[i] = dc_info[i];
    569   }
    570 }
    571 
    572 /*
    573  * Save the current Huffman deocde position and the DC coefficients
    574  * for each component into bitstream_offset and dc_info[], respectively.
    575  */
    576 METHODDEF(void)
    577 get_huffman_decoder_configuration(j_decompress_ptr cinfo,
    578         huffman_offset_data *offset)
    579 {
    580   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    581   short int *dc_info = offset->prev_dc;
    582   int i;
    583   jpeg_get_huffman_decoder_configuration(cinfo, offset);
    584   for (i = 0; i < cinfo->comps_in_scan; i++) {
    585     dc_info[i] = entropy->saved.last_dc_val[i];
    586   }
    587 }
    588 
    589 /*
    590  * Decode and return one MCU's worth of Huffman-compressed coefficients.
    591  * The coefficients are reordered from zigzag order into natural array order,
    592  * but are not dequantized.
    593  *
    594  * The i'th block of the MCU is stored into the block pointed to by
    595  * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
    596  * (Wholesale zeroing is usually a little faster than retail...)
    597  *
    598  * Returns FALSE if data source requested suspension.  In that case no
    599  * changes have been made to permanent state.  (Exception: some output
    600  * coefficients may already have been assigned.  This is harmless for
    601  * this module, since we'll just re-assign them on the next call.)
    602  */
    603 
    604 METHODDEF(boolean)
    605 decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
    606 {
    607   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    608   int blkn;
    609   BITREAD_STATE_VARS;
    610   savable_state state;
    611 
    612   /* Process restart marker if needed; may have to suspend */
    613   if (cinfo->restart_interval) {
    614     if (entropy->restarts_to_go == 0)
    615       if (! process_restart(cinfo))
    616 	return FALSE;
    617   }
    618 
    619   /* If we've run out of data, just leave the MCU set to zeroes.
    620    * This way, we return uniform gray for the remainder of the segment.
    621    */
    622   if (! entropy->pub.insufficient_data) {
    623     /* Load up working state */
    624     BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
    625     ASSIGN_STATE(state, entropy->saved);
    626 
    627     /* Outer loop handles each block in the MCU */
    628 
    629     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
    630       JBLOCKROW block = MCU_data[blkn];
    631       d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
    632       d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
    633       register int s, k, r;
    634 
    635       /* Decode a single block's worth of coefficients */
    636 
    637       /* Section F.2.2.1: decode the DC coefficient difference */
    638       HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
    639       if (s) {
    640 	CHECK_BIT_BUFFER(br_state, s, return FALSE);
    641 	r = GET_BITS(s);
    642 	s = HUFF_EXTEND(r, s);
    643       }
    644 
    645       if (entropy->dc_needed[blkn]) {
    646 	/* Convert DC difference to actual value, update last_dc_val */
    647 	int ci = cinfo->MCU_membership[blkn];
    648 	s += state.last_dc_val[ci];
    649 	state.last_dc_val[ci] = s;
    650 	/* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
    651 	(*block)[0] = (JCOEF) s;
    652       }
    653 
    654       if (entropy->ac_needed[blkn]) {
    655 
    656 	/* Section F.2.2.2: decode the AC coefficients */
    657 	/* Since zeroes are skipped, output area must be cleared beforehand */
    658 	for (k = 1; k < DCTSIZE2; k++) {
    659 	  HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
    660 
    661 	  r = s >> 4;
    662 	  s &= 15;
    663 
    664 	  if (s) {
    665 	    k += r;
    666 	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
    667 	    r = GET_BITS(s);
    668 	    s = HUFF_EXTEND(r, s);
    669 	    /* Output coefficient in natural (dezigzagged) order.
    670 	     * Note: the extra entries in jpeg_natural_order[] will save us
    671 	     * if k >= DCTSIZE2, which could happen if the data is corrupted.
    672 	     */
    673 	    (*block)[jpeg_natural_order[k]] = (JCOEF) s;
    674 	  } else {
    675 	    if (r != 15)
    676 	      break;
    677 	    k += 15;
    678 	  }
    679 	}
    680 
    681       } else {
    682 
    683 	/* Section F.2.2.2: decode the AC coefficients */
    684 	/* In this path we just discard the values */
    685 	for (k = 1; k < DCTSIZE2; k++) {
    686 	  HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
    687 
    688 	  r = s >> 4;
    689 	  s &= 15;
    690 
    691 	  if (s) {
    692 	    k += r;
    693 	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
    694 	    DROP_BITS(s);
    695 	  } else {
    696 	    if (r != 15)
    697 	      break;
    698 	    k += 15;
    699 	  }
    700 	}
    701 
    702       }
    703     }
    704 
    705     /* Completed MCU, so update state */
    706     BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
    707     ASSIGN_STATE(entropy->saved, state);
    708   }
    709 
    710   /* Account for restart interval (no-op if not using restarts) */
    711   entropy->restarts_to_go--;
    712 
    713   return TRUE;
    714 }
    715 
    716 /*
    717  * Decode one MCU's worth of Huffman-compressed coefficients.
    718  * The propose of this method is to calculate the
    719  * data length of one MCU in Huffman-coded format.
    720  * Therefore, all coefficients are discarded.
    721  */
    722 
    723 METHODDEF(boolean)
    724 decode_mcu_discard_coef (j_decompress_ptr cinfo)
    725 {
    726   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    727   int blkn;
    728   BITREAD_STATE_VARS;
    729   savable_state state;
    730 
    731   /* Process restart marker if needed; may have to suspend */
    732   if (cinfo->restart_interval) {
    733     if (entropy->restarts_to_go == 0)
    734       if (! process_restart(cinfo))
    735 	return FALSE;
    736   }
    737 
    738   if (! entropy->pub.insufficient_data) {
    739 
    740     /* Load up working state */
    741     BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
    742     ASSIGN_STATE(state, entropy->saved);
    743 
    744     /* Outer loop handles each block in the MCU */
    745 
    746     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
    747       d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
    748       d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
    749       register int s, k, r;
    750 
    751       /* Decode a single block's worth of coefficients */
    752 
    753       /* Section F.2.2.1: decode the DC coefficient difference */
    754       HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
    755       if (s) {
    756 	CHECK_BIT_BUFFER(br_state, s, return FALSE);
    757 	r = GET_BITS(s);
    758 	s = HUFF_EXTEND(r, s);
    759       }
    760 
    761       /* discard all coefficients */
    762       if (entropy->dc_needed[blkn]) {
    763 	/* Convert DC difference to actual value, update last_dc_val */
    764 	int ci = cinfo->MCU_membership[blkn];
    765 	s += state.last_dc_val[ci];
    766 	state.last_dc_val[ci] = s;
    767       }
    768       for (k = 1; k < DCTSIZE2; k++) {
    769         HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
    770 
    771         r = s >> 4;
    772         s &= 15;
    773 
    774         if (s) {
    775           k += r;
    776           CHECK_BIT_BUFFER(br_state, s, return FALSE);
    777           DROP_BITS(s);
    778         } else {
    779           if (r != 15)
    780             break;
    781           k += 15;
    782         }
    783       }
    784     }
    785 
    786     /* Completed MCU, so update state */
    787     BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
    788     ASSIGN_STATE(entropy->saved, state);
    789   }
    790 
    791   /* Account for restart interval (no-op if not using restarts) */
    792   entropy->restarts_to_go--;
    793 
    794   return TRUE;
    795 }
    796 
    797 
    798 /*
    799  * Module initialization routine for Huffman entropy decoding.
    800  */
    801 
    802 GLOBAL(void)
    803 jinit_huff_decoder (j_decompress_ptr cinfo)
    804 {
    805   huff_entropy_ptr entropy;
    806   int i;
    807 
    808   entropy = (huff_entropy_ptr)
    809     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
    810 				SIZEOF(huff_entropy_decoder));
    811   cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
    812   entropy->pub.start_pass = start_pass_huff_decoder;
    813   entropy->pub.decode_mcu = decode_mcu;
    814   entropy->pub.decode_mcu_discard_coef = decode_mcu_discard_coef;
    815   entropy->pub.configure_huffman_decoder = configure_huffman_decoder;
    816   entropy->pub.get_huffman_decoder_configuration =
    817         get_huffman_decoder_configuration;
    818   entropy->pub.index = NULL;
    819 
    820   /* Mark tables unallocated */
    821   for (i = 0; i < NUM_HUFF_TBLS; i++) {
    822     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
    823   }
    824 }
    825 
    826 /*
    827  * Call after jpeg_read_header
    828  */
    829 GLOBAL(void)
    830 jpeg_create_huffman_index(j_decompress_ptr cinfo, huffman_index *index)
    831 {
    832   int i, s;
    833   index->scan_count = 1;
    834   index->total_iMCU_rows = cinfo->total_iMCU_rows;
    835   index->scan = (huffman_scan_header*)malloc(index->scan_count
    836           * sizeof(huffman_scan_header));
    837   index->scan[0].offset = (huffman_offset_data**)malloc(cinfo->total_iMCU_rows
    838           * sizeof(huffman_offset_data*));
    839   index->scan[0].prev_MCU_offset.bitstream_offset = 0;
    840   index->MCU_sample_size = DEFAULT_MCU_SAMPLE_SIZE;
    841 
    842   index->mem_used = sizeof(huffman_scan_header)
    843       + cinfo->total_iMCU_rows * sizeof(huffman_offset_data*);
    844 }
    845 
    846 GLOBAL(void)
    847 jpeg_destroy_huffman_index(huffman_index *index)
    848 {
    849     int i, j;
    850     for (i = 0; i < index->scan_count; i++) {
    851         for(j = 0; j < index->total_iMCU_rows; j++) {
    852             free(index->scan[i].offset[j]);
    853         }
    854         free(index->scan[i].offset);
    855     }
    856     free(index->scan);
    857 }
    858 
    859 /*
    860  * Set the reader byte position to offset
    861  */
    862 GLOBAL(void)
    863 jset_input_stream_position(j_decompress_ptr cinfo, int offset)
    864 {
    865   if (cinfo->src->seek_input_data) {
    866     cinfo->src->seek_input_data(cinfo, offset);
    867   } else {
    868     cinfo->src->bytes_in_buffer = cinfo->src->current_offset - offset;
    869     cinfo->src->next_input_byte = cinfo->src->start_input_byte + offset;
    870   }
    871 }
    872 
    873 /*
    874  * Set the reader byte position to offset and bit position to bit_left
    875  * with bit buffer set to buf.
    876  */
    877 GLOBAL(void)
    878 jset_input_stream_position_bit(j_decompress_ptr cinfo,
    879         int byte_offset, int bit_left, INT32 buf)
    880 {
    881   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    882 
    883   entropy->bitstate.bits_left = bit_left;
    884   entropy->bitstate.get_buffer = buf;
    885 
    886   jset_input_stream_position(cinfo, byte_offset);
    887 }
    888 
    889 /*
    890  * Get the current reader byte position.
    891  */
    892 GLOBAL(int)
    893 jget_input_stream_position(j_decompress_ptr cinfo)
    894 {
    895   return cinfo->src->current_offset - cinfo->src->bytes_in_buffer;
    896 }
    897