Coverage Report

Created: 2026-02-14 09:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/workdir/UnpackedTarball/libjpeg-turbo/src/jdarith.c
Line
Count
Source
1
/*
2
 * jdarith.c
3
 *
4
 * This file was part of the Independent JPEG Group's software:
5
 * Developed 1997-2015 by Guido Vollbeding.
6
 * libjpeg-turbo Modifications:
7
 * Copyright (C) 2015-2020, 2022, D. R. Commander.
8
 * For conditions of distribution and use, see the accompanying README.ijg
9
 * file.
10
 *
11
 * This file contains portable arithmetic entropy encoding routines for JPEG
12
 * (implementing Recommendation ITU-T T.81 | ISO/IEC 10918-1).
13
 *
14
 * Both sequential and progressive modes are supported in this single module.
15
 *
16
 * Suspension is not currently supported in this module.
17
 *
18
 * NOTE: All referenced figures are from
19
 * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
20
 */
21
22
#define JPEG_INTERNALS
23
#include "jinclude.h"
24
#include "jpeglib.h"
25
26
27
7.28M
#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
180k
#define DC_STAT_BINS  64
70
175k
#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
1.63M
{
77
1.63M
  struct jpeg_source_mgr *src = cinfo->src;
78
79
1.63M
  if (src->bytes_in_buffer == 0)
80
3.44k
    if (!(*src->fill_input_buffer) (cinfo))
81
0
      ERREXIT(cinfo, JERR_CANT_SUSPEND);
82
1.63M
  src->bytes_in_buffer--;
83
1.63M
  return *src->next_input_byte++;
84
1.63M
}
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
513M
{
117
513M
  register arith_entropy_ptr e = (arith_entropy_ptr)cinfo->entropy;
118
513M
  register unsigned char nl, nm;
119
513M
  register JLONG qe, temp;
120
513M
  register int sv, data;
121
122
  /* Renormalization & data input per section D.2.6 */
123
645M
  while (e->a < 0x8000L) {
124
132M
    if (--e->ct < 0) {
125
      /* Need to fetch next data byte */
126
24.7M
      if (cinfo->unread_marker)
127
23.3M
        data = 0;               /* stuff zero data */
128
1.44M
      else {
129
1.44M
        data = get_byte(cinfo); /* read next input byte */
130
1.44M
        if (data == 0xFF) {     /* zero stuff or marker code */
131
195k
          do data = get_byte(cinfo);
132
195k
          while (data == 0xFF); /* swallow extra 0xFF bytes */
133
35.0k
          if (data == 0)
134
9.03k
            data = 0xFF;        /* discard stuffed zero byte */
135
26.0k
          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
26.0k
            cinfo->unread_marker = data;
143
26.0k
            data = 0;
144
26.0k
          }
145
35.0k
        }
146
1.44M
      }
147
24.7M
      e->c = (e->c << 8) | data; /* insert data into C register */
148
24.7M
      if ((e->ct += 8) < 0)      /* update bit shift counter */
149
        /* Need more initial bytes */
150
6.90M
        if (++e->ct == 0)
151
          /* Got 2 initial bytes -> re-init A and exit loop */
152
3.45M
          e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */
153
24.7M
    }
154
132M
    e->a <<= 1;
155
132M
  }
156
157
  /* Fetch values from our compact representation of Table D.2:
158
   * Qe values and probability estimation state machine
159
   */
160
513M
  sv = *st;
161
513M
  qe = jpeg_aritab[sv & 0x7F];  /* => Qe_Value */
162
513M
  nl = qe & 0xFF;  qe >>= 8;    /* Next_Index_LPS + Switch_MPS */
163
513M
  nm = qe & 0xFF;  qe >>= 8;    /* Next_Index_MPS */
164
165
  /* Decode & estimation procedures per sections D.2.4 & D.2.5 */
166
513M
  temp = e->a - qe;
167
513M
  e->a = temp;
168
513M
  temp <<= e->ct;
169
513M
  if (e->c >= temp) {
170
28.7M
    e->c -= temp;
171
    /* Conditional LPS (less probable symbol) exchange */
172
28.7M
    if (e->a < qe) {
173
7.51M
      e->a = qe;
174
7.51M
      *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
175
21.2M
    } else {
176
21.2M
      e->a = qe;
177
21.2M
      *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
178
21.2M
      sv ^= 0x80;               /* Exchange LPS/MPS */
179
21.2M
    }
180
484M
  } else if (e->a < 0x8000L) {
181
    /* Conditional MPS (more probable symbol) exchange */
182
66.1M
    if (e->a < qe) {
183
31.3M
      *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
184
31.3M
      sv ^= 0x80;               /* Exchange LPS/MPS */
185
34.8M
    } else {
186
34.8M
      *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
187
34.8M
    }
188
66.1M
  }
189
190
513M
  return sv >> 7;
191
513M
}
192
193
194
/*
195
 * Check for a restart marker & resynchronize decoder.
196
 */
197
198
LOCAL(void)
199
process_restart(j_decompress_ptr cinfo)
200
3.41M
{
201
3.41M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
202
3.41M
  int ci;
203
3.41M
  jpeg_component_info *compptr;
204
205
  /* Advance past the RSTn marker */
206
3.41M
  if (!(*cinfo->marker->read_restart_marker) (cinfo))
207
0
    ERREXIT(cinfo, JERR_CANT_SUSPEND);
208
209
  /* Re-initialize statistics areas */
210
13.3M
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
211
9.95M
    compptr = cinfo->cur_comp_info[ci];
212
9.95M
    if (!cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
213
135k
      memset(entropy->dc_stats[compptr->dc_tbl_no], 0, DC_STAT_BINS);
214
      /* Reset DC predictions to 0 */
215
135k
      entropy->last_dc_val[ci] = 0;
216
135k
      entropy->dc_context[ci] = 0;
217
135k
    }
218
9.95M
    if (!cinfo->progressive_mode || cinfo->Ss) {
219
136k
      memset(entropy->ac_stats[compptr->ac_tbl_no], 0, AC_STAT_BINS);
220
136k
    }
221
9.95M
  }
222
223
  /* Reset arithmetic decoding variables */
224
3.41M
  entropy->c = 0;
225
3.41M
  entropy->a = 0;
226
3.41M
  entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
227
228
  /* Reset restart counter */
229
3.41M
  entropy->restarts_to_go = cinfo->restart_interval;
230
3.41M
}
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
12.4M
{
252
12.4M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
253
12.4M
  JBLOCKROW block;
254
12.4M
  unsigned char *st;
255
12.4M
  int blkn, ci, tbl, sign;
256
12.4M
  int v, m;
257
258
  /* Process restart marker if needed */
259
12.4M
  if (cinfo->restart_interval) {
260
587k
    if (entropy->restarts_to_go == 0)
261
5.80k
      process_restart(cinfo);
262
587k
    entropy->restarts_to_go--;
263
587k
  }
264
265
12.4M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
266
267
  /* Outer loop handles each block in the MCU */
268
269
41.4M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
270
29.6M
    block = MCU_data[blkn];
271
29.6M
    ci = cinfo->MCU_membership[blkn];
272
29.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
29.6M
    st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
278
279
    /* Figure F.19: Decode_DC_DIFF */
280
29.6M
    if (arith_decode(cinfo, st) == 0)
281
15.9M
      entropy->dc_context[ci] = 0;
282
13.6M
    else {
283
      /* Figure F.21: Decoding nonzero value v */
284
      /* Figure F.22: Decoding the sign of v */
285
13.6M
      sign = arith_decode(cinfo, st + 1);
286
13.6M
      st += 2;  st += sign;
287
      /* Figure F.23: Decoding the magnitude category of v */
288
13.6M
      if ((m = arith_decode(cinfo, st)) != 0) {
289
8.33M
        st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
290
23.9M
        while (arith_decode(cinfo, st)) {
291
15.5M
          if ((m <<= 1) == 0x8000) {
292
1.04k
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
293
1.04k
            entropy->ct = -1;                   /* magnitude overflow */
294
1.04k
            return TRUE;
295
1.04k
          }
296
15.5M
          st += 1;
297
15.5M
        }
298
8.33M
      }
299
      /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
300
13.6M
      if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))
301
166k
        entropy->dc_context[ci] = 0;               /* zero diff category */
302
13.5M
      else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))
303
6.33M
        entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
304
7.18M
      else
305
7.18M
        entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
306
13.6M
      v = m;
307
      /* Figure F.24: Decoding the magnitude bit pattern of v */
308
13.6M
      st += 14;
309
29.2M
      while (m >>= 1)
310
15.5M
        if (arith_decode(cinfo, st)) v |= m;
311
13.6M
      v += 1;  if (sign) v = -v;
312
13.6M
      entropy->last_dc_val[ci] = (entropy->last_dc_val[ci] + v) & 0xffff;
313
13.6M
    }
314
315
    /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
316
29.6M
    (*block)[0] = (JCOEF)LEFT_SHIFT(entropy->last_dc_val[ci], cinfo->Al);
317
29.6M
  }
318
319
11.7M
  return TRUE;
320
11.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
20.6M
{
331
20.6M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
332
20.6M
  JBLOCKROW block;
333
20.6M
  unsigned char *st;
334
20.6M
  int tbl, sign, k;
335
20.6M
  int v, m;
336
337
  /* Process restart marker if needed */
338
20.6M
  if (cinfo->restart_interval) {
339
1.92M
    if (entropy->restarts_to_go == 0)
340
4.01k
      process_restart(cinfo);
341
1.92M
    entropy->restarts_to_go--;
342
1.92M
  }
343
344
20.6M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
345
346
  /* There is always only one block per MCU */
347
15.8M
  block = MCU_data[0];
348
15.8M
  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
25.9M
  for (k = cinfo->Ss; k <= cinfo->Se; k++) {
354
25.9M
    st = entropy->ac_stats[tbl] + 3 * (k - 1);
355
25.9M
    if (arith_decode(cinfo, st)) break;         /* EOB flag */
356
18.2M
    while (arith_decode(cinfo, st + 1) == 0) {
357
8.19M
      st += 3;  k++;
358
8.19M
      if (k > cinfo->Se) {
359
627
        WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
360
627
        entropy->ct = -1;                       /* spectral overflow */
361
627
        return TRUE;
362
627
      }
363
8.19M
    }
364
    /* Figure F.21: Decoding nonzero value v */
365
    /* Figure F.22: Decoding the sign of v */
366
10.0M
    sign = arith_decode(cinfo, entropy->fixed_bin);
367
10.0M
    st += 2;
368
    /* Figure F.23: Decoding the magnitude category of v */
369
10.0M
    if ((m = arith_decode(cinfo, st)) != 0) {
370
5.51M
      if (arith_decode(cinfo, st)) {
371
4.13M
        m <<= 1;
372
4.13M
        st = entropy->ac_stats[tbl] +
373
4.13M
             (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
374
9.54M
        while (arith_decode(cinfo, st)) {
375
5.40M
          if ((m <<= 1) == 0x8000) {
376
790
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
377
790
            entropy->ct = -1;                   /* magnitude overflow */
378
790
            return TRUE;
379
790
          }
380
5.40M
          st += 1;
381
5.40M
        }
382
4.13M
      }
383
5.51M
    }
384
10.0M
    v = m;
385
    /* Figure F.24: Decoding the magnitude bit pattern of v */
386
10.0M
    st += 14;
387
19.6M
    while (m >>= 1)
388
9.53M
      if (arith_decode(cinfo, st)) v |= m;
389
10.0M
    v += 1;  if (sign) v = -v;
390
    /* Scale and output coefficient in natural (dezigzagged) order */
391
10.0M
    (*block)[jpeg_natural_order[k]] = (JCOEF)((unsigned)v << cinfo->Al);
392
10.0M
  }
393
394
15.8M
  return TRUE;
395
15.8M
}
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
12.7M
{
405
12.7M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
406
12.7M
  unsigned char *st;
407
12.7M
  int p1, blkn;
408
409
  /* Process restart marker if needed */
410
12.7M
  if (cinfo->restart_interval) {
411
3.70M
    if (entropy->restarts_to_go == 0)
412
3.28M
      process_restart(cinfo);
413
3.70M
    entropy->restarts_to_go--;
414
3.70M
  }
415
416
12.7M
  st = entropy->fixed_bin;      /* use fixed probability estimation */
417
12.7M
  p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
418
419
  /* Outer loop handles each block in the MCU */
420
421
52.4M
  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
39.6M
    if (arith_decode(cinfo, st))
424
20.6M
      MCU_data[blkn][0][0] |= p1;
425
39.6M
  }
426
427
12.7M
  return TRUE;
428
12.7M
}
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
9.17M
{
438
9.17M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
439
9.17M
  JBLOCKROW block;
440
9.17M
  JCOEFPTR thiscoef;
441
9.17M
  unsigned char *st;
442
9.17M
  int tbl, k, kex;
443
9.17M
  int p1, m1;
444
445
  /* Process restart marker if needed */
446
9.17M
  if (cinfo->restart_interval) {
447
1.10M
    if (entropy->restarts_to_go == 0)
448
8.20k
      process_restart(cinfo);
449
1.10M
    entropy->restarts_to_go--;
450
1.10M
  }
451
452
9.17M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
453
454
  /* There is always only one block per MCU */
455
7.28M
  block = MCU_data[0];
456
7.28M
  tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
457
458
7.28M
  p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
459
7.28M
  m1 = (NEG_1) << cinfo->Al;    /* -1 in the bit position being coded */
460
461
  /* Establish EOBx (previous stage end-of-block) index */
462
241M
  for (kex = cinfo->Se; kex > 0; kex--)
463
235M
    if ((*block)[jpeg_natural_order[kex]]) break;
464
465
14.0M
  for (k = cinfo->Ss; k <= cinfo->Se; k++) {
466
13.7M
    st = entropy->ac_stats[tbl] + 3 * (k - 1);
467
13.7M
    if (k > kex)
468
9.51M
      if (arith_decode(cinfo, st)) break;       /* EOB flag */
469
9.47M
    for (;;) {
470
9.47M
      thiscoef = *block + jpeg_natural_order[k];
471
9.47M
      if (*thiscoef) {                          /* previously nonzero coef */
472
2.08M
        if (arith_decode(cinfo, st + 2)) {
473
1.57M
          if (*thiscoef < 0)
474
786k
            *thiscoef += (JCOEF)m1;
475
788k
          else
476
788k
            *thiscoef += (JCOEF)p1;
477
1.57M
        }
478
2.08M
        break;
479
2.08M
      }
480
7.39M
      if (arith_decode(cinfo, st + 1)) {        /* newly nonzero coef */
481
4.69M
        if (arith_decode(cinfo, entropy->fixed_bin))
482
2.08M
          *thiscoef = (JCOEF)m1;
483
2.60M
        else
484
2.60M
          *thiscoef = (JCOEF)p1;
485
4.69M
        break;
486
4.69M
      }
487
2.70M
      st += 3;  k++;
488
2.70M
      if (k > cinfo->Se) {
489
765
        WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
490
765
        entropy->ct = -1;                       /* spectral overflow */
491
765
        return TRUE;
492
765
      }
493
2.70M
    }
494
6.77M
  }
495
496
7.28M
  return TRUE;
497
7.28M
}
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.05M
{
507
9.05M
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
508
9.05M
  jpeg_component_info *compptr;
509
9.05M
  JBLOCKROW block;
510
9.05M
  unsigned char *st;
511
9.05M
  int blkn, ci, tbl, sign, k;
512
9.05M
  int v, m;
513
514
  /* Process restart marker if needed */
515
9.05M
  if (cinfo->restart_interval) {
516
2.98M
    if (entropy->restarts_to_go == 0)
517
118k
      process_restart(cinfo);
518
2.98M
    entropy->restarts_to_go--;
519
2.98M
  }
520
521
9.05M
  if (entropy->ct == -1) return TRUE;   /* if error do nothing */
522
523
  /* Outer loop handles each block in the MCU */
524
525
26.1M
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
526
18.0M
    block = MCU_data ? MCU_data[blkn] : NULL;
527
18.0M
    ci = cinfo->MCU_membership[blkn];
528
18.0M
    compptr = cinfo->cur_comp_info[ci];
529
530
    /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
531
532
18.0M
    tbl = compptr->dc_tbl_no;
533
534
    /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
535
18.0M
    st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
536
537
    /* Figure F.19: Decode_DC_DIFF */
538
18.0M
    if (arith_decode(cinfo, st) == 0)
539
3.64M
      entropy->dc_context[ci] = 0;
540
14.4M
    else {
541
      /* Figure F.21: Decoding nonzero value v */
542
      /* Figure F.22: Decoding the sign of v */
543
14.4M
      sign = arith_decode(cinfo, st + 1);
544
14.4M
      st += 2;  st += sign;
545
      /* Figure F.23: Decoding the magnitude category of v */
546
14.4M
      if ((m = arith_decode(cinfo, st)) != 0) {
547
13.3M
        st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
548
64.0M
        while (arith_decode(cinfo, st)) {
549
50.6M
          if ((m <<= 1) == 0x8000) {
550
774
            WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
551
774
            entropy->ct = -1;                   /* magnitude overflow */
552
774
            return TRUE;
553
774
          }
554
50.6M
          st += 1;
555
50.6M
        }
556
13.3M
      }
557
      /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
558
14.4M
      if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))
559
190k
        entropy->dc_context[ci] = 0;               /* zero diff category */
560
14.2M
      else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))
561
12.4M
        entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
562
1.74M
      else
563
1.74M
        entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
564
14.4M
      v = m;
565
      /* Figure F.24: Decoding the magnitude bit pattern of v */
566
14.4M
      st += 14;
567
65.0M
      while (m >>= 1)
568
50.6M
        if (arith_decode(cinfo, st)) v |= m;
569
14.4M
      v += 1;  if (sign) v = -v;
570
14.4M
      entropy->last_dc_val[ci] = (entropy->last_dc_val[ci] + v) & 0xffff;
571
14.4M
    }
572
573
18.0M
    if (block)
574
18.0M
      (*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
18.0M
    tbl = compptr->ac_tbl_no;
579
580
    /* Figure F.20: Decode_AC_coefficients */
581
27.7M
    for (k = 1; k <= DCTSIZE2 - 1; k++) {
582
27.5M
      st = entropy->ac_stats[tbl] + 3 * (k - 1);
583
27.5M
      if (arith_decode(cinfo, st)) break;       /* EOB flag */
584
26.5M
      while (arith_decode(cinfo, st + 1) == 0) {
585
16.8M
        st += 3;  k++;
586
16.8M
        if (k > DCTSIZE2 - 1) {
587
368
          WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
588
368
          entropy->ct = -1;                     /* spectral overflow */
589
368
          return TRUE;
590
368
        }
591
16.8M
      }
592
      /* Figure F.21: Decoding nonzero value v */
593
      /* Figure F.22: Decoding the sign of v */
594
9.69M
      sign = arith_decode(cinfo, entropy->fixed_bin);
595
9.69M
      st += 2;
596
      /* Figure F.23: Decoding the magnitude category of v */
597
9.69M
      if ((m = arith_decode(cinfo, st)) != 0) {
598
5.13M
        if (arith_decode(cinfo, st)) {
599
4.79M
          m <<= 1;
600
4.79M
          st = entropy->ac_stats[tbl] +
601
4.79M
               (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
602
11.9M
          while (arith_decode(cinfo, st)) {
603
7.15M
            if ((m <<= 1) == 0x8000) {
604
535
              WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
605
535
              entropy->ct = -1;                 /* magnitude overflow */
606
535
              return TRUE;
607
535
            }
608
7.15M
            st += 1;
609
7.15M
          }
610
4.79M
        }
611
5.13M
      }
612
9.69M
      v = m;
613
      /* Figure F.24: Decoding the magnitude bit pattern of v */
614
9.69M
      st += 14;
615
21.6M
      while (m >>= 1)
616
11.9M
        if (arith_decode(cinfo, st)) v |= m;
617
9.69M
      v += 1;  if (sign) v = -v;
618
9.69M
      if (block)
619
9.69M
        (*block)[jpeg_natural_order[k]] = (JCOEF)v;
620
9.69M
    }
621
18.0M
  }
622
623
8.11M
  return TRUE;
624
8.11M
}
625
626
627
/*
628
 * Initialize for an arithmetic-compressed scan.
629
 */
630
631
METHODDEF(void)
632
start_pass(j_decompress_ptr cinfo)
633
32.9k
{
634
32.9k
  arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;
635
32.9k
  int ci, tbl;
636
32.9k
  jpeg_component_info *compptr;
637
638
32.9k
  if (cinfo->progressive_mode) {
639
    /* Validate progressive scan parameters */
640
11.4k
    if (cinfo->Ss == 0) {
641
6.76k
      if (cinfo->Se != 0)
642
12
        goto bad;
643
6.76k
    } else {
644
      /* need not check Ss/Se < 0 since they came from unsigned bytes */
645
4.69k
      if (cinfo->Se < cinfo->Ss || cinfo->Se > DCTSIZE2 - 1)
646
36
        goto bad;
647
      /* AC scans may have only one component */
648
4.66k
      if (cinfo->comps_in_scan != 1)
649
2
        goto bad;
650
4.66k
    }
651
11.4k
    if (cinfo->Ah != 0) {
652
      /* Successive approximation refinement scan: must have Al = Ah-1. */
653
4.22k
      if (cinfo->Ah - 1 != cinfo->Al)
654
13
        goto bad;
655
4.22k
    }
656
11.3k
    if (cinfo->Al > 13) {       /* need not check for < 0 */
657
65
bad:
658
65
      ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
659
65
               cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
660
65
    }
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
33.4k
    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
666
22.0k
      int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
667
22.0k
      int *coef_bit_ptr = &cinfo->coef_bits[cindex][0];
668
22.0k
      int *prev_coef_bit_ptr =
669
22.0k
        &cinfo->coef_bits[cindex + cinfo->num_components][0];
670
22.0k
      if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
671
3.06k
        WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
672
367k
      for (coefi = MIN(cinfo->Ss, 1); coefi <= MAX(cinfo->Se, 9); coefi++) {
673
345k
        if (cinfo->input_scan_number > 1)
674
222k
          prev_coef_bit_ptr[coefi] = coef_bit_ptr[coefi];
675
123k
        else
676
123k
          prev_coef_bit_ptr[coefi] = 0;
677
345k
      }
678
172k
      for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
679
150k
        int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
680
150k
        if (cinfo->Ah != expected)
681
52.0k
          WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
682
150k
        coef_bit_ptr[coefi] = cinfo->Al;
683
150k
      }
684
22.0k
    }
685
    /* Select MCU decoding routine */
686
11.4k
    if (cinfo->Ah == 0) {
687
7.18k
      if (cinfo->Ss == 0)
688
3.51k
        entropy->pub.decode_mcu = decode_mcu_DC_first;
689
3.67k
      else
690
3.67k
        entropy->pub.decode_mcu = decode_mcu_AC_first;
691
7.18k
    } else {
692
4.27k
      if (cinfo->Ss == 0)
693
3.23k
        entropy->pub.decode_mcu = decode_mcu_DC_refine;
694
1.04k
      else
695
1.04k
        entropy->pub.decode_mcu = decode_mcu_AC_refine;
696
4.27k
    }
697
21.5k
  } 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
21.5k
    if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||
702
6.42k
        cinfo->Ah != 0 || cinfo->Al != 0)
703
19.1k
      WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
704
    /* Select MCU decoding routine */
705
21.5k
    entropy->pub.decode_mcu = decode_mcu;
706
21.5k
  }
707
708
  /* Allocate & initialize requested statistics areas */
709
79.6k
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
710
46.7k
    compptr = cinfo->cur_comp_info[ci];
711
46.7k
    if (!cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
712
33.7k
      tbl = compptr->dc_tbl_no;
713
33.7k
      if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
714
0
        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
715
33.7k
      if (entropy->dc_stats[tbl] == NULL)
716
11.0k
        entropy->dc_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)
717
11.0k
          ((j_common_ptr)cinfo, JPOOL_IMAGE, DC_STAT_BINS);
718
33.7k
      memset(entropy->dc_stats[tbl], 0, DC_STAT_BINS);
719
      /* Initialize DC predictions to 0 */
720
33.7k
      entropy->last_dc_val[ci] = 0;
721
33.7k
      entropy->dc_context[ci] = 0;
722
33.7k
    }
723
46.7k
    if (!cinfo->progressive_mode || cinfo->Ss) {
724
29.3k
      tbl = compptr->ac_tbl_no;
725
29.3k
      if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
726
0
        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
727
29.3k
      if (entropy->ac_stats[tbl] == NULL)
728
9.34k
        entropy->ac_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)
729
9.34k
          ((j_common_ptr)cinfo, JPOOL_IMAGE, AC_STAT_BINS);
730
29.3k
      memset(entropy->ac_stats[tbl], 0, AC_STAT_BINS);
731
29.3k
    }
732
46.7k
  }
733
734
  /* Initialize arithmetic decoding variables */
735
32.9k
  entropy->c = 0;
736
32.9k
  entropy->a = 0;
737
32.9k
  entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
738
32.9k
  entropy->pub.insufficient_data = FALSE;
739
740
  /* Initialize restart counter */
741
32.9k
  entropy->restarts_to_go = cinfo->restart_interval;
742
32.9k
}
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
8.73k
{
752
8.73k
  arith_entropy_ptr entropy;
753
8.73k
  int i;
754
755
8.73k
  entropy = (arith_entropy_ptr)
756
8.73k
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
757
8.73k
                                sizeof(arith_entropy_decoder));
758
8.73k
  cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
759
8.73k
  entropy->pub.start_pass = start_pass;
760
761
  /* Mark tables unallocated */
762
148k
  for (i = 0; i < NUM_ARITH_TBLS; i++) {
763
139k
    entropy->dc_stats[i] = NULL;
764
139k
    entropy->ac_stats[i] = NULL;
765
139k
  }
766
767
  /* Initialize index for fixed probability estimation */
768
8.73k
  entropy->fixed_bin[0] = 113;
769
770
8.73k
  if (cinfo->progressive_mode) {
771
    /* Create progression status table */
772
4.60k
    int *coef_bit_ptr, ci;
773
4.60k
    cinfo->coef_bits = (int (*)[DCTSIZE2])
774
4.60k
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
775
4.60k
                                  cinfo->num_components * 2 * DCTSIZE2 *
776
4.60k
                                  sizeof(int));
777
4.60k
    coef_bit_ptr = &cinfo->coef_bits[0][0];
778
17.1k
    for (ci = 0; ci < cinfo->num_components; ci++)
779
817k
      for (i = 0; i < DCTSIZE2; i++)
780
805k
        *coef_bit_ptr++ = -1;
781
4.60k
  }
782
8.73k
}