1 /*
2 * jdphuff.c
3 *
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-2016, 2018-2021, D. R. Commander.
8 * For conditions of distribution and use, see the accompanying README.ijg
9 * file.
10 *
11 * This file contains Huffman entropy decoding routines for progressive JPEG.
12 *
13 * Much of the complexity here has to do with supporting input suspension.
14 * If the data source module demands suspension, we want to be able to back
15 * up to the start of the current MCU. To do this, we copy state variables
16 * into local working storage, and update them back to the permanent
17 * storage only upon successful completion of an MCU.
18 *
19 * NOTE: All referenced figures are from
20 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
21 */
22
23 #define JPEG_INTERNALS
24 #include "jinclude.h"
25 #include "jpeglib.h"
26 #include "jdhuff.h" /* Declarations shared with jdhuff.c */
27 #include <limits.h>
28
29
30 #ifdef D_PROGRESSIVE_SUPPORTED
31
32 /*
33 * Expanded entropy decoder object for progressive Huffman decoding.
34 *
35 * The savable_state subrecord contains fields that change within an MCU,
36 * but must not be updated permanently until we complete the MCU.
37 */
38
39 typedef struct {
40 unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
41 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
42 } savable_state;
43
44 typedef struct {
45 struct jpeg_entropy_decoder pub; /* public fields */
46
47 /* These fields are loaded into local variables at start of each MCU.
48 * In case of suspension, we exit WITHOUT updating them.
49 */
50 bitread_perm_state bitstate; /* Bit buffer at start of MCU */
51 savable_state saved; /* Other state at start of MCU */
52
53 /* These fields are NOT loaded into local working state. */
54 unsigned int restarts_to_go; /* MCUs left in this restart interval */
55
56 /* Pointers to derived tables (these workspaces have image lifespan) */
57 d_derived_tbl *derived_tbls[NUM_HUFF_TBLS];
58
59 d_derived_tbl *ac_derived_tbl; /* active table during an AC scan */
60 } phuff_entropy_decoder;
61
62 typedef phuff_entropy_decoder *phuff_entropy_ptr;
63
64 /* Forward declarations */
65 METHODDEF(boolean) decode_mcu_DC_first(j_decompress_ptr cinfo,
66 JBLOCKROW *MCU_data);
67 METHODDEF(boolean) decode_mcu_AC_first(j_decompress_ptr cinfo,
68 JBLOCKROW *MCU_data);
69 METHODDEF(boolean) decode_mcu_DC_refine(j_decompress_ptr cinfo,
70 JBLOCKROW *MCU_data);
71 METHODDEF(boolean) decode_mcu_AC_refine(j_decompress_ptr cinfo,
72 JBLOCKROW *MCU_data);
73
74 #ifdef HUFF_DECODE_OPT
75 // OH ISSUE: jpeg optimize
76 LOCAL(void)
jpeg_make_dp_derived_tbl(j_decompress_ptr cinfo,boolean isDC,int tblno,d_derived_tbl ** pdtbl)77 jpeg_make_dp_derived_tbl(j_decompress_ptr cinfo, boolean isDC, int tblno,
78 d_derived_tbl **pdtbl)
79 {
80 JHUFF_TBL *htbl;
81 d_derived_tbl *dtbl;
82 int p, i, l, si, numsymbols;
83 int lookbits, ctr;
84 char huffsize[257];
85 unsigned int huffcode[257];
86 unsigned int code;
87
88 /* Note that huffsize[] and huffcode[] are filled in code-length order,
89 * paralleling the order of the symbols themselves in htbl->huffval[].
90 */
91
92 /* Find the input Huffman table */
93 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
94 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
95 htbl =
96 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
97 if (htbl == NULL)
98 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
99
100 /* Allocate a workspace if we haven't already done so. */
101 if (*pdtbl == NULL)
102 *pdtbl = (d_derived_tbl *)
103 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
104 sizeof(d_derived_tbl));
105 dtbl = *pdtbl;
106 dtbl->pub = htbl; /* fill in back link */
107
108 /* Figure C.1: make table of Huffman code length for each symbol */
109
110 p = 0;
111 for (l = 1; l <= MAX_HUFF_CODE_LEN; l++) {
112 i = (int)htbl->bits[l];
113 if (i < 0 || p + i > 256) /* protect against table overrun, 256 is the max number of symbols */
114 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
115 while (i--)
116 huffsize[p++] = (char)l;
117 }
118 huffsize[p] = 0;
119 numsymbols = p;
120
121 /* Figure C.2: generate the codes themselves */
122 /* We also validate that the counts represent a legal Huffman code tree. */
123
124 code = 0;
125 si = huffsize[0];
126 p = 0;
127 while (huffsize[p]) {
128 while (((int)huffsize[p]) == si) {
129 huffcode[p++] = code;
130 code++;
131 }
132 /* code is now 1 more than the last code used for codelength si; but
133 * it must still fit in si bits, since no code is allowed to be all ones.
134 */
135 if (((JLONG)code) >= (((JLONG)1) << si))
136 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
137 code <<= 1;
138 si++;
139 }
140
141 /* Figure F.15: generate decoding tables for bit-sequential decoding */
142
143 p = 0;
144 for (l = 1; l <= MAX_HUFF_CODE_LEN; l++) {
145 if (htbl->bits[l]) {
146 /* valoffset[l] = huffval[] index of 1st symbol of code length l,
147 * minus the minimum code of length l
148 */
149 dtbl->valoffset[l] = (JLONG)p - (JLONG)huffcode[p];
150 p += htbl->bits[l];
151 dtbl->maxcode[l] = huffcode[p - 1]; /* maximum code of length l */
152 } else {
153 dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
154 }
155 }
156 dtbl->valoffset[17] = 0; /* 17 is always max symbol length in Huffman spec */
157 dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates, 17 has the same meaning above */
158
159 /* Compute lookahead tables to speed up decoding.
160 * First we set all the table entries to 0, indicating "too long";
161 * then we iterate through the Huffman codes that are short enough and
162 * fill in all the entries that correspond to bit sequences starting
163 * with that code.
164 */
165
166 for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++)
167 dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;
168
169 p = 0;
170 for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
171 for (i = 1; i <= (int)htbl->bits[l]; i++, p++) {
172 /* l = current code's length, p = its index in huffcode[] & huffval[]. */
173 /* Generate left-justified code followed by all possible bit sequences */
174 lookbits = huffcode[p] << (HUFF_LOOKAHEAD - l);
175 for (ctr = 1 << (HUFF_LOOKAHEAD - l); ctr > 0; ctr--) {
176 dtbl->lookup[lookbits] = (l << HUFF_LOOKAHEAD) | htbl->huffval[p];
177 lookbits++;
178 }
179 }
180 }
181
182 /* Validate symbols as being reasonable.
183 * For AC tables, we make no check, but accept all byte values 0..255.
184 * For DC tables, we require the symbols to be in range 0..15.
185 * (Tighter bounds could be applied depending on the data depth and mode,
186 * but this is sufficient to ensure safe decoding.)
187 */
188 if (isDC) {
189 for (i = 0; i < numsymbols; i++) {
190 int sym = htbl->huffval[i];
191 if (sym < 0 || sym > 15) // 15 is the max value of DC symbol
192 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
193 }
194 }
195 }
196 #endif
197
198 /*
199 * Initialize for a Huffman-compressed scan.
200 */
201
202 METHODDEF(void)
start_pass_phuff_decoder(j_decompress_ptr cinfo)203 start_pass_phuff_decoder(j_decompress_ptr cinfo)
204 {
205 phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
206 boolean is_DC_band, bad;
207 int ci, coefi, tbl;
208 d_derived_tbl **pdtbl;
209 int *coef_bit_ptr, *prev_coef_bit_ptr;
210 jpeg_component_info *compptr;
211
212 is_DC_band = (cinfo->Ss == 0);
213
214 /* Validate scan parameters */
215 bad = FALSE;
216 if (is_DC_band) {
217 if (cinfo->Se != 0)
218 bad = TRUE;
219 } else {
220 /* need not check Ss/Se < 0 since they came from unsigned bytes */
221 if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
222 bad = TRUE;
223 /* AC scans may have only one component */
224 if (cinfo->comps_in_scan != 1)
225 bad = TRUE;
226 }
227 if (cinfo->Ah != 0) {
228 /* Successive approximation refinement scan: must have Al = Ah-1. */
229 if (cinfo->Al != cinfo->Ah - 1)
230 bad = TRUE;
231 }
232 if (cinfo->Al > 13) /* need not check for < 0 */
233 bad = TRUE;
234 /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
235 * but the spec doesn't say so, and we try to be liberal about what we
236 * accept. Note: large Al values could result in out-of-range DC
237 * coefficients during early scans, leading to bizarre displays due to
238 * overflows in the IDCT math. But we won't crash.
239 */
240 if (bad)
241 ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
242 cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
243 /* Update progression status, and verify that scan order is legal.
244 * Note that inter-scan inconsistencies are treated as warnings
245 * not fatal errors ... not clear if this is right way to behave.
246 */
247 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
248 int cindex = cinfo->cur_comp_info[ci]->component_index;
249 coef_bit_ptr = &cinfo->coef_bits[cindex][0];
250 prev_coef_bit_ptr = &cinfo->coef_bits[cindex + cinfo->num_components][0];
251 if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
252 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
253 for (coefi = MIN(cinfo->Ss, 1); coefi <= MAX(cinfo->Se, 9); coefi++) {
254 if (cinfo->input_scan_number > 1)
255 prev_coef_bit_ptr[coefi] = coef_bit_ptr[coefi];
256 else
257 prev_coef_bit_ptr[coefi] = 0;
258 }
259 for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
260 int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
261 if (cinfo->Ah != expected)
262 WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
263 coef_bit_ptr[coefi] = cinfo->Al;
264 }
265 }
266
267 /* Select MCU decoding routine */
268 if (cinfo->Ah == 0) {
269 if (is_DC_band)
270 entropy->pub.decode_mcu = decode_mcu_DC_first;
271 else
272 entropy->pub.decode_mcu = decode_mcu_AC_first;
273 } else {
274 if (is_DC_band)
275 entropy->pub.decode_mcu = decode_mcu_DC_refine;
276 else
277 entropy->pub.decode_mcu = decode_mcu_AC_refine;
278 }
279
280 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
281 compptr = cinfo->cur_comp_info[ci];
282 /* Make sure requested tables are present, and compute derived tables.
283 * We may build same derived table more than once, but it's not expensive.
284 */
285 if (is_DC_band) {
286 if (cinfo->Ah == 0) { /* DC refinement needs no table */
287 tbl = compptr->dc_tbl_no;
288 pdtbl = (d_derived_tbl **)(entropy->derived_tbls) + tbl;
289 #ifdef HUFF_DECODE_OPT
290 // OH ISSUE: jpeg optimize
291 jpeg_make_dp_derived_tbl(cinfo, TRUE, tbl, pdtbl);
292 #else
293 jpeg_make_d_derived_tbl(cinfo, TRUE, tbl, pdtbl);
294 #endif
295 }
296 } else {
297 tbl = compptr->ac_tbl_no;
298 pdtbl = (d_derived_tbl **)(entropy->derived_tbls) + tbl;
299 #ifdef HUFF_DECODE_OPT
300 // OH ISSUE: jpeg optimize
301 jpeg_make_dp_derived_tbl(cinfo, FALSE, tbl, pdtbl);
302 #else
303 jpeg_make_d_derived_tbl(cinfo, FALSE, tbl, pdtbl);
304 #endif
305 /* remember the single active table */
306 entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
307 }
308 /* Initialize DC predictions to 0 */
309 entropy->saved.last_dc_val[ci] = 0;
310 }
311
312 /* Initialize bitread state variables */
313 entropy->bitstate.bits_left = 0;
314 entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
315 entropy->pub.insufficient_data = FALSE;
316
317 /* Initialize private state variables */
318 entropy->saved.EOBRUN = 0;
319
320 /* Initialize restart counter */
321 entropy->restarts_to_go = cinfo->restart_interval;
322 }
323
324
325 /*
326 * Figure F.12: extend sign bit.
327 * On some machines, a shift and add will be faster than a table lookup.
328 */
329
330 #define AVOID_TABLES
331 #ifdef AVOID_TABLES
332
333 #define NEG_1 ((unsigned)-1)
334 #define HUFF_EXTEND(x, s) \
335 ((x) < (1 << ((s) - 1)) ? (x) + (((NEG_1) << (s)) + 1) : (x))
336
337 #else
338
339 #define HUFF_EXTEND(x, s) \
340 ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
341
342 static const int extend_test[16] = { /* entry n is 2**(n-1) */
343 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
344 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000
345 };
346
347 static const int extend_offset[16] = { /* entry n is (-1 << n) + 1 */
348 0, ((-1) << 1) + 1, ((-1) << 2) + 1, ((-1) << 3) + 1, ((-1) << 4) + 1,
349 ((-1) << 5) + 1, ((-1) << 6) + 1, ((-1) << 7) + 1, ((-1) << 8) + 1,
350 ((-1) << 9) + 1, ((-1) << 10) + 1, ((-1) << 11) + 1, ((-1) << 12) + 1,
351 ((-1) << 13) + 1, ((-1) << 14) + 1, ((-1) << 15) + 1
352 };
353
354 #endif /* AVOID_TABLES */
355
356
357 /*
358 * Check for a restart marker & resynchronize decoder.
359 * Returns FALSE if must suspend.
360 */
361
362 LOCAL(boolean)
process_restart(j_decompress_ptr cinfo)363 process_restart(j_decompress_ptr cinfo)
364 {
365 phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
366 int ci;
367
368 /* Throw away any unused bits remaining in bit buffer; */
369 /* include any full bytes in next_marker's count of discarded bytes */
370 cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
371 entropy->bitstate.bits_left = 0;
372
373 /* Advance past the RSTn marker */
374 if (!(*cinfo->marker->read_restart_marker) (cinfo))
375 return FALSE;
376
377 /* Re-initialize DC predictions to 0 */
378 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
379 entropy->saved.last_dc_val[ci] = 0;
380 /* Re-init EOB run count, too */
381 entropy->saved.EOBRUN = 0;
382
383 /* Reset restart counter */
384 entropy->restarts_to_go = cinfo->restart_interval;
385
386 /* Reset out-of-data flag, unless read_restart_marker left us smack up
387 * against a marker. In that case we will end up treating the next data
388 * segment as empty, and we can avoid producing bogus output pixels by
389 * leaving the flag set.
390 */
391 if (cinfo->unread_marker == 0)
392 entropy->pub.insufficient_data = FALSE;
393
394 return TRUE;
395 }
396
397
398 /*
399 * Huffman MCU decoding.
400 * Each of these routines decodes and returns one MCU's worth of
401 * Huffman-compressed coefficients.
402 * The coefficients are reordered from zigzag order into natural array order,
403 * but are not dequantized.
404 *
405 * The i'th block of the MCU is stored into the block pointed to by
406 * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
407 *
408 * We return FALSE if data source requested suspension. In that case no
409 * changes have been made to permanent state. (Exception: some output
410 * coefficients may already have been assigned. This is harmless for
411 * spectral selection, since we'll just re-assign them on the next call.
412 * Successive approximation AC refinement has to be more careful, however.)
413 */
414
415 /*
416 * MCU decoding for DC initial scan (either spectral selection,
417 * or first pass of successive approximation).
418 */
419
420 METHODDEF(boolean)
decode_mcu_DC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)421 decode_mcu_DC_first(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
422 {
423 phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
424 int Al = cinfo->Al;
425 register int s, r;
426 int blkn, ci;
427 JBLOCKROW block;
428 BITREAD_STATE_VARS;
429 savable_state state;
430 d_derived_tbl *tbl;
431 jpeg_component_info *compptr;
432
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))
437 return FALSE;
438 }
439
440 /* If we've run out of data, just leave the MCU set to zeroes.
441 * This way, we return uniform gray for the remainder of the segment.
442 */
443 if (!entropy->pub.insufficient_data) {
444
445 /* Load up working state */
446 BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
447 state = entropy->saved;
448
449 /* Outer loop handles each block in the MCU */
450
451 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
452 block = MCU_data[blkn];
453 ci = cinfo->MCU_membership[blkn];
454 compptr = cinfo->cur_comp_info[ci];
455 tbl = entropy->derived_tbls[compptr->dc_tbl_no];
456
457 /* Decode a single block's worth of coefficients */
458
459 /* Section F.2.2.1: decode the DC coefficient difference */
460 HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
461 if (s) {
462 CHECK_BIT_BUFFER(br_state, s, return FALSE);
463 r = GET_BITS(s);
464 s = HUFF_EXTEND(r, s);
465 }
466
467 /* Convert DC difference to actual value, update last_dc_val */
468 if ((state.last_dc_val[ci] >= 0 &&
469 s > INT_MAX - state.last_dc_val[ci]) ||
470 (state.last_dc_val[ci] < 0 && s < INT_MIN - state.last_dc_val[ci]))
471 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
472 s += state.last_dc_val[ci];
473 state.last_dc_val[ci] = s;
474 /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
475 (*block)[0] = (JCOEF)LEFT_SHIFT(s, Al);
476 }
477
478 /* Completed MCU, so update state */
479 BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
480 entropy->saved = state;
481 }
482
483 /* Account for restart interval (no-op if not using restarts) */
484 if (cinfo->restart_interval)
485 entropy->restarts_to_go--;
486
487 return TRUE;
488 }
489
490
491 /*
492 * MCU decoding for AC initial scan (either spectral selection,
493 * or first pass of successive approximation).
494 */
495
496 METHODDEF(boolean)
decode_mcu_AC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)497 decode_mcu_AC_first(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
498 {
499 phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
500 int Se = cinfo->Se;
501 int Al = cinfo->Al;
502 register int s, k, r;
503 unsigned int EOBRUN;
504 JBLOCKROW block;
505 BITREAD_STATE_VARS;
506 d_derived_tbl *tbl;
507
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))
512 return FALSE;
513 }
514
515 /* If we've run out of data, just leave the MCU set to zeroes.
516 * This way, we return uniform gray for the remainder of the segment.
517 */
518 if (!entropy->pub.insufficient_data) {
519
520 /* Load up working state.
521 * We can avoid loading/saving bitread state if in an EOB run.
522 */
523 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
524
525 /* There is always only one block per MCU */
526
527 if (EOBRUN > 0) /* if it's a band of zeroes... */
528 EOBRUN--; /* ...process it now (we do nothing) */
529 else {
530 BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
531 block = MCU_data[0];
532 tbl = entropy->ac_derived_tbl;
533
534 for (k = cinfo->Ss; k <= Se; k++) {
535 HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
536 r = s >> 4;
537 s &= 15;
538 if (s) {
539 k += r;
540 CHECK_BIT_BUFFER(br_state, s, return FALSE);
541 r = GET_BITS(s);
542 s = HUFF_EXTEND(r, s);
543 /* Scale and output coefficient in natural (dezigzagged) order */
544 (*block)[jpeg_natural_order[k]] = (JCOEF)LEFT_SHIFT(s, Al);
545 } else {
546 if (r == 15) { /* ZRL */
547 k += 15; /* skip 15 zeroes in band */
548 } else { /* EOBr, run length is 2^r + appended bits */
549 EOBRUN = 1 << r;
550 if (r) { /* EOBr, r > 0 */
551 CHECK_BIT_BUFFER(br_state, r, return FALSE);
552 r = GET_BITS(r);
553 EOBRUN += r;
554 }
555 EOBRUN--; /* this band is processed at this moment */
556 break; /* force end-of-band */
557 }
558 }
559 }
560
561 BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
562 }
563
564 /* Completed MCU, so update state */
565 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
566 }
567
568 /* Account for restart interval (no-op if not using restarts) */
569 if (cinfo->restart_interval)
570 entropy->restarts_to_go--;
571
572 return TRUE;
573 }
574
575
576 /*
577 * MCU decoding for DC successive approximation refinement scan.
578 * Note: we assume such scans can be multi-component, although the spec
579 * is not very clear on the point.
580 */
581
582 METHODDEF(boolean)
decode_mcu_DC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)583 decode_mcu_DC_refine(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
584 {
585 phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
586 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
587 int blkn;
588 JBLOCKROW block;
589 BITREAD_STATE_VARS;
590
591 /* Process restart marker if needed; may have to suspend */
592 if (cinfo->restart_interval) {
593 if (entropy->restarts_to_go == 0)
594 if (!process_restart(cinfo))
595 return FALSE;
596 }
597
598 /* Not worth the cycles to check insufficient_data here,
599 * since we will not change the data anyway if we read zeroes.
600 */
601
602 /* Load up working state */
603 BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
604
605 /* Outer loop handles each block in the MCU */
606
607 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
608 block = MCU_data[blkn];
609
610 /* Encoded data is simply the next bit of the two's-complement DC value */
611 CHECK_BIT_BUFFER(br_state, 1, return FALSE);
612 if (GET_BITS(1))
613 (*block)[0] |= p1;
614 /* Note: since we use |=, repeating the assignment later is safe */
615 }
616
617 /* Completed MCU, so update state */
618 BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
619
620 /* Account for restart interval (no-op if not using restarts) */
621 if (cinfo->restart_interval)
622 entropy->restarts_to_go--;
623
624 return TRUE;
625 }
626
627
628 /*
629 * MCU decoding for AC successive approximation refinement scan.
630 */
631
632 METHODDEF(boolean)
decode_mcu_AC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)633 decode_mcu_AC_refine(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
634 {
635 phuff_entropy_ptr entropy = (phuff_entropy_ptr)cinfo->entropy;
636 int Se = cinfo->Se;
637 int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
638 int m1 = (NEG_1) << cinfo->Al; /* -1 in the bit position being coded */
639 register int s, k, r;
640 unsigned int EOBRUN;
641 JBLOCKROW block;
642 JCOEFPTR thiscoef;
643 BITREAD_STATE_VARS;
644 d_derived_tbl *tbl;
645 int num_newnz;
646 int newnz_pos[DCTSIZE2];
647
648 /* Process restart marker if needed; may have to suspend */
649 if (cinfo->restart_interval) {
650 if (entropy->restarts_to_go == 0)
651 if (!process_restart(cinfo))
652 return FALSE;
653 }
654
655 /* If we've run out of data, don't modify the MCU.
656 */
657 if (!entropy->pub.insufficient_data) {
658
659 /* Load up working state */
660 BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
661 EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
662
663 /* There is always only one block per MCU */
664 block = MCU_data[0];
665 tbl = entropy->ac_derived_tbl;
666
667 /* If we are forced to suspend, we must undo the assignments to any newly
668 * nonzero coefficients in the block, because otherwise we'd get confused
669 * next time about which coefficients were already nonzero.
670 * But we need not undo addition of bits to already-nonzero coefficients;
671 * instead, we can test the current bit to see if we already did it.
672 */
673 num_newnz = 0;
674
675 /* initialize coefficient loop counter to start of band */
676 k = cinfo->Ss;
677
678 if (EOBRUN == 0) {
679 for (; k <= Se; k++) {
680 HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
681 r = s >> 4;
682 s &= 15;
683 if (s) {
684 if (s != 1) /* size of new coef should always be 1 */
685 WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
686 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
687 if (GET_BITS(1))
688 s = p1; /* newly nonzero coef is positive */
689 else
690 s = m1; /* newly nonzero coef is negative */
691 } else {
692 if (r != 15) {
693 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
694 if (r) {
695 CHECK_BIT_BUFFER(br_state, r, goto undoit);
696 r = GET_BITS(r);
697 EOBRUN += r;
698 }
699 break; /* rest of block is handled by EOB logic */
700 }
701 /* note s = 0 for processing ZRL */
702 }
703 /* Advance over already-nonzero coefs and r still-zero coefs,
704 * appending correction bits to the nonzeroes. A correction bit is 1
705 * if the absolute value of the coefficient must be increased.
706 */
707 do {
708 thiscoef = *block + jpeg_natural_order[k];
709 if (*thiscoef != 0) {
710 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
711 if (GET_BITS(1)) {
712 if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
713 if (*thiscoef >= 0)
714 *thiscoef += p1;
715 else
716 *thiscoef += m1;
717 }
718 }
719 } else {
720 if (--r < 0)
721 break; /* reached target zero coefficient */
722 }
723 k++;
724 } while (k <= Se);
725 if (s) {
726 int pos = jpeg_natural_order[k];
727 /* Output newly nonzero coefficient */
728 (*block)[pos] = (JCOEF)s;
729 /* Remember its position in case we have to suspend */
730 newnz_pos[num_newnz++] = pos;
731 }
732 }
733 }
734
735 if (EOBRUN > 0) {
736 /* Scan any remaining coefficient positions after the end-of-band
737 * (the last newly nonzero coefficient, if any). Append a correction
738 * bit to each already-nonzero coefficient. A correction bit is 1
739 * if the absolute value of the coefficient must be increased.
740 */
741 for (; k <= Se; k++) {
742 thiscoef = *block + jpeg_natural_order[k];
743 if (*thiscoef != 0) {
744 CHECK_BIT_BUFFER(br_state, 1, goto undoit);
745 if (GET_BITS(1)) {
746 if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
747 if (*thiscoef >= 0)
748 *thiscoef += p1;
749 else
750 *thiscoef += m1;
751 }
752 }
753 }
754 }
755 /* Count one block completed in EOB run */
756 EOBRUN--;
757 }
758
759 /* Completed MCU, so update state */
760 BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
761 entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
762 }
763
764 /* Account for restart interval (no-op if not using restarts) */
765 if (cinfo->restart_interval)
766 entropy->restarts_to_go--;
767
768 return TRUE;
769
770 undoit:
771 /* Re-zero any output coefficients that we made newly nonzero */
772 while (num_newnz > 0)
773 (*block)[newnz_pos[--num_newnz]] = 0;
774
775 return FALSE;
776 }
777
778
779 /*
780 * Module initialization routine for progressive Huffman entropy decoding.
781 */
782
783 GLOBAL(void)
jinit_phuff_decoder(j_decompress_ptr cinfo)784 jinit_phuff_decoder(j_decompress_ptr cinfo)
785 {
786 phuff_entropy_ptr entropy;
787 int *coef_bit_ptr;
788 int ci, i;
789
790 entropy = (phuff_entropy_ptr)
791 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
792 sizeof(phuff_entropy_decoder));
793 cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
794 entropy->pub.start_pass = start_pass_phuff_decoder;
795
796 /* Mark derived tables unallocated */
797 for (i = 0; i < NUM_HUFF_TBLS; i++) {
798 entropy->derived_tbls[i] = NULL;
799 }
800
801 /* Create progression status table */
802 cinfo->coef_bits = (int (*)[DCTSIZE2])
803 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
804 cinfo->num_components * 2 * DCTSIZE2 *
805 sizeof(int));
806 coef_bit_ptr = &cinfo->coef_bits[0][0];
807 for (ci = 0; ci < cinfo->num_components; ci++)
808 for (i = 0; i < DCTSIZE2; i++)
809 *coef_bit_ptr++ = -1;
810 }
811
812 #endif /* D_PROGRESSIVE_SUPPORTED */
813