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