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-2016, D. R. Commander.
8 * For conditions of distribution and use, see the accompanying README.ijg
11 * This file contains Huffman entropy decoding routines for progressive JPEG.
13 * Much of the complexity here has to do with supporting input suspension.
14 * If the data source module demands suspension, we want to be able to back
15 * up to the start of the current MCU. To do this, we copy state variables
16 * into local working storage, and update them back to the permanent
17 * storage only upon successful completion of an MCU.
20 #define JPEG_INTERNALS
23 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
26 #ifdef D_PROGRESSIVE_SUPPORTED
29 * Expanded entropy decoder object for progressive Huffman decoding.
31 * The savable_state subrecord contains fields that change within an MCU,
32 * but must not be updated permanently until we complete the MCU.
36 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
37 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
40 /* This macro is to work around compilers with missing or broken
41 * structure assignment. You'll need to fix this code if you have
42 * such a compiler and you change MAX_COMPS_IN_SCAN.
45 #ifndef NO_STRUCT_ASSIGN
46 #define ASSIGN_STATE(dest,src) ((dest) = (src))
48 #if MAX_COMPS_IN_SCAN == 4
49 #define ASSIGN_STATE(dest,src) \
50 ((dest).EOBRUN = (src).EOBRUN, \
51 (dest).last_dc_val[0] = (src).last_dc_val[0], \
52 (dest).last_dc_val[1] = (src).last_dc_val[1], \
53 (dest).last_dc_val[2] = (src).last_dc_val[2], \
54 (dest).last_dc_val[3] = (src).last_dc_val[3])
60 struct jpeg_entropy_decoder pub; /* public fields */
62 /* These fields are loaded into local variables at start of each MCU.
63 * In case of suspension, we exit WITHOUT updating them.
65 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
66 savable_state saved; /* Other state at start of MCU */
68 /* These fields are NOT loaded into local working state. */
69 unsigned int restarts_to_go; /* MCUs left in this restart interval */
71 /* Pointers to derived tables (these workspaces have image lifespan) */
72 d_derived_tbl *derived_tbls[NUM_HUFF_TBLS];
74 d_derived_tbl *ac_derived_tbl; /* active table during an AC scan */
75 } phuff_entropy_decoder;
77 typedef phuff_entropy_decoder *phuff_entropy_ptr;
79 /* Forward declarations */
80 METHODDEF(boolean) decode_mcu_DC_first (j_decompress_ptr cinfo,
82 METHODDEF(boolean) decode_mcu_AC_first (j_decompress_ptr cinfo,
84 METHODDEF(boolean) decode_mcu_DC_refine (j_decompress_ptr cinfo,
86 METHODDEF(boolean) decode_mcu_AC_refine (j_decompress_ptr cinfo,
91 * Initialize for a Huffman-compressed scan.
95 start_pass_phuff_decoder (j_decompress_ptr cinfo)
97 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
98 boolean is_DC_band, bad;
100 d_derived_tbl **pdtbl;
102 jpeg_component_info *compptr;
104 is_DC_band = (cinfo->Ss == 0);
106 /* Validate scan parameters */
112 /* need not check Ss/Se < 0 since they came from unsigned bytes */
113 if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
115 /* AC scans may have only one component */
116 if (cinfo->comps_in_scan != 1)
119 if (cinfo->Ah != 0) {
120 /* Successive approximation refinement scan: must have Al = Ah-1. */
121 if (cinfo->Al != cinfo->Ah-1)
124 if (cinfo->Al > 13) /* need not check for < 0 */
126 /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
127 * but the spec doesn't say so, and we try to be liberal about what we
128 * accept. Note: large Al values could result in out-of-range DC
129 * coefficients during early scans, leading to bizarre displays due to
130 * overflows in the IDCT math. But we won't crash.
133 ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
134 cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
135 /* Update progression status, and verify that scan order is legal.
136 * Note that inter-scan inconsistencies are treated as warnings
137 * not fatal errors ... not clear if this is right way to behave.
139 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
140 int cindex = cinfo->cur_comp_info[ci]->component_index;
141 coef_bit_ptr = & cinfo->coef_bits[cindex][0];
142 if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
143 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
144 for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
145 int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
146 if (cinfo->Ah != expected)
147 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
148 coef_bit_ptr[coefi] = cinfo->Al;
152 /* Select MCU decoding routine */
153 if (cinfo->Ah == 0) {
155 entropy->pub.decode_mcu = decode_mcu_DC_first;
157 entropy->pub.decode_mcu = decode_mcu_AC_first;
160 entropy->pub.decode_mcu = decode_mcu_DC_refine;
162 entropy->pub.decode_mcu = decode_mcu_AC_refine;
165 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
166 compptr = cinfo->cur_comp_info[ci];
167 /* Make sure requested tables are present, and compute derived tables.
168 * We may build same derived table more than once, but it's not expensive.
171 if (cinfo->Ah == 0) { /* DC refinement needs no table */
172 tbl = compptr->dc_tbl_no;
173 pdtbl = (d_derived_tbl **)(entropy->derived_tbls) + tbl;
174 jpeg_make_d_derived_tbl(cinfo, TRUE, tbl, pdtbl);
177 tbl = compptr->ac_tbl_no;
178 pdtbl = (d_derived_tbl **)(entropy->derived_tbls) + tbl;
179 jpeg_make_d_derived_tbl(cinfo, FALSE, tbl, pdtbl);
180 /* remember the single active table */
181 entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
183 /* Initialize DC predictions to 0 */
184 entropy->saved.last_dc_val[ci] = 0;
187 /* Initialize bitread state variables */
188 entropy->bitstate.bits_left = 0;
189 entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
190 entropy->pub.insufficient_data = FALSE;
192 /* Initialize private state variables */
193 entropy->saved.EOBRUN = 0;
195 /* Initialize restart counter */
196 entropy->restarts_to_go = cinfo->restart_interval;
201 * Figure F.12: extend sign bit.
202 * On some machines, a shift and add will be faster than a table lookup.
208 #define NEG_1 ((unsigned)-1)
209 #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((NEG_1)<<(s)) + 1) : (x))
213 #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
215 static const int extend_test[16] = /* entry n is 2**(n-1) */
216 { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
217 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
219 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
220 { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
221 ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
222 ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
223 ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
225 #endif /* AVOID_TABLES */
229 * Check for a restart marker & resynchronize decoder.
230 * Returns FALSE if must suspend.
234 process_restart (j_decompress_ptr cinfo)
236 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
239 /* Throw away any unused bits remaining in bit buffer; */
240 /* include any full bytes in next_marker's count of discarded bytes */
241 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
242 entropy->bitstate.bits_left = 0;
244 /* Advance past the RSTn marker */
245 if (! (*cinfo->marker->read_restart_marker) (cinfo))
248 /* Re-initialize DC predictions to 0 */
249 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
250 entropy->saved.last_dc_val[ci] = 0;
251 /* Re-init EOB run count, too */
252 entropy->saved.EOBRUN = 0;
254 /* Reset restart counter */
255 entropy->restarts_to_go = cinfo->restart_interval;
257 /* Reset out-of-data flag, unless read_restart_marker left us smack up
258 * against a marker. In that case we will end up treating the next data
259 * segment as empty, and we can avoid producing bogus output pixels by
260 * leaving the flag set.
262 if (cinfo->unread_marker == 0)
263 entropy->pub.insufficient_data = FALSE;
270 * Huffman MCU decoding.
271 * Each of these routines decodes and returns one MCU's worth of
272 * Huffman-compressed coefficients.
273 * The coefficients are reordered from zigzag order into natural array order,
274 * but are not dequantized.
276 * The i'th block of the MCU is stored into the block pointed to by
277 * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
279 * We return FALSE if data source requested suspension. In that case no
280 * changes have been made to permanent state. (Exception: some output
281 * coefficients may already have been assigned. This is harmless for
282 * spectral selection, since we'll just re-assign them on the next call.
283 * Successive approximation AC refinement has to be more careful, however.)
287 * MCU decoding for DC initial scan (either spectral selection,
288 * or first pass of successive approximation).
292 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
294 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
302 jpeg_component_info *compptr;
304 /* Process restart marker if needed; may have to suspend */
305 if (cinfo->restart_interval) {
306 if (entropy->restarts_to_go == 0)
307 if (! process_restart(cinfo))
311 /* If we've run out of data, just leave the MCU set to zeroes.
312 * This way, we return uniform gray for the remainder of the segment.
314 if (! entropy->pub.insufficient_data) {
316 /* Load up working state */
317 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
318 ASSIGN_STATE(state, entropy->saved);
320 /* Outer loop handles each block in the MCU */
322 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
323 block = MCU_data[blkn];
324 ci = cinfo->MCU_membership[blkn];
325 compptr = cinfo->cur_comp_info[ci];
326 tbl = entropy->derived_tbls[compptr->dc_tbl_no];
328 /* Decode a single block's worth of coefficients */
330 /* Section F.2.2.1: decode the DC coefficient difference */
331 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
333 CHECK_BIT_BUFFER(br_state, s, return FALSE);
335 s = HUFF_EXTEND(r, s);
338 /* Convert DC difference to actual value, update last_dc_val */
339 s += state.last_dc_val[ci];
340 state.last_dc_val[ci] = s;
341 /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
342 (*block)[0] = (JCOEF) LEFT_SHIFT(s, Al);
345 /* Completed MCU, so update state */
346 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
347 ASSIGN_STATE(entropy->saved, state);
350 /* Account for restart interval (no-op if not using restarts) */
351 entropy->restarts_to_go--;
358 * MCU decoding for AC initial scan (either spectral selection,
359 * or first pass of successive approximation).
363 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
365 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
368 register int s, k, r;
374 /* Process restart marker if needed; may have to suspend */
375 if (cinfo->restart_interval) {
376 if (entropy->restarts_to_go == 0)
377 if (! process_restart(cinfo))
381 /* If we've run out of data, just leave the MCU set to zeroes.
382 * This way, we return uniform gray for the remainder of the segment.
384 if (! entropy->pub.insufficient_data) {
386 /* Load up working state.
387 * We can avoid loading/saving bitread state if in an EOB run.
389 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
391 /* There is always only one block per MCU */
393 if (EOBRUN > 0) /* if it's a band of zeroes... */
394 EOBRUN--; /* ...process it now (we do nothing) */
396 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
398 tbl = entropy->ac_derived_tbl;
400 for (k = cinfo->Ss; k <= Se; k++) {
401 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
406 CHECK_BIT_BUFFER(br_state, s, return FALSE);
408 s = HUFF_EXTEND(r, s);
409 /* Scale and output coefficient in natural (dezigzagged) order */
410 (*block)[jpeg_natural_order[k]] = (JCOEF) LEFT_SHIFT(s, Al);
412 if (r == 15) { /* ZRL */
413 k += 15; /* skip 15 zeroes in band */
414 } else { /* EOBr, run length is 2^r + appended bits */
416 if (r) { /* EOBr, r > 0 */
417 CHECK_BIT_BUFFER(br_state, r, return FALSE);
421 EOBRUN--; /* this band is processed at this moment */
422 break; /* force end-of-band */
427 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
430 /* Completed MCU, so update state */
431 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
434 /* Account for restart interval (no-op if not using restarts) */
435 entropy->restarts_to_go--;
442 * MCU decoding for DC successive approximation refinement scan.
443 * Note: we assume such scans can be multi-component, although the spec
444 * is not very clear on the point.
448 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
450 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
451 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
456 /* Process restart marker if needed; may have to suspend */
457 if (cinfo->restart_interval) {
458 if (entropy->restarts_to_go == 0)
459 if (! process_restart(cinfo))
463 /* Not worth the cycles to check insufficient_data here,
464 * since we will not change the data anyway if we read zeroes.
467 /* Load up working state */
468 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
470 /* Outer loop handles each block in the MCU */
472 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
473 block = MCU_data[blkn];
475 /* Encoded data is simply the next bit of the two's-complement DC value */
476 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
479 /* Note: since we use |=, repeating the assignment later is safe */
482 /* Completed MCU, so update state */
483 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
485 /* Account for restart interval (no-op if not using restarts) */
486 entropy->restarts_to_go--;
493 * MCU decoding for AC successive approximation refinement scan.
497 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
499 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
501 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
502 int m1 = (NEG_1) << cinfo->Al; /* -1 in the bit position being coded */
503 register int s, k, r;
510 int newnz_pos[DCTSIZE2];
512 /* Process restart marker if needed; may have to suspend */
513 if (cinfo->restart_interval) {
514 if (entropy->restarts_to_go == 0)
515 if (! process_restart(cinfo))
519 /* If we've run out of data, don't modify the MCU.
521 if (! entropy->pub.insufficient_data) {
523 /* Load up working state */
524 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
525 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
527 /* There is always only one block per MCU */
529 tbl = entropy->ac_derived_tbl;
531 /* If we are forced to suspend, we must undo the assignments to any newly
532 * nonzero coefficients in the block, because otherwise we'd get confused
533 * next time about which coefficients were already nonzero.
534 * But we need not undo addition of bits to already-nonzero coefficients;
535 * instead, we can test the current bit to see if we already did it.
539 /* initialize coefficient loop counter to start of band */
543 for (; k <= Se; k++) {
544 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
548 if (s != 1) /* size of new coef should always be 1 */
549 WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
550 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
552 s = p1; /* newly nonzero coef is positive */
554 s = m1; /* newly nonzero coef is negative */
557 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
559 CHECK_BIT_BUFFER(br_state, r, goto undoit);
563 break; /* rest of block is handled by EOB logic */
565 /* note s = 0 for processing ZRL */
567 /* Advance over already-nonzero coefs and r still-zero coefs,
568 * appending correction bits to the nonzeroes. A correction bit is 1
569 * if the absolute value of the coefficient must be increased.
572 thiscoef = *block + jpeg_natural_order[k];
573 if (*thiscoef != 0) {
574 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
576 if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
585 break; /* reached target zero coefficient */
590 int pos = jpeg_natural_order[k];
591 /* Output newly nonzero coefficient */
592 (*block)[pos] = (JCOEF) s;
593 /* Remember its position in case we have to suspend */
594 newnz_pos[num_newnz++] = pos;
600 /* Scan any remaining coefficient positions after the end-of-band
601 * (the last newly nonzero coefficient, if any). Append a correction
602 * bit to each already-nonzero coefficient. A correction bit is 1
603 * if the absolute value of the coefficient must be increased.
605 for (; k <= Se; k++) {
606 thiscoef = *block + jpeg_natural_order[k];
607 if (*thiscoef != 0) {
608 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
610 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
619 /* Count one block completed in EOB run */
623 /* Completed MCU, so update state */
624 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
625 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
628 /* Account for restart interval (no-op if not using restarts) */
629 entropy->restarts_to_go--;
634 /* Re-zero any output coefficients that we made newly nonzero */
635 while (num_newnz > 0)
636 (*block)[newnz_pos[--num_newnz]] = 0;
643 * Module initialization routine for progressive Huffman entropy decoding.
647 jinit_phuff_decoder (j_decompress_ptr cinfo)
649 phuff_entropy_ptr entropy;
653 entropy = (phuff_entropy_ptr)
654 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
655 sizeof(phuff_entropy_decoder));
656 cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
657 entropy->pub.start_pass = start_pass_phuff_decoder;
659 /* Mark derived tables unallocated */
660 for (i = 0; i < NUM_HUFF_TBLS; i++) {
661 entropy->derived_tbls[i] = NULL;
664 /* Create progression status table */
665 cinfo->coef_bits = (int (*)[DCTSIZE2])
666 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
667 cinfo->num_components*DCTSIZE2*sizeof(int));
668 coef_bit_ptr = & cinfo->coef_bits[0][0];
669 for (ci = 0; ci < cinfo->num_components; ci++)
670 for (i = 0; i < DCTSIZE2; i++)
671 *coef_bit_ptr++ = -1;
674 #endif /* D_PROGRESSIVE_SUPPORTED */