Home | History | Annotate | Download | only in jpeg
      1 /*
      2  * jdphuff.c
      3  *
      4  * Copyright (C) 1995-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 for progressive JPEG.
      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 jdhuff.c */
     21 
     22 
     23 #ifdef D_PROGRESSIVE_SUPPORTED
     24 
     25 /*
     26  * Expanded entropy decoder object for progressive 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   unsigned int EOBRUN;			/* remaining EOBs in EOBRUN */
     34   int last_dc_val[MAX_COMPS_IN_SCAN];	/* last DC coef for each component */
     35 } savable_state;
     36 
     37 /* This macro is to work around compilers with missing or broken
     38  * structure assignment.  You'll need to fix this code if you have
     39  * such a compiler and you change MAX_COMPS_IN_SCAN.
     40  */
     41 
     42 #ifndef NO_STRUCT_ASSIGN
     43 #define ASSIGN_STATE(dest,src)  ((dest) = (src))
     44 #else
     45 #if MAX_COMPS_IN_SCAN == 4
     46 #define ASSIGN_STATE(dest,src)  \
     47 	((dest).EOBRUN = (src).EOBRUN, \
     48 	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
     49 	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
     50 	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
     51 	 (dest).last_dc_val[3] = (src).last_dc_val[3])
     52 #endif
     53 #endif
     54 
     55 
     56 typedef struct {
     57   struct jpeg_entropy_decoder pub; /* public fields */
     58 
     59   /* These fields are loaded into local variables at start of each MCU.
     60    * In case of suspension, we exit WITHOUT updating them.
     61    */
     62   bitread_perm_state bitstate;	/* Bit buffer at start of MCU */
     63   savable_state saved;		/* Other state at start of MCU */
     64 
     65   /* These fields are NOT loaded into local working state. */
     66   unsigned int restarts_to_go;	/* MCUs left in this restart interval */
     67 
     68   /* Pointers to derived tables (these workspaces have image lifespan) */
     69   d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
     70 
     71   d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
     72 } phuff_entropy_decoder;
     73 
     74 typedef phuff_entropy_decoder * phuff_entropy_ptr;
     75 
     76 /* Forward declarations */
     77 METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
     78 					    JBLOCKROW *MCU_data));
     79 METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
     80 					    JBLOCKROW *MCU_data));
     81 METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
     82 					     JBLOCKROW *MCU_data));
     83 METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
     84 					     JBLOCKROW *MCU_data));
     85 
     86 /*
     87  * Initialize for a Huffman-compressed scan.
     88  */
     89 
     90 METHODDEF(void)
     91 start_pass_phuff_decoder (j_decompress_ptr cinfo)
     92 {
     93   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
     94   boolean is_DC_band, bad;
     95   int ci, coefi, tbl;
     96   int *coef_bit_ptr;
     97   jpeg_component_info * compptr;
     98 
     99   is_DC_band = (cinfo->Ss == 0);
    100 
    101   /* Validate scan parameters */
    102   bad = FALSE;
    103   if (is_DC_band) {
    104     if (cinfo->Se != 0)
    105       bad = TRUE;
    106   } else {
    107     /* need not check Ss/Se < 0 since they came from unsigned bytes */
    108     if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
    109       bad = TRUE;
    110     /* AC scans may have only one component */
    111     if (cinfo->comps_in_scan != 1)
    112       bad = TRUE;
    113   }
    114   if (cinfo->Ah != 0) {
    115     /* Successive approximation refinement scan: must have Al = Ah-1. */
    116     if (cinfo->Al != cinfo->Ah-1)
    117       bad = TRUE;
    118   }
    119   if (cinfo->Al > 13)		/* need not check for < 0 */
    120     bad = TRUE;
    121   /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
    122    * but the spec doesn't say so, and we try to be liberal about what we
    123    * accept.  Note: large Al values could result in out-of-range DC
    124    * coefficients during early scans, leading to bizarre displays due to
    125    * overflows in the IDCT math.  But we won't crash.
    126    */
    127   if (bad)
    128     ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
    129 	     cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
    130   /* Update progression status, and verify that scan order is legal.
    131    * Note that inter-scan inconsistencies are treated as warnings
    132    * not fatal errors ... not clear if this is right way to behave.
    133    */
    134   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
    135     int cindex = cinfo->cur_comp_info[ci]->component_index;
    136     coef_bit_ptr = & cinfo->coef_bits[cindex][0];
    137     if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
    138       WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
    139     for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
    140       int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
    141       if (cinfo->Ah != expected)
    142 	WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
    143       coef_bit_ptr[coefi] = cinfo->Al;
    144     }
    145   }
    146 
    147   /* Select MCU decoding routine */
    148   if (cinfo->Ah == 0) {
    149     if (is_DC_band)
    150       entropy->pub.decode_mcu = decode_mcu_DC_first;
    151     else
    152       entropy->pub.decode_mcu = decode_mcu_AC_first;
    153   } else {
    154     if (is_DC_band)
    155       entropy->pub.decode_mcu = decode_mcu_DC_refine;
    156     else
    157       entropy->pub.decode_mcu = decode_mcu_AC_refine;
    158   }
    159 
    160   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
    161     compptr = cinfo->cur_comp_info[ci];
    162     /* Make sure requested tables are present, and compute derived tables.
    163      * We may build same derived table more than once, but it's not expensive.
    164      */
    165     if (is_DC_band) {
    166       if (cinfo->Ah == 0) {	/* DC refinement needs no table */
    167 	tbl = compptr->dc_tbl_no;
    168 	jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
    169 				& entropy->derived_tbls[tbl]);
    170       }
    171     } else {
    172       tbl = compptr->ac_tbl_no;
    173       jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
    174 			      & entropy->derived_tbls[tbl]);
    175       /* remember the single active table */
    176       entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
    177     }
    178     /* Initialize DC predictions to 0 */
    179     entropy->saved.last_dc_val[ci] = 0;
    180   }
    181 
    182   /* Initialize bitread state variables */
    183   entropy->bitstate.bits_left = 0;
    184   entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
    185   entropy->pub.insufficient_data = FALSE;
    186 
    187   /* Initialize private state variables */
    188   entropy->saved.EOBRUN = 0;
    189 
    190   /* Initialize restart counter */
    191   entropy->restarts_to_go = cinfo->restart_interval;
    192 }
    193 
    194 
    195 /*
    196  * Figure F.12: extend sign bit.
    197  * On some machines, a shift and add will be faster than a table lookup.
    198  */
    199 
    200 #ifdef AVOID_TABLES
    201 
    202 #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
    203 
    204 #else
    205 
    206 #define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
    207 
    208 static const int extend_test[16] =   /* entry n is 2**(n-1) */
    209   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
    210     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
    211 
    212 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
    213   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
    214     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
    215     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
    216     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
    217 
    218 #endif /* AVOID_TABLES */
    219 
    220 
    221 /*
    222  * Check for a restart marker & resynchronize decoder.
    223  * Returns FALSE if must suspend.
    224  */
    225 
    226 LOCAL(boolean)
    227 process_restart (j_decompress_ptr cinfo)
    228 {
    229   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    230   int ci;
    231 
    232   /* Throw away any unused bits remaining in bit buffer; */
    233   /* include any full bytes in next_marker's count of discarded bytes */
    234   cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
    235   entropy->bitstate.bits_left = 0;
    236 
    237   /* Advance past the RSTn marker */
    238   if (! (*cinfo->marker->read_restart_marker) (cinfo))
    239     return FALSE;
    240 
    241   /* Re-initialize DC predictions to 0 */
    242   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
    243     entropy->saved.last_dc_val[ci] = 0;
    244   /* Re-init EOB run count, too */
    245   entropy->saved.EOBRUN = 0;
    246 
    247   /* Reset restart counter */
    248   entropy->restarts_to_go = cinfo->restart_interval;
    249 
    250   /* Reset out-of-data flag, unless read_restart_marker left us smack up
    251    * against a marker.  In that case we will end up treating the next data
    252    * segment as empty, and we can avoid producing bogus output pixels by
    253    * leaving the flag set.
    254    */
    255   if (cinfo->unread_marker == 0)
    256     entropy->pub.insufficient_data = FALSE;
    257 
    258   return TRUE;
    259 }
    260 
    261 
    262 /*
    263  * Huffman MCU decoding.
    264  * Each of these routines decodes and returns one MCU's worth of
    265  * Huffman-compressed coefficients.
    266  * The coefficients are reordered from zigzag order into natural array order,
    267  * but are not dequantized.
    268  *
    269  * The i'th block of the MCU is stored into the block pointed to by
    270  * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
    271  *
    272  * We return FALSE if data source requested suspension.  In that case no
    273  * changes have been made to permanent state.  (Exception: some output
    274  * coefficients may already have been assigned.  This is harmless for
    275  * spectral selection, since we'll just re-assign them on the next call.
    276  * Successive approximation AC refinement has to be more careful, however.)
    277  */
    278 
    279 /*
    280  * MCU decoding for DC initial scan (either spectral selection,
    281  * or first pass of successive approximation).
    282  */
    283 
    284 METHODDEF(boolean)
    285 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
    286 {
    287   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    288   int Al = cinfo->Al;
    289   register int s, r;
    290   int blkn, ci;
    291   JBLOCKROW block;
    292   BITREAD_STATE_VARS;
    293   savable_state state;
    294   d_derived_tbl * tbl;
    295   jpeg_component_info * compptr;
    296 
    297   /* Process restart marker if needed; may have to suspend */
    298   if (cinfo->restart_interval) {
    299     if (entropy->restarts_to_go == 0)
    300       if (! process_restart(cinfo))
    301 	return FALSE;
    302   }
    303 
    304   /* If we've run out of data, just leave the MCU set to zeroes.
    305    * This way, we return uniform gray for the remainder of the segment.
    306    */
    307   if (! entropy->pub.insufficient_data) {
    308 
    309     /* Load up working state */
    310     BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
    311     ASSIGN_STATE(state, entropy->saved);
    312 
    313     /* Outer loop handles each block in the MCU */
    314 
    315     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
    316       block = MCU_data[blkn];
    317       ci = cinfo->MCU_membership[blkn];
    318       compptr = cinfo->cur_comp_info[ci];
    319       tbl = entropy->derived_tbls[compptr->dc_tbl_no];
    320 
    321       /* Decode a single block's worth of coefficients */
    322 
    323       /* Section F.2.2.1: decode the DC coefficient difference */
    324       HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
    325       if (s) {
    326 	CHECK_BIT_BUFFER(br_state, s, return FALSE);
    327 	r = GET_BITS(s);
    328 	s = HUFF_EXTEND(r, s);
    329       }
    330 
    331       /* Convert DC difference to actual value, update last_dc_val */
    332       s += state.last_dc_val[ci];
    333       state.last_dc_val[ci] = s;
    334       /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
    335       (*block)[0] = (JCOEF) (s << Al);
    336     }
    337 
    338     /* Completed MCU, so update state */
    339     BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
    340     ASSIGN_STATE(entropy->saved, state);
    341   }
    342 
    343   /* Account for restart interval (no-op if not using restarts) */
    344   entropy->restarts_to_go--;
    345 
    346   return TRUE;
    347 }
    348 
    349 
    350 /*
    351  * MCU decoding for AC initial scan (either spectral selection,
    352  * or first pass of successive approximation).
    353  */
    354 
    355 METHODDEF(boolean)
    356 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
    357 {
    358   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    359   int Se = cinfo->Se;
    360   int Al = cinfo->Al;
    361   register int s, k, r;
    362   unsigned int EOBRUN;
    363   JBLOCKROW block;
    364   BITREAD_STATE_VARS;
    365   d_derived_tbl * tbl;
    366 
    367   /* Process restart marker if needed; may have to suspend */
    368   if (cinfo->restart_interval) {
    369     if (entropy->restarts_to_go == 0)
    370       if (! process_restart(cinfo))
    371 	return FALSE;
    372   }
    373 
    374   /* If we've run out of data, just leave the MCU set to zeroes.
    375    * This way, we return uniform gray for the remainder of the segment.
    376    */
    377   if (! entropy->pub.insufficient_data) {
    378 
    379     /* Load up working state.
    380      * We can avoid loading/saving bitread state if in an EOB run.
    381      */
    382     EOBRUN = entropy->saved.EOBRUN;	/* only part of saved state we need */
    383 
    384     /* There is always only one block per MCU */
    385 
    386     if (EOBRUN > 0)		/* if it's a band of zeroes... */
    387       EOBRUN--;			/* ...process it now (we do nothing) */
    388     else {
    389       BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
    390       block = MCU_data[0];
    391       tbl = entropy->ac_derived_tbl;
    392 
    393       for (k = cinfo->Ss; k <= Se; k++) {
    394 	HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
    395 	r = s >> 4;
    396 	s &= 15;
    397 	if (s) {
    398 	  k += r;
    399 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
    400 	  r = GET_BITS(s);
    401 	  s = HUFF_EXTEND(r, s);
    402 	  /* Scale and output coefficient in natural (dezigzagged) order */
    403 	  (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
    404 	} else {
    405 	  if (r == 15) {	/* ZRL */
    406 	    k += 15;		/* skip 15 zeroes in band */
    407 	  } else {		/* EOBr, run length is 2^r + appended bits */
    408 	    EOBRUN = 1 << r;
    409 	    if (r) {		/* EOBr, r > 0 */
    410 	      CHECK_BIT_BUFFER(br_state, r, return FALSE);
    411 	      r = GET_BITS(r);
    412 	      EOBRUN += r;
    413 	    }
    414 	    EOBRUN--;		/* this band is processed at this moment */
    415 	    break;		/* force end-of-band */
    416 	  }
    417 	}
    418       }
    419 
    420       BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
    421     }
    422 
    423     /* Completed MCU, so update state */
    424     entropy->saved.EOBRUN = EOBRUN;	/* only part of saved state we need */
    425   }
    426 
    427   /* Account for restart interval (no-op if not using restarts) */
    428   entropy->restarts_to_go--;
    429 
    430   return TRUE;
    431 }
    432 
    433 
    434 /*
    435  * MCU decoding for DC successive approximation refinement scan.
    436  * Note: we assume such scans can be multi-component, although the spec
    437  * is not very clear on the point.
    438  */
    439 
    440 METHODDEF(boolean)
    441 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
    442 {
    443   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    444   int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
    445   int blkn;
    446   JBLOCKROW block;
    447   BITREAD_STATE_VARS;
    448 
    449   /* Process restart marker if needed; may have to suspend */
    450   if (cinfo->restart_interval) {
    451     if (entropy->restarts_to_go == 0)
    452       if (! process_restart(cinfo))
    453 	return FALSE;
    454   }
    455 
    456   /* Not worth the cycles to check insufficient_data here,
    457    * since we will not change the data anyway if we read zeroes.
    458    */
    459 
    460   /* Load up working state */
    461   BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
    462 
    463   /* Outer loop handles each block in the MCU */
    464 
    465   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
    466     block = MCU_data[blkn];
    467 
    468     /* Encoded data is simply the next bit of the two's-complement DC value */
    469     CHECK_BIT_BUFFER(br_state, 1, return FALSE);
    470     if (GET_BITS(1))
    471       (*block)[0] |= p1;
    472     /* Note: since we use |=, repeating the assignment later is safe */
    473   }
    474 
    475   /* Completed MCU, so update state */
    476   BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
    477 
    478   /* Account for restart interval (no-op if not using restarts) */
    479   entropy->restarts_to_go--;
    480 
    481   return TRUE;
    482 }
    483 
    484 
    485 /*
    486  * MCU decoding for AC successive approximation refinement scan.
    487  */
    488 
    489 METHODDEF(boolean)
    490 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
    491 {
    492   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    493   int Se = cinfo->Se;
    494   int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
    495   int m1 = (-1) << cinfo->Al;	/* -1 in the bit position being coded */
    496   register int s, k, r;
    497   unsigned int EOBRUN;
    498   JBLOCKROW block;
    499   JCOEFPTR thiscoef;
    500   BITREAD_STATE_VARS;
    501   d_derived_tbl * tbl;
    502   int num_newnz;
    503   int newnz_pos[DCTSIZE2];
    504 
    505   /* Process restart marker if needed; may have to suspend */
    506   if (cinfo->restart_interval) {
    507     if (entropy->restarts_to_go == 0)
    508       if (! process_restart(cinfo))
    509 	return FALSE;
    510   }
    511 
    512   /* If we've run out of data, don't modify the MCU.
    513    */
    514   if (! entropy->pub.insufficient_data) {
    515 
    516     /* Load up working state */
    517     BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
    518     EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
    519 
    520     /* There is always only one block per MCU */
    521     block = MCU_data[0];
    522     tbl = entropy->ac_derived_tbl;
    523 
    524     /* If we are forced to suspend, we must undo the assignments to any newly
    525      * nonzero coefficients in the block, because otherwise we'd get confused
    526      * next time about which coefficients were already nonzero.
    527      * But we need not undo addition of bits to already-nonzero coefficients;
    528      * instead, we can test the current bit to see if we already did it.
    529      */
    530     num_newnz = 0;
    531 
    532     /* initialize coefficient loop counter to start of band */
    533     k = cinfo->Ss;
    534 
    535     if (EOBRUN == 0) {
    536       for (; k <= Se; k++) {
    537 	HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
    538 	r = s >> 4;
    539 	s &= 15;
    540 	if (s) {
    541 	  if (s != 1)		/* size of new coef should always be 1 */
    542 	    WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
    543 	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
    544 	  if (GET_BITS(1))
    545 	    s = p1;		/* newly nonzero coef is positive */
    546 	  else
    547 	    s = m1;		/* newly nonzero coef is negative */
    548 	} else {
    549 	  if (r != 15) {
    550 	    EOBRUN = 1 << r;	/* EOBr, run length is 2^r + appended bits */
    551 	    if (r) {
    552 	      CHECK_BIT_BUFFER(br_state, r, goto undoit);
    553 	      r = GET_BITS(r);
    554 	      EOBRUN += r;
    555 	    }
    556 	    break;		/* rest of block is handled by EOB logic */
    557 	  }
    558 	  /* note s = 0 for processing ZRL */
    559 	}
    560 	/* Advance over already-nonzero coefs and r still-zero coefs,
    561 	 * appending correction bits to the nonzeroes.  A correction bit is 1
    562 	 * if the absolute value of the coefficient must be increased.
    563 	 */
    564 	do {
    565 	  thiscoef = *block + jpeg_natural_order[k];
    566 	  if (*thiscoef != 0) {
    567 	    CHECK_BIT_BUFFER(br_state, 1, goto undoit);
    568 	    if (GET_BITS(1)) {
    569 	      if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
    570 		if (*thiscoef >= 0)
    571 		  *thiscoef += p1;
    572 		else
    573 		  *thiscoef += m1;
    574 	      }
    575 	    }
    576 	  } else {
    577 	    if (--r < 0)
    578 	      break;		/* reached target zero coefficient */
    579 	  }
    580 	  k++;
    581 	} while (k <= Se);
    582 	if (s) {
    583 	  int pos = jpeg_natural_order[k];
    584 	  /* Output newly nonzero coefficient */
    585 	  (*block)[pos] = (JCOEF) s;
    586 	  /* Remember its position in case we have to suspend */
    587 	  newnz_pos[num_newnz++] = pos;
    588 	}
    589       }
    590     }
    591 
    592     if (EOBRUN > 0) {
    593       /* Scan any remaining coefficient positions after the end-of-band
    594        * (the last newly nonzero coefficient, if any).  Append a correction
    595        * bit to each already-nonzero coefficient.  A correction bit is 1
    596        * if the absolute value of the coefficient must be increased.
    597        */
    598       for (; k <= Se; k++) {
    599 	thiscoef = *block + jpeg_natural_order[k];
    600 	if (*thiscoef != 0) {
    601 	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
    602 	  if (GET_BITS(1)) {
    603 	    if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
    604 	      if (*thiscoef >= 0)
    605 		*thiscoef += p1;
    606 	      else
    607 		*thiscoef += m1;
    608 	    }
    609 	  }
    610 	}
    611       }
    612       /* Count one block completed in EOB run */
    613       EOBRUN--;
    614     }
    615 
    616     /* Completed MCU, so update state */
    617     BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
    618     entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
    619   }
    620 
    621   /* Account for restart interval (no-op if not using restarts) */
    622   entropy->restarts_to_go--;
    623 
    624   return TRUE;
    625 
    626 undoit:
    627   /* Re-zero any output coefficients that we made newly nonzero */
    628   while (num_newnz > 0)
    629     (*block)[newnz_pos[--num_newnz]] = 0;
    630 
    631   return FALSE;
    632 }
    633 
    634 /*
    635  * Save the current Huffman deocde position and the DC coefficients
    636  * for each component into bitstream_offset and dc_info[], respectively.
    637  */
    638 METHODDEF(void)
    639 get_huffman_decoder_configuration(j_decompress_ptr cinfo,
    640         huffman_offset_data *offset)
    641 {
    642   int i;
    643   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    644   jpeg_get_huffman_decoder_configuration_progressive(cinfo, offset);
    645   offset->EOBRUN = entropy->saved.EOBRUN;
    646   for (i = 0; i < cinfo->comps_in_scan; i++)
    647     offset->prev_dc[i] = entropy->saved.last_dc_val[i];
    648 }
    649 
    650 
    651 /*
    652  * Save the current Huffman decoder position and the bit buffer
    653  * into bitstream_offset and get_buffer, respectively.
    654  */
    655 GLOBAL(void)
    656 jpeg_get_huffman_decoder_configuration_progressive(j_decompress_ptr cinfo,
    657         huffman_offset_data *offset)
    658 {
    659   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    660 
    661   if (cinfo->restart_interval) {
    662     // We are at the end of a data segment
    663     if (entropy->restarts_to_go == 0)
    664       if (! process_restart(cinfo))
    665 	return;
    666   }
    667 
    668   // Save restarts_to_go and next_restart_num.
    669   offset->restarts_to_go = (unsigned short) entropy->restarts_to_go;
    670   offset->next_restart_num = cinfo->marker->next_restart_num;
    671 
    672   offset->bitstream_offset =
    673       (jget_input_stream_position(cinfo) << LOG_TWO_BIT_BUF_SIZE)
    674       + entropy->bitstate.bits_left;
    675 
    676   offset->get_buffer = entropy->bitstate.get_buffer;
    677 }
    678 
    679 
    680 /*
    681  * Configure the Huffman decoder to decode the image
    682  * starting from (iMCU_row_offset, iMCU_col_offset).
    683  */
    684 METHODDEF(void)
    685 configure_huffman_decoder(j_decompress_ptr cinfo, huffman_offset_data offset)
    686 {
    687   int i;
    688   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    689   jpeg_configure_huffman_decoder_progressive(cinfo, offset);
    690   entropy->saved.EOBRUN = offset.EOBRUN;
    691   for (i = 0; i < cinfo->comps_in_scan; i++)
    692     entropy->saved.last_dc_val[i] = offset.prev_dc[i];
    693 }
    694 
    695 /*
    696  * Configure the Huffman decoder reader position and bit buffer.
    697  */
    698 GLOBAL(void)
    699 jpeg_configure_huffman_decoder_progressive(j_decompress_ptr cinfo,
    700         huffman_offset_data offset)
    701 {
    702 	phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    703 
    704   // Restore restarts_to_go and next_restart_num
    705   cinfo->unread_marker = 0;
    706   entropy->restarts_to_go = offset.restarts_to_go;
    707   cinfo->marker->next_restart_num = offset.next_restart_num;
    708 
    709   unsigned int bitstream_offset = offset.bitstream_offset;
    710   int blkn, i;
    711 
    712   unsigned int byte_offset = bitstream_offset >> LOG_TWO_BIT_BUF_SIZE;
    713   unsigned int bit_in_bit_buffer =
    714       bitstream_offset & ((1 << LOG_TWO_BIT_BUF_SIZE) - 1);
    715 
    716   jset_input_stream_position_bit(cinfo, byte_offset,
    717           bit_in_bit_buffer, offset.get_buffer);
    718 }
    719 
    720 GLOBAL(void)
    721 jpeg_configure_huffman_index_scan(j_decompress_ptr cinfo,
    722         huffman_index *index, int scan_no, int offset)
    723 {
    724   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
    725   if (scan_no >= index->scan_count) {
    726     index->scan = realloc(index->scan,
    727                     (scan_no + 1) * sizeof(huffman_scan_header));
    728     index->mem_used += (scan_no - index->scan_count + 1)
    729       * (sizeof(huffman_scan_header) + cinfo->total_iMCU_rows
    730       * sizeof(huffman_offset_data*));
    731     index->scan_count = scan_no + 1;
    732   }
    733   index->scan[scan_no].offset = (huffman_offset_data**)malloc(
    734           cinfo->total_iMCU_rows * sizeof(huffman_offset_data*));
    735   index->scan[scan_no].bitstream_offset = offset;
    736 }
    737 
    738 /*
    739  * Module initialization routine for progressive Huffman entropy decoding.
    740  */
    741 GLOBAL(void)
    742 jinit_phuff_decoder (j_decompress_ptr cinfo)
    743 {
    744   phuff_entropy_ptr entropy;
    745   int *coef_bit_ptr;
    746   int ci, i;
    747 
    748   entropy = (phuff_entropy_ptr)
    749     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
    750 				SIZEOF(phuff_entropy_decoder));
    751   cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
    752   entropy->pub.start_pass = start_pass_phuff_decoder;
    753   entropy->pub.configure_huffman_decoder = configure_huffman_decoder;
    754   entropy->pub.get_huffman_decoder_configuration =
    755         get_huffman_decoder_configuration;
    756 
    757   /* Mark derived tables unallocated */
    758   for (i = 0; i < NUM_HUFF_TBLS; i++) {
    759     entropy->derived_tbls[i] = NULL;
    760   }
    761 
    762   /* Create progression status table */
    763   cinfo->coef_bits = (int (*)[DCTSIZE2])
    764     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
    765 				cinfo->num_components*DCTSIZE2*SIZEOF(int));
    766   coef_bit_ptr = & cinfo->coef_bits[0][0];
    767   for (ci = 0; ci < cinfo->num_components; ci++)
    768     for (i = 0; i < DCTSIZE2; i++)
    769       *coef_bit_ptr++ = -1;
    770 }
    771 
    772 #endif /* D_PROGRESSIVE_SUPPORTED */
    773