1 /*
2  * jdarith.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Developed 1997-2009 by Guido Vollbeding.
6  * libjpeg-turbo Modifications:
7  * Copyright (C) 2015, D. R. Commander.
8  * For conditions of distribution and use, see the accompanying README file.
9  *
10  * This file contains portable arithmetic entropy decoding routines for JPEG
11  * (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
12  *
13  * Both sequential and progressive modes are supported in this single module.
14  *
15  * Suspension is not currently supported in this module.
16  */
17 
18 #define JPEG_INTERNALS
19 #include "jinclude.h"
20 #include "jpeglib.h"
21 
22 
23 /* Expanded entropy decoder object for arithmetic decoding. */
24 
25 typedef struct {
26   struct jpeg_entropy_decoder pub; /* public fields */
27 
28   INT32 c;       /* C register, base of coding interval + input bit buffer */
29   INT32 a;               /* A register, normalized size of coding interval */
30   int ct;     /* bit shift counter, # of bits left in bit buffer part of C */
31                                                          /* init: ct = -16 */
32                                                          /* run: ct = 0..7 */
33                                                          /* error: ct = -1 */
34   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
35   int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
36 
37   unsigned int restarts_to_go;  /* MCUs left in this restart interval */
38 
39   /* Pointers to statistics areas (these workspaces have image lifespan) */
40   unsigned char * dc_stats[NUM_ARITH_TBLS];
41   unsigned char * ac_stats[NUM_ARITH_TBLS];
42 
43   /* Statistics bin for coding with fixed probability 0.5 */
44   unsigned char fixed_bin[4];
45 } arith_entropy_decoder;
46 
47 typedef arith_entropy_decoder * arith_entropy_ptr;
48 
49 /* The following two definitions specify the allocation chunk size
50  * for the statistics area.
51  * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
52  * 49 statistics bins for DC, and 245 statistics bins for AC coding.
53  *
54  * We use a compact representation with 1 byte per statistics bin,
55  * thus the numbers directly represent byte sizes.
56  * This 1 byte per statistics bin contains the meaning of the MPS
57  * (more probable symbol) in the highest bit (mask 0x80), and the
58  * index into the probability estimation state machine table
59  * in the lower bits (mask 0x7F).
60  */
61 
62 #define DC_STAT_BINS 64
63 #define AC_STAT_BINS 256
64 
65 
66 LOCAL(int)
get_byte(j_decompress_ptr cinfo)67 get_byte (j_decompress_ptr cinfo)
68 /* Read next input byte; we do not support suspension in this module. */
69 {
70   struct jpeg_source_mgr * src = cinfo->src;
71 
72   if (src->bytes_in_buffer == 0)
73     if (! (*src->fill_input_buffer) (cinfo))
74       ERREXIT(cinfo, JERR_CANT_SUSPEND);
75   src->bytes_in_buffer--;
76   return GETJOCTET(*src->next_input_byte++);
77 }
78 
79 
80 /*
81  * The core arithmetic decoding routine (common in JPEG and JBIG).
82  * This needs to go as fast as possible.
83  * Machine-dependent optimization facilities
84  * are not utilized in this portable implementation.
85  * However, this code should be fairly efficient and
86  * may be a good base for further optimizations anyway.
87  *
88  * Return value is 0 or 1 (binary decision).
89  *
90  * Note: I've changed the handling of the code base & bit
91  * buffer register C compared to other implementations
92  * based on the standards layout & procedures.
93  * While it also contains both the actual base of the
94  * coding interval (16 bits) and the next-bits buffer,
95  * the cut-point between these two parts is floating
96  * (instead of fixed) with the bit shift counter CT.
97  * Thus, we also need only one (variable instead of
98  * fixed size) shift for the LPS/MPS decision, and
99  * we can get away with any renormalization update
100  * of C (except for new data insertion, of course).
101  *
102  * I've also introduced a new scheme for accessing
103  * the probability estimation state machine table,
104  * derived from Markus Kuhn's JBIG implementation.
105  */
106 
107 LOCAL(int)
arith_decode(j_decompress_ptr cinfo,unsigned char * st)108 arith_decode (j_decompress_ptr cinfo, unsigned char *st)
109 {
110   register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
111   register unsigned char nl, nm;
112   register INT32 qe, temp;
113   register int sv, data;
114 
115   /* Renormalization & data input per section D.2.6 */
116   while (e->a < 0x8000L) {
117     if (--e->ct < 0) {
118       /* Need to fetch next data byte */
119       if (cinfo->unread_marker)
120         data = 0;               /* stuff zero data */
121       else {
122         data = get_byte(cinfo); /* read next input byte */
123         if (data == 0xFF) {     /* zero stuff or marker code */
124           do data = get_byte(cinfo);
125           while (data == 0xFF); /* swallow extra 0xFF bytes */
126           if (data == 0)
127             data = 0xFF;        /* discard stuffed zero byte */
128           else {
129             /* Note: Different from the Huffman decoder, hitting
130              * a marker while processing the compressed data
131              * segment is legal in arithmetic coding.
132              * The convention is to supply zero data
133              * then until decoding is complete.
134              */
135             cinfo->unread_marker = data;
136             data = 0;
137           }
138         }
139       }
140       e->c = (e->c << 8) | data; /* insert data into C register */
141       if ((e->ct += 8) < 0)      /* update bit shift counter */
142         /* Need more initial bytes */
143         if (++e->ct == 0)
144           /* Got 2 initial bytes -> re-init A and exit loop */
145           e->a = 0x8000L; /* => e->a = 0x10000L after loop exit */
146     }
147     e->a <<= 1;
148   }
149 
150   /* Fetch values from our compact representation of Table D.2:
151    * Qe values and probability estimation state machine
152    */
153   sv = *st;
154   qe = jpeg_aritab[sv & 0x7F];  /* => Qe_Value */
155   nl = qe & 0xFF; qe >>= 8;     /* Next_Index_LPS + Switch_MPS */
156   nm = qe & 0xFF; qe >>= 8;     /* Next_Index_MPS */
157 
158   /* Decode & estimation procedures per sections D.2.4 & D.2.5 */
159   temp = e->a - qe;
160   e->a = temp;
161   temp <<= e->ct;
162   if (e->c >= temp) {
163     e->c -= temp;
164     /* Conditional LPS (less probable symbol) exchange */
165     if (e->a < qe) {
166       e->a = qe;
167       *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
168     } else {
169       e->a = qe;
170       *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
171       sv ^= 0x80;               /* Exchange LPS/MPS */
172     }
173   } else if (e->a < 0x8000L) {
174     /* Conditional MPS (more probable symbol) exchange */
175     if (e->a < qe) {
176       *st = (sv & 0x80) ^ nl;   /* Estimate_after_LPS */
177       sv ^= 0x80;               /* Exchange LPS/MPS */
178     } else {
179       *st = (sv & 0x80) ^ nm;   /* Estimate_after_MPS */
180     }
181   }
182 
183   return sv >> 7;
184 }
185 
186 
187 /*
188  * Check for a restart marker & resynchronize decoder.
189  */
190 
191 LOCAL(void)
process_restart(j_decompress_ptr cinfo)192 process_restart (j_decompress_ptr cinfo)
193 {
194   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
195   int ci;
196   jpeg_component_info * compptr;
197 
198   /* Advance past the RSTn marker */
199   if (! (*cinfo->marker->read_restart_marker) (cinfo))
200     ERREXIT(cinfo, JERR_CANT_SUSPEND);
201 
202   /* Re-initialize statistics areas */
203   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
204     compptr = cinfo->cur_comp_info[ci];
205     if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
206       MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);
207       /* Reset DC predictions to 0 */
208       entropy->last_dc_val[ci] = 0;
209       entropy->dc_context[ci] = 0;
210     }
211     if (! cinfo->progressive_mode || cinfo->Ss) {
212       MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
213     }
214   }
215 
216   /* Reset arithmetic decoding variables */
217   entropy->c = 0;
218   entropy->a = 0;
219   entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
220 
221   /* Reset restart counter */
222   entropy->restarts_to_go = cinfo->restart_interval;
223 }
224 
225 
226 /*
227  * Arithmetic MCU decoding.
228  * Each of these routines decodes and returns one MCU's worth of
229  * arithmetic-compressed coefficients.
230  * The coefficients are reordered from zigzag order into natural array order,
231  * but are not dequantized.
232  *
233  * The i'th block of the MCU is stored into the block pointed to by
234  * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
235  */
236 
237 /*
238  * MCU decoding for DC initial scan (either spectral selection,
239  * or first pass of successive approximation).
240  */
241 
242 METHODDEF(boolean)
decode_mcu_DC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)243 decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
244 {
245   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
246   JBLOCKROW block;
247   unsigned char *st;
248   int blkn, ci, tbl, sign;
249   int v, m;
250 
251   /* Process restart marker if needed */
252   if (cinfo->restart_interval) {
253     if (entropy->restarts_to_go == 0)
254       process_restart(cinfo);
255     entropy->restarts_to_go--;
256   }
257 
258   if (entropy->ct == -1) return TRUE;   /* if error do nothing */
259 
260   /* Outer loop handles each block in the MCU */
261 
262   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
263     block = MCU_data[blkn];
264     ci = cinfo->MCU_membership[blkn];
265     tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
266 
267     /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
268 
269     /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
270     st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
271 
272     /* Figure F.19: Decode_DC_DIFF */
273     if (arith_decode(cinfo, st) == 0)
274       entropy->dc_context[ci] = 0;
275     else {
276       /* Figure F.21: Decoding nonzero value v */
277       /* Figure F.22: Decoding the sign of v */
278       sign = arith_decode(cinfo, st + 1);
279       st += 2; st += sign;
280       /* Figure F.23: Decoding the magnitude category of v */
281       if ((m = arith_decode(cinfo, st)) != 0) {
282         st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
283         while (arith_decode(cinfo, st)) {
284           if ((m <<= 1) == 0x8000) {
285             WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
286             entropy->ct = -1;                   /* magnitude overflow */
287             return TRUE;
288           }
289           st += 1;
290         }
291       }
292       /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
293       if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
294         entropy->dc_context[ci] = 0;               /* zero diff category */
295       else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
296         entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
297       else
298         entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
299       v = m;
300       /* Figure F.24: Decoding the magnitude bit pattern of v */
301       st += 14;
302       while (m >>= 1)
303         if (arith_decode(cinfo, st)) v |= m;
304       v += 1; if (sign) v = -v;
305       entropy->last_dc_val[ci] += v;
306     }
307 
308     /* Scale and output the DC coefficient (assumes jpeg_natural_order[0]=0) */
309     (*block)[0] = (JCOEF) LEFT_SHIFT(entropy->last_dc_val[ci], cinfo->Al);
310   }
311 
312   return TRUE;
313 }
314 
315 
316 /*
317  * MCU decoding for AC initial scan (either spectral selection,
318  * or first pass of successive approximation).
319  */
320 
321 METHODDEF(boolean)
decode_mcu_AC_first(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)322 decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
323 {
324   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
325   JBLOCKROW block;
326   unsigned char *st;
327   int tbl, sign, k;
328   int v, m;
329 
330   /* Process restart marker if needed */
331   if (cinfo->restart_interval) {
332     if (entropy->restarts_to_go == 0)
333       process_restart(cinfo);
334     entropy->restarts_to_go--;
335   }
336 
337   if (entropy->ct == -1) return TRUE;   /* if error do nothing */
338 
339   /* There is always only one block per MCU */
340   block = MCU_data[0];
341   tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
342 
343   /* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
344 
345   /* Figure F.20: Decode_AC_coefficients */
346   for (k = cinfo->Ss; k <= cinfo->Se; k++) {
347     st = entropy->ac_stats[tbl] + 3 * (k - 1);
348     if (arith_decode(cinfo, st)) break;         /* EOB flag */
349     while (arith_decode(cinfo, st + 1) == 0) {
350       st += 3; k++;
351       if (k > cinfo->Se) {
352         WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
353         entropy->ct = -1;                       /* spectral overflow */
354         return TRUE;
355       }
356     }
357     /* Figure F.21: Decoding nonzero value v */
358     /* Figure F.22: Decoding the sign of v */
359     sign = arith_decode(cinfo, entropy->fixed_bin);
360     st += 2;
361     /* Figure F.23: Decoding the magnitude category of v */
362     if ((m = arith_decode(cinfo, st)) != 0) {
363       if (arith_decode(cinfo, st)) {
364         m <<= 1;
365         st = entropy->ac_stats[tbl] +
366              (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
367         while (arith_decode(cinfo, st)) {
368           if ((m <<= 1) == 0x8000) {
369             WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
370             entropy->ct = -1;                   /* magnitude overflow */
371             return TRUE;
372           }
373           st += 1;
374         }
375       }
376     }
377     v = m;
378     /* Figure F.24: Decoding the magnitude bit pattern of v */
379     st += 14;
380     while (m >>= 1)
381       if (arith_decode(cinfo, st)) v |= m;
382     v += 1; if (sign) v = -v;
383     /* Scale and output coefficient in natural (dezigzagged) order */
384     (*block)[jpeg_natural_order[k]] = (JCOEF) (v << cinfo->Al);
385   }
386 
387   return TRUE;
388 }
389 
390 
391 /*
392  * MCU decoding for DC successive approximation refinement scan.
393  */
394 
395 METHODDEF(boolean)
decode_mcu_DC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)396 decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
397 {
398   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
399   unsigned char *st;
400   int p1, blkn;
401 
402   /* Process restart marker if needed */
403   if (cinfo->restart_interval) {
404     if (entropy->restarts_to_go == 0)
405       process_restart(cinfo);
406     entropy->restarts_to_go--;
407   }
408 
409   st = entropy->fixed_bin;      /* use fixed probability estimation */
410   p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
411 
412   /* Outer loop handles each block in the MCU */
413 
414   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
415     /* Encoded data is simply the next bit of the two's-complement DC value */
416     if (arith_decode(cinfo, st))
417       MCU_data[blkn][0][0] |= p1;
418   }
419 
420   return TRUE;
421 }
422 
423 
424 /*
425  * MCU decoding for AC successive approximation refinement scan.
426  */
427 
428 METHODDEF(boolean)
decode_mcu_AC_refine(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)429 decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
430 {
431   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
432   JBLOCKROW block;
433   JCOEFPTR thiscoef;
434   unsigned char *st;
435   int tbl, k, kex;
436   int p1, m1;
437 
438   /* Process restart marker if needed */
439   if (cinfo->restart_interval) {
440     if (entropy->restarts_to_go == 0)
441       process_restart(cinfo);
442     entropy->restarts_to_go--;
443   }
444 
445   if (entropy->ct == -1) return TRUE;   /* if error do nothing */
446 
447   /* There is always only one block per MCU */
448   block = MCU_data[0];
449   tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
450 
451   p1 = 1 << cinfo->Al;          /* 1 in the bit position being coded */
452   m1 = (-1) << cinfo->Al;       /* -1 in the bit position being coded */
453 
454   /* Establish EOBx (previous stage end-of-block) index */
455   for (kex = cinfo->Se; kex > 0; kex--)
456     if ((*block)[jpeg_natural_order[kex]]) break;
457 
458   for (k = cinfo->Ss; k <= cinfo->Se; k++) {
459     st = entropy->ac_stats[tbl] + 3 * (k - 1);
460     if (k > kex)
461       if (arith_decode(cinfo, st)) break;       /* EOB flag */
462     for (;;) {
463       thiscoef = *block + jpeg_natural_order[k];
464       if (*thiscoef) {                          /* previously nonzero coef */
465         if (arith_decode(cinfo, st + 2)) {
466           if (*thiscoef < 0)
467             *thiscoef += m1;
468           else
469             *thiscoef += p1;
470         }
471         break;
472       }
473       if (arith_decode(cinfo, st + 1)) {        /* newly nonzero coef */
474         if (arith_decode(cinfo, entropy->fixed_bin))
475           *thiscoef = m1;
476         else
477           *thiscoef = p1;
478         break;
479       }
480       st += 3; k++;
481       if (k > cinfo->Se) {
482         WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
483         entropy->ct = -1;                       /* spectral overflow */
484         return TRUE;
485       }
486     }
487   }
488 
489   return TRUE;
490 }
491 
492 
493 /*
494  * Decode one MCU's worth of arithmetic-compressed coefficients.
495  */
496 
497 METHODDEF(boolean)
decode_mcu(j_decompress_ptr cinfo,JBLOCKROW * MCU_data)498 decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
499 {
500   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
501   jpeg_component_info * compptr;
502   JBLOCKROW block;
503   unsigned char *st;
504   int blkn, ci, tbl, sign, k;
505   int v, m;
506 
507   /* Process restart marker if needed */
508   if (cinfo->restart_interval) {
509     if (entropy->restarts_to_go == 0)
510       process_restart(cinfo);
511     entropy->restarts_to_go--;
512   }
513 
514   if (entropy->ct == -1) return TRUE;   /* if error do nothing */
515 
516   /* Outer loop handles each block in the MCU */
517 
518   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
519     block = MCU_data ? MCU_data[blkn] : NULL;
520     ci = cinfo->MCU_membership[blkn];
521     compptr = cinfo->cur_comp_info[ci];
522 
523     /* Sections F.2.4.1 & F.1.4.4.1: Decoding of DC coefficients */
524 
525     tbl = compptr->dc_tbl_no;
526 
527     /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
528     st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
529 
530     /* Figure F.19: Decode_DC_DIFF */
531     if (arith_decode(cinfo, st) == 0)
532       entropy->dc_context[ci] = 0;
533     else {
534       /* Figure F.21: Decoding nonzero value v */
535       /* Figure F.22: Decoding the sign of v */
536       sign = arith_decode(cinfo, st + 1);
537       st += 2; st += sign;
538       /* Figure F.23: Decoding the magnitude category of v */
539       if ((m = arith_decode(cinfo, st)) != 0) {
540         st = entropy->dc_stats[tbl] + 20;       /* Table F.4: X1 = 20 */
541         while (arith_decode(cinfo, st)) {
542           if ((m <<= 1) == 0x8000) {
543             WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
544             entropy->ct = -1;                   /* magnitude overflow */
545             return TRUE;
546           }
547           st += 1;
548         }
549       }
550       /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
551       if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
552         entropy->dc_context[ci] = 0;               /* zero diff category */
553       else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
554         entropy->dc_context[ci] = 12 + (sign * 4); /* large diff category */
555       else
556         entropy->dc_context[ci] = 4 + (sign * 4);  /* small diff category */
557       v = m;
558       /* Figure F.24: Decoding the magnitude bit pattern of v */
559       st += 14;
560       while (m >>= 1)
561         if (arith_decode(cinfo, st)) v |= m;
562       v += 1; if (sign) v = -v;
563       entropy->last_dc_val[ci] += v;
564     }
565 
566     if (block)
567       (*block)[0] = (JCOEF) entropy->last_dc_val[ci];
568 
569     /* Sections F.2.4.2 & F.1.4.4.2: Decoding of AC coefficients */
570 
571     tbl = compptr->ac_tbl_no;
572 
573     /* Figure F.20: Decode_AC_coefficients */
574     for (k = 1; k <= DCTSIZE2 - 1; k++) {
575       st = entropy->ac_stats[tbl] + 3 * (k - 1);
576       if (arith_decode(cinfo, st)) break;       /* EOB flag */
577       while (arith_decode(cinfo, st + 1) == 0) {
578         st += 3; k++;
579         if (k > DCTSIZE2 - 1) {
580           WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
581           entropy->ct = -1;                     /* spectral overflow */
582           return TRUE;
583         }
584       }
585       /* Figure F.21: Decoding nonzero value v */
586       /* Figure F.22: Decoding the sign of v */
587       sign = arith_decode(cinfo, entropy->fixed_bin);
588       st += 2;
589       /* Figure F.23: Decoding the magnitude category of v */
590       if ((m = arith_decode(cinfo, st)) != 0) {
591         if (arith_decode(cinfo, st)) {
592           m <<= 1;
593           st = entropy->ac_stats[tbl] +
594                (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
595           while (arith_decode(cinfo, st)) {
596             if ((m <<= 1) == 0x8000) {
597               WARNMS(cinfo, JWRN_ARITH_BAD_CODE);
598               entropy->ct = -1;                 /* magnitude overflow */
599               return TRUE;
600             }
601             st += 1;
602           }
603         }
604       }
605       v = m;
606       /* Figure F.24: Decoding the magnitude bit pattern of v */
607       st += 14;
608       while (m >>= 1)
609         if (arith_decode(cinfo, st)) v |= m;
610       v += 1; if (sign) v = -v;
611       if (block)
612         (*block)[jpeg_natural_order[k]] = (JCOEF) v;
613     }
614   }
615 
616   return TRUE;
617 }
618 
619 
620 /*
621  * Initialize for an arithmetic-compressed scan.
622  */
623 
624 METHODDEF(void)
start_pass(j_decompress_ptr cinfo)625 start_pass (j_decompress_ptr cinfo)
626 {
627   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
628   int ci, tbl;
629   jpeg_component_info * compptr;
630 
631   if (cinfo->progressive_mode) {
632     /* Validate progressive scan parameters */
633     if (cinfo->Ss == 0) {
634       if (cinfo->Se != 0)
635         goto bad;
636     } else {
637       /* need not check Ss/Se < 0 since they came from unsigned bytes */
638       if (cinfo->Se < cinfo->Ss || cinfo->Se > DCTSIZE2 - 1)
639         goto bad;
640       /* AC scans may have only one component */
641       if (cinfo->comps_in_scan != 1)
642         goto bad;
643     }
644     if (cinfo->Ah != 0) {
645       /* Successive approximation refinement scan: must have Al = Ah-1. */
646       if (cinfo->Ah-1 != cinfo->Al)
647         goto bad;
648     }
649     if (cinfo->Al > 13) {       /* need not check for < 0 */
650       bad:
651       ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
652                cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
653     }
654     /* Update progression status, and verify that scan order is legal.
655      * Note that inter-scan inconsistencies are treated as warnings
656      * not fatal errors ... not clear if this is right way to behave.
657      */
658     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
659       int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
660       int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
661       if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
662         WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
663       for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
664         int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
665         if (cinfo->Ah != expected)
666           WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
667         coef_bit_ptr[coefi] = cinfo->Al;
668       }
669     }
670     /* Select MCU decoding routine */
671     if (cinfo->Ah == 0) {
672       if (cinfo->Ss == 0)
673         entropy->pub.decode_mcu = decode_mcu_DC_first;
674       else
675         entropy->pub.decode_mcu = decode_mcu_AC_first;
676     } else {
677       if (cinfo->Ss == 0)
678         entropy->pub.decode_mcu = decode_mcu_DC_refine;
679       else
680         entropy->pub.decode_mcu = decode_mcu_AC_refine;
681     }
682   } else {
683     /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
684      * This ought to be an error condition, but we make it a warning.
685      */
686     if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
687         (cinfo->Se < DCTSIZE2 && cinfo->Se != DCTSIZE2 - 1))
688       WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
689     /* Select MCU decoding routine */
690     entropy->pub.decode_mcu = decode_mcu;
691   }
692 
693   /* Allocate & initialize requested statistics areas */
694   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
695     compptr = cinfo->cur_comp_info[ci];
696     if (! cinfo->progressive_mode || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
697       tbl = compptr->dc_tbl_no;
698       if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
699         ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
700       if (entropy->dc_stats[tbl] == NULL)
701         entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
702           ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
703       MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
704       /* Initialize DC predictions to 0 */
705       entropy->last_dc_val[ci] = 0;
706       entropy->dc_context[ci] = 0;
707     }
708     if (! cinfo->progressive_mode || cinfo->Ss) {
709       tbl = compptr->ac_tbl_no;
710       if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
711         ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
712       if (entropy->ac_stats[tbl] == NULL)
713         entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
714           ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
715       MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
716     }
717   }
718 
719   /* Initialize arithmetic decoding variables */
720   entropy->c = 0;
721   entropy->a = 0;
722   entropy->ct = -16;    /* force reading 2 initial bytes to fill C */
723 
724   /* Initialize restart counter */
725   entropy->restarts_to_go = cinfo->restart_interval;
726 }
727 
728 
729 /*
730  * Module initialization routine for arithmetic entropy decoding.
731  */
732 
733 GLOBAL(void)
jinit_arith_decoder(j_decompress_ptr cinfo)734 jinit_arith_decoder (j_decompress_ptr cinfo)
735 {
736   arith_entropy_ptr entropy;
737   int i;
738 
739   entropy = (arith_entropy_ptr)
740     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
741                                 sizeof(arith_entropy_decoder));
742   cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
743   entropy->pub.start_pass = start_pass;
744 
745   /* Mark tables unallocated */
746   for (i = 0; i < NUM_ARITH_TBLS; i++) {
747     entropy->dc_stats[i] = NULL;
748     entropy->ac_stats[i] = NULL;
749   }
750 
751   /* Initialize index for fixed probability estimation */
752   entropy->fixed_bin[0] = 113;
753 
754   if (cinfo->progressive_mode) {
755     /* Create progression status table */
756     int *coef_bit_ptr, ci;
757     cinfo->coef_bits = (int (*)[DCTSIZE2])
758       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
759                                   cinfo->num_components*DCTSIZE2*sizeof(int));
760     coef_bit_ptr = & cinfo->coef_bits[0][0];
761     for (ci = 0; ci < cinfo->num_components; ci++)
762       for (i = 0; i < DCTSIZE2; i++)
763         *coef_bit_ptr++ = -1;
764   }
765 }
766