• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 GLOBAL(void) jpeg_configure_huffman_decoder_progressive(
86 		j_decompress_ptr cinfo, huffman_offset_data offset);
87 GLOBAL(void) jpeg_get_huffman_decoder_configuration_progressive(
88 	        j_decompress_ptr cinfo, huffman_offset_data *offset);
89 
90 /*
91  * Initialize for a Huffman-compressed scan.
92  */
93 
94 METHODDEF(void)
start_pass_phuff_decoder(j_decompress_ptr cinfo)95 start_pass_phuff_decoder (j_decompress_ptr cinfo)
96 {
97   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
98   boolean is_DC_band, bad;
99   int ci, coefi, tbl;
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 	jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
173 				& entropy->derived_tbls[tbl]);
174       }
175     } else {
176       tbl = compptr->ac_tbl_no;
177       jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
178 			      & entropy->derived_tbls[tbl]);
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 #ifdef AVOID_TABLES
205 
206 #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
207 
208 #else
209 
210 #define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
211 
212 static const int extend_test[16] =   /* entry n is 2**(n-1) */
213   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
214     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
215 
216 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
217   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
218     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
219     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
220     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
221 
222 #endif /* AVOID_TABLES */
223 
224 
225 /*
226  * Check for a restart marker & resynchronize decoder.
227  * Returns FALSE if must suspend.
228  */
229 
230 LOCAL(boolean)
process_restart(j_decompress_ptr cinfo)231 process_restart (j_decompress_ptr cinfo)
232 {
233   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
234   int ci;
235 
236   /* Throw away any unused bits remaining in bit buffer; */
237   /* include any full bytes in next_marker's count of discarded bytes */
238   cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
239   entropy->bitstate.bits_left = 0;
240 
241   /* Advance past the RSTn marker */
242   if (! (*cinfo->marker->read_restart_marker) (cinfo))
243     return FALSE;
244 
245   /* Re-initialize DC predictions to 0 */
246   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
247     entropy->saved.last_dc_val[ci] = 0;
248   /* Re-init EOB run count, too */
249   entropy->saved.EOBRUN = 0;
250 
251   /* Reset restart counter */
252   entropy->restarts_to_go = cinfo->restart_interval;
253 
254   /* Reset out-of-data flag, unless read_restart_marker left us smack up
255    * against a marker.  In that case we will end up treating the next data
256    * segment as empty, and we can avoid producing bogus output pixels by
257    * leaving the flag set.
258    */
259   if (cinfo->unread_marker == 0)
260     entropy->pub.insufficient_data = FALSE;
261 
262   return TRUE;
263 }
264 
265 
266 /*
267  * Huffman MCU decoding.
268  * Each of these routines decodes and returns one MCU's worth of
269  * Huffman-compressed coefficients.
270  * The coefficients are reordered from zigzag order into natural array order,
271  * but are not dequantized.
272  *
273  * The i'th block of the MCU is stored into the block pointed to by
274  * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
275  *
276  * We return FALSE if data source requested suspension.  In that case no
277  * changes have been made to permanent state.  (Exception: some output
278  * coefficients may already have been assigned.  This is harmless for
279  * spectral selection, since we'll just re-assign them on the next call.
280  * Successive approximation AC refinement has to be more careful, however.)
281  */
282 
283 /*
284  * MCU decoding for DC initial scan (either spectral selection,
285  * or first pass of successive approximation).
286  */
287 
288 METHODDEF(boolean)
decode_mcu_DC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)289 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
290 {
291   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
292   int Al = cinfo->Al;
293   register int s, r;
294   int blkn, ci;
295   JBLOCKROW block;
296   BITREAD_STATE_VARS;
297   savable_state state;
298   d_derived_tbl * tbl;
299   jpeg_component_info * compptr;
300 
301   /* Process restart marker if needed; may have to suspend */
302   if (cinfo->restart_interval) {
303     if (entropy->restarts_to_go == 0)
304       if (! process_restart(cinfo))
305 	return FALSE;
306   }
307 
308   /* If we've run out of data, just leave the MCU set to zeroes.
309    * This way, we return uniform gray for the remainder of the segment.
310    */
311   if (! entropy->pub.insufficient_data) {
312 
313     /* Load up working state */
314     BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
315     ASSIGN_STATE(state, entropy->saved);
316 
317     /* Outer loop handles each block in the MCU */
318 
319     for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
320       block = MCU_data[blkn];
321       ci = cinfo->MCU_membership[blkn];
322       compptr = cinfo->cur_comp_info[ci];
323       tbl = entropy->derived_tbls[compptr->dc_tbl_no];
324 
325       /* Decode a single block's worth of coefficients */
326 
327       /* Section F.2.2.1: decode the DC coefficient difference */
328       HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
329       if (s) {
330 	CHECK_BIT_BUFFER(br_state, s, return FALSE);
331 	r = GET_BITS(s);
332 	s = HUFF_EXTEND(r, s);
333       }
334 
335       /* Convert DC difference to actual value, update last_dc_val */
336       s += state.last_dc_val[ci];
337       state.last_dc_val[ci] = s;
338       /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
339       (*block)[0] = (JCOEF) (s << Al);
340     }
341 
342     /* Completed MCU, so update state */
343     BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
344     ASSIGN_STATE(entropy->saved, state);
345   }
346 
347   /* Account for restart interval (no-op if not using restarts) */
348   entropy->restarts_to_go--;
349 
350   return TRUE;
351 }
352 
353 
354 /*
355  * MCU decoding for AC initial scan (either spectral selection,
356  * or first pass of successive approximation).
357  */
358 
359 METHODDEF(boolean)
decode_mcu_AC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)360 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
361 {
362   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
363   int Se = cinfo->Se;
364   int Al = cinfo->Al;
365   register int s, k, r;
366   unsigned int EOBRUN;
367   JBLOCKROW block;
368   BITREAD_STATE_VARS;
369   d_derived_tbl * tbl;
370 
371   /* Process restart marker if needed; may have to suspend */
372   if (cinfo->restart_interval) {
373     if (entropy->restarts_to_go == 0)
374       if (! process_restart(cinfo))
375 	return FALSE;
376   }
377 
378   /* If we've run out of data, just leave the MCU set to zeroes.
379    * This way, we return uniform gray for the remainder of the segment.
380    */
381   if (! entropy->pub.insufficient_data) {
382 
383     /* Load up working state.
384      * We can avoid loading/saving bitread state if in an EOB run.
385      */
386     EOBRUN = entropy->saved.EOBRUN;	/* only part of saved state we need */
387 
388     /* There is always only one block per MCU */
389 
390     if (EOBRUN > 0)		/* if it's a band of zeroes... */
391       EOBRUN--;			/* ...process it now (we do nothing) */
392     else {
393       BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
394       block = MCU_data[0];
395       tbl = entropy->ac_derived_tbl;
396 
397       for (k = cinfo->Ss; k <= Se; k++) {
398 	HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
399 	r = s >> 4;
400 	s &= 15;
401 	if (s) {
402 	  k += r;
403 	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
404 	  r = GET_BITS(s);
405 	  s = HUFF_EXTEND(r, s);
406 	  /* Scale and output coefficient in natural (dezigzagged) order */
407 	  (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
408 	} else {
409 	  if (r == 15) {	/* ZRL */
410 	    k += 15;		/* skip 15 zeroes in band */
411 	  } else {		/* EOBr, run length is 2^r + appended bits */
412 	    EOBRUN = 1 << r;
413 	    if (r) {		/* EOBr, r > 0 */
414 	      CHECK_BIT_BUFFER(br_state, r, return FALSE);
415 	      r = GET_BITS(r);
416 	      EOBRUN += r;
417 	    }
418 	    EOBRUN--;		/* this band is processed at this moment */
419 	    break;		/* force end-of-band */
420 	  }
421 	}
422       }
423 
424       BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
425     }
426 
427     /* Completed MCU, so update state */
428     entropy->saved.EOBRUN = EOBRUN;	/* only part of saved state we need */
429   }
430 
431   /* Account for restart interval (no-op if not using restarts) */
432   entropy->restarts_to_go--;
433 
434   return TRUE;
435 }
436 
437 
438 /*
439  * MCU decoding for DC successive approximation refinement scan.
440  * Note: we assume such scans can be multi-component, although the spec
441  * is not very clear on the point.
442  */
443 
444 METHODDEF(boolean)
decode_mcu_DC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)445 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
446 {
447   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
448   int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
449   int blkn;
450   JBLOCKROW block;
451   BITREAD_STATE_VARS;
452 
453   /* Process restart marker if needed; may have to suspend */
454   if (cinfo->restart_interval) {
455     if (entropy->restarts_to_go == 0)
456       if (! process_restart(cinfo))
457 	return FALSE;
458   }
459 
460   /* Not worth the cycles to check insufficient_data here,
461    * since we will not change the data anyway if we read zeroes.
462    */
463 
464   /* Load up working state */
465   BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
466 
467   /* Outer loop handles each block in the MCU */
468 
469   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
470     block = MCU_data[blkn];
471 
472     /* Encoded data is simply the next bit of the two's-complement DC value */
473     CHECK_BIT_BUFFER(br_state, 1, return FALSE);
474     if (GET_BITS(1))
475       (*block)[0] |= p1;
476     /* Note: since we use |=, repeating the assignment later is safe */
477   }
478 
479   /* Completed MCU, so update state */
480   BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
481 
482   /* Account for restart interval (no-op if not using restarts) */
483   entropy->restarts_to_go--;
484 
485   return TRUE;
486 }
487 
488 
489 /*
490  * MCU decoding for AC successive approximation refinement scan.
491  */
492 
493 METHODDEF(boolean)
decode_mcu_AC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)494 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
495 {
496   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
497   int Se = cinfo->Se;
498   int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
499   int m1 = (-1) << cinfo->Al;	/* -1 in the bit position being coded */
500   register int s, k, r;
501   unsigned int EOBRUN;
502   JBLOCKROW block;
503   JCOEFPTR thiscoef;
504   BITREAD_STATE_VARS;
505   d_derived_tbl * tbl;
506   int num_newnz;
507   int newnz_pos[DCTSIZE2];
508 
509   /* Process restart marker if needed; may have to suspend */
510   if (cinfo->restart_interval) {
511     if (entropy->restarts_to_go == 0)
512       if (! process_restart(cinfo))
513 	return FALSE;
514   }
515 
516   /* If we've run out of data, don't modify the MCU.
517    */
518   if (! entropy->pub.insufficient_data) {
519 
520     /* Load up working state */
521     BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
522     EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
523 
524     /* There is always only one block per MCU */
525     block = MCU_data[0];
526     tbl = entropy->ac_derived_tbl;
527 
528     /* If we are forced to suspend, we must undo the assignments to any newly
529      * nonzero coefficients in the block, because otherwise we'd get confused
530      * next time about which coefficients were already nonzero.
531      * But we need not undo addition of bits to already-nonzero coefficients;
532      * instead, we can test the current bit to see if we already did it.
533      */
534     num_newnz = 0;
535 
536     /* initialize coefficient loop counter to start of band */
537     k = cinfo->Ss;
538 
539     if (EOBRUN == 0) {
540       for (; k <= Se; k++) {
541 	HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
542 	r = s >> 4;
543 	s &= 15;
544 	if (s) {
545 	  if (s != 1)		/* size of new coef should always be 1 */
546 	    WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
547 	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
548 	  if (GET_BITS(1))
549 	    s = p1;		/* newly nonzero coef is positive */
550 	  else
551 	    s = m1;		/* newly nonzero coef is negative */
552 	} else {
553 	  if (r != 15) {
554 	    EOBRUN = 1 << r;	/* EOBr, run length is 2^r + appended bits */
555 	    if (r) {
556 	      CHECK_BIT_BUFFER(br_state, r, goto undoit);
557 	      r = GET_BITS(r);
558 	      EOBRUN += r;
559 	    }
560 	    break;		/* rest of block is handled by EOB logic */
561 	  }
562 	  /* note s = 0 for processing ZRL */
563 	}
564 	/* Advance over already-nonzero coefs and r still-zero coefs,
565 	 * appending correction bits to the nonzeroes.  A correction bit is 1
566 	 * if the absolute value of the coefficient must be increased.
567 	 */
568 	do {
569 	  thiscoef = *block + jpeg_natural_order[k];
570 	  if (*thiscoef != 0) {
571 	    CHECK_BIT_BUFFER(br_state, 1, goto undoit);
572 	    if (GET_BITS(1)) {
573 	      if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
574 		if (*thiscoef >= 0)
575 		  *thiscoef += p1;
576 		else
577 		  *thiscoef += m1;
578 	      }
579 	    }
580 	  } else {
581 	    if (--r < 0)
582 	      break;		/* reached target zero coefficient */
583 	  }
584 	  k++;
585 	} while (k <= Se);
586 	if (s) {
587 	  int pos = jpeg_natural_order[k];
588 	  /* Output newly nonzero coefficient */
589 	  (*block)[pos] = (JCOEF) s;
590 	  /* Remember its position in case we have to suspend */
591 	  newnz_pos[num_newnz++] = pos;
592 	}
593       }
594     }
595 
596     if (EOBRUN > 0) {
597       /* Scan any remaining coefficient positions after the end-of-band
598        * (the last newly nonzero coefficient, if any).  Append a correction
599        * bit to each already-nonzero coefficient.  A correction bit is 1
600        * if the absolute value of the coefficient must be increased.
601        */
602       for (; k <= Se; k++) {
603 	thiscoef = *block + jpeg_natural_order[k];
604 	if (*thiscoef != 0) {
605 	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
606 	  if (GET_BITS(1)) {
607 	    if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
608 	      if (*thiscoef >= 0)
609 		*thiscoef += p1;
610 	      else
611 		*thiscoef += m1;
612 	    }
613 	  }
614 	}
615       }
616       /* Count one block completed in EOB run */
617       EOBRUN--;
618     }
619 
620     /* Completed MCU, so update state */
621     BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
622     entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
623   }
624 
625   /* Account for restart interval (no-op if not using restarts) */
626   entropy->restarts_to_go--;
627 
628   return TRUE;
629 
630 undoit:
631   /* Re-zero any output coefficients that we made newly nonzero */
632   while (num_newnz > 0)
633     (*block)[newnz_pos[--num_newnz]] = 0;
634 
635   return FALSE;
636 }
637 
638 /*
639  * Save the current Huffman deocde position and the DC coefficients
640  * for each component into bitstream_offset and dc_info[], respectively.
641  */
642 METHODDEF(void)
get_huffman_decoder_configuration(j_decompress_ptr cinfo,huffman_offset_data * offset)643 get_huffman_decoder_configuration(j_decompress_ptr cinfo,
644         huffman_offset_data *offset)
645 {
646   int i;
647   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
648   jpeg_get_huffman_decoder_configuration_progressive(cinfo, offset);
649   offset->EOBRUN = entropy->saved.EOBRUN;
650   for (i = 0; i < cinfo->comps_in_scan; i++)
651     offset->prev_dc[i] = entropy->saved.last_dc_val[i];
652 }
653 
654 
655 /*
656  * Save the current Huffman decoder position and the bit buffer
657  * into bitstream_offset and get_buffer, respectively.
658  */
659 GLOBAL(void)
jpeg_get_huffman_decoder_configuration_progressive(j_decompress_ptr cinfo,huffman_offset_data * offset)660 jpeg_get_huffman_decoder_configuration_progressive(j_decompress_ptr cinfo,
661         huffman_offset_data *offset)
662 {
663   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
664 
665   if (cinfo->restart_interval) {
666     // We are at the end of a data segment
667     if (entropy->restarts_to_go == 0)
668       if (! process_restart(cinfo))
669 	return;
670   }
671 
672   // Save restarts_to_go and next_restart_num.
673   offset->restarts_to_go = (unsigned short) entropy->restarts_to_go;
674   offset->next_restart_num = cinfo->marker->next_restart_num;
675 
676   offset->bitstream_offset =
677       (jget_input_stream_position(cinfo) << LOG_TWO_BIT_BUF_SIZE)
678       + entropy->bitstate.bits_left;
679 
680   offset->get_buffer = entropy->bitstate.get_buffer;
681 }
682 
683 
684 /*
685  * Configure the Huffman decoder to decode the image
686  * starting from (iMCU_row_offset, iMCU_col_offset).
687  */
688 METHODDEF(void)
configure_huffman_decoder(j_decompress_ptr cinfo,huffman_offset_data offset)689 configure_huffman_decoder(j_decompress_ptr cinfo, huffman_offset_data offset)
690 {
691   int i;
692   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
693   jpeg_configure_huffman_decoder_progressive(cinfo, offset);
694   entropy->saved.EOBRUN = offset.EOBRUN;
695   for (i = 0; i < cinfo->comps_in_scan; i++)
696     entropy->saved.last_dc_val[i] = offset.prev_dc[i];
697 }
698 
699 /*
700  * Configure the Huffman decoder reader position and bit buffer.
701  */
702 GLOBAL(void)
jpeg_configure_huffman_decoder_progressive(j_decompress_ptr cinfo,huffman_offset_data offset)703 jpeg_configure_huffman_decoder_progressive(j_decompress_ptr cinfo,
704         huffman_offset_data offset)
705 {
706 	phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
707 
708   // Restore restarts_to_go and next_restart_num
709   cinfo->unread_marker = 0;
710   entropy->restarts_to_go = offset.restarts_to_go;
711   cinfo->marker->next_restart_num = offset.next_restart_num;
712 
713   unsigned int bitstream_offset = offset.bitstream_offset;
714   int blkn, i;
715 
716   unsigned int byte_offset = bitstream_offset >> LOG_TWO_BIT_BUF_SIZE;
717   unsigned int bit_in_bit_buffer =
718       bitstream_offset & ((1 << LOG_TWO_BIT_BUF_SIZE) - 1);
719 
720   jset_input_stream_position_bit(cinfo, byte_offset,
721           bit_in_bit_buffer, offset.get_buffer);
722 }
723 
724 GLOBAL(void)
jpeg_configure_huffman_index_scan(j_decompress_ptr cinfo,huffman_index * index,int scan_no,int offset)725 jpeg_configure_huffman_index_scan(j_decompress_ptr cinfo,
726         huffman_index *index, int scan_no, int offset)
727 {
728   phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
729   if (scan_no >= index->scan_count) {
730     index->scan = realloc(index->scan,
731                     (scan_no + 1) * sizeof(huffman_scan_header));
732     index->mem_used += (scan_no - index->scan_count + 1)
733       * (sizeof(huffman_scan_header) + cinfo->total_iMCU_rows
734       * sizeof(huffman_offset_data*));
735     index->scan_count = scan_no + 1;
736   }
737   index->scan[scan_no].offset = (huffman_offset_data**)malloc(
738           cinfo->total_iMCU_rows * sizeof(huffman_offset_data*));
739   index->scan[scan_no].bitstream_offset = offset;
740 }
741 
742 /*
743  * Module initialization routine for progressive Huffman entropy decoding.
744  */
745 GLOBAL(void)
jinit_phuff_decoder(j_decompress_ptr cinfo)746 jinit_phuff_decoder (j_decompress_ptr cinfo)
747 {
748   phuff_entropy_ptr entropy;
749   int *coef_bit_ptr;
750   int ci, i;
751 
752   entropy = (phuff_entropy_ptr)
753     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
754 				SIZEOF(phuff_entropy_decoder));
755   cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
756   entropy->pub.start_pass = start_pass_phuff_decoder;
757   entropy->pub.configure_huffman_decoder = configure_huffman_decoder;
758   entropy->pub.get_huffman_decoder_configuration =
759         get_huffman_decoder_configuration;
760 
761   /* Mark derived tables unallocated */
762   for (i = 0; i < NUM_HUFF_TBLS; i++) {
763     entropy->derived_tbls[i] = NULL;
764   }
765 
766   /* Create progression status table */
767   cinfo->coef_bits = (int (*)[DCTSIZE2])
768     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
769 				cinfo->num_components*DCTSIZE2*SIZEOF(int));
770   coef_bit_ptr = & cinfo->coef_bits[0][0];
771   for (ci = 0; ci < cinfo->num_components; ci++)
772     for (i = 0; i < DCTSIZE2; i++)
773       *coef_bit_ptr++ = -1;
774 }
775 
776 #endif /* D_PROGRESSIVE_SUPPORTED */
777