4 * Copyright (C) 1995, 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.
8 * This file contains Huffman entropy decoding routines for progressive JPEG.
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.
17 #define JPEG_INTERNALS
20 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
23 #ifdef D_PROGRESSIVE_SUPPORTED
26 * Expanded entropy decoder object for progressive Huffman decoding.
28 * The savable_state subrecord contains fields that change within an MCU,
29 * but must not be updated permanently until we complete the MCU.
33 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
34 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
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.
42 #ifndef NO_STRUCT_ASSIGN
43 #define ASSIGN_STATE(dest,src) ((dest) = (src))
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])
57 struct jpeg_entropy_decoder pub; /* public fields */
59 /* These fields are loaded into local variables at start of each MCU.
60 * In case of suspension, we exit WITHOUT updating them.
62 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
63 savable_state saved; /* Other state at start of MCU */
65 /* These fields are NOT loaded into local working state. */
66 unsigned int restarts_to_go; /* MCUs left in this restart interval */
68 /* Pointers to derived tables (these workspaces have image lifespan) */
69 d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
71 d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
72 } phuff_entropy_decoder;
74 typedef phuff_entropy_decoder * phuff_entropy_ptr;
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));
88 * Initialize for a Huffman-compressed scan.
92 start_pass_phuff_decoder (j_decompress_ptr cinfo)
94 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
95 boolean is_DC_band, bad;
98 jpeg_component_info * compptr;
100 is_DC_band = (cinfo->Ss == 0);
102 /* Validate scan parameters */
108 /* need not check Ss/Se < 0 since they came from unsigned bytes */
109 if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
111 /* AC scans may have only one component */
112 if (cinfo->comps_in_scan != 1)
115 if (cinfo->Ah != 0) {
116 /* Successive approximation refinement scan: must have Al = Ah-1. */
117 if (cinfo->Al != cinfo->Ah-1)
120 if (cinfo->Al > 13) /* need not check for < 0 */
123 ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
124 cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
125 /* Update progression status, and verify that scan order is legal.
126 * Note that inter-scan inconsistencies are treated as warnings
127 * not fatal errors ... not clear if this is right way to behave.
129 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
130 int cindex = cinfo->cur_comp_info[ci]->component_index;
131 coef_bit_ptr = & cinfo->coef_bits[cindex][0];
132 if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
133 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
134 for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
135 int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
136 if (cinfo->Ah != expected)
137 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
138 coef_bit_ptr[coefi] = cinfo->Al;
142 /* Select MCU decoding routine */
143 if (cinfo->Ah == 0) {
145 entropy->pub.decode_mcu = decode_mcu_DC_first;
147 entropy->pub.decode_mcu = decode_mcu_AC_first;
150 entropy->pub.decode_mcu = decode_mcu_DC_refine;
152 entropy->pub.decode_mcu = decode_mcu_AC_refine;
155 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
156 compptr = cinfo->cur_comp_info[ci];
157 /* Make sure requested tables are present, and compute derived tables.
158 * We may build same derived table more than once, but it's not expensive.
161 if (cinfo->Ah == 0) { /* DC refinement needs no table */
162 tbl = compptr->dc_tbl_no;
163 if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
164 cinfo->dc_huff_tbl_ptrs[tbl] == NULL)
165 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
166 jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[tbl],
167 & entropy->derived_tbls[tbl]);
170 tbl = compptr->ac_tbl_no;
171 if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
172 cinfo->ac_huff_tbl_ptrs[tbl] == NULL)
173 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
174 jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[tbl],
175 & entropy->derived_tbls[tbl]);
176 /* remember the single active table */
177 entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
179 /* Initialize DC predictions to 0 */
180 entropy->saved.last_dc_val[ci] = 0;
183 /* Initialize bitread state variables */
184 entropy->bitstate.bits_left = 0;
185 entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
186 entropy->bitstate.printed_eod = FALSE;
188 /* Initialize private state variables */
189 entropy->saved.EOBRUN = 0;
191 /* Initialize restart counter */
192 entropy->restarts_to_go = cinfo->restart_interval;
197 * Figure F.12: extend sign bit.
198 * On some machines, a shift and add will be faster than a table lookup.
203 #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
207 #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
209 static const int extend_test[16] = /* entry n is 2**(n-1) */
210 { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
211 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
213 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
214 { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
215 ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
216 ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
217 ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
219 #endif /* AVOID_TABLES */
223 * Check for a restart marker & resynchronize decoder.
224 * Returns FALSE if must suspend.
228 process_restart (j_decompress_ptr cinfo)
230 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
233 /* Throw away any unused bits remaining in bit buffer; */
234 /* include any full bytes in next_marker's count of discarded bytes */
235 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
236 entropy->bitstate.bits_left = 0;
238 /* Advance past the RSTn marker */
239 if (! (*cinfo->marker->read_restart_marker) (cinfo))
242 /* Re-initialize DC predictions to 0 */
243 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
244 entropy->saved.last_dc_val[ci] = 0;
245 /* Re-init EOB run count, too */
246 entropy->saved.EOBRUN = 0;
248 /* Reset restart counter */
249 entropy->restarts_to_go = cinfo->restart_interval;
251 /* Next segment can get another out-of-data warning */
252 entropy->bitstate.printed_eod = FALSE;
259 * Huffman MCU decoding.
260 * Each of these routines decodes and returns one MCU's worth of
261 * Huffman-compressed coefficients.
262 * The coefficients are reordered from zigzag order into natural array order,
263 * but are not dequantized.
265 * The i'th block of the MCU is stored into the block pointed to by
266 * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
268 * We return FALSE if data source requested suspension. In that case no
269 * changes have been made to permanent state. (Exception: some output
270 * coefficients may already have been assigned. This is harmless for
271 * spectral selection, since we'll just re-assign them on the next call.
272 * Successive approximation AC refinement has to be more careful, however.)
276 * MCU decoding for DC initial scan (either spectral selection,
277 * or first pass of successive approximation).
281 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
283 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
291 jpeg_component_info * compptr;
293 /* Process restart marker if needed; may have to suspend */
294 if (cinfo->restart_interval) {
295 if (entropy->restarts_to_go == 0)
296 if (! process_restart(cinfo))
300 /* Load up working state */
301 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
302 ASSIGN_STATE(state, entropy->saved);
304 /* Outer loop handles each block in the MCU */
306 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
307 block = MCU_data[blkn];
308 ci = cinfo->MCU_membership[blkn];
309 compptr = cinfo->cur_comp_info[ci];
310 tbl = entropy->derived_tbls[compptr->dc_tbl_no];
312 /* Decode a single block's worth of coefficients */
314 /* Section F.2.2.1: decode the DC coefficient difference */
315 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
317 CHECK_BIT_BUFFER(br_state, s, return FALSE);
319 s = HUFF_EXTEND(r, s);
322 /* Convert DC difference to actual value, update last_dc_val */
323 s += state.last_dc_val[ci];
324 state.last_dc_val[ci] = s;
325 /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
326 (*block)[0] = (JCOEF) (s << Al);
329 /* Completed MCU, so update state */
330 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
331 ASSIGN_STATE(entropy->saved, state);
333 /* Account for restart interval (no-op if not using restarts) */
334 entropy->restarts_to_go--;
341 * MCU decoding for AC initial scan (either spectral selection,
342 * or first pass of successive approximation).
346 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
348 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
351 register int s, k, r;
357 /* Process restart marker if needed; may have to suspend */
358 if (cinfo->restart_interval) {
359 if (entropy->restarts_to_go == 0)
360 if (! process_restart(cinfo))
364 /* Load up working state.
365 * We can avoid loading/saving bitread state if in an EOB run.
367 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
369 /* There is always only one block per MCU */
371 if (EOBRUN > 0) /* if it's a band of zeroes... */
372 EOBRUN--; /* ...process it now (we do nothing) */
374 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
376 tbl = entropy->ac_derived_tbl;
378 for (k = cinfo->Ss; k <= Se; k++) {
379 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
384 CHECK_BIT_BUFFER(br_state, s, return FALSE);
386 s = HUFF_EXTEND(r, s);
387 /* Scale and output coefficient in natural (dezigzagged) order */
388 (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
390 if (r == 15) { /* ZRL */
391 k += 15; /* skip 15 zeroes in band */
392 } else { /* EOBr, run length is 2^r + appended bits */
394 if (r) { /* EOBr, r > 0 */
395 CHECK_BIT_BUFFER(br_state, r, return FALSE);
399 EOBRUN--; /* this band is processed at this moment */
400 break; /* force end-of-band */
405 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
408 /* Completed MCU, so update state */
409 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
411 /* Account for restart interval (no-op if not using restarts) */
412 entropy->restarts_to_go--;
419 * MCU decoding for DC successive approximation refinement scan.
420 * Note: we assume such scans can be multi-component, although the spec
421 * is not very clear on the point.
425 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
427 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
428 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
433 /* Process restart marker if needed; may have to suspend */
434 if (cinfo->restart_interval) {
435 if (entropy->restarts_to_go == 0)
436 if (! process_restart(cinfo))
440 /* Load up working state */
441 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
443 /* Outer loop handles each block in the MCU */
445 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
446 block = MCU_data[blkn];
448 /* Encoded data is simply the next bit of the two's-complement DC value */
449 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
452 /* Note: since we use |=, repeating the assignment later is safe */
455 /* Completed MCU, so update state */
456 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
458 /* Account for restart interval (no-op if not using restarts) */
459 entropy->restarts_to_go--;
466 * MCU decoding for AC successive approximation refinement scan.
470 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
472 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
474 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
475 int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
476 register int s, k, r;
483 int newnz_pos[DCTSIZE2];
485 /* Process restart marker if needed; may have to suspend */
486 if (cinfo->restart_interval) {
487 if (entropy->restarts_to_go == 0)
488 if (! process_restart(cinfo))
492 /* Load up working state */
493 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
494 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
496 /* There is always only one block per MCU */
498 tbl = entropy->ac_derived_tbl;
500 /* If we are forced to suspend, we must undo the assignments to any newly
501 * nonzero coefficients in the block, because otherwise we'd get confused
502 * next time about which coefficients were already nonzero.
503 * But we need not undo addition of bits to already-nonzero coefficients;
504 * instead, we can test the current bit position to see if we already did it.
508 /* initialize coefficient loop counter to start of band */
512 for (; k <= Se; k++) {
513 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
517 if (s != 1) /* size of new coef should always be 1 */
518 WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
519 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
521 s = p1; /* newly nonzero coef is positive */
523 s = m1; /* newly nonzero coef is negative */
526 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
528 CHECK_BIT_BUFFER(br_state, r, goto undoit);
532 break; /* rest of block is handled by EOB logic */
534 /* note s = 0 for processing ZRL */
536 /* Advance over already-nonzero coefs and r still-zero coefs,
537 * appending correction bits to the nonzeroes. A correction bit is 1
538 * if the absolute value of the coefficient must be increased.
541 thiscoef = *block + jpeg_natural_order[k];
542 if (*thiscoef != 0) {
543 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
545 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
554 break; /* reached target zero coefficient */
559 int pos = jpeg_natural_order[k];
560 /* Output newly nonzero coefficient */
561 (*block)[pos] = (JCOEF) s;
562 /* Remember its position in case we have to suspend */
563 newnz_pos[num_newnz++] = pos;
569 /* Scan any remaining coefficient positions after the end-of-band
570 * (the last newly nonzero coefficient, if any). Append a correction
571 * bit to each already-nonzero coefficient. A correction bit is 1
572 * if the absolute value of the coefficient must be increased.
574 for (; k <= Se; k++) {
575 thiscoef = *block + jpeg_natural_order[k];
576 if (*thiscoef != 0) {
577 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
579 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
588 /* Count one block completed in EOB run */
592 /* Completed MCU, so update state */
593 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
594 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
596 /* Account for restart interval (no-op if not using restarts) */
597 entropy->restarts_to_go--;
602 /* Re-zero any output coefficients that we made newly nonzero */
603 while (num_newnz > 0)
604 (*block)[newnz_pos[--num_newnz]] = 0;
611 * Module initialization routine for progressive Huffman entropy decoding.
615 jinit_phuff_decoder (j_decompress_ptr cinfo)
617 phuff_entropy_ptr entropy;
621 entropy = (phuff_entropy_ptr)
622 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
623 SIZEOF(phuff_entropy_decoder));
624 cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
625 entropy->pub.start_pass = start_pass_phuff_decoder;
627 /* Mark derived tables unallocated */
628 for (i = 0; i < NUM_HUFF_TBLS; i++) {
629 entropy->derived_tbls[i] = NULL;
632 /* Create progression status table */
633 cinfo->coef_bits = (int (*)[DCTSIZE2])
634 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
635 cinfo->num_components*DCTSIZE2*SIZEOF(int));
636 coef_bit_ptr = & cinfo->coef_bits[0][0];
637 for (ci = 0; ci < cinfo->num_components; ci++)
638 for (i = 0; i < DCTSIZE2; i++)
639 *coef_bit_ptr++ = -1;
642 #endif /* D_PROGRESSIVE_SUPPORTED */