faade7f14cbd7af0825f850212a8fd930121cea6
[oweals/cde.git] / cde / lib / DtHelp / jpeg / jdhuff.c
1 /*
2  * CDE - Common Desktop Environment
3  *
4  * Copyright (c) 1993-2012, The Open Group. All rights reserved.
5  *
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)
10  * any later version.
11  *
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
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with these libraries and programs; if not, write
20  * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21  * Floor, Boston, MA 02110-1301 USA
22  */
23 /* $XConsortium: jdhuff.c /main/2 1996/05/09 03:47:48 drk $ */
24 /*
25  * jdhuff.c
26  *
27  * Copyright (C) 1991-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.
30  *
31  * This file contains Huffman entropy decoding routines.
32  *
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.
38  */
39
40 #define JPEG_INTERNALS
41 #include "jinclude.h"
42 #include "jpeglib.h"
43 #include "jdhuff.h"             /* Declarations shared with jdphuff.c */
44
45
46 /*
47  * Expanded entropy decoder object for Huffman decoding.
48  *
49  * The savable_state subrecord contains fields that change within an MCU,
50  * but must not be updated permanently until we complete the MCU.
51  */
52
53 typedef struct {
54   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
55 } savable_state;
56
57 /* This macro is to work around compilers with missing or broken
58  * structure assignment.  You'll need to fix this code if you have
59  * such a compiler and you change MAX_COMPS_IN_SCAN.
60  */
61
62 #ifndef NO_STRUCT_ASSIGN
63 #define ASSIGN_STATE(dest,src)  ((dest) = (src))
64 #else
65 #if MAX_COMPS_IN_SCAN == 4
66 #define ASSIGN_STATE(dest,src)  \
67         ((dest).last_dc_val[0] = (src).last_dc_val[0], \
68          (dest).last_dc_val[1] = (src).last_dc_val[1], \
69          (dest).last_dc_val[2] = (src).last_dc_val[2], \
70          (dest).last_dc_val[3] = (src).last_dc_val[3])
71 #endif
72 #endif
73
74
75 typedef struct {
76   struct jpeg_entropy_decoder pub; /* public fields */
77
78   /* These fields are loaded into local variables at start of each MCU.
79    * In case of suspension, we exit WITHOUT updating them.
80    */
81   bitread_perm_state bitstate;  /* Bit buffer at start of MCU */
82   savable_state saved;          /* Other state at start of MCU */
83
84   /* These fields are NOT loaded into local working state. */
85   unsigned int restarts_to_go;  /* MCUs left in this restart interval */
86
87   /* Pointers to derived tables (these workspaces have image lifespan) */
88   d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
89   d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
90 } huff_entropy_decoder;
91
92 typedef huff_entropy_decoder * huff_entropy_ptr;
93
94
95 /*
96  * Initialize for a Huffman-compressed scan.
97  */
98
99 METHODDEF(void)
100 start_pass_huff_decoder (j_decompress_ptr cinfo)
101 {
102   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
103   int ci, dctbl, actbl;
104   jpeg_component_info * compptr;
105
106   /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
107    * This ought to be an error condition, but we make it a warning because
108    * there are some baseline files out there with all zeroes in these bytes.
109    */
110   if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
111       cinfo->Ah != 0 || cinfo->Al != 0)
112     WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
113
114   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
115     compptr = cinfo->cur_comp_info[ci];
116     dctbl = compptr->dc_tbl_no;
117     actbl = compptr->ac_tbl_no;
118     /* Make sure requested tables are present */
119     if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
120         cinfo->dc_huff_tbl_ptrs[dctbl] == NULL)
121       ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
122     if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
123         cinfo->ac_huff_tbl_ptrs[actbl] == NULL)
124       ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
125     /* Compute derived values for Huffman tables */
126     /* We may do this more than once for a table, but it's not expensive */
127     jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
128                             & entropy->dc_derived_tbls[dctbl]);
129     jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
130                             & entropy->ac_derived_tbls[actbl]);
131     /* Initialize DC predictions to 0 */
132     entropy->saved.last_dc_val[ci] = 0;
133   }
134
135   /* Initialize bitread state variables */
136   entropy->bitstate.bits_left = 0;
137   entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
138   entropy->bitstate.printed_eod = FALSE;
139
140   /* Initialize restart counter */
141   entropy->restarts_to_go = cinfo->restart_interval;
142 }
143
144
145 /*
146  * Compute the derived values for a Huffman table.
147  * Note this is also used by jdphuff.c.
148  */
149
150 GLOBAL(void)
151 jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, JHUFF_TBL * htbl,
152                          d_derived_tbl ** pdtbl)
153 {
154   d_derived_tbl *dtbl;
155   int p, i, l, si;
156   int lookbits, ctr;
157   char huffsize[257];
158   unsigned int huffcode[257];
159   unsigned int code;
160
161   /* Allocate a workspace if we haven't already done so. */
162   if (*pdtbl == NULL)
163     *pdtbl = (d_derived_tbl *)
164       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
165                                   SIZEOF(d_derived_tbl));
166   dtbl = *pdtbl;
167   dtbl->pub = htbl;             /* fill in back link */
168   
169   /* Figure C.1: make table of Huffman code length for each symbol */
170   /* Note that this is in code-length order. */
171
172   p = 0;
173   for (l = 1; l <= 16; l++) {
174     for (i = 1; i <= (int) htbl->bits[l]; i++)
175       huffsize[p++] = (char) l;
176   }
177   huffsize[p] = 0;
178   
179   /* Figure C.2: generate the codes themselves */
180   /* Note that this is in code-length order. */
181   
182   code = 0;
183   si = huffsize[0];
184   p = 0;
185   while (huffsize[p]) {
186     while (((int) huffsize[p]) == si) {
187       huffcode[p++] = code;
188       code++;
189     }
190     code <<= 1;
191     si++;
192   }
193
194   /* Figure F.15: generate decoding tables for bit-sequential decoding */
195
196   p = 0;
197   for (l = 1; l <= 16; l++) {
198     if (htbl->bits[l]) {
199       dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */
200       dtbl->mincode[l] = huffcode[p]; /* minimum code of length l */
201       p += htbl->bits[l];
202       dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
203     } else {
204       dtbl->maxcode[l] = -1;    /* -1 if no codes of this length */
205     }
206   }
207   dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
208
209   /* Compute lookahead tables to speed up decoding.
210    * First we set all the table entries to 0, indicating "too long";
211    * then we iterate through the Huffman codes that are short enough and
212    * fill in all the entries that correspond to bit sequences starting
213    * with that code.
214    */
215
216   MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
217
218   p = 0;
219   for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
220     for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
221       /* l = current code's length, p = its index in huffcode[] & huffval[]. */
222       /* Generate left-justified code followed by all possible bit sequences */
223       lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
224       for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
225         dtbl->look_nbits[lookbits] = l;
226         dtbl->look_sym[lookbits] = htbl->huffval[p];
227         lookbits++;
228       }
229     }
230   }
231 }
232
233
234 /*
235  * Out-of-line code for bit fetching (shared with jdphuff.c).
236  * See jdhuff.h for info about usage.
237  * Note: current values of get_buffer and bits_left are passed as parameters,
238  * but are returned in the corresponding fields of the state struct.
239  *
240  * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
241  * of get_buffer to be used.  (On machines with wider words, an even larger
242  * buffer could be used.)  However, on some machines 32-bit shifts are
243  * quite slow and take time proportional to the number of places shifted.
244  * (This is true with most PC compilers, for instance.)  In this case it may
245  * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
246  * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
247  */
248
249 #ifdef SLOW_SHIFT_32
250 #define MIN_GET_BITS  15        /* minimum allowable value */
251 #else
252 #define MIN_GET_BITS  (BIT_BUF_SIZE-7)
253 #endif
254
255
256 GLOBAL(boolean)
257 jpeg_fill_bit_buffer (bitread_working_state * state,
258                       bit_buf_type get_buffer, int bits_left,
259                       int nbits)
260 /* Load up the bit buffer to a depth of at least nbits */
261 {
262   /* Copy heavily used state fields into locals (hopefully registers) */
263   const JOCTET * next_input_byte = state->next_input_byte;
264   size_t bytes_in_buffer = state->bytes_in_buffer;
265   int c;
266
267   /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
268   /* (It is assumed that no request will be for more than that many bits.) */
269
270   while (bits_left < MIN_GET_BITS) {
271     /* Attempt to read a byte */
272     if (state->unread_marker != 0)
273       goto no_more_data;        /* can't advance past a marker */
274
275     if (bytes_in_buffer == 0) {
276       if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
277         return FALSE;
278       next_input_byte = state->cinfo->src->next_input_byte;
279       bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
280     }
281     bytes_in_buffer--;
282     c = GETJOCTET(*next_input_byte++);
283
284     /* If it's 0xFF, check and discard stuffed zero byte */
285     if (c == 0xFF) {
286       do {
287         if (bytes_in_buffer == 0) {
288           if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
289             return FALSE;
290           next_input_byte = state->cinfo->src->next_input_byte;
291           bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
292         }
293         bytes_in_buffer--;
294         c = GETJOCTET(*next_input_byte++);
295       } while (c == 0xFF);
296
297       if (c == 0) {
298         /* Found FF/00, which represents an FF data byte */
299         c = 0xFF;
300       } else {
301         /* Oops, it's actually a marker indicating end of compressed data. */
302         /* Better put it back for use later */
303         state->unread_marker = c;
304
305       no_more_data:
306         /* There should be enough bits still left in the data segment; */
307         /* if so, just break out of the outer while loop. */
308         if (bits_left >= nbits)
309           break;
310         /* Uh-oh.  Report corrupted data to user and stuff zeroes into
311          * the data stream, so that we can produce some kind of image.
312          * Note that this code will be repeated for each byte demanded
313          * for the rest of the segment.  We use a nonvolatile flag to ensure
314          * that only one warning message appears.
315          */
316         if (! *(state->printed_eod_ptr)) {
317           WARNMS(state->cinfo, JWRN_HIT_MARKER);
318           *(state->printed_eod_ptr) = TRUE;
319         }
320         c = 0;                  /* insert a zero byte into bit buffer */
321       }
322     }
323
324     /* OK, load c into get_buffer */
325     get_buffer = (get_buffer << 8) | c;
326     bits_left += 8;
327   }
328
329   /* Unload the local registers */
330   state->next_input_byte = next_input_byte;
331   state->bytes_in_buffer = bytes_in_buffer;
332   state->get_buffer = get_buffer;
333   state->bits_left = bits_left;
334
335   return TRUE;
336 }
337
338
339 /*
340  * Out-of-line code for Huffman code decoding.
341  * See jdhuff.h for info about usage.
342  */
343
344 GLOBAL(int)
345 jpeg_huff_decode (bitread_working_state * state,
346                   bit_buf_type get_buffer, int bits_left,
347                   d_derived_tbl * htbl, int min_bits)
348 {
349   int l = min_bits;
350   INT32 code;
351
352   /* HUFF_DECODE has determined that the code is at least min_bits */
353   /* bits long, so fetch that many bits in one swoop. */
354
355   CHECK_BIT_BUFFER(*state, l, return -1);
356   code = GET_BITS(l);
357
358   /* Collect the rest of the Huffman code one bit at a time. */
359   /* This is per Figure F.16 in the JPEG spec. */
360
361   while (code > htbl->maxcode[l]) {
362     code <<= 1;
363     CHECK_BIT_BUFFER(*state, 1, return -1);
364     code |= GET_BITS(1);
365     l++;
366   }
367
368   /* Unload the local registers */
369   state->get_buffer = get_buffer;
370   state->bits_left = bits_left;
371
372   /* With garbage input we may reach the sentinel value l = 17. */
373
374   if (l > 16) {
375     WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
376     return 0;                   /* fake a zero as the safest result */
377   }
378
379   return htbl->pub->huffval[ htbl->valptr[l] +
380                             ((int) (code - htbl->mincode[l])) ];
381 }
382
383
384 /*
385  * Figure F.12: extend sign bit.
386  * On some machines, a shift and add will be faster than a table lookup.
387  */
388
389 #ifdef AVOID_TABLES
390
391 #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
392
393 #else
394
395 #define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
396
397 static const int extend_test[16] =   /* entry n is 2**(n-1) */
398   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
399     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
400
401 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
402   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
403     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
404     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
405     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
406
407 #endif /* AVOID_TABLES */
408
409
410 /*
411  * Check for a restart marker & resynchronize decoder.
412  * Returns FALSE if must suspend.
413  */
414
415 LOCAL(boolean)
416 process_restart (j_decompress_ptr cinfo)
417 {
418   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
419   int ci;
420
421   /* Throw away any unused bits remaining in bit buffer; */
422   /* include any full bytes in next_marker's count of discarded bytes */
423   cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
424   entropy->bitstate.bits_left = 0;
425
426   /* Advance past the RSTn marker */
427   if (! (*cinfo->marker->read_restart_marker) (cinfo))
428     return FALSE;
429
430   /* Re-initialize DC predictions to 0 */
431   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
432     entropy->saved.last_dc_val[ci] = 0;
433
434   /* Reset restart counter */
435   entropy->restarts_to_go = cinfo->restart_interval;
436
437   /* Next segment can get another out-of-data warning */
438   entropy->bitstate.printed_eod = FALSE;
439
440   return TRUE;
441 }
442
443
444 /*
445  * Decode and return one MCU's worth of Huffman-compressed coefficients.
446  * The coefficients are reordered from zigzag order into natural array order,
447  * but are not dequantized.
448  *
449  * The i'th block of the MCU is stored into the block pointed to by
450  * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
451  * (Wholesale zeroing is usually a little faster than retail...)
452  *
453  * Returns FALSE if data source requested suspension.  In that case no
454  * changes have been made to permanent state.  (Exception: some output
455  * coefficients may already have been assigned.  This is harmless for
456  * this module, since we'll just re-assign them on the next call.)
457  */
458
459 METHODDEF(boolean)
460 decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
461 {
462   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
463   int s, k, r;
464   int blkn, ci;
465   JBLOCKROW block;
466   BITREAD_STATE_VARS;
467   savable_state state;
468   d_derived_tbl * dctbl;
469   d_derived_tbl * actbl;
470   jpeg_component_info * compptr;
471
472   /* Process restart marker if needed; may have to suspend */
473   if (cinfo->restart_interval) {
474     if (entropy->restarts_to_go == 0)
475       if (! process_restart(cinfo))
476         return FALSE;
477   }
478
479   /* Load up working state */
480   BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
481   ASSIGN_STATE(state, entropy->saved);
482
483   /* Outer loop handles each block in the MCU */
484
485   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
486     block = MCU_data[blkn];
487     ci = cinfo->MCU_membership[blkn];
488     compptr = cinfo->cur_comp_info[ci];
489     dctbl = entropy->dc_derived_tbls[compptr->dc_tbl_no];
490     actbl = entropy->ac_derived_tbls[compptr->ac_tbl_no];
491
492     /* Decode a single block's worth of coefficients */
493
494     /* Section F.2.2.1: decode the DC coefficient difference */
495     HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
496     if (s) {
497       CHECK_BIT_BUFFER(br_state, s, return FALSE);
498       r = GET_BITS(s);
499       s = HUFF_EXTEND(r, s);
500     }
501
502     /* Shortcut if component's values are not interesting */
503     if (! compptr->component_needed)
504       goto skip_ACs;
505
506     /* Convert DC difference to actual value, update last_dc_val */
507     s += state.last_dc_val[ci];
508     state.last_dc_val[ci] = s;
509     /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
510     (*block)[0] = (JCOEF) s;
511
512     /* Do we need to decode the AC coefficients for this component? */
513     if (compptr->DCT_scaled_size > 1) {
514
515       /* Section F.2.2.2: decode the AC coefficients */
516       /* Since zeroes are skipped, output area must be cleared beforehand */
517       for (k = 1; k < DCTSIZE2; k++) {
518         HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
519       
520         r = s >> 4;
521         s &= 15;
522       
523         if (s) {
524           k += r;
525           CHECK_BIT_BUFFER(br_state, s, return FALSE);
526           r = GET_BITS(s);
527           s = HUFF_EXTEND(r, s);
528           /* Output coefficient in natural (dezigzagged) order.
529            * Note: the extra entries in jpeg_natural_order[] will save us
530            * if k >= DCTSIZE2, which could happen if the data is corrupted.
531            */
532           (*block)[jpeg_natural_order[k]] = (JCOEF) s;
533         } else {
534           if (r != 15)
535             break;
536           k += 15;
537         }
538       }
539
540     } else {
541 skip_ACs:
542
543       /* Section F.2.2.2: decode the AC coefficients */
544       /* In this path we just discard the values */
545       for (k = 1; k < DCTSIZE2; k++) {
546         HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
547       
548         r = s >> 4;
549         s &= 15;
550       
551         if (s) {
552           k += r;
553           CHECK_BIT_BUFFER(br_state, s, return FALSE);
554           DROP_BITS(s);
555         } else {
556           if (r != 15)
557             break;
558           k += 15;
559         }
560       }
561
562     }
563   }
564
565   /* Completed MCU, so update state */
566   BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
567   ASSIGN_STATE(entropy->saved, state);
568
569   /* Account for restart interval (no-op if not using restarts) */
570   entropy->restarts_to_go--;
571
572   return TRUE;
573 }
574
575
576 /*
577  * Module initialization routine for Huffman entropy decoding.
578  */
579
580 GLOBAL(void)
581 jinit_huff_decoder (j_decompress_ptr cinfo)
582 {
583   huff_entropy_ptr entropy;
584   int i;
585
586   entropy = (huff_entropy_ptr)
587     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
588                                 SIZEOF(huff_entropy_decoder));
589   cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
590   entropy->pub.start_pass = start_pass_huff_decoder;
591   entropy->pub.decode_mcu = decode_mcu;
592
593   /* Mark tables unallocated */
594   for (i = 0; i < NUM_HUFF_TBLS; i++) {
595     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
596   }
597 }