/*1* jchuff.c2*3* Copyright (C) 1991-1997, Thomas G. Lane.4* Modified 2006-2023 by Guido Vollbeding.5* This file is part of the Independent JPEG Group's software.6* For conditions of distribution and use, see the accompanying README file.7*8* This file contains Huffman entropy encoding routines.9* Both sequential and progressive modes are supported in this single module.10*11* Much of the complexity here has to do with supporting output suspension.12* If the data destination module demands suspension, we want to be able to13* back up to the start of the current MCU. To do this, we copy state14* variables into local working storage, and update them back to the15* permanent JPEG objects only upon successful completion of an MCU.16*17* We do not support output suspension for the progressive JPEG mode, since18* the library currently does not allow multiple-scan files to be written19* with output suspension.20*/2122#define JPEG_INTERNALS23#include "jinclude.h"24#include "jpeglib.h"252627/* The legal range of a DCT coefficient is28* -1024 .. +1023 for 8-bit sample data precision;29* -16384 .. +16383 for 12-bit sample data precision.30* Hence the magnitude should always fit in sample data precision + 2 bits.31*/3233/* Derived data constructed for each Huffman table */3435typedef struct {36unsigned int ehufco[256]; /* code for each symbol */37char ehufsi[256]; /* length of code for each symbol */38/* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */39} c_derived_tbl;404142/* Expanded entropy encoder object for Huffman encoding.43*44* The savable_state subrecord contains fields that change within an MCU,45* but must not be updated permanently until we complete the MCU.46*/4748typedef struct {49INT32 put_buffer; /* current bit-accumulation buffer */50int put_bits; /* # of bits now in it */51int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */52} savable_state;5354/* This macro is to work around compilers with missing or broken55* structure assignment. You'll need to fix this code if you have56* such a compiler and you change MAX_COMPS_IN_SCAN.57*/5859#ifndef NO_STRUCT_ASSIGN60#define ASSIGN_STATE(dest,src) ((dest) = (src))61#else62#if MAX_COMPS_IN_SCAN == 463#define ASSIGN_STATE(dest,src) \64((dest).put_buffer = (src).put_buffer, \65(dest).put_bits = (src).put_bits, \66(dest).last_dc_val[0] = (src).last_dc_val[0], \67(dest).last_dc_val[1] = (src).last_dc_val[1], \68(dest).last_dc_val[2] = (src).last_dc_val[2], \69(dest).last_dc_val[3] = (src).last_dc_val[3])70#endif71#endif727374typedef struct {75struct jpeg_entropy_encoder pub; /* public fields */7677savable_state saved; /* Bit buffer & DC state at start of MCU */7879/* These fields are NOT loaded into local working state. */80unsigned int restarts_to_go; /* MCUs left in this restart interval */81int next_restart_num; /* next restart number to write (0-7) */8283/* Pointers to derived tables (these workspaces have image lifespan) */84c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];85c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];8687/* Statistics tables for optimization */88long * dc_count_ptrs[NUM_HUFF_TBLS];89long * ac_count_ptrs[NUM_HUFF_TBLS];9091/* Following fields used only in progressive mode */9293/* Mode flag: TRUE for optimization, FALSE for actual data output */94boolean gather_statistics;9596/* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.97*/98JOCTET * next_output_byte; /* => next byte to write in buffer */99size_t free_in_buffer; /* # of byte spaces remaining in buffer */100j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */101102/* Coding status for AC components */103int ac_tbl_no; /* the table number of the single component */104unsigned int EOBRUN; /* run length of EOBs */105unsigned int BE; /* # of buffered correction bits before MCU */106char * bit_buffer; /* buffer for correction bits (1 per char) */107/* packing correction bits tightly would save some space but cost time... */108} huff_entropy_encoder;109110typedef huff_entropy_encoder * huff_entropy_ptr;111112/* Working state while writing an MCU (sequential mode).113* This struct contains all the fields that are needed by subroutines.114*/115116typedef struct {117JOCTET * next_output_byte; /* => next byte to write in buffer */118size_t free_in_buffer; /* # of byte spaces remaining in buffer */119savable_state cur; /* Current bit buffer & DC state */120j_compress_ptr cinfo; /* dump_buffer needs access to this */121} working_state;122123/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit124* buffer can hold. Larger sizes may slightly improve compression, but125* 1000 is already well into the realm of overkill.126* The minimum safe size is 64 bits.127*/128129#define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */130131/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.132* We assume that int right shift is unsigned if INT32 right shift is,133* which should be safe.134*/135136#ifdef RIGHT_SHIFT_IS_UNSIGNED137#define ISHIFT_TEMPS int ishift_temp;138#define IRIGHT_SHIFT(x,shft) \139((ishift_temp = (x)) < 0 ? \140(ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \141(ishift_temp >> (shft)))142#else143#define ISHIFT_TEMPS144#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))145#endif146147148/*149* Compute the derived values for a Huffman table.150* This routine also performs some validation checks on the table.151*/152153LOCAL(void)154jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,155c_derived_tbl ** pdtbl)156{157JHUFF_TBL *htbl;158c_derived_tbl *dtbl;159int p, i, l, lastp, si, maxsymbol;160char huffsize[257];161unsigned int huffcode[257];162unsigned int code;163164/* Note that huffsize[] and huffcode[] are filled in code-length order,165* paralleling the order of the symbols themselves in htbl->huffval[].166*/167168/* Find the input Huffman table */169if (tblno < 0 || tblno >= NUM_HUFF_TBLS)170ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);171htbl =172isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];173if (htbl == NULL)174htbl = jpeg_std_huff_table((j_common_ptr) cinfo, isDC, tblno);175176/* Allocate a workspace if we haven't already done so. */177if (*pdtbl == NULL)178*pdtbl = (c_derived_tbl *) (*cinfo->mem->alloc_small)179((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(c_derived_tbl));180dtbl = *pdtbl;181182/* Figure C.1: make table of Huffman code length for each symbol */183184p = 0;185for (l = 1; l <= 16; l++) {186i = (int) htbl->bits[l];187if (i < 0 || p + i > 256) /* protect against table overrun */188ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);189while (i--)190huffsize[p++] = (char) l;191}192huffsize[p] = 0;193lastp = p;194195/* Figure C.2: generate the codes themselves */196/* We also validate that the counts represent a legal Huffman code tree. */197198code = 0;199si = huffsize[0];200p = 0;201while (huffsize[p]) {202while (((int) huffsize[p]) == si) {203huffcode[p++] = code;204code++;205}206/* code is now 1 more than the last code used for codelength si; but207* it must still fit in si bits, since no code is allowed to be all ones.208*/209if (((INT32) code) >= (((INT32) 1) << si))210ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);211code <<= 1;212si++;213}214215/* Figure C.3: generate encoding tables */216/* These are code and size indexed by symbol value */217218/* Set all codeless symbols to have code length 0;219* this lets us detect duplicate VAL entries here, and later220* allows emit_bits to detect any attempt to emit such symbols.221*/222MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));223224/* This is also a convenient place to check for out-of-range225* and duplicated VAL entries. We allow 0..255 for AC symbols226* but only 0..15 for DC. (We could constrain them further227* based on data depth and mode, but this seems enough.)228*/229maxsymbol = isDC ? 15 : 255;230231for (p = 0; p < lastp; p++) {232i = htbl->huffval[p];233if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])234ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);235dtbl->ehufco[i] = huffcode[p];236dtbl->ehufsi[i] = huffsize[p];237}238}239240241/* Outputting bytes to the file.242* NB: these must be called only when actually outputting,243* that is, entropy->gather_statistics == FALSE.244*/245246/* Emit a byte, taking 'action' if must suspend. */247#define emit_byte_s(state,val,action) \248{ *(state)->next_output_byte++ = (JOCTET) (val); \249if (--(state)->free_in_buffer == 0) \250if (! dump_buffer_s(state)) \251{ action; } }252253/* Emit a byte */254#define emit_byte_e(entropy,val) \255{ *(entropy)->next_output_byte++ = (JOCTET) (val); \256if (--(entropy)->free_in_buffer == 0) \257dump_buffer_e(entropy); }258259260LOCAL(boolean)261dump_buffer_s (working_state * state)262/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */263{264struct jpeg_destination_mgr * dest = state->cinfo->dest;265266if (! (*dest->empty_output_buffer) (state->cinfo))267return FALSE;268/* After a successful buffer dump, must reset buffer pointers */269state->next_output_byte = dest->next_output_byte;270state->free_in_buffer = dest->free_in_buffer;271return TRUE;272}273274275LOCAL(void)276dump_buffer_e (huff_entropy_ptr entropy)277/* Empty the output buffer; we do not support suspension in this case. */278{279struct jpeg_destination_mgr * dest = entropy->cinfo->dest;280281if (! (*dest->empty_output_buffer) (entropy->cinfo))282ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);283/* After a successful buffer dump, must reset buffer pointers */284entropy->next_output_byte = dest->next_output_byte;285entropy->free_in_buffer = dest->free_in_buffer;286}287288289/* Outputting bits to the file */290291/* Only the right 24 bits of put_buffer are used; the valid bits are292* left-justified in this part. At most 16 bits can be passed to emit_bits293* in one call, and we never retain more than 7 bits in put_buffer294* between calls, so 24 bits are sufficient.295*/296297INLINE298LOCAL(boolean)299emit_bits_s (working_state * state, unsigned int code, int size)300/* Emit some bits; return TRUE if successful, FALSE if must suspend */301{302/* This routine is heavily used, so it's worth coding tightly. */303register INT32 put_buffer;304register int put_bits;305306/* if size is 0, caller used an invalid Huffman table entry */307if (size == 0)308ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);309310/* mask off any extra bits in code */311put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);312313/* new number of bits in buffer */314put_bits = size + state->cur.put_bits;315316put_buffer <<= 24 - put_bits; /* align incoming bits */317318/* and merge with old buffer contents */319put_buffer |= state->cur.put_buffer;320321while (put_bits >= 8) {322int c = (int) ((put_buffer >> 16) & 0xFF);323324emit_byte_s(state, c, return FALSE);325if (c == 0xFF) { /* need to stuff a zero byte? */326emit_byte_s(state, 0, return FALSE);327}328put_buffer <<= 8;329put_bits -= 8;330}331332state->cur.put_buffer = put_buffer; /* update state variables */333state->cur.put_bits = put_bits;334335return TRUE;336}337338339INLINE340LOCAL(void)341emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)342/* Emit some bits, unless we are in gather mode */343{344/* This routine is heavily used, so it's worth coding tightly. */345register INT32 put_buffer;346register int put_bits;347348/* if size is 0, caller used an invalid Huffman table entry */349if (size == 0)350ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);351352if (entropy->gather_statistics)353return; /* do nothing if we're only getting stats */354355/* mask off any extra bits in code */356put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);357358/* new number of bits in buffer */359put_bits = size + entropy->saved.put_bits;360361put_buffer <<= 24 - put_bits; /* align incoming bits */362363/* and merge with old buffer contents */364put_buffer |= entropy->saved.put_buffer;365366while (put_bits >= 8) {367int c = (int) ((put_buffer >> 16) & 0xFF);368369emit_byte_e(entropy, c);370if (c == 0xFF) { /* need to stuff a zero byte? */371emit_byte_e(entropy, 0);372}373put_buffer <<= 8;374put_bits -= 8;375}376377entropy->saved.put_buffer = put_buffer; /* update variables */378entropy->saved.put_bits = put_bits;379}380381382LOCAL(boolean)383flush_bits_s (working_state * state)384{385if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */386return FALSE;387state->cur.put_buffer = 0; /* and reset bit-buffer to empty */388state->cur.put_bits = 0;389return TRUE;390}391392393LOCAL(void)394flush_bits_e (huff_entropy_ptr entropy)395{396emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */397entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */398entropy->saved.put_bits = 0;399}400401402/*403* Emit (or just count) a Huffman symbol.404*/405406INLINE407LOCAL(void)408emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)409{410if (entropy->gather_statistics)411entropy->dc_count_ptrs[tbl_no][symbol]++;412else {413c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];414emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);415}416}417418419INLINE420LOCAL(void)421emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)422{423if (entropy->gather_statistics)424entropy->ac_count_ptrs[tbl_no][symbol]++;425else {426c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];427emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);428}429}430431432/*433* Emit bits from a correction bit buffer.434*/435436LOCAL(void)437emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,438unsigned int nbits)439{440if (entropy->gather_statistics)441return; /* no real work */442443while (nbits > 0) {444emit_bits_e(entropy, (unsigned int) (*bufstart), 1);445bufstart++;446nbits--;447}448}449450451/*452* Emit any pending EOBRUN symbol.453*/454455LOCAL(void)456emit_eobrun (huff_entropy_ptr entropy)457{458register int temp, nbits;459460if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */461temp = entropy->EOBRUN;462nbits = 0;463while ((temp >>= 1))464nbits++;465/* safety check: shouldn't happen given limited correction-bit buffer */466if (nbits > 14)467ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);468469emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);470if (nbits)471emit_bits_e(entropy, entropy->EOBRUN, nbits);472473entropy->EOBRUN = 0;474475/* Emit any buffered correction bits */476emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);477entropy->BE = 0;478}479}480481482/*483* Emit a restart marker & resynchronize predictions.484*/485486LOCAL(boolean)487emit_restart_s (working_state * state, int restart_num)488{489int ci;490491if (! flush_bits_s(state))492return FALSE;493494emit_byte_s(state, 0xFF, return FALSE);495emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);496497/* Re-initialize DC predictions to 0 */498for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)499state->cur.last_dc_val[ci] = 0;500501/* The restart counter is not updated until we successfully write the MCU. */502503return TRUE;504}505506507LOCAL(void)508emit_restart_e (huff_entropy_ptr entropy, int restart_num)509{510int ci;511512emit_eobrun(entropy);513514if (! entropy->gather_statistics) {515flush_bits_e(entropy);516emit_byte_e(entropy, 0xFF);517emit_byte_e(entropy, JPEG_RST0 + restart_num);518}519520if (entropy->cinfo->Ss == 0) {521/* Re-initialize DC predictions to 0 */522for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)523entropy->saved.last_dc_val[ci] = 0;524} else {525/* Re-initialize all AC-related fields to 0 */526entropy->EOBRUN = 0;527entropy->BE = 0;528}529}530531532/*533* MCU encoding for DC initial scan (either spectral selection,534* or first pass of successive approximation).535*/536537METHODDEF(boolean)538encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)539{540huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;541register int temp, temp2;542register int nbits;543int max_coef_bits;544int blkn, ci, tbl;545ISHIFT_TEMPS546547entropy->next_output_byte = cinfo->dest->next_output_byte;548entropy->free_in_buffer = cinfo->dest->free_in_buffer;549550/* Emit restart marker if needed */551if (cinfo->restart_interval)552if (entropy->restarts_to_go == 0)553emit_restart_e(entropy, entropy->next_restart_num);554555/* Since we're encoding a difference, the range limit is twice as much. */556max_coef_bits = cinfo->data_precision + 3;557558/* Encode the MCU data blocks */559for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {560ci = cinfo->MCU_membership[blkn];561tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;562563/* Compute the DC value after the required point transform by Al.564* This is simply an arithmetic right shift.565*/566temp = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);567568/* DC differences are figured on the point-transformed values. */569if ((temp2 = temp - entropy->saved.last_dc_val[ci]) == 0) {570/* Count/emit the Huffman-coded symbol for the number of bits */571emit_dc_symbol(entropy, tbl, 0);572573continue;574}575576entropy->saved.last_dc_val[ci] = temp;577578/* Encode the DC coefficient difference per section G.1.2.1 */579if ((temp = temp2) < 0) {580temp = -temp; /* temp is abs value of input */581/* For a negative input, want temp2 = bitwise complement of abs(input) */582/* This code assumes we are on a two's complement machine */583temp2--;584}585586/* Find the number of bits needed for the magnitude of the coefficient */587nbits = 0;588do nbits++; /* there must be at least one 1 bit */589while ((temp >>= 1));590/* Check for out-of-range coefficient values */591if (nbits > max_coef_bits)592ERREXIT(cinfo, JERR_BAD_DCT_COEF);593594/* Count/emit the Huffman-coded symbol for the number of bits */595emit_dc_symbol(entropy, tbl, nbits);596597/* Emit that number of bits of the value, if positive, */598/* or the complement of its magnitude, if negative. */599emit_bits_e(entropy, (unsigned int) temp2, nbits);600}601602cinfo->dest->next_output_byte = entropy->next_output_byte;603cinfo->dest->free_in_buffer = entropy->free_in_buffer;604605/* Update restart-interval state too */606if (cinfo->restart_interval) {607if (entropy->restarts_to_go == 0) {608entropy->restarts_to_go = cinfo->restart_interval;609entropy->next_restart_num++;610entropy->next_restart_num &= 7;611}612entropy->restarts_to_go--;613}614615return TRUE;616}617618619/*620* MCU encoding for AC initial scan (either spectral selection,621* or first pass of successive approximation).622*/623624METHODDEF(boolean)625encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)626{627huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;628const int * natural_order;629JBLOCKROW block;630register int temp, temp2;631register int nbits;632register int r, k;633int Se, Al, max_coef_bits;634635entropy->next_output_byte = cinfo->dest->next_output_byte;636entropy->free_in_buffer = cinfo->dest->free_in_buffer;637638/* Emit restart marker if needed */639if (cinfo->restart_interval)640if (entropy->restarts_to_go == 0)641emit_restart_e(entropy, entropy->next_restart_num);642643Se = cinfo->Se;644Al = cinfo->Al;645natural_order = cinfo->natural_order;646max_coef_bits = cinfo->data_precision + 2;647648/* Encode the MCU data block */649block = MCU_data[0];650651/* Encode the AC coefficients per section G.1.2.2, fig. G.3 */652653r = 0; /* r = run length of zeros */654655for (k = cinfo->Ss; k <= Se; k++) {656if ((temp = (*block)[natural_order[k]]) == 0) {657r++;658continue;659}660/* We must apply the point transform by Al. For AC coefficients this661* is an integer division with rounding towards 0. To do this portably662* in C, we shift after obtaining the absolute value; so the code is663* interwoven with finding the abs value (temp) and output bits (temp2).664*/665if (temp < 0) {666temp = -temp; /* temp is abs value of input */667/* Apply the point transform, and watch out for case */668/* that nonzero coef is zero after point transform. */669if ((temp >>= Al) == 0) {670r++;671continue;672}673/* For a negative coef, want temp2 = bitwise complement of abs(coef) */674temp2 = ~temp;675} else {676/* Apply the point transform, and watch out for case */677/* that nonzero coef is zero after point transform. */678if ((temp >>= Al) == 0) {679r++;680continue;681}682temp2 = temp;683}684685/* Emit any pending EOBRUN */686if (entropy->EOBRUN > 0)687emit_eobrun(entropy);688/* if run length > 15, must emit special run-length-16 codes (0xF0) */689while (r > 15) {690emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);691r -= 16;692}693694/* Find the number of bits needed for the magnitude of the coefficient */695nbits = 0;696do nbits++; /* there must be at least one 1 bit */697while ((temp >>= 1));698/* Check for out-of-range coefficient values */699if (nbits > max_coef_bits)700ERREXIT(cinfo, JERR_BAD_DCT_COEF);701702/* Count/emit Huffman symbol for run length / number of bits */703emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);704705/* Emit that number of bits of the value, if positive, */706/* or the complement of its magnitude, if negative. */707emit_bits_e(entropy, (unsigned int) temp2, nbits);708709r = 0; /* reset zero run length */710}711712if (r > 0) { /* If there are trailing zeroes, */713entropy->EOBRUN++; /* count an EOB */714if (entropy->EOBRUN == 0x7FFF)715emit_eobrun(entropy); /* force it out to avoid overflow */716}717718cinfo->dest->next_output_byte = entropy->next_output_byte;719cinfo->dest->free_in_buffer = entropy->free_in_buffer;720721/* Update restart-interval state too */722if (cinfo->restart_interval) {723if (entropy->restarts_to_go == 0) {724entropy->restarts_to_go = cinfo->restart_interval;725entropy->next_restart_num++;726entropy->next_restart_num &= 7;727}728entropy->restarts_to_go--;729}730731return TRUE;732}733734735/*736* MCU encoding for DC successive approximation refinement scan.737* Note: we assume such scans can be multi-component,738* although the spec is not very clear on the point.739*/740741METHODDEF(boolean)742encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)743{744huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;745int Al, blkn;746747entropy->next_output_byte = cinfo->dest->next_output_byte;748entropy->free_in_buffer = cinfo->dest->free_in_buffer;749750/* Emit restart marker if needed */751if (cinfo->restart_interval)752if (entropy->restarts_to_go == 0)753emit_restart_e(entropy, entropy->next_restart_num);754755Al = cinfo->Al;756757/* Encode the MCU data blocks */758for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {759/* We simply emit the Al'th bit of the DC coefficient value. */760emit_bits_e(entropy, (unsigned int) (MCU_data[blkn][0][0] >> Al), 1);761}762763cinfo->dest->next_output_byte = entropy->next_output_byte;764cinfo->dest->free_in_buffer = entropy->free_in_buffer;765766/* Update restart-interval state too */767if (cinfo->restart_interval) {768if (entropy->restarts_to_go == 0) {769entropy->restarts_to_go = cinfo->restart_interval;770entropy->next_restart_num++;771entropy->next_restart_num &= 7;772}773entropy->restarts_to_go--;774}775776return TRUE;777}778779780/*781* MCU encoding for AC successive approximation refinement scan.782*/783784METHODDEF(boolean)785encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)786{787huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;788const int * natural_order;789JBLOCKROW block;790register int temp;791register int r, k;792int Se, Al;793int EOB;794char *BR_buffer;795unsigned int BR;796int absvalues[DCTSIZE2];797798entropy->next_output_byte = cinfo->dest->next_output_byte;799entropy->free_in_buffer = cinfo->dest->free_in_buffer;800801/* Emit restart marker if needed */802if (cinfo->restart_interval)803if (entropy->restarts_to_go == 0)804emit_restart_e(entropy, entropy->next_restart_num);805806Se = cinfo->Se;807Al = cinfo->Al;808natural_order = cinfo->natural_order;809810/* Encode the MCU data block */811block = MCU_data[0];812813/* It is convenient to make a pre-pass to determine the transformed814* coefficients' absolute values and the EOB position.815*/816EOB = 0;817for (k = cinfo->Ss; k <= Se; k++) {818temp = (*block)[natural_order[k]];819/* We must apply the point transform by Al. For AC coefficients this820* is an integer division with rounding towards 0. To do this portably821* in C, we shift after obtaining the absolute value.822*/823if (temp < 0)824temp = -temp; /* temp is abs value of input */825temp >>= Al; /* apply the point transform */826absvalues[k] = temp; /* save abs value for main pass */827if (temp == 1)828EOB = k; /* EOB = index of last newly-nonzero coef */829}830831/* Encode the AC coefficients per section G.1.2.3, fig. G.7 */832833r = 0; /* r = run length of zeros */834BR = 0; /* BR = count of buffered bits added now */835BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */836837for (k = cinfo->Ss; k <= Se; k++) {838if ((temp = absvalues[k]) == 0) {839r++;840continue;841}842843/* Emit any required ZRLs, but not if they can be folded into EOB */844while (r > 15 && k <= EOB) {845/* emit any pending EOBRUN and the BE correction bits */846emit_eobrun(entropy);847/* Emit ZRL */848emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);849r -= 16;850/* Emit buffered correction bits that must be associated with ZRL */851emit_buffered_bits(entropy, BR_buffer, BR);852BR_buffer = entropy->bit_buffer; /* BE bits are gone now */853BR = 0;854}855856/* If the coef was previously nonzero, it only needs a correction bit.857* NOTE: a straight translation of the spec's figure G.7 would suggest858* that we also need to test r > 15. But if r > 15, we can only get here859* if k > EOB, which implies that this coefficient is not 1.860*/861if (temp > 1) {862/* The correction bit is the next bit of the absolute value. */863BR_buffer[BR++] = (char) (temp & 1);864continue;865}866867/* Emit any pending EOBRUN and the BE correction bits */868emit_eobrun(entropy);869870/* Count/emit Huffman symbol for run length / number of bits */871emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);872873/* Emit output bit for newly-nonzero coef */874temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;875emit_bits_e(entropy, (unsigned int) temp, 1);876877/* Emit buffered correction bits that must be associated with this code */878emit_buffered_bits(entropy, BR_buffer, BR);879BR_buffer = entropy->bit_buffer; /* BE bits are gone now */880BR = 0;881r = 0; /* reset zero run length */882}883884if (r > 0 || BR > 0) { /* If there are trailing zeroes, */885entropy->EOBRUN++; /* count an EOB */886entropy->BE += BR; /* concat my correction bits to older ones */887/* We force out the EOB if we risk either:888* 1. overflow of the EOB counter;889* 2. overflow of the correction bit buffer during the next MCU.890*/891if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))892emit_eobrun(entropy);893}894895cinfo->dest->next_output_byte = entropy->next_output_byte;896cinfo->dest->free_in_buffer = entropy->free_in_buffer;897898/* Update restart-interval state too */899if (cinfo->restart_interval) {900if (entropy->restarts_to_go == 0) {901entropy->restarts_to_go = cinfo->restart_interval;902entropy->next_restart_num++;903entropy->next_restart_num &= 7;904}905entropy->restarts_to_go--;906}907908return TRUE;909}910911912/* Encode a single block's worth of coefficients */913914LOCAL(boolean)915encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,916c_derived_tbl *dctbl, c_derived_tbl *actbl)917{918register int temp, temp2;919register int nbits;920register int r, k;921int Se = state->cinfo->lim_Se;922int max_coef_bits = state->cinfo->data_precision + 3;923const int * natural_order = state->cinfo->natural_order;924925/* Encode the DC coefficient difference per section F.1.2.1 */926927if ((temp = block[0] - last_dc_val) == 0) {928/* Emit the Huffman-coded symbol for the number of bits */929if (! emit_bits_s(state, dctbl->ehufco[0], dctbl->ehufsi[0]))930return FALSE;931} else {932if ((temp2 = temp) < 0) {933temp = -temp; /* temp is abs value of input */934/* For a negative input, want temp2 = bitwise complement of abs(input) */935/* This code assumes we are on a two's complement machine */936temp2--;937}938939/* Find the number of bits needed for the magnitude of the coefficient */940nbits = 0;941do nbits++; /* there must be at least one 1 bit */942while ((temp >>= 1));943/* Check for out-of-range coefficient values.944* Since we're encoding a difference, the range limit is twice as much.945*/946if (nbits > max_coef_bits)947ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);948949/* Emit the Huffman-coded symbol for the number of bits */950if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))951return FALSE;952953/* Emit that number of bits of the value, if positive, */954/* or the complement of its magnitude, if negative. */955if (! emit_bits_s(state, (unsigned int) temp2, nbits))956return FALSE;957}958959/* Encode the AC coefficients per section F.1.2.2 */960961r = 0; /* r = run length of zeros */962963for (k = 1; k <= Se; k++) {964if ((temp = block[natural_order[k]]) == 0) {965r++;966continue;967}968969/* if run length > 15, must emit special run-length-16 codes (0xF0) */970while (r > 15) {971if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))972return FALSE;973r -= 16;974}975976if ((temp2 = temp) < 0) {977temp = -temp; /* temp is abs value of input */978/* For a negative coef, want temp2 = bitwise complement of abs(coef) */979/* This code assumes we are on a two's complement machine */980temp2--;981}982983/* Find the number of bits needed for the magnitude of the coefficient */984nbits = 0;985do nbits++; /* there must be at least one 1 bit */986while ((temp >>= 1));987/* Check for out-of-range coefficient values.988* Use ">=" instead of ">" so can use the989* same one larger limit from DC check here.990*/991if (nbits >= max_coef_bits)992ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);993994/* Emit Huffman symbol for run length / number of bits */995temp = (r << 4) + nbits;996if (! emit_bits_s(state, actbl->ehufco[temp], actbl->ehufsi[temp]))997return FALSE;998999/* Emit that number of bits of the value, if positive, */1000/* or the complement of its magnitude, if negative. */1001if (! emit_bits_s(state, (unsigned int) temp2, nbits))1002return FALSE;10031004r = 0; /* reset zero run length */1005}10061007/* If the last coef(s) were zero, emit an end-of-block code */1008if (r > 0)1009if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))1010return FALSE;10111012return TRUE;1013}101410151016/*1017* Encode and output one MCU's worth of Huffman-compressed coefficients.1018*/10191020METHODDEF(boolean)1021encode_mcu_huff (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)1022{1023huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1024working_state state;1025int blkn, ci;1026jpeg_component_info * compptr;10271028/* Load up working state */1029state.next_output_byte = cinfo->dest->next_output_byte;1030state.free_in_buffer = cinfo->dest->free_in_buffer;1031ASSIGN_STATE(state.cur, entropy->saved);1032state.cinfo = cinfo;10331034/* Emit restart marker if needed */1035if (cinfo->restart_interval) {1036if (entropy->restarts_to_go == 0)1037if (! emit_restart_s(&state, entropy->next_restart_num))1038return FALSE;1039}10401041/* Encode the MCU data blocks */1042for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1043ci = cinfo->MCU_membership[blkn];1044compptr = cinfo->cur_comp_info[ci];1045if (! encode_one_block(&state,1046MCU_data[blkn][0], state.cur.last_dc_val[ci],1047entropy->dc_derived_tbls[compptr->dc_tbl_no],1048entropy->ac_derived_tbls[compptr->ac_tbl_no]))1049return FALSE;1050/* Update last_dc_val */1051state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];1052}10531054/* Completed MCU, so update state */1055cinfo->dest->next_output_byte = state.next_output_byte;1056cinfo->dest->free_in_buffer = state.free_in_buffer;1057ASSIGN_STATE(entropy->saved, state.cur);10581059/* Update restart-interval state too */1060if (cinfo->restart_interval) {1061if (entropy->restarts_to_go == 0) {1062entropy->restarts_to_go = cinfo->restart_interval;1063entropy->next_restart_num++;1064entropy->next_restart_num &= 7;1065}1066entropy->restarts_to_go--;1067}10681069return TRUE;1070}107110721073/*1074* Finish up at the end of a Huffman-compressed scan.1075*/10761077METHODDEF(void)1078finish_pass_huff (j_compress_ptr cinfo)1079{1080huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1081working_state state;10821083if (cinfo->progressive_mode) {1084entropy->next_output_byte = cinfo->dest->next_output_byte;1085entropy->free_in_buffer = cinfo->dest->free_in_buffer;10861087/* Flush out any buffered data */1088emit_eobrun(entropy);1089flush_bits_e(entropy);10901091cinfo->dest->next_output_byte = entropy->next_output_byte;1092cinfo->dest->free_in_buffer = entropy->free_in_buffer;1093} else {1094/* Load up working state ... flush_bits needs it */1095state.next_output_byte = cinfo->dest->next_output_byte;1096state.free_in_buffer = cinfo->dest->free_in_buffer;1097ASSIGN_STATE(state.cur, entropy->saved);1098state.cinfo = cinfo;10991100/* Flush out the last data */1101if (! flush_bits_s(&state))1102ERREXIT(cinfo, JERR_CANT_SUSPEND);11031104/* Update state */1105cinfo->dest->next_output_byte = state.next_output_byte;1106cinfo->dest->free_in_buffer = state.free_in_buffer;1107ASSIGN_STATE(entropy->saved, state.cur);1108}1109}111011111112/*1113* Huffman coding optimization.1114*1115* We first scan the supplied data and count the number of uses of each symbol1116* that is to be Huffman-coded. (This process MUST agree with the code above.)1117* Then we build a Huffman coding tree for the observed counts.1118* Symbols which are not needed at all for the particular image are not1119* assigned any code, which saves space in the DHT marker as well as in1120* the compressed data.1121*/112211231124/* Process a single block's worth of coefficients */11251126LOCAL(void)1127htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,1128long dc_counts[], long ac_counts[])1129{1130register int temp;1131register int nbits;1132register int r, k;1133int Se = cinfo->lim_Se;1134int max_coef_bits = cinfo->data_precision + 3;1135const int * natural_order = cinfo->natural_order;11361137/* Encode the DC coefficient difference per section F.1.2.1 */11381139if ((temp = block[0] - last_dc_val) == 0) {1140/* Count the Huffman symbol for the number of bits */1141dc_counts[0]++;1142} else {1143if (temp < 0)1144temp = -temp; /* temp is abs value of input */11451146/* Find the number of bits needed for the magnitude of the coefficient */1147nbits = 0;1148do nbits++; /* there must be at least one 1 bit */1149while ((temp >>= 1));1150/* Check for out-of-range coefficient values.1151* Since we're encoding a difference, the range limit is twice as much.1152*/1153if (nbits > max_coef_bits)1154ERREXIT(cinfo, JERR_BAD_DCT_COEF);11551156/* Count the Huffman symbol for the number of bits */1157dc_counts[nbits]++;1158}11591160/* Encode the AC coefficients per section F.1.2.2 */11611162r = 0; /* r = run length of zeros */11631164for (k = 1; k <= Se; k++) {1165if ((temp = block[natural_order[k]]) == 0) {1166r++;1167continue;1168}11691170/* if run length > 15, must emit special run-length-16 codes (0xF0) */1171while (r > 15) {1172ac_counts[0xF0]++;1173r -= 16;1174}11751176if (temp < 0)1177temp = -temp; /* temp is abs value of input */11781179/* Find the number of bits needed for the magnitude of the coefficient */1180nbits = 0;1181do nbits++; /* there must be at least one 1 bit */1182while ((temp >>= 1));1183/* Check for out-of-range coefficient values.1184* Use ">=" instead of ">" so can use the1185* same one larger limit from DC check here.1186*/1187if (nbits >= max_coef_bits)1188ERREXIT(cinfo, JERR_BAD_DCT_COEF);11891190/* Count Huffman symbol for run length / number of bits */1191ac_counts[(r << 4) + nbits]++;11921193r = 0; /* reset zero run length */1194}11951196/* If the last coef(s) were zero, emit an end-of-block code */1197if (r > 0)1198ac_counts[0]++;1199}120012011202/*1203* Trial-encode one MCU's worth of Huffman-compressed coefficients.1204* No data is actually output, so no suspension return is possible.1205*/12061207METHODDEF(boolean)1208encode_mcu_gather (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)1209{1210huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1211int blkn, ci;1212jpeg_component_info * compptr;12131214/* Take care of restart intervals if needed */1215if (cinfo->restart_interval) {1216if (entropy->restarts_to_go == 0) {1217/* Re-initialize DC predictions to 0 */1218for (ci = 0; ci < cinfo->comps_in_scan; ci++)1219entropy->saved.last_dc_val[ci] = 0;1220/* Update restart state */1221entropy->restarts_to_go = cinfo->restart_interval;1222}1223entropy->restarts_to_go--;1224}12251226for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1227ci = cinfo->MCU_membership[blkn];1228compptr = cinfo->cur_comp_info[ci];1229htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],1230entropy->dc_count_ptrs[compptr->dc_tbl_no],1231entropy->ac_count_ptrs[compptr->ac_tbl_no]);1232entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];1233}12341235return TRUE;1236}123712381239/*1240* Generate the best Huffman code table for the given counts, fill htbl.1241*1242* The JPEG standard requires that no symbol be assigned a codeword of all1243* one bits (so that padding bits added at the end of a compressed segment1244* can't look like a valid code). Because of the canonical ordering of1245* codewords, this just means that there must be an unused slot in the1246* longest codeword length category. Section K.2 of the JPEG spec suggests1247* reserving such a slot by pretending that symbol 256 is a valid symbol1248* with count 1. In theory that's not optimal; giving it count zero but1249* including it in the symbol set anyway should give a better Huffman code.1250* But the theoretically better code actually seems to come out worse in1251* practice, because it produces more all-ones bytes (which incur stuffed1252* zero bytes in the final file). In any case the difference is tiny.1253*1254* The JPEG standard requires Huffman codes to be no more than 16 bits long.1255* If some symbols have a very small but nonzero probability, the Huffman tree1256* must be adjusted to meet the code length restriction. We currently use1257* the adjustment method suggested in JPEG section K.2. This method is *not*1258* optimal; it may not choose the best possible limited-length code. But1259* typically only very-low-frequency symbols will be given less-than-optimal1260* lengths, so the code is almost optimal. Experimental comparisons against1261* an optimal limited-length-code algorithm indicate that the difference is1262* microscopic --- usually less than a hundredth of a percent of total size.1263* So the extra complexity of an optimal algorithm doesn't seem worthwhile.1264*/12651266LOCAL(void)1267jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])1268{1269#define MAX_CLEN 32 /* assumed maximum initial code length */1270UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */1271int codesize[257]; /* codesize[k] = code length of symbol k */1272int others[257]; /* next symbol in current branch of tree */1273int c1, c2, i, j;1274UINT8 *p;1275long v;12761277freq[256] = 1; /* make sure 256 has a nonzero count */1278/* Including the pseudo-symbol 256 in the Huffman procedure guarantees1279* that no real symbol is given code-value of all ones, because 2561280* will be placed last in the largest codeword category.1281* In the symbol list build procedure this element serves as sentinel1282* for the zero run loop.1283*/12841285#ifndef DONT_USE_FANCY_HUFF_OPT12861287/* Build list of symbols sorted in order of descending frequency */1288/* This approach has several benefits (thank to John Korejwa for the idea):1289* 1.1290* If a codelength category is split during the length limiting procedure1291* below, the feature that more frequent symbols are assigned shorter1292* codewords remains valid for the adjusted code.1293* 2.1294* To reduce consecutive ones in a Huffman data stream (thus reducing the1295* number of stuff bytes in JPEG) it is preferable to follow 0 branches1296* (and avoid 1 branches) as much as possible. This is easily done by1297* assigning symbols to leaves of the Huffman tree in order of decreasing1298* frequency, with no secondary sort based on codelengths.1299* 3.1300* The symbol list can be built independently from the assignment of code1301* lengths by the Huffman procedure below.1302* Note: The symbol list build procedure must be performed first, because1303* the Huffman procedure assigning the codelengths clobbers the frequency1304* counts!1305*/13061307/* Here we use the others array as a linked list of nonzero frequencies1308* to be sorted. Already sorted elements are removed from the list.1309*/13101311/* Building list */13121313/* This item does not correspond to a valid symbol frequency and is used1314* as starting index.1315*/1316j = 256;13171318for (i = 0;; i++) {1319if (freq[i] == 0) /* skip zero frequencies */1320continue;1321if (i > 255)1322break;1323others[j] = i; /* this symbol value */1324j = i; /* previous symbol value */1325}1326others[j] = -1; /* mark end of list */13271328/* Sorting list */13291330p = htbl->huffval;1331while ((c1 = others[256]) >= 0) {1332v = freq[c1];1333i = c1; /* first symbol value */1334j = 256; /* pseudo symbol value for starting index */1335while ((c2 = others[c1]) >= 0) {1336if (freq[c2] > v) {1337v = freq[c2];1338i = c2; /* this symbol value */1339j = c1; /* previous symbol value */1340}1341c1 = c2;1342}1343others[j] = others[i]; /* remove this symbol i from list */1344*p++ = (UINT8) i;1345}13461347#endif /* DONT_USE_FANCY_HUFF_OPT */13481349/* This algorithm is explained in section K.2 of the JPEG standard */13501351MEMZERO(bits, SIZEOF(bits));1352MEMZERO(codesize, SIZEOF(codesize));1353for (i = 0; i < 257; i++)1354others[i] = -1; /* init links to empty */13551356/* Huffman's basic algorithm to assign optimal code lengths to symbols */13571358for (;;) {1359/* Find the smallest nonzero frequency, set c1 = its symbol */1360/* In case of ties, take the larger symbol number */1361c1 = -1;1362v = 1000000000L;1363for (i = 0; i <= 256; i++) {1364if (freq[i] && freq[i] <= v) {1365v = freq[i];1366c1 = i;1367}1368}13691370/* Find the next smallest nonzero frequency, set c2 = its symbol */1371/* In case of ties, take the larger symbol number */1372c2 = -1;1373v = 1000000000L;1374for (i = 0; i <= 256; i++) {1375if (freq[i] && freq[i] <= v && i != c1) {1376v = freq[i];1377c2 = i;1378}1379}13801381/* Done if we've merged everything into one frequency */1382if (c2 < 0)1383break;13841385/* Else merge the two counts/trees */1386freq[c1] += freq[c2];1387freq[c2] = 0;13881389/* Increment the codesize of everything in c1's tree branch */1390codesize[c1]++;1391while (others[c1] >= 0) {1392c1 = others[c1];1393codesize[c1]++;1394}13951396others[c1] = c2; /* chain c2 onto c1's tree branch */13971398/* Increment the codesize of everything in c2's tree branch */1399codesize[c2]++;1400while (others[c2] >= 0) {1401c2 = others[c2];1402codesize[c2]++;1403}1404}14051406/* Now count the number of symbols of each code length */1407for (i = 0; i <= 256; i++) {1408if (codesize[i]) {1409/* The JPEG standard seems to think that this can't happen, */1410/* but I'm paranoid... */1411if (codesize[i] > MAX_CLEN)1412ERREXIT(cinfo, JERR_HUFF_CLEN_OUTOFBOUNDS);14131414bits[codesize[i]]++;1415}1416}14171418/* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure1419* Huffman procedure assigned any such lengths, we must adjust the coding.1420* Here is what the JPEG spec says about how this next bit works:1421* Since symbols are paired for the longest Huffman code, the symbols are1422* removed from this length category two at a time. The prefix for the pair1423* (which is one bit shorter) is allocated to one of the pair; then,1424* skipping the BITS entry for that prefix length, a code word from the next1425* shortest nonzero BITS entry is converted into a prefix for two code words1426* one bit longer.1427*/14281429for (i = MAX_CLEN; i > 16; i--) {1430while (bits[i] > 0) {1431j = i - 2; /* find length of new prefix to be used */1432while (bits[j] == 0) {1433if (j == 0)1434ERREXIT(cinfo, JERR_HUFF_CLEN_OUTOFBOUNDS);1435j--;1436}14371438bits[i] -= 2; /* remove two symbols */1439bits[i-1]++; /* one goes in this length */1440bits[j+1] += 2; /* two new symbols in this length */1441bits[j]--; /* symbol of this length is now a prefix */1442}1443}14441445/* Remove the count for the pseudo-symbol 256 from the largest codelength */1446while (bits[i] == 0) /* find largest codelength still in use */1447i--;1448bits[i]--;14491450/* Return final symbol counts (only for lengths 0..16) */1451MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));14521453#ifdef DONT_USE_FANCY_HUFF_OPT14541455/* Return a list of the symbols sorted by code length */1456/* Note: Due to the codelength changes made above, it can happen1457* that more frequent symbols are assigned longer codewords.1458*/1459p = htbl->huffval;1460for (i = 1; i <= MAX_CLEN; i++) {1461for (j = 0; j <= 255; j++) {1462if (codesize[j] == i) {1463*p++ = (UINT8) j;1464}1465}1466}14671468#endif /* DONT_USE_FANCY_HUFF_OPT */14691470/* Set sent_table FALSE so updated table will be written to JPEG file. */1471htbl->sent_table = FALSE;1472}147314741475/*1476* Finish up a statistics-gathering pass and create the new Huffman tables.1477*/14781479METHODDEF(void)1480finish_pass_gather (j_compress_ptr cinfo)1481{1482huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1483int ci, tbl;1484jpeg_component_info * compptr;1485JHUFF_TBL **htblptr;1486boolean did_dc[NUM_HUFF_TBLS];1487boolean did_ac[NUM_HUFF_TBLS];14881489if (cinfo->progressive_mode)1490/* Flush out buffered data (all we care about is counting the EOB symbol) */1491emit_eobrun(entropy);14921493/* It's important not to apply jpeg_gen_optimal_table more than once1494* per table, because it clobbers the input frequency counts!1495*/1496MEMZERO(did_dc, SIZEOF(did_dc));1497MEMZERO(did_ac, SIZEOF(did_ac));14981499for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1500compptr = cinfo->cur_comp_info[ci];1501/* DC needs no table for refinement scan */1502if (cinfo->Ss == 0 && cinfo->Ah == 0) {1503tbl = compptr->dc_tbl_no;1504if (! did_dc[tbl]) {1505htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];1506if (*htblptr == NULL)1507*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);1508jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);1509did_dc[tbl] = TRUE;1510}1511}1512/* AC needs no table when not present */1513if (cinfo->Se) {1514tbl = compptr->ac_tbl_no;1515if (! did_ac[tbl]) {1516htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];1517if (*htblptr == NULL)1518*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);1519jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);1520did_ac[tbl] = TRUE;1521}1522}1523}1524}152515261527/*1528* Initialize for a Huffman-compressed scan.1529* If gather_statistics is TRUE, we do not output anything during the scan,1530* just count the Huffman symbols used and generate Huffman code tables.1531*/15321533METHODDEF(void)1534start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)1535{1536huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1537int ci, tbl;1538jpeg_component_info * compptr;15391540if (gather_statistics)1541entropy->pub.finish_pass = finish_pass_gather;1542else1543entropy->pub.finish_pass = finish_pass_huff;15441545if (cinfo->progressive_mode) {1546entropy->cinfo = cinfo;1547entropy->gather_statistics = gather_statistics;15481549/* We assume jcmaster.c already validated the scan parameters. */15501551/* Select execution routine */1552if (cinfo->Ah == 0) {1553if (cinfo->Ss == 0)1554entropy->pub.encode_mcu = encode_mcu_DC_first;1555else1556entropy->pub.encode_mcu = encode_mcu_AC_first;1557} else {1558if (cinfo->Ss == 0)1559entropy->pub.encode_mcu = encode_mcu_DC_refine;1560else {1561entropy->pub.encode_mcu = encode_mcu_AC_refine;1562/* AC refinement needs a correction bit buffer */1563if (entropy->bit_buffer == NULL)1564entropy->bit_buffer = (char *) (*cinfo->mem->alloc_small)1565((j_common_ptr) cinfo, JPOOL_IMAGE, MAX_CORR_BITS * SIZEOF(char));1566}1567}15681569/* Initialize AC stuff */1570entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;1571entropy->EOBRUN = 0;1572entropy->BE = 0;1573} else {1574if (gather_statistics)1575entropy->pub.encode_mcu = encode_mcu_gather;1576else1577entropy->pub.encode_mcu = encode_mcu_huff;1578}15791580for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1581compptr = cinfo->cur_comp_info[ci];1582/* DC needs no table for refinement scan */1583if (cinfo->Ss == 0 && cinfo->Ah == 0) {1584tbl = compptr->dc_tbl_no;1585if (gather_statistics) {1586/* Check for invalid table index */1587/* (make_c_derived_tbl does this in the other path) */1588if (tbl < 0 || tbl >= NUM_HUFF_TBLS)1589ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);1590/* Allocate and zero the statistics tables */1591/* Note that jpeg_gen_optimal_table expects 257 entries in each table! */1592if (entropy->dc_count_ptrs[tbl] == NULL)1593entropy->dc_count_ptrs[tbl] = (long *) (*cinfo->mem->alloc_small)1594((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long));1595MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));1596} else {1597/* Compute derived values for Huffman tables */1598/* We may do this more than once for a table, but it's not expensive */1599jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,1600& entropy->dc_derived_tbls[tbl]);1601}1602/* Initialize DC predictions to 0 */1603entropy->saved.last_dc_val[ci] = 0;1604}1605/* AC needs no table when not present */1606if (cinfo->Se) {1607tbl = compptr->ac_tbl_no;1608if (gather_statistics) {1609if (tbl < 0 || tbl >= NUM_HUFF_TBLS)1610ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);1611if (entropy->ac_count_ptrs[tbl] == NULL)1612entropy->ac_count_ptrs[tbl] = (long *) (*cinfo->mem->alloc_small)1613((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long));1614MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));1615} else {1616jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,1617& entropy->ac_derived_tbls[tbl]);1618}1619}1620}16211622/* Initialize bit buffer to empty */1623entropy->saved.put_buffer = 0;1624entropy->saved.put_bits = 0;16251626/* Initialize restart stuff */1627entropy->restarts_to_go = cinfo->restart_interval;1628entropy->next_restart_num = 0;1629}163016311632/*1633* Module initialization routine for Huffman entropy encoding.1634*/16351636GLOBAL(void)1637jinit_huff_encoder (j_compress_ptr cinfo)1638{1639huff_entropy_ptr entropy;1640int i;16411642entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small)1643((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_encoder));1644cinfo->entropy = &entropy->pub;1645entropy->pub.start_pass = start_pass_huff;16461647/* Mark tables unallocated */1648for (i = 0; i < NUM_HUFF_TBLS; i++) {1649entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;1650entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;1651}16521653if (cinfo->progressive_mode)1654entropy->bit_buffer = NULL; /* needed only in AC refinement scan */1655}165616571658