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