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
8.73M
#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
85.9k
{
96
85.9k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
97
85.9k
  int ci, blkn, dctbl, actbl;
98
85.9k
  d_derived_tbl **pdtbl;
99
85.9k
  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
85.9k
  if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||
106
85.9k
      cinfo->Ah != 0 || cinfo->Al != 0)
107
78.1k
    WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
108
109
216k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
110
130k
    compptr = cinfo->cur_comp_info[ci];
111
130k
    dctbl = compptr->dc_tbl_no;
112
130k
    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
130k
    pdtbl = (d_derived_tbl **)(entropy->dc_derived_tbls) + dctbl;
116
130k
    jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl, pdtbl);
117
130k
    pdtbl = (d_derived_tbl **)(entropy->ac_derived_tbls) + actbl;
118
130k
    jpeg_make_d_derived_tbl(cinfo, FALSE, actbl, pdtbl);
119
    /* Initialize DC predictions to 0 */
120
130k
    entropy->saved.last_dc_val[ci] = 0;
121
130k
  }
122
123
  /* Precalculate decoding info for each block in an MCU of this scan */
124
297k
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
125
211k
    ci = cinfo->MCU_membership[blkn];
126
211k
    compptr = cinfo->cur_comp_info[ci];
127
    /* Precalculate which table to use for each block */
128
211k
    entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
129
211k
    entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
130
    /* Decide whether we really care about the coefficient values */
131
211k
    if (compptr->component_needed) {
132
209k
      entropy->dc_needed[blkn] = TRUE;
133
      /* we don't need the ACs if producing a 1/8th-size image */
134
209k
      entropy->ac_needed[blkn] = (compptr->_DCT_scaled_size > 1);
135
209k
    } else {
136
1.70k
      entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
137
1.70k
    }
138
211k
  }
139
140
  /* Initialize bitread state variables */
141
85.9k
  entropy->bitstate.bits_left = 0;
142
85.9k
  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
143
85.9k
  entropy->pub.insufficient_data = FALSE;
144
145
  /* Initialize restart counter */
146
85.9k
  entropy->restarts_to_go = cinfo->restart_interval;
147
85.9k
}
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
207k
{
161
207k
  JHUFF_TBL *htbl;
162
207k
  d_derived_tbl *dtbl;
163
207k
  int p, i, l, si, numsymbols;
164
207k
  int lookbits, ctr;
165
207k
  char huffsize[257];
166
207k
  unsigned int huffcode[257];
167
207k
  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
207k
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
175
262
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
176
207k
  htbl =
177
207k
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
178
207k
  if (htbl == NULL)
179
160
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
180
181
  /* Allocate a workspace if we haven't already done so. */
182
207k
  if (*pdtbl == NULL)
183
27.9k
    *pdtbl = (d_derived_tbl *)
184
27.9k
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
185
27.9k
                                  sizeof(d_derived_tbl));
186
207k
  dtbl = *pdtbl;
187
207k
  dtbl->pub = htbl;             /* fill in back link */
188
189
  /* Figure C.1: make table of Huffman code length for each symbol */
190
191
207k
  p = 0;
192
3.52M
  for (l = 1; l <= 16; l++) {
193
3.31M
    i = (int)htbl->bits[l];
194
3.31M
    if (i < 0 || p + i > 256)   /* protect against table overrun */
195
0
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
196
13.1M
    while (i--)
197
9.80M
      huffsize[p++] = (char)l;
198
3.31M
  }
199
207k
  huffsize[p] = 0;
200
207k
  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
207k
  code = 0;
206
207k
  si = huffsize[0];
207
207k
  p = 0;
208
2.01M
  while (huffsize[p]) {
209
11.6M
    while (((int)huffsize[p]) == si) {
210
9.80M
      huffcode[p++] = code;
211
9.80M
      code++;
212
9.80M
    }
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
1.80M
    if (((JLONG)code) >= (((JLONG)1) << si))
217
44
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
218
1.80M
    code <<= 1;
219
1.80M
    si++;
220
1.80M
  }
221
222
  /* Figure F.15: generate decoding tables for bit-sequential decoding */
223
224
207k
  p = 0;
225
3.52M
  for (l = 1; l <= 16; l++) {
226
3.31M
    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
1.64M
      dtbl->valoffset[l] = (JLONG)p - (JLONG)huffcode[p];
231
1.64M
      p += htbl->bits[l];
232
1.64M
      dtbl->maxcode[l] = huffcode[p - 1]; /* maximum code of length l */
233
1.67M
    } else {
234
1.67M
      dtbl->maxcode[l] = -1;    /* -1 if no codes of this length */
235
1.67M
    }
236
3.31M
  }
237
207k
  dtbl->valoffset[17] = 0;
238
207k
  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
53.2M
  for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++)
248
53.0M
    dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;
249
250
207k
  p = 0;
251
1.86M
  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
252
4.03M
    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
2.38M
      lookbits = huffcode[p] << (HUFF_LOOKAHEAD - l);
256
51.5M
      for (ctr = 1 << (HUFF_LOOKAHEAD - l); ctr > 0; ctr--) {
257
49.1M
        dtbl->lookup[lookbits] = (l << HUFF_LOOKAHEAD) | htbl->huffval[p];
258
49.1M
        lookbits++;
259
49.1M
      }
260
2.38M
    }
261
1.65M
  }
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
207k
  if (isDC) {
270
999k
    for (i = 0; i < numsymbols; i++) {
271
894k
      int sym = htbl->huffval[i];
272
894k
      if (sym < 0 || sym > 15)
273
123
        ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
274
894k
    }
275
105k
  }
276
207k
}
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
129M
#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
69.1M
{
307
  /* Copy heavily used state fields into locals (hopefully registers) */
308
69.1M
  register const JOCTET *next_input_byte = state->next_input_byte;
309
69.1M
  register size_t bytes_in_buffer = state->bytes_in_buffer;
310
69.1M
  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
69.1M
  if (cinfo->unread_marker == 0) {      /* cannot advance past a marker */
317
7.46M
    while (bits_left < MIN_GET_BITS) {
318
6.60M
      register int c;
319
320
      /* Attempt to read a byte */
321
6.60M
      if (bytes_in_buffer == 0) {
322
12.3k
        if (!(*cinfo->src->fill_input_buffer) (cinfo))
323
0
          return FALSE;
324
12.3k
        next_input_byte = cinfo->src->next_input_byte;
325
12.3k
        bytes_in_buffer = cinfo->src->bytes_in_buffer;
326
12.3k
      }
327
6.60M
      bytes_in_buffer--;
328
6.60M
      c = GETJOCTET(*next_input_byte++);
329
330
      /* If it's 0xFF, check and discard stuffed zero byte */
331
6.60M
      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
611k
        do {
338
611k
          if (bytes_in_buffer == 0) {
339
433
            if (!(*cinfo->src->fill_input_buffer) (cinfo))
340
0
              return FALSE;
341
433
            next_input_byte = cinfo->src->next_input_byte;
342
433
            bytes_in_buffer = cinfo->src->bytes_in_buffer;
343
433
          }
344
611k
          bytes_in_buffer--;
345
611k
          c = GETJOCTET(*next_input_byte++);
346
611k
        } while (c == 0xFF);
347
348
357k
        if (c == 0) {
349
          /* Found FF/00, which represents an FF data byte */
350
182k
          c = 0xFF;
351
182k
        } 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
175k
          cinfo->unread_marker = c;
361
          /* See if we need to insert some fake zero bits. */
362
175k
          goto no_more_bytes;
363
175k
        }
364
357k
      }
365
366
      /* OK, load c into get_buffer */
367
6.42M
      get_buffer = (get_buffer << 8) | c;
368
6.42M
      bits_left += 8;
369
6.42M
    } /* end while */
370
68.1M
  } else {
371
68.3M
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
68.3M
    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
60.8M
      if (!cinfo->entropy->insufficient_data) {
383
178k
        WARNMS(cinfo, JWRN_HIT_MARKER);
384
178k
        cinfo->entropy->insufficient_data = TRUE;
385
178k
      }
386
      /* Fill the buffer with zero bits */
387
60.8M
      get_buffer <<= MIN_GET_BITS - bits_left;
388
60.8M
      bits_left = MIN_GET_BITS;
389
60.8M
    }
390
68.3M
  }
391
392
  /* Unload the local registers */
393
69.1M
  state->next_input_byte = next_input_byte;
394
69.1M
  state->bytes_in_buffer = bytes_in_buffer;
395
69.1M
  state->get_buffer = get_buffer;
396
69.1M
  state->bits_left = bits_left;
397
398
69.1M
  return TRUE;
399
69.1M
}
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
22.7M
#define GET_BYTE { \
407
22.7M
  register int c0, c1; \
408
22.7M
  c0 = GETJOCTET(*buffer++); \
409
22.7M
  c1 = GETJOCTET(*buffer); \
410
22.7M
  /* Pre-execute most common case */ \
411
22.7M
  get_buffer = (get_buffer << 8) | c0; \
412
22.7M
  bits_left += 8; \
413
22.7M
  if (c0 == 0xFF) { \
414
1.99M
    /* Pre-execute case of FF/00, which represents an FF data byte */ \
415
1.99M
    buffer++; \
416
1.99M
    if (c1 != 0) { \
417
1.44M
      /* Oops, it's actually a marker indicating end of compressed data. */ \
418
1.44M
      cinfo->unread_marker = c1; \
419
1.44M
      /* Back out pre-execution and fill the buffer with zero bits */ \
420
1.44M
      buffer -= 2; \
421
1.44M
      get_buffer &= ~0xFF; \
422
1.44M
    } \
423
1.99M
  } \
424
22.7M
}
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
66.3M
  if (bits_left <= 16) { \
431
3.78M
    GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE \
432
3.78M
  }
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
7.79M
{
455
7.79M
  register int l = min_bits;
456
7.79M
  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
7.79M
  CHECK_BIT_BUFFER(*state, l, return -1);
462
7.79M
  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
13.6M
  while (code > htbl->maxcode[l]) {
468
5.84M
    code <<= 1;
469
5.84M
    CHECK_BIT_BUFFER(*state, 1, return -1);
470
5.84M
    code |= GET_BITS(1);
471
5.84M
    l++;
472
5.84M
  }
473
474
  /* Unload the local registers */
475
7.79M
  state->get_buffer = get_buffer;
476
7.79M
  state->bits_left = bits_left;
477
478
  /* With garbage input we may reach the sentinel value l = 17. */
479
480
7.79M
  if (l > 16) {
481
170k
    WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
482
170k
    return 0;                   /* fake a zero as the safest result */
483
170k
  }
484
485
7.62M
  return htbl->pub->huffval[(int)(code + htbl->valoffset[l])];
486
7.79M
}
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
39.7M
#define NEG_1  ((unsigned int)-1)
498
#define HUFF_EXTEND(x, s) \
499
39.7M
  ((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
1.52M
{
529
1.52M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
530
1.52M
  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
1.52M
  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
535
1.52M
  entropy->bitstate.bits_left = 0;
536
537
  /* Advance past the RSTn marker */
538
1.52M
  if (!(*cinfo->marker->read_restart_marker) (cinfo))
539
0
    return FALSE;
540
541
  /* Re-initialize DC predictions to 0 */
542
3.53M
  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
543
2.00M
    entropy->saved.last_dc_val[ci] = 0;
544
545
  /* Reset restart counter */
546
1.52M
  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
1.52M
  if (cinfo->unread_marker == 0)
554
18.3k
    entropy->pub.insufficient_data = FALSE;
555
556
1.52M
  return TRUE;
557
1.52M
}
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
817k
{
569
817k
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
570
817k
  BITREAD_STATE_VARS;
571
817k
  int blkn;
572
817k
  savable_state state;
573
  /* Outer loop handles each block in the MCU */
574
575
  /* Load up working state */
576
817k
  BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
577
817k
  ASSIGN_STATE(state, entropy->saved);
578
579
1.92M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
580
1.10M
    JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
581
1.10M
    d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
582
1.10M
    d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
583
1.10M
    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
1.10M
    HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
589
1.10M
    if (s) {
590
524k
      CHECK_BIT_BUFFER(br_state, s, return FALSE);
591
524k
      r = GET_BITS(s);
592
524k
      s = HUFF_EXTEND(r, s);
593
524k
    }
594
595
1.10M
    if (entropy->dc_needed[blkn]) {
596
      /* Convert DC difference to actual value, update last_dc_val */
597
1.09M
      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
1.09M
      s += state.last_dc_val[ci];
607
1.09M
      state.last_dc_val[ci] = s;
608
1.09M
      if (block) {
609
        /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
610
1.09M
        (*block)[0] = (JCOEF)s;
611
1.09M
      }
612
1.09M
    }
613
614
1.10M
    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
11.1M
      for (k = 1; k < DCTSIZE2; k++) {
619
10.8M
        HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
620
621
10.8M
        r = s >> 4;
622
10.8M
        s &= 15;
623
624
10.8M
        if (s) {
625
9.64M
          k += r;
626
9.64M
          CHECK_BIT_BUFFER(br_state, s, return FALSE);
627
9.64M
          r = GET_BITS(s);
628
9.64M
          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
9.64M
          (*block)[jpeg_natural_order[k]] = (JCOEF)s;
634
9.64M
        } else {
635
1.20M
          if (r != 15)
636
819k
            break;
637
380k
          k += 15;
638
380k
        }
639
10.8M
      }
640
641
1.09M
    } else {
642
643
      /* Section F.2.2.2: decode the AC coefficients */
644
      /* In this path we just discard the values */
645
150k
      for (k = 1; k < DCTSIZE2; k++) {
646
146k
        HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
647
648
146k
        r = s >> 4;
649
146k
        s &= 15;
650
651
146k
        if (s) {
652
128k
          k += r;
653
128k
          CHECK_BIT_BUFFER(br_state, s, return FALSE);
654
128k
          DROP_BITS(s);
655
128k
        } else {
656
18.6k
          if (r != 15)
657
9.64k
            break;
658
9.01k
          k += 15;
659
9.01k
        }
660
146k
      }
661
13.8k
    }
662
1.10M
  }
663
664
  /* Completed MCU, so update state */
665
817k
  BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
666
817k
  ASSIGN_STATE(entropy->saved, state);
667
817k
  return TRUE;
668
817k
}
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
3.60M
{
680
3.60M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
681
3.60M
  BITREAD_STATE_VARS;
682
3.60M
  JOCTET *buffer;
683
3.60M
  int blkn;
684
3.60M
  savable_state state;
685
  /* Outer loop handles each block in the MCU */
686
687
  /* Load up working state */
688
3.60M
  BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
689
3.60M
  buffer = (JOCTET *)br_state.next_input_byte;
690
3.60M
  ASSIGN_STATE(state, entropy->saved);
691
692
7.64M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
693
4.03M
    JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
694
4.03M
    d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
695
4.03M
    d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
696
4.03M
    register int s, k, r, l;
697
698
4.03M
    HUFF_DECODE_FAST(s, l, dctbl);
699
4.03M
    if (s) {
700
2.43M
      FILL_BIT_BUFFER_FAST
701
2.43M
      r = GET_BITS(s);
702
2.43M
      s = HUFF_EXTEND(r, s);
703
2.43M
    }
704
705
4.03M
    if (entropy->dc_needed[blkn]) {
706
4.02M
      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
4.02M
      s += state.last_dc_val[ci];
711
4.02M
      state.last_dc_val[ci] = s;
712
4.02M
      if (block)
713
4.02M
        (*block)[0] = (JCOEF)s;
714
4.02M
    }
715
716
4.03M
    if (entropy->ac_needed[blkn] && block) {
717
718
33.6M
      for (k = 1; k < DCTSIZE2; k++) {
719
32.5M
        HUFF_DECODE_FAST(s, l, actbl);
720
32.5M
        r = s >> 4;
721
32.5M
        s &= 15;
722
723
32.5M
        if (s) {
724
27.0M
          k += r;
725
27.0M
          FILL_BIT_BUFFER_FAST
726
27.0M
          r = GET_BITS(s);
727
27.0M
          s = HUFF_EXTEND(r, s);
728
27.0M
          (*block)[jpeg_natural_order[k]] = (JCOEF)s;
729
27.0M
        } else {
730
5.47M
          if (r != 15) break;
731
2.52M
          k += 15;
732
2.52M
        }
733
32.5M
      }
734
735
4.02M
    } else {
736
737
121k
      for (k = 1; k < DCTSIZE2; k++) {
738
118k
        HUFF_DECODE_FAST(s, l, actbl);
739
118k
        r = s >> 4;
740
118k
        s &= 15;
741
742
118k
        if (s) {
743
109k
          k += r;
744
109k
          FILL_BIT_BUFFER_FAST
745
109k
          DROP_BITS(s);
746
109k
        } else {
747
8.21k
          if (r != 15) break;
748
3.26k
          k += 15;
749
3.26k
        }
750
118k
      }
751
8.00k
    }
752
4.03M
  }
753
754
3.60M
  if (cinfo->unread_marker != 0) {
755
112k
    cinfo->unread_marker = 0;
756
112k
    return FALSE;
757
112k
  }
758
759
3.49M
  br_state.bytes_in_buffer -= (buffer - br_state.next_input_byte);
760
3.49M
  br_state.next_input_byte = buffer;
761
3.49M
  BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
762
3.49M
  ASSIGN_STATE(entropy->saved, state);
763
3.49M
  return TRUE;
764
3.60M
}
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
123M
#define BUFSIZE  (DCTSIZE2 * 8)
783
784
METHODDEF(boolean)
785
decode_mcu(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
786
123M
{
787
123M
  huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
788
123M
  int usefast = 1;
789
790
  /* Process restart marker if needed; may have to suspend */
791
123M
  if (cinfo->restart_interval) {
792
28.3M
    if (entropy->restarts_to_go == 0)
793
1.52M
      if (!process_restart(cinfo))
794
0
        return FALSE;
795
28.3M
    usefast = 0;
796
28.3M
  }
797
798
123M
  if (cinfo->src->bytes_in_buffer < BUFSIZE * (size_t)cinfo->blocks_in_MCU ||
799
123M
      cinfo->unread_marker != 0)
800
119M
    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
123M
  if (!entropy->pub.insufficient_data) {
806
807
4.31M
    if (usefast) {
808
3.60M
      if (!decode_mcu_fast(cinfo, MCU_data)) goto use_slow;
809
3.60M
    } else {
810
817k
use_slow:
811
817k
      if (!decode_mcu_slow(cinfo, MCU_data)) return FALSE;
812
817k
    }
813
814
4.31M
  }
815
816
  /* Account for restart interval (no-op if not using restarts) */
817
123M
  if (cinfo->restart_interval)
818
28.3M
    entropy->restarts_to_go--;
819
820
123M
  return TRUE;
821
123M
}
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
15.0k
{
831
15.0k
  huff_entropy_ptr entropy;
832
15.0k
  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
15.0k
  std_huff_tables((j_common_ptr)cinfo);
839
840
15.0k
  entropy = (huff_entropy_ptr)
841
15.0k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
842
15.0k
                                sizeof(huff_entropy_decoder));
843
15.0k
  cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
844
15.0k
  entropy->pub.start_pass = start_pass_huff_decoder;
845
15.0k
  entropy->pub.decode_mcu = decode_mcu;
846
847
  /* Mark tables unallocated */
848
75.0k
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
849
60.0k
    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
850
60.0k
  }
851
15.0k
}