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