Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/media/libjpeg/jdhuff.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * jdhuff.c
3
 *
4
 * This file was part of the Independent JPEG Group's software:
5
 * Copyright (C) 1991-1997, Thomas G. Lane.
6
 * libjpeg-turbo Modifications:
7
 * Copyright (C) 2009-2011, 2016, 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.
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
20
#define JPEG_INTERNALS
21
#include "jinclude.h"
22
#include "jpeglib.h"
23
#include "jdhuff.h"             /* Declarations shared with jdphuff.c */
24
#include "jpegcomp.h"
25
#include "jstdhuff.c"
26
27
28
/*
29
 * Expanded entropy decoder object for Huffman decoding.
30
 *
31
 * The savable_state subrecord contains fields that change within an MCU,
32
 * but must not be updated permanently until we complete the MCU.
33
 */
34
35
typedef struct {
36
  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
37
} savable_state;
38
39
/* This macro is to work around compilers with missing or broken
40
 * structure assignment.  You'll need to fix this code if you have
41
 * such a compiler and you change MAX_COMPS_IN_SCAN.
42
 */
43
44
#ifndef NO_STRUCT_ASSIGN
45
0
#define ASSIGN_STATE(dest,src)  ((dest) = (src))
46
#else
47
#if MAX_COMPS_IN_SCAN == 4
48
#define ASSIGN_STATE(dest,src)  \
49
        ((dest).last_dc_val[0] = (src).last_dc_val[0], \
50
         (dest).last_dc_val[1] = (src).last_dc_val[1], \
51
         (dest).last_dc_val[2] = (src).last_dc_val[2], \
52
         (dest).last_dc_val[3] = (src).last_dc_val[3])
53
#endif
54
#endif
55
56
57
typedef struct {
58
  struct jpeg_entropy_decoder pub; /* public fields */
59
60
  /* These fields are loaded into local variables at start of each MCU.
61
   * In case of suspension, we exit WITHOUT updating them.
62
   */
63
  bitread_perm_state bitstate;  /* Bit buffer at start of MCU */
64
  savable_state saved;          /* Other state at start of MCU */
65
66
  /* These fields are NOT loaded into local working state. */
67
  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
68
69
  /* Pointers to derived tables (these workspaces have image lifespan) */
70
  d_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
71
  d_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
72
73
  /* Precalculated info set up by start_pass for use in decode_mcu: */
74
75
  /* Pointers to derived tables to be used for each block within an MCU */
76
  d_derived_tbl *dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
77
  d_derived_tbl *ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
78
  /* Whether we care about the DC and AC coefficient values for each block */
79
  boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
80
  boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
81
} huff_entropy_decoder;
82
83
typedef huff_entropy_decoder *huff_entropy_ptr;
84
85
86
/*
87
 * Initialize for a Huffman-compressed scan.
88
 */
89
90
METHODDEF(void)
91
start_pass_huff_decoder (j_decompress_ptr cinfo)
92
0
{
93
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
94
0
  int ci, blkn, dctbl, actbl;
95
0
  d_derived_tbl **pdtbl;
96
0
  jpeg_component_info *compptr;
97
0
98
0
  /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
99
0
   * This ought to be an error condition, but we make it a warning because
100
0
   * there are some baseline files out there with all zeroes in these bytes.
101
0
   */
102
0
  if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
103
0
      cinfo->Ah != 0 || cinfo->Al != 0)
104
0
    WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
105
0
106
0
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
107
0
    compptr = cinfo->cur_comp_info[ci];
108
0
    dctbl = compptr->dc_tbl_no;
109
0
    actbl = compptr->ac_tbl_no;
110
0
    /* Compute derived values for Huffman tables */
111
0
    /* We may do this more than once for a table, but it's not expensive */
112
0
    pdtbl = (d_derived_tbl **)(entropy->dc_derived_tbls) + dctbl;
113
0
    jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl, pdtbl);
114
0
    pdtbl = (d_derived_tbl **)(entropy->ac_derived_tbls) + actbl;
115
0
    jpeg_make_d_derived_tbl(cinfo, FALSE, actbl, pdtbl);
116
0
    /* Initialize DC predictions to 0 */
117
0
    entropy->saved.last_dc_val[ci] = 0;
118
0
  }
119
0
120
0
  /* Precalculate decoding info for each block in an MCU of this scan */
121
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
122
0
    ci = cinfo->MCU_membership[blkn];
123
0
    compptr = cinfo->cur_comp_info[ci];
124
0
    /* Precalculate which table to use for each block */
125
0
    entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
126
0
    entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
127
0
    /* Decide whether we really care about the coefficient values */
128
0
    if (compptr->component_needed) {
129
0
      entropy->dc_needed[blkn] = TRUE;
130
0
      /* we don't need the ACs if producing a 1/8th-size image */
131
0
      entropy->ac_needed[blkn] = (compptr->_DCT_scaled_size > 1);
132
0
    } else {
133
0
      entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
134
0
    }
135
0
  }
136
0
137
0
  /* Initialize bitread state variables */
138
0
  entropy->bitstate.bits_left = 0;
139
0
  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
140
0
  entropy->pub.insufficient_data = FALSE;
141
0
142
0
  /* Initialize restart counter */
143
0
  entropy->restarts_to_go = cinfo->restart_interval;
144
0
}
145
146
147
/*
148
 * Compute the derived values for a Huffman table.
149
 * This routine also performs some validation checks on the table.
150
 *
151
 * Note this is also used by jdphuff.c.
152
 */
153
154
GLOBAL(void)
155
jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
156
                         d_derived_tbl **pdtbl)
157
0
{
158
0
  JHUFF_TBL *htbl;
159
0
  d_derived_tbl *dtbl;
160
0
  int p, i, l, si, numsymbols;
161
0
  int lookbits, ctr;
162
0
  char huffsize[257];
163
0
  unsigned int huffcode[257];
164
0
  unsigned int code;
165
0
166
0
  /* Note that huffsize[] and huffcode[] are filled in code-length order,
167
0
   * paralleling the order of the symbols themselves in htbl->huffval[].
168
0
   */
169
0
170
0
  /* Find the input Huffman table */
171
0
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
172
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
173
0
  htbl =
174
0
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
175
0
  if (htbl == NULL)
176
0
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
177
0
178
0
  /* Allocate a workspace if we haven't already done so. */
179
0
  if (*pdtbl == NULL)
180
0
    *pdtbl = (d_derived_tbl *)
181
0
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
182
0
                                  sizeof(d_derived_tbl));
183
0
  dtbl = *pdtbl;
184
0
  dtbl->pub = htbl;             /* fill in back link */
185
0
186
0
  /* Figure C.1: make table of Huffman code length for each symbol */
187
0
188
0
  p = 0;
189
0
  for (l = 1; l <= 16; l++) {
190
0
    i = (int) htbl->bits[l];
191
0
    if (i < 0 || p + i > 256)   /* protect against table overrun */
192
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
193
0
    while (i--)
194
0
      huffsize[p++] = (char) l;
195
0
  }
196
0
  huffsize[p] = 0;
197
0
  numsymbols = p;
198
0
199
0
  /* Figure C.2: generate the codes themselves */
200
0
  /* We also validate that the counts represent a legal Huffman code tree. */
201
0
202
0
  code = 0;
203
0
  si = huffsize[0];
204
0
  p = 0;
205
0
  while (huffsize[p]) {
206
0
    while (((int) huffsize[p]) == si) {
207
0
      huffcode[p++] = code;
208
0
      code++;
209
0
    }
210
0
    /* code is now 1 more than the last code used for codelength si; but
211
0
     * it must still fit in si bits, since no code is allowed to be all ones.
212
0
     */
213
0
    if (((JLONG) code) >= (((JLONG) 1) << si))
214
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
215
0
    code <<= 1;
216
0
    si++;
217
0
  }
218
0
219
0
  /* Figure F.15: generate decoding tables for bit-sequential decoding */
220
0
221
0
  p = 0;
222
0
  for (l = 1; l <= 16; l++) {
223
0
    if (htbl->bits[l]) {
224
0
      /* valoffset[l] = huffval[] index of 1st symbol of code length l,
225
0
       * minus the minimum code of length l
226
0
       */
227
0
      dtbl->valoffset[l] = (JLONG) p - (JLONG) huffcode[p];
228
0
      p += htbl->bits[l];
229
0
      dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
230
0
    } else {
231
0
      dtbl->maxcode[l] = -1;    /* -1 if no codes of this length */
232
0
    }
233
0
  }
234
0
  dtbl->valoffset[17] = 0;
235
0
  dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
236
0
237
0
  /* Compute lookahead tables to speed up decoding.
238
0
   * First we set all the table entries to 0, indicating "too long";
239
0
   * then we iterate through the Huffman codes that are short enough and
240
0
   * fill in all the entries that correspond to bit sequences starting
241
0
   * with that code.
242
0
   */
243
0
244
0
   for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++)
245
0
     dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;
246
0
247
0
  p = 0;
248
0
  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
249
0
    for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
250
0
      /* l = current code's length, p = its index in huffcode[] & huffval[]. */
251
0
      /* Generate left-justified code followed by all possible bit sequences */
252
0
      lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
253
0
      for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
254
0
        dtbl->lookup[lookbits] = (l << HUFF_LOOKAHEAD) | htbl->huffval[p];
255
0
        lookbits++;
256
0
      }
257
0
    }
258
0
  }
259
0
260
0
  /* Validate symbols as being reasonable.
261
0
   * For AC tables, we make no check, but accept all byte values 0..255.
262
0
   * For DC tables, we require the symbols to be in range 0..15.
263
0
   * (Tighter bounds could be applied depending on the data depth and mode,
264
0
   * but this is sufficient to ensure safe decoding.)
265
0
   */
266
0
  if (isDC) {
267
0
    for (i = 0; i < numsymbols; i++) {
268
0
      int sym = htbl->huffval[i];
269
0
      if (sym < 0 || sym > 15)
270
0
        ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
271
0
    }
272
0
  }
273
0
}
274
275
276
/*
277
 * Out-of-line code for bit fetching (shared with jdphuff.c).
278
 * See jdhuff.h for info about usage.
279
 * Note: current values of get_buffer and bits_left are passed as parameters,
280
 * but are returned in the corresponding fields of the state struct.
281
 *
282
 * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
283
 * of get_buffer to be used.  (On machines with wider words, an even larger
284
 * buffer could be used.)  However, on some machines 32-bit shifts are
285
 * quite slow and take time proportional to the number of places shifted.
286
 * (This is true with most PC compilers, for instance.)  In this case it may
287
 * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
288
 * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
289
 */
290
291
#ifdef SLOW_SHIFT_32
292
#define MIN_GET_BITS  15        /* minimum allowable value */
293
#else
294
0
#define MIN_GET_BITS  (BIT_BUF_SIZE-7)
295
#endif
296
297
298
GLOBAL(boolean)
299
jpeg_fill_bit_buffer (bitread_working_state *state,
300
                      register bit_buf_type get_buffer, register int bits_left,
301
                      int nbits)
302
/* Load up the bit buffer to a depth of at least nbits */
303
0
{
304
0
  /* Copy heavily used state fields into locals (hopefully registers) */
305
0
  register const JOCTET *next_input_byte = state->next_input_byte;
306
0
  register size_t bytes_in_buffer = state->bytes_in_buffer;
307
0
  j_decompress_ptr cinfo = state->cinfo;
308
0
309
0
  /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
310
0
  /* (It is assumed that no request will be for more than that many bits.) */
311
0
  /* We fail to do so only if we hit a marker or are forced to suspend. */
312
0
313
0
  if (cinfo->unread_marker == 0) {      /* cannot advance past a marker */
314
0
    while (bits_left < MIN_GET_BITS) {
315
0
      register int c;
316
0
317
0
      /* Attempt to read a byte */
318
0
      if (bytes_in_buffer == 0) {
319
0
        if (! (*cinfo->src->fill_input_buffer) (cinfo))
320
0
          return FALSE;
321
0
        next_input_byte = cinfo->src->next_input_byte;
322
0
        bytes_in_buffer = cinfo->src->bytes_in_buffer;
323
0
      }
324
0
      bytes_in_buffer--;
325
0
      c = GETJOCTET(*next_input_byte++);
326
0
327
0
      /* If it's 0xFF, check and discard stuffed zero byte */
328
0
      if (c == 0xFF) {
329
0
        /* Loop here to discard any padding FF's on terminating marker,
330
0
         * so that we can save a valid unread_marker value.  NOTE: we will
331
0
         * accept multiple FF's followed by a 0 as meaning a single FF data
332
0
         * byte.  This data pattern is not valid according to the standard.
333
0
         */
334
0
        do {
335
0
          if (bytes_in_buffer == 0) {
336
0
            if (! (*cinfo->src->fill_input_buffer) (cinfo))
337
0
              return FALSE;
338
0
            next_input_byte = cinfo->src->next_input_byte;
339
0
            bytes_in_buffer = cinfo->src->bytes_in_buffer;
340
0
          }
341
0
          bytes_in_buffer--;
342
0
          c = GETJOCTET(*next_input_byte++);
343
0
        } while (c == 0xFF);
344
0
345
0
        if (c == 0) {
346
0
          /* Found FF/00, which represents an FF data byte */
347
0
          c = 0xFF;
348
0
        } else {
349
0
          /* Oops, it's actually a marker indicating end of compressed data.
350
0
           * Save the marker code for later use.
351
0
           * Fine point: it might appear that we should save the marker into
352
0
           * bitread working state, not straight into permanent state.  But
353
0
           * once we have hit a marker, we cannot need to suspend within the
354
0
           * current MCU, because we will read no more bytes from the data
355
0
           * source.  So it is OK to update permanent state right away.
356
0
           */
357
0
          cinfo->unread_marker = c;
358
0
          /* See if we need to insert some fake zero bits. */
359
0
          goto no_more_bytes;
360
0
        }
361
0
      }
362
0
363
0
      /* OK, load c into get_buffer */
364
0
      get_buffer = (get_buffer << 8) | c;
365
0
      bits_left += 8;
366
0
    } /* end while */
367
0
  } else {
368
0
  no_more_bytes:
369
0
    /* We get here if we've read the marker that terminates the compressed
370
0
     * data segment.  There should be enough bits in the buffer register
371
0
     * to satisfy the request; if so, no problem.
372
0
     */
373
0
    if (nbits > bits_left) {
374
0
      /* Uh-oh.  Report corrupted data to user and stuff zeroes into
375
0
       * the data stream, so that we can produce some kind of image.
376
0
       * We use a nonvolatile flag to ensure that only one warning message
377
0
       * appears per data segment.
378
0
       */
379
0
      if (! cinfo->entropy->insufficient_data) {
380
0
        WARNMS(cinfo, JWRN_HIT_MARKER);
381
0
        cinfo->entropy->insufficient_data = TRUE;
382
0
      }
383
0
      /* Fill the buffer with zero bits */
384
0
      get_buffer <<= MIN_GET_BITS - bits_left;
385
0
      bits_left = MIN_GET_BITS;
386
0
    }
387
0
  }
388
0
389
0
  /* Unload the local registers */
390
0
  state->next_input_byte = next_input_byte;
391
0
  state->bytes_in_buffer = bytes_in_buffer;
392
0
  state->get_buffer = get_buffer;
393
0
  state->bits_left = bits_left;
394
0
395
0
  return TRUE;
396
0
}
397
398
399
/* Macro version of the above, which performs much better but does not
400
   handle markers.  We have to hand off any blocks with markers to the
401
   slower routines. */
402
403
0
#define GET_BYTE \
404
0
{ \
405
0
  register int c0, c1; \
406
0
  c0 = GETJOCTET(*buffer++); \
407
0
  c1 = GETJOCTET(*buffer); \
408
0
  /* Pre-execute most common case */ \
409
0
  get_buffer = (get_buffer << 8) | c0; \
410
0
  bits_left += 8; \
411
0
  if (c0 == 0xFF) { \
412
0
    /* Pre-execute case of FF/00, which represents an FF data byte */ \
413
0
    buffer++; \
414
0
    if (c1 != 0) { \
415
0
      /* Oops, it's actually a marker indicating end of compressed data. */ \
416
0
      cinfo->unread_marker = c1; \
417
0
      /* Back out pre-execution and fill the buffer with zero bits */ \
418
0
      buffer -= 2; \
419
0
      get_buffer &= ~0xFF; \
420
0
    } \
421
0
  } \
422
0
}
423
424
#if SIZEOF_SIZE_T==8 || defined(_WIN64)
425
426
/* Pre-fetch 48 bytes, because the holding register is 64-bit */
427
#define FILL_BIT_BUFFER_FAST \
428
0
  if (bits_left <= 16) { \
429
0
    GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE \
430
0
  }
431
432
#else
433
434
/* Pre-fetch 16 bytes, because the holding register is 32-bit */
435
#define FILL_BIT_BUFFER_FAST \
436
  if (bits_left <= 16) { \
437
    GET_BYTE GET_BYTE \
438
  }
439
440
#endif
441
442
443
/*
444
 * Out-of-line code for Huffman code decoding.
445
 * See jdhuff.h for info about usage.
446
 */
447
448
GLOBAL(int)
449
jpeg_huff_decode (bitread_working_state *state,
450
                  register bit_buf_type get_buffer, register int bits_left,
451
                  d_derived_tbl *htbl, int min_bits)
452
0
{
453
0
  register int l = min_bits;
454
0
  register JLONG code;
455
0
456
0
  /* HUFF_DECODE has determined that the code is at least min_bits */
457
0
  /* bits long, so fetch that many bits in one swoop. */
458
0
459
0
  CHECK_BIT_BUFFER(*state, l, return -1);
460
0
  code = GET_BITS(l);
461
0
462
0
  /* Collect the rest of the Huffman code one bit at a time. */
463
0
  /* This is per Figure F.16 in the JPEG spec. */
464
0
465
0
  while (code > htbl->maxcode[l]) {
466
0
    code <<= 1;
467
0
    CHECK_BIT_BUFFER(*state, 1, return -1);
468
0
    code |= GET_BITS(1);
469
0
    l++;
470
0
  }
471
0
472
0
  /* Unload the local registers */
473
0
  state->get_buffer = get_buffer;
474
0
  state->bits_left = bits_left;
475
0
476
0
  /* With garbage input we may reach the sentinel value l = 17. */
477
0
478
0
  if (l > 16) {
479
0
    WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
480
0
    return 0;                   /* fake a zero as the safest result */
481
0
  }
482
0
483
0
  return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
484
0
}
485
486
487
/*
488
 * Figure F.12: extend sign bit.
489
 * On some machines, a shift and add will be faster than a table lookup.
490
 */
491
492
#define AVOID_TABLES
493
#ifdef AVOID_TABLES
494
495
0
#define NEG_1 ((unsigned int)-1)
496
0
#define HUFF_EXTEND(x,s)  ((x) + ((((x) - (1<<((s)-1))) >> 31) & (((NEG_1)<<(s)) + 1)))
497
498
#else
499
500
#define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
501
502
static const int extend_test[16] =   /* entry n is 2**(n-1) */
503
  { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
504
    0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
505
506
static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
507
  { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
508
    ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
509
    ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
510
    ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
511
512
#endif /* AVOID_TABLES */
513
514
515
/*
516
 * Check for a restart marker & resynchronize decoder.
517
 * Returns FALSE if must suspend.
518
 */
519
520
LOCAL(boolean)
521
process_restart (j_decompress_ptr cinfo)
522
0
{
523
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
524
0
  int ci;
525
0
526
0
  /* Throw away any unused bits remaining in bit buffer; */
527
0
  /* include any full bytes in next_marker's count of discarded bytes */
528
0
  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
529
0
  entropy->bitstate.bits_left = 0;
530
0
531
0
  /* Advance past the RSTn marker */
532
0
  if (! (*cinfo->marker->read_restart_marker) (cinfo))
533
0
    return FALSE;
534
0
535
0
  /* Re-initialize DC predictions to 0 */
536
0
  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
537
0
    entropy->saved.last_dc_val[ci] = 0;
538
0
539
0
  /* Reset restart counter */
540
0
  entropy->restarts_to_go = cinfo->restart_interval;
541
0
542
0
  /* Reset out-of-data flag, unless read_restart_marker left us smack up
543
0
   * against a marker.  In that case we will end up treating the next data
544
0
   * segment as empty, and we can avoid producing bogus output pixels by
545
0
   * leaving the flag set.
546
0
   */
547
0
  if (cinfo->unread_marker == 0)
548
0
    entropy->pub.insufficient_data = FALSE;
549
0
550
0
  return TRUE;
551
0
}
552
553
554
LOCAL(boolean)
555
decode_mcu_slow (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
556
0
{
557
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
558
0
  BITREAD_STATE_VARS;
559
0
  int blkn;
560
0
  savable_state state;
561
0
  /* Outer loop handles each block in the MCU */
562
0
563
0
  /* Load up working state */
564
0
  BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
565
0
  ASSIGN_STATE(state, entropy->saved);
566
0
567
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
568
0
    JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
569
0
    d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
570
0
    d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
571
0
    register int s, k, r;
572
0
573
0
    /* Decode a single block's worth of coefficients */
574
0
575
0
    /* Section F.2.2.1: decode the DC coefficient difference */
576
0
    HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
577
0
    if (s) {
578
0
      CHECK_BIT_BUFFER(br_state, s, return FALSE);
579
0
      r = GET_BITS(s);
580
0
      s = HUFF_EXTEND(r, s);
581
0
    }
582
0
583
0
    if (entropy->dc_needed[blkn]) {
584
0
      /* Convert DC difference to actual value, update last_dc_val */
585
0
      int ci = cinfo->MCU_membership[blkn];
586
0
      s += state.last_dc_val[ci];
587
0
      state.last_dc_val[ci] = s;
588
0
      if (block) {
589
0
        /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
590
0
        (*block)[0] = (JCOEF) s;
591
0
      }
592
0
    }
593
0
594
0
    if (entropy->ac_needed[blkn] && block) {
595
0
596
0
      /* Section F.2.2.2: decode the AC coefficients */
597
0
      /* Since zeroes are skipped, output area must be cleared beforehand */
598
0
      for (k = 1; k < DCTSIZE2; k++) {
599
0
        HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
600
0
601
0
        r = s >> 4;
602
0
        s &= 15;
603
0
604
0
        if (s) {
605
0
          k += r;
606
0
          CHECK_BIT_BUFFER(br_state, s, return FALSE);
607
0
          r = GET_BITS(s);
608
0
          s = HUFF_EXTEND(r, s);
609
0
          /* Output coefficient in natural (dezigzagged) order.
610
0
           * Note: the extra entries in jpeg_natural_order[] will save us
611
0
           * if k >= DCTSIZE2, which could happen if the data is corrupted.
612
0
           */
613
0
          (*block)[jpeg_natural_order[k]] = (JCOEF) s;
614
0
        } else {
615
0
          if (r != 15)
616
0
            break;
617
0
          k += 15;
618
0
        }
619
0
      }
620
0
621
0
    } else {
622
0
623
0
      /* Section F.2.2.2: decode the AC coefficients */
624
0
      /* In this path we just discard the values */
625
0
      for (k = 1; k < DCTSIZE2; k++) {
626
0
        HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
627
0
628
0
        r = s >> 4;
629
0
        s &= 15;
630
0
631
0
        if (s) {
632
0
          k += r;
633
0
          CHECK_BIT_BUFFER(br_state, s, return FALSE);
634
0
          DROP_BITS(s);
635
0
        } else {
636
0
          if (r != 15)
637
0
            break;
638
0
          k += 15;
639
0
        }
640
0
      }
641
0
    }
642
0
  }
643
0
644
0
  /* Completed MCU, so update state */
645
0
  BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
646
0
  ASSIGN_STATE(entropy->saved, state);
647
0
  return TRUE;
648
0
}
649
650
651
LOCAL(boolean)
652
decode_mcu_fast (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
653
0
{
654
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
655
0
  BITREAD_STATE_VARS;
656
0
  JOCTET *buffer;
657
0
  int blkn;
658
0
  savable_state state;
659
0
  /* Outer loop handles each block in the MCU */
660
0
661
0
  /* Load up working state */
662
0
  BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
663
0
  buffer = (JOCTET *) br_state.next_input_byte;
664
0
  ASSIGN_STATE(state, entropy->saved);
665
0
666
0
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
667
0
    JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
668
0
    d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
669
0
    d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
670
0
    register int s, k, r, l;
671
0
672
0
    HUFF_DECODE_FAST(s, l, dctbl, slow_decode_mcu);
673
0
    if (s) {
674
0
      FILL_BIT_BUFFER_FAST
675
0
      r = GET_BITS(s);
676
0
      s = HUFF_EXTEND(r, s);
677
0
    }
678
0
679
0
    if (entropy->dc_needed[blkn]) {
680
0
      int ci = cinfo->MCU_membership[blkn];
681
0
      s += state.last_dc_val[ci];
682
0
      state.last_dc_val[ci] = s;
683
0
      if (block)
684
0
        (*block)[0] = (JCOEF) s;
685
0
    }
686
0
687
0
    if (entropy->ac_needed[blkn] && block) {
688
0
689
0
      for (k = 1; k < DCTSIZE2; k++) {
690
0
        HUFF_DECODE_FAST(s, l, actbl, slow_decode_mcu);
691
0
        r = s >> 4;
692
0
        s &= 15;
693
0
694
0
        if (s) {
695
0
          k += r;
696
0
          FILL_BIT_BUFFER_FAST
697
0
          r = GET_BITS(s);
698
0
          s = HUFF_EXTEND(r, s);
699
0
          (*block)[jpeg_natural_order[k]] = (JCOEF) s;
700
0
        } else {
701
0
          if (r != 15) break;
702
0
          k += 15;
703
0
        }
704
0
      }
705
0
706
0
    } else {
707
0
708
0
      for (k = 1; k < DCTSIZE2; k++) {
709
0
        HUFF_DECODE_FAST(s, l, actbl, slow_decode_mcu);
710
0
        r = s >> 4;
711
0
        s &= 15;
712
0
713
0
        if (s) {
714
0
          k += r;
715
0
          FILL_BIT_BUFFER_FAST
716
0
          DROP_BITS(s);
717
0
        } else {
718
0
          if (r != 15) break;
719
0
          k += 15;
720
0
        }
721
0
      }
722
0
    }
723
0
  }
724
0
725
0
  if (cinfo->unread_marker != 0) {
726
0
slow_decode_mcu:
727
0
    cinfo->unread_marker = 0;
728
0
    return FALSE;
729
0
  }
730
0
731
0
  br_state.bytes_in_buffer -= (buffer - br_state.next_input_byte);
732
0
  br_state.next_input_byte = buffer;
733
0
  BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
734
0
  ASSIGN_STATE(entropy->saved, state);
735
0
  return TRUE;
736
0
}
737
738
739
/*
740
 * Decode and return one MCU's worth of Huffman-compressed coefficients.
741
 * The coefficients are reordered from zigzag order into natural array order,
742
 * but are not dequantized.
743
 *
744
 * The i'th block of the MCU is stored into the block pointed to by
745
 * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
746
 * (Wholesale zeroing is usually a little faster than retail...)
747
 *
748
 * Returns FALSE if data source requested suspension.  In that case no
749
 * changes have been made to permanent state.  (Exception: some output
750
 * coefficients may already have been assigned.  This is harmless for
751
 * this module, since we'll just re-assign them on the next call.)
752
 */
753
754
0
#define BUFSIZE (DCTSIZE2 * 8)
755
756
METHODDEF(boolean)
757
decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
758
0
{
759
0
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
760
0
  int usefast = 1;
761
0
762
0
  /* Process restart marker if needed; may have to suspend */
763
0
  if (cinfo->restart_interval) {
764
0
    if (entropy->restarts_to_go == 0)
765
0
      if (! process_restart(cinfo))
766
0
        return FALSE;
767
0
    usefast = 0;
768
0
  }
769
0
770
0
  if (cinfo->src->bytes_in_buffer < BUFSIZE * (size_t)cinfo->blocks_in_MCU
771
0
    || cinfo->unread_marker != 0)
772
0
    usefast = 0;
773
0
774
0
  /* If we've run out of data, just leave the MCU set to zeroes.
775
0
   * This way, we return uniform gray for the remainder of the segment.
776
0
   */
777
0
  if (! entropy->pub.insufficient_data) {
778
0
779
0
    if (usefast) {
780
0
      if (!decode_mcu_fast(cinfo, MCU_data)) goto use_slow;
781
0
    }
782
0
    else {
783
0
      use_slow:
784
0
      if (!decode_mcu_slow(cinfo, MCU_data)) return FALSE;
785
0
    }
786
0
787
0
  }
788
0
789
0
  /* Account for restart interval (no-op if not using restarts) */
790
0
  entropy->restarts_to_go--;
791
0
792
0
  return TRUE;
793
0
}
794
795
796
/*
797
 * Module initialization routine for Huffman entropy decoding.
798
 */
799
800
GLOBAL(void)
801
jinit_huff_decoder (j_decompress_ptr cinfo)
802
0
{
803
0
  huff_entropy_ptr entropy;
804
0
  int i;
805
0
806
0
  /* Motion JPEG frames typically do not include the Huffman tables if they
807
0
     are the default tables.  Thus, if the tables are not set by the time
808
0
     the Huffman decoder is initialized (usually within the body of
809
0
     jpeg_start_decompress()), we set them to default values. */
810
0
  std_huff_tables((j_common_ptr) cinfo);
811
0
812
0
  entropy = (huff_entropy_ptr)
813
0
    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
814
0
                                sizeof(huff_entropy_decoder));
815
0
  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
816
0
  entropy->pub.start_pass = start_pass_huff_decoder;
817
0
  entropy->pub.decode_mcu = decode_mcu;
818
0
819
0
  /* Mark tables unallocated */
820
0
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
821
0
    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
822
0
  }
823
0
}