2 * Modified by Kenichi Kurimoto
3 * for LEON MJPEG project
8 * Copyright (C) 1995-1997, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
12 * This file contains Huffman entropy decoding routines for progressive JPEG.
14 * Much of the complexity here has to do with supporting input suspension.
15 * If the data source module demands suspension, we want to be able to back
16 * up to the start of the current MCU. To do this, we copy state variables
17 * into local working storage, and update them back to the permanent
18 * storage only upon successful completion of an MCU.
21 #define JPEG_INTERNALS
24 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
27 #ifdef D_PROGRESSIVE_SUPPORTED
30 * Expanded entropy decoder object for progressive Huffman decoding.
32 * The savable_state subrecord contains fields that change within an MCU,
33 * but must not be updated permanently until we complete the MCU.
37 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
38 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
41 /* This macro is to work around compilers with missing or broken
42 * structure assignment. You'll need to fix this code if you have
43 * such a compiler and you change MAX_COMPS_IN_SCAN.
46 #ifndef NO_STRUCT_ASSIGN
47 #define ASSIGN_STATE(dest,src) ((dest) = (src))
49 #if MAX_COMPS_IN_SCAN == 4
50 #define ASSIGN_STATE(dest,src) \
51 ((dest).EOBRUN = (src).EOBRUN, \
52 (dest).last_dc_val[0] = (src).last_dc_val[0], \
53 (dest).last_dc_val[1] = (src).last_dc_val[1], \
54 (dest).last_dc_val[2] = (src).last_dc_val[2], \
55 (dest).last_dc_val[3] = (src).last_dc_val[3])
61 struct jpeg_entropy_decoder pub; /* public fields */
63 /* These fields are loaded into local variables at start of each MCU.
64 * In case of suspension, we exit WITHOUT updating them.
66 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
67 savable_state saved; /* Other state at start of MCU */
69 /* These fields are NOT loaded into local working state. */
70 unsigned int restarts_to_go; /* MCUs left in this restart interval */
72 /* Pointers to derived tables (these workspaces have image lifespan) */
73 d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
75 d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
76 } phuff_entropy_decoder;
78 typedef phuff_entropy_decoder * phuff_entropy_ptr;
80 /* Forward declarations */
81 METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
82 JBLOCKROW *MCU_data));
83 METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
84 JBLOCKROW *MCU_data));
85 METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
86 JBLOCKROW *MCU_data));
87 METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
88 JBLOCKROW *MCU_data));
92 * Initialize for a Huffman-compressed scan.
96 start_pass_phuff_decoder (j_decompress_ptr cinfo)
98 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
99 boolean is_DC_band, bad;
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 jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
174 & entropy->derived_tbls[tbl]);
177 tbl = compptr->ac_tbl_no;
178 jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
179 & entropy->derived_tbls[tbl]);
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.
207 #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
211 #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
213 static const int extend_test[16] = /* entry n is 2**(n-1) */
214 { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
215 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
217 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
218 { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
219 ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
220 ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
221 ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
223 #endif /* AVOID_TABLES */
227 * Check for a restart marker & resynchronize decoder.
228 * Returns FALSE if must suspend.
232 process_restart (j_decompress_ptr cinfo)
234 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
237 /* Throw away any unused bits remaining in bit buffer; */
238 /* include any full bytes in next_marker's count of discarded bytes */
239 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
240 entropy->bitstate.bits_left = 0;
242 /* Advance past the RSTn marker */
243 if (! (*cinfo->marker->read_restart_marker) (cinfo))
246 /* Re-initialize DC predictions to 0 */
247 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
248 entropy->saved.last_dc_val[ci] = 0;
249 /* Re-init EOB run count, too */
250 entropy->saved.EOBRUN = 0;
252 /* Reset restart counter */
253 entropy->restarts_to_go = cinfo->restart_interval;
255 /* Reset out-of-data flag, unless read_restart_marker left us smack up
256 * against a marker. In that case we will end up treating the next data
257 * segment as empty, and we can avoid producing bogus output pixels by
258 * leaving the flag set.
260 if (cinfo->unread_marker == 0)
261 entropy->pub.insufficient_data = FALSE;
268 * Huffman MCU decoding.
269 * Each of these routines decodes and returns one MCU's worth of
270 * Huffman-compressed coefficients.
271 * The coefficients are reordered from zigzag order into natural array order,
272 * but are not dequantized.
274 * The i'th block of the MCU is stored into the block pointed to by
275 * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
277 * We return FALSE if data source requested suspension. In that case no
278 * changes have been made to permanent state. (Exception: some output
279 * coefficients may already have been assigned. This is harmless for
280 * spectral selection, since we'll just re-assign them on the next call.
281 * Successive approximation AC refinement has to be more careful, however.)
285 * MCU decoding for DC initial scan (either spectral selection,
286 * or first pass of successive approximation).
290 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
292 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
300 jpeg_component_info * compptr;
302 /* Process restart marker if needed; may have to suspend */
303 if (cinfo->restart_interval) {
304 if (entropy->restarts_to_go == 0)
305 if (! process_restart(cinfo))
309 /* If we've run out of data, just leave the MCU set to zeroes.
310 * This way, we return uniform gray for the remainder of the segment.
312 if (! entropy->pub.insufficient_data) {
314 /* Load up working state */
315 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
316 ASSIGN_STATE(state, entropy->saved);
318 /* Outer loop handles each block in the MCU */
320 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
321 block = MCU_data[blkn];
322 ci = cinfo->MCU_membership[blkn];
323 compptr = cinfo->cur_comp_info[ci];
324 tbl = entropy->derived_tbls[compptr->dc_tbl_no];
326 /* Decode a single block's worth of coefficients */
328 /* Section F.2.2.1: decode the DC coefficient difference */
329 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
331 CHECK_BIT_BUFFER(br_state, s, return FALSE);
333 s = HUFF_EXTEND(r, s);
336 /* Convert DC difference to actual value, update last_dc_val */
337 s += state.last_dc_val[ci];
338 state.last_dc_val[ci] = s;
339 /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
340 (*block)[0] = (JCOEF) (s << Al);
343 /* Completed MCU, so update state */
344 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
345 ASSIGN_STATE(entropy->saved, state);
348 /* Account for restart interval (no-op if not using restarts) */
349 entropy->restarts_to_go--;
356 * MCU decoding for AC initial scan (either spectral selection,
357 * or first pass of successive approximation).
361 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
363 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
366 register int s, k, r;
372 /* Process restart marker if needed; may have to suspend */
373 if (cinfo->restart_interval) {
374 if (entropy->restarts_to_go == 0)
375 if (! process_restart(cinfo))
379 /* If we've run out of data, just leave the MCU set to zeroes.
380 * This way, we return uniform gray for the remainder of the segment.
382 if (! entropy->pub.insufficient_data) {
384 /* Load up working state.
385 * We can avoid loading/saving bitread state if in an EOB run.
387 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
389 /* There is always only one block per MCU */
391 if (EOBRUN > 0) /* if it's a band of zeroes... */
392 EOBRUN--; /* ...process it now (we do nothing) */
394 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
396 tbl = entropy->ac_derived_tbl;
398 for (k = cinfo->Ss; k <= Se; k++) {
399 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
404 CHECK_BIT_BUFFER(br_state, s, return FALSE);
406 s = HUFF_EXTEND(r, s);
407 /* Scale and output coefficient in natural (dezigzagged) order */
408 (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
410 if (r == 15) { /* ZRL */
411 k += 15; /* skip 15 zeroes in band */
412 } else { /* EOBr, run length is 2^r + appended bits */
414 if (r) { /* EOBr, r > 0 */
415 CHECK_BIT_BUFFER(br_state, r, return FALSE);
419 EOBRUN--; /* this band is processed at this moment */
420 break; /* force end-of-band */
425 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
428 /* Completed MCU, so update state */
429 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
432 /* Account for restart interval (no-op if not using restarts) */
433 entropy->restarts_to_go--;
440 * MCU decoding for DC successive approximation refinement scan.
441 * Note: we assume such scans can be multi-component, although the spec
442 * is not very clear on the point.
446 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
448 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
449 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
454 /* Process restart marker if needed; may have to suspend */
455 if (cinfo->restart_interval) {
456 if (entropy->restarts_to_go == 0)
457 if (! process_restart(cinfo))
461 /* Not worth the cycles to check insufficient_data here,
462 * since we will not change the data anyway if we read zeroes.
465 /* Load up working state */
466 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
468 /* Outer loop handles each block in the MCU */
470 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
471 block = MCU_data[blkn];
473 /* Encoded data is simply the next bit of the two's-complement DC value */
474 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
477 /* Note: since we use |=, repeating the assignment later is safe */
480 /* Completed MCU, so update state */
481 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
483 /* Account for restart interval (no-op if not using restarts) */
484 entropy->restarts_to_go--;
491 * MCU decoding for AC successive approximation refinement scan.
495 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
497 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
499 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
500 int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
501 register int s, k, r;
508 int newnz_pos[DCTSIZE2];
510 /* Process restart marker if needed; may have to suspend */
511 if (cinfo->restart_interval) {
512 if (entropy->restarts_to_go == 0)
513 if (! process_restart(cinfo))
517 /* If we've run out of data, don't modify the MCU.
519 if (! entropy->pub.insufficient_data) {
521 /* Load up working state */
522 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
523 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
525 /* There is always only one block per MCU */
527 tbl = entropy->ac_derived_tbl;
529 /* If we are forced to suspend, we must undo the assignments to any newly
530 * nonzero coefficients in the block, because otherwise we'd get confused
531 * next time about which coefficients were already nonzero.
532 * But we need not undo addition of bits to already-nonzero coefficients;
533 * instead, we can test the current bit to see if we already did it.
537 /* initialize coefficient loop counter to start of band */
541 for (; k <= Se; k++) {
542 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
546 if (s != 1) /* size of new coef should always be 1 */
547 WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
548 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
550 s = p1; /* newly nonzero coef is positive */
552 s = m1; /* newly nonzero coef is negative */
555 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
557 CHECK_BIT_BUFFER(br_state, r, goto undoit);
561 break; /* rest of block is handled by EOB logic */
563 /* note s = 0 for processing ZRL */
565 /* Advance over already-nonzero coefs and r still-zero coefs,
566 * appending correction bits to the nonzeroes. A correction bit is 1
567 * if the absolute value of the coefficient must be increased.
570 thiscoef = *block + jpeg_natural_order[k];
571 if (*thiscoef != 0) {
572 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
574 if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
583 break; /* reached target zero coefficient */
588 int pos = jpeg_natural_order[k];
589 /* Output newly nonzero coefficient */
590 (*block)[pos] = (JCOEF) s;
591 /* Remember its position in case we have to suspend */
592 newnz_pos[num_newnz++] = pos;
598 /* Scan any remaining coefficient positions after the end-of-band
599 * (the last newly nonzero coefficient, if any). Append a correction
600 * bit to each already-nonzero coefficient. A correction bit is 1
601 * if the absolute value of the coefficient must be increased.
603 for (; k <= Se; k++) {
604 thiscoef = *block + jpeg_natural_order[k];
605 if (*thiscoef != 0) {
606 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
608 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
617 /* Count one block completed in EOB run */
621 /* Completed MCU, so update state */
622 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
623 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
626 /* Account for restart interval (no-op if not using restarts) */
627 entropy->restarts_to_go--;
632 /* Re-zero any output coefficients that we made newly nonzero */
633 while (num_newnz > 0)
634 (*block)[newnz_pos[--num_newnz]] = 0;
641 * Module initialization routine for progressive Huffman entropy decoding.
645 jinit_phuff_decoder (j_decompress_ptr cinfo)
647 phuff_entropy_ptr entropy;
651 entropy = (phuff_entropy_ptr)
652 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
653 SIZEOF(phuff_entropy_decoder));
654 cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
655 entropy->pub.start_pass = start_pass_phuff_decoder;
657 /* Mark derived tables unallocated */
658 for (i = 0; i < NUM_HUFF_TBLS; i++) {
659 entropy->derived_tbls[i] = NULL;
662 /* Create progression status table */
663 cinfo->coef_bits = (int (*)[DCTSIZE2])
664 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
665 cinfo->num_components*DCTSIZE2*SIZEOF(int));
666 coef_bit_ptr = & cinfo->coef_bits[0][0];
667 for (ci = 0; ci < cinfo->num_components; ci++)
668 for (i = 0; i < DCTSIZE2; i++)
669 *coef_bit_ptr++ = -1;
672 #endif /* D_PROGRESSIVE_SUPPORTED */