Coverage Report

Created: 2023-06-07 06:03

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