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