Coverage Report

Created: 2026-06-15 06:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjpeg-turbo/src/jdarith.c
Line
Count
Source
1
/*
2
 * jdarith.c
3
 *
4
 * This file was part of the Independent JPEG Group's software:
5
 * Developed 1997-2015 by Guido Vollbeding.
6
 * libjpeg-turbo Modifications:
7
 * Copyright (C) 2015-2020, 2022, D. R. Commander.
8
 * For conditions of distribution and use, see the accompanying README.ijg
9
 * file.
10
 *
11
 * This file contains portable arithmetic entropy encoding routines for JPEG
12
 * (implementing Recommendation ITU-T T.81 | ISO/IEC 10918-1).
13
 *
14
 * Both sequential and progressive modes are supported in this single module.
15
 *
16
 * Suspension is not currently supported in this module.
17
 *
18
 * NOTE: All referenced figures are from
19
 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
20
 */
21
22
#define JPEG_INTERNALS
23
#include "jinclude.h"
24
#include "jpeglib.h"
25
26
27
346k
#define NEG_1  ((unsigned int)-1)
28
29
30
/* Expanded entropy decoder object for arithmetic decoding. */
31
32
typedef struct {
33
  struct jpeg_entropy_decoder pub; /* public fields */
34
35
  JLONG c;       /* C register, base of coding interval + input bit buffer */
36
  JLONG a;               /* A register, normalized size of coding interval */
37
  int ct;     /* bit shift counter, # of bits left in bit buffer part of C */
38
                                                         /* init: ct = -16 */
39
                                                         /* run: ct = 0..7 */
40
                                                         /* error: ct = -1 */
41
  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
42
  int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
43
44
  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
45
46
  /* Pointers to statistics areas (these workspaces have image lifespan) */
47
  unsigned char *dc_stats[NUM_ARITH_TBLS];
48
  unsigned char *ac_stats[NUM_ARITH_TBLS];
49
50
  /* Statistics bin for coding with fixed probability 0.5 */
51
  unsigned char fixed_bin[4];
52
} arith_entropy_decoder;
53
54
typedef arith_entropy_decoder *arith_entropy_ptr;
55
56
/* The following two definitions specify the allocation chunk size
57
 * for the statistics area.
58
 * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
59
 * 49 statistics bins for DC, and 245 statistics bins for AC coding.
60
 *
61
 * We use a compact representation with 1 byte per statistics bin,
62
 * thus the numbers directly represent byte sizes.
63
 * This 1 byte per statistics bin contains the meaning of the MPS
64
 * (more probable symbol) in the highest bit (mask 0x80), and the
65
 * index into the probability estimation state machine table
66
 * in the lower bits (mask 0x7F).
67
 */
68
69
7.22k
#define DC_STAT_BINS  64
70
4.04k
#define AC_STAT_BINS  256
71
72
73
LOCAL(int)
74
get_byte(j_decompress_ptr cinfo)
75
/* Read next input byte; we do not support suspension in this module. */
76
94.2k
{
77
94.2k
  struct jpeg_source_mgr *src = cinfo->src;
78
79
94.2k
  if (src->bytes_in_buffer == 0)
80
229
    if (!(*src->fill_input_buffer) (cinfo))
81
0
      ERREXIT(cinfo, JERR_CANT_SUSPEND);
82
94.2k
  src->bytes_in_buffer--;
83
94.2k
  return *src->next_input_byte++;
84
94.2k
}
85
86
87
/*
88
 * The core arithmetic decoding routine (common in JPEG and JBIG).
89
 * This needs to go as fast as possible.
90
 * Machine-dependent optimization facilities
91
 * are not utilized in this portable implementation.
92
 * However, this code should be fairly efficient and
93
 * may be a good base for further optimizations anyway.
94
 *
95
 * Return value is 0 or 1 (binary decision).
96
 *
97
 * Note: I've changed the handling of the code base & bit
98
 * buffer register C compared to other implementations
99
 * based on the standards layout & procedures.
100
 * While it also contains both the actual base of the
101
 * coding interval (16 bits) and the next-bits buffer,
102
 * the cut-point between these two parts is floating
103
 * (instead of fixed) with the bit shift counter CT.
104
 * Thus, we also need only one (variable instead of
105
 * fixed size) shift for the LPS/MPS decision, and
106
 * we can do away with any renormalization update
107
 * of C (except for new data insertion, of course).
108
 *
109
 * I've also introduced a new scheme for accessing
110
 * the probability estimation state machine table,
111
 * derived from Markus Kuhn's JBIG implementation.
112
 */
113
114
LOCAL(int)
115
arith_decode(j_decompress_ptr cinfo, unsigned char *st)
116
54.2M
{
117
54.2M
  register arith_entropy_ptr e = (arith_entropy_ptr)cinfo->entropy;
118
54.2M
  register unsigned char nl, nm;
119
54.2M
  register JLONG qe, temp;
120
54.2M
  register int sv, data;
121
122
  /* Renormalization & data input per section D.2.6 */
123
66.4M
  while (e->a < 0x8000L) {
124
12.2M
    if (--e->ct < 0) {
125
      /* Need to fetch next data byte */
126
1.53M
      if (cinfo->unread_marker)
127
1.45M
        data = 0;               /* stuff zero data */
128
80.9k
      else {
129
80.9k
        data = get_byte(cinfo); /* read next input byte */
130
80.9k
        if (data == 0xFF) {     /* zero stuff or marker code */
131
13.2k
          do data = get_byte(cinfo);
132
13.2k
          while (data == 0xFF); /* swallow extra 0xFF bytes */
133
7.73k
          if (data == 0)
134
3.48k
            data = 0xFF;        /* discard stuffed zero byte */
135
4.25k
          else {
136
            /* Note: Different from the Huffman decoder, hitting
137
             * a marker while processing the compressed data
138
             * segment is legal in arithmetic coding.
139
             * The convention is to supply zero data
140
             * then until decoding is complete.
141
             */
142
4.25k
            cinfo->unread_marker = data;
143
4.25k
            data = 0;
144
4.25k
          }
145
7.73k
        }
146
80.9k
      }
147
1.53M
      e->c = (e->c << 8) | data; /* insert data into C register */
148
1.53M
      if ((e->ct += 8) < 0)      /* update bit shift counter */
149
        /* Need more initial bytes */
150
8.96k
        if (++e->ct == 0)
151
          /* Got 2 initial bytes -> re-init A and exit loop */
152
4.46k
          e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */
153
1.53M
    }
154
12.2M
    e->a <<= 1;
155
12.2M
  }
156
157
  /* Fetch values from our compact representation of Table D.2:
158
   * Qe values and probability estimation state machine
159
   */
160
54.2M
  sv = *st;
161
54.2M
  qe = jpeg_aritab[sv & 0x7F];  /* => Qe_Value */
162
54.2M
  nl = qe & 0xFF;  qe >>= 8;    /* Next_Index_LPS + Switch_MPS */
163
54.2M
  nm = qe & 0xFF;  qe >>= 8;    /* Next_Index_MPS */
164
165
  /* Decode & estimation procedures per sections D.2.4 & D.2.5 */
166
54.2M
  temp = e->a - qe;
167
54.2M
  e->a = temp;
168
54.2M
  temp <<= e->ct;
169
54.2M
  if (e->c >= temp) {
170
3.84M
    e->c -= temp;
171
    /* Conditional LPS (less probable symbol) exchange */
172
3.84M
    if (e->a < qe) {
173
1.06M
      e->a = qe;
174
1.06M
      *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
175
2.77M
    } else {
176
2.77M
      e->a = qe;
177
2.77M
      *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
178
2.77M
      sv ^= 0x80;               /* Exchange LPS/MPS */
179
2.77M
    }
180
50.4M
  } else if (e->a < 0x8000L) {
181
    /* Conditional MPS (more probable symbol) exchange */
182
5.28M
    if (e->a < qe) {
183
1.63M
      *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
184
1.63M
      sv ^= 0x80;               /* Exchange LPS/MPS */
185
3.65M
    } else {
186
3.65M
      *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
187
3.65M
    }
188
5.28M
  }
189
190
54.2M
  return sv >> 7;
191
54.2M
}
192
193
194
/*
195
 * Check for a restart marker & resynchronize decoder.
196
 */
197
198
LOCAL(void)
199
process_restart(j_decompress_ptr cinfo)
200
912
{
201
912
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
202
912
  int ci;
203
912
  jpeg_component_info *compptr;
204
205
  /* Advance past the RSTn marker */
206
912
  if (!(*cinfo->marker->read_restart_marker) (cinfo))
207
0
    ERREXIT(cinfo, JERR_CANT_SUSPEND);
208
209
  /* Re-initialize statistics areas */
210
2.38k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
211
1.47k
    compptr = cinfo->cur_comp_info[ci];
212
1.47k
    if (!cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
213
1.09k
      memset(entropy->dc_stats[compptr->dc_tbl_no], 0, DC_STAT_BINS);
214
      /* Reset DC predictions to 0 */
215
1.09k
      entropy->last_dc_val[ci] = 0;
216
1.09k
      entropy->dc_context[ci] = 0;
217
1.09k
    }
218
1.47k
    if (!cinfo->progressive_mode || cinfo->Ss) {
219
1.10k
      memset(entropy->ac_stats[compptr->ac_tbl_no], 0, AC_STAT_BINS);
220
1.10k
    }
221
1.47k
  }
222
223
  /* Reset arithmetic decoding variables */
224
912
  entropy->c = 0;
225
912
  entropy->a = 0;
226
912
  entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
227
228
  /* Reset restart counter */
229
912
  entropy->restarts_to_go = cinfo->restart_interval;
230
912
}
231
232
233
/*
234
 * Arithmetic MCU decoding.
235
 * Each of these routines decodes and returns one MCU's worth of
236
 * arithmetic-compressed coefficients.
237
 * The coefficients are reordered from zigzag order into natural array order,
238
 * but are not dequantized.
239
 *
240
 * The i'th block of the MCU is stored into the block pointed to by
241
 * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
242
 */
243
244
/*
245
 * MCU decoding for DC initial scan (either spectral selection,
246
 * or first pass of successive approximation).
247
 */
248
249
METHODDEF(boolean)
250
decode_mcu_DC_first(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
251
3.42M
{
252
3.42M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
253
3.42M
  JBLOCKROW block;
254
3.42M
  unsigned char *st;
255
3.42M
  int blkn, ci, tbl, sign;
256
3.42M
  int v, m;
257
258
  /* Process restart marker if needed */
259
3.42M
  if (cinfo->restart_interval) {
260
555k
    if (entropy->restarts_to_go == 0)
261
159
      process_restart(cinfo);
262
555k
    entropy->restarts_to_go--;
263
555k
  }
264
265
3.42M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
266
267
  /* Outer loop handles each block in the MCU */
268
269
8.09M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
270
4.67M
    block = MCU_data[blkn];
271
4.67M
    ci = cinfo->MCU_membership[blkn];
272
4.67M
    tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
273
274
    /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
275
276
    /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
277
4.67M
    st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
278
279
    /* Figure F.19: Decode_DC_DIFF */
280
4.67M
    if (arith_decode(cinfo, st) == 0)
281
2.22M
      entropy->dc_context[ci] = 0;
282
2.44M
    else {
283
      /* Figure F.21: Decoding nonzero value v */
284
      /* Figure F.22: Decoding the sign of v */
285
2.44M
      sign = arith_decode(cinfo, st + 1);
286
2.44M
      st += 2;  st += sign;
287
      /* Figure F.23: Decoding the magnitude category of v */
288
2.44M
      if ((m = arith_decode(cinfo, st)) != 0) {
289
1.86M
        st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
290
4.41M
        while (arith_decode(cinfo, st)) {
291
2.54M
          if ((m <<= 1) == 0x8000) {
292
2
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
293
2
            entropy->ct = -1;                   /* magnitude overflow */
294
2
            return TRUE;
295
2
          }
296
2.54M
          st += 1;
297
2.54M
        }
298
1.86M
      }
299
      /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
300
2.44M
      if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))
301
6.89k
        entropy->dc_context[ci] = 0;               /* zero diff category */
302
2.43M
      else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))
303
1.58M
        entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
304
848k
      else
305
848k
        entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
306
2.44M
      v = m;
307
      /* Figure F.24: Decoding the magnitude bit pattern of v */
308
2.44M
      st += 14;
309
4.99M
      while (m >>= 1)
310
2.54M
        if (arith_decode(cinfo, st)) v |= m;
311
2.44M
      v += 1;  if (sign) v = -v;
312
2.44M
      entropy->last_dc_val[ci] = (entropy->last_dc_val[ci] + v) & 0xffff;
313
2.44M
    }
314
315
    /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
316
4.67M
    (*block)[0] = (JCOEF)LEFT_SHIFT(entropy->last_dc_val[ci], cinfo->Al);
317
4.67M
  }
318
319
3.42M
  return TRUE;
320
3.42M
}
321
322
323
/*
324
 * MCU decoding for AC initial scan (either spectral selection,
325
 * or first pass of successive approximation).
326
 */
327
328
METHODDEF(boolean)
329
decode_mcu_AC_first(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
330
2.18M
{
331
2.18M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
332
2.18M
  JBLOCKROW block;
333
2.18M
  unsigned char *st;
334
2.18M
  int tbl, sign, k;
335
2.18M
  int v, m;
336
337
  /* Process restart marker if needed */
338
2.18M
  if (cinfo->restart_interval) {
339
679k
    if (entropy->restarts_to_go == 0)
340
230
      process_restart(cinfo);
341
679k
    entropy->restarts_to_go--;
342
679k
  }
343
344
2.18M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
345
346
  /* There is always only one block per MCU */
347
2.18M
  block = MCU_data[0];
348
2.18M
  tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
349
350
  /* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
351
352
  /* Figure F.20: Decode_AC_coefficients */
353
3.35M
  for (k = cinfo->Ss; k <= cinfo->Se; k++) {
354
3.34M
    st = entropy->ac_stats[tbl] + 3 * (k - 1);
355
3.34M
    if (arith_decode(cinfo, st)) break;         /* EOB flag */
356
2.32M
    while (arith_decode(cinfo, st + 1) == 0) {
357
1.15M
      st += 3;  k++;
358
1.15M
      if (k > cinfo->Se) {
359
11
        WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
360
11
        entropy->ct = -1;                       /* spectral overflow */
361
11
        return TRUE;
362
11
      }
363
1.15M
    }
364
    /* Figure F.21: Decoding nonzero value v */
365
    /* Figure F.22: Decoding the sign of v */
366
1.17M
    sign = arith_decode(cinfo, entropy->fixed_bin);
367
1.17M
    st += 2;
368
    /* Figure F.23: Decoding the magnitude category of v */
369
1.17M
    if ((m = arith_decode(cinfo, st)) != 0) {
370
595k
      if (arith_decode(cinfo, st)) {
371
462k
        m <<= 1;
372
462k
        st = entropy->ac_stats[tbl] +
373
462k
             (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
374
1.30M
        while (arith_decode(cinfo, st)) {
375
841k
          if ((m <<= 1) == 0x8000) {
376
2
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
377
2
            entropy->ct = -1;                   /* magnitude overflow */
378
2
            return TRUE;
379
2
          }
380
841k
          st += 1;
381
841k
        }
382
462k
      }
383
595k
    }
384
1.17M
    v = m;
385
    /* Figure F.24: Decoding the magnitude bit pattern of v */
386
1.17M
    st += 14;
387
2.47M
    while (m >>= 1)
388
1.30M
      if (arith_decode(cinfo, st)) v |= m;
389
1.17M
    v += 1;  if (sign) v = -v;
390
    /* Scale and output coefficient in natural (dezigzagged) order */
391
1.17M
    (*block)[jpeg_natural_order[k]] = (JCOEF)((unsigned)v << cinfo->Al);
392
1.17M
  }
393
394
2.18M
  return TRUE;
395
2.18M
}
396
397
398
/*
399
 * MCU decoding for DC successive approximation refinement scan.
400
 */
401
402
METHODDEF(boolean)
403
decode_mcu_DC_refine(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
404
319k
{
405
319k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
406
319k
  unsigned char *st;
407
319k
  int p1, blkn;
408
409
  /* Process restart marker if needed */
410
319k
  if (cinfo->restart_interval) {
411
249k
    if (entropy->restarts_to_go == 0)
412
47
      process_restart(cinfo);
413
249k
    entropy->restarts_to_go--;
414
249k
  }
415
416
319k
  st = entropy->fixed_bin;      /* use fixed probability estimation */
417
319k
  p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
418
419
  /* Outer loop handles each block in the MCU */
420
421
754k
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
422
    /* Encoded data is simply the next bit of the two's-complement DC value */
423
434k
    if (arith_decode(cinfo, st))
424
222k
      MCU_data[blkn][0][0] |= p1;
425
434k
  }
426
427
319k
  return TRUE;
428
319k
}
429
430
431
/*
432
 * MCU decoding for AC successive approximation refinement scan.
433
 */
434
435
METHODDEF(boolean)
436
decode_mcu_AC_refine(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
437
346k
{
438
346k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
439
346k
  JBLOCKROW block;
440
346k
  JCOEFPTR thiscoef;
441
346k
  unsigned char *st;
442
346k
  int tbl, k, kex;
443
346k
  int p1, m1;
444
445
  /* Process restart marker if needed */
446
346k
  if (cinfo->restart_interval) {
447
205k
    if (entropy->restarts_to_go == 0)
448
71
      process_restart(cinfo);
449
205k
    entropy->restarts_to_go--;
450
205k
  }
451
452
346k
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
453
454
  /* There is always only one block per MCU */
455
346k
  block = MCU_data[0];
456
346k
  tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
457
458
346k
  p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
459
346k
  m1 = (NEG_1) << cinfo->Al;    /* -1 in the bit position being coded */
460
461
  /* Establish EOBx (previous stage end-of-block) index */
462
12.3M
  for (kex = cinfo->Se; kex > 0; kex--)
463
12.2M
    if ((*block)[jpeg_natural_order[kex]]) break;
464
465
1.63M
  for (k = cinfo->Ss; k <= cinfo->Se; k++) {
466
1.63M
    st = entropy->ac_stats[tbl] + 3 * (k - 1);
467
1.63M
    if (k > kex)
468
438k
      if (arith_decode(cinfo, st)) break;       /* EOB flag */
469
1.47M
    for (;;) {
470
1.47M
      thiscoef = *block + jpeg_natural_order[k];
471
1.47M
      if (*thiscoef) {                          /* previously nonzero coef */
472
1.09M
        if (arith_decode(cinfo, st + 2)) {
473
704k
          if (*thiscoef < 0)
474
346k
            *thiscoef += (JCOEF)m1;
475
358k
          else
476
358k
            *thiscoef += (JCOEF)p1;
477
704k
        }
478
1.09M
        break;
479
1.09M
      }
480
378k
      if (arith_decode(cinfo, st + 1)) {        /* newly nonzero coef */
481
189k
        if (arith_decode(cinfo, entropy->fixed_bin))
482
95.2k
          *thiscoef = (JCOEF)m1;
483
94.2k
        else
484
94.2k
          *thiscoef = (JCOEF)p1;
485
189k
        break;
486
189k
      }
487
189k
      st += 3;  k++;
488
189k
      if (k > cinfo->Se) {
489
7
        WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
490
7
        entropy->ct = -1;                       /* spectral overflow */
491
7
        return TRUE;
492
7
      }
493
189k
    }
494
1.28M
  }
495
496
346k
  return TRUE;
497
346k
}
498
499
500
/*
501
 * Decode one MCU's worth of arithmetic-compressed coefficients.
502
 */
503
504
METHODDEF(boolean)
505
decode_mcu(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
506
830k
{
507
830k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
508
830k
  jpeg_component_info *compptr;
509
830k
  JBLOCKROW block;
510
830k
  unsigned char *st;
511
830k
  int blkn, ci, tbl, sign, k;
512
830k
  int v, m;
513
514
  /* Process restart marker if needed */
515
830k
  if (cinfo->restart_interval) {
516
48.4k
    if (entropy->restarts_to_go == 0)
517
405
      process_restart(cinfo);
518
48.4k
    entropy->restarts_to_go--;
519
48.4k
  }
520
521
830k
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
522
523
  /* Outer loop handles each block in the MCU */
524
525
2.26M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
526
1.43M
    block = MCU_data ? MCU_data[blkn] : NULL;
527
1.43M
    ci = cinfo->MCU_membership[blkn];
528
1.43M
    compptr = cinfo->cur_comp_info[ci];
529
530
    /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
531
532
1.43M
    tbl = compptr->dc_tbl_no;
533
534
    /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
535
1.43M
    st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
536
537
    /* Figure F.19: Decode_DC_DIFF */
538
1.43M
    if (arith_decode(cinfo, st) == 0)
539
418k
      entropy->dc_context[ci] = 0;
540
1.01M
    else {
541
      /* Figure F.21: Decoding nonzero value v */
542
      /* Figure F.22: Decoding the sign of v */
543
1.01M
      sign = arith_decode(cinfo, st + 1);
544
1.01M
      st += 2;  st += sign;
545
      /* Figure F.23: Decoding the magnitude category of v */
546
1.01M
      if ((m = arith_decode(cinfo, st)) != 0) {
547
815k
        st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
548
3.60M
        while (arith_decode(cinfo, st)) {
549
2.78M
          if ((m <<= 1) == 0x8000) {
550
7
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
551
7
            entropy->ct = -1;                   /* magnitude overflow */
552
7
            return TRUE;
553
7
          }
554
2.78M
          st += 1;
555
2.78M
        }
556
815k
      }
557
      /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
558
1.01M
      if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))
559
15.5k
        entropy->dc_context[ci] = 0;               /* zero diff category */
560
1.00M
      else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))
561
735k
        entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
562
267k
      else
563
267k
        entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
564
1.01M
      v = m;
565
      /* Figure F.24: Decoding the magnitude bit pattern of v */
566
1.01M
      st += 14;
567
3.80M
      while (m >>= 1)
568
2.78M
        if (arith_decode(cinfo, st)) v |= m;
569
1.01M
      v += 1;  if (sign) v = -v;
570
1.01M
      entropy->last_dc_val[ci] = (entropy->last_dc_val[ci] + v) & 0xffff;
571
1.01M
    }
572
573
1.43M
    if (block)
574
1.43M
      (*block)[0] = (JCOEF)entropy->last_dc_val[ci];
575
576
    /* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
577
578
1.43M
    tbl = compptr->ac_tbl_no;
579
580
    /* Figure F.20: Decode_AC_coefficients */
581
2.99M
    for (k = 1; k <= DCTSIZE2 - 1; k++) {
582
2.98M
      st = entropy->ac_stats[tbl] + 3 * (k - 1);
583
2.98M
      if (arith_decode(cinfo, st)) break;       /* EOB flag */
584
3.65M
      while (arith_decode(cinfo, st + 1) == 0) {
585
2.09M
        st += 3;  k++;
586
2.09M
        if (k > DCTSIZE2 - 1) {
587
2
          WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
588
2
          entropy->ct = -1;                     /* spectral overflow */
589
2
          return TRUE;
590
2
        }
591
2.09M
      }
592
      /* Figure F.21: Decoding nonzero value v */
593
      /* Figure F.22: Decoding the sign of v */
594
1.55M
      sign = arith_decode(cinfo, entropy->fixed_bin);
595
1.55M
      st += 2;
596
      /* Figure F.23: Decoding the magnitude category of v */
597
1.55M
      if ((m = arith_decode(cinfo, st)) != 0) {
598
787k
        if (arith_decode(cinfo, st)) {
599
683k
          m <<= 1;
600
683k
          st = entropy->ac_stats[tbl] +
601
683k
               (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
602
1.77M
          while (arith_decode(cinfo, st)) {
603
1.09M
            if ((m <<= 1) == 0x8000) {
604
3
              WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
605
3
              entropy->ct = -1;                 /* magnitude overflow */
606
3
              return TRUE;
607
3
            }
608
1.09M
            st += 1;
609
1.09M
          }
610
683k
        }
611
787k
      }
612
1.55M
      v = m;
613
      /* Figure F.24: Decoding the magnitude bit pattern of v */
614
1.55M
      st += 14;
615
3.33M
      while (m >>= 1)
616
1.77M
        if (arith_decode(cinfo, st)) v |= m;
617
1.55M
      v += 1;  if (sign) v = -v;
618
1.55M
      if (block)
619
1.55M
        (*block)[jpeg_natural_order[k]] = (JCOEF)v;
620
1.55M
    }
621
1.43M
  }
622
623
830k
  return TRUE;
624
830k
}
625
626
627
/*
628
 * Initialize for an arithmetic-compressed scan.
629
 */
630
631
METHODDEF(void)
632
start_pass(j_decompress_ptr cinfo)
633
3.75k
{
634
3.75k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
635
3.75k
  int ci, tbl;
636
3.75k
  jpeg_component_info *compptr;
637
638
3.75k
  if (cinfo->progressive_mode) {
639
    /* Validate progressive scan parameters */
640
3.08k
    if (cinfo->Ss == 0) {
641
2.00k
      if (cinfo->Se != 0)
642
6
        goto bad;
643
2.00k
    } else {
644
      /* need not check Ss/Se < 0 since they came from unsigned bytes */
645
1.07k
      if (cinfo->Se < cinfo->Ss || cinfo->Se > DCTSIZE2 - 1)
646
12
        goto bad;
647
      /* AC scans may have only one component */
648
1.06k
      if (cinfo->comps_in_scan != 1)
649
3
        goto bad;
650
1.06k
    }
651
3.06k
    if (cinfo->Ah != 0) {
652
      /* Successive approximation refinement scan: must have Al = Ah-1. */
653
288
      if (cinfo->Ah - 1 != cinfo->Al)
654
4
        goto bad;
655
288
    }
656
3.05k
    if (cinfo->Al > 13) {       /* need not check for < 0 */
657
26
bad:
658
26
      ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
659
26
               cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
660
26
    }
661
    /* Update progression status, and verify that scan order is legal.
662
     * Note that inter-scan inconsistencies are treated as warnings
663
     * not fatal errors ... not clear if this is right way to behave.
664
     */
665
7.78k
    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
666
4.70k
      int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
667
4.70k
      int *coef_bit_ptr = &cinfo->coef_bits[cindex][0];
668
4.70k
      int *prev_coef_bit_ptr =
669
4.70k
        &cinfo->coef_bits[cindex + cinfo->num_components][0];
670
4.70k
      if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
671
8
        WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
672
77.4k
      for (coefi = MIN(cinfo->Ss, 1); coefi <= MAX(cinfo->Se, 9); coefi++) {
673
72.7k
        if (cinfo->input_scan_number > 1)
674
59.8k
          prev_coef_bit_ptr[coefi] = coef_bit_ptr[coefi];
675
12.9k
        else
676
12.9k
          prev_coef_bit_ptr[coefi] = 0;
677
72.7k
      }
678
39.2k
      for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
679
34.5k
        int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
680
34.5k
        if (cinfo->Ah != expected)
681
15
          WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
682
34.5k
        coef_bit_ptr[coefi] = cinfo->Al;
683
34.5k
      }
684
4.70k
    }
685
    /* Select MCU decoding routine */
686
3.08k
    if (cinfo->Ah == 0) {
687
2.76k
      if (cinfo->Ss == 0)
688
1.86k
        entropy->pub.decode_mcu = decode_mcu_DC_first;
689
895
      else
690
895
        entropy->pub.decode_mcu = decode_mcu_AC_first;
691
2.76k
    } else {
692
323
      if (cinfo->Ss == 0)
693
124
        entropy->pub.decode_mcu = decode_mcu_DC_refine;
694
199
      else
695
199
        entropy->pub.decode_mcu = decode_mcu_AC_refine;
696
323
    }
697
3.08k
  } else {
698
    /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
699
     * This ought to be an error condition, but we make it a warning.
700
     */
701
675
    if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||
702
665
        cinfo->Ah != 0 || cinfo->Al != 0)
703
16
      WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
704
    /* Select MCU decoding routine */
705
675
    entropy->pub.decode_mcu = decode_mcu;
706
675
  }
707
708
  /* Allocate & initialize requested statistics areas */
709
9.38k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
710
5.62k
    compptr = cinfo->cur_comp_info[ci];
711
5.62k
    if (!cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
712
4.40k
      tbl = compptr->dc_tbl_no;
713
4.40k
      if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
714
0
        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
715
4.40k
      if (entropy->dc_stats[tbl] == NULL)
716
1.72k
        entropy->dc_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)
717
1.72k
          ((j_common_ptr)cinfo, JPOOL_IMAGE, DC_STAT_BINS);
718
4.40k
      memset(entropy->dc_stats[tbl], 0, DC_STAT_BINS);
719
      /* Initialize DC predictions to 0 */
720
4.40k
      entropy->last_dc_val[ci] = 0;
721
4.40k
      entropy->dc_context[ci] = 0;
722
4.40k
    }
723
5.62k
    if (!cinfo->progressive_mode || cinfo->Ss) {
724
1.99k
      tbl = compptr->ac_tbl_no;
725
1.99k
      if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
726
0
        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
727
1.99k
      if (entropy->ac_stats[tbl] == NULL)
728
945
        entropy->ac_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)
729
945
          ((j_common_ptr)cinfo, JPOOL_IMAGE, AC_STAT_BINS);
730
1.99k
      memset(entropy->ac_stats[tbl], 0, AC_STAT_BINS);
731
1.99k
    }
732
5.62k
  }
733
734
  /* Initialize arithmetic decoding variables */
735
3.75k
  entropy->c = 0;
736
3.75k
  entropy->a = 0;
737
3.75k
  entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
738
3.75k
  entropy->pub.insufficient_data = FALSE;
739
740
  /* Initialize restart counter */
741
3.75k
  entropy->restarts_to_go = cinfo->restart_interval;
742
3.75k
}
743
744
745
/*
746
 * Module initialization routine for arithmetic entropy decoding.
747
 */
748
749
GLOBAL(void)
750
jinit_arith_decoder(j_decompress_ptr cinfo)
751
1.47k
{
752
1.47k
  arith_entropy_ptr entropy;
753
1.47k
  int i;
754
755
1.47k
  entropy = (arith_entropy_ptr)
756
1.47k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
757
1.47k
                                sizeof(arith_entropy_decoder));
758
1.47k
  cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
759
1.47k
  entropy->pub.start_pass = start_pass;
760
761
  /* Mark tables unallocated */
762
25.0k
  for (i = 0; i < NUM_ARITH_TBLS; i++) {
763
23.6k
    entropy->dc_stats[i] = NULL;
764
23.6k
    entropy->ac_stats[i] = NULL;
765
23.6k
  }
766
767
  /* Initialize index for fixed probability estimation */
768
1.47k
  entropy->fixed_bin[0] = 113;
769
770
1.47k
  if (cinfo->progressive_mode) {
771
    /* Create progression status table */
772
1.12k
    int *coef_bit_ptr, ci;
773
1.12k
    cinfo->coef_bits = (int (*)[DCTSIZE2])
774
1.12k
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
775
1.12k
                                  cinfo->num_components * 2 * DCTSIZE2 *
776
1.12k
                                  sizeof(int));
777
1.12k
    coef_bit_ptr = &cinfo->coef_bits[0][0];
778
2.70k
    for (ci = 0; ci < cinfo->num_components; ci++)
779
102k
      for (i = 0; i < DCTSIZE2; i++)
780
101k
        *coef_bit_ptr++ = -1;
781
1.12k
  }
782
1.47k
}