Path: blob/master/src/java.desktop/share/native/libjavajpeg/jchuff.c
41152 views
/*1* reserved comment block2* DO NOT REMOVE OR ALTER!3*/4/*5* jchuff.c6*7* Copyright (C) 1991-1997, Thomas G. Lane.8* This file is part of the Independent JPEG Group's software.9* For conditions of distribution and use, see the accompanying README file.10*11* This file contains Huffman entropy encoding routines.12*13* Much of the complexity here has to do with supporting output suspension.14* If the data destination module demands suspension, we want to be able to15* back up to the start of the current MCU. To do this, we copy state16* variables into local working storage, and update them back to the17* permanent JPEG objects only upon successful completion of an MCU.18*/1920#define JPEG_INTERNALS21#include "jinclude.h"22#include "jpeglib.h"23#include "jchuff.h" /* Declarations shared with jcphuff.c */242526/* Expanded entropy encoder object for Huffman encoding.27*28* The savable_state subrecord contains fields that change within an MCU,29* but must not be updated permanently until we complete the MCU.30*/3132typedef struct {33INT32 put_buffer; /* current bit-accumulation buffer */34int put_bits; /* # of bits now in it */35int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */36} savable_state;3738/* This macro is to work around compilers with missing or broken39* structure assignment. You'll need to fix this code if you have40* such a compiler and you change MAX_COMPS_IN_SCAN.41*/4243#ifndef NO_STRUCT_ASSIGN44#define ASSIGN_STATE(dest,src) ((dest) = (src))45#else46#if MAX_COMPS_IN_SCAN == 447#define ASSIGN_STATE(dest,src) \48((dest).put_buffer = (src).put_buffer, \49(dest).put_bits = (src).put_bits, \50(dest).last_dc_val[0] = (src).last_dc_val[0], \51(dest).last_dc_val[1] = (src).last_dc_val[1], \52(dest).last_dc_val[2] = (src).last_dc_val[2], \53(dest).last_dc_val[3] = (src).last_dc_val[3])54#endif55#endif565758typedef struct {59struct jpeg_entropy_encoder pub; /* public fields */6061savable_state saved; /* Bit buffer & DC state at start of MCU */6263/* These fields are NOT loaded into local working state. */64unsigned int restarts_to_go; /* MCUs left in this restart interval */65int next_restart_num; /* next restart number to write (0-7) */6667/* Pointers to derived tables (these workspaces have image lifespan) */68c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];69c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];7071#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */72long * dc_count_ptrs[NUM_HUFF_TBLS];73long * ac_count_ptrs[NUM_HUFF_TBLS];74#endif75} huff_entropy_encoder;7677typedef huff_entropy_encoder * huff_entropy_ptr;7879/* Working state while writing an MCU.80* This struct contains all the fields that are needed by subroutines.81*/8283typedef struct {84JOCTET * next_output_byte; /* => next byte to write in buffer */85size_t free_in_buffer; /* # of byte spaces remaining in buffer */86savable_state cur; /* Current bit buffer & DC state */87j_compress_ptr cinfo; /* dump_buffer needs access to this */88} working_state;899091/* Forward declarations */92METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,93JBLOCKROW *MCU_data));94METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));95#ifdef ENTROPY_OPT_SUPPORTED96METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,97JBLOCKROW *MCU_data));98METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));99#endif100101102/*103* Initialize for a Huffman-compressed scan.104* If gather_statistics is TRUE, we do not output anything during the scan,105* just count the Huffman symbols used and generate Huffman code tables.106*/107108METHODDEF(void)109start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)110{111huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;112int ci, dctbl, actbl;113jpeg_component_info * compptr;114115if (gather_statistics) {116#ifdef ENTROPY_OPT_SUPPORTED117entropy->pub.encode_mcu = encode_mcu_gather;118entropy->pub.finish_pass = finish_pass_gather;119#else120ERREXIT(cinfo, JERR_NOT_COMPILED);121#endif122} else {123entropy->pub.encode_mcu = encode_mcu_huff;124entropy->pub.finish_pass = finish_pass_huff;125}126127for (ci = 0; ci < cinfo->comps_in_scan; ci++) {128compptr = cinfo->cur_comp_info[ci];129dctbl = compptr->dc_tbl_no;130actbl = compptr->ac_tbl_no;131if (gather_statistics) {132#ifdef ENTROPY_OPT_SUPPORTED133/* Check for invalid table indexes */134/* (make_c_derived_tbl does this in the other path) */135if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)136ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);137if (actbl < 0 || actbl >= NUM_HUFF_TBLS)138ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);139/* Allocate and zero the statistics tables */140/* Note that jpeg_gen_optimal_table expects 257 entries in each table! */141if (entropy->dc_count_ptrs[dctbl] == NULL)142entropy->dc_count_ptrs[dctbl] = (long *)143(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,144257 * SIZEOF(long));145MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));146if (entropy->ac_count_ptrs[actbl] == NULL)147entropy->ac_count_ptrs[actbl] = (long *)148(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,149257 * SIZEOF(long));150MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));151#endif152} else {153/* Compute derived values for Huffman tables */154/* We may do this more than once for a table, but it's not expensive */155jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,156& entropy->dc_derived_tbls[dctbl]);157jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,158& entropy->ac_derived_tbls[actbl]);159}160/* Initialize DC predictions to 0 */161entropy->saved.last_dc_val[ci] = 0;162}163164/* Initialize bit buffer to empty */165entropy->saved.put_buffer = 0;166entropy->saved.put_bits = 0;167168/* Initialize restart stuff */169entropy->restarts_to_go = cinfo->restart_interval;170entropy->next_restart_num = 0;171}172173174/*175* Compute the derived values for a Huffman table.176* This routine also performs some validation checks on the table.177*178* Note this is also used by jcphuff.c.179*/180181GLOBAL(void)182jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,183c_derived_tbl ** pdtbl)184{185JHUFF_TBL *htbl;186c_derived_tbl *dtbl;187int p, i, l, lastp, si, maxsymbol;188char huffsize[257];189unsigned int huffcode[257];190unsigned int code;191192/* Note that huffsize[] and huffcode[] are filled in code-length order,193* paralleling the order of the symbols themselves in htbl->huffval[].194*/195196/* Find the input Huffman table */197if (tblno < 0 || tblno >= NUM_HUFF_TBLS)198ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);199htbl =200isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];201if (htbl == NULL)202ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);203204/* Allocate a workspace if we haven't already done so. */205if (*pdtbl == NULL)206*pdtbl = (c_derived_tbl *)207(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,208SIZEOF(c_derived_tbl));209dtbl = *pdtbl;210211/* Figure C.1: make table of Huffman code length for each symbol */212213p = 0;214for (l = 1; l <= 16; l++) {215i = (int) htbl->bits[l];216if (i < 0 || p + i > 256) /* protect against table overrun */217ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);218while (i--)219huffsize[p++] = (char) l;220}221huffsize[p] = 0;222lastp = p;223224/* Figure C.2: generate the codes themselves */225/* We also validate that the counts represent a legal Huffman code tree. */226227code = 0;228si = huffsize[0];229p = 0;230while (huffsize[p]) {231while (((int) huffsize[p]) == si) {232huffcode[p++] = code;233code++;234}235/* code is now 1 more than the last code used for codelength si; but236* it must still fit in si bits, since no code is allowed to be all ones.237*/238if (((INT32) code) >= (((INT32) 1) << si))239ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);240code <<= 1;241si++;242}243244/* Figure C.3: generate encoding tables */245/* These are code and size indexed by symbol value */246247/* Set all codeless symbols to have code length 0;248* this lets us detect duplicate VAL entries here, and later249* allows emit_bits to detect any attempt to emit such symbols.250*/251MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));252253/* This is also a convenient place to check for out-of-range254* and duplicated VAL entries. We allow 0..255 for AC symbols255* but only 0..15 for DC. (We could constrain them further256* based on data depth and mode, but this seems enough.)257*/258maxsymbol = isDC ? 15 : 255;259260for (p = 0; p < lastp; p++) {261i = htbl->huffval[p];262if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])263ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);264dtbl->ehufco[i] = huffcode[p];265dtbl->ehufsi[i] = huffsize[p];266}267}268269270/* Outputting bytes to the file */271272/* Emit a byte, taking 'action' if must suspend. */273#define emit_byte(state,val,action) \274{ *(state)->next_output_byte++ = (JOCTET) (val); \275if (--(state)->free_in_buffer == 0) \276if (! dump_buffer(state)) \277{ action; } }278279280LOCAL(boolean)281dump_buffer (working_state * state)282/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */283{284struct jpeg_destination_mgr * dest = state->cinfo->dest;285286if (! (*dest->empty_output_buffer) (state->cinfo))287return FALSE;288/* After a successful buffer dump, must reset buffer pointers */289state->next_output_byte = dest->next_output_byte;290state->free_in_buffer = dest->free_in_buffer;291return TRUE;292}293294295/* Outputting bits to the file */296297/* Only the right 24 bits of put_buffer are used; the valid bits are298* left-justified in this part. At most 16 bits can be passed to emit_bits299* in one call, and we never retain more than 7 bits in put_buffer300* between calls, so 24 bits are sufficient.301*/302303INLINE304LOCAL(boolean)305emit_bits (working_state * state, unsigned int code, int size)306/* Emit some bits; return TRUE if successful, FALSE if must suspend */307{308/* This routine is heavily used, so it's worth coding tightly. */309register INT32 put_buffer = (INT32) code;310register int put_bits = state->cur.put_bits;311312/* if size is 0, caller used an invalid Huffman table entry */313if (size == 0)314ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);315316put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */317318put_bits += size; /* new number of bits in buffer */319320put_buffer <<= 24 - put_bits; /* align incoming bits */321322put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */323324while (put_bits >= 8) {325int c = (int) ((put_buffer >> 16) & 0xFF);326327emit_byte(state, c, return FALSE);328if (c == 0xFF) { /* need to stuff a zero byte? */329emit_byte(state, 0, return FALSE);330}331put_buffer <<= 8;332put_bits -= 8;333}334335state->cur.put_buffer = put_buffer; /* update state variables */336state->cur.put_bits = put_bits;337338return TRUE;339}340341342LOCAL(boolean)343flush_bits (working_state * state)344{345if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */346return FALSE;347state->cur.put_buffer = 0; /* and reset bit-buffer to empty */348state->cur.put_bits = 0;349return TRUE;350}351352353/* Encode a single block's worth of coefficients */354355LOCAL(boolean)356encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,357c_derived_tbl *dctbl, c_derived_tbl *actbl)358{359register int temp, temp2;360register int nbits;361register int k, r, i;362363/* Encode the DC coefficient difference per section F.1.2.1 */364365temp = temp2 = block[0] - last_dc_val;366367if (temp < 0) {368temp = -temp; /* temp is abs value of input */369/* For a negative input, want temp2 = bitwise complement of abs(input) */370/* This code assumes we are on a two's complement machine */371temp2--;372}373374/* Find the number of bits needed for the magnitude of the coefficient */375nbits = 0;376while (temp) {377nbits++;378temp >>= 1;379}380/* Check for out-of-range coefficient values.381* Since we're encoding a difference, the range limit is twice as much.382*/383if (nbits > MAX_COEF_BITS+1)384ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);385386/* Emit the Huffman-coded symbol for the number of bits */387if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))388return FALSE;389390/* Emit that number of bits of the value, if positive, */391/* or the complement of its magnitude, if negative. */392if (nbits) /* emit_bits rejects calls with size 0 */393if (! emit_bits(state, (unsigned int) temp2, nbits))394return FALSE;395396/* Encode the AC coefficients per section F.1.2.2 */397398r = 0; /* r = run length of zeros */399400for (k = 1; k < DCTSIZE2; k++) {401if ((temp = block[jpeg_natural_order[k]]) == 0) {402r++;403} else {404/* if run length > 15, must emit special run-length-16 codes (0xF0) */405while (r > 15) {406if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))407return FALSE;408r -= 16;409}410411temp2 = temp;412if (temp < 0) {413temp = -temp; /* temp is abs value of input */414/* This code assumes we are on a two's complement machine */415temp2--;416}417418/* Find the number of bits needed for the magnitude of the coefficient */419nbits = 1; /* there must be at least one 1 bit */420while ((temp >>= 1))421nbits++;422/* Check for out-of-range coefficient values */423if (nbits > MAX_COEF_BITS)424ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);425426/* Emit Huffman symbol for run length / number of bits */427i = (r << 4) + nbits;428if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))429return FALSE;430431/* Emit that number of bits of the value, if positive, */432/* or the complement of its magnitude, if negative. */433if (! emit_bits(state, (unsigned int) temp2, nbits))434return FALSE;435436r = 0;437}438}439440/* If the last coef(s) were zero, emit an end-of-block code */441if (r > 0)442if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))443return FALSE;444445return TRUE;446}447448449/*450* Emit a restart marker & resynchronize predictions.451*/452453LOCAL(boolean)454emit_restart (working_state * state, int restart_num)455{456int ci;457458if (! flush_bits(state))459return FALSE;460461emit_byte(state, 0xFF, return FALSE);462emit_byte(state, JPEG_RST0 + restart_num, return FALSE);463464/* Re-initialize DC predictions to 0 */465for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)466state->cur.last_dc_val[ci] = 0;467468/* The restart counter is not updated until we successfully write the MCU. */469470return TRUE;471}472473474/*475* Encode and output one MCU's worth of Huffman-compressed coefficients.476*/477478METHODDEF(boolean)479encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)480{481huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;482working_state state;483int blkn, ci;484jpeg_component_info * compptr;485486/* Load up working state */487state.next_output_byte = cinfo->dest->next_output_byte;488state.free_in_buffer = cinfo->dest->free_in_buffer;489ASSIGN_STATE(state.cur, entropy->saved);490state.cinfo = cinfo;491492/* Emit restart marker if needed */493if (cinfo->restart_interval) {494if (entropy->restarts_to_go == 0)495if (! emit_restart(&state, entropy->next_restart_num))496return FALSE;497}498499/* Encode the MCU data blocks */500for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {501ci = cinfo->MCU_membership[blkn];502compptr = cinfo->cur_comp_info[ci];503if (! encode_one_block(&state,504MCU_data[blkn][0], state.cur.last_dc_val[ci],505entropy->dc_derived_tbls[compptr->dc_tbl_no],506entropy->ac_derived_tbls[compptr->ac_tbl_no]))507return FALSE;508/* Update last_dc_val */509state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];510}511512/* Completed MCU, so update state */513cinfo->dest->next_output_byte = state.next_output_byte;514cinfo->dest->free_in_buffer = state.free_in_buffer;515ASSIGN_STATE(entropy->saved, state.cur);516517/* Update restart-interval state too */518if (cinfo->restart_interval) {519if (entropy->restarts_to_go == 0) {520entropy->restarts_to_go = cinfo->restart_interval;521entropy->next_restart_num++;522entropy->next_restart_num &= 7;523}524entropy->restarts_to_go--;525}526527return TRUE;528}529530531/*532* Finish up at the end of a Huffman-compressed scan.533*/534535METHODDEF(void)536finish_pass_huff (j_compress_ptr cinfo)537{538huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;539working_state state;540541/* Load up working state ... flush_bits needs it */542state.next_output_byte = cinfo->dest->next_output_byte;543state.free_in_buffer = cinfo->dest->free_in_buffer;544ASSIGN_STATE(state.cur, entropy->saved);545state.cinfo = cinfo;546547/* Flush out the last data */548if (! flush_bits(&state))549ERREXIT(cinfo, JERR_CANT_SUSPEND);550551/* Update state */552cinfo->dest->next_output_byte = state.next_output_byte;553cinfo->dest->free_in_buffer = state.free_in_buffer;554ASSIGN_STATE(entropy->saved, state.cur);555}556557558/*559* Huffman coding optimization.560*561* We first scan the supplied data and count the number of uses of each symbol562* that is to be Huffman-coded. (This process MUST agree with the code above.)563* Then we build a Huffman coding tree for the observed counts.564* Symbols which are not needed at all for the particular image are not565* assigned any code, which saves space in the DHT marker as well as in566* the compressed data.567*/568569#ifdef ENTROPY_OPT_SUPPORTED570571572/* Process a single block's worth of coefficients */573574LOCAL(void)575htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,576long dc_counts[], long ac_counts[])577{578register int temp;579register int nbits;580register int k, r;581582/* Encode the DC coefficient difference per section F.1.2.1 */583584temp = block[0] - last_dc_val;585if (temp < 0)586temp = -temp;587588/* Find the number of bits needed for the magnitude of the coefficient */589nbits = 0;590while (temp) {591nbits++;592temp >>= 1;593}594/* Check for out-of-range coefficient values.595* Since we're encoding a difference, the range limit is twice as much.596*/597if (nbits > MAX_COEF_BITS+1)598ERREXIT(cinfo, JERR_BAD_DCT_COEF);599600/* Count the Huffman symbol for the number of bits */601dc_counts[nbits]++;602603/* Encode the AC coefficients per section F.1.2.2 */604605r = 0; /* r = run length of zeros */606607for (k = 1; k < DCTSIZE2; k++) {608if ((temp = block[jpeg_natural_order[k]]) == 0) {609r++;610} else {611/* if run length > 15, must emit special run-length-16 codes (0xF0) */612while (r > 15) {613ac_counts[0xF0]++;614r -= 16;615}616617/* Find the number of bits needed for the magnitude of the coefficient */618if (temp < 0)619temp = -temp;620621/* Find the number of bits needed for the magnitude of the coefficient */622nbits = 1; /* there must be at least one 1 bit */623while ((temp >>= 1))624nbits++;625/* Check for out-of-range coefficient values */626if (nbits > MAX_COEF_BITS)627ERREXIT(cinfo, JERR_BAD_DCT_COEF);628629/* Count Huffman symbol for run length / number of bits */630ac_counts[(r << 4) + nbits]++;631632r = 0;633}634}635636/* If the last coef(s) were zero, emit an end-of-block code */637if (r > 0)638ac_counts[0]++;639}640641642/*643* Trial-encode one MCU's worth of Huffman-compressed coefficients.644* No data is actually output, so no suspension return is possible.645*/646647METHODDEF(boolean)648encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)649{650huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;651int blkn, ci;652jpeg_component_info * compptr;653654/* Take care of restart intervals if needed */655if (cinfo->restart_interval) {656if (entropy->restarts_to_go == 0) {657/* Re-initialize DC predictions to 0 */658for (ci = 0; ci < cinfo->comps_in_scan; ci++)659entropy->saved.last_dc_val[ci] = 0;660/* Update restart state */661entropy->restarts_to_go = cinfo->restart_interval;662}663entropy->restarts_to_go--;664}665666for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {667ci = cinfo->MCU_membership[blkn];668compptr = cinfo->cur_comp_info[ci];669htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],670entropy->dc_count_ptrs[compptr->dc_tbl_no],671entropy->ac_count_ptrs[compptr->ac_tbl_no]);672entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];673}674675return TRUE;676}677678679/*680* Generate the best Huffman code table for the given counts, fill htbl.681* Note this is also used by jcphuff.c.682*683* The JPEG standard requires that no symbol be assigned a codeword of all684* one bits (so that padding bits added at the end of a compressed segment685* can't look like a valid code). Because of the canonical ordering of686* codewords, this just means that there must be an unused slot in the687* longest codeword length category. Section K.2 of the JPEG spec suggests688* reserving such a slot by pretending that symbol 256 is a valid symbol689* with count 1. In theory that's not optimal; giving it count zero but690* including it in the symbol set anyway should give a better Huffman code.691* But the theoretically better code actually seems to come out worse in692* practice, because it produces more all-ones bytes (which incur stuffed693* zero bytes in the final file). In any case the difference is tiny.694*695* The JPEG standard requires Huffman codes to be no more than 16 bits long.696* If some symbols have a very small but nonzero probability, the Huffman tree697* must be adjusted to meet the code length restriction. We currently use698* the adjustment method suggested in JPEG section K.2. This method is *not*699* optimal; it may not choose the best possible limited-length code. But700* typically only very-low-frequency symbols will be given less-than-optimal701* lengths, so the code is almost optimal. Experimental comparisons against702* an optimal limited-length-code algorithm indicate that the difference is703* microscopic --- usually less than a hundredth of a percent of total size.704* So the extra complexity of an optimal algorithm doesn't seem worthwhile.705*/706707GLOBAL(void)708jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])709{710#define MAX_CLEN 32 /* assumed maximum initial code length */711UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */712int codesize[257]; /* codesize[k] = code length of symbol k */713int others[257]; /* next symbol in current branch of tree */714int c1, c2;715int p, i, j;716long v;717718/* This algorithm is explained in section K.2 of the JPEG standard */719720MEMZERO(bits, SIZEOF(bits));721MEMZERO(codesize, SIZEOF(codesize));722for (i = 0; i < 257; i++)723others[i] = -1; /* init links to empty */724725freq[256] = 1; /* make sure 256 has a nonzero count */726/* Including the pseudo-symbol 256 in the Huffman procedure guarantees727* that no real symbol is given code-value of all ones, because 256728* will be placed last in the largest codeword category.729*/730731/* Huffman's basic algorithm to assign optimal code lengths to symbols */732733for (;;) {734/* Find the smallest nonzero frequency, set c1 = its symbol */735/* In case of ties, take the larger symbol number */736c1 = -1;737v = 1000000000L;738for (i = 0; i <= 256; i++) {739if (freq[i] && freq[i] <= v) {740v = freq[i];741c1 = i;742}743}744745/* Find the next smallest nonzero frequency, set c2 = its symbol */746/* In case of ties, take the larger symbol number */747c2 = -1;748v = 1000000000L;749for (i = 0; i <= 256; i++) {750if (freq[i] && freq[i] <= v && i != c1) {751v = freq[i];752c2 = i;753}754}755756/* Done if we've merged everything into one frequency */757if (c2 < 0)758break;759760/* Else merge the two counts/trees */761freq[c1] += freq[c2];762freq[c2] = 0;763764/* Increment the codesize of everything in c1's tree branch */765codesize[c1]++;766while (others[c1] >= 0) {767c1 = others[c1];768codesize[c1]++;769}770771others[c1] = c2; /* chain c2 onto c1's tree branch */772773/* Increment the codesize of everything in c2's tree branch */774codesize[c2]++;775while (others[c2] >= 0) {776c2 = others[c2];777codesize[c2]++;778}779}780781/* Now count the number of symbols of each code length */782for (i = 0; i <= 256; i++) {783if (codesize[i]) {784/* The JPEG standard seems to think that this can't happen, */785/* but I'm paranoid... */786if (codesize[i] > MAX_CLEN)787ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);788789bits[codesize[i]]++;790}791}792793/* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure794* Huffman procedure assigned any such lengths, we must adjust the coding.795* Here is what the JPEG spec says about how this next bit works:796* Since symbols are paired for the longest Huffman code, the symbols are797* removed from this length category two at a time. The prefix for the pair798* (which is one bit shorter) is allocated to one of the pair; then,799* skipping the BITS entry for that prefix length, a code word from the next800* shortest nonzero BITS entry is converted into a prefix for two code words801* one bit longer.802*/803804for (i = MAX_CLEN; i > 16; i--) {805while (bits[i] > 0) {806j = i - 2; /* find length of new prefix to be used */807while (bits[j] == 0) {808if (j == 0)809ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);810j--;811}812813bits[i] -= 2; /* remove two symbols */814bits[i-1]++; /* one goes in this length */815bits[j+1] += 2; /* two new symbols in this length */816bits[j]--; /* symbol of this length is now a prefix */817}818}819820/* Remove the count for the pseudo-symbol 256 from the largest codelength */821while (bits[i] == 0) /* find largest codelength still in use */822i--;823bits[i]--;824825/* Return final symbol counts (only for lengths 0..16) */826MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));827828/* Return a list of the symbols sorted by code length */829/* It's not real clear to me why we don't need to consider the codelength830* changes made above, but the JPEG spec seems to think this works.831*/832p = 0;833for (i = 1; i <= MAX_CLEN; i++) {834for (j = 0; j <= 255; j++) {835if (codesize[j] == i) {836htbl->huffval[p] = (UINT8) j;837p++;838}839}840}841842/* Set sent_table FALSE so updated table will be written to JPEG file. */843htbl->sent_table = FALSE;844}845846847/*848* Finish up a statistics-gathering pass and create the new Huffman tables.849*/850851METHODDEF(void)852finish_pass_gather (j_compress_ptr cinfo)853{854huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;855int ci, dctbl, actbl;856jpeg_component_info * compptr;857JHUFF_TBL **htblptr;858boolean did_dc[NUM_HUFF_TBLS];859boolean did_ac[NUM_HUFF_TBLS];860861/* It's important not to apply jpeg_gen_optimal_table more than once862* per table, because it clobbers the input frequency counts!863*/864MEMZERO(did_dc, SIZEOF(did_dc));865MEMZERO(did_ac, SIZEOF(did_ac));866867for (ci = 0; ci < cinfo->comps_in_scan; ci++) {868compptr = cinfo->cur_comp_info[ci];869dctbl = compptr->dc_tbl_no;870actbl = compptr->ac_tbl_no;871if (! did_dc[dctbl]) {872htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];873if (*htblptr == NULL)874*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);875jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);876did_dc[dctbl] = TRUE;877}878if (! did_ac[actbl]) {879htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];880if (*htblptr == NULL)881*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);882jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);883did_ac[actbl] = TRUE;884}885}886}887888889#endif /* ENTROPY_OPT_SUPPORTED */890891892/*893* Module initialization routine for Huffman entropy encoding.894*/895896GLOBAL(void)897jinit_huff_encoder (j_compress_ptr cinfo)898{899huff_entropy_ptr entropy;900int i;901902entropy = (huff_entropy_ptr)903(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,904SIZEOF(huff_entropy_encoder));905cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;906entropy->pub.start_pass = start_pass_huff;907908/* Mark tables unallocated */909for (i = 0; i < NUM_HUFF_TBLS; i++) {910entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;911#ifdef ENTROPY_OPT_SUPPORTED912entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;913#endif914}915}916917918