kusano 7d535a
/*
kusano 7d535a
 * jchuff.c
kusano 7d535a
 *
kusano 7d535a
 * Copyright (C) 1991-1997, Thomas G. Lane.
kusano 7d535a
 * Modified 2006-2009 by Guido Vollbeding.
kusano 7d535a
 * This file is part of the Independent JPEG Group's software.
kusano 7d535a
 * For conditions of distribution and use, see the accompanying README file.
kusano 7d535a
 *
kusano 7d535a
 * This file contains Huffman entropy encoding routines.
kusano 7d535a
 * Both sequential and progressive modes are supported in this single module.
kusano 7d535a
 *
kusano 7d535a
 * Much of the complexity here has to do with supporting output suspension.
kusano 7d535a
 * If the data destination module demands suspension, we want to be able to
kusano 7d535a
 * back up to the start of the current MCU.  To do this, we copy state
kusano 7d535a
 * variables into local working storage, and update them back to the
kusano 7d535a
 * permanent JPEG objects only upon successful completion of an MCU.
kusano 7d535a
 *
kusano 7d535a
 * We do not support output suspension for the progressive JPEG mode, since
kusano 7d535a
 * the library currently does not allow multiple-scan files to be written
kusano 7d535a
 * with output suspension.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#define JPEG_INTERNALS
kusano 7d535a
#include "jinclude.h"
kusano 7d535a
#include "jpeglib.h"
kusano 7d535a
kusano 7d535a
kusano 7d535a
/* The legal range of a DCT coefficient is
kusano 7d535a
 *  -1024 .. +1023  for 8-bit data;
kusano 7d535a
 * -16384 .. +16383 for 12-bit data.
kusano 7d535a
 * Hence the magnitude should always fit in 10 or 14 bits respectively.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#if BITS_IN_JSAMPLE == 8
kusano 7d535a
#define MAX_COEF_BITS 10
kusano 7d535a
#else
kusano 7d535a
#define MAX_COEF_BITS 14
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
/* Derived data constructed for each Huffman table */
kusano 7d535a
kusano 7d535a
typedef struct {
kusano 7d535a
  unsigned int ehufco[256];	/* code for each symbol */
kusano 7d535a
  char ehufsi[256];		/* length of code for each symbol */
kusano 7d535a
  /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
kusano 7d535a
} c_derived_tbl;
kusano 7d535a
kusano 7d535a
kusano 7d535a
/* Expanded entropy encoder object for Huffman encoding.
kusano 7d535a
 *
kusano 7d535a
 * The savable_state subrecord contains fields that change within an MCU,
kusano 7d535a
 * but must not be updated permanently until we complete the MCU.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
typedef struct {
kusano 7d535a
  INT32 put_buffer;		/* current bit-accumulation buffer */
kusano 7d535a
  int put_bits;			/* # of bits now in it */
kusano 7d535a
  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
kusano 7d535a
} savable_state;
kusano 7d535a
kusano 7d535a
/* This macro is to work around compilers with missing or broken
kusano 7d535a
 * structure assignment.  You'll need to fix this code if you have
kusano 7d535a
 * such a compiler and you change MAX_COMPS_IN_SCAN.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#ifndef NO_STRUCT_ASSIGN
kusano 7d535a
#define ASSIGN_STATE(dest,src)  ((dest) = (src))
kusano 7d535a
#else
kusano 7d535a
#if MAX_COMPS_IN_SCAN == 4
kusano 7d535a
#define ASSIGN_STATE(dest,src)  \
kusano 7d535a
	((dest).put_buffer = (src).put_buffer, \
kusano 7d535a
	 (dest).put_bits = (src).put_bits, \
kusano 7d535a
	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
kusano 7d535a
	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
kusano 7d535a
	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
kusano 7d535a
	 (dest).last_dc_val[3] = (src).last_dc_val[3])
kusano 7d535a
#endif
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
kusano 7d535a
typedef struct {
kusano 7d535a
  struct jpeg_entropy_encoder pub; /* public fields */
kusano 7d535a
kusano 7d535a
  savable_state saved;		/* Bit buffer & DC state at start of MCU */
kusano 7d535a
kusano 7d535a
  /* These fields are NOT loaded into local working state. */
kusano 7d535a
  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
kusano 7d535a
  int next_restart_num;		/* next restart number to write (0-7) */
kusano 7d535a
kusano 7d535a
  /* Pointers to derived tables (these workspaces have image lifespan) */
kusano 7d535a
  c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
kusano 7d535a
  c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
kusano 7d535a
kusano 7d535a
  /* Statistics tables for optimization */
kusano 7d535a
  long * dc_count_ptrs[NUM_HUFF_TBLS];
kusano 7d535a
  long * ac_count_ptrs[NUM_HUFF_TBLS];
kusano 7d535a
kusano 7d535a
  /* Following fields used only in progressive mode */
kusano 7d535a
kusano 7d535a
  /* Mode flag: TRUE for optimization, FALSE for actual data output */
kusano 7d535a
  boolean gather_statistics;
kusano 7d535a
kusano 7d535a
  /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
kusano 7d535a
   */
kusano 7d535a
  JOCTET * next_output_byte;	/* => next byte to write in buffer */
kusano 7d535a
  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
kusano 7d535a
  j_compress_ptr cinfo;		/* link to cinfo (needed for dump_buffer) */
kusano 7d535a
kusano 7d535a
  /* Coding status for AC components */
kusano 7d535a
  int ac_tbl_no;		/* the table number of the single component */
kusano 7d535a
  unsigned int EOBRUN;		/* run length of EOBs */
kusano 7d535a
  unsigned int BE;		/* # of buffered correction bits before MCU */
kusano 7d535a
  char * bit_buffer;		/* buffer for correction bits (1 per char) */
kusano 7d535a
  /* packing correction bits tightly would save some space but cost time... */
kusano 7d535a
} huff_entropy_encoder;
kusano 7d535a
kusano 7d535a
typedef huff_entropy_encoder * huff_entropy_ptr;
kusano 7d535a
kusano 7d535a
/* Working state while writing an MCU (sequential mode).
kusano 7d535a
 * This struct contains all the fields that are needed by subroutines.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
typedef struct {
kusano 7d535a
  JOCTET * next_output_byte;	/* => next byte to write in buffer */
kusano 7d535a
  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
kusano 7d535a
  savable_state cur;		/* Current bit buffer & DC state */
kusano 7d535a
  j_compress_ptr cinfo;		/* dump_buffer needs access to this */
kusano 7d535a
} working_state;
kusano 7d535a
kusano 7d535a
/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
kusano 7d535a
 * buffer can hold.  Larger sizes may slightly improve compression, but
kusano 7d535a
 * 1000 is already well into the realm of overkill.
kusano 7d535a
 * The minimum safe size is 64 bits.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#define MAX_CORR_BITS  1000	/* Max # of correction bits I can buffer */
kusano 7d535a
kusano 7d535a
/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
kusano 7d535a
 * We assume that int right shift is unsigned if INT32 right shift is,
kusano 7d535a
 * which should be safe.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#ifdef RIGHT_SHIFT_IS_UNSIGNED
kusano 7d535a
#define ISHIFT_TEMPS	int ishift_temp;
kusano 7d535a
#define IRIGHT_SHIFT(x,shft)  \
kusano 7d535a
	((ishift_temp = (x)) < 0 ? \
kusano 7d535a
	 (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
kusano 7d535a
	 (ishift_temp >> (shft)))
kusano 7d535a
#else
kusano 7d535a
#define ISHIFT_TEMPS
kusano 7d535a
#define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
kusano 7d535a
#endif
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Compute the derived values for a Huffman table.
kusano 7d535a
 * This routine also performs some validation checks on the table.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
kusano 7d535a
			 c_derived_tbl ** pdtbl)
kusano 7d535a
{
kusano 7d535a
  JHUFF_TBL *htbl;
kusano 7d535a
  c_derived_tbl *dtbl;
kusano 7d535a
  int p, i, l, lastp, si, maxsymbol;
kusano 7d535a
  char huffsize[257];
kusano 7d535a
  unsigned int huffcode[257];
kusano 7d535a
  unsigned int code;
kusano 7d535a
kusano 7d535a
  /* Note that huffsize[] and huffcode[] are filled in code-length order,
kusano 7d535a
   * paralleling the order of the symbols themselves in htbl->huffval[].
kusano 7d535a
   */
kusano 7d535a
kusano 7d535a
  /* Find the input Huffman table */
kusano 7d535a
  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
kusano 7d535a
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
kusano 7d535a
  htbl =
kusano 7d535a
    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
kusano 7d535a
  if (htbl == NULL)
kusano 7d535a
    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
kusano 7d535a
kusano 7d535a
  /* Allocate a workspace if we haven't already done so. */
kusano 7d535a
  if (*pdtbl == NULL)
kusano 7d535a
    *pdtbl = (c_derived_tbl *)
kusano 7d535a
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
kusano 7d535a
				  SIZEOF(c_derived_tbl));
kusano 7d535a
  dtbl = *pdtbl;
kusano 7d535a
  
kusano 7d535a
  /* Figure C.1: make table of Huffman code length for each symbol */
kusano 7d535a
kusano 7d535a
  p = 0;
kusano 7d535a
  for (l = 1; l <= 16; l++) {
kusano 7d535a
    i = (int) htbl->bits[l];
kusano 7d535a
    if (i < 0 || p + i > 256)	/* protect against table overrun */
kusano 7d535a
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
kusano 7d535a
    while (i--)
kusano 7d535a
      huffsize[p++] = (char) l;
kusano 7d535a
  }
kusano 7d535a
  huffsize[p] = 0;
kusano 7d535a
  lastp = p;
kusano 7d535a
  
kusano 7d535a
  /* Figure C.2: generate the codes themselves */
kusano 7d535a
  /* We also validate that the counts represent a legal Huffman code tree. */
kusano 7d535a
kusano 7d535a
  code = 0;
kusano 7d535a
  si = huffsize[0];
kusano 7d535a
  p = 0;
kusano 7d535a
  while (huffsize[p]) {
kusano 7d535a
    while (((int) huffsize[p]) == si) {
kusano 7d535a
      huffcode[p++] = code;
kusano 7d535a
      code++;
kusano 7d535a
    }
kusano 7d535a
    /* code is now 1 more than the last code used for codelength si; but
kusano 7d535a
     * it must still fit in si bits, since no code is allowed to be all ones.
kusano 7d535a
     */
kusano 7d535a
    if (((INT32) code) >= (((INT32) 1) << si))
kusano 7d535a
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
kusano 7d535a
    code <<= 1;
kusano 7d535a
    si++;
kusano 7d535a
  }
kusano 7d535a
  
kusano 7d535a
  /* Figure C.3: generate encoding tables */
kusano 7d535a
  /* These are code and size indexed by symbol value */
kusano 7d535a
kusano 7d535a
  /* Set all codeless symbols to have code length 0;
kusano 7d535a
   * this lets us detect duplicate VAL entries here, and later
kusano 7d535a
   * allows emit_bits to detect any attempt to emit such symbols.
kusano 7d535a
   */
kusano 7d535a
  MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
kusano 7d535a
kusano 7d535a
  /* This is also a convenient place to check for out-of-range
kusano 7d535a
   * and duplicated VAL entries.  We allow 0..255 for AC symbols
kusano 7d535a
   * but only 0..15 for DC.  (We could constrain them further
kusano 7d535a
   * based on data depth and mode, but this seems enough.)
kusano 7d535a
   */
kusano 7d535a
  maxsymbol = isDC ? 15 : 255;
kusano 7d535a
kusano 7d535a
  for (p = 0; p < lastp; p++) {
kusano 7d535a
    i = htbl->huffval[p];
kusano 7d535a
    if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
kusano 7d535a
      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
kusano 7d535a
    dtbl->ehufco[i] = huffcode[p];
kusano 7d535a
    dtbl->ehufsi[i] = huffsize[p];
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/* Outputting bytes to the file.
kusano 7d535a
 * NB: these must be called only when actually outputting,
kusano 7d535a
 * that is, entropy->gather_statistics == FALSE.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
/* Emit a byte, taking 'action' if must suspend. */
kusano 7d535a
#define emit_byte_s(state,val,action)  \
kusano 7d535a
	{ *(state)->next_output_byte++ = (JOCTET) (val);  \
kusano 7d535a
	  if (--(state)->free_in_buffer == 0)  \
kusano 7d535a
	    if (! dump_buffer_s(state))  \
kusano 7d535a
	      { action; } }
kusano 7d535a
kusano 7d535a
/* Emit a byte */
kusano 7d535a
#define emit_byte_e(entropy,val)  \
kusano 7d535a
	{ *(entropy)->next_output_byte++ = (JOCTET) (val);  \
kusano 7d535a
	  if (--(entropy)->free_in_buffer == 0)  \
kusano 7d535a
	    dump_buffer_e(entropy); }
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(boolean)
kusano 7d535a
dump_buffer_s (working_state * state)
kusano 7d535a
/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
kusano 7d535a
{
kusano 7d535a
  struct jpeg_destination_mgr * dest = state->cinfo->dest;
kusano 7d535a
kusano 7d535a
  if (! (*dest->empty_output_buffer) (state->cinfo))
kusano 7d535a
    return FALSE;
kusano 7d535a
  /* After a successful buffer dump, must reset buffer pointers */
kusano 7d535a
  state->next_output_byte = dest->next_output_byte;
kusano 7d535a
  state->free_in_buffer = dest->free_in_buffer;
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
dump_buffer_e (huff_entropy_ptr entropy)
kusano 7d535a
/* Empty the output buffer; we do not support suspension in this case. */
kusano 7d535a
{
kusano 7d535a
  struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
kusano 7d535a
kusano 7d535a
  if (! (*dest->empty_output_buffer) (entropy->cinfo))
kusano 7d535a
    ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
kusano 7d535a
  /* After a successful buffer dump, must reset buffer pointers */
kusano 7d535a
  entropy->next_output_byte = dest->next_output_byte;
kusano 7d535a
  entropy->free_in_buffer = dest->free_in_buffer;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/* Outputting bits to the file */
kusano 7d535a
kusano 7d535a
/* Only the right 24 bits of put_buffer are used; the valid bits are
kusano 7d535a
 * left-justified in this part.  At most 16 bits can be passed to emit_bits
kusano 7d535a
 * in one call, and we never retain more than 7 bits in put_buffer
kusano 7d535a
 * between calls, so 24 bits are sufficient.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
INLINE
kusano 7d535a
LOCAL(boolean)
kusano 7d535a
emit_bits_s (working_state * state, unsigned int code, int size)
kusano 7d535a
/* Emit some bits; return TRUE if successful, FALSE if must suspend */
kusano 7d535a
{
kusano 7d535a
  /* This routine is heavily used, so it's worth coding tightly. */
kusano 7d535a
  register INT32 put_buffer = (INT32) code;
kusano 7d535a
  register int put_bits = state->cur.put_bits;
kusano 7d535a
kusano 7d535a
  /* if size is 0, caller used an invalid Huffman table entry */
kusano 7d535a
  if (size == 0)
kusano 7d535a
    ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
kusano 7d535a
kusano 7d535a
  put_buffer &= (((INT32) 1)<
kusano 7d535a
  
kusano 7d535a
  put_bits += size;		/* new number of bits in buffer */
kusano 7d535a
  
kusano 7d535a
  put_buffer <<= 24 - put_bits; /* align incoming bits */
kusano 7d535a
kusano 7d535a
  put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
kusano 7d535a
  
kusano 7d535a
  while (put_bits >= 8) {
kusano 7d535a
    int c = (int) ((put_buffer >> 16) & 0xFF);
kusano 7d535a
    
kusano 7d535a
    emit_byte_s(state, c, return FALSE);
kusano 7d535a
    if (c == 0xFF) {		/* need to stuff a zero byte? */
kusano 7d535a
      emit_byte_s(state, 0, return FALSE);
kusano 7d535a
    }
kusano 7d535a
    put_buffer <<= 8;
kusano 7d535a
    put_bits -= 8;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  state->cur.put_buffer = put_buffer; /* update state variables */
kusano 7d535a
  state->cur.put_bits = put_bits;
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
INLINE
kusano 7d535a
LOCAL(void)
kusano 7d535a
emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
kusano 7d535a
/* Emit some bits, unless we are in gather mode */
kusano 7d535a
{
kusano 7d535a
  /* This routine is heavily used, so it's worth coding tightly. */
kusano 7d535a
  register INT32 put_buffer = (INT32) code;
kusano 7d535a
  register int put_bits = entropy->saved.put_bits;
kusano 7d535a
kusano 7d535a
  /* if size is 0, caller used an invalid Huffman table entry */
kusano 7d535a
  if (size == 0)
kusano 7d535a
    ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
kusano 7d535a
kusano 7d535a
  if (entropy->gather_statistics)
kusano 7d535a
    return;			/* do nothing if we're only getting stats */
kusano 7d535a
kusano 7d535a
  put_buffer &= (((INT32) 1)<
kusano 7d535a
  
kusano 7d535a
  put_bits += size;		/* new number of bits in buffer */
kusano 7d535a
kusano 7d535a
  put_buffer <<= 24 - put_bits; /* align incoming bits */
kusano 7d535a
kusano 7d535a
  /* and merge with old buffer contents */
kusano 7d535a
  put_buffer |= entropy->saved.put_buffer;
kusano 7d535a
kusano 7d535a
  while (put_bits >= 8) {
kusano 7d535a
    int c = (int) ((put_buffer >> 16) & 0xFF);
kusano 7d535a
kusano 7d535a
    emit_byte_e(entropy, c);
kusano 7d535a
    if (c == 0xFF) {		/* need to stuff a zero byte? */
kusano 7d535a
      emit_byte_e(entropy, 0);
kusano 7d535a
    }
kusano 7d535a
    put_buffer <<= 8;
kusano 7d535a
    put_bits -= 8;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  entropy->saved.put_buffer = put_buffer; /* update variables */
kusano 7d535a
  entropy->saved.put_bits = put_bits;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(boolean)
kusano 7d535a
flush_bits_s (working_state * state)
kusano 7d535a
{
kusano 7d535a
  if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */
kusano 7d535a
    return FALSE;
kusano 7d535a
  state->cur.put_buffer = 0;	     /* and reset bit-buffer to empty */
kusano 7d535a
  state->cur.put_bits = 0;
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
flush_bits_e (huff_entropy_ptr entropy)
kusano 7d535a
{
kusano 7d535a
  emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
kusano 7d535a
  entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
kusano 7d535a
  entropy->saved.put_bits = 0;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Emit (or just count) a Huffman symbol.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
INLINE
kusano 7d535a
LOCAL(void)
kusano 7d535a
emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
kusano 7d535a
{
kusano 7d535a
  if (entropy->gather_statistics)
kusano 7d535a
    entropy->dc_count_ptrs[tbl_no][symbol]++;
kusano 7d535a
  else {
kusano 7d535a
    c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];
kusano 7d535a
    emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
INLINE
kusano 7d535a
LOCAL(void)
kusano 7d535a
emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
kusano 7d535a
{
kusano 7d535a
  if (entropy->gather_statistics)
kusano 7d535a
    entropy->ac_count_ptrs[tbl_no][symbol]++;
kusano 7d535a
  else {
kusano 7d535a
    c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];
kusano 7d535a
    emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Emit bits from a correction bit buffer.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
kusano 7d535a
		    unsigned int nbits)
kusano 7d535a
{
kusano 7d535a
  if (entropy->gather_statistics)
kusano 7d535a
    return;			/* no real work */
kusano 7d535a
kusano 7d535a
  while (nbits > 0) {
kusano 7d535a
    emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
kusano 7d535a
    bufstart++;
kusano 7d535a
    nbits--;
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Emit any pending EOBRUN symbol.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
emit_eobrun (huff_entropy_ptr entropy)
kusano 7d535a
{
kusano 7d535a
  register int temp, nbits;
kusano 7d535a
kusano 7d535a
  if (entropy->EOBRUN > 0) {	/* if there is any pending EOBRUN */
kusano 7d535a
    temp = entropy->EOBRUN;
kusano 7d535a
    nbits = 0;
kusano 7d535a
    while ((temp >>= 1))
kusano 7d535a
      nbits++;
kusano 7d535a
    /* safety check: shouldn't happen given limited correction-bit buffer */
kusano 7d535a
    if (nbits > 14)
kusano 7d535a
      ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
kusano 7d535a
kusano 7d535a
    emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
kusano 7d535a
    if (nbits)
kusano 7d535a
      emit_bits_e(entropy, entropy->EOBRUN, nbits);
kusano 7d535a
kusano 7d535a
    entropy->EOBRUN = 0;
kusano 7d535a
kusano 7d535a
    /* Emit any buffered correction bits */
kusano 7d535a
    emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
kusano 7d535a
    entropy->BE = 0;
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Emit a restart marker & resynchronize predictions.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
LOCAL(boolean)
kusano 7d535a
emit_restart_s (working_state * state, int restart_num)
kusano 7d535a
{
kusano 7d535a
  int ci;
kusano 7d535a
kusano 7d535a
  if (! flush_bits_s(state))
kusano 7d535a
    return FALSE;
kusano 7d535a
kusano 7d535a
  emit_byte_s(state, 0xFF, return FALSE);
kusano 7d535a
  emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);
kusano 7d535a
kusano 7d535a
  /* Re-initialize DC predictions to 0 */
kusano 7d535a
  for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
kusano 7d535a
    state->cur.last_dc_val[ci] = 0;
kusano 7d535a
kusano 7d535a
  /* The restart counter is not updated until we successfully write the MCU. */
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
emit_restart_e (huff_entropy_ptr entropy, int restart_num)
kusano 7d535a
{
kusano 7d535a
  int ci;
kusano 7d535a
kusano 7d535a
  emit_eobrun(entropy);
kusano 7d535a
kusano 7d535a
  if (! entropy->gather_statistics) {
kusano 7d535a
    flush_bits_e(entropy);
kusano 7d535a
    emit_byte_e(entropy, 0xFF);
kusano 7d535a
    emit_byte_e(entropy, JPEG_RST0 + restart_num);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  if (entropy->cinfo->Ss == 0) {
kusano 7d535a
    /* Re-initialize DC predictions to 0 */
kusano 7d535a
    for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
kusano 7d535a
      entropy->saved.last_dc_val[ci] = 0;
kusano 7d535a
  } else {
kusano 7d535a
    /* Re-initialize all AC-related fields to 0 */
kusano 7d535a
    entropy->EOBRUN = 0;
kusano 7d535a
    entropy->BE = 0;
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * MCU encoding for DC initial scan (either spectral selection,
kusano 7d535a
 * or first pass of successive approximation).
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(boolean)
kusano 7d535a
encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  register int temp, temp2;
kusano 7d535a
  register int nbits;
kusano 7d535a
  int blkn, ci;
kusano 7d535a
  int Al = cinfo->Al;
kusano 7d535a
  JBLOCKROW block;
kusano 7d535a
  jpeg_component_info * compptr;
kusano 7d535a
  ISHIFT_TEMPS
kusano 7d535a
kusano 7d535a
  entropy->next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Emit restart marker if needed */
kusano 7d535a
  if (cinfo->restart_interval)
kusano 7d535a
    if (entropy->restarts_to_go == 0)
kusano 7d535a
      emit_restart_e(entropy, entropy->next_restart_num);
kusano 7d535a
kusano 7d535a
  /* Encode the MCU data blocks */
kusano 7d535a
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
kusano 7d535a
    block = MCU_data[blkn];
kusano 7d535a
    ci = cinfo->MCU_membership[blkn];
kusano 7d535a
    compptr = cinfo->cur_comp_info[ci];
kusano 7d535a
kusano 7d535a
    /* Compute the DC value after the required point transform by Al.
kusano 7d535a
     * This is simply an arithmetic right shift.
kusano 7d535a
     */
kusano 7d535a
    temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
kusano 7d535a
kusano 7d535a
    /* DC differences are figured on the point-transformed values. */
kusano 7d535a
    temp = temp2 - entropy->saved.last_dc_val[ci];
kusano 7d535a
    entropy->saved.last_dc_val[ci] = temp2;
kusano 7d535a
kusano 7d535a
    /* Encode the DC coefficient difference per section G.1.2.1 */
kusano 7d535a
    temp2 = temp;
kusano 7d535a
    if (temp < 0) {
kusano 7d535a
      temp = -temp;		/* temp is abs value of input */
kusano 7d535a
      /* For a negative input, want temp2 = bitwise complement of abs(input) */
kusano 7d535a
      /* This code assumes we are on a two's complement machine */
kusano 7d535a
      temp2--;
kusano 7d535a
    }
kusano 7d535a
    
kusano 7d535a
    /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
    nbits = 0;
kusano 7d535a
    while (temp) {
kusano 7d535a
      nbits++;
kusano 7d535a
      temp >>= 1;
kusano 7d535a
    }
kusano 7d535a
    /* Check for out-of-range coefficient values.
kusano 7d535a
     * Since we're encoding a difference, the range limit is twice as much.
kusano 7d535a
     */
kusano 7d535a
    if (nbits > MAX_COEF_BITS+1)
kusano 7d535a
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
kusano 7d535a
    
kusano 7d535a
    /* Count/emit the Huffman-coded symbol for the number of bits */
kusano 7d535a
    emit_dc_symbol(entropy, compptr->dc_tbl_no, nbits);
kusano 7d535a
    
kusano 7d535a
    /* Emit that number of bits of the value, if positive, */
kusano 7d535a
    /* or the complement of its magnitude, if negative. */
kusano 7d535a
    if (nbits)			/* emit_bits rejects calls with size 0 */
kusano 7d535a
      emit_bits_e(entropy, (unsigned int) temp2, nbits);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  cinfo->dest->next_output_byte = entropy->next_output_byte;
kusano 7d535a
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Update restart-interval state too */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0) {
kusano 7d535a
      entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
      entropy->next_restart_num++;
kusano 7d535a
      entropy->next_restart_num &= 7;
kusano 7d535a
    }
kusano 7d535a
    entropy->restarts_to_go--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * MCU encoding for AC initial scan (either spectral selection,
kusano 7d535a
 * or first pass of successive approximation).
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(boolean)
kusano 7d535a
encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  register int temp, temp2;
kusano 7d535a
  register int nbits;
kusano 7d535a
  register int r, k;
kusano 7d535a
  int Se, Al;
kusano 7d535a
  const int * natural_order;
kusano 7d535a
  JBLOCKROW block;
kusano 7d535a
kusano 7d535a
  entropy->next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Emit restart marker if needed */
kusano 7d535a
  if (cinfo->restart_interval)
kusano 7d535a
    if (entropy->restarts_to_go == 0)
kusano 7d535a
      emit_restart_e(entropy, entropy->next_restart_num);
kusano 7d535a
kusano 7d535a
  Se = cinfo->Se;
kusano 7d535a
  Al = cinfo->Al;
kusano 7d535a
  natural_order = cinfo->natural_order;
kusano 7d535a
kusano 7d535a
  /* Encode the MCU data block */
kusano 7d535a
  block = MCU_data[0];
kusano 7d535a
kusano 7d535a
  /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
kusano 7d535a
  
kusano 7d535a
  r = 0;			/* r = run length of zeros */
kusano 7d535a
   
kusano 7d535a
  for (k = cinfo->Ss; k <= Se; k++) {
kusano 7d535a
    if ((temp = (*block)[natural_order[k]]) == 0) {
kusano 7d535a
      r++;
kusano 7d535a
      continue;
kusano 7d535a
    }
kusano 7d535a
    /* We must apply the point transform by Al.  For AC coefficients this
kusano 7d535a
     * is an integer division with rounding towards 0.  To do this portably
kusano 7d535a
     * in C, we shift after obtaining the absolute value; so the code is
kusano 7d535a
     * interwoven with finding the abs value (temp) and output bits (temp2).
kusano 7d535a
     */
kusano 7d535a
    if (temp < 0) {
kusano 7d535a
      temp = -temp;		/* temp is abs value of input */
kusano 7d535a
      temp >>= Al;		/* apply the point transform */
kusano 7d535a
      /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
kusano 7d535a
      temp2 = ~temp;
kusano 7d535a
    } else {
kusano 7d535a
      temp >>= Al;		/* apply the point transform */
kusano 7d535a
      temp2 = temp;
kusano 7d535a
    }
kusano 7d535a
    /* Watch out for case that nonzero coef is zero after point transform */
kusano 7d535a
    if (temp == 0) {
kusano 7d535a
      r++;
kusano 7d535a
      continue;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Emit any pending EOBRUN */
kusano 7d535a
    if (entropy->EOBRUN > 0)
kusano 7d535a
      emit_eobrun(entropy);
kusano 7d535a
    /* if run length > 15, must emit special run-length-16 codes (0xF0) */
kusano 7d535a
    while (r > 15) {
kusano 7d535a
      emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
kusano 7d535a
      r -= 16;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
    nbits = 1;			/* there must be at least one 1 bit */
kusano 7d535a
    while ((temp >>= 1))
kusano 7d535a
      nbits++;
kusano 7d535a
    /* Check for out-of-range coefficient values */
kusano 7d535a
    if (nbits > MAX_COEF_BITS)
kusano 7d535a
      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
kusano 7d535a
kusano 7d535a
    /* Count/emit Huffman symbol for run length / number of bits */
kusano 7d535a
    emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
kusano 7d535a
kusano 7d535a
    /* Emit that number of bits of the value, if positive, */
kusano 7d535a
    /* or the complement of its magnitude, if negative. */
kusano 7d535a
    emit_bits_e(entropy, (unsigned int) temp2, nbits);
kusano 7d535a
kusano 7d535a
    r = 0;			/* reset zero run length */
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  if (r > 0) {			/* If there are trailing zeroes, */
kusano 7d535a
    entropy->EOBRUN++;		/* count an EOB */
kusano 7d535a
    if (entropy->EOBRUN == 0x7FFF)
kusano 7d535a
      emit_eobrun(entropy);	/* force it out to avoid overflow */
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  cinfo->dest->next_output_byte = entropy->next_output_byte;
kusano 7d535a
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Update restart-interval state too */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0) {
kusano 7d535a
      entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
      entropy->next_restart_num++;
kusano 7d535a
      entropy->next_restart_num &= 7;
kusano 7d535a
    }
kusano 7d535a
    entropy->restarts_to_go--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * MCU encoding for DC successive approximation refinement scan.
kusano 7d535a
 * Note: we assume such scans can be multi-component, although the spec
kusano 7d535a
 * is not very clear on the point.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(boolean)
kusano 7d535a
encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  register int temp;
kusano 7d535a
  int blkn;
kusano 7d535a
  int Al = cinfo->Al;
kusano 7d535a
  JBLOCKROW block;
kusano 7d535a
kusano 7d535a
  entropy->next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Emit restart marker if needed */
kusano 7d535a
  if (cinfo->restart_interval)
kusano 7d535a
    if (entropy->restarts_to_go == 0)
kusano 7d535a
      emit_restart_e(entropy, entropy->next_restart_num);
kusano 7d535a
kusano 7d535a
  /* Encode the MCU data blocks */
kusano 7d535a
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
kusano 7d535a
    block = MCU_data[blkn];
kusano 7d535a
kusano 7d535a
    /* We simply emit the Al'th bit of the DC coefficient value. */
kusano 7d535a
    temp = (*block)[0];
kusano 7d535a
    emit_bits_e(entropy, (unsigned int) (temp >> Al), 1);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  cinfo->dest->next_output_byte = entropy->next_output_byte;
kusano 7d535a
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Update restart-interval state too */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0) {
kusano 7d535a
      entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
      entropy->next_restart_num++;
kusano 7d535a
      entropy->next_restart_num &= 7;
kusano 7d535a
    }
kusano 7d535a
    entropy->restarts_to_go--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * MCU encoding for AC successive approximation refinement scan.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(boolean)
kusano 7d535a
encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  register int temp;
kusano 7d535a
  register int r, k;
kusano 7d535a
  int EOB;
kusano 7d535a
  char *BR_buffer;
kusano 7d535a
  unsigned int BR;
kusano 7d535a
  int Se, Al;
kusano 7d535a
  const int * natural_order;
kusano 7d535a
  JBLOCKROW block;
kusano 7d535a
  int absvalues[DCTSIZE2];
kusano 7d535a
kusano 7d535a
  entropy->next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Emit restart marker if needed */
kusano 7d535a
  if (cinfo->restart_interval)
kusano 7d535a
    if (entropy->restarts_to_go == 0)
kusano 7d535a
      emit_restart_e(entropy, entropy->next_restart_num);
kusano 7d535a
kusano 7d535a
  Se = cinfo->Se;
kusano 7d535a
  Al = cinfo->Al;
kusano 7d535a
  natural_order = cinfo->natural_order;
kusano 7d535a
kusano 7d535a
  /* Encode the MCU data block */
kusano 7d535a
  block = MCU_data[0];
kusano 7d535a
kusano 7d535a
  /* It is convenient to make a pre-pass to determine the transformed
kusano 7d535a
   * coefficients' absolute values and the EOB position.
kusano 7d535a
   */
kusano 7d535a
  EOB = 0;
kusano 7d535a
  for (k = cinfo->Ss; k <= Se; k++) {
kusano 7d535a
    temp = (*block)[natural_order[k]];
kusano 7d535a
    /* We must apply the point transform by Al.  For AC coefficients this
kusano 7d535a
     * is an integer division with rounding towards 0.  To do this portably
kusano 7d535a
     * in C, we shift after obtaining the absolute value.
kusano 7d535a
     */
kusano 7d535a
    if (temp < 0)
kusano 7d535a
      temp = -temp;		/* temp is abs value of input */
kusano 7d535a
    temp >>= Al;		/* apply the point transform */
kusano 7d535a
    absvalues[k] = temp;	/* save abs value for main pass */
kusano 7d535a
    if (temp == 1)
kusano 7d535a
      EOB = k;			/* EOB = index of last newly-nonzero coef */
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
kusano 7d535a
  
kusano 7d535a
  r = 0;			/* r = run length of zeros */
kusano 7d535a
  BR = 0;			/* BR = count of buffered bits added now */
kusano 7d535a
  BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
kusano 7d535a
kusano 7d535a
  for (k = cinfo->Ss; k <= Se; k++) {
kusano 7d535a
    if ((temp = absvalues[k]) == 0) {
kusano 7d535a
      r++;
kusano 7d535a
      continue;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Emit any required ZRLs, but not if they can be folded into EOB */
kusano 7d535a
    while (r > 15 && k <= EOB) {
kusano 7d535a
      /* emit any pending EOBRUN and the BE correction bits */
kusano 7d535a
      emit_eobrun(entropy);
kusano 7d535a
      /* Emit ZRL */
kusano 7d535a
      emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
kusano 7d535a
      r -= 16;
kusano 7d535a
      /* Emit buffered correction bits that must be associated with ZRL */
kusano 7d535a
      emit_buffered_bits(entropy, BR_buffer, BR);
kusano 7d535a
      BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
kusano 7d535a
      BR = 0;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* If the coef was previously nonzero, it only needs a correction bit.
kusano 7d535a
     * NOTE: a straight translation of the spec's figure G.7 would suggest
kusano 7d535a
     * that we also need to test r > 15.  But if r > 15, we can only get here
kusano 7d535a
     * if k > EOB, which implies that this coefficient is not 1.
kusano 7d535a
     */
kusano 7d535a
    if (temp > 1) {
kusano 7d535a
      /* The correction bit is the next bit of the absolute value. */
kusano 7d535a
      BR_buffer[BR++] = (char) (temp & 1);
kusano 7d535a
      continue;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Emit any pending EOBRUN and the BE correction bits */
kusano 7d535a
    emit_eobrun(entropy);
kusano 7d535a
kusano 7d535a
    /* Count/emit Huffman symbol for run length / number of bits */
kusano 7d535a
    emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
kusano 7d535a
kusano 7d535a
    /* Emit output bit for newly-nonzero coef */
kusano 7d535a
    temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;
kusano 7d535a
    emit_bits_e(entropy, (unsigned int) temp, 1);
kusano 7d535a
kusano 7d535a
    /* Emit buffered correction bits that must be associated with this code */
kusano 7d535a
    emit_buffered_bits(entropy, BR_buffer, BR);
kusano 7d535a
    BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
kusano 7d535a
    BR = 0;
kusano 7d535a
    r = 0;			/* reset zero run length */
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  if (r > 0 || BR > 0) {	/* If there are trailing zeroes, */
kusano 7d535a
    entropy->EOBRUN++;		/* count an EOB */
kusano 7d535a
    entropy->BE += BR;		/* concat my correction bits to older ones */
kusano 7d535a
    /* We force out the EOB if we risk either:
kusano 7d535a
     * 1. overflow of the EOB counter;
kusano 7d535a
     * 2. overflow of the correction bit buffer during the next MCU.
kusano 7d535a
     */
kusano 7d535a
    if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
kusano 7d535a
      emit_eobrun(entropy);
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  cinfo->dest->next_output_byte = entropy->next_output_byte;
kusano 7d535a
  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
kusano 7d535a
kusano 7d535a
  /* Update restart-interval state too */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0) {
kusano 7d535a
      entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
      entropy->next_restart_num++;
kusano 7d535a
      entropy->next_restart_num &= 7;
kusano 7d535a
    }
kusano 7d535a
    entropy->restarts_to_go--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/* Encode a single block's worth of coefficients */
kusano 7d535a
kusano 7d535a
LOCAL(boolean)
kusano 7d535a
encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
kusano 7d535a
		  c_derived_tbl *dctbl, c_derived_tbl *actbl)
kusano 7d535a
{
kusano 7d535a
  register int temp, temp2;
kusano 7d535a
  register int nbits;
kusano 7d535a
  register int k, r, i;
kusano 7d535a
  int Se = state->cinfo->lim_Se;
kusano 7d535a
  const int * natural_order = state->cinfo->natural_order;
kusano 7d535a
kusano 7d535a
  /* Encode the DC coefficient difference per section F.1.2.1 */
kusano 7d535a
kusano 7d535a
  temp = temp2 = block[0] - last_dc_val;
kusano 7d535a
kusano 7d535a
  if (temp < 0) {
kusano 7d535a
    temp = -temp;		/* temp is abs value of input */
kusano 7d535a
    /* For a negative input, want temp2 = bitwise complement of abs(input) */
kusano 7d535a
    /* This code assumes we are on a two's complement machine */
kusano 7d535a
    temp2--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
  nbits = 0;
kusano 7d535a
  while (temp) {
kusano 7d535a
    nbits++;
kusano 7d535a
    temp >>= 1;
kusano 7d535a
  }
kusano 7d535a
  /* Check for out-of-range coefficient values.
kusano 7d535a
   * Since we're encoding a difference, the range limit is twice as much.
kusano 7d535a
   */
kusano 7d535a
  if (nbits > MAX_COEF_BITS+1)
kusano 7d535a
    ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
kusano 7d535a
kusano 7d535a
  /* Emit the Huffman-coded symbol for the number of bits */
kusano 7d535a
  if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
kusano 7d535a
    return FALSE;
kusano 7d535a
kusano 7d535a
  /* Emit that number of bits of the value, if positive, */
kusano 7d535a
  /* or the complement of its magnitude, if negative. */
kusano 7d535a
  if (nbits)			/* emit_bits rejects calls with size 0 */
kusano 7d535a
    if (! emit_bits_s(state, (unsigned int) temp2, nbits))
kusano 7d535a
      return FALSE;
kusano 7d535a
kusano 7d535a
  /* Encode the AC coefficients per section F.1.2.2 */
kusano 7d535a
kusano 7d535a
  r = 0;			/* r = run length of zeros */
kusano 7d535a
kusano 7d535a
  for (k = 1; k <= Se; k++) {
kusano 7d535a
    if ((temp = block[natural_order[k]]) == 0) {
kusano 7d535a
      r++;
kusano 7d535a
    } else {
kusano 7d535a
      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
kusano 7d535a
      while (r > 15) {
kusano 7d535a
	if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
kusano 7d535a
	  return FALSE;
kusano 7d535a
	r -= 16;
kusano 7d535a
      }
kusano 7d535a
kusano 7d535a
      temp2 = temp;
kusano 7d535a
      if (temp < 0) {
kusano 7d535a
	temp = -temp;		/* temp is abs value of input */
kusano 7d535a
	/* This code assumes we are on a two's complement machine */
kusano 7d535a
	temp2--;
kusano 7d535a
      }
kusano 7d535a
kusano 7d535a
      /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
      nbits = 1;		/* there must be at least one 1 bit */
kusano 7d535a
      while ((temp >>= 1))
kusano 7d535a
	nbits++;
kusano 7d535a
      /* Check for out-of-range coefficient values */
kusano 7d535a
      if (nbits > MAX_COEF_BITS)
kusano 7d535a
	ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
kusano 7d535a
kusano 7d535a
      /* Emit Huffman symbol for run length / number of bits */
kusano 7d535a
      i = (r << 4) + nbits;
kusano 7d535a
      if (! emit_bits_s(state, actbl->ehufco[i], actbl->ehufsi[i]))
kusano 7d535a
	return FALSE;
kusano 7d535a
kusano 7d535a
      /* Emit that number of bits of the value, if positive, */
kusano 7d535a
      /* or the complement of its magnitude, if negative. */
kusano 7d535a
      if (! emit_bits_s(state, (unsigned int) temp2, nbits))
kusano 7d535a
	return FALSE;
kusano 7d535a
kusano 7d535a
      r = 0;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* If the last coef(s) were zero, emit an end-of-block code */
kusano 7d535a
  if (r > 0)
kusano 7d535a
    if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
kusano 7d535a
      return FALSE;
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Encode and output one MCU's worth of Huffman-compressed coefficients.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(boolean)
kusano 7d535a
encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  working_state state;
kusano 7d535a
  int blkn, ci;
kusano 7d535a
  jpeg_component_info * compptr;
kusano 7d535a
kusano 7d535a
  /* Load up working state */
kusano 7d535a
  state.next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
  state.free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
  ASSIGN_STATE(state.cur, entropy->saved);
kusano 7d535a
  state.cinfo = cinfo;
kusano 7d535a
kusano 7d535a
  /* Emit restart marker if needed */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0)
kusano 7d535a
      if (! emit_restart_s(&state, entropy->next_restart_num))
kusano 7d535a
	return FALSE;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Encode the MCU data blocks */
kusano 7d535a
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
kusano 7d535a
    ci = cinfo->MCU_membership[blkn];
kusano 7d535a
    compptr = cinfo->cur_comp_info[ci];
kusano 7d535a
    if (! encode_one_block(&state,
kusano 7d535a
			   MCU_data[blkn][0], state.cur.last_dc_val[ci],
kusano 7d535a
			   entropy->dc_derived_tbls[compptr->dc_tbl_no],
kusano 7d535a
			   entropy->ac_derived_tbls[compptr->ac_tbl_no]))
kusano 7d535a
      return FALSE;
kusano 7d535a
    /* Update last_dc_val */
kusano 7d535a
    state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Completed MCU, so update state */
kusano 7d535a
  cinfo->dest->next_output_byte = state.next_output_byte;
kusano 7d535a
  cinfo->dest->free_in_buffer = state.free_in_buffer;
kusano 7d535a
  ASSIGN_STATE(entropy->saved, state.cur);
kusano 7d535a
kusano 7d535a
  /* Update restart-interval state too */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0) {
kusano 7d535a
      entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
      entropy->next_restart_num++;
kusano 7d535a
      entropy->next_restart_num &= 7;
kusano 7d535a
    }
kusano 7d535a
    entropy->restarts_to_go--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Finish up at the end of a Huffman-compressed scan.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(void)
kusano 7d535a
finish_pass_huff (j_compress_ptr cinfo)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  working_state state;
kusano 7d535a
kusano 7d535a
  if (cinfo->progressive_mode) {
kusano 7d535a
    entropy->next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
    entropy->free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
kusano 7d535a
    /* Flush out any buffered data */
kusano 7d535a
    emit_eobrun(entropy);
kusano 7d535a
    flush_bits_e(entropy);
kusano 7d535a
kusano 7d535a
    cinfo->dest->next_output_byte = entropy->next_output_byte;
kusano 7d535a
    cinfo->dest->free_in_buffer = entropy->free_in_buffer;
kusano 7d535a
  } else {
kusano 7d535a
    /* Load up working state ... flush_bits needs it */
kusano 7d535a
    state.next_output_byte = cinfo->dest->next_output_byte;
kusano 7d535a
    state.free_in_buffer = cinfo->dest->free_in_buffer;
kusano 7d535a
    ASSIGN_STATE(state.cur, entropy->saved);
kusano 7d535a
    state.cinfo = cinfo;
kusano 7d535a
kusano 7d535a
    /* Flush out the last data */
kusano 7d535a
    if (! flush_bits_s(&state))
kusano 7d535a
      ERREXIT(cinfo, JERR_CANT_SUSPEND);
kusano 7d535a
kusano 7d535a
    /* Update state */
kusano 7d535a
    cinfo->dest->next_output_byte = state.next_output_byte;
kusano 7d535a
    cinfo->dest->free_in_buffer = state.free_in_buffer;
kusano 7d535a
    ASSIGN_STATE(entropy->saved, state.cur);
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Huffman coding optimization.
kusano 7d535a
 *
kusano 7d535a
 * We first scan the supplied data and count the number of uses of each symbol
kusano 7d535a
 * that is to be Huffman-coded. (This process MUST agree with the code above.)
kusano 7d535a
 * Then we build a Huffman coding tree for the observed counts.
kusano 7d535a
 * Symbols which are not needed at all for the particular image are not
kusano 7d535a
 * assigned any code, which saves space in the DHT marker as well as in
kusano 7d535a
 * the compressed data.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
kusano 7d535a
/* Process a single block's worth of coefficients */
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
kusano 7d535a
		 long dc_counts[], long ac_counts[])
kusano 7d535a
{
kusano 7d535a
  register int temp;
kusano 7d535a
  register int nbits;
kusano 7d535a
  register int k, r;
kusano 7d535a
  int Se = cinfo->lim_Se;
kusano 7d535a
  const int * natural_order = cinfo->natural_order;
kusano 7d535a
  
kusano 7d535a
  /* Encode the DC coefficient difference per section F.1.2.1 */
kusano 7d535a
  
kusano 7d535a
  temp = block[0] - last_dc_val;
kusano 7d535a
  if (temp < 0)
kusano 7d535a
    temp = -temp;
kusano 7d535a
  
kusano 7d535a
  /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
  nbits = 0;
kusano 7d535a
  while (temp) {
kusano 7d535a
    nbits++;
kusano 7d535a
    temp >>= 1;
kusano 7d535a
  }
kusano 7d535a
  /* Check for out-of-range coefficient values.
kusano 7d535a
   * Since we're encoding a difference, the range limit is twice as much.
kusano 7d535a
   */
kusano 7d535a
  if (nbits > MAX_COEF_BITS+1)
kusano 7d535a
    ERREXIT(cinfo, JERR_BAD_DCT_COEF);
kusano 7d535a
kusano 7d535a
  /* Count the Huffman symbol for the number of bits */
kusano 7d535a
  dc_counts[nbits]++;
kusano 7d535a
  
kusano 7d535a
  /* Encode the AC coefficients per section F.1.2.2 */
kusano 7d535a
  
kusano 7d535a
  r = 0;			/* r = run length of zeros */
kusano 7d535a
  
kusano 7d535a
  for (k = 1; k <= Se; k++) {
kusano 7d535a
    if ((temp = block[natural_order[k]]) == 0) {
kusano 7d535a
      r++;
kusano 7d535a
    } else {
kusano 7d535a
      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
kusano 7d535a
      while (r > 15) {
kusano 7d535a
	ac_counts[0xF0]++;
kusano 7d535a
	r -= 16;
kusano 7d535a
      }
kusano 7d535a
      
kusano 7d535a
      /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
      if (temp < 0)
kusano 7d535a
	temp = -temp;
kusano 7d535a
      
kusano 7d535a
      /* Find the number of bits needed for the magnitude of the coefficient */
kusano 7d535a
      nbits = 1;		/* there must be at least one 1 bit */
kusano 7d535a
      while ((temp >>= 1))
kusano 7d535a
	nbits++;
kusano 7d535a
      /* Check for out-of-range coefficient values */
kusano 7d535a
      if (nbits > MAX_COEF_BITS)
kusano 7d535a
	ERREXIT(cinfo, JERR_BAD_DCT_COEF);
kusano 7d535a
      
kusano 7d535a
      /* Count Huffman symbol for run length / number of bits */
kusano 7d535a
      ac_counts[(r << 4) + nbits]++;
kusano 7d535a
      
kusano 7d535a
      r = 0;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* If the last coef(s) were zero, emit an end-of-block code */
kusano 7d535a
  if (r > 0)
kusano 7d535a
    ac_counts[0]++;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
kusano 7d535a
 * No data is actually output, so no suspension return is possible.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(boolean)
kusano 7d535a
encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  int blkn, ci;
kusano 7d535a
  jpeg_component_info * compptr;
kusano 7d535a
kusano 7d535a
  /* Take care of restart intervals if needed */
kusano 7d535a
  if (cinfo->restart_interval) {
kusano 7d535a
    if (entropy->restarts_to_go == 0) {
kusano 7d535a
      /* Re-initialize DC predictions to 0 */
kusano 7d535a
      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
kusano 7d535a
	entropy->saved.last_dc_val[ci] = 0;
kusano 7d535a
      /* Update restart state */
kusano 7d535a
      entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
    }
kusano 7d535a
    entropy->restarts_to_go--;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
kusano 7d535a
    ci = cinfo->MCU_membership[blkn];
kusano 7d535a
    compptr = cinfo->cur_comp_info[ci];
kusano 7d535a
    htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
kusano 7d535a
		    entropy->dc_count_ptrs[compptr->dc_tbl_no],
kusano 7d535a
		    entropy->ac_count_ptrs[compptr->ac_tbl_no]);
kusano 7d535a
    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  return TRUE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Generate the best Huffman code table for the given counts, fill htbl.
kusano 7d535a
 *
kusano 7d535a
 * The JPEG standard requires that no symbol be assigned a codeword of all
kusano 7d535a
 * one bits (so that padding bits added at the end of a compressed segment
kusano 7d535a
 * can't look like a valid code).  Because of the canonical ordering of
kusano 7d535a
 * codewords, this just means that there must be an unused slot in the
kusano 7d535a
 * longest codeword length category.  Section K.2 of the JPEG spec suggests
kusano 7d535a
 * reserving such a slot by pretending that symbol 256 is a valid symbol
kusano 7d535a
 * with count 1.  In theory that's not optimal; giving it count zero but
kusano 7d535a
 * including it in the symbol set anyway should give a better Huffman code.
kusano 7d535a
 * But the theoretically better code actually seems to come out worse in
kusano 7d535a
 * practice, because it produces more all-ones bytes (which incur stuffed
kusano 7d535a
 * zero bytes in the final file).  In any case the difference is tiny.
kusano 7d535a
 *
kusano 7d535a
 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
kusano 7d535a
 * If some symbols have a very small but nonzero probability, the Huffman tree
kusano 7d535a
 * must be adjusted to meet the code length restriction.  We currently use
kusano 7d535a
 * the adjustment method suggested in JPEG section K.2.  This method is *not*
kusano 7d535a
 * optimal; it may not choose the best possible limited-length code.  But
kusano 7d535a
 * typically only very-low-frequency symbols will be given less-than-optimal
kusano 7d535a
 * lengths, so the code is almost optimal.  Experimental comparisons against
kusano 7d535a
 * an optimal limited-length-code algorithm indicate that the difference is
kusano 7d535a
 * microscopic --- usually less than a hundredth of a percent of total size.
kusano 7d535a
 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
LOCAL(void)
kusano 7d535a
jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
kusano 7d535a
{
kusano 7d535a
#define MAX_CLEN 32		/* assumed maximum initial code length */
kusano 7d535a
  UINT8 bits[MAX_CLEN+1];	/* bits[k] = # of symbols with code length k */
kusano 7d535a
  int codesize[257];		/* codesize[k] = code length of symbol k */
kusano 7d535a
  int others[257];		/* next symbol in current branch of tree */
kusano 7d535a
  int c1, c2;
kusano 7d535a
  int p, i, j;
kusano 7d535a
  long v;
kusano 7d535a
kusano 7d535a
  /* This algorithm is explained in section K.2 of the JPEG standard */
kusano 7d535a
kusano 7d535a
  MEMZERO(bits, SIZEOF(bits));
kusano 7d535a
  MEMZERO(codesize, SIZEOF(codesize));
kusano 7d535a
  for (i = 0; i < 257; i++)
kusano 7d535a
    others[i] = -1;		/* init links to empty */
kusano 7d535a
  
kusano 7d535a
  freq[256] = 1;		/* make sure 256 has a nonzero count */
kusano 7d535a
  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
kusano 7d535a
   * that no real symbol is given code-value of all ones, because 256
kusano 7d535a
   * will be placed last in the largest codeword category.
kusano 7d535a
   */
kusano 7d535a
kusano 7d535a
  /* Huffman's basic algorithm to assign optimal code lengths to symbols */
kusano 7d535a
kusano 7d535a
  for (;;) {
kusano 7d535a
    /* Find the smallest nonzero frequency, set c1 = its symbol */
kusano 7d535a
    /* In case of ties, take the larger symbol number */
kusano 7d535a
    c1 = -1;
kusano 7d535a
    v = 1000000000L;
kusano 7d535a
    for (i = 0; i <= 256; i++) {
kusano 7d535a
      if (freq[i] && freq[i] <= v) {
kusano 7d535a
	v = freq[i];
kusano 7d535a
	c1 = i;
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Find the next smallest nonzero frequency, set c2 = its symbol */
kusano 7d535a
    /* In case of ties, take the larger symbol number */
kusano 7d535a
    c2 = -1;
kusano 7d535a
    v = 1000000000L;
kusano 7d535a
    for (i = 0; i <= 256; i++) {
kusano 7d535a
      if (freq[i] && freq[i] <= v && i != c1) {
kusano 7d535a
	v = freq[i];
kusano 7d535a
	c2 = i;
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Done if we've merged everything into one frequency */
kusano 7d535a
    if (c2 < 0)
kusano 7d535a
      break;
kusano 7d535a
    
kusano 7d535a
    /* Else merge the two counts/trees */
kusano 7d535a
    freq[c1] += freq[c2];
kusano 7d535a
    freq[c2] = 0;
kusano 7d535a
kusano 7d535a
    /* Increment the codesize of everything in c1's tree branch */
kusano 7d535a
    codesize[c1]++;
kusano 7d535a
    while (others[c1] >= 0) {
kusano 7d535a
      c1 = others[c1];
kusano 7d535a
      codesize[c1]++;
kusano 7d535a
    }
kusano 7d535a
    
kusano 7d535a
    others[c1] = c2;		/* chain c2 onto c1's tree branch */
kusano 7d535a
    
kusano 7d535a
    /* Increment the codesize of everything in c2's tree branch */
kusano 7d535a
    codesize[c2]++;
kusano 7d535a
    while (others[c2] >= 0) {
kusano 7d535a
      c2 = others[c2];
kusano 7d535a
      codesize[c2]++;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Now count the number of symbols of each code length */
kusano 7d535a
  for (i = 0; i <= 256; i++) {
kusano 7d535a
    if (codesize[i]) {
kusano 7d535a
      /* The JPEG standard seems to think that this can't happen, */
kusano 7d535a
      /* but I'm paranoid... */
kusano 7d535a
      if (codesize[i] > MAX_CLEN)
kusano 7d535a
	ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
kusano 7d535a
kusano 7d535a
      bits[codesize[i]]++;
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
kusano 7d535a
   * Huffman procedure assigned any such lengths, we must adjust the coding.
kusano 7d535a
   * Here is what the JPEG spec says about how this next bit works:
kusano 7d535a
   * Since symbols are paired for the longest Huffman code, the symbols are
kusano 7d535a
   * removed from this length category two at a time.  The prefix for the pair
kusano 7d535a
   * (which is one bit shorter) is allocated to one of the pair; then,
kusano 7d535a
   * skipping the BITS entry for that prefix length, a code word from the next
kusano 7d535a
   * shortest nonzero BITS entry is converted into a prefix for two code words
kusano 7d535a
   * one bit longer.
kusano 7d535a
   */
kusano 7d535a
  
kusano 7d535a
  for (i = MAX_CLEN; i > 16; i--) {
kusano 7d535a
    while (bits[i] > 0) {
kusano 7d535a
      j = i - 2;		/* find length of new prefix to be used */
kusano 7d535a
      while (bits[j] == 0)
kusano 7d535a
	j--;
kusano 7d535a
      
kusano 7d535a
      bits[i] -= 2;		/* remove two symbols */
kusano 7d535a
      bits[i-1]++;		/* one goes in this length */
kusano 7d535a
      bits[j+1] += 2;		/* two new symbols in this length */
kusano 7d535a
      bits[j]--;		/* symbol of this length is now a prefix */
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Remove the count for the pseudo-symbol 256 from the largest codelength */
kusano 7d535a
  while (bits[i] == 0)		/* find largest codelength still in use */
kusano 7d535a
    i--;
kusano 7d535a
  bits[i]--;
kusano 7d535a
  
kusano 7d535a
  /* Return final symbol counts (only for lengths 0..16) */
kusano 7d535a
  MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
kusano 7d535a
  
kusano 7d535a
  /* Return a list of the symbols sorted by code length */
kusano 7d535a
  /* It's not real clear to me why we don't need to consider the codelength
kusano 7d535a
   * changes made above, but the JPEG spec seems to think this works.
kusano 7d535a
   */
kusano 7d535a
  p = 0;
kusano 7d535a
  for (i = 1; i <= MAX_CLEN; i++) {
kusano 7d535a
    for (j = 0; j <= 255; j++) {
kusano 7d535a
      if (codesize[j] == i) {
kusano 7d535a
	htbl->huffval[p] = (UINT8) j;
kusano 7d535a
	p++;
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Set sent_table FALSE so updated table will be written to JPEG file. */
kusano 7d535a
  htbl->sent_table = FALSE;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Finish up a statistics-gathering pass and create the new Huffman tables.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(void)
kusano 7d535a
finish_pass_gather (j_compress_ptr cinfo)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  int ci, tbl;
kusano 7d535a
  jpeg_component_info * compptr;
kusano 7d535a
  JHUFF_TBL **htblptr;
kusano 7d535a
  boolean did_dc[NUM_HUFF_TBLS];
kusano 7d535a
  boolean did_ac[NUM_HUFF_TBLS];
kusano 7d535a
kusano 7d535a
  /* It's important not to apply jpeg_gen_optimal_table more than once
kusano 7d535a
   * per table, because it clobbers the input frequency counts!
kusano 7d535a
   */
kusano 7d535a
  if (cinfo->progressive_mode)
kusano 7d535a
    /* Flush out buffered data (all we care about is counting the EOB symbol) */
kusano 7d535a
    emit_eobrun(entropy);
kusano 7d535a
kusano 7d535a
  MEMZERO(did_dc, SIZEOF(did_dc));
kusano 7d535a
  MEMZERO(did_ac, SIZEOF(did_ac));
kusano 7d535a
kusano 7d535a
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
kusano 7d535a
    compptr = cinfo->cur_comp_info[ci];
kusano 7d535a
    /* DC needs no table for refinement scan */
kusano 7d535a
    if (cinfo->Ss == 0 && cinfo->Ah == 0) {
kusano 7d535a
      tbl = compptr->dc_tbl_no;
kusano 7d535a
      if (! did_dc[tbl]) {
kusano 7d535a
	htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
kusano 7d535a
	if (*htblptr == NULL)
kusano 7d535a
	  *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
kusano 7d535a
	jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);
kusano 7d535a
	did_dc[tbl] = TRUE;
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
    /* AC needs no table when not present */
kusano 7d535a
    if (cinfo->Se) {
kusano 7d535a
      tbl = compptr->ac_tbl_no;
kusano 7d535a
      if (! did_ac[tbl]) {
kusano 7d535a
	htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
kusano 7d535a
	if (*htblptr == NULL)
kusano 7d535a
	  *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
kusano 7d535a
	jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);
kusano 7d535a
	did_ac[tbl] = TRUE;
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Initialize for a Huffman-compressed scan.
kusano 7d535a
 * If gather_statistics is TRUE, we do not output anything during the scan,
kusano 7d535a
 * just count the Huffman symbols used and generate Huffman code tables.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
METHODDEF(void)
kusano 7d535a
start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
kusano 7d535a
  int ci, tbl;
kusano 7d535a
  jpeg_component_info * compptr;
kusano 7d535a
kusano 7d535a
  if (gather_statistics)
kusano 7d535a
    entropy->pub.finish_pass = finish_pass_gather;
kusano 7d535a
  else
kusano 7d535a
    entropy->pub.finish_pass = finish_pass_huff;
kusano 7d535a
kusano 7d535a
  if (cinfo->progressive_mode) {
kusano 7d535a
    entropy->cinfo = cinfo;
kusano 7d535a
    entropy->gather_statistics = gather_statistics;
kusano 7d535a
kusano 7d535a
    /* We assume jcmaster.c already validated the scan parameters. */
kusano 7d535a
kusano 7d535a
    /* Select execution routine */
kusano 7d535a
    if (cinfo->Ah == 0) {
kusano 7d535a
      if (cinfo->Ss == 0)
kusano 7d535a
	entropy->pub.encode_mcu = encode_mcu_DC_first;
kusano 7d535a
      else
kusano 7d535a
	entropy->pub.encode_mcu = encode_mcu_AC_first;
kusano 7d535a
    } else {
kusano 7d535a
      if (cinfo->Ss == 0)
kusano 7d535a
	entropy->pub.encode_mcu = encode_mcu_DC_refine;
kusano 7d535a
      else {
kusano 7d535a
	entropy->pub.encode_mcu = encode_mcu_AC_refine;
kusano 7d535a
	/* AC refinement needs a correction bit buffer */
kusano 7d535a
	if (entropy->bit_buffer == NULL)
kusano 7d535a
	  entropy->bit_buffer = (char *)
kusano 7d535a
	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
kusano 7d535a
					MAX_CORR_BITS * SIZEOF(char));
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* Initialize AC stuff */
kusano 7d535a
    entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;
kusano 7d535a
    entropy->EOBRUN = 0;
kusano 7d535a
    entropy->BE = 0;
kusano 7d535a
  } else {
kusano 7d535a
    if (gather_statistics)
kusano 7d535a
      entropy->pub.encode_mcu = encode_mcu_gather;
kusano 7d535a
    else
kusano 7d535a
      entropy->pub.encode_mcu = encode_mcu_huff;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
kusano 7d535a
    compptr = cinfo->cur_comp_info[ci];
kusano 7d535a
    /* DC needs no table for refinement scan */
kusano 7d535a
    if (cinfo->Ss == 0 && cinfo->Ah == 0) {
kusano 7d535a
      tbl = compptr->dc_tbl_no;
kusano 7d535a
      if (gather_statistics) {
kusano 7d535a
	/* Check for invalid table index */
kusano 7d535a
	/* (make_c_derived_tbl does this in the other path) */
kusano 7d535a
	if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
kusano 7d535a
	  ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
kusano 7d535a
	/* Allocate and zero the statistics tables */
kusano 7d535a
	/* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
kusano 7d535a
	if (entropy->dc_count_ptrs[tbl] == NULL)
kusano 7d535a
	  entropy->dc_count_ptrs[tbl] = (long *)
kusano 7d535a
	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
kusano 7d535a
					257 * SIZEOF(long));
kusano 7d535a
	MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));
kusano 7d535a
      } else {
kusano 7d535a
	/* Compute derived values for Huffman tables */
kusano 7d535a
	/* We may do this more than once for a table, but it's not expensive */
kusano 7d535a
	jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,
kusano 7d535a
				& entropy->dc_derived_tbls[tbl]);
kusano 7d535a
      }
kusano 7d535a
      /* Initialize DC predictions to 0 */
kusano 7d535a
      entropy->saved.last_dc_val[ci] = 0;
kusano 7d535a
    }
kusano 7d535a
    /* AC needs no table when not present */
kusano 7d535a
    if (cinfo->Se) {
kusano 7d535a
      tbl = compptr->ac_tbl_no;
kusano 7d535a
      if (gather_statistics) {
kusano 7d535a
	if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
kusano 7d535a
	  ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
kusano 7d535a
	if (entropy->ac_count_ptrs[tbl] == NULL)
kusano 7d535a
	  entropy->ac_count_ptrs[tbl] = (long *)
kusano 7d535a
	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
kusano 7d535a
					257 * SIZEOF(long));
kusano 7d535a
	MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));
kusano 7d535a
      } else {
kusano 7d535a
	jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,
kusano 7d535a
				& entropy->ac_derived_tbls[tbl]);
kusano 7d535a
      }
kusano 7d535a
    }
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  /* Initialize bit buffer to empty */
kusano 7d535a
  entropy->saved.put_buffer = 0;
kusano 7d535a
  entropy->saved.put_bits = 0;
kusano 7d535a
kusano 7d535a
  /* Initialize restart stuff */
kusano 7d535a
  entropy->restarts_to_go = cinfo->restart_interval;
kusano 7d535a
  entropy->next_restart_num = 0;
kusano 7d535a
}
kusano 7d535a
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
 * Module initialization routine for Huffman entropy encoding.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
GLOBAL(void)
kusano 7d535a
jinit_huff_encoder (j_compress_ptr cinfo)
kusano 7d535a
{
kusano 7d535a
  huff_entropy_ptr entropy;
kusano 7d535a
  int i;
kusano 7d535a
kusano 7d535a
  entropy = (huff_entropy_ptr)
kusano 7d535a
    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
kusano 7d535a
				SIZEOF(huff_entropy_encoder));
kusano 7d535a
  cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
kusano 7d535a
  entropy->pub.start_pass = start_pass_huff;
kusano 7d535a
kusano 7d535a
  /* Mark tables unallocated */
kusano 7d535a
  for (i = 0; i < NUM_HUFF_TBLS; i++) {
kusano 7d535a
    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
kusano 7d535a
    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
kusano 7d535a
  }
kusano 7d535a
kusano 7d535a
  if (cinfo->progressive_mode)
kusano 7d535a
    entropy->bit_buffer = NULL;	/* needed only in AC refinement scan */
kusano 7d535a
}