/*1* jchuff.c2*3* Copyright (C) 1991-1997, Thomas G. Lane.4* Modified 2006-2013 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 data;29* -16384 .. +16383 for 12-bit data.30* Hence the magnitude should always fit in 10 or 14 bits respectively.31*/3233#if BITS_IN_JSAMPLE == 834#define MAX_COEF_BITS 1035#else36#define MAX_COEF_BITS 1437#endif3839/* Derived data constructed for each Huffman table */4041typedef struct {42unsigned int ehufco[256]; /* code for each symbol */43char ehufsi[256]; /* length of code for each symbol */44/* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */45} c_derived_tbl;464748/* Expanded entropy encoder object for Huffman encoding.49*50* The savable_state subrecord contains fields that change within an MCU,51* but must not be updated permanently until we complete the MCU.52*/5354typedef struct {55INT32 put_buffer; /* current bit-accumulation buffer */56int put_bits; /* # of bits now in it */57int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */58} savable_state;5960/* This macro is to work around compilers with missing or broken61* structure assignment. You'll need to fix this code if you have62* such a compiler and you change MAX_COMPS_IN_SCAN.63*/6465#ifndef NO_STRUCT_ASSIGN66#define ASSIGN_STATE(dest,src) ((dest) = (src))67#else68#if MAX_COMPS_IN_SCAN == 469#define ASSIGN_STATE(dest,src) \70((dest).put_buffer = (src).put_buffer, \71(dest).put_bits = (src).put_bits, \72(dest).last_dc_val[0] = (src).last_dc_val[0], \73(dest).last_dc_val[1] = (src).last_dc_val[1], \74(dest).last_dc_val[2] = (src).last_dc_val[2], \75(dest).last_dc_val[3] = (src).last_dc_val[3])76#endif77#endif787980typedef struct {81struct jpeg_entropy_encoder pub; /* public fields */8283savable_state saved; /* Bit buffer & DC state at start of MCU */8485/* These fields are NOT loaded into local working state. */86unsigned int restarts_to_go; /* MCUs left in this restart interval */87int next_restart_num; /* next restart number to write (0-7) */8889/* Pointers to derived tables (these workspaces have image lifespan) */90c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];91c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];9293/* Statistics tables for optimization */94long * dc_count_ptrs[NUM_HUFF_TBLS];95long * ac_count_ptrs[NUM_HUFF_TBLS];9697/* Following fields used only in progressive mode */9899/* Mode flag: TRUE for optimization, FALSE for actual data output */100boolean gather_statistics;101102/* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.103*/104JOCTET * next_output_byte; /* => next byte to write in buffer */105size_t free_in_buffer; /* # of byte spaces remaining in buffer */106j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */107108/* Coding status for AC components */109int ac_tbl_no; /* the table number of the single component */110unsigned int EOBRUN; /* run length of EOBs */111unsigned int BE; /* # of buffered correction bits before MCU */112char * bit_buffer; /* buffer for correction bits (1 per char) */113/* packing correction bits tightly would save some space but cost time... */114} huff_entropy_encoder;115116typedef huff_entropy_encoder * huff_entropy_ptr;117118/* Working state while writing an MCU (sequential mode).119* This struct contains all the fields that are needed by subroutines.120*/121122typedef struct {123JOCTET * next_output_byte; /* => next byte to write in buffer */124size_t free_in_buffer; /* # of byte spaces remaining in buffer */125savable_state cur; /* Current bit buffer & DC state */126j_compress_ptr cinfo; /* dump_buffer needs access to this */127} working_state;128129/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit130* buffer can hold. Larger sizes may slightly improve compression, but131* 1000 is already well into the realm of overkill.132* The minimum safe size is 64 bits.133*/134135#define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */136137/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.138* We assume that int right shift is unsigned if INT32 right shift is,139* which should be safe.140*/141142#ifdef RIGHT_SHIFT_IS_UNSIGNED143#define ISHIFT_TEMPS int ishift_temp;144#define IRIGHT_SHIFT(x,shft) \145((ishift_temp = (x)) < 0 ? \146(ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \147(ishift_temp >> (shft)))148#else149#define ISHIFT_TEMPS150#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))151#endif152153154/*155* Compute the derived values for a Huffman table.156* This routine also performs some validation checks on the table.157*/158159LOCAL(void)160jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,161c_derived_tbl ** pdtbl)162{163JHUFF_TBL *htbl;164c_derived_tbl *dtbl;165int p, i, l, lastp, si, maxsymbol;166char huffsize[257];167unsigned int huffcode[257];168unsigned int code;169170/* Note that huffsize[] and huffcode[] are filled in code-length order,171* paralleling the order of the symbols themselves in htbl->huffval[].172*/173174/* Find the input Huffman table */175if (tblno < 0 || tblno >= NUM_HUFF_TBLS)176ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);177htbl =178isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];179if (htbl == NULL)180ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);181182/* Allocate a workspace if we haven't already done so. */183if (*pdtbl == NULL)184*pdtbl = (c_derived_tbl *)185(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,186SIZEOF(c_derived_tbl));187dtbl = *pdtbl;188189/* Figure C.1: make table of Huffman code length for each symbol */190191p = 0;192for (l = 1; l <= 16; l++) {193i = (int) htbl->bits[l];194if (i < 0 || p + i > 256) /* protect against table overrun */195ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);196while (i--)197huffsize[p++] = (char) l;198}199huffsize[p] = 0;200lastp = p;201202/* Figure C.2: generate the codes themselves */203/* We also validate that the counts represent a legal Huffman code tree. */204205code = 0;206si = huffsize[0];207p = 0;208while (huffsize[p]) {209while (((int) huffsize[p]) == si) {210huffcode[p++] = code;211code++;212}213/* code is now 1 more than the last code used for codelength si; but214* it must still fit in si bits, since no code is allowed to be all ones.215*/216if (((INT32) code) >= (((INT32) 1) << si))217ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);218code <<= 1;219si++;220}221222/* Figure C.3: generate encoding tables */223/* These are code and size indexed by symbol value */224225/* Set all codeless symbols to have code length 0;226* this lets us detect duplicate VAL entries here, and later227* allows emit_bits to detect any attempt to emit such symbols.228*/229MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));230231/* This is also a convenient place to check for out-of-range232* and duplicated VAL entries. We allow 0..255 for AC symbols233* but only 0..15 for DC. (We could constrain them further234* based on data depth and mode, but this seems enough.)235*/236maxsymbol = isDC ? 15 : 255;237238for (p = 0; p < lastp; p++) {239i = htbl->huffval[p];240if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])241ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);242dtbl->ehufco[i] = huffcode[p];243dtbl->ehufsi[i] = huffsize[p];244}245}246247248/* Outputting bytes to the file.249* NB: these must be called only when actually outputting,250* that is, entropy->gather_statistics == FALSE.251*/252253/* Emit a byte, taking 'action' if must suspend. */254#define emit_byte_s(state,val,action) \255{ *(state)->next_output_byte++ = (JOCTET) (val); \256if (--(state)->free_in_buffer == 0) \257if (! dump_buffer_s(state)) \258{ action; } }259260/* Emit a byte */261#define emit_byte_e(entropy,val) \262{ *(entropy)->next_output_byte++ = (JOCTET) (val); \263if (--(entropy)->free_in_buffer == 0) \264dump_buffer_e(entropy); }265266267LOCAL(boolean)268dump_buffer_s (working_state * state)269/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */270{271struct jpeg_destination_mgr * dest = state->cinfo->dest;272273if (! (*dest->empty_output_buffer) (state->cinfo))274return FALSE;275/* After a successful buffer dump, must reset buffer pointers */276state->next_output_byte = dest->next_output_byte;277state->free_in_buffer = dest->free_in_buffer;278return TRUE;279}280281282LOCAL(void)283dump_buffer_e (huff_entropy_ptr entropy)284/* Empty the output buffer; we do not support suspension in this case. */285{286struct jpeg_destination_mgr * dest = entropy->cinfo->dest;287288if (! (*dest->empty_output_buffer) (entropy->cinfo))289ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);290/* After a successful buffer dump, must reset buffer pointers */291entropy->next_output_byte = dest->next_output_byte;292entropy->free_in_buffer = dest->free_in_buffer;293}294295296/* Outputting bits to the file */297298/* Only the right 24 bits of put_buffer are used; the valid bits are299* left-justified in this part. At most 16 bits can be passed to emit_bits300* in one call, and we never retain more than 7 bits in put_buffer301* between calls, so 24 bits are sufficient.302*/303304INLINE305LOCAL(boolean)306emit_bits_s (working_state * state, unsigned int code, int size)307/* Emit some bits; return TRUE if successful, FALSE if must suspend */308{309/* This routine is heavily used, so it's worth coding tightly. */310register INT32 put_buffer;311register int put_bits;312313/* if size is 0, caller used an invalid Huffman table entry */314if (size == 0)315ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);316317/* mask off any extra bits in code */318put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);319320/* new number of bits in buffer */321put_bits = size + state->cur.put_bits;322323put_buffer <<= 24 - put_bits; /* align incoming bits */324325/* and merge with old buffer contents */326put_buffer |= state->cur.put_buffer;327328while (put_bits >= 8) {329int c = (int) ((put_buffer >> 16) & 0xFF);330331emit_byte_s(state, c, return FALSE);332if (c == 0xFF) { /* need to stuff a zero byte? */333emit_byte_s(state, 0, return FALSE);334}335put_buffer <<= 8;336put_bits -= 8;337}338339state->cur.put_buffer = put_buffer; /* update state variables */340state->cur.put_bits = put_bits;341342return TRUE;343}344345346INLINE347LOCAL(void)348emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)349/* Emit some bits, unless we are in gather mode */350{351/* This routine is heavily used, so it's worth coding tightly. */352register INT32 put_buffer;353register int put_bits;354355/* if size is 0, caller used an invalid Huffman table entry */356if (size == 0)357ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);358359if (entropy->gather_statistics)360return; /* do nothing if we're only getting stats */361362/* mask off any extra bits in code */363put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);364365/* new number of bits in buffer */366put_bits = size + entropy->saved.put_bits;367368put_buffer <<= 24 - put_bits; /* align incoming bits */369370/* and merge with old buffer contents */371put_buffer |= entropy->saved.put_buffer;372373while (put_bits >= 8) {374int c = (int) ((put_buffer >> 16) & 0xFF);375376emit_byte_e(entropy, c);377if (c == 0xFF) { /* need to stuff a zero byte? */378emit_byte_e(entropy, 0);379}380put_buffer <<= 8;381put_bits -= 8;382}383384entropy->saved.put_buffer = put_buffer; /* update variables */385entropy->saved.put_bits = put_bits;386}387388389LOCAL(boolean)390flush_bits_s (working_state * state)391{392if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */393return FALSE;394state->cur.put_buffer = 0; /* and reset bit-buffer to empty */395state->cur.put_bits = 0;396return TRUE;397}398399400LOCAL(void)401flush_bits_e (huff_entropy_ptr entropy)402{403emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */404entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */405entropy->saved.put_bits = 0;406}407408409/*410* Emit (or just count) a Huffman symbol.411*/412413INLINE414LOCAL(void)415emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)416{417if (entropy->gather_statistics)418entropy->dc_count_ptrs[tbl_no][symbol]++;419else {420c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];421emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);422}423}424425426INLINE427LOCAL(void)428emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)429{430if (entropy->gather_statistics)431entropy->ac_count_ptrs[tbl_no][symbol]++;432else {433c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];434emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);435}436}437438439/*440* Emit bits from a correction bit buffer.441*/442443LOCAL(void)444emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,445unsigned int nbits)446{447if (entropy->gather_statistics)448return; /* no real work */449450while (nbits > 0) {451emit_bits_e(entropy, (unsigned int) (*bufstart), 1);452bufstart++;453nbits--;454}455}456457458/*459* Emit any pending EOBRUN symbol.460*/461462LOCAL(void)463emit_eobrun (huff_entropy_ptr entropy)464{465register int temp, nbits;466467if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */468temp = entropy->EOBRUN;469nbits = 0;470while ((temp >>= 1))471nbits++;472/* safety check: shouldn't happen given limited correction-bit buffer */473if (nbits > 14)474ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);475476emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);477if (nbits)478emit_bits_e(entropy, entropy->EOBRUN, nbits);479480entropy->EOBRUN = 0;481482/* Emit any buffered correction bits */483emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);484entropy->BE = 0;485}486}487488489/*490* Emit a restart marker & resynchronize predictions.491*/492493LOCAL(boolean)494emit_restart_s (working_state * state, int restart_num)495{496int ci;497498if (! flush_bits_s(state))499return FALSE;500501emit_byte_s(state, 0xFF, return FALSE);502emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);503504/* Re-initialize DC predictions to 0 */505for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)506state->cur.last_dc_val[ci] = 0;507508/* The restart counter is not updated until we successfully write the MCU. */509510return TRUE;511}512513514LOCAL(void)515emit_restart_e (huff_entropy_ptr entropy, int restart_num)516{517int ci;518519emit_eobrun(entropy);520521if (! entropy->gather_statistics) {522flush_bits_e(entropy);523emit_byte_e(entropy, 0xFF);524emit_byte_e(entropy, JPEG_RST0 + restart_num);525}526527if (entropy->cinfo->Ss == 0) {528/* Re-initialize DC predictions to 0 */529for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)530entropy->saved.last_dc_val[ci] = 0;531} else {532/* Re-initialize all AC-related fields to 0 */533entropy->EOBRUN = 0;534entropy->BE = 0;535}536}537538539/*540* MCU encoding for DC initial scan (either spectral selection,541* or first pass of successive approximation).542*/543544METHODDEF(boolean)545encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)546{547huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;548register int temp, temp2;549register int nbits;550int blkn, ci, tbl;551ISHIFT_TEMPS552553entropy->next_output_byte = cinfo->dest->next_output_byte;554entropy->free_in_buffer = cinfo->dest->free_in_buffer;555556/* Emit restart marker if needed */557if (cinfo->restart_interval)558if (entropy->restarts_to_go == 0)559emit_restart_e(entropy, entropy->next_restart_num);560561/* Encode the MCU data blocks */562for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {563ci = cinfo->MCU_membership[blkn];564tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;565566/* Compute the DC value after the required point transform by Al.567* This is simply an arithmetic right shift.568*/569temp = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);570571/* DC differences are figured on the point-transformed values. */572temp2 = temp - entropy->saved.last_dc_val[ci];573entropy->saved.last_dc_val[ci] = temp;574575/* Encode the DC coefficient difference per section G.1.2.1 */576temp = temp2;577if (temp < 0) {578temp = -temp; /* temp is abs value of input */579/* For a negative input, want temp2 = bitwise complement of abs(input) */580/* This code assumes we are on a two's complement machine */581temp2--;582}583584/* Find the number of bits needed for the magnitude of the coefficient */585nbits = 0;586while (temp) {587nbits++;588temp >>= 1;589}590/* Check for out-of-range coefficient values.591* Since we're encoding a difference, the range limit is twice as much.592*/593if (nbits > MAX_COEF_BITS+1)594ERREXIT(cinfo, JERR_BAD_DCT_COEF);595596/* Count/emit the Huffman-coded symbol for the number of bits */597emit_dc_symbol(entropy, tbl, nbits);598599/* Emit that number of bits of the value, if positive, */600/* or the complement of its magnitude, if negative. */601if (nbits) /* emit_bits rejects calls with size 0 */602emit_bits_e(entropy, (unsigned int) temp2, nbits);603}604605cinfo->dest->next_output_byte = entropy->next_output_byte;606cinfo->dest->free_in_buffer = entropy->free_in_buffer;607608/* Update restart-interval state too */609if (cinfo->restart_interval) {610if (entropy->restarts_to_go == 0) {611entropy->restarts_to_go = cinfo->restart_interval;612entropy->next_restart_num++;613entropy->next_restart_num &= 7;614}615entropy->restarts_to_go--;616}617618return TRUE;619}620621622/*623* MCU encoding for AC initial scan (either spectral selection,624* or first pass of successive approximation).625*/626627METHODDEF(boolean)628encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)629{630huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;631const int * natural_order;632JBLOCKROW block;633register int temp, temp2;634register int nbits;635register int r, k;636int Se, Al;637638entropy->next_output_byte = cinfo->dest->next_output_byte;639entropy->free_in_buffer = cinfo->dest->free_in_buffer;640641/* Emit restart marker if needed */642if (cinfo->restart_interval)643if (entropy->restarts_to_go == 0)644emit_restart_e(entropy, entropy->next_restart_num);645646Se = cinfo->Se;647Al = cinfo->Al;648natural_order = cinfo->natural_order;649650/* Encode the MCU data block */651block = MCU_data[0];652653/* Encode the AC coefficients per section G.1.2.2, fig. G.3 */654655r = 0; /* r = run length of zeros */656657for (k = cinfo->Ss; k <= Se; k++) {658if ((temp = (*block)[natural_order[k]]) == 0) {659r++;660continue;661}662/* We must apply the point transform by Al. For AC coefficients this663* is an integer division with rounding towards 0. To do this portably664* in C, we shift after obtaining the absolute value; so the code is665* interwoven with finding the abs value (temp) and output bits (temp2).666*/667if (temp < 0) {668temp = -temp; /* temp is abs value of input */669temp >>= Al; /* apply the point transform */670/* For a negative coef, want temp2 = bitwise complement of abs(coef) */671temp2 = ~temp;672} else {673temp >>= Al; /* apply the point transform */674temp2 = temp;675}676/* Watch out for case that nonzero coef is zero after point transform */677if (temp == 0) {678r++;679continue;680}681682/* Emit any pending EOBRUN */683if (entropy->EOBRUN > 0)684emit_eobrun(entropy);685/* if run length > 15, must emit special run-length-16 codes (0xF0) */686while (r > 15) {687emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);688r -= 16;689}690691/* Find the number of bits needed for the magnitude of the coefficient */692nbits = 1; /* there must be at least one 1 bit */693while ((temp >>= 1))694nbits++;695/* Check for out-of-range coefficient values */696if (nbits > MAX_COEF_BITS)697ERREXIT(cinfo, JERR_BAD_DCT_COEF);698699/* Count/emit Huffman symbol for run length / number of bits */700emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);701702/* Emit that number of bits of the value, if positive, */703/* or the complement of its magnitude, if negative. */704emit_bits_e(entropy, (unsigned int) temp2, nbits);705706r = 0; /* reset zero run length */707}708709if (r > 0) { /* If there are trailing zeroes, */710entropy->EOBRUN++; /* count an EOB */711if (entropy->EOBRUN == 0x7FFF)712emit_eobrun(entropy); /* force it out to avoid overflow */713}714715cinfo->dest->next_output_byte = entropy->next_output_byte;716cinfo->dest->free_in_buffer = entropy->free_in_buffer;717718/* Update restart-interval state too */719if (cinfo->restart_interval) {720if (entropy->restarts_to_go == 0) {721entropy->restarts_to_go = cinfo->restart_interval;722entropy->next_restart_num++;723entropy->next_restart_num &= 7;724}725entropy->restarts_to_go--;726}727728return TRUE;729}730731732/*733* MCU encoding for DC successive approximation refinement scan.734* Note: we assume such scans can be multi-component,735* although the spec is not very clear on the point.736*/737738METHODDEF(boolean)739encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)740{741huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;742int Al, blkn;743744entropy->next_output_byte = cinfo->dest->next_output_byte;745entropy->free_in_buffer = cinfo->dest->free_in_buffer;746747/* Emit restart marker if needed */748if (cinfo->restart_interval)749if (entropy->restarts_to_go == 0)750emit_restart_e(entropy, entropy->next_restart_num);751752Al = cinfo->Al;753754/* Encode the MCU data blocks */755for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {756/* We simply emit the Al'th bit of the DC coefficient value. */757emit_bits_e(entropy, (unsigned int) (MCU_data[blkn][0][0] >> Al), 1);758}759760cinfo->dest->next_output_byte = entropy->next_output_byte;761cinfo->dest->free_in_buffer = entropy->free_in_buffer;762763/* Update restart-interval state too */764if (cinfo->restart_interval) {765if (entropy->restarts_to_go == 0) {766entropy->restarts_to_go = cinfo->restart_interval;767entropy->next_restart_num++;768entropy->next_restart_num &= 7;769}770entropy->restarts_to_go--;771}772773return TRUE;774}775776777/*778* MCU encoding for AC successive approximation refinement scan.779*/780781METHODDEF(boolean)782encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)783{784huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;785const int * natural_order;786JBLOCKROW block;787register int temp;788register int r, k;789int Se, Al;790int EOB;791char *BR_buffer;792unsigned int BR;793int absvalues[DCTSIZE2];794795entropy->next_output_byte = cinfo->dest->next_output_byte;796entropy->free_in_buffer = cinfo->dest->free_in_buffer;797798/* Emit restart marker if needed */799if (cinfo->restart_interval)800if (entropy->restarts_to_go == 0)801emit_restart_e(entropy, entropy->next_restart_num);802803Se = cinfo->Se;804Al = cinfo->Al;805natural_order = cinfo->natural_order;806807/* Encode the MCU data block */808block = MCU_data[0];809810/* It is convenient to make a pre-pass to determine the transformed811* coefficients' absolute values and the EOB position.812*/813EOB = 0;814for (k = cinfo->Ss; k <= Se; k++) {815temp = (*block)[natural_order[k]];816/* We must apply the point transform by Al. For AC coefficients this817* is an integer division with rounding towards 0. To do this portably818* in C, we shift after obtaining the absolute value.819*/820if (temp < 0)821temp = -temp; /* temp is abs value of input */822temp >>= Al; /* apply the point transform */823absvalues[k] = temp; /* save abs value for main pass */824if (temp == 1)825EOB = k; /* EOB = index of last newly-nonzero coef */826}827828/* Encode the AC coefficients per section G.1.2.3, fig. G.7 */829830r = 0; /* r = run length of zeros */831BR = 0; /* BR = count of buffered bits added now */832BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */833834for (k = cinfo->Ss; k <= Se; k++) {835if ((temp = absvalues[k]) == 0) {836r++;837continue;838}839840/* Emit any required ZRLs, but not if they can be folded into EOB */841while (r > 15 && k <= EOB) {842/* emit any pending EOBRUN and the BE correction bits */843emit_eobrun(entropy);844/* Emit ZRL */845emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);846r -= 16;847/* Emit buffered correction bits that must be associated with ZRL */848emit_buffered_bits(entropy, BR_buffer, BR);849BR_buffer = entropy->bit_buffer; /* BE bits are gone now */850BR = 0;851}852853/* If the coef was previously nonzero, it only needs a correction bit.854* NOTE: a straight translation of the spec's figure G.7 would suggest855* that we also need to test r > 15. But if r > 15, we can only get here856* if k > EOB, which implies that this coefficient is not 1.857*/858if (temp > 1) {859/* The correction bit is the next bit of the absolute value. */860BR_buffer[BR++] = (char) (temp & 1);861continue;862}863864/* Emit any pending EOBRUN and the BE correction bits */865emit_eobrun(entropy);866867/* Count/emit Huffman symbol for run length / number of bits */868emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);869870/* Emit output bit for newly-nonzero coef */871temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;872emit_bits_e(entropy, (unsigned int) temp, 1);873874/* Emit buffered correction bits that must be associated with this code */875emit_buffered_bits(entropy, BR_buffer, BR);876BR_buffer = entropy->bit_buffer; /* BE bits are gone now */877BR = 0;878r = 0; /* reset zero run length */879}880881if (r > 0 || BR > 0) { /* If there are trailing zeroes, */882entropy->EOBRUN++; /* count an EOB */883entropy->BE += BR; /* concat my correction bits to older ones */884/* We force out the EOB if we risk either:885* 1. overflow of the EOB counter;886* 2. overflow of the correction bit buffer during the next MCU.887*/888if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))889emit_eobrun(entropy);890}891892cinfo->dest->next_output_byte = entropy->next_output_byte;893cinfo->dest->free_in_buffer = entropy->free_in_buffer;894895/* Update restart-interval state too */896if (cinfo->restart_interval) {897if (entropy->restarts_to_go == 0) {898entropy->restarts_to_go = cinfo->restart_interval;899entropy->next_restart_num++;900entropy->next_restart_num &= 7;901}902entropy->restarts_to_go--;903}904905return TRUE;906}907908909/* Encode a single block's worth of coefficients */910911LOCAL(boolean)912encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,913c_derived_tbl *dctbl, c_derived_tbl *actbl)914{915register int temp, temp2;916register int nbits;917register int r, k;918int Se = state->cinfo->lim_Se;919const int * natural_order = state->cinfo->natural_order;920921/* Encode the DC coefficient difference per section F.1.2.1 */922923temp = temp2 = block[0] - last_dc_val;924925if (temp < 0) {926temp = -temp; /* temp is abs value of input */927/* For a negative input, want temp2 = bitwise complement of abs(input) */928/* This code assumes we are on a two's complement machine */929temp2--;930}931932/* Find the number of bits needed for the magnitude of the coefficient */933nbits = 0;934while (temp) {935nbits++;936temp >>= 1;937}938/* Check for out-of-range coefficient values.939* Since we're encoding a difference, the range limit is twice as much.940*/941if (nbits > MAX_COEF_BITS+1)942ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);943944/* Emit the Huffman-coded symbol for the number of bits */945if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))946return FALSE;947948/* Emit that number of bits of the value, if positive, */949/* or the complement of its magnitude, if negative. */950if (nbits) /* emit_bits rejects calls with size 0 */951if (! emit_bits_s(state, (unsigned int) temp2, nbits))952return FALSE;953954/* Encode the AC coefficients per section F.1.2.2 */955956r = 0; /* r = run length of zeros */957958for (k = 1; k <= Se; k++) {959if ((temp2 = block[natural_order[k]]) == 0) {960r++;961} else {962/* if run length > 15, must emit special run-length-16 codes (0xF0) */963while (r > 15) {964if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))965return FALSE;966r -= 16;967}968969temp = temp2;970if (temp < 0) {971temp = -temp; /* temp is abs value of input */972/* This code assumes we are on a two's complement machine */973temp2--;974}975976/* Find the number of bits needed for the magnitude of the coefficient */977nbits = 1; /* there must be at least one 1 bit */978while ((temp >>= 1))979nbits++;980/* Check for out-of-range coefficient values */981if (nbits > MAX_COEF_BITS)982ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);983984/* Emit Huffman symbol for run length / number of bits */985temp = (r << 4) + nbits;986if (! emit_bits_s(state, actbl->ehufco[temp], actbl->ehufsi[temp]))987return FALSE;988989/* Emit that number of bits of the value, if positive, */990/* or the complement of its magnitude, if negative. */991if (! emit_bits_s(state, (unsigned int) temp2, nbits))992return FALSE;993994r = 0;995}996}997998/* If the last coef(s) were zero, emit an end-of-block code */999if (r > 0)1000if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))1001return FALSE;10021003return TRUE;1004}100510061007/*1008* Encode and output one MCU's worth of Huffman-compressed coefficients.1009*/10101011METHODDEF(boolean)1012encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)1013{1014huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1015working_state state;1016int blkn, ci;1017jpeg_component_info * compptr;10181019/* Load up working state */1020state.next_output_byte = cinfo->dest->next_output_byte;1021state.free_in_buffer = cinfo->dest->free_in_buffer;1022ASSIGN_STATE(state.cur, entropy->saved);1023state.cinfo = cinfo;10241025/* Emit restart marker if needed */1026if (cinfo->restart_interval) {1027if (entropy->restarts_to_go == 0)1028if (! emit_restart_s(&state, entropy->next_restart_num))1029return FALSE;1030}10311032/* Encode the MCU data blocks */1033for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1034ci = cinfo->MCU_membership[blkn];1035compptr = cinfo->cur_comp_info[ci];1036if (! encode_one_block(&state,1037MCU_data[blkn][0], state.cur.last_dc_val[ci],1038entropy->dc_derived_tbls[compptr->dc_tbl_no],1039entropy->ac_derived_tbls[compptr->ac_tbl_no]))1040return FALSE;1041/* Update last_dc_val */1042state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];1043}10441045/* Completed MCU, so update state */1046cinfo->dest->next_output_byte = state.next_output_byte;1047cinfo->dest->free_in_buffer = state.free_in_buffer;1048ASSIGN_STATE(entropy->saved, state.cur);10491050/* Update restart-interval state too */1051if (cinfo->restart_interval) {1052if (entropy->restarts_to_go == 0) {1053entropy->restarts_to_go = cinfo->restart_interval;1054entropy->next_restart_num++;1055entropy->next_restart_num &= 7;1056}1057entropy->restarts_to_go--;1058}10591060return TRUE;1061}106210631064/*1065* Finish up at the end of a Huffman-compressed scan.1066*/10671068METHODDEF(void)1069finish_pass_huff (j_compress_ptr cinfo)1070{1071huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1072working_state state;10731074if (cinfo->progressive_mode) {1075entropy->next_output_byte = cinfo->dest->next_output_byte;1076entropy->free_in_buffer = cinfo->dest->free_in_buffer;10771078/* Flush out any buffered data */1079emit_eobrun(entropy);1080flush_bits_e(entropy);10811082cinfo->dest->next_output_byte = entropy->next_output_byte;1083cinfo->dest->free_in_buffer = entropy->free_in_buffer;1084} else {1085/* Load up working state ... flush_bits needs it */1086state.next_output_byte = cinfo->dest->next_output_byte;1087state.free_in_buffer = cinfo->dest->free_in_buffer;1088ASSIGN_STATE(state.cur, entropy->saved);1089state.cinfo = cinfo;10901091/* Flush out the last data */1092if (! flush_bits_s(&state))1093ERREXIT(cinfo, JERR_CANT_SUSPEND);10941095/* Update state */1096cinfo->dest->next_output_byte = state.next_output_byte;1097cinfo->dest->free_in_buffer = state.free_in_buffer;1098ASSIGN_STATE(entropy->saved, state.cur);1099}1100}110111021103/*1104* Huffman coding optimization.1105*1106* We first scan the supplied data and count the number of uses of each symbol1107* that is to be Huffman-coded. (This process MUST agree with the code above.)1108* Then we build a Huffman coding tree for the observed counts.1109* Symbols which are not needed at all for the particular image are not1110* assigned any code, which saves space in the DHT marker as well as in1111* the compressed data.1112*/111311141115/* Process a single block's worth of coefficients */11161117LOCAL(void)1118htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,1119long dc_counts[], long ac_counts[])1120{1121register int temp;1122register int nbits;1123register int r, k;1124int Se = cinfo->lim_Se;1125const int * natural_order = cinfo->natural_order;11261127/* Encode the DC coefficient difference per section F.1.2.1 */11281129temp = block[0] - last_dc_val;1130if (temp < 0)1131temp = -temp;11321133/* Find the number of bits needed for the magnitude of the coefficient */1134nbits = 0;1135while (temp) {1136nbits++;1137temp >>= 1;1138}1139/* Check for out-of-range coefficient values.1140* Since we're encoding a difference, the range limit is twice as much.1141*/1142if (nbits > MAX_COEF_BITS+1)1143ERREXIT(cinfo, JERR_BAD_DCT_COEF);11441145/* Count the Huffman symbol for the number of bits */1146dc_counts[nbits]++;11471148/* Encode the AC coefficients per section F.1.2.2 */11491150r = 0; /* r = run length of zeros */11511152for (k = 1; k <= Se; k++) {1153if ((temp = block[natural_order[k]]) == 0) {1154r++;1155} else {1156/* if run length > 15, must emit special run-length-16 codes (0xF0) */1157while (r > 15) {1158ac_counts[0xF0]++;1159r -= 16;1160}11611162/* Find the number of bits needed for the magnitude of the coefficient */1163if (temp < 0)1164temp = -temp;11651166/* Find the number of bits needed for the magnitude of the coefficient */1167nbits = 1; /* there must be at least one 1 bit */1168while ((temp >>= 1))1169nbits++;1170/* Check for out-of-range coefficient values */1171if (nbits > MAX_COEF_BITS)1172ERREXIT(cinfo, JERR_BAD_DCT_COEF);11731174/* Count Huffman symbol for run length / number of bits */1175ac_counts[(r << 4) + nbits]++;11761177r = 0;1178}1179}11801181/* If the last coef(s) were zero, emit an end-of-block code */1182if (r > 0)1183ac_counts[0]++;1184}118511861187/*1188* Trial-encode one MCU's worth of Huffman-compressed coefficients.1189* No data is actually output, so no suspension return is possible.1190*/11911192METHODDEF(boolean)1193encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)1194{1195huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1196int blkn, ci;1197jpeg_component_info * compptr;11981199/* Take care of restart intervals if needed */1200if (cinfo->restart_interval) {1201if (entropy->restarts_to_go == 0) {1202/* Re-initialize DC predictions to 0 */1203for (ci = 0; ci < cinfo->comps_in_scan; ci++)1204entropy->saved.last_dc_val[ci] = 0;1205/* Update restart state */1206entropy->restarts_to_go = cinfo->restart_interval;1207}1208entropy->restarts_to_go--;1209}12101211for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1212ci = cinfo->MCU_membership[blkn];1213compptr = cinfo->cur_comp_info[ci];1214htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],1215entropy->dc_count_ptrs[compptr->dc_tbl_no],1216entropy->ac_count_ptrs[compptr->ac_tbl_no]);1217entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];1218}12191220return TRUE;1221}122212231224/*1225* Generate the best Huffman code table for the given counts, fill htbl.1226*1227* The JPEG standard requires that no symbol be assigned a codeword of all1228* one bits (so that padding bits added at the end of a compressed segment1229* can't look like a valid code). Because of the canonical ordering of1230* codewords, this just means that there must be an unused slot in the1231* longest codeword length category. Section K.2 of the JPEG spec suggests1232* reserving such a slot by pretending that symbol 256 is a valid symbol1233* with count 1. In theory that's not optimal; giving it count zero but1234* including it in the symbol set anyway should give a better Huffman code.1235* But the theoretically better code actually seems to come out worse in1236* practice, because it produces more all-ones bytes (which incur stuffed1237* zero bytes in the final file). In any case the difference is tiny.1238*1239* The JPEG standard requires Huffman codes to be no more than 16 bits long.1240* If some symbols have a very small but nonzero probability, the Huffman tree1241* must be adjusted to meet the code length restriction. We currently use1242* the adjustment method suggested in JPEG section K.2. This method is *not*1243* optimal; it may not choose the best possible limited-length code. But1244* typically only very-low-frequency symbols will be given less-than-optimal1245* lengths, so the code is almost optimal. Experimental comparisons against1246* an optimal limited-length-code algorithm indicate that the difference is1247* microscopic --- usually less than a hundredth of a percent of total size.1248* So the extra complexity of an optimal algorithm doesn't seem worthwhile.1249*/12501251LOCAL(void)1252jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])1253{1254#define MAX_CLEN 32 /* assumed maximum initial code length */1255UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */1256int codesize[257]; /* codesize[k] = code length of symbol k */1257int others[257]; /* next symbol in current branch of tree */1258int c1, c2;1259int p, i, j;1260long v;12611262/* This algorithm is explained in section K.2 of the JPEG standard */12631264MEMZERO(bits, SIZEOF(bits));1265MEMZERO(codesize, SIZEOF(codesize));1266for (i = 0; i < 257; i++)1267others[i] = -1; /* init links to empty */12681269freq[256] = 1; /* make sure 256 has a nonzero count */1270/* Including the pseudo-symbol 256 in the Huffman procedure guarantees1271* that no real symbol is given code-value of all ones, because 2561272* will be placed last in the largest codeword category.1273*/12741275/* Huffman's basic algorithm to assign optimal code lengths to symbols */12761277for (;;) {1278/* Find the smallest nonzero frequency, set c1 = its symbol */1279/* In case of ties, take the larger symbol number */1280c1 = -1;1281v = 1000000000L;1282for (i = 0; i <= 256; i++) {1283if (freq[i] && freq[i] <= v) {1284v = freq[i];1285c1 = i;1286}1287}12881289/* Find the next smallest nonzero frequency, set c2 = its symbol */1290/* In case of ties, take the larger symbol number */1291c2 = -1;1292v = 1000000000L;1293for (i = 0; i <= 256; i++) {1294if (freq[i] && freq[i] <= v && i != c1) {1295v = freq[i];1296c2 = i;1297}1298}12991300/* Done if we've merged everything into one frequency */1301if (c2 < 0)1302break;13031304/* Else merge the two counts/trees */1305freq[c1] += freq[c2];1306freq[c2] = 0;13071308/* Increment the codesize of everything in c1's tree branch */1309codesize[c1]++;1310while (others[c1] >= 0) {1311c1 = others[c1];1312codesize[c1]++;1313}13141315others[c1] = c2; /* chain c2 onto c1's tree branch */13161317/* Increment the codesize of everything in c2's tree branch */1318codesize[c2]++;1319while (others[c2] >= 0) {1320c2 = others[c2];1321codesize[c2]++;1322}1323}13241325/* Now count the number of symbols of each code length */1326for (i = 0; i <= 256; i++) {1327if (codesize[i]) {1328/* The JPEG standard seems to think that this can't happen, */1329/* but I'm paranoid... */1330if (codesize[i] > MAX_CLEN)1331ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);13321333bits[codesize[i]]++;1334}1335}13361337/* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure1338* Huffman procedure assigned any such lengths, we must adjust the coding.1339* Here is what the JPEG spec says about how this next bit works:1340* Since symbols are paired for the longest Huffman code, the symbols are1341* removed from this length category two at a time. The prefix for the pair1342* (which is one bit shorter) is allocated to one of the pair; then,1343* skipping the BITS entry for that prefix length, a code word from the next1344* shortest nonzero BITS entry is converted into a prefix for two code words1345* one bit longer.1346*/13471348for (i = MAX_CLEN; i > 16; i--) {1349while (bits[i] > 0) {1350j = i - 2; /* find length of new prefix to be used */1351while (bits[j] == 0)1352j--;13531354bits[i] -= 2; /* remove two symbols */1355bits[i-1]++; /* one goes in this length */1356bits[j+1] += 2; /* two new symbols in this length */1357bits[j]--; /* symbol of this length is now a prefix */1358}1359}13601361/* Remove the count for the pseudo-symbol 256 from the largest codelength */1362while (bits[i] == 0) /* find largest codelength still in use */1363i--;1364bits[i]--;13651366/* Return final symbol counts (only for lengths 0..16) */1367MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));13681369/* Return a list of the symbols sorted by code length */1370/* It's not real clear to me why we don't need to consider the codelength1371* changes made above, but the JPEG spec seems to think this works.1372*/1373p = 0;1374for (i = 1; i <= MAX_CLEN; i++) {1375for (j = 0; j <= 255; j++) {1376if (codesize[j] == i) {1377htbl->huffval[p] = (UINT8) j;1378p++;1379}1380}1381}13821383/* Set sent_table FALSE so updated table will be written to JPEG file. */1384htbl->sent_table = FALSE;1385}138613871388/*1389* Finish up a statistics-gathering pass and create the new Huffman tables.1390*/13911392METHODDEF(void)1393finish_pass_gather (j_compress_ptr cinfo)1394{1395huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1396int ci, tbl;1397jpeg_component_info * compptr;1398JHUFF_TBL **htblptr;1399boolean did_dc[NUM_HUFF_TBLS];1400boolean did_ac[NUM_HUFF_TBLS];14011402/* It's important not to apply jpeg_gen_optimal_table more than once1403* per table, because it clobbers the input frequency counts!1404*/1405if (cinfo->progressive_mode)1406/* Flush out buffered data (all we care about is counting the EOB symbol) */1407emit_eobrun(entropy);14081409MEMZERO(did_dc, SIZEOF(did_dc));1410MEMZERO(did_ac, SIZEOF(did_ac));14111412for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1413compptr = cinfo->cur_comp_info[ci];1414/* DC needs no table for refinement scan */1415if (cinfo->Ss == 0 && cinfo->Ah == 0) {1416tbl = compptr->dc_tbl_no;1417if (! did_dc[tbl]) {1418htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];1419if (*htblptr == NULL)1420*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);1421jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);1422did_dc[tbl] = TRUE;1423}1424}1425/* AC needs no table when not present */1426if (cinfo->Se) {1427tbl = compptr->ac_tbl_no;1428if (! did_ac[tbl]) {1429htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];1430if (*htblptr == NULL)1431*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);1432jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);1433did_ac[tbl] = TRUE;1434}1435}1436}1437}143814391440/*1441* Initialize for a Huffman-compressed scan.1442* If gather_statistics is TRUE, we do not output anything during the scan,1443* just count the Huffman symbols used and generate Huffman code tables.1444*/14451446METHODDEF(void)1447start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)1448{1449huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1450int ci, tbl;1451jpeg_component_info * compptr;14521453if (gather_statistics)1454entropy->pub.finish_pass = finish_pass_gather;1455else1456entropy->pub.finish_pass = finish_pass_huff;14571458if (cinfo->progressive_mode) {1459entropy->cinfo = cinfo;1460entropy->gather_statistics = gather_statistics;14611462/* We assume jcmaster.c already validated the scan parameters. */14631464/* Select execution routine */1465if (cinfo->Ah == 0) {1466if (cinfo->Ss == 0)1467entropy->pub.encode_mcu = encode_mcu_DC_first;1468else1469entropy->pub.encode_mcu = encode_mcu_AC_first;1470} else {1471if (cinfo->Ss == 0)1472entropy->pub.encode_mcu = encode_mcu_DC_refine;1473else {1474entropy->pub.encode_mcu = encode_mcu_AC_refine;1475/* AC refinement needs a correction bit buffer */1476if (entropy->bit_buffer == NULL)1477entropy->bit_buffer = (char *)1478(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,1479MAX_CORR_BITS * SIZEOF(char));1480}1481}14821483/* Initialize AC stuff */1484entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;1485entropy->EOBRUN = 0;1486entropy->BE = 0;1487} else {1488if (gather_statistics)1489entropy->pub.encode_mcu = encode_mcu_gather;1490else1491entropy->pub.encode_mcu = encode_mcu_huff;1492}14931494for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1495compptr = cinfo->cur_comp_info[ci];1496/* DC needs no table for refinement scan */1497if (cinfo->Ss == 0 && cinfo->Ah == 0) {1498tbl = compptr->dc_tbl_no;1499if (gather_statistics) {1500/* Check for invalid table index */1501/* (make_c_derived_tbl does this in the other path) */1502if (tbl < 0 || tbl >= NUM_HUFF_TBLS)1503ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);1504/* Allocate and zero the statistics tables */1505/* Note that jpeg_gen_optimal_table expects 257 entries in each table! */1506if (entropy->dc_count_ptrs[tbl] == NULL)1507entropy->dc_count_ptrs[tbl] = (long *)1508(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,1509257 * SIZEOF(long));1510MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));1511} else {1512/* Compute derived values for Huffman tables */1513/* We may do this more than once for a table, but it's not expensive */1514jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,1515& entropy->dc_derived_tbls[tbl]);1516}1517/* Initialize DC predictions to 0 */1518entropy->saved.last_dc_val[ci] = 0;1519}1520/* AC needs no table when not present */1521if (cinfo->Se) {1522tbl = compptr->ac_tbl_no;1523if (gather_statistics) {1524if (tbl < 0 || tbl >= NUM_HUFF_TBLS)1525ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);1526if (entropy->ac_count_ptrs[tbl] == NULL)1527entropy->ac_count_ptrs[tbl] = (long *)1528(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,1529257 * SIZEOF(long));1530MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));1531} else {1532jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,1533& entropy->ac_derived_tbls[tbl]);1534}1535}1536}15371538/* Initialize bit buffer to empty */1539entropy->saved.put_buffer = 0;1540entropy->saved.put_bits = 0;15411542/* Initialize restart stuff */1543entropy->restarts_to_go = cinfo->restart_interval;1544entropy->next_restart_num = 0;1545}154615471548/*1549* Module initialization routine for Huffman entropy encoding.1550*/15511552GLOBAL(void)1553jinit_huff_encoder (j_compress_ptr cinfo)1554{1555huff_entropy_ptr entropy;1556int i;15571558entropy = (huff_entropy_ptr)1559(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,1560SIZEOF(huff_entropy_encoder));1561cinfo->entropy = &entropy->pub;1562entropy->pub.start_pass = start_pass_huff;15631564/* Mark tables unallocated */1565for (i = 0; i < NUM_HUFF_TBLS; i++) {1566entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;1567entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;1568}15691570if (cinfo->progressive_mode)1571entropy->bit_buffer = NULL; /* needed only in AC refinement scan */1572}157315741575