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