src/3rdparty/libjpeg/jchuff.c
changeset 30 5dc02b23752f
parent 0 1918ee327afb
equal deleted inserted replaced
29:b72c6db6890b 30:5dc02b23752f
     1 /*
     1 /*
     2  * jchuff.c
     2  * jchuff.c
     3  *
     3  *
     4  * Copyright (C) 1991-1997, Thomas G. Lane.
     4  * Copyright (C) 1991-1997, Thomas G. Lane.
       
     5  * Modified 2006-2009 by Guido Vollbeding.
     5  * This file is part of the Independent JPEG Group's software.
     6  * This file is part of the Independent JPEG Group's software.
     6  * For conditions of distribution and use, see the accompanying README file.
     7  * For conditions of distribution and use, see the accompanying README file.
     7  *
     8  *
     8  * This file contains Huffman entropy encoding routines.
     9  * This file contains Huffman entropy encoding routines.
       
    10  * Both sequential and progressive modes are supported in this single module.
     9  *
    11  *
    10  * Much of the complexity here has to do with supporting output suspension.
    12  * Much of the complexity here has to do with supporting output suspension.
    11  * If the data destination module demands suspension, we want to be able to
    13  * If the data destination module demands suspension, we want to be able to
    12  * back up to the start of the current MCU.  To do this, we copy state
    14  * back up to the start of the current MCU.  To do this, we copy state
    13  * variables into local working storage, and update them back to the
    15  * variables into local working storage, and update them back to the
    14  * permanent JPEG objects only upon successful completion of an MCU.
    16  * permanent JPEG objects only upon successful completion of an MCU.
       
    17  *
       
    18  * We do not support output suspension for the progressive JPEG mode, since
       
    19  * the library currently does not allow multiple-scan files to be written
       
    20  * with output suspension.
    15  */
    21  */
    16 
    22 
    17 #define JPEG_INTERNALS
    23 #define JPEG_INTERNALS
    18 #include "jinclude.h"
    24 #include "jinclude.h"
    19 #include "jpeglib.h"
    25 #include "jpeglib.h"
    20 #include "jchuff.h"		/* Declarations shared with jcphuff.c */
    26 
       
    27 
       
    28 /* The legal range of a DCT coefficient is
       
    29  *  -1024 .. +1023  for 8-bit data;
       
    30  * -16384 .. +16383 for 12-bit data.
       
    31  * Hence the magnitude should always fit in 10 or 14 bits respectively.
       
    32  */
       
    33 
       
    34 #if BITS_IN_JSAMPLE == 8
       
    35 #define MAX_COEF_BITS 10
       
    36 #else
       
    37 #define MAX_COEF_BITS 14
       
    38 #endif
       
    39 
       
    40 /* Derived data constructed for each Huffman table */
       
    41 
       
    42 typedef struct {
       
    43   unsigned int ehufco[256];	/* code for each symbol */
       
    44   char ehufsi[256];		/* length of code for each symbol */
       
    45   /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
       
    46 } c_derived_tbl;
    21 
    47 
    22 
    48 
    23 /* Expanded entropy encoder object for Huffman encoding.
    49 /* Expanded entropy encoder object for Huffman encoding.
    24  *
    50  *
    25  * The savable_state subrecord contains fields that change within an MCU,
    51  * The savable_state subrecord contains fields that change within an MCU,
    63 
    89 
    64   /* Pointers to derived tables (these workspaces have image lifespan) */
    90   /* Pointers to derived tables (these workspaces have image lifespan) */
    65   c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
    91   c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
    66   c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
    92   c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
    67 
    93 
    68 #ifdef ENTROPY_OPT_SUPPORTED	/* Statistics tables for optimization */
    94   /* Statistics tables for optimization */
    69   long * dc_count_ptrs[NUM_HUFF_TBLS];
    95   long * dc_count_ptrs[NUM_HUFF_TBLS];
    70   long * ac_count_ptrs[NUM_HUFF_TBLS];
    96   long * ac_count_ptrs[NUM_HUFF_TBLS];
    71 #endif
    97 
       
    98   /* Following fields used only in progressive mode */
       
    99 
       
   100   /* Mode flag: TRUE for optimization, FALSE for actual data output */
       
   101   boolean gather_statistics;
       
   102 
       
   103   /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
       
   104    */
       
   105   JOCTET * next_output_byte;	/* => next byte to write in buffer */
       
   106   size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
       
   107   j_compress_ptr cinfo;		/* link to cinfo (needed for dump_buffer) */
       
   108 
       
   109   /* Coding status for AC components */
       
   110   int ac_tbl_no;		/* the table number of the single component */
       
   111   unsigned int EOBRUN;		/* run length of EOBs */
       
   112   unsigned int BE;		/* # of buffered correction bits before MCU */
       
   113   char * bit_buffer;		/* buffer for correction bits (1 per char) */
       
   114   /* packing correction bits tightly would save some space but cost time... */
    72 } huff_entropy_encoder;
   115 } huff_entropy_encoder;
    73 
   116 
    74 typedef huff_entropy_encoder * huff_entropy_ptr;
   117 typedef huff_entropy_encoder * huff_entropy_ptr;
    75 
   118 
    76 /* Working state while writing an MCU.
   119 /* Working state while writing an MCU (sequential mode).
    77  * This struct contains all the fields that are needed by subroutines.
   120  * This struct contains all the fields that are needed by subroutines.
    78  */
   121  */
    79 
   122 
    80 typedef struct {
   123 typedef struct {
    81   JOCTET * next_output_byte;	/* => next byte to write in buffer */
   124   JOCTET * next_output_byte;	/* => next byte to write in buffer */
    82   size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
   125   size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
    83   savable_state cur;		/* Current bit buffer & DC state */
   126   savable_state cur;		/* Current bit buffer & DC state */
    84   j_compress_ptr cinfo;		/* dump_buffer needs access to this */
   127   j_compress_ptr cinfo;		/* dump_buffer needs access to this */
    85 } working_state;
   128 } working_state;
    86 
   129 
    87 
   130 /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
    88 /* Forward declarations */
   131  * buffer can hold.  Larger sizes may slightly improve compression, but
    89 METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
   132  * 1000 is already well into the realm of overkill.
    90 					JBLOCKROW *MCU_data));
   133  * The minimum safe size is 64 bits.
    91 METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
   134  */
    92 #ifdef ENTROPY_OPT_SUPPORTED
   135 
    93 METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
   136 #define MAX_CORR_BITS  1000	/* Max # of correction bits I can buffer */
    94 					  JBLOCKROW *MCU_data));
   137 
    95 METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
   138 /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
       
   139  * We assume that int right shift is unsigned if INT32 right shift is,
       
   140  * which should be safe.
       
   141  */
       
   142 
       
   143 #ifdef RIGHT_SHIFT_IS_UNSIGNED
       
   144 #define ISHIFT_TEMPS	int ishift_temp;
       
   145 #define IRIGHT_SHIFT(x,shft)  \
       
   146 	((ishift_temp = (x)) < 0 ? \
       
   147 	 (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
       
   148 	 (ishift_temp >> (shft)))
       
   149 #else
       
   150 #define ISHIFT_TEMPS
       
   151 #define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
    96 #endif
   152 #endif
    97 
       
    98 
       
    99 /*
       
   100  * Initialize for a Huffman-compressed scan.
       
   101  * If gather_statistics is TRUE, we do not output anything during the scan,
       
   102  * just count the Huffman symbols used and generate Huffman code tables.
       
   103  */
       
   104 
       
   105 METHODDEF(void)
       
   106 start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
       
   107 {
       
   108   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
       
   109   int ci, dctbl, actbl;
       
   110   jpeg_component_info * compptr;
       
   111 
       
   112   if (gather_statistics) {
       
   113 #ifdef ENTROPY_OPT_SUPPORTED
       
   114     entropy->pub.encode_mcu = encode_mcu_gather;
       
   115     entropy->pub.finish_pass = finish_pass_gather;
       
   116 #else
       
   117     ERREXIT(cinfo, JERR_NOT_COMPILED);
       
   118 #endif
       
   119   } else {
       
   120     entropy->pub.encode_mcu = encode_mcu_huff;
       
   121     entropy->pub.finish_pass = finish_pass_huff;
       
   122   }
       
   123 
       
   124   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
       
   125     compptr = cinfo->cur_comp_info[ci];
       
   126     dctbl = compptr->dc_tbl_no;
       
   127     actbl = compptr->ac_tbl_no;
       
   128     if (gather_statistics) {
       
   129 #ifdef ENTROPY_OPT_SUPPORTED
       
   130       /* Check for invalid table indexes */
       
   131       /* (make_c_derived_tbl does this in the other path) */
       
   132       if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
       
   133 	ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
       
   134       if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
       
   135 	ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
       
   136       /* Allocate and zero the statistics tables */
       
   137       /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
       
   138       if (entropy->dc_count_ptrs[dctbl] == NULL)
       
   139 	entropy->dc_count_ptrs[dctbl] = (long *)
       
   140 	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
       
   141 				      257 * SIZEOF(long));
       
   142       MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
       
   143       if (entropy->ac_count_ptrs[actbl] == NULL)
       
   144 	entropy->ac_count_ptrs[actbl] = (long *)
       
   145 	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
       
   146 				      257 * SIZEOF(long));
       
   147       MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
       
   148 #endif
       
   149     } else {
       
   150       /* Compute derived values for Huffman tables */
       
   151       /* We may do this more than once for a table, but it's not expensive */
       
   152       jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
       
   153 			      & entropy->dc_derived_tbls[dctbl]);
       
   154       jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
       
   155 			      & entropy->ac_derived_tbls[actbl]);
       
   156     }
       
   157     /* Initialize DC predictions to 0 */
       
   158     entropy->saved.last_dc_val[ci] = 0;
       
   159   }
       
   160 
       
   161   /* Initialize bit buffer to empty */
       
   162   entropy->saved.put_buffer = 0;
       
   163   entropy->saved.put_bits = 0;
       
   164 
       
   165   /* Initialize restart stuff */
       
   166   entropy->restarts_to_go = cinfo->restart_interval;
       
   167   entropy->next_restart_num = 0;
       
   168 }
       
   169 
   153 
   170 
   154 
   171 /*
   155 /*
   172  * Compute the derived values for a Huffman table.
   156  * Compute the derived values for a Huffman table.
   173  * This routine also performs some validation checks on the table.
   157  * This routine also performs some validation checks on the table.
   174  *
   158  */
   175  * Note this is also used by jcphuff.c.
   159 
   176  */
   160 LOCAL(void)
   177 
       
   178 GLOBAL(void)
       
   179 jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
   161 jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
   180 			 c_derived_tbl ** pdtbl)
   162 			 c_derived_tbl ** pdtbl)
   181 {
   163 {
   182   JHUFF_TBL *htbl;
   164   JHUFF_TBL *htbl;
   183   c_derived_tbl *dtbl;
   165   c_derived_tbl *dtbl;
   262     dtbl->ehufsi[i] = huffsize[p];
   244     dtbl->ehufsi[i] = huffsize[p];
   263   }
   245   }
   264 }
   246 }
   265 
   247 
   266 
   248 
   267 /* Outputting bytes to the file */
   249 /* Outputting bytes to the file.
       
   250  * NB: these must be called only when actually outputting,
       
   251  * that is, entropy->gather_statistics == FALSE.
       
   252  */
   268 
   253 
   269 /* Emit a byte, taking 'action' if must suspend. */
   254 /* Emit a byte, taking 'action' if must suspend. */
   270 #define emit_byte(state,val,action)  \
   255 #define emit_byte_s(state,val,action)  \
   271 	{ *(state)->next_output_byte++ = (JOCTET) (val);  \
   256 	{ *(state)->next_output_byte++ = (JOCTET) (val);  \
   272 	  if (--(state)->free_in_buffer == 0)  \
   257 	  if (--(state)->free_in_buffer == 0)  \
   273 	    if (! dump_buffer(state))  \
   258 	    if (! dump_buffer_s(state))  \
   274 	      { action; } }
   259 	      { action; } }
   275 
   260 
       
   261 /* Emit a byte */
       
   262 #define emit_byte_e(entropy,val)  \
       
   263 	{ *(entropy)->next_output_byte++ = (JOCTET) (val);  \
       
   264 	  if (--(entropy)->free_in_buffer == 0)  \
       
   265 	    dump_buffer_e(entropy); }
       
   266 
   276 
   267 
   277 LOCAL(boolean)
   268 LOCAL(boolean)
   278 dump_buffer (working_state * state)
   269 dump_buffer_s (working_state * state)
   279 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
   270 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
   280 {
   271 {
   281   struct jpeg_destination_mgr * dest = state->cinfo->dest;
   272   struct jpeg_destination_mgr * dest = state->cinfo->dest;
   282 
   273 
   283   if (! (*dest->empty_output_buffer) (state->cinfo))
   274   if (! (*dest->empty_output_buffer) (state->cinfo))
   287   state->free_in_buffer = dest->free_in_buffer;
   278   state->free_in_buffer = dest->free_in_buffer;
   288   return TRUE;
   279   return TRUE;
   289 }
   280 }
   290 
   281 
   291 
   282 
       
   283 LOCAL(void)
       
   284 dump_buffer_e (huff_entropy_ptr entropy)
       
   285 /* Empty the output buffer; we do not support suspension in this case. */
       
   286 {
       
   287   struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
       
   288 
       
   289   if (! (*dest->empty_output_buffer) (entropy->cinfo))
       
   290     ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
       
   291   /* After a successful buffer dump, must reset buffer pointers */
       
   292   entropy->next_output_byte = dest->next_output_byte;
       
   293   entropy->free_in_buffer = dest->free_in_buffer;
       
   294 }
       
   295 
       
   296 
   292 /* Outputting bits to the file */
   297 /* Outputting bits to the file */
   293 
   298 
   294 /* Only the right 24 bits of put_buffer are used; the valid bits are
   299 /* Only the right 24 bits of put_buffer are used; the valid bits are
   295  * left-justified in this part.  At most 16 bits can be passed to emit_bits
   300  * left-justified in this part.  At most 16 bits can be passed to emit_bits
   296  * in one call, and we never retain more than 7 bits in put_buffer
   301  * in one call, and we never retain more than 7 bits in put_buffer
   297  * between calls, so 24 bits are sufficient.
   302  * between calls, so 24 bits are sufficient.
   298  */
   303  */
   299 
   304 
   300 INLINE
   305 INLINE
   301 LOCAL(boolean)
   306 LOCAL(boolean)
   302 emit_bits (working_state * state, unsigned int code, int size)
   307 emit_bits_s (working_state * state, unsigned int code, int size)
   303 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
   308 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
   304 {
   309 {
   305   /* This routine is heavily used, so it's worth coding tightly. */
   310   /* This routine is heavily used, so it's worth coding tightly. */
   306   register INT32 put_buffer = (INT32) code;
   311   register INT32 put_buffer = (INT32) code;
   307   register int put_bits = state->cur.put_bits;
   312   register int put_bits = state->cur.put_bits;
   319   put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
   324   put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
   320   
   325   
   321   while (put_bits >= 8) {
   326   while (put_bits >= 8) {
   322     int c = (int) ((put_buffer >> 16) & 0xFF);
   327     int c = (int) ((put_buffer >> 16) & 0xFF);
   323     
   328     
   324     emit_byte(state, c, return FALSE);
   329     emit_byte_s(state, c, return FALSE);
   325     if (c == 0xFF) {		/* need to stuff a zero byte? */
   330     if (c == 0xFF) {		/* need to stuff a zero byte? */
   326       emit_byte(state, 0, return FALSE);
   331       emit_byte_s(state, 0, return FALSE);
   327     }
   332     }
   328     put_buffer <<= 8;
   333     put_buffer <<= 8;
   329     put_bits -= 8;
   334     put_bits -= 8;
   330   }
   335   }
   331 
   336 
   334 
   339 
   335   return TRUE;
   340   return TRUE;
   336 }
   341 }
   337 
   342 
   338 
   343 
       
   344 INLINE
       
   345 LOCAL(void)
       
   346 emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
       
   347 /* Emit some bits, unless we are in gather mode */
       
   348 {
       
   349   /* This routine is heavily used, so it's worth coding tightly. */
       
   350   register INT32 put_buffer = (INT32) code;
       
   351   register int put_bits = entropy->saved.put_bits;
       
   352 
       
   353   /* if size is 0, caller used an invalid Huffman table entry */
       
   354   if (size == 0)
       
   355     ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
       
   356 
       
   357   if (entropy->gather_statistics)
       
   358     return;			/* do nothing if we're only getting stats */
       
   359 
       
   360   put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
       
   361   
       
   362   put_bits += size;		/* new number of bits in buffer */
       
   363 
       
   364   put_buffer <<= 24 - put_bits; /* align incoming bits */
       
   365 
       
   366   /* and merge with old buffer contents */
       
   367   put_buffer |= entropy->saved.put_buffer;
       
   368 
       
   369   while (put_bits >= 8) {
       
   370     int c = (int) ((put_buffer >> 16) & 0xFF);
       
   371 
       
   372     emit_byte_e(entropy, c);
       
   373     if (c == 0xFF) {		/* need to stuff a zero byte? */
       
   374       emit_byte_e(entropy, 0);
       
   375     }
       
   376     put_buffer <<= 8;
       
   377     put_bits -= 8;
       
   378   }
       
   379 
       
   380   entropy->saved.put_buffer = put_buffer; /* update variables */
       
   381   entropy->saved.put_bits = put_bits;
       
   382 }
       
   383 
       
   384 
   339 LOCAL(boolean)
   385 LOCAL(boolean)
   340 flush_bits (working_state * state)
   386 flush_bits_s (working_state * state)
   341 {
   387 {
   342   if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
   388   if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */
   343     return FALSE;
   389     return FALSE;
   344   state->cur.put_buffer = 0;	/* and reset bit-buffer to empty */
   390   state->cur.put_buffer = 0;	     /* and reset bit-buffer to empty */
   345   state->cur.put_bits = 0;
   391   state->cur.put_bits = 0;
       
   392   return TRUE;
       
   393 }
       
   394 
       
   395 
       
   396 LOCAL(void)
       
   397 flush_bits_e (huff_entropy_ptr entropy)
       
   398 {
       
   399   emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
       
   400   entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
       
   401   entropy->saved.put_bits = 0;
       
   402 }
       
   403 
       
   404 
       
   405 /*
       
   406  * Emit (or just count) a Huffman symbol.
       
   407  */
       
   408 
       
   409 INLINE
       
   410 LOCAL(void)
       
   411 emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
       
   412 {
       
   413   if (entropy->gather_statistics)
       
   414     entropy->dc_count_ptrs[tbl_no][symbol]++;
       
   415   else {
       
   416     c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];
       
   417     emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
       
   418   }
       
   419 }
       
   420 
       
   421 
       
   422 INLINE
       
   423 LOCAL(void)
       
   424 emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
       
   425 {
       
   426   if (entropy->gather_statistics)
       
   427     entropy->ac_count_ptrs[tbl_no][symbol]++;
       
   428   else {
       
   429     c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];
       
   430     emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
       
   431   }
       
   432 }
       
   433 
       
   434 
       
   435 /*
       
   436  * Emit bits from a correction bit buffer.
       
   437  */
       
   438 
       
   439 LOCAL(void)
       
   440 emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
       
   441 		    unsigned int nbits)
       
   442 {
       
   443   if (entropy->gather_statistics)
       
   444     return;			/* no real work */
       
   445 
       
   446   while (nbits > 0) {
       
   447     emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
       
   448     bufstart++;
       
   449     nbits--;
       
   450   }
       
   451 }
       
   452 
       
   453 
       
   454 /*
       
   455  * Emit any pending EOBRUN symbol.
       
   456  */
       
   457 
       
   458 LOCAL(void)
       
   459 emit_eobrun (huff_entropy_ptr entropy)
       
   460 {
       
   461   register int temp, nbits;
       
   462 
       
   463   if (entropy->EOBRUN > 0) {	/* if there is any pending EOBRUN */
       
   464     temp = entropy->EOBRUN;
       
   465     nbits = 0;
       
   466     while ((temp >>= 1))
       
   467       nbits++;
       
   468     /* safety check: shouldn't happen given limited correction-bit buffer */
       
   469     if (nbits > 14)
       
   470       ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
       
   471 
       
   472     emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
       
   473     if (nbits)
       
   474       emit_bits_e(entropy, entropy->EOBRUN, nbits);
       
   475 
       
   476     entropy->EOBRUN = 0;
       
   477 
       
   478     /* Emit any buffered correction bits */
       
   479     emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
       
   480     entropy->BE = 0;
       
   481   }
       
   482 }
       
   483 
       
   484 
       
   485 /*
       
   486  * Emit a restart marker & resynchronize predictions.
       
   487  */
       
   488 
       
   489 LOCAL(boolean)
       
   490 emit_restart_s (working_state * state, int restart_num)
       
   491 {
       
   492   int ci;
       
   493 
       
   494   if (! flush_bits_s(state))
       
   495     return FALSE;
       
   496 
       
   497   emit_byte_s(state, 0xFF, return FALSE);
       
   498   emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);
       
   499 
       
   500   /* Re-initialize DC predictions to 0 */
       
   501   for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
       
   502     state->cur.last_dc_val[ci] = 0;
       
   503 
       
   504   /* The restart counter is not updated until we successfully write the MCU. */
       
   505 
       
   506   return TRUE;
       
   507 }
       
   508 
       
   509 
       
   510 LOCAL(void)
       
   511 emit_restart_e (huff_entropy_ptr entropy, int restart_num)
       
   512 {
       
   513   int ci;
       
   514 
       
   515   emit_eobrun(entropy);
       
   516 
       
   517   if (! entropy->gather_statistics) {
       
   518     flush_bits_e(entropy);
       
   519     emit_byte_e(entropy, 0xFF);
       
   520     emit_byte_e(entropy, JPEG_RST0 + restart_num);
       
   521   }
       
   522 
       
   523   if (entropy->cinfo->Ss == 0) {
       
   524     /* Re-initialize DC predictions to 0 */
       
   525     for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
       
   526       entropy->saved.last_dc_val[ci] = 0;
       
   527   } else {
       
   528     /* Re-initialize all AC-related fields to 0 */
       
   529     entropy->EOBRUN = 0;
       
   530     entropy->BE = 0;
       
   531   }
       
   532 }
       
   533 
       
   534 
       
   535 /*
       
   536  * MCU encoding for DC initial scan (either spectral selection,
       
   537  * or first pass of successive approximation).
       
   538  */
       
   539 
       
   540 METHODDEF(boolean)
       
   541 encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
       
   542 {
       
   543   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
       
   544   register int temp, temp2;
       
   545   register int nbits;
       
   546   int blkn, ci;
       
   547   int Al = cinfo->Al;
       
   548   JBLOCKROW block;
       
   549   jpeg_component_info * compptr;
       
   550   ISHIFT_TEMPS
       
   551 
       
   552   entropy->next_output_byte = cinfo->dest->next_output_byte;
       
   553   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
       
   554 
       
   555   /* Emit restart marker if needed */
       
   556   if (cinfo->restart_interval)
       
   557     if (entropy->restarts_to_go == 0)
       
   558       emit_restart_e(entropy, entropy->next_restart_num);
       
   559 
       
   560   /* Encode the MCU data blocks */
       
   561   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
       
   562     block = MCU_data[blkn];
       
   563     ci = cinfo->MCU_membership[blkn];
       
   564     compptr = cinfo->cur_comp_info[ci];
       
   565 
       
   566     /* Compute the DC value after the required point transform by Al.
       
   567      * This is simply an arithmetic right shift.
       
   568      */
       
   569     temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
       
   570 
       
   571     /* DC differences are figured on the point-transformed values. */
       
   572     temp = temp2 - entropy->saved.last_dc_val[ci];
       
   573     entropy->saved.last_dc_val[ci] = temp2;
       
   574 
       
   575     /* Encode the DC coefficient difference per section G.1.2.1 */
       
   576     temp2 = temp;
       
   577     if (temp < 0) {
       
   578       temp = -temp;		/* temp is abs value of input */
       
   579       /* For a negative input, want temp2 = bitwise complement of abs(input) */
       
   580       /* This code assumes we are on a two's complement machine */
       
   581       temp2--;
       
   582     }
       
   583     
       
   584     /* Find the number of bits needed for the magnitude of the coefficient */
       
   585     nbits = 0;
       
   586     while (temp) {
       
   587       nbits++;
       
   588       temp >>= 1;
       
   589     }
       
   590     /* Check for out-of-range coefficient values.
       
   591      * Since we're encoding a difference, the range limit is twice as much.
       
   592      */
       
   593     if (nbits > MAX_COEF_BITS+1)
       
   594       ERREXIT(cinfo, JERR_BAD_DCT_COEF);
       
   595     
       
   596     /* Count/emit the Huffman-coded symbol for the number of bits */
       
   597     emit_dc_symbol(entropy, compptr->dc_tbl_no, nbits);
       
   598     
       
   599     /* Emit that number of bits of the value, if positive, */
       
   600     /* or the complement of its magnitude, if negative. */
       
   601     if (nbits)			/* emit_bits rejects calls with size 0 */
       
   602       emit_bits_e(entropy, (unsigned int) temp2, nbits);
       
   603   }
       
   604 
       
   605   cinfo->dest->next_output_byte = entropy->next_output_byte;
       
   606   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
       
   607 
       
   608   /* Update restart-interval state too */
       
   609   if (cinfo->restart_interval) {
       
   610     if (entropy->restarts_to_go == 0) {
       
   611       entropy->restarts_to_go = cinfo->restart_interval;
       
   612       entropy->next_restart_num++;
       
   613       entropy->next_restart_num &= 7;
       
   614     }
       
   615     entropy->restarts_to_go--;
       
   616   }
       
   617 
       
   618   return TRUE;
       
   619 }
       
   620 
       
   621 
       
   622 /*
       
   623  * MCU encoding for AC initial scan (either spectral selection,
       
   624  * or first pass of successive approximation).
       
   625  */
       
   626 
       
   627 METHODDEF(boolean)
       
   628 encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
       
   629 {
       
   630   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
       
   631   register int temp, temp2;
       
   632   register int nbits;
       
   633   register int r, k;
       
   634   int Se, Al;
       
   635   const int * natural_order;
       
   636   JBLOCKROW block;
       
   637 
       
   638   entropy->next_output_byte = cinfo->dest->next_output_byte;
       
   639   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
       
   640 
       
   641   /* Emit restart marker if needed */
       
   642   if (cinfo->restart_interval)
       
   643     if (entropy->restarts_to_go == 0)
       
   644       emit_restart_e(entropy, entropy->next_restart_num);
       
   645 
       
   646   Se = cinfo->Se;
       
   647   Al = cinfo->Al;
       
   648   natural_order = cinfo->natural_order;
       
   649 
       
   650   /* Encode the MCU data block */
       
   651   block = MCU_data[0];
       
   652 
       
   653   /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
       
   654   
       
   655   r = 0;			/* r = run length of zeros */
       
   656    
       
   657   for (k = cinfo->Ss; k <= Se; k++) {
       
   658     if ((temp = (*block)[natural_order[k]]) == 0) {
       
   659       r++;
       
   660       continue;
       
   661     }
       
   662     /* We must apply the point transform by Al.  For AC coefficients this
       
   663      * is an integer division with rounding towards 0.  To do this portably
       
   664      * in C, we shift after obtaining the absolute value; so the code is
       
   665      * interwoven with finding the abs value (temp) and output bits (temp2).
       
   666      */
       
   667     if (temp < 0) {
       
   668       temp = -temp;		/* temp is abs value of input */
       
   669       temp >>= Al;		/* apply the point transform */
       
   670       /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
       
   671       temp2 = ~temp;
       
   672     } else {
       
   673       temp >>= Al;		/* apply the point transform */
       
   674       temp2 = temp;
       
   675     }
       
   676     /* Watch out for case that nonzero coef is zero after point transform */
       
   677     if (temp == 0) {
       
   678       r++;
       
   679       continue;
       
   680     }
       
   681 
       
   682     /* Emit any pending EOBRUN */
       
   683     if (entropy->EOBRUN > 0)
       
   684       emit_eobrun(entropy);
       
   685     /* if run length > 15, must emit special run-length-16 codes (0xF0) */
       
   686     while (r > 15) {
       
   687       emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
       
   688       r -= 16;
       
   689     }
       
   690 
       
   691     /* Find the number of bits needed for the magnitude of the coefficient */
       
   692     nbits = 1;			/* there must be at least one 1 bit */
       
   693     while ((temp >>= 1))
       
   694       nbits++;
       
   695     /* Check for out-of-range coefficient values */
       
   696     if (nbits > MAX_COEF_BITS)
       
   697       ERREXIT(cinfo, JERR_BAD_DCT_COEF);
       
   698 
       
   699     /* Count/emit Huffman symbol for run length / number of bits */
       
   700     emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
       
   701 
       
   702     /* Emit that number of bits of the value, if positive, */
       
   703     /* or the complement of its magnitude, if negative. */
       
   704     emit_bits_e(entropy, (unsigned int) temp2, nbits);
       
   705 
       
   706     r = 0;			/* reset zero run length */
       
   707   }
       
   708 
       
   709   if (r > 0) {			/* If there are trailing zeroes, */
       
   710     entropy->EOBRUN++;		/* count an EOB */
       
   711     if (entropy->EOBRUN == 0x7FFF)
       
   712       emit_eobrun(entropy);	/* force it out to avoid overflow */
       
   713   }
       
   714 
       
   715   cinfo->dest->next_output_byte = entropy->next_output_byte;
       
   716   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
       
   717 
       
   718   /* Update restart-interval state too */
       
   719   if (cinfo->restart_interval) {
       
   720     if (entropy->restarts_to_go == 0) {
       
   721       entropy->restarts_to_go = cinfo->restart_interval;
       
   722       entropy->next_restart_num++;
       
   723       entropy->next_restart_num &= 7;
       
   724     }
       
   725     entropy->restarts_to_go--;
       
   726   }
       
   727 
       
   728   return TRUE;
       
   729 }
       
   730 
       
   731 
       
   732 /*
       
   733  * MCU encoding for DC successive approximation refinement scan.
       
   734  * Note: we assume such scans can be multi-component, although the spec
       
   735  * is not very clear on the point.
       
   736  */
       
   737 
       
   738 METHODDEF(boolean)
       
   739 encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
       
   740 {
       
   741   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
       
   742   register int temp;
       
   743   int blkn;
       
   744   int Al = cinfo->Al;
       
   745   JBLOCKROW block;
       
   746 
       
   747   entropy->next_output_byte = cinfo->dest->next_output_byte;
       
   748   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
       
   749 
       
   750   /* Emit restart marker if needed */
       
   751   if (cinfo->restart_interval)
       
   752     if (entropy->restarts_to_go == 0)
       
   753       emit_restart_e(entropy, entropy->next_restart_num);
       
   754 
       
   755   /* Encode the MCU data blocks */
       
   756   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
       
   757     block = MCU_data[blkn];
       
   758 
       
   759     /* We simply emit the Al'th bit of the DC coefficient value. */
       
   760     temp = (*block)[0];
       
   761     emit_bits_e(entropy, (unsigned int) (temp >> Al), 1);
       
   762   }
       
   763 
       
   764   cinfo->dest->next_output_byte = entropy->next_output_byte;
       
   765   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
       
   766 
       
   767   /* Update restart-interval state too */
       
   768   if (cinfo->restart_interval) {
       
   769     if (entropy->restarts_to_go == 0) {
       
   770       entropy->restarts_to_go = cinfo->restart_interval;
       
   771       entropy->next_restart_num++;
       
   772       entropy->next_restart_num &= 7;
       
   773     }
       
   774     entropy->restarts_to_go--;
       
   775   }
       
   776 
       
   777   return TRUE;
       
   778 }
       
   779 
       
   780 
       
   781 /*
       
   782  * MCU encoding for AC successive approximation refinement scan.
       
   783  */
       
   784 
       
   785 METHODDEF(boolean)
       
   786 encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
       
   787 {
       
   788   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
       
   789   register int temp;
       
   790   register int r, k;
       
   791   int EOB;
       
   792   char *BR_buffer;
       
   793   unsigned int BR;
       
   794   int Se, Al;
       
   795   const int * natural_order;
       
   796   JBLOCKROW block;
       
   797   int absvalues[DCTSIZE2];
       
   798 
       
   799   entropy->next_output_byte = cinfo->dest->next_output_byte;
       
   800   entropy->free_in_buffer = cinfo->dest->free_in_buffer;
       
   801 
       
   802   /* Emit restart marker if needed */
       
   803   if (cinfo->restart_interval)
       
   804     if (entropy->restarts_to_go == 0)
       
   805       emit_restart_e(entropy, entropy->next_restart_num);
       
   806 
       
   807   Se = cinfo->Se;
       
   808   Al = cinfo->Al;
       
   809   natural_order = cinfo->natural_order;
       
   810 
       
   811   /* Encode the MCU data block */
       
   812   block = MCU_data[0];
       
   813 
       
   814   /* It is convenient to make a pre-pass to determine the transformed
       
   815    * coefficients' absolute values and the EOB position.
       
   816    */
       
   817   EOB = 0;
       
   818   for (k = cinfo->Ss; k <= Se; k++) {
       
   819     temp = (*block)[natural_order[k]];
       
   820     /* We must apply the point transform by Al.  For AC coefficients this
       
   821      * is an integer division with rounding towards 0.  To do this portably
       
   822      * in C, we shift after obtaining the absolute value.
       
   823      */
       
   824     if (temp < 0)
       
   825       temp = -temp;		/* temp is abs value of input */
       
   826     temp >>= Al;		/* apply the point transform */
       
   827     absvalues[k] = temp;	/* save abs value for main pass */
       
   828     if (temp == 1)
       
   829       EOB = k;			/* EOB = index of last newly-nonzero coef */
       
   830   }
       
   831 
       
   832   /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
       
   833   
       
   834   r = 0;			/* r = run length of zeros */
       
   835   BR = 0;			/* BR = count of buffered bits added now */
       
   836   BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
       
   837 
       
   838   for (k = cinfo->Ss; k <= Se; k++) {
       
   839     if ((temp = absvalues[k]) == 0) {
       
   840       r++;
       
   841       continue;
       
   842     }
       
   843 
       
   844     /* Emit any required ZRLs, but not if they can be folded into EOB */
       
   845     while (r > 15 && k <= EOB) {
       
   846       /* emit any pending EOBRUN and the BE correction bits */
       
   847       emit_eobrun(entropy);
       
   848       /* Emit ZRL */
       
   849       emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
       
   850       r -= 16;
       
   851       /* Emit buffered correction bits that must be associated with ZRL */
       
   852       emit_buffered_bits(entropy, BR_buffer, BR);
       
   853       BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
       
   854       BR = 0;
       
   855     }
       
   856 
       
   857     /* If the coef was previously nonzero, it only needs a correction bit.
       
   858      * NOTE: a straight translation of the spec's figure G.7 would suggest
       
   859      * that we also need to test r > 15.  But if r > 15, we can only get here
       
   860      * if k > EOB, which implies that this coefficient is not 1.
       
   861      */
       
   862     if (temp > 1) {
       
   863       /* The correction bit is the next bit of the absolute value. */
       
   864       BR_buffer[BR++] = (char) (temp & 1);
       
   865       continue;
       
   866     }
       
   867 
       
   868     /* Emit any pending EOBRUN and the BE correction bits */
       
   869     emit_eobrun(entropy);
       
   870 
       
   871     /* Count/emit Huffman symbol for run length / number of bits */
       
   872     emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
       
   873 
       
   874     /* Emit output bit for newly-nonzero coef */
       
   875     temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;
       
   876     emit_bits_e(entropy, (unsigned int) temp, 1);
       
   877 
       
   878     /* Emit buffered correction bits that must be associated with this code */
       
   879     emit_buffered_bits(entropy, BR_buffer, BR);
       
   880     BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
       
   881     BR = 0;
       
   882     r = 0;			/* reset zero run length */
       
   883   }
       
   884 
       
   885   if (r > 0 || BR > 0) {	/* If there are trailing zeroes, */
       
   886     entropy->EOBRUN++;		/* count an EOB */
       
   887     entropy->BE += BR;		/* concat my correction bits to older ones */
       
   888     /* We force out the EOB if we risk either:
       
   889      * 1. overflow of the EOB counter;
       
   890      * 2. overflow of the correction bit buffer during the next MCU.
       
   891      */
       
   892     if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
       
   893       emit_eobrun(entropy);
       
   894   }
       
   895 
       
   896   cinfo->dest->next_output_byte = entropy->next_output_byte;
       
   897   cinfo->dest->free_in_buffer = entropy->free_in_buffer;
       
   898 
       
   899   /* Update restart-interval state too */
       
   900   if (cinfo->restart_interval) {
       
   901     if (entropy->restarts_to_go == 0) {
       
   902       entropy->restarts_to_go = cinfo->restart_interval;
       
   903       entropy->next_restart_num++;
       
   904       entropy->next_restart_num &= 7;
       
   905     }
       
   906     entropy->restarts_to_go--;
       
   907   }
       
   908 
   346   return TRUE;
   909   return TRUE;
   347 }
   910 }
   348 
   911 
   349 
   912 
   350 /* Encode a single block's worth of coefficients */
   913 /* Encode a single block's worth of coefficients */
   354 		  c_derived_tbl *dctbl, c_derived_tbl *actbl)
   917 		  c_derived_tbl *dctbl, c_derived_tbl *actbl)
   355 {
   918 {
   356   register int temp, temp2;
   919   register int temp, temp2;
   357   register int nbits;
   920   register int nbits;
   358   register int k, r, i;
   921   register int k, r, i;
   359   
   922   int Se = state->cinfo->lim_Se;
       
   923   const int * natural_order = state->cinfo->natural_order;
       
   924 
   360   /* Encode the DC coefficient difference per section F.1.2.1 */
   925   /* Encode the DC coefficient difference per section F.1.2.1 */
   361   
   926 
   362   temp = temp2 = block[0] - last_dc_val;
   927   temp = temp2 = block[0] - last_dc_val;
   363 
   928 
   364   if (temp < 0) {
   929   if (temp < 0) {
   365     temp = -temp;		/* temp is abs value of input */
   930     temp = -temp;		/* temp is abs value of input */
   366     /* For a negative input, want temp2 = bitwise complement of abs(input) */
   931     /* For a negative input, want temp2 = bitwise complement of abs(input) */
   367     /* This code assumes we are on a two's complement machine */
   932     /* This code assumes we are on a two's complement machine */
   368     temp2--;
   933     temp2--;
   369   }
   934   }
   370   
   935 
   371   /* Find the number of bits needed for the magnitude of the coefficient */
   936   /* Find the number of bits needed for the magnitude of the coefficient */
   372   nbits = 0;
   937   nbits = 0;
   373   while (temp) {
   938   while (temp) {
   374     nbits++;
   939     nbits++;
   375     temp >>= 1;
   940     temp >>= 1;
   377   /* Check for out-of-range coefficient values.
   942   /* Check for out-of-range coefficient values.
   378    * Since we're encoding a difference, the range limit is twice as much.
   943    * Since we're encoding a difference, the range limit is twice as much.
   379    */
   944    */
   380   if (nbits > MAX_COEF_BITS+1)
   945   if (nbits > MAX_COEF_BITS+1)
   381     ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
   946     ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
   382   
   947 
   383   /* Emit the Huffman-coded symbol for the number of bits */
   948   /* Emit the Huffman-coded symbol for the number of bits */
   384   if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
   949   if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
   385     return FALSE;
   950     return FALSE;
   386 
   951 
   387   /* Emit that number of bits of the value, if positive, */
   952   /* Emit that number of bits of the value, if positive, */
   388   /* or the complement of its magnitude, if negative. */
   953   /* or the complement of its magnitude, if negative. */
   389   if (nbits)			/* emit_bits rejects calls with size 0 */
   954   if (nbits)			/* emit_bits rejects calls with size 0 */
   390     if (! emit_bits(state, (unsigned int) temp2, nbits))
   955     if (! emit_bits_s(state, (unsigned int) temp2, nbits))
   391       return FALSE;
   956       return FALSE;
   392 
   957 
   393   /* Encode the AC coefficients per section F.1.2.2 */
   958   /* Encode the AC coefficients per section F.1.2.2 */
   394   
   959 
   395   r = 0;			/* r = run length of zeros */
   960   r = 0;			/* r = run length of zeros */
   396   
   961 
   397   for (k = 1; k < DCTSIZE2; k++) {
   962   for (k = 1; k <= Se; k++) {
   398     if ((temp = block[jpeg_natural_order[k]]) == 0) {
   963     if ((temp = block[natural_order[k]]) == 0) {
   399       r++;
   964       r++;
   400     } else {
   965     } else {
   401       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
   966       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
   402       while (r > 15) {
   967       while (r > 15) {
   403 	if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
   968 	if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
   404 	  return FALSE;
   969 	  return FALSE;
   405 	r -= 16;
   970 	r -= 16;
   406       }
   971       }
   407 
   972 
   408       temp2 = temp;
   973       temp2 = temp;
   409       if (temp < 0) {
   974       if (temp < 0) {
   410 	temp = -temp;		/* temp is abs value of input */
   975 	temp = -temp;		/* temp is abs value of input */
   411 	/* This code assumes we are on a two's complement machine */
   976 	/* This code assumes we are on a two's complement machine */
   412 	temp2--;
   977 	temp2--;
   413       }
   978       }
   414       
   979 
   415       /* Find the number of bits needed for the magnitude of the coefficient */
   980       /* Find the number of bits needed for the magnitude of the coefficient */
   416       nbits = 1;		/* there must be at least one 1 bit */
   981       nbits = 1;		/* there must be at least one 1 bit */
   417       while ((temp >>= 1))
   982       while ((temp >>= 1))
   418 	nbits++;
   983 	nbits++;
   419       /* Check for out-of-range coefficient values */
   984       /* Check for out-of-range coefficient values */
   420       if (nbits > MAX_COEF_BITS)
   985       if (nbits > MAX_COEF_BITS)
   421 	ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
   986 	ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
   422       
   987 
   423       /* Emit Huffman symbol for run length / number of bits */
   988       /* Emit Huffman symbol for run length / number of bits */
   424       i = (r << 4) + nbits;
   989       i = (r << 4) + nbits;
   425       if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
   990       if (! emit_bits_s(state, actbl->ehufco[i], actbl->ehufsi[i]))
   426 	return FALSE;
   991 	return FALSE;
   427 
   992 
   428       /* Emit that number of bits of the value, if positive, */
   993       /* Emit that number of bits of the value, if positive, */
   429       /* or the complement of its magnitude, if negative. */
   994       /* or the complement of its magnitude, if negative. */
   430       if (! emit_bits(state, (unsigned int) temp2, nbits))
   995       if (! emit_bits_s(state, (unsigned int) temp2, nbits))
   431 	return FALSE;
   996 	return FALSE;
   432       
   997 
   433       r = 0;
   998       r = 0;
   434     }
   999     }
   435   }
  1000   }
   436 
  1001 
   437   /* If the last coef(s) were zero, emit an end-of-block code */
  1002   /* If the last coef(s) were zero, emit an end-of-block code */
   438   if (r > 0)
  1003   if (r > 0)
   439     if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  1004     if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
   440       return FALSE;
  1005       return FALSE;
   441 
       
   442   return TRUE;
       
   443 }
       
   444 
       
   445 
       
   446 /*
       
   447  * Emit a restart marker & resynchronize predictions.
       
   448  */
       
   449 
       
   450 LOCAL(boolean)
       
   451 emit_restart (working_state * state, int restart_num)
       
   452 {
       
   453   int ci;
       
   454 
       
   455   if (! flush_bits(state))
       
   456     return FALSE;
       
   457 
       
   458   emit_byte(state, 0xFF, return FALSE);
       
   459   emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
       
   460 
       
   461   /* Re-initialize DC predictions to 0 */
       
   462   for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
       
   463     state->cur.last_dc_val[ci] = 0;
       
   464 
       
   465   /* The restart counter is not updated until we successfully write the MCU. */
       
   466 
  1006 
   467   return TRUE;
  1007   return TRUE;
   468 }
  1008 }
   469 
  1009 
   470 
  1010 
   487   state.cinfo = cinfo;
  1027   state.cinfo = cinfo;
   488 
  1028 
   489   /* Emit restart marker if needed */
  1029   /* Emit restart marker if needed */
   490   if (cinfo->restart_interval) {
  1030   if (cinfo->restart_interval) {
   491     if (entropy->restarts_to_go == 0)
  1031     if (entropy->restarts_to_go == 0)
   492       if (! emit_restart(&state, entropy->next_restart_num))
  1032       if (! emit_restart_s(&state, entropy->next_restart_num))
   493 	return FALSE;
  1033 	return FALSE;
   494   }
  1034   }
   495 
  1035 
   496   /* Encode the MCU data blocks */
  1036   /* Encode the MCU data blocks */
   497   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1037   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
   533 finish_pass_huff (j_compress_ptr cinfo)
  1073 finish_pass_huff (j_compress_ptr cinfo)
   534 {
  1074 {
   535   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1075   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
   536   working_state state;
  1076   working_state state;
   537 
  1077 
   538   /* Load up working state ... flush_bits needs it */
  1078   if (cinfo->progressive_mode) {
   539   state.next_output_byte = cinfo->dest->next_output_byte;
  1079     entropy->next_output_byte = cinfo->dest->next_output_byte;
   540   state.free_in_buffer = cinfo->dest->free_in_buffer;
  1080     entropy->free_in_buffer = cinfo->dest->free_in_buffer;
   541   ASSIGN_STATE(state.cur, entropy->saved);
  1081 
   542   state.cinfo = cinfo;
  1082     /* Flush out any buffered data */
   543 
  1083     emit_eobrun(entropy);
   544   /* Flush out the last data */
  1084     flush_bits_e(entropy);
   545   if (! flush_bits(&state))
  1085 
   546     ERREXIT(cinfo, JERR_CANT_SUSPEND);
  1086     cinfo->dest->next_output_byte = entropy->next_output_byte;
   547 
  1087     cinfo->dest->free_in_buffer = entropy->free_in_buffer;
   548   /* Update state */
  1088   } else {
   549   cinfo->dest->next_output_byte = state.next_output_byte;
  1089     /* Load up working state ... flush_bits needs it */
   550   cinfo->dest->free_in_buffer = state.free_in_buffer;
  1090     state.next_output_byte = cinfo->dest->next_output_byte;
   551   ASSIGN_STATE(entropy->saved, state.cur);
  1091     state.free_in_buffer = cinfo->dest->free_in_buffer;
       
  1092     ASSIGN_STATE(state.cur, entropy->saved);
       
  1093     state.cinfo = cinfo;
       
  1094 
       
  1095     /* Flush out the last data */
       
  1096     if (! flush_bits_s(&state))
       
  1097       ERREXIT(cinfo, JERR_CANT_SUSPEND);
       
  1098 
       
  1099     /* Update state */
       
  1100     cinfo->dest->next_output_byte = state.next_output_byte;
       
  1101     cinfo->dest->free_in_buffer = state.free_in_buffer;
       
  1102     ASSIGN_STATE(entropy->saved, state.cur);
       
  1103   }
   552 }
  1104 }
   553 
  1105 
   554 
  1106 
   555 /*
  1107 /*
   556  * Huffman coding optimization.
  1108  * Huffman coding optimization.
   561  * Symbols which are not needed at all for the particular image are not
  1113  * Symbols which are not needed at all for the particular image are not
   562  * assigned any code, which saves space in the DHT marker as well as in
  1114  * assigned any code, which saves space in the DHT marker as well as in
   563  * the compressed data.
  1115  * the compressed data.
   564  */
  1116  */
   565 
  1117 
   566 #ifdef ENTROPY_OPT_SUPPORTED
       
   567 
       
   568 
  1118 
   569 /* Process a single block's worth of coefficients */
  1119 /* Process a single block's worth of coefficients */
   570 
  1120 
   571 LOCAL(void)
  1121 LOCAL(void)
   572 htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  1122 htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
   573 		 long dc_counts[], long ac_counts[])
  1123 		 long dc_counts[], long ac_counts[])
   574 {
  1124 {
   575   register int temp;
  1125   register int temp;
   576   register int nbits;
  1126   register int nbits;
   577   register int k, r;
  1127   register int k, r;
       
  1128   int Se = cinfo->lim_Se;
       
  1129   const int * natural_order = cinfo->natural_order;
   578   
  1130   
   579   /* Encode the DC coefficient difference per section F.1.2.1 */
  1131   /* Encode the DC coefficient difference per section F.1.2.1 */
   580   
  1132   
   581   temp = block[0] - last_dc_val;
  1133   temp = block[0] - last_dc_val;
   582   if (temp < 0)
  1134   if (temp < 0)
   599   
  1151   
   600   /* Encode the AC coefficients per section F.1.2.2 */
  1152   /* Encode the AC coefficients per section F.1.2.2 */
   601   
  1153   
   602   r = 0;			/* r = run length of zeros */
  1154   r = 0;			/* r = run length of zeros */
   603   
  1155   
   604   for (k = 1; k < DCTSIZE2; k++) {
  1156   for (k = 1; k <= Se; k++) {
   605     if ((temp = block[jpeg_natural_order[k]]) == 0) {
  1157     if ((temp = block[natural_order[k]]) == 0) {
   606       r++;
  1158       r++;
   607     } else {
  1159     } else {
   608       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  1160       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
   609       while (r > 15) {
  1161       while (r > 15) {
   610 	ac_counts[0xF0]++;
  1162 	ac_counts[0xF0]++;
   673 }
  1225 }
   674 
  1226 
   675 
  1227 
   676 /*
  1228 /*
   677  * Generate the best Huffman code table for the given counts, fill htbl.
  1229  * Generate the best Huffman code table for the given counts, fill htbl.
   678  * Note this is also used by jcphuff.c.
       
   679  *
  1230  *
   680  * The JPEG standard requires that no symbol be assigned a codeword of all
  1231  * The JPEG standard requires that no symbol be assigned a codeword of all
   681  * one bits (so that padding bits added at the end of a compressed segment
  1232  * one bits (so that padding bits added at the end of a compressed segment
   682  * can't look like a valid code).  Because of the canonical ordering of
  1233  * can't look like a valid code).  Because of the canonical ordering of
   683  * codewords, this just means that there must be an unused slot in the
  1234  * codewords, this just means that there must be an unused slot in the
   699  * an optimal limited-length-code algorithm indicate that the difference is
  1250  * an optimal limited-length-code algorithm indicate that the difference is
   700  * microscopic --- usually less than a hundredth of a percent of total size.
  1251  * microscopic --- usually less than a hundredth of a percent of total size.
   701  * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  1252  * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
   702  */
  1253  */
   703 
  1254 
   704 GLOBAL(void)
  1255 LOCAL(void)
   705 jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  1256 jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
   706 {
  1257 {
   707 #define MAX_CLEN 32		/* assumed maximum initial code length */
  1258 #define MAX_CLEN 32		/* assumed maximum initial code length */
   708   UINT8 bits[MAX_CLEN+1];	/* bits[k] = # of symbols with code length k */
  1259   UINT8 bits[MAX_CLEN+1];	/* bits[k] = # of symbols with code length k */
   709   int codesize[257];		/* codesize[k] = code length of symbol k */
  1260   int codesize[257];		/* codesize[k] = code length of symbol k */
   844 
  1395 
   845 METHODDEF(void)
  1396 METHODDEF(void)
   846 finish_pass_gather (j_compress_ptr cinfo)
  1397 finish_pass_gather (j_compress_ptr cinfo)
   847 {
  1398 {
   848   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1399   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
   849   int ci, dctbl, actbl;
  1400   int ci, tbl;
   850   jpeg_component_info * compptr;
  1401   jpeg_component_info * compptr;
   851   JHUFF_TBL **htblptr;
  1402   JHUFF_TBL **htblptr;
   852   boolean did_dc[NUM_HUFF_TBLS];
  1403   boolean did_dc[NUM_HUFF_TBLS];
   853   boolean did_ac[NUM_HUFF_TBLS];
  1404   boolean did_ac[NUM_HUFF_TBLS];
   854 
  1405 
   855   /* It's important not to apply jpeg_gen_optimal_table more than once
  1406   /* It's important not to apply jpeg_gen_optimal_table more than once
   856    * per table, because it clobbers the input frequency counts!
  1407    * per table, because it clobbers the input frequency counts!
   857    */
  1408    */
       
  1409   if (cinfo->progressive_mode)
       
  1410     /* Flush out buffered data (all we care about is counting the EOB symbol) */
       
  1411     emit_eobrun(entropy);
       
  1412 
   858   MEMZERO(did_dc, SIZEOF(did_dc));
  1413   MEMZERO(did_dc, SIZEOF(did_dc));
   859   MEMZERO(did_ac, SIZEOF(did_ac));
  1414   MEMZERO(did_ac, SIZEOF(did_ac));
   860 
  1415 
   861   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1416   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
   862     compptr = cinfo->cur_comp_info[ci];
  1417     compptr = cinfo->cur_comp_info[ci];
   863     dctbl = compptr->dc_tbl_no;
  1418     /* DC needs no table for refinement scan */
   864     actbl = compptr->ac_tbl_no;
  1419     if (cinfo->Ss == 0 && cinfo->Ah == 0) {
   865     if (! did_dc[dctbl]) {
  1420       tbl = compptr->dc_tbl_no;
   866       htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  1421       if (! did_dc[tbl]) {
   867       if (*htblptr == NULL)
  1422 	htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
   868 	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1423 	if (*htblptr == NULL)
   869       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  1424 	  *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
   870       did_dc[dctbl] = TRUE;
  1425 	jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);
   871     }
  1426 	did_dc[tbl] = TRUE;
   872     if (! did_ac[actbl]) {
  1427       }
   873       htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  1428     }
   874       if (*htblptr == NULL)
  1429     /* AC needs no table when not present */
   875 	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1430     if (cinfo->Se) {
   876       jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  1431       tbl = compptr->ac_tbl_no;
   877       did_ac[actbl] = TRUE;
  1432       if (! did_ac[tbl]) {
   878     }
  1433 	htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
   879   }
  1434 	if (*htblptr == NULL)
   880 }
  1435 	  *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
   881 
  1436 	jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);
   882 
  1437 	did_ac[tbl] = TRUE;
   883 #endif /* ENTROPY_OPT_SUPPORTED */
  1438       }
       
  1439     }
       
  1440   }
       
  1441 }
       
  1442 
       
  1443 
       
  1444 /*
       
  1445  * Initialize for a Huffman-compressed scan.
       
  1446  * If gather_statistics is TRUE, we do not output anything during the scan,
       
  1447  * just count the Huffman symbols used and generate Huffman code tables.
       
  1448  */
       
  1449 
       
  1450 METHODDEF(void)
       
  1451 start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
       
  1452 {
       
  1453   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
       
  1454   int ci, tbl;
       
  1455   jpeg_component_info * compptr;
       
  1456 
       
  1457   if (gather_statistics)
       
  1458     entropy->pub.finish_pass = finish_pass_gather;
       
  1459   else
       
  1460     entropy->pub.finish_pass = finish_pass_huff;
       
  1461 
       
  1462   if (cinfo->progressive_mode) {
       
  1463     entropy->cinfo = cinfo;
       
  1464     entropy->gather_statistics = gather_statistics;
       
  1465 
       
  1466     /* We assume jcmaster.c already validated the scan parameters. */
       
  1467 
       
  1468     /* Select execution routine */
       
  1469     if (cinfo->Ah == 0) {
       
  1470       if (cinfo->Ss == 0)
       
  1471 	entropy->pub.encode_mcu = encode_mcu_DC_first;
       
  1472       else
       
  1473 	entropy->pub.encode_mcu = encode_mcu_AC_first;
       
  1474     } else {
       
  1475       if (cinfo->Ss == 0)
       
  1476 	entropy->pub.encode_mcu = encode_mcu_DC_refine;
       
  1477       else {
       
  1478 	entropy->pub.encode_mcu = encode_mcu_AC_refine;
       
  1479 	/* AC refinement needs a correction bit buffer */
       
  1480 	if (entropy->bit_buffer == NULL)
       
  1481 	  entropy->bit_buffer = (char *)
       
  1482 	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
       
  1483 					MAX_CORR_BITS * SIZEOF(char));
       
  1484       }
       
  1485     }
       
  1486 
       
  1487     /* Initialize AC stuff */
       
  1488     entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;
       
  1489     entropy->EOBRUN = 0;
       
  1490     entropy->BE = 0;
       
  1491   } else {
       
  1492     if (gather_statistics)
       
  1493       entropy->pub.encode_mcu = encode_mcu_gather;
       
  1494     else
       
  1495       entropy->pub.encode_mcu = encode_mcu_huff;
       
  1496   }
       
  1497 
       
  1498   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
       
  1499     compptr = cinfo->cur_comp_info[ci];
       
  1500     /* DC needs no table for refinement scan */
       
  1501     if (cinfo->Ss == 0 && cinfo->Ah == 0) {
       
  1502       tbl = compptr->dc_tbl_no;
       
  1503       if (gather_statistics) {
       
  1504 	/* Check for invalid table index */
       
  1505 	/* (make_c_derived_tbl does this in the other path) */
       
  1506 	if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
       
  1507 	  ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
       
  1508 	/* Allocate and zero the statistics tables */
       
  1509 	/* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
       
  1510 	if (entropy->dc_count_ptrs[tbl] == NULL)
       
  1511 	  entropy->dc_count_ptrs[tbl] = (long *)
       
  1512 	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
       
  1513 					257 * SIZEOF(long));
       
  1514 	MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));
       
  1515       } else {
       
  1516 	/* Compute derived values for Huffman tables */
       
  1517 	/* We may do this more than once for a table, but it's not expensive */
       
  1518 	jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,
       
  1519 				& entropy->dc_derived_tbls[tbl]);
       
  1520       }
       
  1521       /* Initialize DC predictions to 0 */
       
  1522       entropy->saved.last_dc_val[ci] = 0;
       
  1523     }
       
  1524     /* AC needs no table when not present */
       
  1525     if (cinfo->Se) {
       
  1526       tbl = compptr->ac_tbl_no;
       
  1527       if (gather_statistics) {
       
  1528 	if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
       
  1529 	  ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
       
  1530 	if (entropy->ac_count_ptrs[tbl] == NULL)
       
  1531 	  entropy->ac_count_ptrs[tbl] = (long *)
       
  1532 	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
       
  1533 					257 * SIZEOF(long));
       
  1534 	MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));
       
  1535       } else {
       
  1536 	jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,
       
  1537 				& entropy->ac_derived_tbls[tbl]);
       
  1538       }
       
  1539     }
       
  1540   }
       
  1541 
       
  1542   /* Initialize bit buffer to empty */
       
  1543   entropy->saved.put_buffer = 0;
       
  1544   entropy->saved.put_bits = 0;
       
  1545 
       
  1546   /* Initialize restart stuff */
       
  1547   entropy->restarts_to_go = cinfo->restart_interval;
       
  1548   entropy->next_restart_num = 0;
       
  1549 }
   884 
  1550 
   885 
  1551 
   886 /*
  1552 /*
   887  * Module initialization routine for Huffman entropy encoding.
  1553  * Module initialization routine for Huffman entropy encoding.
   888  */
  1554  */
   900   entropy->pub.start_pass = start_pass_huff;
  1566   entropy->pub.start_pass = start_pass_huff;
   901 
  1567 
   902   /* Mark tables unallocated */
  1568   /* Mark tables unallocated */
   903   for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1569   for (i = 0; i < NUM_HUFF_TBLS; i++) {
   904     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1570     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
   905 #ifdef ENTROPY_OPT_SUPPORTED
       
   906     entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  1571     entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
   907 #endif
  1572   }
   908   }
  1573 
   909 }
  1574   if (cinfo->progressive_mode)
       
  1575     entropy->bit_buffer = NULL;	/* needed only in AC refinement scan */
       
  1576 }