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