Coverage Report

Created: 2024-01-23 06:27

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