Coverage Report

Created: 2024-08-17 06:42

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