Coverage Report

Created: 2025-07-11 07:03

/src/libjpeg-turbo/src/jdarith.c
Line
Count
Source (jump to first uncovered line)
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
4.24M
#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
15.7k
#define DC_STAT_BINS  64
70
5.58k
#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
546k
{
77
546k
  struct jpeg_source_mgr *src = cinfo->src;
78
79
546k
  if (src->bytes_in_buffer == 0)
80
142
    if (!(*src->fill_input_buffer) (cinfo))
81
0
      ERREXIT(cinfo, JERR_CANT_SUSPEND);
82
546k
  src->bytes_in_buffer--;
83
546k
  return *src->next_input_byte++;
84
546k
}
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
555M
{
117
555M
  register arith_entropy_ptr e = (arith_entropy_ptr)cinfo->entropy;
118
555M
  register unsigned char nl, nm;
119
555M
  register JLONG qe, temp;
120
555M
  register int sv, data;
121
122
  /* Renormalization & data input per section D.2.6 */
123
678M
  while (e->a < 0x8000L) {
124
123M
    if (--e->ct < 0) {
125
      /* Need to fetch next data byte */
126
15.4M
      if (cinfo->unread_marker)
127
14.8M
        data = 0;               /* stuff zero data */
128
532k
      else {
129
532k
        data = get_byte(cinfo); /* read next input byte */
130
532k
        if (data == 0xFF) {     /* zero stuff or marker code */
131
14.4k
          do data = get_byte(cinfo);
132
14.4k
          while (data == 0xFF); /* swallow extra 0xFF bytes */
133
7.45k
          if (data == 0)
134
1.94k
            data = 0xFF;        /* discard stuffed zero byte */
135
5.51k
          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
5.51k
            cinfo->unread_marker = data;
143
5.51k
            data = 0;
144
5.51k
          }
145
7.45k
        }
146
532k
      }
147
15.4M
      e->c = (e->c << 8) | data; /* insert data into C register */
148
15.4M
      if ((e->ct += 8) < 0)      /* update bit shift counter */
149
        /* Need more initial bytes */
150
11.3k
        if (++e->ct == 0)
151
          /* Got 2 initial bytes -> re-init A and exit loop */
152
5.68k
          e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */
153
15.4M
    }
154
123M
    e->a <<= 1;
155
123M
  }
156
157
  /* Fetch values from our compact representation of Table D.2:
158
   * Qe values and probability estimation state machine
159
   */
160
555M
  sv = *st;
161
555M
  qe = jpeg_aritab[sv & 0x7F];  /* => Qe_Value */
162
555M
  nl = qe & 0xFF;  qe >>= 8;    /* Next_Index_LPS + Switch_MPS */
163
555M
  nm = qe & 0xFF;  qe >>= 8;    /* Next_Index_MPS */
164
165
  /* Decode & estimation procedures per sections D.2.4 & D.2.5 */
166
555M
  temp = e->a - qe;
167
555M
  e->a = temp;
168
555M
  temp <<= e->ct;
169
555M
  if (e->c >= temp) {
170
33.3M
    e->c -= temp;
171
    /* Conditional LPS (less probable symbol) exchange */
172
33.3M
    if (e->a < qe) {
173
9.33M
      e->a = qe;
174
9.33M
      *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
175
24.0M
    } else {
176
24.0M
      e->a = qe;
177
24.0M
      *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
178
24.0M
      sv ^= 0x80;               /* Exchange LPS/MPS */
179
24.0M
    }
180
522M
  } else if (e->a < 0x8000L) {
181
    /* Conditional MPS (more probable symbol) exchange */
182
57.5M
    if (e->a < qe) {
183
23.4M
      *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
184
23.4M
      sv ^= 0x80;               /* Exchange LPS/MPS */
185
34.0M
    } else {
186
34.0M
      *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
187
34.0M
    }
188
57.5M
  }
189
190
555M
  return sv >> 7;
191
555M
}
192
193
194
/*
195
 * Check for a restart marker & resynchronize decoder.
196
 */
197
198
LOCAL(void)
199
process_restart(j_decompress_ptr cinfo)
200
1
{
201
1
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
202
1
  int ci;
203
1
  jpeg_component_info *compptr;
204
205
  /* Advance past the RSTn marker */
206
1
  if (!(*cinfo->marker->read_restart_marker) (cinfo))
207
0
    ERREXIT(cinfo, JERR_CANT_SUSPEND);
208
209
  /* Re-initialize statistics areas */
210
1
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
211
0
    compptr = cinfo->cur_comp_info[ci];
212
0
    if (!cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
213
0
      memset(entropy->dc_stats[compptr->dc_tbl_no], 0, DC_STAT_BINS);
214
      /* Reset DC predictions to 0 */
215
0
      entropy->last_dc_val[ci] = 0;
216
0
      entropy->dc_context[ci] = 0;
217
0
    }
218
0
    if (!cinfo->progressive_mode || cinfo->Ss) {
219
0
      memset(entropy->ac_stats[compptr->ac_tbl_no], 0, AC_STAT_BINS);
220
0
    }
221
0
  }
222
223
  /* Reset arithmetic decoding variables */
224
1
  entropy->c = 0;
225
1
  entropy->a = 0;
226
1
  entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
227
228
  /* Reset restart counter */
229
1
  entropy->restarts_to_go = cinfo->restart_interval;
230
1
}
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
16.4M
{
252
16.4M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
253
16.4M
  JBLOCKROW block;
254
16.4M
  unsigned char *st;
255
16.4M
  int blkn, ci, tbl, sign;
256
16.4M
  int v, m;
257
258
  /* Process restart marker if needed */
259
16.4M
  if (cinfo->restart_interval) {
260
0
    if (entropy->restarts_to_go == 0)
261
0
      process_restart(cinfo);
262
0
    entropy->restarts_to_go--;
263
0
  }
264
265
16.4M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
266
267
  /* Outer loop handles each block in the MCU */
268
269
77.1M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
270
60.6M
    block = MCU_data[blkn];
271
60.6M
    ci = cinfo->MCU_membership[blkn];
272
60.6M
    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
60.6M
    st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
278
279
    /* Figure F.19: Decode_DC_DIFF */
280
60.6M
    if (arith_decode(cinfo, st) == 0)
281
30.1M
      entropy->dc_context[ci] = 0;
282
30.4M
    else {
283
      /* Figure F.21: Decoding nonzero value v */
284
      /* Figure F.22: Decoding the sign of v */
285
30.4M
      sign = arith_decode(cinfo, st + 1);
286
30.4M
      st += 2;  st += sign;
287
      /* Figure F.23: Decoding the magnitude category of v */
288
30.4M
      if ((m = arith_decode(cinfo, st)) != 0) {
289
15.5M
        st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
290
34.2M
        while (arith_decode(cinfo, st)) {
291
18.7M
          if ((m <<= 1) == 0x8000) {
292
7
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
293
7
            entropy->ct = -1;                   /* magnitude overflow */
294
7
            return TRUE;
295
7
          }
296
18.7M
          st += 1;
297
18.7M
        }
298
15.5M
      }
299
      /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
300
30.4M
      if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))
301
0
        entropy->dc_context[ci] = 0;               /* zero diff category */
302
30.4M
      else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))
303
8.08M
        entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
304
22.3M
      else
305
22.3M
        entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
306
30.4M
      v = m;
307
      /* Figure F.24: Decoding the magnitude bit pattern of v */
308
30.4M
      st += 14;
309
49.1M
      while (m >>= 1)
310
18.7M
        if (arith_decode(cinfo, st)) v |= m;
311
30.4M
      v += 1;  if (sign) v = -v;
312
30.4M
      entropy->last_dc_val[ci] = (entropy->last_dc_val[ci] + v) & 0xffff;
313
30.4M
    }
314
315
    /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
316
60.6M
    (*block)[0] = (JCOEF)LEFT_SHIFT(entropy->last_dc_val[ci], cinfo->Al);
317
60.6M
  }
318
319
16.4M
  return TRUE;
320
16.4M
}
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
13.7M
{
331
13.7M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
332
13.7M
  JBLOCKROW block;
333
13.7M
  unsigned char *st;
334
13.7M
  int tbl, sign, k;
335
13.7M
  int v, m;
336
337
  /* Process restart marker if needed */
338
13.7M
  if (cinfo->restart_interval) {
339
0
    if (entropy->restarts_to_go == 0)
340
0
      process_restart(cinfo);
341
0
    entropy->restarts_to_go--;
342
0
  }
343
344
13.7M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
345
346
  /* There is always only one block per MCU */
347
13.7M
  block = MCU_data[0];
348
13.7M
  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
38.3M
  for (k = cinfo->Ss; k <= cinfo->Se; k++) {
354
38.3M
    st = entropy->ac_stats[tbl] + 3 * (k - 1);
355
38.3M
    if (arith_decode(cinfo, st)) break;         /* EOB flag */
356
51.9M
    while (arith_decode(cinfo, st + 1) == 0) {
357
27.2M
      st += 3;  k++;
358
27.2M
      if (k > cinfo->Se) {
359
34
        WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
360
34
        entropy->ct = -1;                       /* spectral overflow */
361
34
        return TRUE;
362
34
      }
363
27.2M
    }
364
    /* Figure F.21: Decoding nonzero value v */
365
    /* Figure F.22: Decoding the sign of v */
366
24.6M
    sign = arith_decode(cinfo, entropy->fixed_bin);
367
24.6M
    st += 2;
368
    /* Figure F.23: Decoding the magnitude category of v */
369
24.6M
    if ((m = arith_decode(cinfo, st)) != 0) {
370
13.8M
      if (arith_decode(cinfo, st)) {
371
12.3M
        m <<= 1;
372
12.3M
        st = entropy->ac_stats[tbl] +
373
12.3M
             (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
374
26.3M
        while (arith_decode(cinfo, st)) {
375
13.9M
          if ((m <<= 1) == 0x8000) {
376
13
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
377
13
            entropy->ct = -1;                   /* magnitude overflow */
378
13
            return TRUE;
379
13
          }
380
13.9M
          st += 1;
381
13.9M
        }
382
12.3M
      }
383
13.8M
    }
384
24.6M
    v = m;
385
    /* Figure F.24: Decoding the magnitude bit pattern of v */
386
24.6M
    st += 14;
387
50.9M
    while (m >>= 1)
388
26.3M
      if (arith_decode(cinfo, st)) v |= m;
389
24.6M
    v += 1;  if (sign) v = -v;
390
    /* Scale and output coefficient in natural (dezigzagged) order */
391
24.6M
    (*block)[jpeg_natural_order[k]] = (JCOEF)((unsigned)v << cinfo->Al);
392
24.6M
  }
393
394
13.7M
  return TRUE;
395
13.7M
}
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
859k
{
405
859k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
406
859k
  unsigned char *st;
407
859k
  int p1, blkn;
408
409
  /* Process restart marker if needed */
410
859k
  if (cinfo->restart_interval) {
411
0
    if (entropy->restarts_to_go == 0)
412
0
      process_restart(cinfo);
413
0
    entropy->restarts_to_go--;
414
0
  }
415
416
859k
  st = entropy->fixed_bin;      /* use fixed probability estimation */
417
859k
  p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
418
419
  /* Outer loop handles each block in the MCU */
420
421
4.46M
  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
3.60M
    if (arith_decode(cinfo, st))
424
1.80M
      MCU_data[blkn][0][0] |= p1;
425
3.60M
  }
426
427
859k
  return TRUE;
428
859k
}
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
4.24M
{
438
4.24M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
439
4.24M
  JBLOCKROW block;
440
4.24M
  JCOEFPTR thiscoef;
441
4.24M
  unsigned char *st;
442
4.24M
  int tbl, k, kex;
443
4.24M
  int p1, m1;
444
445
  /* Process restart marker if needed */
446
4.24M
  if (cinfo->restart_interval) {
447
0
    if (entropy->restarts_to_go == 0)
448
0
      process_restart(cinfo);
449
0
    entropy->restarts_to_go--;
450
0
  }
451
452
4.24M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
453
454
  /* There is always only one block per MCU */
455
4.24M
  block = MCU_data[0];
456
4.24M
  tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
457
458
4.24M
  p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
459
4.24M
  m1 = (NEG_1) << cinfo->Al;    /* -1 in the bit position being coded */
460
461
  /* Establish EOBx (previous stage end-of-block) index */
462
244M
  for (kex = cinfo->Se; kex > 0; kex--)
463
243M
    if ((*block)[jpeg_natural_order[kex]]) break;
464
465
31.0M
  for (k = cinfo->Ss; k <= cinfo->Se; k++) {
466
31.0M
    st = entropy->ac_stats[tbl] + 3 * (k - 1);
467
31.0M
    if (k > kex)
468
8.66M
      if (arith_decode(cinfo, st)) break;       /* EOB flag */
469
37.2M
    for (;;) {
470
37.2M
      thiscoef = *block + jpeg_natural_order[k];
471
37.2M
      if (*thiscoef) {                          /* previously nonzero coef */
472
17.8M
        if (arith_decode(cinfo, st + 2)) {
473
8.74M
          if (*thiscoef < 0)
474
4.29M
            *thiscoef += (JCOEF)m1;
475
4.45M
          else
476
4.45M
            *thiscoef += (JCOEF)p1;
477
8.74M
        }
478
17.8M
        break;
479
17.8M
      }
480
19.3M
      if (arith_decode(cinfo, st + 1)) {        /* newly nonzero coef */
481
8.93M
        if (arith_decode(cinfo, entropy->fixed_bin))
482
4.36M
          *thiscoef = (JCOEF)m1;
483
4.57M
        else
484
4.57M
          *thiscoef = (JCOEF)p1;
485
8.93M
        break;
486
8.93M
      }
487
10.4M
      st += 3;  k++;
488
10.4M
      if (k > cinfo->Se) {
489
4
        WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
490
4
        entropy->ct = -1;                       /* spectral overflow */
491
4
        return TRUE;
492
4
      }
493
10.4M
    }
494
26.8M
  }
495
496
4.24M
  return TRUE;
497
4.24M
}
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
2.43M
{
507
2.43M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
508
2.43M
  jpeg_component_info *compptr;
509
2.43M
  JBLOCKROW block;
510
2.43M
  unsigned char *st;
511
2.43M
  int blkn, ci, tbl, sign, k;
512
2.43M
  int v, m;
513
514
  /* Process restart marker if needed */
515
2.43M
  if (cinfo->restart_interval) {
516
25
    if (entropy->restarts_to_go == 0)
517
1
      process_restart(cinfo);
518
25
    entropy->restarts_to_go--;
519
25
  }
520
521
2.43M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
522
523
  /* Outer loop handles each block in the MCU */
524
525
9.09M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
526
6.65M
    block = MCU_data ? MCU_data[blkn] : NULL;
527
6.65M
    ci = cinfo->MCU_membership[blkn];
528
6.65M
    compptr = cinfo->cur_comp_info[ci];
529
530
    /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
531
532
6.65M
    tbl = compptr->dc_tbl_no;
533
534
    /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
535
6.65M
    st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
536
537
    /* Figure F.19: Decode_DC_DIFF */
538
6.65M
    if (arith_decode(cinfo, st) == 0)
539
3.54M
      entropy->dc_context[ci] = 0;
540
3.11M
    else {
541
      /* Figure F.21: Decoding nonzero value v */
542
      /* Figure F.22: Decoding the sign of v */
543
3.11M
      sign = arith_decode(cinfo, st + 1);
544
3.11M
      st += 2;  st += sign;
545
      /* Figure F.23: Decoding the magnitude category of v */
546
3.11M
      if ((m = arith_decode(cinfo, st)) != 0) {
547
1.34M
        st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
548
3.20M
        while (arith_decode(cinfo, st)) {
549
1.86M
          if ((m <<= 1) == 0x8000) {
550
10
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
551
10
            entropy->ct = -1;                   /* magnitude overflow */
552
10
            return TRUE;
553
10
          }
554
1.86M
          st += 1;
555
1.86M
        }
556
1.34M
      }
557
      /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
558
3.11M
      if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))
559
0
        entropy->dc_context[ci] = 0;               /* zero diff category */
560
3.11M
      else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))
561
678k
        entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
562
2.43M
      else
563
2.43M
        entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
564
3.11M
      v = m;
565
      /* Figure F.24: Decoding the magnitude bit pattern of v */
566
3.11M
      st += 14;
567
4.97M
      while (m >>= 1)
568
1.86M
        if (arith_decode(cinfo, st)) v |= m;
569
3.11M
      v += 1;  if (sign) v = -v;
570
3.11M
      entropy->last_dc_val[ci] = (entropy->last_dc_val[ci] + v) & 0xffff;
571
3.11M
    }
572
573
6.65M
    if (block)
574
6.65M
      (*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
6.65M
    tbl = compptr->ac_tbl_no;
579
580
    /* Figure F.20: Decode_AC_coefficients */
581
16.9M
    for (k = 1; k <= DCTSIZE2 - 1; k++) {
582
16.9M
      st = entropy->ac_stats[tbl] + 3 * (k - 1);
583
16.9M
      if (arith_decode(cinfo, st)) break;       /* EOB flag */
584
23.5M
      while (arith_decode(cinfo, st + 1) == 0) {
585
13.3M
        st += 3;  k++;
586
13.3M
        if (k > DCTSIZE2 - 1) {
587
1
          WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
588
1
          entropy->ct = -1;                     /* spectral overflow */
589
1
          return TRUE;
590
1
        }
591
13.3M
      }
592
      /* Figure F.21: Decoding nonzero value v */
593
      /* Figure F.22: Decoding the sign of v */
594
10.2M
      sign = arith_decode(cinfo, entropy->fixed_bin);
595
10.2M
      st += 2;
596
      /* Figure F.23: Decoding the magnitude category of v */
597
10.2M
      if ((m = arith_decode(cinfo, st)) != 0) {
598
6.11M
        if (arith_decode(cinfo, st)) {
599
5.90M
          m <<= 1;
600
5.90M
          st = entropy->ac_stats[tbl] +
601
5.90M
               (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
602
15.7M
          while (arith_decode(cinfo, st)) {
603
9.88M
            if ((m <<= 1) == 0x8000) {
604
8
              WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
605
8
              entropy->ct = -1;                 /* magnitude overflow */
606
8
              return TRUE;
607
8
            }
608
9.88M
            st += 1;
609
9.88M
          }
610
5.90M
        }
611
6.11M
      }
612
10.2M
      v = m;
613
      /* Figure F.24: Decoding the magnitude bit pattern of v */
614
10.2M
      st += 14;
615
26.0M
      while (m >>= 1)
616
15.7M
        if (arith_decode(cinfo, st)) v |= m;
617
10.2M
      v += 1;  if (sign) v = -v;
618
10.2M
      if (block)
619
10.2M
        (*block)[jpeg_natural_order[k]] = (JCOEF)v;
620
10.2M
    }
621
6.65M
  }
622
623
2.43M
  return TRUE;
624
2.43M
}
625
626
627
/*
628
 * Initialize for an arithmetic-compressed scan.
629
 */
630
631
METHODDEF(void)
632
start_pass(j_decompress_ptr cinfo)
633
5.76k
{
634
5.76k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
635
5.76k
  int ci, tbl;
636
5.76k
  jpeg_component_info *compptr;
637
638
5.76k
  if (cinfo->progressive_mode) {
639
    /* Validate progressive scan parameters */
640
5.36k
    if (cinfo->Ss == 0) {
641
2.81k
      if (cinfo->Se != 0)
642
5
        goto bad;
643
2.81k
    } else {
644
      /* need not check Ss/Se < 0 since they came from unsigned bytes */
645
2.54k
      if (cinfo->Se < cinfo->Ss || cinfo->Se > DCTSIZE2 - 1)
646
16
        goto bad;
647
      /* AC scans may have only one component */
648
2.53k
      if (cinfo->comps_in_scan != 1)
649
6
        goto bad;
650
2.53k
    }
651
5.33k
    if (cinfo->Ah != 0) {
652
      /* Successive approximation refinement scan: must have Al = Ah-1. */
653
798
      if (cinfo->Ah - 1 != cinfo->Al)
654
7
        goto bad;
655
798
    }
656
5.32k
    if (cinfo->Al > 13) {       /* need not check for < 0 */
657
38
bad:
658
38
      ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
659
38
               cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
660
38
    }
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
16.2k
    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
666
10.9k
      int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
667
10.9k
      int *coef_bit_ptr = &cinfo->coef_bits[cindex][0];
668
10.9k
      int *prev_coef_bit_ptr =
669
10.9k
        &cinfo->coef_bits[cindex + cinfo->num_components][0];
670
10.9k
      if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
671
8
        WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
672
249k
      for (coefi = MIN(cinfo->Ss, 1); coefi <= MAX(cinfo->Se, 9); coefi++) {
673
239k
        if (cinfo->input_scan_number > 1)
674
169k
          prev_coef_bit_ptr[coefi] = coef_bit_ptr[coefi];
675
69.8k
        else
676
69.8k
          prev_coef_bit_ptr[coefi] = 0;
677
239k
      }
678
169k
      for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
679
158k
        int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
680
158k
        if (cinfo->Ah != expected)
681
20
          WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
682
158k
        coef_bit_ptr[coefi] = cinfo->Al;
683
158k
      }
684
10.9k
    }
685
    /* Select MCU decoding routine */
686
5.36k
    if (cinfo->Ah == 0) {
687
4.51k
      if (cinfo->Ss == 0)
688
2.57k
        entropy->pub.decode_mcu = decode_mcu_DC_first;
689
1.94k
      else
690
1.94k
        entropy->pub.decode_mcu = decode_mcu_AC_first;
691
4.51k
    } else {
692
843
      if (cinfo->Ss == 0)
693
218
        entropy->pub.decode_mcu = decode_mcu_DC_refine;
694
625
      else
695
625
        entropy->pub.decode_mcu = decode_mcu_AC_refine;
696
843
    }
697
5.36k
  } 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
404
    if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||
702
404
        cinfo->Ah != 0 || cinfo->Al != 0)
703
13
      WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
704
    /* Select MCU decoding routine */
705
404
    entropy->pub.decode_mcu = decode_mcu;
706
404
  }
707
708
  /* Allocate & initialize requested statistics areas */
709
17.6k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
710
11.8k
    compptr = cinfo->cur_comp_info[ci];
711
11.8k
    if (!cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
712
8.70k
      tbl = compptr->dc_tbl_no;
713
8.70k
      if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
714
0
        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
715
8.70k
      if (entropy->dc_stats[tbl] == NULL)
716
7.00k
        entropy->dc_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)
717
7.00k
          ((j_common_ptr)cinfo, JPOOL_IMAGE, DC_STAT_BINS);
718
8.70k
      memset(entropy->dc_stats[tbl], 0, DC_STAT_BINS);
719
      /* Initialize DC predictions to 0 */
720
8.70k
      entropy->last_dc_val[ci] = 0;
721
8.70k
      entropy->dc_context[ci] = 0;
722
8.70k
    }
723
11.8k
    if (!cinfo->progressive_mode || cinfo->Ss) {
724
3.49k
      tbl = compptr->ac_tbl_no;
725
3.49k
      if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
726
0
        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
727
3.49k
      if (entropy->ac_stats[tbl] == NULL)
728
2.08k
        entropy->ac_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)
729
2.08k
          ((j_common_ptr)cinfo, JPOOL_IMAGE, AC_STAT_BINS);
730
3.49k
      memset(entropy->ac_stats[tbl], 0, AC_STAT_BINS);
731
3.49k
    }
732
11.8k
  }
733
734
  /* Initialize arithmetic decoding variables */
735
5.76k
  entropy->c = 0;
736
5.76k
  entropy->a = 0;
737
5.76k
  entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
738
5.76k
  entropy->pub.insufficient_data = FALSE;
739
740
  /* Initialize restart counter */
741
5.76k
  entropy->restarts_to_go = cinfo->restart_interval;
742
5.76k
}
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
2.78k
{
752
2.78k
  arith_entropy_ptr entropy;
753
2.78k
  int i;
754
755
2.78k
  entropy = (arith_entropy_ptr)
756
2.78k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
757
2.78k
                                sizeof(arith_entropy_decoder));
758
2.78k
  cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
759
2.78k
  entropy->pub.start_pass = start_pass;
760
761
  /* Mark tables unallocated */
762
47.3k
  for (i = 0; i < NUM_ARITH_TBLS; i++) {
763
44.5k
    entropy->dc_stats[i] = NULL;
764
44.5k
    entropy->ac_stats[i] = NULL;
765
44.5k
  }
766
767
  /* Initialize index for fixed probability estimation */
768
2.78k
  entropy->fixed_bin[0] = 113;
769
770
2.78k
  if (cinfo->progressive_mode) {
771
    /* Create progression status table */
772
2.38k
    int *coef_bit_ptr, ci;
773
2.38k
    cinfo->coef_bits = (int (*)[DCTSIZE2])
774
2.38k
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
775
2.38k
                                  cinfo->num_components * 2 * DCTSIZE2 *
776
2.38k
                                  sizeof(int));
777
2.38k
    coef_bit_ptr = &cinfo->coef_bits[0][0];
778
9.51k
    for (ci = 0; ci < cinfo->num_components; ci++)
779
464k
      for (i = 0; i < DCTSIZE2; i++)
780
456k
        *coef_bit_ptr++ = -1;
781
2.38k
  }
782
2.78k
}