2 * CDE - Common Desktop Environment
4 * Copyright (c) 1993-2012, The Open Group. All rights reserved.
6 * These libraries and programs are free software; you can
7 * redistribute them and/or modify them under the terms of the GNU
8 * Lesser General Public License as published by the Free Software
9 * Foundation; either version 2 of the License, or (at your option)
12 * These libraries and programs are distributed in the hope that
13 * they will be useful, but WITHOUT ANY WARRANTY; without even the
14 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU Lesser General Public License for more
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with these librararies and programs; if not, write
20 * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21 * Floor, Boston, MA 02110-1301 USA
23 /* $XConsortium: jdphuff.c /main/2 1996/05/09 03:49:25 drk $ */
27 * Copyright (C) 1995-1996, Thomas G. Lane.
28 * This file is part of the Independent JPEG Group's software.
29 * For conditions of distribution and use, see the accompanying README file.
31 * This file contains Huffman entropy decoding routines for progressive JPEG.
33 * Much of the complexity here has to do with supporting input suspension.
34 * If the data source module demands suspension, we want to be able to back
35 * up to the start of the current MCU. To do this, we copy state variables
36 * into local working storage, and update them back to the permanent
37 * storage only upon successful completion of an MCU.
40 #define JPEG_INTERNALS
43 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
46 #ifdef D_PROGRESSIVE_SUPPORTED
49 * Expanded entropy decoder object for progressive Huffman decoding.
51 * The savable_state subrecord contains fields that change within an MCU,
52 * but must not be updated permanently until we complete the MCU.
56 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
57 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
60 /* This macro is to work around compilers with missing or broken
61 * structure assignment. You'll need to fix this code if you have
62 * such a compiler and you change MAX_COMPS_IN_SCAN.
65 #ifndef NO_STRUCT_ASSIGN
66 #define ASSIGN_STATE(dest,src) ((dest) = (src))
68 #if MAX_COMPS_IN_SCAN == 4
69 #define ASSIGN_STATE(dest,src) \
70 ((dest).EOBRUN = (src).EOBRUN, \
71 (dest).last_dc_val[0] = (src).last_dc_val[0], \
72 (dest).last_dc_val[1] = (src).last_dc_val[1], \
73 (dest).last_dc_val[2] = (src).last_dc_val[2], \
74 (dest).last_dc_val[3] = (src).last_dc_val[3])
80 struct jpeg_entropy_decoder pub; /* public fields */
82 /* These fields are loaded into local variables at start of each MCU.
83 * In case of suspension, we exit WITHOUT updating them.
85 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
86 savable_state saved; /* Other state at start of MCU */
88 /* These fields are NOT loaded into local working state. */
89 unsigned int restarts_to_go; /* MCUs left in this restart interval */
91 /* Pointers to derived tables (these workspaces have image lifespan) */
92 d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
94 d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
95 } phuff_entropy_decoder;
97 typedef phuff_entropy_decoder * phuff_entropy_ptr;
99 /* Forward declarations */
100 METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
101 JBLOCKROW *MCU_data));
102 METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
103 JBLOCKROW *MCU_data));
104 METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
105 JBLOCKROW *MCU_data));
106 METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
107 JBLOCKROW *MCU_data));
111 * Initialize for a Huffman-compressed scan.
115 start_pass_phuff_decoder (j_decompress_ptr cinfo)
117 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
118 boolean is_DC_band, bad;
121 jpeg_component_info * compptr;
123 is_DC_band = (cinfo->Ss == 0);
125 /* Validate scan parameters */
131 /* need not check Ss/Se < 0 since they came from unsigned bytes */
132 if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
134 /* AC scans may have only one component */
135 if (cinfo->comps_in_scan != 1)
138 if (cinfo->Ah != 0) {
139 /* Successive approximation refinement scan: must have Al = Ah-1. */
140 if (cinfo->Al != cinfo->Ah-1)
143 if (cinfo->Al > 13) /* need not check for < 0 */
146 ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
147 cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
148 /* Update progression status, and verify that scan order is legal.
149 * Note that inter-scan inconsistencies are treated as warnings
150 * not fatal errors ... not clear if this is right way to behave.
152 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
153 int cindex = cinfo->cur_comp_info[ci]->component_index;
154 coef_bit_ptr = & cinfo->coef_bits[cindex][0];
155 if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
156 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
157 for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
158 int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
159 if (cinfo->Ah != expected)
160 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
161 coef_bit_ptr[coefi] = cinfo->Al;
165 /* Select MCU decoding routine */
166 if (cinfo->Ah == 0) {
168 entropy->pub.decode_mcu = decode_mcu_DC_first;
170 entropy->pub.decode_mcu = decode_mcu_AC_first;
173 entropy->pub.decode_mcu = decode_mcu_DC_refine;
175 entropy->pub.decode_mcu = decode_mcu_AC_refine;
178 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
179 compptr = cinfo->cur_comp_info[ci];
180 /* Make sure requested tables are present, and compute derived tables.
181 * We may build same derived table more than once, but it's not expensive.
184 if (cinfo->Ah == 0) { /* DC refinement needs no table */
185 tbl = compptr->dc_tbl_no;
186 if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
187 cinfo->dc_huff_tbl_ptrs[tbl] == NULL)
188 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
189 jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[tbl],
190 & entropy->derived_tbls[tbl]);
193 tbl = compptr->ac_tbl_no;
194 if (tbl < 0 || tbl >= NUM_HUFF_TBLS ||
195 cinfo->ac_huff_tbl_ptrs[tbl] == NULL)
196 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
197 jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[tbl],
198 & entropy->derived_tbls[tbl]);
199 /* remember the single active table */
200 entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
202 /* Initialize DC predictions to 0 */
203 entropy->saved.last_dc_val[ci] = 0;
206 /* Initialize bitread state variables */
207 entropy->bitstate.bits_left = 0;
208 entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
209 entropy->bitstate.printed_eod = FALSE;
211 /* Initialize private state variables */
212 entropy->saved.EOBRUN = 0;
214 /* Initialize restart counter */
215 entropy->restarts_to_go = cinfo->restart_interval;
220 * Figure F.12: extend sign bit.
221 * On some machines, a shift and add will be faster than a table lookup.
226 #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
230 #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
232 static const int extend_test[16] = /* entry n is 2**(n-1) */
233 { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
234 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
236 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
237 { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
238 ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
239 ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
240 ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
242 #endif /* AVOID_TABLES */
246 * Check for a restart marker & resynchronize decoder.
247 * Returns FALSE if must suspend.
251 process_restart (j_decompress_ptr cinfo)
253 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
256 /* Throw away any unused bits remaining in bit buffer; */
257 /* include any full bytes in next_marker's count of discarded bytes */
258 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
259 entropy->bitstate.bits_left = 0;
261 /* Advance past the RSTn marker */
262 if (! (*cinfo->marker->read_restart_marker) (cinfo))
265 /* Re-initialize DC predictions to 0 */
266 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
267 entropy->saved.last_dc_val[ci] = 0;
268 /* Re-init EOB run count, too */
269 entropy->saved.EOBRUN = 0;
271 /* Reset restart counter */
272 entropy->restarts_to_go = cinfo->restart_interval;
274 /* Next segment can get another out-of-data warning */
275 entropy->bitstate.printed_eod = FALSE;
282 * Huffman MCU decoding.
283 * Each of these routines decodes and returns one MCU's worth of
284 * Huffman-compressed coefficients.
285 * The coefficients are reordered from zigzag order into natural array order,
286 * but are not dequantized.
288 * The i'th block of the MCU is stored into the block pointed to by
289 * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
291 * We return FALSE if data source requested suspension. In that case no
292 * changes have been made to permanent state. (Exception: some output
293 * coefficients may already have been assigned. This is harmless for
294 * spectral selection, since we'll just re-assign them on the next call.
295 * Successive approximation AC refinement has to be more careful, however.)
299 * MCU decoding for DC initial scan (either spectral selection,
300 * or first pass of successive approximation).
304 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
306 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
314 jpeg_component_info * compptr;
316 /* Process restart marker if needed; may have to suspend */
317 if (cinfo->restart_interval) {
318 if (entropy->restarts_to_go == 0)
319 if (! process_restart(cinfo))
323 /* Load up working state */
324 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
325 ASSIGN_STATE(state, entropy->saved);
327 /* Outer loop handles each block in the MCU */
329 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
330 block = MCU_data[blkn];
331 ci = cinfo->MCU_membership[blkn];
332 compptr = cinfo->cur_comp_info[ci];
333 tbl = entropy->derived_tbls[compptr->dc_tbl_no];
335 /* Decode a single block's worth of coefficients */
337 /* Section F.2.2.1: decode the DC coefficient difference */
338 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
340 CHECK_BIT_BUFFER(br_state, s, return FALSE);
342 s = HUFF_EXTEND(r, s);
345 /* Convert DC difference to actual value, update last_dc_val */
346 s += state.last_dc_val[ci];
347 state.last_dc_val[ci] = s;
348 /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
349 (*block)[0] = (JCOEF) (s << Al);
352 /* Completed MCU, so update state */
353 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
354 ASSIGN_STATE(entropy->saved, state);
356 /* Account for restart interval (no-op if not using restarts) */
357 entropy->restarts_to_go--;
364 * MCU decoding for AC initial scan (either spectral selection,
365 * or first pass of successive approximation).
369 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
371 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
374 register int s, k, r;
380 /* Process restart marker if needed; may have to suspend */
381 if (cinfo->restart_interval) {
382 if (entropy->restarts_to_go == 0)
383 if (! process_restart(cinfo))
387 /* Load up working state.
388 * We can avoid loading/saving bitread state if in an EOB run.
390 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
392 /* There is always only one block per MCU */
394 if (EOBRUN > 0) /* if it's a band of zeroes... */
395 EOBRUN--; /* ...process it now (we do nothing) */
397 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
399 tbl = entropy->ac_derived_tbl;
401 for (k = cinfo->Ss; k <= Se; k++) {
402 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
407 CHECK_BIT_BUFFER(br_state, s, return FALSE);
409 s = HUFF_EXTEND(r, s);
410 /* Scale and output coefficient in natural (dezigzagged) order */
411 (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
413 if (r == 15) { /* ZRL */
414 k += 15; /* skip 15 zeroes in band */
415 } else { /* EOBr, run length is 2^r + appended bits */
417 if (r) { /* EOBr, r > 0 */
418 CHECK_BIT_BUFFER(br_state, r, return FALSE);
422 EOBRUN--; /* this band is processed at this moment */
423 break; /* force end-of-band */
428 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
431 /* Completed MCU, so update state */
432 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
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 /* Load up working state */
464 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
466 /* Outer loop handles each block in the MCU */
468 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
469 block = MCU_data[blkn];
471 /* Encoded data is simply the next bit of the two's-complement DC value */
472 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
475 /* Note: since we use |=, repeating the assignment later is safe */
478 /* Completed MCU, so update state */
479 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
481 /* Account for restart interval (no-op if not using restarts) */
482 entropy->restarts_to_go--;
489 * MCU decoding for AC successive approximation refinement scan.
493 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
495 phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
497 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
498 int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
499 register int s, k, r;
506 int newnz_pos[DCTSIZE2];
508 /* Process restart marker if needed; may have to suspend */
509 if (cinfo->restart_interval) {
510 if (entropy->restarts_to_go == 0)
511 if (! process_restart(cinfo))
515 /* Load up working state */
516 BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
517 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we care about */
519 /* There is always only one block per MCU */
521 tbl = entropy->ac_derived_tbl;
523 /* If we are forced to suspend, we must undo the assignments to any newly
524 * nonzero coefficients in the block, because otherwise we'd get confused
525 * next time about which coefficients were already nonzero.
526 * But we need not undo addition of bits to already-nonzero coefficients;
527 * instead, we can test the current bit position to see if we already did it.
531 /* initialize coefficient loop counter to start of band */
535 for (; k <= Se; k++) {
536 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
540 if (s != 1) /* size of new coef should always be 1 */
541 WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
542 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
544 s = p1; /* newly nonzero coef is positive */
546 s = m1; /* newly nonzero coef is negative */
549 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
551 CHECK_BIT_BUFFER(br_state, r, goto undoit);
555 break; /* rest of block is handled by EOB logic */
557 /* note s = 0 for processing ZRL */
559 /* Advance over already-nonzero coefs and r still-zero coefs,
560 * appending correction bits to the nonzeroes. A correction bit is 1
561 * if the absolute value of the coefficient must be increased.
564 thiscoef = *block + jpeg_natural_order[k];
565 if (*thiscoef != 0) {
566 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
568 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
577 break; /* reached target zero coefficient */
582 int pos = jpeg_natural_order[k];
583 /* Output newly nonzero coefficient */
584 (*block)[pos] = (JCOEF) s;
585 /* Remember its position in case we have to suspend */
586 newnz_pos[num_newnz++] = pos;
592 /* Scan any remaining coefficient positions after the end-of-band
593 * (the last newly nonzero coefficient, if any). Append a correction
594 * bit to each already-nonzero coefficient. A correction bit is 1
595 * if the absolute value of the coefficient must be increased.
597 for (; k <= Se; k++) {
598 thiscoef = *block + jpeg_natural_order[k];
599 if (*thiscoef != 0) {
600 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
602 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
611 /* Count one block completed in EOB run */
615 /* Completed MCU, so update state */
616 BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
617 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we care about */
619 /* Account for restart interval (no-op if not using restarts) */
620 entropy->restarts_to_go--;
625 /* Re-zero any output coefficients that we made newly nonzero */
626 while (num_newnz > 0)
627 (*block)[newnz_pos[--num_newnz]] = 0;
634 * Module initialization routine for progressive Huffman entropy decoding.
638 jinit_phuff_decoder (j_decompress_ptr cinfo)
640 phuff_entropy_ptr entropy;
644 entropy = (phuff_entropy_ptr)
645 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
646 SIZEOF(phuff_entropy_decoder));
647 cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
648 entropy->pub.start_pass = start_pass_phuff_decoder;
650 /* Mark derived tables unallocated */
651 for (i = 0; i < NUM_HUFF_TBLS; i++) {
652 entropy->derived_tbls[i] = NULL;
655 /* Create progression status table */
656 cinfo->coef_bits = (int (*)[DCTSIZE2])
657 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
658 cinfo->num_components*DCTSIZE2*SIZEOF(int));
659 coef_bit_ptr = & cinfo->coef_bits[0][0];
660 for (ci = 0; ci < cinfo->num_components; ci++)
661 for (i = 0; i < DCTSIZE2; i++)
662 *coef_bit_ptr++ = -1;
665 #endif /* D_PROGRESSIVE_SUPPORTED */