source: trunk/libjpeg/jdhuff.c @ 426

Last change on this file since 426 was 283, checked in by rbri, 12 years ago

JPEG plugin: libjpeg updated to version 7

File size: 42.6 KB
Line 
1/*
2 * jdhuff.c
3 *
4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * Modified 2006-2009 by Guido Vollbeding.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
8 *
9 * This file contains Huffman entropy decoding routines.
10 * Both sequential and progressive modes are supported in this single module.
11 *
12 * Much of the complexity here has to do with supporting input suspension.
13 * If the data source module demands suspension, we want to be able to back
14 * up to the start of the current MCU.  To do this, we copy state variables
15 * into local working storage, and update them back to the permanent
16 * storage only upon successful completion of an MCU.
17 */
18
19#define JPEG_INTERNALS
20#include "jinclude.h"
21#include "jpeglib.h"
22
23
24/* Derived data constructed for each Huffman table */
25
26#define HUFF_LOOKAHEAD  8       /* # of bits of lookahead */
27
28typedef struct {
29  /* Basic tables: (element [0] of each array is unused) */
30  INT32 maxcode[18];            /* largest code of length k (-1 if none) */
31  /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
32  INT32 valoffset[17];          /* huffval[] offset for codes of length k */
33  /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
34   * the smallest code of length k; so given a code of length k, the
35   * corresponding symbol is huffval[code + valoffset[k]]
36   */
37
38  /* Link to public Huffman table (needed only in jpeg_huff_decode) */
39  JHUFF_TBL *pub;
40
41  /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
42   * the input data stream.  If the next Huffman code is no more
43   * than HUFF_LOOKAHEAD bits long, we can obtain its length and
44   * the corresponding symbol directly from these tables.
45   */
46  int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
47  UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
48} d_derived_tbl;
49
50
51/*
52 * Fetching the next N bits from the input stream is a time-critical operation
53 * for the Huffman decoders.  We implement it with a combination of inline
54 * macros and out-of-line subroutines.  Note that N (the number of bits
55 * demanded at one time) never exceeds 15 for JPEG use.
56 *
57 * We read source bytes into get_buffer and dole out bits as needed.
58 * If get_buffer already contains enough bits, they are fetched in-line
59 * by the macros CHECK_BIT_BUFFER and GET_BITS.  When there aren't enough
60 * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
61 * as full as possible (not just to the number of bits needed; this
62 * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
63 * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
64 * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
65 * at least the requested number of bits --- dummy zeroes are inserted if
66 * necessary.
67 */
68
69typedef INT32 bit_buf_type;     /* type of bit-extraction buffer */
70#define BIT_BUF_SIZE  32        /* size of buffer in bits */
71
72/* If long is > 32 bits on your machine, and shifting/masking longs is
73 * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
74 * appropriately should be a win.  Unfortunately we can't define the size
75 * with something like  #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
76 * because not all machines measure sizeof in 8-bit bytes.
77 */
78
79typedef struct {                /* Bitreading state saved across MCUs */
80  bit_buf_type get_buffer;      /* current bit-extraction buffer */
81  int bits_left;                /* # of unused bits in it */
82} bitread_perm_state;
83
84typedef struct {                /* Bitreading working state within an MCU */
85  /* Current data source location */
86  /* We need a copy, rather than munging the original, in case of suspension */
87  const JOCTET * next_input_byte; /* => next byte to read from source */
88  size_t bytes_in_buffer;       /* # of bytes remaining in source buffer */
89  /* Bit input buffer --- note these values are kept in register variables,
90   * not in this struct, inside the inner loops.
91   */
92  bit_buf_type get_buffer;      /* current bit-extraction buffer */
93  int bits_left;                /* # of unused bits in it */
94  /* Pointer needed by jpeg_fill_bit_buffer. */
95  j_decompress_ptr cinfo;       /* back link to decompress master record */
96} bitread_working_state;
97
98/* Macros to declare and load/save bitread local variables. */
99#define BITREAD_STATE_VARS  \
100        register bit_buf_type get_buffer;  \
101        register int bits_left;  \
102        bitread_working_state br_state
103
104#define BITREAD_LOAD_STATE(cinfop,permstate)  \
105        br_state.cinfo = cinfop; \
106        br_state.next_input_byte = cinfop->src->next_input_byte; \
107        br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
108        get_buffer = permstate.get_buffer; \
109        bits_left = permstate.bits_left;
110
111#define BITREAD_SAVE_STATE(cinfop,permstate)  \
112        cinfop->src->next_input_byte = br_state.next_input_byte; \
113        cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
114        permstate.get_buffer = get_buffer; \
115        permstate.bits_left = bits_left
116
117/*
118 * These macros provide the in-line portion of bit fetching.
119 * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
120 * before using GET_BITS, PEEK_BITS, or DROP_BITS.
121 * The variables get_buffer and bits_left are assumed to be locals,
122 * but the state struct might not be (jpeg_huff_decode needs this).
123 *      CHECK_BIT_BUFFER(state,n,action);
124 *              Ensure there are N bits in get_buffer; if suspend, take action.
125 *      val = GET_BITS(n);
126 *              Fetch next N bits.
127 *      val = PEEK_BITS(n);
128 *              Fetch next N bits without removing them from the buffer.
129 *      DROP_BITS(n);
130 *              Discard next N bits.
131 * The value N should be a simple variable, not an expression, because it
132 * is evaluated multiple times.
133 */
134
135#define CHECK_BIT_BUFFER(state,nbits,action) \
136        { if (bits_left < (nbits)) {  \
137            if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits))  \
138              { action; }  \
139            get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
140
141#define GET_BITS(nbits) \
142        (((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits))
143
144#define PEEK_BITS(nbits) \
145        (((int) (get_buffer >> (bits_left -  (nbits)))) & BIT_MASK(nbits))
146
147#define DROP_BITS(nbits) \
148        (bits_left -= (nbits))
149
150
151/*
152 * Code for extracting next Huffman-coded symbol from input bit stream.
153 * Again, this is time-critical and we make the main paths be macros.
154 *
155 * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
156 * without looping.  Usually, more than 95% of the Huffman codes will be 8
157 * or fewer bits long.  The few overlength codes are handled with a loop,
158 * which need not be inline code.
159 *
160 * Notes about the HUFF_DECODE macro:
161 * 1. Near the end of the data segment, we may fail to get enough bits
162 *    for a lookahead.  In that case, we do it the hard way.
163 * 2. If the lookahead table contains no entry, the next code must be
164 *    more than HUFF_LOOKAHEAD bits long.
165 * 3. jpeg_huff_decode returns -1 if forced to suspend.
166 */
167
168#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
169{ register int nb, look; \
170  if (bits_left < HUFF_LOOKAHEAD) { \
171    if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
172    get_buffer = state.get_buffer; bits_left = state.bits_left; \
173    if (bits_left < HUFF_LOOKAHEAD) { \
174      nb = 1; goto slowlabel; \
175    } \
176  } \
177  look = PEEK_BITS(HUFF_LOOKAHEAD); \
178  if ((nb = htbl->look_nbits[look]) != 0) { \
179    DROP_BITS(nb); \
180    result = htbl->look_sym[look]; \
181  } else { \
182    nb = HUFF_LOOKAHEAD+1; \
183slowlabel: \
184    if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
185        { failaction; } \
186    get_buffer = state.get_buffer; bits_left = state.bits_left; \
187  } \
188}
189
190
191/*
192 * Expanded entropy decoder object for Huffman decoding.
193 *
194 * The savable_state subrecord contains fields that change within an MCU,
195 * but must not be updated permanently until we complete the MCU.
196 */
197
198typedef struct {
199  unsigned int EOBRUN;                  /* remaining EOBs in EOBRUN */
200  int last_dc_val[MAX_COMPS_IN_SCAN];   /* last DC coef for each component */
201} savable_state;
202
203/* This macro is to work around compilers with missing or broken
204 * structure assignment.  You'll need to fix this code if you have
205 * such a compiler and you change MAX_COMPS_IN_SCAN.
206 */
207
208#ifndef NO_STRUCT_ASSIGN
209#define ASSIGN_STATE(dest,src)  ((dest) = (src))
210#else
211#if MAX_COMPS_IN_SCAN == 4
212#define ASSIGN_STATE(dest,src)  \
213        ((dest).EOBRUN = (src).EOBRUN, \
214         (dest).last_dc_val[0] = (src).last_dc_val[0], \
215         (dest).last_dc_val[1] = (src).last_dc_val[1], \
216         (dest).last_dc_val[2] = (src).last_dc_val[2], \
217         (dest).last_dc_val[3] = (src).last_dc_val[3])
218#endif
219#endif
220
221
222typedef struct {
223  struct jpeg_entropy_decoder pub; /* public fields */
224
225  /* These fields are loaded into local variables at start of each MCU.
226   * In case of suspension, we exit WITHOUT updating them.
227   */
228  bitread_perm_state bitstate;  /* Bit buffer at start of MCU */
229  savable_state saved;          /* Other state at start of MCU */
230
231  /* These fields are NOT loaded into local working state. */
232  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
233
234  /* Following two fields used only in progressive mode */
235
236  /* Pointers to derived tables (these workspaces have image lifespan) */
237  d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
238
239  d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
240
241  /* Following fields used only in sequential mode */
242
243  /* Pointers to derived tables (these workspaces have image lifespan) */
244  d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
245  d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
246
247  /* Precalculated info set up by start_pass for use in decode_mcu: */
248
249  /* Pointers to derived tables to be used for each block within an MCU */
250  d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
251  d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
252  /* Whether we care about the DC and AC coefficient values for each block */
253  int coef_limit[D_MAX_BLOCKS_IN_MCU];
254} huff_entropy_decoder;
255
256typedef huff_entropy_decoder * huff_entropy_ptr;
257
258
259static const int jpeg_zigzag_order[8][8] = {
260  {  0,  1,  5,  6, 14, 15, 27, 28 },
261  {  2,  4,  7, 13, 16, 26, 29, 42 },
262  {  3,  8, 12, 17, 25, 30, 41, 43 },
263  {  9, 11, 18, 24, 31, 40, 44, 53 },
264  { 10, 19, 23, 32, 39, 45, 52, 54 },
265  { 20, 22, 33, 38, 46, 51, 55, 60 },
266  { 21, 34, 37, 47, 50, 56, 59, 61 },
267  { 35, 36, 48, 49, 57, 58, 62, 63 }
268};
269
270
271/*
272 * Compute the derived values for a Huffman table.
273 * This routine also performs some validation checks on the table.
274 */
275
276LOCAL(void)
277jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
278                         d_derived_tbl ** pdtbl)
279{
280  JHUFF_TBL *htbl;
281  d_derived_tbl *dtbl;
282  int p, i, l, si, numsymbols;
283  int lookbits, ctr;
284  char huffsize[257];
285  unsigned int huffcode[257];
286  unsigned int code;
287
288  /* Note that huffsize[] and huffcode[] are filled in code-length order,
289   * paralleling the order of the symbols themselves in htbl->huffval[].
290   */
291
292  /* Find the input Huffman table */
293  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
294    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
295  htbl =
296    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
297  if (htbl == NULL)
298    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
299
300  /* Allocate a workspace if we haven't already done so. */
301  if (*pdtbl == NULL)
302    *pdtbl = (d_derived_tbl *)
303      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
304                                  SIZEOF(d_derived_tbl));
305  dtbl = *pdtbl;
306  dtbl->pub = htbl;             /* fill in back link */
307 
308  /* Figure C.1: make table of Huffman code length for each symbol */
309
310  p = 0;
311  for (l = 1; l <= 16; l++) {
312    i = (int) htbl->bits[l];
313    if (i < 0 || p + i > 256)   /* protect against table overrun */
314      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
315    while (i--)
316      huffsize[p++] = (char) l;
317  }
318  huffsize[p] = 0;
319  numsymbols = p;
320 
321  /* Figure C.2: generate the codes themselves */
322  /* We also validate that the counts represent a legal Huffman code tree. */
323 
324  code = 0;
325  si = huffsize[0];
326  p = 0;
327  while (huffsize[p]) {
328    while (((int) huffsize[p]) == si) {
329      huffcode[p++] = code;
330      code++;
331    }
332    /* code is now 1 more than the last code used for codelength si; but
333     * it must still fit in si bits, since no code is allowed to be all ones.
334     */
335    if (((INT32) code) >= (((INT32) 1) << si))
336      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
337    code <<= 1;
338    si++;
339  }
340
341  /* Figure F.15: generate decoding tables for bit-sequential decoding */
342
343  p = 0;
344  for (l = 1; l <= 16; l++) {
345    if (htbl->bits[l]) {
346      /* valoffset[l] = huffval[] index of 1st symbol of code length l,
347       * minus the minimum code of length l
348       */
349      dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
350      p += htbl->bits[l];
351      dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
352    } else {
353      dtbl->maxcode[l] = -1;    /* -1 if no codes of this length */
354    }
355  }
356  dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
357
358  /* Compute lookahead tables to speed up decoding.
359   * First we set all the table entries to 0, indicating "too long";
360   * then we iterate through the Huffman codes that are short enough and
361   * fill in all the entries that correspond to bit sequences starting
362   * with that code.
363   */
364
365  MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
366
367  p = 0;
368  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
369    for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
370      /* l = current code's length, p = its index in huffcode[] & huffval[]. */
371      /* Generate left-justified code followed by all possible bit sequences */
372      lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
373      for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
374        dtbl->look_nbits[lookbits] = l;
375        dtbl->look_sym[lookbits] = htbl->huffval[p];
376        lookbits++;
377      }
378    }
379  }
380
381  /* Validate symbols as being reasonable.
382   * For AC tables, we make no check, but accept all byte values 0..255.
383   * For DC tables, we require the symbols to be in range 0..15.
384   * (Tighter bounds could be applied depending on the data depth and mode,
385   * but this is sufficient to ensure safe decoding.)
386   */
387  if (isDC) {
388    for (i = 0; i < numsymbols; i++) {
389      int sym = htbl->huffval[i];
390      if (sym < 0 || sym > 15)
391        ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
392    }
393  }
394}
395
396
397/*
398 * Out-of-line code for bit fetching.
399 * Note: current values of get_buffer and bits_left are passed as parameters,
400 * but are returned in the corresponding fields of the state struct.
401 *
402 * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
403 * of get_buffer to be used.  (On machines with wider words, an even larger
404 * buffer could be used.)  However, on some machines 32-bit shifts are
405 * quite slow and take time proportional to the number of places shifted.
406 * (This is true with most PC compilers, for instance.)  In this case it may
407 * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
408 * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
409 */
410
411#ifdef SLOW_SHIFT_32
412#define MIN_GET_BITS  15        /* minimum allowable value */
413#else
414#define MIN_GET_BITS  (BIT_BUF_SIZE-7)
415#endif
416
417
418LOCAL(boolean)
419jpeg_fill_bit_buffer (bitread_working_state * state,
420                      register bit_buf_type get_buffer, register int bits_left,
421                      int nbits)
422/* Load up the bit buffer to a depth of at least nbits */
423{
424  /* Copy heavily used state fields into locals (hopefully registers) */
425  register const JOCTET * next_input_byte = state->next_input_byte;
426  register size_t bytes_in_buffer = state->bytes_in_buffer;
427  j_decompress_ptr cinfo = state->cinfo;
428
429  /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
430  /* (It is assumed that no request will be for more than that many bits.) */
431  /* We fail to do so only if we hit a marker or are forced to suspend. */
432
433  if (cinfo->unread_marker == 0) {      /* cannot advance past a marker */
434    while (bits_left < MIN_GET_BITS) {
435      register int c;
436
437      /* Attempt to read a byte */
438      if (bytes_in_buffer == 0) {
439        if (! (*cinfo->src->fill_input_buffer) (cinfo))
440          return FALSE;
441        next_input_byte = cinfo->src->next_input_byte;
442        bytes_in_buffer = cinfo->src->bytes_in_buffer;
443      }
444      bytes_in_buffer--;
445      c = GETJOCTET(*next_input_byte++);
446
447      /* If it's 0xFF, check and discard stuffed zero byte */
448      if (c == 0xFF) {
449        /* Loop here to discard any padding FF's on terminating marker,
450         * so that we can save a valid unread_marker value.  NOTE: we will
451         * accept multiple FF's followed by a 0 as meaning a single FF data
452         * byte.  This data pattern is not valid according to the standard.
453         */
454        do {
455          if (bytes_in_buffer == 0) {
456            if (! (*cinfo->src->fill_input_buffer) (cinfo))
457              return FALSE;
458            next_input_byte = cinfo->src->next_input_byte;
459            bytes_in_buffer = cinfo->src->bytes_in_buffer;
460          }
461          bytes_in_buffer--;
462          c = GETJOCTET(*next_input_byte++);
463        } while (c == 0xFF);
464
465        if (c == 0) {
466          /* Found FF/00, which represents an FF data byte */
467          c = 0xFF;
468        } else {
469          /* Oops, it's actually a marker indicating end of compressed data.
470           * Save the marker code for later use.
471           * Fine point: it might appear that we should save the marker into
472           * bitread working state, not straight into permanent state.  But
473           * once we have hit a marker, we cannot need to suspend within the
474           * current MCU, because we will read no more bytes from the data
475           * source.  So it is OK to update permanent state right away.
476           */
477          cinfo->unread_marker = c;
478          /* See if we need to insert some fake zero bits. */
479          goto no_more_bytes;
480        }
481      }
482
483      /* OK, load c into get_buffer */
484      get_buffer = (get_buffer << 8) | c;
485      bits_left += 8;
486    } /* end while */
487  } else {
488  no_more_bytes:
489    /* We get here if we've read the marker that terminates the compressed
490     * data segment.  There should be enough bits in the buffer register
491     * to satisfy the request; if so, no problem.
492     */
493    if (nbits > bits_left) {
494      /* Uh-oh.  Report corrupted data to user and stuff zeroes into
495       * the data stream, so that we can produce some kind of image.
496       * We use a nonvolatile flag to ensure that only one warning message
497       * appears per data segment.
498       */
499      if (! cinfo->entropy->insufficient_data) {
500        WARNMS(cinfo, JWRN_HIT_MARKER);
501        cinfo->entropy->insufficient_data = TRUE;
502      }
503      /* Fill the buffer with zero bits */
504      get_buffer <<= MIN_GET_BITS - bits_left;
505      bits_left = MIN_GET_BITS;
506    }
507  }
508
509  /* Unload the local registers */
510  state->next_input_byte = next_input_byte;
511  state->bytes_in_buffer = bytes_in_buffer;
512  state->get_buffer = get_buffer;
513  state->bits_left = bits_left;
514
515  return TRUE;
516}
517
518
519/*
520 * Figure F.12: extend sign bit.
521 * On some machines, a shift and sub will be faster than a table lookup.
522 */
523
524#ifdef AVOID_TABLES
525
526#define BIT_MASK(nbits)   ((1<<(nbits))-1)
527#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
528
529#else
530
531#define BIT_MASK(nbits)   bmask[nbits]
532#define HUFF_EXTEND(x,s)  ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
533
534static const int bmask[16] =    /* bmask[n] is mask for n rightmost bits */
535  { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
536    0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
537
538#endif /* AVOID_TABLES */
539
540
541/*
542 * Out-of-line code for Huffman code decoding.
543 */
544
545LOCAL(int)
546jpeg_huff_decode (bitread_working_state * state,
547                  register bit_buf_type get_buffer, register int bits_left,
548                  d_derived_tbl * htbl, int min_bits)
549{
550  register int l = min_bits;
551  register INT32 code;
552
553  /* HUFF_DECODE has determined that the code is at least min_bits */
554  /* bits long, so fetch that many bits in one swoop. */
555
556  CHECK_BIT_BUFFER(*state, l, return -1);
557  code = GET_BITS(l);
558
559  /* Collect the rest of the Huffman code one bit at a time. */
560  /* This is per Figure F.16 in the JPEG spec. */
561
562  while (code > htbl->maxcode[l]) {
563    code <<= 1;
564    CHECK_BIT_BUFFER(*state, 1, return -1);
565    code |= GET_BITS(1);
566    l++;
567  }
568
569  /* Unload the local registers */
570  state->get_buffer = get_buffer;
571  state->bits_left = bits_left;
572
573  /* With garbage input we may reach the sentinel value l = 17. */
574
575  if (l > 16) {
576    WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
577    return 0;                   /* fake a zero as the safest result */
578  }
579
580  return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
581}
582
583
584/*
585 * Check for a restart marker & resynchronize decoder.
586 * Returns FALSE if must suspend.
587 */
588
589LOCAL(boolean)
590process_restart (j_decompress_ptr cinfo)
591{
592  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
593  int ci;
594
595  /* Throw away any unused bits remaining in bit buffer; */
596  /* include any full bytes in next_marker's count of discarded bytes */
597  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
598  entropy->bitstate.bits_left = 0;
599
600  /* Advance past the RSTn marker */
601  if (! (*cinfo->marker->read_restart_marker) (cinfo))
602    return FALSE;
603
604  /* Re-initialize DC predictions to 0 */
605  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
606    entropy->saved.last_dc_val[ci] = 0;
607  /* Re-init EOB run count, too */
608  entropy->saved.EOBRUN = 0;
609
610  /* Reset restart counter */
611  entropy->restarts_to_go = cinfo->restart_interval;
612
613  /* Reset out-of-data flag, unless read_restart_marker left us smack up
614   * against a marker.  In that case we will end up treating the next data
615   * segment as empty, and we can avoid producing bogus output pixels by
616   * leaving the flag set.
617   */
618  if (cinfo->unread_marker == 0)
619    entropy->pub.insufficient_data = FALSE;
620
621  return TRUE;
622}
623
624
625/*
626 * Huffman MCU decoding.
627 * Each of these routines decodes and returns one MCU's worth of
628 * Huffman-compressed coefficients.
629 * The coefficients are reordered from zigzag order into natural array order,
630 * but are not dequantized.
631 *
632 * The i'th block of the MCU is stored into the block pointed to by
633 * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
634 * (Wholesale zeroing is usually a little faster than retail...)
635 *
636 * We return FALSE if data source requested suspension.  In that case no
637 * changes have been made to permanent state.  (Exception: some output
638 * coefficients may already have been assigned.  This is harmless for
639 * spectral selection, since we'll just re-assign them on the next call.
640 * Successive approximation AC refinement has to be more careful, however.)
641 */
642
643/*
644 * MCU decoding for DC initial scan (either spectral selection,
645 * or first pass of successive approximation).
646 */
647
648METHODDEF(boolean)
649decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
650{   
651  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
652  int Al = cinfo->Al;
653  register int s, r;
654  int blkn, ci;
655  JBLOCKROW block;
656  BITREAD_STATE_VARS;
657  savable_state state;
658  d_derived_tbl * tbl;
659  jpeg_component_info * compptr;
660
661  /* Process restart marker if needed; may have to suspend */
662  if (cinfo->restart_interval) {
663    if (entropy->restarts_to_go == 0)
664      if (! process_restart(cinfo))
665        return FALSE;
666  }
667
668  /* If we've run out of data, just leave the MCU set to zeroes.
669   * This way, we return uniform gray for the remainder of the segment.
670   */
671  if (! entropy->pub.insufficient_data) {
672
673    /* Load up working state */
674    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
675    ASSIGN_STATE(state, entropy->saved);
676
677    /* Outer loop handles each block in the MCU */
678
679    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
680      block = MCU_data[blkn];
681      ci = cinfo->MCU_membership[blkn];
682      compptr = cinfo->cur_comp_info[ci];
683      tbl = entropy->derived_tbls[compptr->dc_tbl_no];
684
685      /* Decode a single block's worth of coefficients */
686
687      /* Section F.2.2.1: decode the DC coefficient difference */
688      HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
689      if (s) {
690        CHECK_BIT_BUFFER(br_state, s, return FALSE);
691        r = GET_BITS(s);
692        s = HUFF_EXTEND(r, s);
693      }
694
695      /* Convert DC difference to actual value, update last_dc_val */
696      s += state.last_dc_val[ci];
697      state.last_dc_val[ci] = s;
698      /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
699      (*block)[0] = (JCOEF) (s << Al);
700    }
701
702    /* Completed MCU, so update state */
703    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
704    ASSIGN_STATE(entropy->saved, state);
705  }
706
707  /* Account for restart interval (no-op if not using restarts) */
708  entropy->restarts_to_go--;
709
710  return TRUE;
711}
712
713
714/*
715 * MCU decoding for AC initial scan (either spectral selection,
716 * or first pass of successive approximation).
717 */
718
719METHODDEF(boolean)
720decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
721{   
722  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
723  int Se = cinfo->Se;
724  int Al = cinfo->Al;
725  register int s, k, r;
726  unsigned int EOBRUN;
727  JBLOCKROW block;
728  BITREAD_STATE_VARS;
729  d_derived_tbl * tbl;
730
731  /* Process restart marker if needed; may have to suspend */
732  if (cinfo->restart_interval) {
733    if (entropy->restarts_to_go == 0)
734      if (! process_restart(cinfo))
735        return FALSE;
736  }
737
738  /* If we've run out of data, just leave the MCU set to zeroes.
739   * This way, we return uniform gray for the remainder of the segment.
740   */
741  if (! entropy->pub.insufficient_data) {
742
743    /* Load up working state.
744     * We can avoid loading/saving bitread state if in an EOB run.
745     */
746    EOBRUN = entropy->saved.EOBRUN;     /* only part of saved state we need */
747
748    /* There is always only one block per MCU */
749
750    if (EOBRUN > 0)             /* if it's a band of zeroes... */
751      EOBRUN--;                 /* ...process it now (we do nothing) */
752    else {
753      BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
754      block = MCU_data[0];
755      tbl = entropy->ac_derived_tbl;
756
757      for (k = cinfo->Ss; k <= Se; k++) {
758        HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
759        r = s >> 4;
760        s &= 15;
761        if (s) {
762          k += r;
763          CHECK_BIT_BUFFER(br_state, s, return FALSE);
764          r = GET_BITS(s);
765          s = HUFF_EXTEND(r, s);
766          /* Scale and output coefficient in natural (dezigzagged) order */
767          (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
768        } else {
769          if (r == 15) {        /* ZRL */
770            k += 15;            /* skip 15 zeroes in band */
771          } else {              /* EOBr, run length is 2^r + appended bits */
772            EOBRUN = 1 << r;
773            if (r) {            /* EOBr, r > 0 */
774              CHECK_BIT_BUFFER(br_state, r, return FALSE);
775              r = GET_BITS(r);
776              EOBRUN += r;
777            }
778            EOBRUN--;           /* this band is processed at this moment */
779            break;              /* force end-of-band */
780          }
781        }
782      }
783
784      BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
785    }
786
787    /* Completed MCU, so update state */
788    entropy->saved.EOBRUN = EOBRUN;     /* only part of saved state we need */
789  }
790
791  /* Account for restart interval (no-op if not using restarts) */
792  entropy->restarts_to_go--;
793
794  return TRUE;
795}
796
797
798/*
799 * MCU decoding for DC successive approximation refinement scan.
800 * Note: we assume such scans can be multi-component, although the spec
801 * is not very clear on the point.
802 */
803
804METHODDEF(boolean)
805decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
806{   
807  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
808  int p1 = 1 << cinfo->Al;      /* 1 in the bit position being coded */
809  int blkn;
810  JBLOCKROW block;
811  BITREAD_STATE_VARS;
812
813  /* Process restart marker if needed; may have to suspend */
814  if (cinfo->restart_interval) {
815    if (entropy->restarts_to_go == 0)
816      if (! process_restart(cinfo))
817        return FALSE;
818  }
819
820  /* Not worth the cycles to check insufficient_data here,
821   * since we will not change the data anyway if we read zeroes.
822   */
823
824  /* Load up working state */
825  BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
826
827  /* Outer loop handles each block in the MCU */
828
829  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
830    block = MCU_data[blkn];
831
832    /* Encoded data is simply the next bit of the two's-complement DC value */
833    CHECK_BIT_BUFFER(br_state, 1, return FALSE);
834    if (GET_BITS(1))
835      (*block)[0] |= p1;
836    /* Note: since we use |=, repeating the assignment later is safe */
837  }
838
839  /* Completed MCU, so update state */
840  BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
841
842  /* Account for restart interval (no-op if not using restarts) */
843  entropy->restarts_to_go--;
844
845  return TRUE;
846}
847
848
849/*
850 * MCU decoding for AC successive approximation refinement scan.
851 */
852
853METHODDEF(boolean)
854decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
855{   
856  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
857  int Se = cinfo->Se;
858  int p1 = 1 << cinfo->Al;      /* 1 in the bit position being coded */
859  int m1 = (-1) << cinfo->Al;   /* -1 in the bit position being coded */
860  register int s, k, r;
861  unsigned int EOBRUN;
862  JBLOCKROW block;
863  JCOEFPTR thiscoef;
864  BITREAD_STATE_VARS;
865  d_derived_tbl * tbl;
866  int num_newnz;
867  int newnz_pos[DCTSIZE2];
868
869  /* Process restart marker if needed; may have to suspend */
870  if (cinfo->restart_interval) {
871    if (entropy->restarts_to_go == 0)
872      if (! process_restart(cinfo))
873        return FALSE;
874  }
875
876  /* If we've run out of data, don't modify the MCU.
877   */
878  if (! entropy->pub.insufficient_data) {
879
880    /* Load up working state */
881    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
882    EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
883
884    /* There is always only one block per MCU */
885    block = MCU_data[0];
886    tbl = entropy->ac_derived_tbl;
887
888    /* If we are forced to suspend, we must undo the assignments to any newly
889     * nonzero coefficients in the block, because otherwise we'd get confused
890     * next time about which coefficients were already nonzero.
891     * But we need not undo addition of bits to already-nonzero coefficients;
892     * instead, we can test the current bit to see if we already did it.
893     */
894    num_newnz = 0;
895
896    /* initialize coefficient loop counter to start of band */
897    k = cinfo->Ss;
898
899    if (EOBRUN == 0) {
900      for (; k <= Se; k++) {
901        HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
902        r = s >> 4;
903        s &= 15;
904        if (s) {
905          if (s != 1)           /* size of new coef should always be 1 */
906            WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
907          CHECK_BIT_BUFFER(br_state, 1, goto undoit);
908          if (GET_BITS(1))
909            s = p1;             /* newly nonzero coef is positive */
910          else
911            s = m1;             /* newly nonzero coef is negative */
912        } else {
913          if (r != 15) {
914            EOBRUN = 1 << r;    /* EOBr, run length is 2^r + appended bits */
915            if (r) {
916              CHECK_BIT_BUFFER(br_state, r, goto undoit);
917              r = GET_BITS(r);
918              EOBRUN += r;
919            }
920            break;              /* rest of block is handled by EOB logic */
921          }
922          /* note s = 0 for processing ZRL */
923        }
924        /* Advance over already-nonzero coefs and r still-zero coefs,
925         * appending correction bits to the nonzeroes.  A correction bit is 1
926         * if the absolute value of the coefficient must be increased.
927         */
928        do {
929          thiscoef = *block + jpeg_natural_order[k];
930          if (*thiscoef != 0) {
931            CHECK_BIT_BUFFER(br_state, 1, goto undoit);
932            if (GET_BITS(1)) {
933              if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
934                if (*thiscoef >= 0)
935                  *thiscoef += p1;
936                else
937                  *thiscoef += m1;
938              }
939            }
940          } else {
941            if (--r < 0)
942              break;            /* reached target zero coefficient */
943          }
944          k++;
945        } while (k <= Se);
946        if (s) {
947          int pos = jpeg_natural_order[k];
948          /* Output newly nonzero coefficient */
949          (*block)[pos] = (JCOEF) s;
950          /* Remember its position in case we have to suspend */
951          newnz_pos[num_newnz++] = pos;
952        }
953      }
954    }
955
956    if (EOBRUN > 0) {
957      /* Scan any remaining coefficient positions after the end-of-band
958       * (the last newly nonzero coefficient, if any).  Append a correction
959       * bit to each already-nonzero coefficient.  A correction bit is 1
960       * if the absolute value of the coefficient must be increased.
961       */
962      for (; k <= Se; k++) {
963        thiscoef = *block + jpeg_natural_order[k];
964        if (*thiscoef != 0) {
965          CHECK_BIT_BUFFER(br_state, 1, goto undoit);
966          if (GET_BITS(1)) {
967            if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
968              if (*thiscoef >= 0)
969                *thiscoef += p1;
970              else
971                *thiscoef += m1;
972            }
973          }
974        }
975      }
976      /* Count one block completed in EOB run */
977      EOBRUN--;
978    }
979
980    /* Completed MCU, so update state */
981    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
982    entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
983  }
984
985  /* Account for restart interval (no-op if not using restarts) */
986  entropy->restarts_to_go--;
987
988  return TRUE;
989
990undoit:
991  /* Re-zero any output coefficients that we made newly nonzero */
992  while (num_newnz > 0)
993    (*block)[newnz_pos[--num_newnz]] = 0;
994
995  return FALSE;
996}
997
998
999/*
1000 * Decode one MCU's worth of Huffman-compressed coefficients.
1001 */
1002
1003METHODDEF(boolean)
1004decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
1005{
1006  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1007  int blkn;
1008  BITREAD_STATE_VARS;
1009  savable_state state;
1010
1011  /* Process restart marker if needed; may have to suspend */
1012  if (cinfo->restart_interval) {
1013    if (entropy->restarts_to_go == 0)
1014      if (! process_restart(cinfo))
1015        return FALSE;
1016  }
1017
1018  /* If we've run out of data, just leave the MCU set to zeroes.
1019   * This way, we return uniform gray for the remainder of the segment.
1020   */
1021  if (! entropy->pub.insufficient_data) {
1022
1023    /* Load up working state */
1024    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
1025    ASSIGN_STATE(state, entropy->saved);
1026
1027    /* Outer loop handles each block in the MCU */
1028
1029    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1030      JBLOCKROW block = MCU_data[blkn];
1031      d_derived_tbl * htbl;
1032      register int s, k, r;
1033      int coef_limit, ci;
1034
1035      /* Decode a single block's worth of coefficients */
1036
1037      /* Section F.2.2.1: decode the DC coefficient difference */
1038      htbl = entropy->dc_cur_tbls[blkn];
1039      HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
1040
1041      htbl = entropy->ac_cur_tbls[blkn];
1042      k = 1;
1043      coef_limit = entropy->coef_limit[blkn];
1044      if (coef_limit) {
1045        /* Convert DC difference to actual value, update last_dc_val */
1046        if (s) {
1047          CHECK_BIT_BUFFER(br_state, s, return FALSE);
1048          r = GET_BITS(s);
1049          s = HUFF_EXTEND(r, s);
1050        }
1051        ci = cinfo->MCU_membership[blkn];
1052        s += state.last_dc_val[ci];
1053        state.last_dc_val[ci] = s;
1054        /* Output the DC coefficient */
1055        (*block)[0] = (JCOEF) s;
1056
1057        /* Section F.2.2.2: decode the AC coefficients */
1058        /* Since zeroes are skipped, output area must be cleared beforehand */
1059        for (; k < coef_limit; k++) {
1060          HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
1061
1062          r = s >> 4;
1063          s &= 15;
1064
1065          if (s) {
1066            k += r;
1067            CHECK_BIT_BUFFER(br_state, s, return FALSE);
1068            r = GET_BITS(s);
1069            s = HUFF_EXTEND(r, s);
1070            /* Output coefficient in natural (dezigzagged) order.
1071             * Note: the extra entries in jpeg_natural_order[] will save us
1072             * if k >= DCTSIZE2, which could happen if the data is corrupted.
1073             */
1074            (*block)[jpeg_natural_order[k]] = (JCOEF) s;
1075          } else {
1076            if (r != 15)
1077              goto EndOfBlock;
1078            k += 15;
1079          }
1080        }
1081      } else {
1082        if (s) {
1083          CHECK_BIT_BUFFER(br_state, s, return FALSE);
1084          DROP_BITS(s);
1085        }
1086      }
1087
1088      /* Section F.2.2.2: decode the AC coefficients */
1089      /* In this path we just discard the values */
1090      for (; k < DCTSIZE2; k++) {
1091        HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
1092
1093        r = s >> 4;
1094        s &= 15;
1095
1096        if (s) {
1097          k += r;
1098          CHECK_BIT_BUFFER(br_state, s, return FALSE);
1099          DROP_BITS(s);
1100        } else {
1101          if (r != 15)
1102            break;
1103          k += 15;
1104        }
1105      }
1106
1107      EndOfBlock: ;
1108    }
1109
1110    /* Completed MCU, so update state */
1111    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
1112    ASSIGN_STATE(entropy->saved, state);
1113  }
1114
1115  /* Account for restart interval (no-op if not using restarts) */
1116  entropy->restarts_to_go--;
1117
1118  return TRUE;
1119}
1120
1121
1122/*
1123 * Initialize for a Huffman-compressed scan.
1124 */
1125
1126METHODDEF(void)
1127start_pass_huff_decoder (j_decompress_ptr cinfo)
1128{
1129  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
1130  int ci, blkn, dctbl, actbl, i;
1131  jpeg_component_info * compptr;
1132
1133  if (cinfo->progressive_mode) {
1134    /* Validate progressive scan parameters */
1135    if (cinfo->Ss == 0) {
1136      if (cinfo->Se != 0)
1137        goto bad;
1138    } else {
1139      /* need not check Ss/Se < 0 since they came from unsigned bytes */
1140      if (cinfo->Se < cinfo->Ss || cinfo->Se >= DCTSIZE2)
1141        goto bad;
1142      /* AC scans may have only one component */
1143      if (cinfo->comps_in_scan != 1)
1144        goto bad;
1145    }
1146    if (cinfo->Ah != 0) {
1147      /* Successive approximation refinement scan: must have Al = Ah-1. */
1148      if (cinfo->Ah-1 != cinfo->Al)
1149        goto bad;
1150    }
1151    if (cinfo->Al > 13) {       /* need not check for < 0 */
1152      /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
1153       * but the spec doesn't say so, and we try to be liberal about what we
1154       * accept.  Note: large Al values could result in out-of-range DC
1155       * coefficients during early scans, leading to bizarre displays due to
1156       * overflows in the IDCT math.  But we won't crash.
1157       */
1158      bad:
1159      ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
1160               cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
1161    }
1162    /* Update progression status, and verify that scan order is legal.
1163     * Note that inter-scan inconsistencies are treated as warnings
1164     * not fatal errors ... not clear if this is right way to behave.
1165     */
1166    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1167      int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
1168      int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
1169      if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
1170        WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
1171      for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
1172        int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
1173        if (cinfo->Ah != expected)
1174          WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
1175        coef_bit_ptr[coefi] = cinfo->Al;
1176      }
1177    }
1178
1179    /* Select MCU decoding routine */
1180    if (cinfo->Ah == 0) {
1181      if (cinfo->Ss == 0)
1182        entropy->pub.decode_mcu = decode_mcu_DC_first;
1183      else
1184        entropy->pub.decode_mcu = decode_mcu_AC_first;
1185    } else {
1186      if (cinfo->Ss == 0)
1187        entropy->pub.decode_mcu = decode_mcu_DC_refine;
1188      else
1189        entropy->pub.decode_mcu = decode_mcu_AC_refine;
1190    }
1191
1192    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1193      compptr = cinfo->cur_comp_info[ci];
1194      /* Make sure requested tables are present, and compute derived tables.
1195       * We may build same derived table more than once, but it's not expensive.
1196       */
1197      if (cinfo->Ss == 0) {
1198        if (cinfo->Ah == 0) {   /* DC refinement needs no table */
1199          i = compptr->dc_tbl_no;
1200          jpeg_make_d_derived_tbl(cinfo, TRUE, i,
1201                                  & entropy->derived_tbls[i]);
1202        }
1203      } else {
1204        i = compptr->ac_tbl_no;
1205        jpeg_make_d_derived_tbl(cinfo, FALSE, i,
1206                                & entropy->derived_tbls[i]);
1207        /* remember the single active table */
1208        entropy->ac_derived_tbl = entropy->derived_tbls[i];
1209      }
1210      /* Initialize DC predictions to 0 */
1211      entropy->saved.last_dc_val[ci] = 0;
1212    }
1213
1214    /* Initialize private state variables */
1215    entropy->saved.EOBRUN = 0;
1216  } else {
1217    /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
1218     * This ought to be an error condition, but we make it a warning because
1219     * there are some baseline files out there with all zeroes in these bytes.
1220     */
1221    if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
1222        cinfo->Ah != 0 || cinfo->Al != 0)
1223      WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
1224
1225    /* Select MCU decoding routine */
1226    entropy->pub.decode_mcu = decode_mcu;
1227
1228    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
1229      compptr = cinfo->cur_comp_info[ci];
1230      dctbl = compptr->dc_tbl_no;
1231      actbl = compptr->ac_tbl_no;
1232      /* Compute derived values for Huffman tables */
1233      /* We may do this more than once for a table, but it's not expensive */
1234      jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
1235                              & entropy->dc_derived_tbls[dctbl]);
1236      jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
1237                              & entropy->ac_derived_tbls[actbl]);
1238      /* Initialize DC predictions to 0 */
1239      entropy->saved.last_dc_val[ci] = 0;
1240    }
1241
1242    /* Precalculate decoding info for each block in an MCU of this scan */
1243    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
1244      ci = cinfo->MCU_membership[blkn];
1245      compptr = cinfo->cur_comp_info[ci];
1246      /* Precalculate which table to use for each block */
1247      entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
1248      entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
1249      /* Decide whether we really care about the coefficient values */
1250      if (compptr->component_needed) {
1251        ci = compptr->DCT_v_scaled_size;
1252        if (ci <= 0 || ci > 8) ci = 8;
1253        i = compptr->DCT_h_scaled_size;
1254        if (i <= 0 || i > 8) i = 8;
1255        entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
1256      } else {
1257        entropy->coef_limit[blkn] = 0;
1258      }
1259    }
1260  }
1261
1262  /* Initialize bitread state variables */
1263  entropy->bitstate.bits_left = 0;
1264  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
1265  entropy->pub.insufficient_data = FALSE;
1266
1267  /* Initialize restart counter */
1268  entropy->restarts_to_go = cinfo->restart_interval;
1269}
1270
1271
1272/*
1273 * Module initialization routine for Huffman entropy decoding.
1274 */
1275
1276GLOBAL(void)
1277jinit_huff_decoder (j_decompress_ptr cinfo)
1278{
1279  huff_entropy_ptr entropy;
1280  int i;
1281
1282  entropy = (huff_entropy_ptr)
1283    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1284                                SIZEOF(huff_entropy_decoder));
1285  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
1286  entropy->pub.start_pass = start_pass_huff_decoder;
1287
1288  if (cinfo->progressive_mode) {
1289    /* Create progression status table */
1290    int *coef_bit_ptr, ci;
1291    cinfo->coef_bits = (int (*)[DCTSIZE2])
1292      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1293                                  cinfo->num_components*DCTSIZE2*SIZEOF(int));
1294    coef_bit_ptr = & cinfo->coef_bits[0][0];
1295    for (ci = 0; ci < cinfo->num_components; ci++)
1296      for (i = 0; i < DCTSIZE2; i++)
1297        *coef_bit_ptr++ = -1;
1298
1299    /* Mark derived tables unallocated */
1300    for (i = 0; i < NUM_HUFF_TBLS; i++) {
1301      entropy->derived_tbls[i] = NULL;
1302    }
1303  } else {
1304    /* Mark tables unallocated */
1305    for (i = 0; i < NUM_HUFF_TBLS; i++) {
1306      entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
1307    }
1308  }
1309}
Note: See TracBrowser for help on using the repository browser.