Coverage Report

Created: 2024-05-04 12:45

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