jcarith.c

Go to the documentation of this file.
00001 /*
00002  * jcarith.c
00003  *
00004  * Developed 1997-2009 by Guido Vollbeding.
00005  * This file is part of the Independent JPEG Group's software.
00006  * For conditions of distribution and use, see the accompanying README file.
00007  *
00008  * This file contains portable arithmetic entropy encoding routines for JPEG
00009  * (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
00010  *
00011  * Both sequential and progressive modes are supported in this single module.
00012  *
00013  * Suspension is not currently supported in this module.
00014  */
00015 
00016 #define JPEG_INTERNALS
00017 #include "jinclude.h"
00018 #include "jpeglib.h"
00019 
00020 
00021 /* Expanded entropy encoder object for arithmetic encoding. */
00022 
00023 typedef struct {
00024   struct jpeg_entropy_encoder pub; /* public fields */
00025 
00026   INT32 c; /* C register, base of coding interval, layout as in sec. D.1.3 */
00027   INT32 a;               /* A register, normalized size of coding interval */
00028   INT32 sc;        /* counter for stacked 0xFF values which might overflow */
00029   INT32 zc;          /* counter for pending 0x00 output values which might *
00030                           * be discarded at the end ("Pacman" termination) */
00031   int ct;  /* bit shift counter, determines when next byte will be written */
00032   int buffer;                /* buffer for most recent output byte != 0xFF */
00033 
00034   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
00035   int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
00036 
00037   unsigned int restarts_to_go;  /* MCUs left in this restart interval */
00038   int next_restart_num;         /* next restart number to write (0-7) */
00039 
00040   /* Pointers to statistics areas (these workspaces have image lifespan) */
00041   unsigned char * dc_stats[NUM_ARITH_TBLS];
00042   unsigned char * ac_stats[NUM_ARITH_TBLS];
00043 
00044   /* Statistics bin for coding with fixed probability 0.5 */
00045   unsigned char fixed_bin[4];
00046 } arith_entropy_encoder;
00047 
00048 typedef arith_entropy_encoder * arith_entropy_ptr;
00049 
00050 /* The following two definitions specify the allocation chunk size
00051  * for the statistics area.
00052  * According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
00053  * 49 statistics bins for DC, and 245 statistics bins for AC coding.
00054  *
00055  * We use a compact representation with 1 byte per statistics bin,
00056  * thus the numbers directly represent byte sizes.
00057  * This 1 byte per statistics bin contains the meaning of the MPS
00058  * (more probable symbol) in the highest bit (mask 0x80), and the
00059  * index into the probability estimation state machine table
00060  * in the lower bits (mask 0x7F).
00061  */
00062 
00063 #define DC_STAT_BINS 64
00064 #define AC_STAT_BINS 256
00065 
00066 /* NOTE: Uncomment the following #define if you want to use the
00067  * given formula for calculating the AC conditioning parameter Kx
00068  * for spectral selection progressive coding in section G.1.3.2
00069  * of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4).
00070  * Although the spec and P&M authors claim that this "has proven
00071  * to give good results for 8 bit precision samples", I'm not
00072  * convinced yet that this is really beneficial.
00073  * Early tests gave only very marginal compression enhancements
00074  * (a few - around 5 or so - bytes even for very large files),
00075  * which would turn out rather negative if we'd suppress the
00076  * DAC (Define Arithmetic Conditioning) marker segments for
00077  * the default parameters in the future.
00078  * Note that currently the marker writing module emits 12-byte
00079  * DAC segments for a full-component scan in a color image.
00080  * This is not worth worrying about IMHO. However, since the
00081  * spec defines the default values to be used if the tables
00082  * are omitted (unlike Huffman tables, which are required
00083  * anyway), one might optimize this behaviour in the future,
00084  * and then it would be disadvantageous to use custom tables if
00085  * they don't provide sufficient gain to exceed the DAC size.
00086  *
00087  * On the other hand, I'd consider it as a reasonable result
00088  * that the conditioning has no significant influence on the
00089  * compression performance. This means that the basic
00090  * statistical model is already rather stable.
00091  *
00092  * Thus, at the moment, we use the default conditioning values
00093  * anyway, and do not use the custom formula.
00094  *
00095 #define CALCULATE_SPECTRAL_CONDITIONING
00096  */
00097 
00098 /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
00099  * We assume that int right shift is unsigned if INT32 right shift is,
00100  * which should be safe.
00101  */
00102 
00103 #ifdef RIGHT_SHIFT_IS_UNSIGNED
00104 #define ISHIFT_TEMPS    int ishift_temp;
00105 #define IRIGHT_SHIFT(x,shft)  \
00106         ((ishift_temp = (x)) < 0 ? \
00107          (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
00108          (ishift_temp >> (shft)))
00109 #else
00110 #define ISHIFT_TEMPS
00111 #define IRIGHT_SHIFT(x,shft)    ((x) >> (shft))
00112 #endif
00113 
00114 
00115 LOCAL(void)
00116 emit_byte (int val, j_compress_ptr cinfo)
00117 /* Write next output byte; we do not support suspension in this module. */
00118 {
00119   struct jpeg_destination_mgr * dest = cinfo->dest;
00120 
00121   *dest->next_output_byte++ = (JOCTET) val;
00122   if (--dest->free_in_buffer == 0)
00123     if (! (*dest->empty_output_buffer) (cinfo))
00124       ERREXIT(cinfo, JERR_CANT_SUSPEND);
00125 }
00126 
00127 
00128 /*
00129  * Finish up at the end of an arithmetic-compressed scan.
00130  */
00131 
00132 METHODDEF(void)
00133 finish_pass (j_compress_ptr cinfo)
00134 {
00135   arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
00136   INT32 temp;
00137 
00138   /* Section D.1.8: Termination of encoding */
00139 
00140   /* Find the e->c in the coding interval with the largest
00141    * number of trailing zero bits */
00142   if ((temp = (e->a - 1 + e->c) & 0xFFFF0000L) < e->c)
00143     e->c = temp + 0x8000L;
00144   else
00145     e->c = temp;
00146   /* Send remaining bytes to output */
00147   e->c <<= e->ct;
00148   if (e->c & 0xF8000000L) {
00149     /* One final overflow has to be handled */
00150     if (e->buffer >= 0) {
00151       if (e->zc)
00152         do emit_byte(0x00, cinfo);
00153         while (--e->zc);
00154       emit_byte(e->buffer + 1, cinfo);
00155       if (e->buffer + 1 == 0xFF)
00156         emit_byte(0x00, cinfo);
00157     }
00158     e->zc += e->sc;  /* carry-over converts stacked 0xFF bytes to 0x00 */
00159     e->sc = 0;
00160   } else {
00161     if (e->buffer == 0)
00162       ++e->zc;
00163     else if (e->buffer >= 0) {
00164       if (e->zc)
00165         do emit_byte(0x00, cinfo);
00166         while (--e->zc);
00167       emit_byte(e->buffer, cinfo);
00168     }
00169     if (e->sc) {
00170       if (e->zc)
00171         do emit_byte(0x00, cinfo);
00172         while (--e->zc);
00173       do {
00174         emit_byte(0xFF, cinfo);
00175         emit_byte(0x00, cinfo);
00176       } while (--e->sc);
00177     }
00178   }
00179   /* Output final bytes only if they are not 0x00 */
00180   if (e->c & 0x7FFF800L) {
00181     if (e->zc)  /* output final pending zero bytes */
00182       do emit_byte(0x00, cinfo);
00183       while (--e->zc);
00184     emit_byte((e->c >> 19) & 0xFF, cinfo);
00185     if (((e->c >> 19) & 0xFF) == 0xFF)
00186       emit_byte(0x00, cinfo);
00187     if (e->c & 0x7F800L) {
00188       emit_byte((e->c >> 11) & 0xFF, cinfo);
00189       if (((e->c >> 11) & 0xFF) == 0xFF)
00190         emit_byte(0x00, cinfo);
00191     }
00192   }
00193 }
00194 
00195 
00196 /*
00197  * The core arithmetic encoding routine (common in JPEG and JBIG).
00198  * This needs to go as fast as possible.
00199  * Machine-dependent optimization facilities
00200  * are not utilized in this portable implementation.
00201  * However, this code should be fairly efficient and
00202  * may be a good base for further optimizations anyway.
00203  *
00204  * Parameter 'val' to be encoded may be 0 or 1 (binary decision).
00205  *
00206  * Note: I've added full "Pacman" termination support to the
00207  * byte output routines, which is equivalent to the optional
00208  * Discard_final_zeros procedure (Figure D.15) in the spec.
00209  * Thus, we always produce the shortest possible output
00210  * stream compliant to the spec (no trailing zero bytes,
00211  * except for FF stuffing).
00212  *
00213  * I've also introduced a new scheme for accessing
00214  * the probability estimation state machine table,
00215  * derived from Markus Kuhn's JBIG implementation.
00216  */
00217 
00218 LOCAL(void)
00219 arith_encode (j_compress_ptr cinfo, unsigned char *st, int val) 
00220 {
00221   register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
00222   register unsigned char nl, nm;
00223   register INT32 qe, temp;
00224   register int sv;
00225 
00226   /* Fetch values from our compact representation of Table D.2:
00227    * Qe values and probability estimation state machine
00228    */
00229   sv = *st;
00230   qe = jpeg_aritab[sv & 0x7F];  /* => Qe_Value */
00231   nl = qe & 0xFF; qe >>= 8;     /* Next_Index_LPS + Switch_MPS */
00232   nm = qe & 0xFF; qe >>= 8;     /* Next_Index_MPS */
00233 
00234   /* Encode & estimation procedures per sections D.1.4 & D.1.5 */
00235   e->a -= qe;
00236   if (val != (sv >> 7)) {
00237     /* Encode the less probable symbol */
00238     if (e->a >= qe) {
00239       /* If the interval size (qe) for the less probable symbol (LPS)
00240        * is larger than the interval size for the MPS, then exchange
00241        * the two symbols for coding efficiency, otherwise code the LPS
00242        * as usual: */
00243       e->c += e->a;
00244       e->a = qe;
00245     }
00246     *st = (sv & 0x80) ^ nl;     /* Estimate_after_LPS */
00247   } else {
00248     /* Encode the more probable symbol */
00249     if (e->a >= 0x8000L)
00250       return;  /* A >= 0x8000 -> ready, no renormalization required */
00251     if (e->a < qe) {
00252       /* If the interval size (qe) for the less probable symbol (LPS)
00253        * is larger than the interval size for the MPS, then exchange
00254        * the two symbols for coding efficiency: */
00255       e->c += e->a;
00256       e->a = qe;
00257     }
00258     *st = (sv & 0x80) ^ nm;     /* Estimate_after_MPS */
00259   }
00260 
00261   /* Renormalization & data output per section D.1.6 */
00262   do {
00263     e->a <<= 1;
00264     e->c <<= 1;
00265     if (--e->ct == 0) {
00266       /* Another byte is ready for output */
00267       temp = e->c >> 19;
00268       if (temp > 0xFF) {
00269         /* Handle overflow over all stacked 0xFF bytes */
00270         if (e->buffer >= 0) {
00271           if (e->zc)
00272             do emit_byte(0x00, cinfo);
00273             while (--e->zc);
00274           emit_byte(e->buffer + 1, cinfo);
00275           if (e->buffer + 1 == 0xFF)
00276             emit_byte(0x00, cinfo);
00277         }
00278         e->zc += e->sc;  /* carry-over converts stacked 0xFF bytes to 0x00 */
00279         e->sc = 0;
00280         /* Note: The 3 spacer bits in the C register guarantee
00281          * that the new buffer byte can't be 0xFF here
00282          * (see page 160 in the P&M JPEG book). */
00283         e->buffer = temp & 0xFF;  /* new output byte, might overflow later */
00284       } else if (temp == 0xFF) {
00285         ++e->sc;  /* stack 0xFF byte (which might overflow later) */
00286       } else {
00287         /* Output all stacked 0xFF bytes, they will not overflow any more */
00288         if (e->buffer == 0)
00289           ++e->zc;
00290         else if (e->buffer >= 0) {
00291           if (e->zc)
00292             do emit_byte(0x00, cinfo);
00293             while (--e->zc);
00294           emit_byte(e->buffer, cinfo);
00295         }
00296         if (e->sc) {
00297           if (e->zc)
00298             do emit_byte(0x00, cinfo);
00299             while (--e->zc);
00300           do {
00301             emit_byte(0xFF, cinfo);
00302             emit_byte(0x00, cinfo);
00303           } while (--e->sc);
00304         }
00305         e->buffer = temp & 0xFF;  /* new output byte (can still overflow) */
00306       }
00307       e->c &= 0x7FFFFL;
00308       e->ct += 8;
00309     }
00310   } while (e->a < 0x8000L);
00311 }
00312 
00313 
00314 /*
00315  * Emit a restart marker & resynchronize predictions.
00316  */
00317 
00318 LOCAL(void)
00319 emit_restart (j_compress_ptr cinfo, int restart_num)
00320 {
00321   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00322   int ci;
00323   jpeg_component_info * compptr;
00324 
00325   finish_pass(cinfo);
00326 
00327   emit_byte(0xFF, cinfo);
00328   emit_byte(JPEG_RST0 + restart_num, cinfo);
00329 
00330   /* Re-initialize statistics areas */
00331   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
00332     compptr = cinfo->cur_comp_info[ci];
00333     /* DC needs no table for refinement scan */
00334     if (cinfo->Ss == 0 && cinfo->Ah == 0) {
00335       MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);
00336       /* Reset DC predictions to 0 */
00337       entropy->last_dc_val[ci] = 0;
00338       entropy->dc_context[ci] = 0;
00339     }
00340     /* AC needs no table when not present */
00341     if (cinfo->Se) {
00342       MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
00343     }
00344   }
00345 
00346   /* Reset arithmetic encoding variables */
00347   entropy->c = 0;
00348   entropy->a = 0x10000L;
00349   entropy->sc = 0;
00350   entropy->zc = 0;
00351   entropy->ct = 11;
00352   entropy->buffer = -1;  /* empty */
00353 }
00354 
00355 
00356 /*
00357  * MCU encoding for DC initial scan (either spectral selection,
00358  * or first pass of successive approximation).
00359  */
00360 
00361 METHODDEF(boolean)
00362 encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00363 {
00364   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00365   JBLOCKROW block;
00366   unsigned char *st;
00367   int blkn, ci, tbl;
00368   int v, v2, m;
00369   ISHIFT_TEMPS
00370 
00371   /* Emit restart marker if needed */
00372   if (cinfo->restart_interval) {
00373     if (entropy->restarts_to_go == 0) {
00374       emit_restart(cinfo, entropy->next_restart_num);
00375       entropy->restarts_to_go = cinfo->restart_interval;
00376       entropy->next_restart_num++;
00377       entropy->next_restart_num &= 7;
00378     }
00379     entropy->restarts_to_go--;
00380   }
00381 
00382   /* Encode the MCU data blocks */
00383   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
00384     block = MCU_data[blkn];
00385     ci = cinfo->MCU_membership[blkn];
00386     tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
00387 
00388     /* Compute the DC value after the required point transform by Al.
00389      * This is simply an arithmetic right shift.
00390      */
00391     m = IRIGHT_SHIFT((int) ((*block)[0]), cinfo->Al);
00392 
00393     /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
00394 
00395     /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
00396     st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
00397 
00398     /* Figure F.4: Encode_DC_DIFF */
00399     if ((v = m - entropy->last_dc_val[ci]) == 0) {
00400       arith_encode(cinfo, st, 0);
00401       entropy->dc_context[ci] = 0;      /* zero diff category */
00402     } else {
00403       entropy->last_dc_val[ci] = m;
00404       arith_encode(cinfo, st, 1);
00405       /* Figure F.6: Encoding nonzero value v */
00406       /* Figure F.7: Encoding the sign of v */
00407       if (v > 0) {
00408         arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
00409         st += 2;                        /* Table F.4: SP = S0 + 2 */
00410         entropy->dc_context[ci] = 4;    /* small positive diff category */
00411       } else {
00412         v = -v;
00413         arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
00414         st += 3;                        /* Table F.4: SN = S0 + 3 */
00415         entropy->dc_context[ci] = 8;    /* small negative diff category */
00416       }
00417       /* Figure F.8: Encoding the magnitude category of v */
00418       m = 0;
00419       if (v -= 1) {
00420         arith_encode(cinfo, st, 1);
00421         m = 1;
00422         v2 = v;
00423         st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
00424         while (v2 >>= 1) {
00425           arith_encode(cinfo, st, 1);
00426           m <<= 1;
00427           st += 1;
00428         }
00429       }
00430       arith_encode(cinfo, st, 0);
00431       /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
00432       if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
00433         entropy->dc_context[ci] = 0;    /* zero diff category */
00434       else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
00435         entropy->dc_context[ci] += 8;   /* large diff category */
00436       /* Figure F.9: Encoding the magnitude bit pattern of v */
00437       st += 14;
00438       while (m >>= 1)
00439         arith_encode(cinfo, st, (m & v) ? 1 : 0);
00440     }
00441   }
00442 
00443   return TRUE;
00444 }
00445 
00446 
00447 /*
00448  * MCU encoding for AC initial scan (either spectral selection,
00449  * or first pass of successive approximation).
00450  */
00451 
00452 METHODDEF(boolean)
00453 encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00454 {
00455   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00456   JBLOCKROW block;
00457   unsigned char *st;
00458   int tbl, k, ke;
00459   int v, v2, m;
00460   const int * natural_order;
00461 
00462   /* Emit restart marker if needed */
00463   if (cinfo->restart_interval) {
00464     if (entropy->restarts_to_go == 0) {
00465       emit_restart(cinfo, entropy->next_restart_num);
00466       entropy->restarts_to_go = cinfo->restart_interval;
00467       entropy->next_restart_num++;
00468       entropy->next_restart_num &= 7;
00469     }
00470     entropy->restarts_to_go--;
00471   }
00472 
00473   natural_order = cinfo->natural_order;
00474 
00475   /* Encode the MCU data block */
00476   block = MCU_data[0];
00477   tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
00478 
00479   /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
00480 
00481   /* Establish EOB (end-of-block) index */
00482   for (ke = cinfo->Se; ke > 0; ke--)
00483     /* We must apply the point transform by Al.  For AC coefficients this
00484      * is an integer division with rounding towards 0.  To do this portably
00485      * in C, we shift after obtaining the absolute value.
00486      */
00487     if ((v = (*block)[natural_order[ke]]) >= 0) {
00488       if (v >>= cinfo->Al) break;
00489     } else {
00490       v = -v;
00491       if (v >>= cinfo->Al) break;
00492     }
00493 
00494   /* Figure F.5: Encode_AC_Coefficients */
00495   for (k = cinfo->Ss; k <= ke; k++) {
00496     st = entropy->ac_stats[tbl] + 3 * (k - 1);
00497     arith_encode(cinfo, st, 0);         /* EOB decision */
00498     for (;;) {
00499       if ((v = (*block)[natural_order[k]]) >= 0) {
00500         if (v >>= cinfo->Al) {
00501           arith_encode(cinfo, st + 1, 1);
00502           arith_encode(cinfo, entropy->fixed_bin, 0);
00503           break;
00504         }
00505       } else {
00506         v = -v;
00507         if (v >>= cinfo->Al) {
00508           arith_encode(cinfo, st + 1, 1);
00509           arith_encode(cinfo, entropy->fixed_bin, 1);
00510           break;
00511         }
00512       }
00513       arith_encode(cinfo, st + 1, 0); st += 3; k++;
00514     }
00515     st += 2;
00516     /* Figure F.8: Encoding the magnitude category of v */
00517     m = 0;
00518     if (v -= 1) {
00519       arith_encode(cinfo, st, 1);
00520       m = 1;
00521       v2 = v;
00522       if (v2 >>= 1) {
00523         arith_encode(cinfo, st, 1);
00524         m <<= 1;
00525         st = entropy->ac_stats[tbl] +
00526              (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
00527         while (v2 >>= 1) {
00528           arith_encode(cinfo, st, 1);
00529           m <<= 1;
00530           st += 1;
00531         }
00532       }
00533     }
00534     arith_encode(cinfo, st, 0);
00535     /* Figure F.9: Encoding the magnitude bit pattern of v */
00536     st += 14;
00537     while (m >>= 1)
00538       arith_encode(cinfo, st, (m & v) ? 1 : 0);
00539   }
00540   /* Encode EOB decision only if k <= cinfo->Se */
00541   if (k <= cinfo->Se) {
00542     st = entropy->ac_stats[tbl] + 3 * (k - 1);
00543     arith_encode(cinfo, st, 1);
00544   }
00545 
00546   return TRUE;
00547 }
00548 
00549 
00550 /*
00551  * MCU encoding for DC successive approximation refinement scan.
00552  */
00553 
00554 METHODDEF(boolean)
00555 encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00556 {
00557   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00558   unsigned char *st;
00559   int Al, blkn;
00560 
00561   /* Emit restart marker if needed */
00562   if (cinfo->restart_interval) {
00563     if (entropy->restarts_to_go == 0) {
00564       emit_restart(cinfo, entropy->next_restart_num);
00565       entropy->restarts_to_go = cinfo->restart_interval;
00566       entropy->next_restart_num++;
00567       entropy->next_restart_num &= 7;
00568     }
00569     entropy->restarts_to_go--;
00570   }
00571 
00572   st = entropy->fixed_bin;      /* use fixed probability estimation */
00573   Al = cinfo->Al;
00574 
00575   /* Encode the MCU data blocks */
00576   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
00577     /* We simply emit the Al'th bit of the DC coefficient value. */
00578     arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);
00579   }
00580 
00581   return TRUE;
00582 }
00583 
00584 
00585 /*
00586  * MCU encoding for AC successive approximation refinement scan.
00587  */
00588 
00589 METHODDEF(boolean)
00590 encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00591 {
00592   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00593   JBLOCKROW block;
00594   unsigned char *st;
00595   int tbl, k, ke, kex;
00596   int v;
00597   const int * natural_order;
00598 
00599   /* Emit restart marker if needed */
00600   if (cinfo->restart_interval) {
00601     if (entropy->restarts_to_go == 0) {
00602       emit_restart(cinfo, entropy->next_restart_num);
00603       entropy->restarts_to_go = cinfo->restart_interval;
00604       entropy->next_restart_num++;
00605       entropy->next_restart_num &= 7;
00606     }
00607     entropy->restarts_to_go--;
00608   }
00609 
00610   natural_order = cinfo->natural_order;
00611 
00612   /* Encode the MCU data block */
00613   block = MCU_data[0];
00614   tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
00615 
00616   /* Section G.1.3.3: Encoding of AC coefficients */
00617 
00618   /* Establish EOB (end-of-block) index */
00619   for (ke = cinfo->Se; ke > 0; ke--)
00620     /* We must apply the point transform by Al.  For AC coefficients this
00621      * is an integer division with rounding towards 0.  To do this portably
00622      * in C, we shift after obtaining the absolute value.
00623      */
00624     if ((v = (*block)[natural_order[ke]]) >= 0) {
00625       if (v >>= cinfo->Al) break;
00626     } else {
00627       v = -v;
00628       if (v >>= cinfo->Al) break;
00629     }
00630 
00631   /* Establish EOBx (previous stage end-of-block) index */
00632   for (kex = ke; kex > 0; kex--)
00633     if ((v = (*block)[natural_order[kex]]) >= 0) {
00634       if (v >>= cinfo->Ah) break;
00635     } else {
00636       v = -v;
00637       if (v >>= cinfo->Ah) break;
00638     }
00639 
00640   /* Figure G.10: Encode_AC_Coefficients_SA */
00641   for (k = cinfo->Ss; k <= ke; k++) {
00642     st = entropy->ac_stats[tbl] + 3 * (k - 1);
00643     if (k > kex)
00644       arith_encode(cinfo, st, 0);       /* EOB decision */
00645     for (;;) {
00646       if ((v = (*block)[natural_order[k]]) >= 0) {
00647         if (v >>= cinfo->Al) {
00648           if (v >> 1)                   /* previously nonzero coef */
00649             arith_encode(cinfo, st + 2, (v & 1));
00650           else {                        /* newly nonzero coef */
00651             arith_encode(cinfo, st + 1, 1);
00652             arith_encode(cinfo, entropy->fixed_bin, 0);
00653           }
00654           break;
00655         }
00656       } else {
00657         v = -v;
00658         if (v >>= cinfo->Al) {
00659           if (v >> 1)                   /* previously nonzero coef */
00660             arith_encode(cinfo, st + 2, (v & 1));
00661           else {                        /* newly nonzero coef */
00662             arith_encode(cinfo, st + 1, 1);
00663             arith_encode(cinfo, entropy->fixed_bin, 1);
00664           }
00665           break;
00666         }
00667       }
00668       arith_encode(cinfo, st + 1, 0); st += 3; k++;
00669     }
00670   }
00671   /* Encode EOB decision only if k <= cinfo->Se */
00672   if (k <= cinfo->Se) {
00673     st = entropy->ac_stats[tbl] + 3 * (k - 1);
00674     arith_encode(cinfo, st, 1);
00675   }
00676 
00677   return TRUE;
00678 }
00679 
00680 
00681 /*
00682  * Encode and output one MCU's worth of arithmetic-compressed coefficients.
00683  */
00684 
00685 METHODDEF(boolean)
00686 encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00687 {
00688   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00689   jpeg_component_info * compptr;
00690   JBLOCKROW block;
00691   unsigned char *st;
00692   int blkn, ci, tbl, k, ke;
00693   int v, v2, m;
00694   const int * natural_order;
00695 
00696   /* Emit restart marker if needed */
00697   if (cinfo->restart_interval) {
00698     if (entropy->restarts_to_go == 0) {
00699       emit_restart(cinfo, entropy->next_restart_num);
00700       entropy->restarts_to_go = cinfo->restart_interval;
00701       entropy->next_restart_num++;
00702       entropy->next_restart_num &= 7;
00703     }
00704     entropy->restarts_to_go--;
00705   }
00706 
00707   natural_order = cinfo->natural_order;
00708 
00709   /* Encode the MCU data blocks */
00710   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
00711     block = MCU_data[blkn];
00712     ci = cinfo->MCU_membership[blkn];
00713     compptr = cinfo->cur_comp_info[ci];
00714 
00715     /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
00716 
00717     tbl = compptr->dc_tbl_no;
00718 
00719     /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
00720     st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
00721 
00722     /* Figure F.4: Encode_DC_DIFF */
00723     if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {
00724       arith_encode(cinfo, st, 0);
00725       entropy->dc_context[ci] = 0;      /* zero diff category */
00726     } else {
00727       entropy->last_dc_val[ci] = (*block)[0];
00728       arith_encode(cinfo, st, 1);
00729       /* Figure F.6: Encoding nonzero value v */
00730       /* Figure F.7: Encoding the sign of v */
00731       if (v > 0) {
00732         arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
00733         st += 2;                        /* Table F.4: SP = S0 + 2 */
00734         entropy->dc_context[ci] = 4;    /* small positive diff category */
00735       } else {
00736         v = -v;
00737         arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
00738         st += 3;                        /* Table F.4: SN = S0 + 3 */
00739         entropy->dc_context[ci] = 8;    /* small negative diff category */
00740       }
00741       /* Figure F.8: Encoding the magnitude category of v */
00742       m = 0;
00743       if (v -= 1) {
00744         arith_encode(cinfo, st, 1);
00745         m = 1;
00746         v2 = v;
00747         st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
00748         while (v2 >>= 1) {
00749           arith_encode(cinfo, st, 1);
00750           m <<= 1;
00751           st += 1;
00752         }
00753       }
00754       arith_encode(cinfo, st, 0);
00755       /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
00756       if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
00757         entropy->dc_context[ci] = 0;    /* zero diff category */
00758       else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
00759         entropy->dc_context[ci] += 8;   /* large diff category */
00760       /* Figure F.9: Encoding the magnitude bit pattern of v */
00761       st += 14;
00762       while (m >>= 1)
00763         arith_encode(cinfo, st, (m & v) ? 1 : 0);
00764     }
00765 
00766     /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
00767 
00768     tbl = compptr->ac_tbl_no;
00769 
00770     /* Establish EOB (end-of-block) index */
00771     for (ke = cinfo->lim_Se; ke > 0; ke--)
00772       if ((*block)[natural_order[ke]]) break;
00773 
00774     /* Figure F.5: Encode_AC_Coefficients */
00775     for (k = 1; k <= ke; k++) {
00776       st = entropy->ac_stats[tbl] + 3 * (k - 1);
00777       arith_encode(cinfo, st, 0);       /* EOB decision */
00778       while ((v = (*block)[natural_order[k]]) == 0) {
00779         arith_encode(cinfo, st + 1, 0); st += 3; k++;
00780       }
00781       arith_encode(cinfo, st + 1, 1);
00782       /* Figure F.6: Encoding nonzero value v */
00783       /* Figure F.7: Encoding the sign of v */
00784       if (v > 0) {
00785         arith_encode(cinfo, entropy->fixed_bin, 0);
00786       } else {
00787         v = -v;
00788         arith_encode(cinfo, entropy->fixed_bin, 1);
00789       }
00790       st += 2;
00791       /* Figure F.8: Encoding the magnitude category of v */
00792       m = 0;
00793       if (v -= 1) {
00794         arith_encode(cinfo, st, 1);
00795         m = 1;
00796         v2 = v;
00797         if (v2 >>= 1) {
00798           arith_encode(cinfo, st, 1);
00799           m <<= 1;
00800           st = entropy->ac_stats[tbl] +
00801                (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
00802           while (v2 >>= 1) {
00803             arith_encode(cinfo, st, 1);
00804             m <<= 1;
00805             st += 1;
00806           }
00807         }
00808       }
00809       arith_encode(cinfo, st, 0);
00810       /* Figure F.9: Encoding the magnitude bit pattern of v */
00811       st += 14;
00812       while (m >>= 1)
00813         arith_encode(cinfo, st, (m & v) ? 1 : 0);
00814     }
00815     /* Encode EOB decision only if k <= cinfo->lim_Se */
00816     if (k <= cinfo->lim_Se) {
00817       st = entropy->ac_stats[tbl] + 3 * (k - 1);
00818       arith_encode(cinfo, st, 1);
00819     }
00820   }
00821 
00822   return TRUE;
00823 }
00824 
00825 
00826 /*
00827  * Initialize for an arithmetic-compressed scan.
00828  */
00829 
00830 METHODDEF(void)
00831 start_pass (j_compress_ptr cinfo, boolean gather_statistics)
00832 {
00833   arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
00834   int ci, tbl;
00835   jpeg_component_info * compptr;
00836 
00837   if (gather_statistics)
00838     /* Make sure to avoid that in the master control logic!
00839      * We are fully adaptive here and need no extra
00840      * statistics gathering pass!
00841      */
00842     ERREXIT(cinfo, JERR_NOT_COMPILED);
00843 
00844   /* We assume jcmaster.c already validated the progressive scan parameters. */
00845 
00846   /* Select execution routines */
00847   if (cinfo->progressive_mode) {
00848     if (cinfo->Ah == 0) {
00849       if (cinfo->Ss == 0)
00850         entropy->pub.encode_mcu = encode_mcu_DC_first;
00851       else
00852         entropy->pub.encode_mcu = encode_mcu_AC_first;
00853     } else {
00854       if (cinfo->Ss == 0)
00855         entropy->pub.encode_mcu = encode_mcu_DC_refine;
00856       else
00857         entropy->pub.encode_mcu = encode_mcu_AC_refine;
00858     }
00859   } else
00860     entropy->pub.encode_mcu = encode_mcu;
00861 
00862   /* Allocate & initialize requested statistics areas */
00863   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
00864     compptr = cinfo->cur_comp_info[ci];
00865     /* DC needs no table for refinement scan */
00866     if (cinfo->Ss == 0 && cinfo->Ah == 0) {
00867       tbl = compptr->dc_tbl_no;
00868       if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
00869         ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
00870       if (entropy->dc_stats[tbl] == NULL)
00871         entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
00872           ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
00873       MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
00874       /* Initialize DC predictions to 0 */
00875       entropy->last_dc_val[ci] = 0;
00876       entropy->dc_context[ci] = 0;
00877     }
00878     /* AC needs no table when not present */
00879     if (cinfo->Se) {
00880       tbl = compptr->ac_tbl_no;
00881       if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
00882         ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
00883       if (entropy->ac_stats[tbl] == NULL)
00884         entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
00885           ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
00886       MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
00887 #ifdef CALCULATE_SPECTRAL_CONDITIONING
00888       if (cinfo->progressive_mode)
00889         /* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */
00890         cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);
00891 #endif
00892     }
00893   }
00894 
00895   /* Initialize arithmetic encoding variables */
00896   entropy->c = 0;
00897   entropy->a = 0x10000L;
00898   entropy->sc = 0;
00899   entropy->zc = 0;
00900   entropy->ct = 11;
00901   entropy->buffer = -1;  /* empty */
00902 
00903   /* Initialize restart stuff */
00904   entropy->restarts_to_go = cinfo->restart_interval;
00905   entropy->next_restart_num = 0;
00906 }
00907 
00908 
00909 /*
00910  * Module initialization routine for arithmetic entropy encoding.
00911  */
00912 
00913 GLOBAL(void)
00914 jinit_arith_encoder (j_compress_ptr cinfo)
00915 {
00916   arith_entropy_ptr entropy;
00917   int i;
00918 
00919   entropy = (arith_entropy_ptr)
00920     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
00921                                 SIZEOF(arith_entropy_encoder));
00922   cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
00923   entropy->pub.start_pass = start_pass;
00924   entropy->pub.finish_pass = finish_pass;
00925 
00926   /* Mark tables unallocated */
00927   for (i = 0; i < NUM_ARITH_TBLS; i++) {
00928     entropy->dc_stats[i] = NULL;
00929     entropy->ac_stats[i] = NULL;
00930   }
00931 
00932   /* Initialize index for fixed probability estimation */
00933   entropy->fixed_bin[0] = 113;
00934 }

Generated on Tue Jul 5 14:13:28 2011 for ROOT_528-00b_version by  doxygen 1.5.1