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.
10 * This file contains Huffman entropy decoding routines for progressive JPEG.
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.
19 #define JPEG_INTERNALS
22 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
25 #ifdef D_PROGRESSIVE_SUPPORTED
28 * Expanded entropy decoder object for progressive Huffman decoding.
30 * The savable_state subrecord contains fields that change within an MCU,
31 * but must not be updated permanently until we complete the MCU.
35 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
36 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
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.
44 #ifndef NO_STRUCT_ASSIGN
45 #define ASSIGN_STATE(dest,src) ((dest) = (src))
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])
59 struct jpeg_entropy_decoder pub; /* public fields */
61 /* These fields are loaded into local variables at start of each MCU.
62 * In case of suspension, we exit WITHOUT updating them.
64 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
65 savable_state saved; /* Other state at start of MCU */
67 /* These fields are NOT loaded into local working state. */
68 unsigned int restarts_to_go; /* MCUs left in this restart interval */
70 /* Pointers to derived tables (these workspaces have image lifespan) */
71 d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
73 d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
74 } phuff_entropy_decoder;
76 typedef phuff_entropy_decoder * phuff_entropy_ptr;
78 /* Forward declarations */
79 METHODDEF(boolean) decode_mcu_DC_first (j_decompress_ptr cinfo,
81 METHODDEF(boolean) decode_mcu_AC_first (j_decompress_ptr cinfo,
83 METHODDEF(boolean) decode_mcu_DC_refine (j_decompress_ptr cinfo,
85 METHODDEF(boolean) decode_mcu_AC_refine (j_decompress_ptr cinfo,
90 * Initialize for a Huffman-compressed scan.
94 start_pass_phuff_decoder (j_decompress_ptr cinfo)
96 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
97 boolean is_DC_band, bad;
99 d_derived_tbl **pdtbl;
101 jpeg_component_info * compptr;
103 is_DC_band = (cinfo->Ss == 0);
105 /* Validate scan parameters */
111 /* need not check Ss/Se < 0 since they came from unsigned bytes */
112 if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
114 /* AC scans may have only one component */
115 if (cinfo->comps_in_scan != 1)
118 if (cinfo->Ah != 0) {
119 /* Successive approximation refinement scan: must have Al = Ah-1. */
120 if (cinfo->Al != cinfo->Ah-1)
123 if (cinfo->Al > 13) /* need not check for < 0 */
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.
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.
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;
151 /* Select MCU decoding routine */
152 if (cinfo->Ah == 0) {
154 entropy->pub.decode_mcu = decode_mcu_DC_first;
156 entropy->pub.decode_mcu = decode_mcu_AC_first;
159 entropy->pub.decode_mcu = decode_mcu_DC_refine;
161 entropy->pub.decode_mcu = decode_mcu_AC_refine;
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.
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);
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];
182 /* Initialize DC predictions to 0 */
183 entropy->saved.last_dc_val[ci] = 0;
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;
191 /* Initialize private state variables */
192 entropy->saved.EOBRUN = 0;
194 /* Initialize restart counter */
195 entropy->restarts_to_go = cinfo->restart_interval;
200 * Figure F.12: extend sign bit.
201 * On some machines, a shift and add will be faster than a table lookup.
207 #define NEG_1 ((unsigned)-1)
208 #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((NEG_1)<<(s)) + 1) : (x))
212 #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
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 };
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 };
224 #endif /* AVOID_TABLES */
228 * Check for a restart marker & resynchronize decoder.
229 * Returns FALSE if must suspend.
233 process_restart (j_decompress_ptr cinfo)
235 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
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;
243 /* Advance past the RSTn marker */
244 if (! (*cinfo->marker->read_restart_marker) (cinfo))
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;
253 /* Reset restart counter */
254 entropy->restarts_to_go = cinfo->restart_interval;
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.
261 if (cinfo->unread_marker == 0)
262 entropy->pub.insufficient_data = FALSE;
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.
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.
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.)
286 * MCU decoding for DC initial scan (either spectral selection,
287 * or first pass of successive approximation).
291 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
293 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
301 jpeg_component_info * compptr;
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))
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.
313 if (! entropy->pub.insufficient_data) {
315 /* Load up working state */
316 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
317 ASSIGN_STATE(state, entropy->saved);
319 /* Outer loop handles each block in the MCU */
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];
327 /* Decode a single block's worth of coefficients */
329 /* Section F.2.2.1: decode the DC coefficient difference */
330 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
332 CHECK_BIT_BUFFER(br_state, s, return FALSE);
334 s = HUFF_EXTEND(r, s);
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);
344 /* Completed MCU, so update state */
345 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
346 ASSIGN_STATE(entropy->saved, state);
349 /* Account for restart interval (no-op if not using restarts) */
350 entropy->restarts_to_go--;
357 * MCU decoding for AC initial scan (either spectral selection,
358 * or first pass of successive approximation).
362 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
364 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
367 register int s, k, r;
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))
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.
383 if (! entropy->pub.insufficient_data) {
385 /* Load up working state.
386 * We can avoid loading/saving bitread state if in an EOB run.
388 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
390 /* There is always only one block per MCU */
392 if (EOBRUN > 0) /* if it's a band of zeroes... */
393 EOBRUN--; /* ...process it now (we do nothing) */
395 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
397 tbl = entropy->ac_derived_tbl;
399 for (k = cinfo->Ss; k <= Se; k++) {
400 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
405 CHECK_BIT_BUFFER(br_state, s, return FALSE);
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);
411 if (r == 15) { /* ZRL */
412 k += 15; /* skip 15 zeroes in band */
413 } else { /* EOBr, run length is 2^r + appended bits */
415 if (r) { /* EOBr, r > 0 */
416 CHECK_BIT_BUFFER(br_state, r, return FALSE);
420 EOBRUN--; /* this band is processed at this moment */
421 break; /* force end-of-band */
426 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
429 /* Completed MCU, so update state */
430 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
433 /* Account for restart interval (no-op if not using restarts) */
434 entropy->restarts_to_go--;
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.
447 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
449 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
450 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
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))
462 /* Not worth the cycles to check insufficient_data here,
463 * since we will not change the data anyway if we read zeroes.
466 /* Load up working state */
467 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
469 /* Outer loop handles each block in the MCU */
471 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
472 block = MCU_data[blkn];
474 /* Encoded data is simply the next bit of the two's-complement DC value */
475 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
478 /* Note: since we use |=, repeating the assignment later is safe */
481 /* Completed MCU, so update state */
482 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
484 /* Account for restart interval (no-op if not using restarts) */
485 entropy->restarts_to_go--;
492 * MCU decoding for AC successive approximation refinement scan.
496 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
498 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
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;
509 int newnz_pos[DCTSIZE2];
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))
518 /* If we've run out of data, don't modify the MCU.
520 if (! entropy->pub.insufficient_data) {
522 /* Load up working state */
523 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
524 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
526 /* There is always only one block per MCU */
528 tbl = entropy->ac_derived_tbl;
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.
538 /* initialize coefficient loop counter to start of band */
542 for (; k <= Se; k++) {
543 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
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);
551 s = p1; /* newly nonzero coef is positive */
553 s = m1; /* newly nonzero coef is negative */
556 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
558 CHECK_BIT_BUFFER(br_state, r, goto undoit);
562 break; /* rest of block is handled by EOB logic */
564 /* note s = 0 for processing ZRL */
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.
571 thiscoef = *block + jpeg_natural_order[k];
572 if (*thiscoef != 0) {
573 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
575 if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
584 break; /* reached target zero coefficient */
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;
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.
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);
609 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
618 /* Count one block completed in EOB run */
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 */
627 /* Account for restart interval (no-op if not using restarts) */
628 entropy->restarts_to_go--;
633 /* Re-zero any output coefficients that we made newly nonzero */
634 while (num_newnz > 0)
635 (*block)[newnz_pos[--num_newnz]] = 0;
642 * Module initialization routine for progressive Huffman entropy decoding.
646 jinit_phuff_decoder (j_decompress_ptr cinfo)
648 phuff_entropy_ptr entropy;
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;
658 /* Mark derived tables unallocated */
659 for (i = 0; i < NUM_HUFF_TBLS; i++) {
660 entropy->derived_tbls[i] = NULL;
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;
673 #endif /* D_PROGRESSIVE_SUPPORTED */