jchuff.c
Go to the documentation of this file.
00001 /*
00002  * jchuff.c
00003  *
00004  * Copyright (C) 1991-1997, Thomas G. Lane.
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 Huffman entropy encoding routines.
00009  *
00010  * Much of the complexity here has to do with supporting output suspension.
00011  * If the data destination module demands suspension, we want to be able to
00012  * back up to the start of the current MCU.  To do this, we copy state
00013  * variables into local working storage, and update them back to the
00014  * permanent JPEG objects only upon successful completion of an MCU.
00015  */
00016 
00017 #define JPEG_INTERNALS
00018 #include "jinclude.h"
00019 #include "jpeglib.h"
00020 #include "jchuff.h"             /* Declarations shared with jcphuff.c */
00021 
00022 
00023 /* Expanded entropy encoder object for Huffman encoding.
00024  *
00025  * The savable_state subrecord contains fields that change within an MCU,
00026  * but must not be updated permanently until we complete the MCU.
00027  */
00028 
00029 typedef struct {
00030   INT32 put_buffer;             /* current bit-accumulation buffer */
00031   int put_bits;                 /* # of bits now in it */
00032   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
00033 } savable_state;
00034 
00035 /* This macro is to work around compilers with missing or broken
00036  * structure assignment.  You'll need to fix this code if you have
00037  * such a compiler and you change MAX_COMPS_IN_SCAN.
00038  */
00039 
00040 #ifndef NO_STRUCT_ASSIGN
00041 #define ASSIGN_STATE(dest,src)  ((dest) = (src))
00042 #else
00043 #if MAX_COMPS_IN_SCAN == 4
00044 #define ASSIGN_STATE(dest,src)  \
00045         ((dest).put_buffer = (src).put_buffer, \
00046          (dest).put_bits = (src).put_bits, \
00047          (dest).last_dc_val[0] = (src).last_dc_val[0], \
00048          (dest).last_dc_val[1] = (src).last_dc_val[1], \
00049          (dest).last_dc_val[2] = (src).last_dc_val[2], \
00050          (dest).last_dc_val[3] = (src).last_dc_val[3])
00051 #endif
00052 #endif
00053 
00054 
00055 typedef struct {
00056   struct jpeg_entropy_encoder pub; /* public fields */
00057 
00058   savable_state saved;          /* Bit buffer & DC state at start of MCU */
00059 
00060   /* These fields are NOT loaded into local working state. */
00061   unsigned int restarts_to_go;  /* MCUs left in this restart interval */
00062   int next_restart_num;         /* next restart number to write (0-7) */
00063 
00064   /* Pointers to derived tables (these workspaces have image lifespan) */
00065   c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
00066   c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
00067 
00068 #ifdef ENTROPY_OPT_SUPPORTED    /* Statistics tables for optimization */
00069   long * dc_count_ptrs[NUM_HUFF_TBLS];
00070   long * ac_count_ptrs[NUM_HUFF_TBLS];
00071 #endif
00072 } huff_entropy_encoder;
00073 
00074 typedef huff_entropy_encoder * huff_entropy_ptr;
00075 
00076 /* Working state while writing an MCU.
00077  * This struct contains all the fields that are needed by subroutines.
00078  */
00079 
00080 typedef struct {
00081   JOCTET * next_output_byte;    /* => next byte to write in buffer */
00082   size_t free_in_buffer;        /* # of byte spaces remaining in buffer */
00083   savable_state cur;            /* Current bit buffer & DC state */
00084   j_compress_ptr cinfo;         /* dump_buffer needs access to this */
00085 } working_state;
00086 
00087 
00088 /* Forward declarations */
00089 METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
00090                                         JBLOCKROW *MCU_data));
00091 METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
00092 #ifdef ENTROPY_OPT_SUPPORTED
00093 METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
00094                                           JBLOCKROW *MCU_data));
00095 METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
00096 #endif
00097 
00098 
00099 /*
00100  * Initialize for a Huffman-compressed scan.
00101  * If gather_statistics is TRUE, we do not output anything during the scan,
00102  * just count the Huffman symbols used and generate Huffman code tables.
00103  */
00104 
00105 METHODDEF(void)
00106 start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
00107 {
00108   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
00109   int ci, dctbl, actbl;
00110   jpeg_component_info * compptr;
00111 
00112   if (gather_statistics) {
00113 #ifdef ENTROPY_OPT_SUPPORTED
00114     entropy->pub.encode_mcu = encode_mcu_gather;
00115     entropy->pub.finish_pass = finish_pass_gather;
00116 #else
00117     ERREXIT(cinfo, JERR_NOT_COMPILED);
00118 #endif
00119   } else {
00120     entropy->pub.encode_mcu = encode_mcu_huff;
00121     entropy->pub.finish_pass = finish_pass_huff;
00122   }
00123 
00124   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
00125     compptr = cinfo->cur_comp_info[ci];
00126     dctbl = compptr->dc_tbl_no;
00127     actbl = compptr->ac_tbl_no;
00128     if (gather_statistics) {
00129 #ifdef ENTROPY_OPT_SUPPORTED
00130       /* Check for invalid table indexes */
00131       /* (make_c_derived_tbl does this in the other path) */
00132       if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
00133         ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
00134       if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
00135         ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
00136       /* Allocate and zero the statistics tables */
00137       /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
00138       if (entropy->dc_count_ptrs[dctbl] == NULL)
00139         entropy->dc_count_ptrs[dctbl] = (long *)
00140           (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
00141                                       257 * SIZEOF(long));
00142       MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
00143       if (entropy->ac_count_ptrs[actbl] == NULL)
00144         entropy->ac_count_ptrs[actbl] = (long *)
00145           (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
00146                                       257 * SIZEOF(long));
00147       MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
00148 #endif
00149     } else {
00150       /* Compute derived values for Huffman tables */
00151       /* We may do this more than once for a table, but it's not expensive */
00152       jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
00153                               & entropy->dc_derived_tbls[dctbl]);
00154       jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
00155                               & entropy->ac_derived_tbls[actbl]);
00156     }
00157     /* Initialize DC predictions to 0 */
00158     entropy->saved.last_dc_val[ci] = 0;
00159   }
00160 
00161   /* Initialize bit buffer to empty */
00162   entropy->saved.put_buffer = 0;
00163   entropy->saved.put_bits = 0;
00164 
00165   /* Initialize restart stuff */
00166   entropy->restarts_to_go = cinfo->restart_interval;
00167   entropy->next_restart_num = 0;
00168 }
00169 
00170 
00171 /*
00172  * Compute the derived values for a Huffman table.
00173  * This routine also performs some validation checks on the table.
00174  *
00175  * Note this is also used by jcphuff.c.
00176  */
00177 
00178 GLOBAL(void)
00179 jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
00180                          c_derived_tbl ** pdtbl)
00181 {
00182   JHUFF_TBL *htbl;
00183   c_derived_tbl *dtbl;
00184   int p, i, l, lastp, si, maxsymbol;
00185   char huffsize[257];
00186   unsigned int huffcode[257];
00187   unsigned int code;
00188 
00189   /* Note that huffsize[] and huffcode[] are filled in code-length order,
00190    * paralleling the order of the symbols themselves in htbl->huffval[].
00191    */
00192 
00193   /* Find the input Huffman table */
00194   if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
00195     ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
00196   htbl =
00197     isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
00198   if (htbl == NULL)
00199     ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
00200 
00201   /* Allocate a workspace if we haven't already done so. */
00202   if (*pdtbl == NULL)
00203     *pdtbl = (c_derived_tbl *)
00204       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
00205                                   SIZEOF(c_derived_tbl));
00206   dtbl = *pdtbl;
00207   
00208   /* Figure C.1: make table of Huffman code length for each symbol */
00209 
00210   p = 0;
00211   for (l = 1; l <= 16; l++) {
00212     i = (int) htbl->bits[l];
00213     if (i < 0 || p + i > 256)   /* protect against table overrun */
00214       ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
00215     while (i--)
00216       huffsize[p++] = (char) l;
00217   }
00218   huffsize[p] = 0;
00219   lastp = p;
00220   
00221   /* Figure C.2: generate the codes themselves */
00222   /* We also validate that the counts represent a legal Huffman code tree. */
00223 
00224   code = 0;
00225   si = huffsize[0];
00226   p = 0;
00227   while (huffsize[p]) {
00228     while (((int) huffsize[p]) == si) {
00229       huffcode[p++] = code;
00230       code++;
00231     }
00232     /* code is now 1 more than the last code used for codelength si; but
00233      * it must still fit in si bits, since no code is allowed to be all ones.
00234      */
00235     if (((INT32) code) >= (((INT32) 1) << si))
00236       ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
00237     code <<= 1;
00238     si++;
00239   }
00240   
00241   /* Figure C.3: generate encoding tables */
00242   /* These are code and size indexed by symbol value */
00243 
00244   /* Set all codeless symbols to have code length 0;
00245    * this lets us detect duplicate VAL entries here, and later
00246    * allows emit_bits to detect any attempt to emit such symbols.
00247    */
00248   MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
00249 
00250   /* This is also a convenient place to check for out-of-range
00251    * and duplicated VAL entries.  We allow 0..255 for AC symbols
00252    * but only 0..15 for DC.  (We could constrain them further
00253    * based on data depth and mode, but this seems enough.)
00254    */
00255   maxsymbol = isDC ? 15 : 255;
00256 
00257   for (p = 0; p < lastp; p++) {
00258     i = htbl->huffval[p];
00259     if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
00260       ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
00261     dtbl->ehufco[i] = huffcode[p];
00262     dtbl->ehufsi[i] = huffsize[p];
00263   }
00264 }
00265 
00266 
00267 /* Outputting bytes to the file */
00268 
00269 /* Emit a byte, taking 'action' if must suspend. */
00270 #define emit_byte(state,val,action)  \
00271         { *(state)->next_output_byte++ = (JOCTET) (val);  \
00272           if (--(state)->free_in_buffer == 0)  \
00273             if (! dump_buffer(state))  \
00274               { action; } }
00275 
00276 
00277 LOCAL(boolean)
00278 dump_buffer (working_state * state)
00279 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
00280 {
00281   struct jpeg_destination_mgr * dest = state->cinfo->dest;
00282 
00283   if (! (*dest->empty_output_buffer) (state->cinfo))
00284     return FALSE;
00285   /* After a successful buffer dump, must reset buffer pointers */
00286   state->next_output_byte = dest->next_output_byte;
00287   state->free_in_buffer = dest->free_in_buffer;
00288   return TRUE;
00289 }
00290 
00291 
00292 /* Outputting bits to the file */
00293 
00294 /* Only the right 24 bits of put_buffer are used; the valid bits are
00295  * left-justified in this part.  At most 16 bits can be passed to emit_bits
00296  * in one call, and we never retain more than 7 bits in put_buffer
00297  * between calls, so 24 bits are sufficient.
00298  */
00299 
00300 INLINE
00301 LOCAL(boolean)
00302 emit_bits (working_state * state, unsigned int code, int size)
00303 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
00304 {
00305   /* This routine is heavily used, so it's worth coding tightly. */
00306   register INT32 put_buffer = (INT32) code;
00307   register int put_bits = state->cur.put_bits;
00308 
00309   /* if size is 0, caller used an invalid Huffman table entry */
00310   if (size == 0)
00311     ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
00312 
00313   put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
00314   
00315   put_bits += size;             /* new number of bits in buffer */
00316   
00317   put_buffer <<= 24 - put_bits; /* align incoming bits */
00318 
00319   put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
00320   
00321   while (put_bits >= 8) {
00322     int c = (int) ((put_buffer >> 16) & 0xFF);
00323     
00324     emit_byte(state, c, return FALSE);
00325     if (c == 0xFF) {            /* need to stuff a zero byte? */
00326       emit_byte(state, 0, return FALSE);
00327     }
00328     put_buffer <<= 8;
00329     put_bits -= 8;
00330   }
00331 
00332   state->cur.put_buffer = put_buffer; /* update state variables */
00333   state->cur.put_bits = put_bits;
00334 
00335   return TRUE;
00336 }
00337 
00338 
00339 LOCAL(boolean)
00340 flush_bits (working_state * state)
00341 {
00342   if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
00343     return FALSE;
00344   state->cur.put_buffer = 0;    /* and reset bit-buffer to empty */
00345   state->cur.put_bits = 0;
00346   return TRUE;
00347 }
00348 
00349 
00350 /* Encode a single block's worth of coefficients */
00351 
00352 LOCAL(boolean)
00353 encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
00354                   c_derived_tbl *dctbl, c_derived_tbl *actbl)
00355 {
00356   register int temp, temp2;
00357   register int nbits;
00358   register int k, r, i;
00359   
00360   /* Encode the DC coefficient difference per section F.1.2.1 */
00361   
00362   temp = temp2 = block[0] - last_dc_val;
00363 
00364   if (temp < 0) {
00365     temp = -temp;               /* temp is abs value of input */
00366     /* For a negative input, want temp2 = bitwise complement of abs(input) */
00367     /* This code assumes we are on a two's complement machine */
00368     temp2--;
00369   }
00370   
00371   /* Find the number of bits needed for the magnitude of the coefficient */
00372   nbits = 0;
00373   while (temp) {
00374     nbits++;
00375     temp >>= 1;
00376   }
00377   /* Check for out-of-range coefficient values.
00378    * Since we're encoding a difference, the range limit is twice as much.
00379    */
00380   if (nbits > MAX_COEF_BITS+1)
00381     ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
00382   
00383   /* Emit the Huffman-coded symbol for the number of bits */
00384   if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
00385     return FALSE;
00386 
00387   /* Emit that number of bits of the value, if positive, */
00388   /* or the complement of its magnitude, if negative. */
00389   if (nbits)                    /* emit_bits rejects calls with size 0 */
00390     if (! emit_bits(state, (unsigned int) temp2, nbits))
00391       return FALSE;
00392 
00393   /* Encode the AC coefficients per section F.1.2.2 */
00394   
00395   r = 0;                        /* r = run length of zeros */
00396   
00397   for (k = 1; k < DCTSIZE2; k++) {
00398     if ((temp = block[jpeg_natural_order[k]]) == 0) {
00399       r++;
00400     } else {
00401       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
00402       while (r > 15) {
00403         if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
00404           return FALSE;
00405         r -= 16;
00406       }
00407 
00408       temp2 = temp;
00409       if (temp < 0) {
00410         temp = -temp;           /* temp is abs value of input */
00411         /* This code assumes we are on a two's complement machine */
00412         temp2--;
00413       }
00414       
00415       /* Find the number of bits needed for the magnitude of the coefficient */
00416       nbits = 1;                /* there must be at least one 1 bit */
00417       while ((temp >>= 1))
00418         nbits++;
00419       /* Check for out-of-range coefficient values */
00420       if (nbits > MAX_COEF_BITS)
00421         ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
00422       
00423       /* Emit Huffman symbol for run length / number of bits */
00424       i = (r << 4) + nbits;
00425       if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
00426         return FALSE;
00427 
00428       /* Emit that number of bits of the value, if positive, */
00429       /* or the complement of its magnitude, if negative. */
00430       if (! emit_bits(state, (unsigned int) temp2, nbits))
00431         return FALSE;
00432       
00433       r = 0;
00434     }
00435   }
00436 
00437   /* If the last coef(s) were zero, emit an end-of-block code */
00438   if (r > 0)
00439     if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
00440       return FALSE;
00441 
00442   return TRUE;
00443 }
00444 
00445 
00446 /*
00447  * Emit a restart marker & resynchronize predictions.
00448  */
00449 
00450 LOCAL(boolean)
00451 emit_restart (working_state * state, int restart_num)
00452 {
00453   int ci;
00454 
00455   if (! flush_bits(state))
00456     return FALSE;
00457 
00458   emit_byte(state, 0xFF, return FALSE);
00459   emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
00460 
00461   /* Re-initialize DC predictions to 0 */
00462   for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
00463     state->cur.last_dc_val[ci] = 0;
00464 
00465   /* The restart counter is not updated until we successfully write the MCU. */
00466 
00467   return TRUE;
00468 }
00469 
00470 
00471 /*
00472  * Encode and output one MCU's worth of Huffman-compressed coefficients.
00473  */
00474 
00475 METHODDEF(boolean)
00476 encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00477 {
00478   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
00479   working_state state;
00480   int blkn, ci;
00481   jpeg_component_info * compptr;
00482 
00483   /* Load up working state */
00484   state.next_output_byte = cinfo->dest->next_output_byte;
00485   state.free_in_buffer = cinfo->dest->free_in_buffer;
00486   ASSIGN_STATE(state.cur, entropy->saved);
00487   state.cinfo = cinfo;
00488 
00489   /* Emit restart marker if needed */
00490   if (cinfo->restart_interval) {
00491     if (entropy->restarts_to_go == 0)
00492       if (! emit_restart(&state, entropy->next_restart_num))
00493         return FALSE;
00494   }
00495 
00496   /* Encode the MCU data blocks */
00497   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
00498     ci = cinfo->MCU_membership[blkn];
00499     compptr = cinfo->cur_comp_info[ci];
00500     if (! encode_one_block(&state,
00501                            MCU_data[blkn][0], state.cur.last_dc_val[ci],
00502                            entropy->dc_derived_tbls[compptr->dc_tbl_no],
00503                            entropy->ac_derived_tbls[compptr->ac_tbl_no]))
00504       return FALSE;
00505     /* Update last_dc_val */
00506     state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
00507   }
00508 
00509   /* Completed MCU, so update state */
00510   cinfo->dest->next_output_byte = state.next_output_byte;
00511   cinfo->dest->free_in_buffer = state.free_in_buffer;
00512   ASSIGN_STATE(entropy->saved, state.cur);
00513 
00514   /* Update restart-interval state too */
00515   if (cinfo->restart_interval) {
00516     if (entropy->restarts_to_go == 0) {
00517       entropy->restarts_to_go = cinfo->restart_interval;
00518       entropy->next_restart_num++;
00519       entropy->next_restart_num &= 7;
00520     }
00521     entropy->restarts_to_go--;
00522   }
00523 
00524   return TRUE;
00525 }
00526 
00527 
00528 /*
00529  * Finish up at the end of a Huffman-compressed scan.
00530  */
00531 
00532 METHODDEF(void)
00533 finish_pass_huff (j_compress_ptr cinfo)
00534 {
00535   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
00536   working_state state;
00537 
00538   /* Load up working state ... flush_bits needs it */
00539   state.next_output_byte = cinfo->dest->next_output_byte;
00540   state.free_in_buffer = cinfo->dest->free_in_buffer;
00541   ASSIGN_STATE(state.cur, entropy->saved);
00542   state.cinfo = cinfo;
00543 
00544   /* Flush out the last data */
00545   if (! flush_bits(&state))
00546     ERREXIT(cinfo, JERR_CANT_SUSPEND);
00547 
00548   /* Update state */
00549   cinfo->dest->next_output_byte = state.next_output_byte;
00550   cinfo->dest->free_in_buffer = state.free_in_buffer;
00551   ASSIGN_STATE(entropy->saved, state.cur);
00552 }
00553 
00554 
00555 /*
00556  * Huffman coding optimization.
00557  *
00558  * We first scan the supplied data and count the number of uses of each symbol
00559  * that is to be Huffman-coded. (This process MUST agree with the code above.)
00560  * Then we build a Huffman coding tree for the observed counts.
00561  * Symbols which are not needed at all for the particular image are not
00562  * assigned any code, which saves space in the DHT marker as well as in
00563  * the compressed data.
00564  */
00565 
00566 #ifdef ENTROPY_OPT_SUPPORTED
00567 
00568 
00569 /* Process a single block's worth of coefficients */
00570 
00571 LOCAL(void)
00572 htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
00573                  long dc_counts[], long ac_counts[])
00574 {
00575   register int temp;
00576   register int nbits;
00577   register int k, r;
00578   
00579   /* Encode the DC coefficient difference per section F.1.2.1 */
00580   
00581   temp = block[0] - last_dc_val;
00582   if (temp < 0)
00583     temp = -temp;
00584   
00585   /* Find the number of bits needed for the magnitude of the coefficient */
00586   nbits = 0;
00587   while (temp) {
00588     nbits++;
00589     temp >>= 1;
00590   }
00591   /* Check for out-of-range coefficient values.
00592    * Since we're encoding a difference, the range limit is twice as much.
00593    */
00594   if (nbits > MAX_COEF_BITS+1)
00595     ERREXIT(cinfo, JERR_BAD_DCT_COEF);
00596 
00597   /* Count the Huffman symbol for the number of bits */
00598   dc_counts[nbits]++;
00599   
00600   /* Encode the AC coefficients per section F.1.2.2 */
00601   
00602   r = 0;                        /* r = run length of zeros */
00603   
00604   for (k = 1; k < DCTSIZE2; k++) {
00605     if ((temp = block[jpeg_natural_order[k]]) == 0) {
00606       r++;
00607     } else {
00608       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
00609       while (r > 15) {
00610         ac_counts[0xF0]++;
00611         r -= 16;
00612       }
00613       
00614       /* Find the number of bits needed for the magnitude of the coefficient */
00615       if (temp < 0)
00616         temp = -temp;
00617       
00618       /* Find the number of bits needed for the magnitude of the coefficient */
00619       nbits = 1;                /* there must be at least one 1 bit */
00620       while ((temp >>= 1))
00621         nbits++;
00622       /* Check for out-of-range coefficient values */
00623       if (nbits > MAX_COEF_BITS)
00624         ERREXIT(cinfo, JERR_BAD_DCT_COEF);
00625       
00626       /* Count Huffman symbol for run length / number of bits */
00627       ac_counts[(r << 4) + nbits]++;
00628       
00629       r = 0;
00630     }
00631   }
00632 
00633   /* If the last coef(s) were zero, emit an end-of-block code */
00634   if (r > 0)
00635     ac_counts[0]++;
00636 }
00637 
00638 
00639 /*
00640  * Trial-encode one MCU's worth of Huffman-compressed coefficients.
00641  * No data is actually output, so no suspension return is possible.
00642  */
00643 
00644 METHODDEF(boolean)
00645 encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
00646 {
00647   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
00648   int blkn, ci;
00649   jpeg_component_info * compptr;
00650 
00651   /* Take care of restart intervals if needed */
00652   if (cinfo->restart_interval) {
00653     if (entropy->restarts_to_go == 0) {
00654       /* Re-initialize DC predictions to 0 */
00655       for (ci = 0; ci < cinfo->comps_in_scan; ci++)
00656         entropy->saved.last_dc_val[ci] = 0;
00657       /* Update restart state */
00658       entropy->restarts_to_go = cinfo->restart_interval;
00659     }
00660     entropy->restarts_to_go--;
00661   }
00662 
00663   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
00664     ci = cinfo->MCU_membership[blkn];
00665     compptr = cinfo->cur_comp_info[ci];
00666     htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
00667                     entropy->dc_count_ptrs[compptr->dc_tbl_no],
00668                     entropy->ac_count_ptrs[compptr->ac_tbl_no]);
00669     entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
00670   }
00671 
00672   return TRUE;
00673 }
00674 
00675 
00676 /*
00677  * Generate the best Huffman code table for the given counts, fill htbl.
00678  * Note this is also used by jcphuff.c.
00679  *
00680  * The JPEG standard requires that no symbol be assigned a codeword of all
00681  * one bits (so that padding bits added at the end of a compressed segment
00682  * can't look like a valid code).  Because of the canonical ordering of
00683  * codewords, this just means that there must be an unused slot in the
00684  * longest codeword length category.  Section K.2 of the JPEG spec suggests
00685  * reserving such a slot by pretending that symbol 256 is a valid symbol
00686  * with count 1.  In theory that's not optimal; giving it count zero but
00687  * including it in the symbol set anyway should give a better Huffman code.
00688  * But the theoretically better code actually seems to come out worse in
00689  * practice, because it produces more all-ones bytes (which incur stuffed
00690  * zero bytes in the final file).  In any case the difference is tiny.
00691  *
00692  * The JPEG standard requires Huffman codes to be no more than 16 bits long.
00693  * If some symbols have a very small but nonzero probability, the Huffman tree
00694  * must be adjusted to meet the code length restriction.  We currently use
00695  * the adjustment method suggested in JPEG section K.2.  This method is *not*
00696  * optimal; it may not choose the best possible limited-length code.  But
00697  * typically only very-low-frequency symbols will be given less-than-optimal
00698  * lengths, so the code is almost optimal.  Experimental comparisons against
00699  * an optimal limited-length-code algorithm indicate that the difference is
00700  * microscopic --- usually less than a hundredth of a percent of total size.
00701  * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
00702  */
00703 
00704 GLOBAL(void)
00705 jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
00706 {
00707 #define MAX_CLEN 32             /* assumed maximum initial code length */
00708   UINT8 bits[MAX_CLEN+1];       /* bits[k] = # of symbols with code length k */
00709   int codesize[257];            /* codesize[k] = code length of symbol k */
00710   int others[257];              /* next symbol in current branch of tree */
00711   int c1, c2;
00712   int p, i, j;
00713   long v;
00714 
00715   /* This algorithm is explained in section K.2 of the JPEG standard */
00716 
00717   MEMZERO(bits, SIZEOF(bits));
00718   MEMZERO(codesize, SIZEOF(codesize));
00719   for (i = 0; i < 257; i++)
00720     others[i] = -1;             /* init links to empty */
00721   
00722   freq[256] = 1;                /* make sure 256 has a nonzero count */
00723   /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
00724    * that no real symbol is given code-value of all ones, because 256
00725    * will be placed last in the largest codeword category.
00726    */
00727 
00728   /* Huffman's basic algorithm to assign optimal code lengths to symbols */
00729 
00730   for (;;) {
00731     /* Find the smallest nonzero frequency, set c1 = its symbol */
00732     /* In case of ties, take the larger symbol number */
00733     c1 = -1;
00734     v = 1000000000L;
00735     for (i = 0; i <= 256; i++) {
00736       if (freq[i] && freq[i] <= v) {
00737         v = freq[i];
00738         c1 = i;
00739       }
00740     }
00741 
00742     /* Find the next smallest nonzero frequency, set c2 = its symbol */
00743     /* In case of ties, take the larger symbol number */
00744     c2 = -1;
00745     v = 1000000000L;
00746     for (i = 0; i <= 256; i++) {
00747       if (freq[i] && freq[i] <= v && i != c1) {
00748         v = freq[i];
00749         c2 = i;
00750       }
00751     }
00752 
00753     /* Done if we've merged everything into one frequency */
00754     if (c2 < 0)
00755       break;
00756     
00757     /* Else merge the two counts/trees */
00758     freq[c1] += freq[c2];
00759     freq[c2] = 0;
00760 
00761     /* Increment the codesize of everything in c1's tree branch */
00762     codesize[c1]++;
00763     while (others[c1] >= 0) {
00764       c1 = others[c1];
00765       codesize[c1]++;
00766     }
00767     
00768     others[c1] = c2;            /* chain c2 onto c1's tree branch */
00769     
00770     /* Increment the codesize of everything in c2's tree branch */
00771     codesize[c2]++;
00772     while (others[c2] >= 0) {
00773       c2 = others[c2];
00774       codesize[c2]++;
00775     }
00776   }
00777 
00778   /* Now count the number of symbols of each code length */
00779   for (i = 0; i <= 256; i++) {
00780     if (codesize[i]) {
00781       /* The JPEG standard seems to think that this can't happen, */
00782       /* but I'm paranoid... */
00783       if (codesize[i] > MAX_CLEN)
00784         ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
00785 
00786       bits[codesize[i]]++;
00787     }
00788   }
00789 
00790   /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
00791    * Huffman procedure assigned any such lengths, we must adjust the coding.
00792    * Here is what the JPEG spec says about how this next bit works:
00793    * Since symbols are paired for the longest Huffman code, the symbols are
00794    * removed from this length category two at a time.  The prefix for the pair
00795    * (which is one bit shorter) is allocated to one of the pair; then,
00796    * skipping the BITS entry for that prefix length, a code word from the next
00797    * shortest nonzero BITS entry is converted into a prefix for two code words
00798    * one bit longer.
00799    */
00800   
00801   for (i = MAX_CLEN; i > 16; i--) {
00802     while (bits[i] > 0) {
00803       j = i - 2;                /* find length of new prefix to be used */
00804       while (bits[j] == 0)
00805         j--;
00806       
00807       bits[i] -= 2;             /* remove two symbols */
00808       bits[i-1]++;              /* one goes in this length */
00809       bits[j+1] += 2;           /* two new symbols in this length */
00810       bits[j]--;                /* symbol of this length is now a prefix */
00811     }
00812   }
00813 
00814   /* Remove the count for the pseudo-symbol 256 from the largest codelength */
00815   while (bits[i] == 0)          /* find largest codelength still in use */
00816     i--;
00817   bits[i]--;
00818   
00819   /* Return final symbol counts (only for lengths 0..16) */
00820   MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
00821   
00822   /* Return a list of the symbols sorted by code length */
00823   /* It's not real clear to me why we don't need to consider the codelength
00824    * changes made above, but the JPEG spec seems to think this works.
00825    */
00826   p = 0;
00827   for (i = 1; i <= MAX_CLEN; i++) {
00828     for (j = 0; j <= 255; j++) {
00829       if (codesize[j] == i) {
00830         htbl->huffval[p] = (UINT8) j;
00831         p++;
00832       }
00833     }
00834   }
00835 
00836   /* Set sent_table FALSE so updated table will be written to JPEG file. */
00837   htbl->sent_table = FALSE;
00838 }
00839 
00840 
00841 /*
00842  * Finish up a statistics-gathering pass and create the new Huffman tables.
00843  */
00844 
00845 METHODDEF(void)
00846 finish_pass_gather (j_compress_ptr cinfo)
00847 {
00848   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
00849   int ci, dctbl, actbl;
00850   jpeg_component_info * compptr;
00851   JHUFF_TBL **htblptr;
00852   boolean did_dc[NUM_HUFF_TBLS];
00853   boolean did_ac[NUM_HUFF_TBLS];
00854 
00855   /* It's important not to apply jpeg_gen_optimal_table more than once
00856    * per table, because it clobbers the input frequency counts!
00857    */
00858   MEMZERO(did_dc, SIZEOF(did_dc));
00859   MEMZERO(did_ac, SIZEOF(did_ac));
00860 
00861   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
00862     compptr = cinfo->cur_comp_info[ci];
00863     dctbl = compptr->dc_tbl_no;
00864     actbl = compptr->ac_tbl_no;
00865     if (! did_dc[dctbl]) {
00866       htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
00867       if (*htblptr == NULL)
00868         *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
00869       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
00870       did_dc[dctbl] = TRUE;
00871     }
00872     if (! did_ac[actbl]) {
00873       htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
00874       if (*htblptr == NULL)
00875         *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
00876       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
00877       did_ac[actbl] = TRUE;
00878     }
00879   }
00880 }
00881 
00882 
00883 #endif /* ENTROPY_OPT_SUPPORTED */
00884 
00885 
00886 /*
00887  * Module initialization routine for Huffman entropy encoding.
00888  */
00889 
00890 GLOBAL(void)
00891 jinit_huff_encoder (j_compress_ptr cinfo)
00892 {
00893   huff_entropy_ptr entropy;
00894   int i;
00895 
00896   entropy = (huff_entropy_ptr)
00897     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
00898                                 SIZEOF(huff_entropy_encoder));
00899   cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
00900   entropy->pub.start_pass = start_pass_huff;
00901 
00902   /* Mark tables unallocated */
00903   for (i = 0; i < NUM_HUFF_TBLS; i++) {
00904     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
00905 #ifdef ENTROPY_OPT_SUPPORTED
00906     entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
00907 #endif
00908   }
00909 }


openhrp3
Author(s): AIST, General Robotix Inc., Nakamura Lab of Dept. of Mechano Informatics at University of Tokyo
autogenerated on Sun Apr 2 2017 03:43:55