nuclear@2: /* nuclear@2: * jchuff.c nuclear@2: * nuclear@2: * Copyright (C) 1991-1997, Thomas G. Lane. nuclear@2: * This file is part of the Independent JPEG Group's software. nuclear@2: * For conditions of distribution and use, see the accompanying README file. nuclear@2: * nuclear@2: * This file contains Huffman entropy encoding routines. nuclear@2: * nuclear@2: * Much of the complexity here has to do with supporting output suspension. nuclear@2: * If the data destination module demands suspension, we want to be able to nuclear@2: * back up to the start of the current MCU. To do this, we copy state nuclear@2: * variables into local working storage, and update them back to the nuclear@2: * permanent JPEG objects only upon successful completion of an MCU. nuclear@2: */ nuclear@2: nuclear@2: #define JPEG_INTERNALS nuclear@2: #include "jinclude.h" nuclear@2: #include "jpeglib.h" nuclear@2: #include "jchuff.h" /* Declarations shared with jcphuff.c */ nuclear@2: nuclear@2: nuclear@2: /* Expanded entropy encoder object for Huffman encoding. nuclear@2: * nuclear@2: * The savable_state subrecord contains fields that change within an MCU, nuclear@2: * but must not be updated permanently until we complete the MCU. nuclear@2: */ nuclear@2: nuclear@2: typedef struct { nuclear@2: INT32 put_buffer; /* current bit-accumulation buffer */ nuclear@2: int put_bits; /* # of bits now in it */ nuclear@2: int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ nuclear@2: } savable_state; nuclear@2: nuclear@2: /* This macro is to work around compilers with missing or broken nuclear@2: * structure assignment. You'll need to fix this code if you have nuclear@2: * such a compiler and you change MAX_COMPS_IN_SCAN. nuclear@2: */ nuclear@2: nuclear@2: #ifndef NO_STRUCT_ASSIGN nuclear@2: #define ASSIGN_STATE(dest,src) ((dest) = (src)) nuclear@2: #else nuclear@2: #if MAX_COMPS_IN_SCAN == 4 nuclear@2: #define ASSIGN_STATE(dest,src) \ nuclear@2: ((dest).put_buffer = (src).put_buffer, \ nuclear@2: (dest).put_bits = (src).put_bits, \ nuclear@2: (dest).last_dc_val[0] = (src).last_dc_val[0], \ nuclear@2: (dest).last_dc_val[1] = (src).last_dc_val[1], \ nuclear@2: (dest).last_dc_val[2] = (src).last_dc_val[2], \ nuclear@2: (dest).last_dc_val[3] = (src).last_dc_val[3]) nuclear@2: #endif nuclear@2: #endif nuclear@2: nuclear@2: nuclear@2: typedef struct { nuclear@2: struct jpeg_entropy_encoder pub; /* public fields */ nuclear@2: nuclear@2: savable_state saved; /* Bit buffer & DC state at start of MCU */ nuclear@2: nuclear@2: /* These fields are NOT loaded into local working state. */ nuclear@2: unsigned int restarts_to_go; /* MCUs left in this restart interval */ nuclear@2: int next_restart_num; /* next restart number to write (0-7) */ nuclear@2: nuclear@2: /* Pointers to derived tables (these workspaces have image lifespan) */ nuclear@2: c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; nuclear@2: c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; nuclear@2: nuclear@2: #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */ nuclear@2: long * dc_count_ptrs[NUM_HUFF_TBLS]; nuclear@2: long * ac_count_ptrs[NUM_HUFF_TBLS]; nuclear@2: #endif nuclear@2: } huff_entropy_encoder; nuclear@2: nuclear@2: typedef huff_entropy_encoder * huff_entropy_ptr; nuclear@2: nuclear@2: /* Working state while writing an MCU. nuclear@2: * This struct contains all the fields that are needed by subroutines. nuclear@2: */ nuclear@2: nuclear@2: typedef struct { nuclear@2: JOCTET * next_output_byte; /* => next byte to write in buffer */ nuclear@2: size_t free_in_buffer; /* # of byte spaces remaining in buffer */ nuclear@2: savable_state cur; /* Current bit buffer & DC state */ nuclear@2: j_compress_ptr cinfo; /* dump_buffer needs access to this */ nuclear@2: } working_state; nuclear@2: nuclear@2: nuclear@2: /* Forward declarations */ nuclear@2: METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo, nuclear@2: JBLOCKROW *MCU_data)); nuclear@2: METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo)); nuclear@2: #ifdef ENTROPY_OPT_SUPPORTED nuclear@2: METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo, nuclear@2: JBLOCKROW *MCU_data)); nuclear@2: METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo)); nuclear@2: #endif nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Initialize for a Huffman-compressed scan. nuclear@2: * If gather_statistics is TRUE, we do not output anything during the scan, nuclear@2: * just count the Huffman symbols used and generate Huffman code tables. nuclear@2: */ nuclear@2: nuclear@2: METHODDEF(void) nuclear@2: start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics) nuclear@2: { nuclear@2: huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; nuclear@2: int ci, dctbl, actbl; nuclear@2: jpeg_component_info * compptr; nuclear@2: nuclear@2: if (gather_statistics) { nuclear@2: #ifdef ENTROPY_OPT_SUPPORTED nuclear@2: entropy->pub.encode_mcu = encode_mcu_gather; nuclear@2: entropy->pub.finish_pass = finish_pass_gather; nuclear@2: #else nuclear@2: ERREXIT(cinfo, JERR_NOT_COMPILED); nuclear@2: #endif nuclear@2: } else { nuclear@2: entropy->pub.encode_mcu = encode_mcu_huff; nuclear@2: entropy->pub.finish_pass = finish_pass_huff; nuclear@2: } nuclear@2: nuclear@2: for (ci = 0; ci < cinfo->comps_in_scan; ci++) { nuclear@2: compptr = cinfo->cur_comp_info[ci]; nuclear@2: dctbl = compptr->dc_tbl_no; nuclear@2: actbl = compptr->ac_tbl_no; nuclear@2: if (gather_statistics) { nuclear@2: #ifdef ENTROPY_OPT_SUPPORTED nuclear@2: /* Check for invalid table indexes */ nuclear@2: /* (make_c_derived_tbl does this in the other path) */ nuclear@2: if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS) nuclear@2: ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl); nuclear@2: if (actbl < 0 || actbl >= NUM_HUFF_TBLS) nuclear@2: ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl); nuclear@2: /* Allocate and zero the statistics tables */ nuclear@2: /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */ nuclear@2: if (entropy->dc_count_ptrs[dctbl] == NULL) nuclear@2: entropy->dc_count_ptrs[dctbl] = (long *) nuclear@2: (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, nuclear@2: 257 * SIZEOF(long)); nuclear@2: MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long)); nuclear@2: if (entropy->ac_count_ptrs[actbl] == NULL) nuclear@2: entropy->ac_count_ptrs[actbl] = (long *) nuclear@2: (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, nuclear@2: 257 * SIZEOF(long)); nuclear@2: MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long)); nuclear@2: #endif nuclear@2: } else { nuclear@2: /* Compute derived values for Huffman tables */ nuclear@2: /* We may do this more than once for a table, but it's not expensive */ nuclear@2: jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl, nuclear@2: & entropy->dc_derived_tbls[dctbl]); nuclear@2: jpeg_make_c_derived_tbl(cinfo, FALSE, actbl, nuclear@2: & entropy->ac_derived_tbls[actbl]); nuclear@2: } nuclear@2: /* Initialize DC predictions to 0 */ nuclear@2: entropy->saved.last_dc_val[ci] = 0; nuclear@2: } nuclear@2: nuclear@2: /* Initialize bit buffer to empty */ nuclear@2: entropy->saved.put_buffer = 0; nuclear@2: entropy->saved.put_bits = 0; nuclear@2: nuclear@2: /* Initialize restart stuff */ nuclear@2: entropy->restarts_to_go = cinfo->restart_interval; nuclear@2: entropy->next_restart_num = 0; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Compute the derived values for a Huffman table. nuclear@2: * This routine also performs some validation checks on the table. nuclear@2: * nuclear@2: * Note this is also used by jcphuff.c. nuclear@2: */ nuclear@2: nuclear@2: GLOBAL(void) nuclear@2: jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno, nuclear@2: c_derived_tbl ** pdtbl) nuclear@2: { nuclear@2: JHUFF_TBL *htbl; nuclear@2: c_derived_tbl *dtbl; nuclear@2: int p, i, l, lastp, si, maxsymbol; nuclear@2: char huffsize[257]; nuclear@2: unsigned int huffcode[257]; nuclear@2: unsigned int code; nuclear@2: nuclear@2: /* Note that huffsize[] and huffcode[] are filled in code-length order, nuclear@2: * paralleling the order of the symbols themselves in htbl->huffval[]. nuclear@2: */ nuclear@2: nuclear@2: /* Find the input Huffman table */ nuclear@2: if (tblno < 0 || tblno >= NUM_HUFF_TBLS) nuclear@2: ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); nuclear@2: htbl = nuclear@2: isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno]; nuclear@2: if (htbl == NULL) nuclear@2: ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); nuclear@2: nuclear@2: /* Allocate a workspace if we haven't already done so. */ nuclear@2: if (*pdtbl == NULL) nuclear@2: *pdtbl = (c_derived_tbl *) nuclear@2: (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, nuclear@2: SIZEOF(c_derived_tbl)); nuclear@2: dtbl = *pdtbl; nuclear@2: nuclear@2: /* Figure C.1: make table of Huffman code length for each symbol */ nuclear@2: nuclear@2: p = 0; nuclear@2: for (l = 1; l <= 16; l++) { nuclear@2: i = (int) htbl->bits[l]; nuclear@2: if (i < 0 || p + i > 256) /* protect against table overrun */ nuclear@2: ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); nuclear@2: while (i--) nuclear@2: huffsize[p++] = (char) l; nuclear@2: } nuclear@2: huffsize[p] = 0; nuclear@2: lastp = p; nuclear@2: nuclear@2: /* Figure C.2: generate the codes themselves */ nuclear@2: /* We also validate that the counts represent a legal Huffman code tree. */ nuclear@2: nuclear@2: code = 0; nuclear@2: si = huffsize[0]; nuclear@2: p = 0; nuclear@2: while (huffsize[p]) { nuclear@2: while (((int) huffsize[p]) == si) { nuclear@2: huffcode[p++] = code; nuclear@2: code++; nuclear@2: } nuclear@2: /* code is now 1 more than the last code used for codelength si; but nuclear@2: * it must still fit in si bits, since no code is allowed to be all ones. nuclear@2: */ nuclear@2: if (((INT32) code) >= (((INT32) 1) << si)) nuclear@2: ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); nuclear@2: code <<= 1; nuclear@2: si++; nuclear@2: } nuclear@2: nuclear@2: /* Figure C.3: generate encoding tables */ nuclear@2: /* These are code and size indexed by symbol value */ nuclear@2: nuclear@2: /* Set all codeless symbols to have code length 0; nuclear@2: * this lets us detect duplicate VAL entries here, and later nuclear@2: * allows emit_bits to detect any attempt to emit such symbols. nuclear@2: */ nuclear@2: MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi)); nuclear@2: nuclear@2: /* This is also a convenient place to check for out-of-range nuclear@2: * and duplicated VAL entries. We allow 0..255 for AC symbols nuclear@2: * but only 0..15 for DC. (We could constrain them further nuclear@2: * based on data depth and mode, but this seems enough.) nuclear@2: */ nuclear@2: maxsymbol = isDC ? 15 : 255; nuclear@2: nuclear@2: for (p = 0; p < lastp; p++) { nuclear@2: i = htbl->huffval[p]; nuclear@2: if (i < 0 || i > maxsymbol || dtbl->ehufsi[i]) nuclear@2: ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); nuclear@2: dtbl->ehufco[i] = huffcode[p]; nuclear@2: dtbl->ehufsi[i] = huffsize[p]; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* Outputting bytes to the file */ nuclear@2: nuclear@2: /* Emit a byte, taking 'action' if must suspend. */ nuclear@2: #define emit_byte(state,val,action) \ nuclear@2: { *(state)->next_output_byte++ = (JOCTET) (val); \ nuclear@2: if (--(state)->free_in_buffer == 0) \ nuclear@2: if (! dump_buffer(state)) \ nuclear@2: { action; } } nuclear@2: nuclear@2: nuclear@2: LOCAL(boolean) nuclear@2: dump_buffer (working_state * state) nuclear@2: /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */ nuclear@2: { nuclear@2: struct jpeg_destination_mgr * dest = state->cinfo->dest; nuclear@2: nuclear@2: if (! (*dest->empty_output_buffer) (state->cinfo)) nuclear@2: return FALSE; nuclear@2: /* After a successful buffer dump, must reset buffer pointers */ nuclear@2: state->next_output_byte = dest->next_output_byte; nuclear@2: state->free_in_buffer = dest->free_in_buffer; nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* Outputting bits to the file */ nuclear@2: nuclear@2: /* Only the right 24 bits of put_buffer are used; the valid bits are nuclear@2: * left-justified in this part. At most 16 bits can be passed to emit_bits nuclear@2: * in one call, and we never retain more than 7 bits in put_buffer nuclear@2: * between calls, so 24 bits are sufficient. nuclear@2: */ nuclear@2: nuclear@2: INLINE nuclear@2: LOCAL(boolean) nuclear@2: emit_bits (working_state * state, unsigned int code, int size) nuclear@2: /* Emit some bits; return TRUE if successful, FALSE if must suspend */ nuclear@2: { nuclear@2: /* This routine is heavily used, so it's worth coding tightly. */ nuclear@2: register INT32 put_buffer = (INT32) code; nuclear@2: register int put_bits = state->cur.put_bits; nuclear@2: nuclear@2: /* if size is 0, caller used an invalid Huffman table entry */ nuclear@2: if (size == 0) nuclear@2: ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE); nuclear@2: nuclear@2: put_buffer &= (((INT32) 1)<cur.put_buffer; /* and merge with old buffer contents */ nuclear@2: nuclear@2: while (put_bits >= 8) { nuclear@2: int c = (int) ((put_buffer >> 16) & 0xFF); nuclear@2: nuclear@2: emit_byte(state, c, return FALSE); nuclear@2: if (c == 0xFF) { /* need to stuff a zero byte? */ nuclear@2: emit_byte(state, 0, return FALSE); nuclear@2: } nuclear@2: put_buffer <<= 8; nuclear@2: put_bits -= 8; nuclear@2: } nuclear@2: nuclear@2: state->cur.put_buffer = put_buffer; /* update state variables */ nuclear@2: state->cur.put_bits = put_bits; nuclear@2: nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: LOCAL(boolean) nuclear@2: flush_bits (working_state * state) nuclear@2: { nuclear@2: if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */ nuclear@2: return FALSE; nuclear@2: state->cur.put_buffer = 0; /* and reset bit-buffer to empty */ nuclear@2: state->cur.put_bits = 0; nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* Encode a single block's worth of coefficients */ nuclear@2: nuclear@2: LOCAL(boolean) nuclear@2: encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val, nuclear@2: c_derived_tbl *dctbl, c_derived_tbl *actbl) nuclear@2: { nuclear@2: register int temp, temp2; nuclear@2: register int nbits; nuclear@2: register int k, r, i; nuclear@2: nuclear@2: /* Encode the DC coefficient difference per section F.1.2.1 */ nuclear@2: nuclear@2: temp = temp2 = block[0] - last_dc_val; nuclear@2: nuclear@2: if (temp < 0) { nuclear@2: temp = -temp; /* temp is abs value of input */ nuclear@2: /* For a negative input, want temp2 = bitwise complement of abs(input) */ nuclear@2: /* This code assumes we are on a two's complement machine */ nuclear@2: temp2--; nuclear@2: } nuclear@2: nuclear@2: /* Find the number of bits needed for the magnitude of the coefficient */ nuclear@2: nbits = 0; nuclear@2: while (temp) { nuclear@2: nbits++; nuclear@2: temp >>= 1; nuclear@2: } nuclear@2: /* Check for out-of-range coefficient values. nuclear@2: * Since we're encoding a difference, the range limit is twice as much. nuclear@2: */ nuclear@2: if (nbits > MAX_COEF_BITS+1) nuclear@2: ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); nuclear@2: nuclear@2: /* Emit the Huffman-coded symbol for the number of bits */ nuclear@2: if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits])) nuclear@2: return FALSE; nuclear@2: nuclear@2: /* Emit that number of bits of the value, if positive, */ nuclear@2: /* or the complement of its magnitude, if negative. */ nuclear@2: if (nbits) /* emit_bits rejects calls with size 0 */ nuclear@2: if (! emit_bits(state, (unsigned int) temp2, nbits)) nuclear@2: return FALSE; nuclear@2: nuclear@2: /* Encode the AC coefficients per section F.1.2.2 */ nuclear@2: nuclear@2: r = 0; /* r = run length of zeros */ nuclear@2: nuclear@2: for (k = 1; k < DCTSIZE2; k++) { nuclear@2: if ((temp = block[jpeg_natural_order[k]]) == 0) { nuclear@2: r++; nuclear@2: } else { nuclear@2: /* if run length > 15, must emit special run-length-16 codes (0xF0) */ nuclear@2: while (r > 15) { nuclear@2: if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0])) nuclear@2: return FALSE; nuclear@2: r -= 16; nuclear@2: } nuclear@2: nuclear@2: temp2 = temp; nuclear@2: if (temp < 0) { nuclear@2: temp = -temp; /* temp is abs value of input */ nuclear@2: /* This code assumes we are on a two's complement machine */ nuclear@2: temp2--; nuclear@2: } nuclear@2: nuclear@2: /* Find the number of bits needed for the magnitude of the coefficient */ nuclear@2: nbits = 1; /* there must be at least one 1 bit */ nuclear@2: while ((temp >>= 1)) nuclear@2: nbits++; nuclear@2: /* Check for out-of-range coefficient values */ nuclear@2: if (nbits > MAX_COEF_BITS) nuclear@2: ERREXIT(state->cinfo, JERR_BAD_DCT_COEF); nuclear@2: nuclear@2: /* Emit Huffman symbol for run length / number of bits */ nuclear@2: i = (r << 4) + nbits; nuclear@2: if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i])) nuclear@2: return FALSE; nuclear@2: nuclear@2: /* Emit that number of bits of the value, if positive, */ nuclear@2: /* or the complement of its magnitude, if negative. */ nuclear@2: if (! emit_bits(state, (unsigned int) temp2, nbits)) nuclear@2: return FALSE; nuclear@2: nuclear@2: r = 0; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* If the last coef(s) were zero, emit an end-of-block code */ nuclear@2: if (r > 0) nuclear@2: if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0])) nuclear@2: return FALSE; nuclear@2: nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Emit a restart marker & resynchronize predictions. nuclear@2: */ nuclear@2: nuclear@2: LOCAL(boolean) nuclear@2: emit_restart (working_state * state, int restart_num) nuclear@2: { nuclear@2: int ci; nuclear@2: nuclear@2: if (! flush_bits(state)) nuclear@2: return FALSE; nuclear@2: nuclear@2: emit_byte(state, 0xFF, return FALSE); nuclear@2: emit_byte(state, JPEG_RST0 + restart_num, return FALSE); nuclear@2: nuclear@2: /* Re-initialize DC predictions to 0 */ nuclear@2: for (ci = 0; ci < state->cinfo->comps_in_scan; ci++) nuclear@2: state->cur.last_dc_val[ci] = 0; nuclear@2: nuclear@2: /* The restart counter is not updated until we successfully write the MCU. */ nuclear@2: nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Encode and output one MCU's worth of Huffman-compressed coefficients. nuclear@2: */ nuclear@2: nuclear@2: METHODDEF(boolean) nuclear@2: encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data) nuclear@2: { nuclear@2: huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; nuclear@2: working_state state; nuclear@2: int blkn, ci; nuclear@2: jpeg_component_info * compptr; nuclear@2: nuclear@2: /* Load up working state */ nuclear@2: state.next_output_byte = cinfo->dest->next_output_byte; nuclear@2: state.free_in_buffer = cinfo->dest->free_in_buffer; nuclear@2: ASSIGN_STATE(state.cur, entropy->saved); nuclear@2: state.cinfo = cinfo; nuclear@2: nuclear@2: /* Emit restart marker if needed */ nuclear@2: if (cinfo->restart_interval) { nuclear@2: if (entropy->restarts_to_go == 0) nuclear@2: if (! emit_restart(&state, entropy->next_restart_num)) nuclear@2: return FALSE; nuclear@2: } nuclear@2: nuclear@2: /* Encode the MCU data blocks */ nuclear@2: for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { nuclear@2: ci = cinfo->MCU_membership[blkn]; nuclear@2: compptr = cinfo->cur_comp_info[ci]; nuclear@2: if (! encode_one_block(&state, nuclear@2: MCU_data[blkn][0], state.cur.last_dc_val[ci], nuclear@2: entropy->dc_derived_tbls[compptr->dc_tbl_no], nuclear@2: entropy->ac_derived_tbls[compptr->ac_tbl_no])) nuclear@2: return FALSE; nuclear@2: /* Update last_dc_val */ nuclear@2: state.cur.last_dc_val[ci] = MCU_data[blkn][0][0]; nuclear@2: } nuclear@2: nuclear@2: /* Completed MCU, so update state */ nuclear@2: cinfo->dest->next_output_byte = state.next_output_byte; nuclear@2: cinfo->dest->free_in_buffer = state.free_in_buffer; nuclear@2: ASSIGN_STATE(entropy->saved, state.cur); nuclear@2: nuclear@2: /* Update restart-interval state too */ nuclear@2: if (cinfo->restart_interval) { nuclear@2: if (entropy->restarts_to_go == 0) { nuclear@2: entropy->restarts_to_go = cinfo->restart_interval; nuclear@2: entropy->next_restart_num++; nuclear@2: entropy->next_restart_num &= 7; nuclear@2: } nuclear@2: entropy->restarts_to_go--; nuclear@2: } nuclear@2: nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Finish up at the end of a Huffman-compressed scan. nuclear@2: */ nuclear@2: nuclear@2: METHODDEF(void) nuclear@2: finish_pass_huff (j_compress_ptr cinfo) nuclear@2: { nuclear@2: huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; nuclear@2: working_state state; nuclear@2: nuclear@2: /* Load up working state ... flush_bits needs it */ nuclear@2: state.next_output_byte = cinfo->dest->next_output_byte; nuclear@2: state.free_in_buffer = cinfo->dest->free_in_buffer; nuclear@2: ASSIGN_STATE(state.cur, entropy->saved); nuclear@2: state.cinfo = cinfo; nuclear@2: nuclear@2: /* Flush out the last data */ nuclear@2: if (! flush_bits(&state)) nuclear@2: ERREXIT(cinfo, JERR_CANT_SUSPEND); nuclear@2: nuclear@2: /* Update state */ nuclear@2: cinfo->dest->next_output_byte = state.next_output_byte; nuclear@2: cinfo->dest->free_in_buffer = state.free_in_buffer; nuclear@2: ASSIGN_STATE(entropy->saved, state.cur); nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Huffman coding optimization. nuclear@2: * nuclear@2: * We first scan the supplied data and count the number of uses of each symbol nuclear@2: * that is to be Huffman-coded. (This process MUST agree with the code above.) nuclear@2: * Then we build a Huffman coding tree for the observed counts. nuclear@2: * Symbols which are not needed at all for the particular image are not nuclear@2: * assigned any code, which saves space in the DHT marker as well as in nuclear@2: * the compressed data. nuclear@2: */ nuclear@2: nuclear@2: #ifdef ENTROPY_OPT_SUPPORTED nuclear@2: nuclear@2: nuclear@2: /* Process a single block's worth of coefficients */ nuclear@2: nuclear@2: LOCAL(void) nuclear@2: htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val, nuclear@2: long dc_counts[], long ac_counts[]) nuclear@2: { nuclear@2: register int temp; nuclear@2: register int nbits; nuclear@2: register int k, r; nuclear@2: nuclear@2: /* Encode the DC coefficient difference per section F.1.2.1 */ nuclear@2: nuclear@2: temp = block[0] - last_dc_val; nuclear@2: if (temp < 0) nuclear@2: temp = -temp; nuclear@2: nuclear@2: /* Find the number of bits needed for the magnitude of the coefficient */ nuclear@2: nbits = 0; nuclear@2: while (temp) { nuclear@2: nbits++; nuclear@2: temp >>= 1; nuclear@2: } nuclear@2: /* Check for out-of-range coefficient values. nuclear@2: * Since we're encoding a difference, the range limit is twice as much. nuclear@2: */ nuclear@2: if (nbits > MAX_COEF_BITS+1) nuclear@2: ERREXIT(cinfo, JERR_BAD_DCT_COEF); nuclear@2: nuclear@2: /* Count the Huffman symbol for the number of bits */ nuclear@2: dc_counts[nbits]++; nuclear@2: nuclear@2: /* Encode the AC coefficients per section F.1.2.2 */ nuclear@2: nuclear@2: r = 0; /* r = run length of zeros */ nuclear@2: nuclear@2: for (k = 1; k < DCTSIZE2; k++) { nuclear@2: if ((temp = block[jpeg_natural_order[k]]) == 0) { nuclear@2: r++; nuclear@2: } else { nuclear@2: /* if run length > 15, must emit special run-length-16 codes (0xF0) */ nuclear@2: while (r > 15) { nuclear@2: ac_counts[0xF0]++; nuclear@2: r -= 16; nuclear@2: } nuclear@2: nuclear@2: /* Find the number of bits needed for the magnitude of the coefficient */ nuclear@2: if (temp < 0) nuclear@2: temp = -temp; nuclear@2: nuclear@2: /* Find the number of bits needed for the magnitude of the coefficient */ nuclear@2: nbits = 1; /* there must be at least one 1 bit */ nuclear@2: while ((temp >>= 1)) nuclear@2: nbits++; nuclear@2: /* Check for out-of-range coefficient values */ nuclear@2: if (nbits > MAX_COEF_BITS) nuclear@2: ERREXIT(cinfo, JERR_BAD_DCT_COEF); nuclear@2: nuclear@2: /* Count Huffman symbol for run length / number of bits */ nuclear@2: ac_counts[(r << 4) + nbits]++; nuclear@2: nuclear@2: r = 0; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* If the last coef(s) were zero, emit an end-of-block code */ nuclear@2: if (r > 0) nuclear@2: ac_counts[0]++; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Trial-encode one MCU's worth of Huffman-compressed coefficients. nuclear@2: * No data is actually output, so no suspension return is possible. nuclear@2: */ nuclear@2: nuclear@2: METHODDEF(boolean) nuclear@2: encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data) nuclear@2: { nuclear@2: huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; nuclear@2: int blkn, ci; nuclear@2: jpeg_component_info * compptr; nuclear@2: nuclear@2: /* Take care of restart intervals if needed */ nuclear@2: if (cinfo->restart_interval) { nuclear@2: if (entropy->restarts_to_go == 0) { nuclear@2: /* Re-initialize DC predictions to 0 */ nuclear@2: for (ci = 0; ci < cinfo->comps_in_scan; ci++) nuclear@2: entropy->saved.last_dc_val[ci] = 0; nuclear@2: /* Update restart state */ nuclear@2: entropy->restarts_to_go = cinfo->restart_interval; nuclear@2: } nuclear@2: entropy->restarts_to_go--; nuclear@2: } nuclear@2: nuclear@2: for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) { nuclear@2: ci = cinfo->MCU_membership[blkn]; nuclear@2: compptr = cinfo->cur_comp_info[ci]; nuclear@2: htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci], nuclear@2: entropy->dc_count_ptrs[compptr->dc_tbl_no], nuclear@2: entropy->ac_count_ptrs[compptr->ac_tbl_no]); nuclear@2: entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0]; nuclear@2: } nuclear@2: nuclear@2: return TRUE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Generate the best Huffman code table for the given counts, fill htbl. nuclear@2: * Note this is also used by jcphuff.c. nuclear@2: * nuclear@2: * The JPEG standard requires that no symbol be assigned a codeword of all nuclear@2: * one bits (so that padding bits added at the end of a compressed segment nuclear@2: * can't look like a valid code). Because of the canonical ordering of nuclear@2: * codewords, this just means that there must be an unused slot in the nuclear@2: * longest codeword length category. Section K.2 of the JPEG spec suggests nuclear@2: * reserving such a slot by pretending that symbol 256 is a valid symbol nuclear@2: * with count 1. In theory that's not optimal; giving it count zero but nuclear@2: * including it in the symbol set anyway should give a better Huffman code. nuclear@2: * But the theoretically better code actually seems to come out worse in nuclear@2: * practice, because it produces more all-ones bytes (which incur stuffed nuclear@2: * zero bytes in the final file). In any case the difference is tiny. nuclear@2: * nuclear@2: * The JPEG standard requires Huffman codes to be no more than 16 bits long. nuclear@2: * If some symbols have a very small but nonzero probability, the Huffman tree nuclear@2: * must be adjusted to meet the code length restriction. We currently use nuclear@2: * the adjustment method suggested in JPEG section K.2. This method is *not* nuclear@2: * optimal; it may not choose the best possible limited-length code. But nuclear@2: * typically only very-low-frequency symbols will be given less-than-optimal nuclear@2: * lengths, so the code is almost optimal. Experimental comparisons against nuclear@2: * an optimal limited-length-code algorithm indicate that the difference is nuclear@2: * microscopic --- usually less than a hundredth of a percent of total size. nuclear@2: * So the extra complexity of an optimal algorithm doesn't seem worthwhile. nuclear@2: */ nuclear@2: nuclear@2: GLOBAL(void) nuclear@2: jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]) nuclear@2: { nuclear@2: #define MAX_CLEN 32 /* assumed maximum initial code length */ nuclear@2: UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */ nuclear@2: int codesize[257]; /* codesize[k] = code length of symbol k */ nuclear@2: int others[257]; /* next symbol in current branch of tree */ nuclear@2: int c1, c2; nuclear@2: int p, i, j; nuclear@2: long v; nuclear@2: nuclear@2: /* This algorithm is explained in section K.2 of the JPEG standard */ nuclear@2: nuclear@2: MEMZERO(bits, SIZEOF(bits)); nuclear@2: MEMZERO(codesize, SIZEOF(codesize)); nuclear@2: for (i = 0; i < 257; i++) nuclear@2: others[i] = -1; /* init links to empty */ nuclear@2: nuclear@2: freq[256] = 1; /* make sure 256 has a nonzero count */ nuclear@2: /* Including the pseudo-symbol 256 in the Huffman procedure guarantees nuclear@2: * that no real symbol is given code-value of all ones, because 256 nuclear@2: * will be placed last in the largest codeword category. nuclear@2: */ nuclear@2: nuclear@2: /* Huffman's basic algorithm to assign optimal code lengths to symbols */ nuclear@2: nuclear@2: for (;;) { nuclear@2: /* Find the smallest nonzero frequency, set c1 = its symbol */ nuclear@2: /* In case of ties, take the larger symbol number */ nuclear@2: c1 = -1; nuclear@2: v = 1000000000L; nuclear@2: for (i = 0; i <= 256; i++) { nuclear@2: if (freq[i] && freq[i] <= v) { nuclear@2: v = freq[i]; nuclear@2: c1 = i; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* Find the next smallest nonzero frequency, set c2 = its symbol */ nuclear@2: /* In case of ties, take the larger symbol number */ nuclear@2: c2 = -1; nuclear@2: v = 1000000000L; nuclear@2: for (i = 0; i <= 256; i++) { nuclear@2: if (freq[i] && freq[i] <= v && i != c1) { nuclear@2: v = freq[i]; nuclear@2: c2 = i; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* Done if we've merged everything into one frequency */ nuclear@2: if (c2 < 0) nuclear@2: break; nuclear@2: nuclear@2: /* Else merge the two counts/trees */ nuclear@2: freq[c1] += freq[c2]; nuclear@2: freq[c2] = 0; nuclear@2: nuclear@2: /* Increment the codesize of everything in c1's tree branch */ nuclear@2: codesize[c1]++; nuclear@2: while (others[c1] >= 0) { nuclear@2: c1 = others[c1]; nuclear@2: codesize[c1]++; nuclear@2: } nuclear@2: nuclear@2: others[c1] = c2; /* chain c2 onto c1's tree branch */ nuclear@2: nuclear@2: /* Increment the codesize of everything in c2's tree branch */ nuclear@2: codesize[c2]++; nuclear@2: while (others[c2] >= 0) { nuclear@2: c2 = others[c2]; nuclear@2: codesize[c2]++; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* Now count the number of symbols of each code length */ nuclear@2: for (i = 0; i <= 256; i++) { nuclear@2: if (codesize[i]) { nuclear@2: /* The JPEG standard seems to think that this can't happen, */ nuclear@2: /* but I'm paranoid... */ nuclear@2: if (codesize[i] > MAX_CLEN) nuclear@2: ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW); nuclear@2: nuclear@2: bits[codesize[i]]++; nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure nuclear@2: * Huffman procedure assigned any such lengths, we must adjust the coding. nuclear@2: * Here is what the JPEG spec says about how this next bit works: nuclear@2: * Since symbols are paired for the longest Huffman code, the symbols are nuclear@2: * removed from this length category two at a time. The prefix for the pair nuclear@2: * (which is one bit shorter) is allocated to one of the pair; then, nuclear@2: * skipping the BITS entry for that prefix length, a code word from the next nuclear@2: * shortest nonzero BITS entry is converted into a prefix for two code words nuclear@2: * one bit longer. nuclear@2: */ nuclear@2: nuclear@2: for (i = MAX_CLEN; i > 16; i--) { nuclear@2: while (bits[i] > 0) { nuclear@2: j = i - 2; /* find length of new prefix to be used */ nuclear@2: while (bits[j] == 0) nuclear@2: j--; nuclear@2: nuclear@2: bits[i] -= 2; /* remove two symbols */ nuclear@2: bits[i-1]++; /* one goes in this length */ nuclear@2: bits[j+1] += 2; /* two new symbols in this length */ nuclear@2: bits[j]--; /* symbol of this length is now a prefix */ nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* Remove the count for the pseudo-symbol 256 from the largest codelength */ nuclear@2: while (bits[i] == 0) /* find largest codelength still in use */ nuclear@2: i--; nuclear@2: bits[i]--; nuclear@2: nuclear@2: /* Return final symbol counts (only for lengths 0..16) */ nuclear@2: MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits)); nuclear@2: nuclear@2: /* Return a list of the symbols sorted by code length */ nuclear@2: /* It's not real clear to me why we don't need to consider the codelength nuclear@2: * changes made above, but the JPEG spec seems to think this works. nuclear@2: */ nuclear@2: p = 0; nuclear@2: for (i = 1; i <= MAX_CLEN; i++) { nuclear@2: for (j = 0; j <= 255; j++) { nuclear@2: if (codesize[j] == i) { nuclear@2: htbl->huffval[p] = (UINT8) j; nuclear@2: p++; nuclear@2: } nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: /* Set sent_table FALSE so updated table will be written to JPEG file. */ nuclear@2: htbl->sent_table = FALSE; nuclear@2: } nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Finish up a statistics-gathering pass and create the new Huffman tables. nuclear@2: */ nuclear@2: nuclear@2: METHODDEF(void) nuclear@2: finish_pass_gather (j_compress_ptr cinfo) nuclear@2: { nuclear@2: huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; nuclear@2: int ci, dctbl, actbl; nuclear@2: jpeg_component_info * compptr; nuclear@2: JHUFF_TBL **htblptr; nuclear@2: boolean did_dc[NUM_HUFF_TBLS]; nuclear@2: boolean did_ac[NUM_HUFF_TBLS]; nuclear@2: nuclear@2: /* It's important not to apply jpeg_gen_optimal_table more than once nuclear@2: * per table, because it clobbers the input frequency counts! nuclear@2: */ nuclear@2: MEMZERO(did_dc, SIZEOF(did_dc)); nuclear@2: MEMZERO(did_ac, SIZEOF(did_ac)); nuclear@2: nuclear@2: for (ci = 0; ci < cinfo->comps_in_scan; ci++) { nuclear@2: compptr = cinfo->cur_comp_info[ci]; nuclear@2: dctbl = compptr->dc_tbl_no; nuclear@2: actbl = compptr->ac_tbl_no; nuclear@2: if (! did_dc[dctbl]) { nuclear@2: htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl]; nuclear@2: if (*htblptr == NULL) nuclear@2: *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); nuclear@2: jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]); nuclear@2: did_dc[dctbl] = TRUE; nuclear@2: } nuclear@2: if (! did_ac[actbl]) { nuclear@2: htblptr = & cinfo->ac_huff_tbl_ptrs[actbl]; nuclear@2: if (*htblptr == NULL) nuclear@2: *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); nuclear@2: jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]); nuclear@2: did_ac[actbl] = TRUE; nuclear@2: } nuclear@2: } nuclear@2: } nuclear@2: nuclear@2: nuclear@2: #endif /* ENTROPY_OPT_SUPPORTED */ nuclear@2: nuclear@2: nuclear@2: /* nuclear@2: * Module initialization routine for Huffman entropy encoding. nuclear@2: */ nuclear@2: nuclear@2: GLOBAL(void) nuclear@2: jinit_huff_encoder (j_compress_ptr cinfo) nuclear@2: { nuclear@2: huff_entropy_ptr entropy; nuclear@2: int i; nuclear@2: nuclear@2: entropy = (huff_entropy_ptr) nuclear@2: (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, nuclear@2: SIZEOF(huff_entropy_encoder)); nuclear@2: cinfo->entropy = (struct jpeg_entropy_encoder *) entropy; nuclear@2: entropy->pub.start_pass = start_pass_huff; nuclear@2: nuclear@2: /* Mark tables unallocated */ nuclear@2: for (i = 0; i < NUM_HUFF_TBLS; i++) { nuclear@2: entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; nuclear@2: #ifdef ENTROPY_OPT_SUPPORTED nuclear@2: entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL; nuclear@2: #endif nuclear@2: } nuclear@2: }