Coverage Report

Created: 2026-05-11 06:55

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