Coverage Report

Created: 2025-07-01 06:26

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