1 /* $XConsortium: jdphuff.c /main/2 1996/05/09 03:49:25 drk $ */
5 * Copyright (C) 1995-1996, Thomas G. Lane.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
9 * This file contains Huffman entropy decoding routines for progressive JPEG.
11 * Much of the complexity here has to do with supporting input suspension.
12 * If the data source module demands suspension, we want to be able to back
13 * up to the start of the current MCU. To do this, we copy state variables
14 * into local working storage, and update them back to the permanent
15 * storage only upon successful completion of an MCU.
18 #define JPEG_INTERNALS
21 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
24 #ifdef D_PROGRESSIVE_SUPPORTED
27 * Expanded entropy decoder object for progressive Huffman decoding.
29 * The savable_state subrecord contains fields that change within an MCU,
30 * but must not be updated permanently until we complete the MCU.
34 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
35 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
38 /* This macro is to work around compilers with missing or broken
39 * structure assignment. You'll need to fix this code if you have
40 * such a compiler and you change MAX_COMPS_IN_SCAN.
43 #ifndef NO_STRUCT_ASSIGN
44 #define ASSIGN_STATE(dest,src) ((dest) = (src))
46 #if MAX_COMPS_IN_SCAN == 4
47 #define ASSIGN_STATE(dest,src) \
48 ((dest).EOBRUN = (src).EOBRUN, \
49 (dest).last_dc_val[0] = (src).last_dc_val[0], \
50 (dest).last_dc_val[1] = (src).last_dc_val[1], \
51 (dest).last_dc_val[2] = (src).last_dc_val[2], \
52 (dest).last_dc_val[3] = (src).last_dc_val[3])
58 struct jpeg_entropy_decoder pub; /* public fields */
60 /* These fields are loaded into local variables at start of each MCU.
61 * In case of suspension, we exit WITHOUT updating them.
63 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
64 savable_state saved; /* Other state at start of MCU */
66 /* These fields are NOT loaded into local working state. */
67 unsigned int restarts_to_go; /* MCUs left in this restart interval */
69 /* Pointers to derived tables (these workspaces have image lifespan) */
70 d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
72 d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
73 } phuff_entropy_decoder;
75 typedef phuff_entropy_decoder * phuff_entropy_ptr;
77 /* Forward declarations */
78 METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
79 JBLOCKROW *MCU_data));
80 METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
81 JBLOCKROW *MCU_data));
82 METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
83 JBLOCKROW *MCU_data));
84 METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
85 JBLOCKROW *MCU_data));
89 * Initialize for a Huffman-compressed scan.
93 start_pass_phuff_decoder (j_decompress_ptr cinfo)
95 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
96 boolean is_DC_band, bad;
99 jpeg_component_info * compptr;
101 is_DC_band = (cinfo->Ss == 0);
103 /* Validate scan parameters */
109 /* need not check Ss/Se < 0 since they came from unsigned bytes */
110 if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
112 /* AC scans may have only one component */
113 if (cinfo->comps_in_scan != 1)
116 if (cinfo->Ah != 0) {
117 /* Successive approximation refinement scan: must have Al = Ah-1. */
118 if (cinfo->Al != cinfo->Ah-1)
121 if (cinfo->Al > 13) /* need not check for < 0 */
124 ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
125 cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
126 /* Update progression status, and verify that scan order is legal.
127 * Note that inter-scan inconsistencies are treated as warnings
128 * not fatal errors ... not clear if this is right way to behave.
130 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
131 int cindex = cinfo->cur_comp_info[ci]->component_index;
132 coef_bit_ptr = & cinfo->coef_bits[cindex][0];
133 if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
134 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
135 for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
136 int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
137 if (cinfo->Ah != expected)
138 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
139 coef_bit_ptr[coefi] = cinfo->Al;
143 /* Select MCU decoding routine */
144 if (cinfo->Ah == 0) {
146 entropy->pub.decode_mcu = decode_mcu_DC_first;
148 entropy->pub.decode_mcu = decode_mcu_AC_first;
151 entropy->pub.decode_mcu = decode_mcu_DC_refine;
153 entropy->pub.decode_mcu = decode_mcu_AC_refine;
156 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
157 compptr = cinfo->cur_comp_info[ci];
158 /* Make sure requested tables are present, and compute derived tables.
159 * We may build same derived table more than once, but it's not expensive.
162 if (cinfo->Ah == 0) { /* DC refinement needs no table */
163 tbl = compptr->dc_tbl_no;
164 if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
165 cinfo->dc_huff_tbl_ptrs[tbl] == NULL)
166 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
167 jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[tbl],
168 & entropy->derived_tbls[tbl]);
171 tbl = compptr->ac_tbl_no;
172 if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
173 cinfo->ac_huff_tbl_ptrs[tbl] == NULL)
174 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
175 jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[tbl],
176 & entropy->derived_tbls[tbl]);
177 /* remember the single active table */
178 entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
180 /* Initialize DC predictions to 0 */
181 entropy->saved.last_dc_val[ci] = 0;
184 /* Initialize bitread state variables */
185 entropy->bitstate.bits_left = 0;
186 entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
187 entropy->bitstate.printed_eod = FALSE;
189 /* Initialize private state variables */
190 entropy->saved.EOBRUN = 0;
192 /* Initialize restart counter */
193 entropy->restarts_to_go = cinfo->restart_interval;
198 * Figure F.12: extend sign bit.
199 * On some machines, a shift and add will be faster than a table lookup.
204 #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
208 #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
210 static const int extend_test[16] = /* entry n is 2**(n-1) */
211 { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
212 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
214 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
215 { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
216 ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
217 ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
218 ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
220 #endif /* AVOID_TABLES */
224 * Check for a restart marker & resynchronize decoder.
225 * Returns FALSE if must suspend.
229 process_restart (j_decompress_ptr cinfo)
231 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
234 /* Throw away any unused bits remaining in bit buffer; */
235 /* include any full bytes in next_marker's count of discarded bytes */
236 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
237 entropy->bitstate.bits_left = 0;
239 /* Advance past the RSTn marker */
240 if (! (*cinfo->marker->read_restart_marker) (cinfo))
243 /* Re-initialize DC predictions to 0 */
244 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
245 entropy->saved.last_dc_val[ci] = 0;
246 /* Re-init EOB run count, too */
247 entropy->saved.EOBRUN = 0;
249 /* Reset restart counter */
250 entropy->restarts_to_go = cinfo->restart_interval;
252 /* Next segment can get another out-of-data warning */
253 entropy->bitstate.printed_eod = FALSE;
260 * Huffman MCU decoding.
261 * Each of these routines decodes and returns one MCU's worth of
262 * Huffman-compressed coefficients.
263 * The coefficients are reordered from zigzag order into natural array order,
264 * but are not dequantized.
266 * The i'th block of the MCU is stored into the block pointed to by
267 * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
269 * We return FALSE if data source requested suspension. In that case no
270 * changes have been made to permanent state. (Exception: some output
271 * coefficients may already have been assigned. This is harmless for
272 * spectral selection, since we'll just re-assign them on the next call.
273 * Successive approximation AC refinement has to be more careful, however.)
277 * MCU decoding for DC initial scan (either spectral selection,
278 * or first pass of successive approximation).
282 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
284 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
292 jpeg_component_info * compptr;
294 /* Process restart marker if needed; may have to suspend */
295 if (cinfo->restart_interval) {
296 if (entropy->restarts_to_go == 0)
297 if (! process_restart(cinfo))
301 /* Load up working state */
302 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
303 ASSIGN_STATE(state, entropy->saved);
305 /* Outer loop handles each block in the MCU */
307 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
308 block = MCU_data[blkn];
309 ci = cinfo->MCU_membership[blkn];
310 compptr = cinfo->cur_comp_info[ci];
311 tbl = entropy->derived_tbls[compptr->dc_tbl_no];
313 /* Decode a single block's worth of coefficients */
315 /* Section F.2.2.1: decode the DC coefficient difference */
316 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
318 CHECK_BIT_BUFFER(br_state, s, return FALSE);
320 s = HUFF_EXTEND(r, s);
323 /* Convert DC difference to actual value, update last_dc_val */
324 s += state.last_dc_val[ci];
325 state.last_dc_val[ci] = s;
326 /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
327 (*block)[0] = (JCOEF) (s << Al);
330 /* Completed MCU, so update state */
331 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
332 ASSIGN_STATE(entropy->saved, state);
334 /* Account for restart interval (no-op if not using restarts) */
335 entropy->restarts_to_go--;
342 * MCU decoding for AC initial scan (either spectral selection,
343 * or first pass of successive approximation).
347 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
349 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
352 register int s, k, r;
358 /* Process restart marker if needed; may have to suspend */
359 if (cinfo->restart_interval) {
360 if (entropy->restarts_to_go == 0)
361 if (! process_restart(cinfo))
365 /* Load up working state.
366 * We can avoid loading/saving bitread state if in an EOB run.
368 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
370 /* There is always only one block per MCU */
372 if (EOBRUN > 0) /* if it's a band of zeroes... */
373 EOBRUN--; /* ...process it now (we do nothing) */
375 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
377 tbl = entropy->ac_derived_tbl;
379 for (k = cinfo->Ss; k <= Se; k++) {
380 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
385 CHECK_BIT_BUFFER(br_state, s, return FALSE);
387 s = HUFF_EXTEND(r, s);
388 /* Scale and output coefficient in natural (dezigzagged) order */
389 (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
391 if (r == 15) { /* ZRL */
392 k += 15; /* skip 15 zeroes in band */
393 } else { /* EOBr, run length is 2^r + appended bits */
395 if (r) { /* EOBr, r > 0 */
396 CHECK_BIT_BUFFER(br_state, r, return FALSE);
400 EOBRUN--; /* this band is processed at this moment */
401 break; /* force end-of-band */
406 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
409 /* Completed MCU, so update state */
410 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
412 /* Account for restart interval (no-op if not using restarts) */
413 entropy->restarts_to_go--;
420 * MCU decoding for DC successive approximation refinement scan.
421 * Note: we assume such scans can be multi-component, although the spec
422 * is not very clear on the point.
426 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
428 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
429 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
434 /* Process restart marker if needed; may have to suspend */
435 if (cinfo->restart_interval) {
436 if (entropy->restarts_to_go == 0)
437 if (! process_restart(cinfo))
441 /* Load up working state */
442 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
444 /* Outer loop handles each block in the MCU */
446 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
447 block = MCU_data[blkn];
449 /* Encoded data is simply the next bit of the two's-complement DC value */
450 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
453 /* Note: since we use |=, repeating the assignment later is safe */
456 /* Completed MCU, so update state */
457 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
459 /* Account for restart interval (no-op if not using restarts) */
460 entropy->restarts_to_go--;
467 * MCU decoding for AC successive approximation refinement scan.
471 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
473 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
475 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
476 int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
477 register int s, k, r;
484 int newnz_pos[DCTSIZE2];
486 /* Process restart marker if needed; may have to suspend */
487 if (cinfo->restart_interval) {
488 if (entropy->restarts_to_go == 0)
489 if (! process_restart(cinfo))
493 /* Load up working state */
494 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
495 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
497 /* There is always only one block per MCU */
499 tbl = entropy->ac_derived_tbl;
501 /* If we are forced to suspend, we must undo the assignments to any newly
502 * nonzero coefficients in the block, because otherwise we'd get confused
503 * next time about which coefficients were already nonzero.
504 * But we need not undo addition of bits to already-nonzero coefficients;
505 * instead, we can test the current bit position to see if we already did it.
509 /* initialize coefficient loop counter to start of band */
513 for (; k <= Se; k++) {
514 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
518 if (s != 1) /* size of new coef should always be 1 */
519 WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
520 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
522 s = p1; /* newly nonzero coef is positive */
524 s = m1; /* newly nonzero coef is negative */
527 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
529 CHECK_BIT_BUFFER(br_state, r, goto undoit);
533 break; /* rest of block is handled by EOB logic */
535 /* note s = 0 for processing ZRL */
537 /* Advance over already-nonzero coefs and r still-zero coefs,
538 * appending correction bits to the nonzeroes. A correction bit is 1
539 * if the absolute value of the coefficient must be increased.
542 thiscoef = *block + jpeg_natural_order[k];
543 if (*thiscoef != 0) {
544 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
546 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
555 break; /* reached target zero coefficient */
560 int pos = jpeg_natural_order[k];
561 /* Output newly nonzero coefficient */
562 (*block)[pos] = (JCOEF) s;
563 /* Remember its position in case we have to suspend */
564 newnz_pos[num_newnz++] = pos;
570 /* Scan any remaining coefficient positions after the end-of-band
571 * (the last newly nonzero coefficient, if any). Append a correction
572 * bit to each already-nonzero coefficient. A correction bit is 1
573 * if the absolute value of the coefficient must be increased.
575 for (; k <= Se; k++) {
576 thiscoef = *block + jpeg_natural_order[k];
577 if (*thiscoef != 0) {
578 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
580 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
589 /* Count one block completed in EOB run */
593 /* Completed MCU, so update state */
594 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
595 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
597 /* Account for restart interval (no-op if not using restarts) */
598 entropy->restarts_to_go--;
603 /* Re-zero any output coefficients that we made newly nonzero */
604 while (num_newnz > 0)
605 (*block)[newnz_pos[--num_newnz]] = 0;
612 * Module initialization routine for progressive Huffman entropy decoding.
616 jinit_phuff_decoder (j_decompress_ptr cinfo)
618 phuff_entropy_ptr entropy;
622 entropy = (phuff_entropy_ptr)
623 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
624 SIZEOF(phuff_entropy_decoder));
625 cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
626 entropy->pub.start_pass = start_pass_phuff_decoder;
628 /* Mark derived tables unallocated */
629 for (i = 0; i < NUM_HUFF_TBLS; i++) {
630 entropy->derived_tbls[i] = NULL;
633 /* Create progression status table */
634 cinfo->coef_bits = (int (*)[DCTSIZE2])
635 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
636 cinfo->num_components*DCTSIZE2*SIZEOF(int));
637 coef_bit_ptr = & cinfo->coef_bits[0][0];
638 for (ci = 0; ci < cinfo->num_components; ci++)
639 for (i = 0; i < DCTSIZE2; i++)
640 *coef_bit_ptr++ = -1;
643 #endif /* D_PROGRESSIVE_SUPPORTED */