Coverage Report

Created: 2026-04-28 06:57

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