source: golgotha/src/i4/loaders/jpg/jdhuff.cc @ 80

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