/*1* jcarith.c2*3* Developed 1997-2013 by Guido Vollbeding.4* This file is part of the Independent JPEG Group's software.5* For conditions of distribution and use, see the accompanying README file.6*7* This file contains portable arithmetic entropy encoding routines for JPEG8* (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).9*10* Both sequential and progressive modes are supported in this single module.11*12* Suspension is not currently supported in this module.13*/1415#define JPEG_INTERNALS16#include "jinclude.h"17#include "jpeglib.h"181920/* Expanded entropy encoder object for arithmetic encoding. */2122typedef struct {23struct jpeg_entropy_encoder pub; /* public fields */2425INT32 c; /* C register, base of coding interval, layout as in sec. D.1.3 */26INT32 a; /* A register, normalized size of coding interval */27INT32 sc; /* counter for stacked 0xFF values which might overflow */28INT32 zc; /* counter for pending 0x00 output values which might *29* be discarded at the end ("Pacman" termination) */30int ct; /* bit shift counter, determines when next byte will be written */31int buffer; /* buffer for most recent output byte != 0xFF */3233int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */34int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */3536unsigned int restarts_to_go; /* MCUs left in this restart interval */37int next_restart_num; /* next restart number to write (0-7) */3839/* Pointers to statistics areas (these workspaces have image lifespan) */40unsigned char * dc_stats[NUM_ARITH_TBLS];41unsigned char * ac_stats[NUM_ARITH_TBLS];4243/* Statistics bin for coding with fixed probability 0.5 */44unsigned char fixed_bin[4];45} arith_entropy_encoder;4647typedef arith_entropy_encoder * arith_entropy_ptr;4849/* The following two definitions specify the allocation chunk size50* for the statistics area.51* According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least52* 49 statistics bins for DC, and 245 statistics bins for AC coding.53*54* We use a compact representation with 1 byte per statistics bin,55* thus the numbers directly represent byte sizes.56* This 1 byte per statistics bin contains the meaning of the MPS57* (more probable symbol) in the highest bit (mask 0x80), and the58* index into the probability estimation state machine table59* in the lower bits (mask 0x7F).60*/6162#define DC_STAT_BINS 6463#define AC_STAT_BINS 2566465/* NOTE: Uncomment the following #define if you want to use the66* given formula for calculating the AC conditioning parameter Kx67* for spectral selection progressive coding in section G.1.3.268* of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4).69* Although the spec and P&M authors claim that this "has proven70* to give good results for 8 bit precision samples", I'm not71* convinced yet that this is really beneficial.72* Early tests gave only very marginal compression enhancements73* (a few - around 5 or so - bytes even for very large files),74* which would turn out rather negative if we'd suppress the75* DAC (Define Arithmetic Conditioning) marker segments for76* the default parameters in the future.77* Note that currently the marker writing module emits 12-byte78* DAC segments for a full-component scan in a color image.79* This is not worth worrying about IMHO. However, since the80* spec defines the default values to be used if the tables81* are omitted (unlike Huffman tables, which are required82* anyway), one might optimize this behaviour in the future,83* and then it would be disadvantageous to use custom tables if84* they don't provide sufficient gain to exceed the DAC size.85*86* On the other hand, I'd consider it as a reasonable result87* that the conditioning has no significant influence on the88* compression performance. This means that the basic89* statistical model is already rather stable.90*91* Thus, at the moment, we use the default conditioning values92* anyway, and do not use the custom formula.93*94#define CALCULATE_SPECTRAL_CONDITIONING95*/9697/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.98* We assume that int right shift is unsigned if INT32 right shift is,99* which should be safe.100*/101102#ifdef RIGHT_SHIFT_IS_UNSIGNED103#define ISHIFT_TEMPS int ishift_temp;104#define IRIGHT_SHIFT(x,shft) \105((ishift_temp = (x)) < 0 ? \106(ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \107(ishift_temp >> (shft)))108#else109#define ISHIFT_TEMPS110#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))111#endif112113114LOCAL(void)115emit_byte (int val, j_compress_ptr cinfo)116/* Write next output byte; we do not support suspension in this module. */117{118struct jpeg_destination_mgr * dest = cinfo->dest;119120*dest->next_output_byte++ = (JOCTET) val;121if (--dest->free_in_buffer == 0)122if (! (*dest->empty_output_buffer) (cinfo))123ERREXIT(cinfo, JERR_CANT_SUSPEND);124}125126127/*128* Finish up at the end of an arithmetic-compressed scan.129*/130131METHODDEF(void)132finish_pass (j_compress_ptr cinfo)133{134arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;135INT32 temp;136137/* Section D.1.8: Termination of encoding */138139/* Find the e->c in the coding interval with the largest140* number of trailing zero bits */141if ((temp = (e->a - 1 + e->c) & 0xFFFF0000L) < e->c)142e->c = temp + 0x8000L;143else144e->c = temp;145/* Send remaining bytes to output */146e->c <<= e->ct;147if (e->c & 0xF8000000L) {148/* One final overflow has to be handled */149if (e->buffer >= 0) {150if (e->zc)151do emit_byte(0x00, cinfo);152while (--e->zc);153emit_byte(e->buffer + 1, cinfo);154if (e->buffer + 1 == 0xFF)155emit_byte(0x00, cinfo);156}157e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */158e->sc = 0;159} else {160if (e->buffer == 0)161++e->zc;162else if (e->buffer >= 0) {163if (e->zc)164do emit_byte(0x00, cinfo);165while (--e->zc);166emit_byte(e->buffer, cinfo);167}168if (e->sc) {169if (e->zc)170do emit_byte(0x00, cinfo);171while (--e->zc);172do {173emit_byte(0xFF, cinfo);174emit_byte(0x00, cinfo);175} while (--e->sc);176}177}178/* Output final bytes only if they are not 0x00 */179if (e->c & 0x7FFF800L) {180if (e->zc) /* output final pending zero bytes */181do emit_byte(0x00, cinfo);182while (--e->zc);183emit_byte((e->c >> 19) & 0xFF, cinfo);184if (((e->c >> 19) & 0xFF) == 0xFF)185emit_byte(0x00, cinfo);186if (e->c & 0x7F800L) {187emit_byte((e->c >> 11) & 0xFF, cinfo);188if (((e->c >> 11) & 0xFF) == 0xFF)189emit_byte(0x00, cinfo);190}191}192}193194195/*196* The core arithmetic encoding routine (common in JPEG and JBIG).197* This needs to go as fast as possible.198* Machine-dependent optimization facilities199* are not utilized in this portable implementation.200* However, this code should be fairly efficient and201* may be a good base for further optimizations anyway.202*203* Parameter 'val' to be encoded may be 0 or 1 (binary decision).204*205* Note: I've added full "Pacman" termination support to the206* byte output routines, which is equivalent to the optional207* Discard_final_zeros procedure (Figure D.15) in the spec.208* Thus, we always produce the shortest possible output209* stream compliant to the spec (no trailing zero bytes,210* except for FF stuffing).211*212* I've also introduced a new scheme for accessing213* the probability estimation state machine table,214* derived from Markus Kuhn's JBIG implementation.215*/216217LOCAL(void)218arith_encode (j_compress_ptr cinfo, unsigned char *st, int val)219{220register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;221register unsigned char nl, nm;222register INT32 qe, temp;223register int sv;224225/* Fetch values from our compact representation of Table D.3(D.2):226* Qe values and probability estimation state machine227*/228sv = *st;229qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */230nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */231nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */232233/* Encode & estimation procedures per sections D.1.4 & D.1.5 */234e->a -= qe;235if (val != (sv >> 7)) {236/* Encode the less probable symbol */237if (e->a >= qe) {238/* If the interval size (qe) for the less probable symbol (LPS)239* is larger than the interval size for the MPS, then exchange240* the two symbols for coding efficiency, otherwise code the LPS241* as usual: */242e->c += e->a;243e->a = qe;244}245*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */246} else {247/* Encode the more probable symbol */248if (e->a >= 0x8000L)249return; /* A >= 0x8000 -> ready, no renormalization required */250if (e->a < qe) {251/* If the interval size (qe) for the less probable symbol (LPS)252* is larger than the interval size for the MPS, then exchange253* the two symbols for coding efficiency: */254e->c += e->a;255e->a = qe;256}257*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */258}259260/* Renormalization & data output per section D.1.6 */261do {262e->a <<= 1;263e->c <<= 1;264if (--e->ct == 0) {265/* Another byte is ready for output */266temp = e->c >> 19;267if (temp > 0xFF) {268/* Handle overflow over all stacked 0xFF bytes */269if (e->buffer >= 0) {270if (e->zc)271do emit_byte(0x00, cinfo);272while (--e->zc);273emit_byte(e->buffer + 1, cinfo);274if (e->buffer + 1 == 0xFF)275emit_byte(0x00, cinfo);276}277e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */278e->sc = 0;279/* Note: The 3 spacer bits in the C register guarantee280* that the new buffer byte can't be 0xFF here281* (see page 160 in the P&M JPEG book). */282e->buffer = temp & 0xFF; /* new output byte, might overflow later */283} else if (temp == 0xFF) {284++e->sc; /* stack 0xFF byte (which might overflow later) */285} else {286/* Output all stacked 0xFF bytes, they will not overflow any more */287if (e->buffer == 0)288++e->zc;289else if (e->buffer >= 0) {290if (e->zc)291do emit_byte(0x00, cinfo);292while (--e->zc);293emit_byte(e->buffer, cinfo);294}295if (e->sc) {296if (e->zc)297do emit_byte(0x00, cinfo);298while (--e->zc);299do {300emit_byte(0xFF, cinfo);301emit_byte(0x00, cinfo);302} while (--e->sc);303}304e->buffer = temp & 0xFF; /* new output byte (can still overflow) */305}306e->c &= 0x7FFFFL;307e->ct += 8;308}309} while (e->a < 0x8000L);310}311312313/*314* Emit a restart marker & resynchronize predictions.315*/316317LOCAL(void)318emit_restart (j_compress_ptr cinfo, int restart_num)319{320arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;321int ci;322jpeg_component_info * compptr;323324finish_pass(cinfo);325326emit_byte(0xFF, cinfo);327emit_byte(JPEG_RST0 + restart_num, cinfo);328329/* Re-initialize statistics areas */330for (ci = 0; ci < cinfo->comps_in_scan; ci++) {331compptr = cinfo->cur_comp_info[ci];332/* DC needs no table for refinement scan */333if (cinfo->Ss == 0 && cinfo->Ah == 0) {334MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);335/* Reset DC predictions to 0 */336entropy->last_dc_val[ci] = 0;337entropy->dc_context[ci] = 0;338}339/* AC needs no table when not present */340if (cinfo->Se) {341MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);342}343}344345/* Reset arithmetic encoding variables */346entropy->c = 0;347entropy->a = 0x10000L;348entropy->sc = 0;349entropy->zc = 0;350entropy->ct = 11;351entropy->buffer = -1; /* empty */352}353354355/*356* MCU encoding for DC initial scan (either spectral selection,357* or first pass of successive approximation).358*/359360METHODDEF(boolean)361encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)362{363arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;364unsigned char *st;365int blkn, ci, tbl;366int v, v2, m;367ISHIFT_TEMPS368369/* Emit restart marker if needed */370if (cinfo->restart_interval) {371if (entropy->restarts_to_go == 0) {372emit_restart(cinfo, entropy->next_restart_num);373entropy->restarts_to_go = cinfo->restart_interval;374entropy->next_restart_num++;375entropy->next_restart_num &= 7;376}377entropy->restarts_to_go--;378}379380/* Encode the MCU data blocks */381for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {382ci = cinfo->MCU_membership[blkn];383tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;384385/* Compute the DC value after the required point transform by Al.386* This is simply an arithmetic right shift.387*/388m = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);389390/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */391392/* Table F.4: Point to statistics bin S0 for DC coefficient coding */393st = entropy->dc_stats[tbl] + entropy->dc_context[ci];394395/* Figure F.4: Encode_DC_DIFF */396if ((v = m - entropy->last_dc_val[ci]) == 0) {397arith_encode(cinfo, st, 0);398entropy->dc_context[ci] = 0; /* zero diff category */399} else {400entropy->last_dc_val[ci] = m;401arith_encode(cinfo, st, 1);402/* Figure F.6: Encoding nonzero value v */403/* Figure F.7: Encoding the sign of v */404if (v > 0) {405arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */406st += 2; /* Table F.4: SP = S0 + 2 */407entropy->dc_context[ci] = 4; /* small positive diff category */408} else {409v = -v;410arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */411st += 3; /* Table F.4: SN = S0 + 3 */412entropy->dc_context[ci] = 8; /* small negative diff category */413}414/* Figure F.8: Encoding the magnitude category of v */415m = 0;416if (v -= 1) {417arith_encode(cinfo, st, 1);418m = 1;419v2 = v;420st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */421while (v2 >>= 1) {422arith_encode(cinfo, st, 1);423m <<= 1;424st += 1;425}426}427arith_encode(cinfo, st, 0);428/* Section F.1.4.4.1.2: Establish dc_context conditioning category */429if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))430entropy->dc_context[ci] = 0; /* zero diff category */431else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))432entropy->dc_context[ci] += 8; /* large diff category */433/* Figure F.9: Encoding the magnitude bit pattern of v */434st += 14;435while (m >>= 1)436arith_encode(cinfo, st, (m & v) ? 1 : 0);437}438}439440return TRUE;441}442443444/*445* MCU encoding for AC initial scan (either spectral selection,446* or first pass of successive approximation).447*/448449METHODDEF(boolean)450encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)451{452arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;453const int * natural_order;454JBLOCKROW block;455unsigned char *st;456int tbl, k, ke;457int v, v2, m;458459/* Emit restart marker if needed */460if (cinfo->restart_interval) {461if (entropy->restarts_to_go == 0) {462emit_restart(cinfo, entropy->next_restart_num);463entropy->restarts_to_go = cinfo->restart_interval;464entropy->next_restart_num++;465entropy->next_restart_num &= 7;466}467entropy->restarts_to_go--;468}469470natural_order = cinfo->natural_order;471472/* Encode the MCU data block */473block = MCU_data[0];474tbl = cinfo->cur_comp_info[0]->ac_tbl_no;475476/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */477478/* Establish EOB (end-of-block) index */479ke = cinfo->Se;480do {481/* We must apply the point transform by Al. For AC coefficients this482* is an integer division with rounding towards 0. To do this portably483* in C, we shift after obtaining the absolute value.484*/485if ((v = (*block)[natural_order[ke]]) >= 0) {486if (v >>= cinfo->Al) break;487} else {488v = -v;489if (v >>= cinfo->Al) break;490}491} while (--ke);492493/* Figure F.5: Encode_AC_Coefficients */494for (k = cinfo->Ss - 1; k < ke;) {495st = entropy->ac_stats[tbl] + 3 * k;496arith_encode(cinfo, st, 0); /* EOB decision */497for (;;) {498if ((v = (*block)[natural_order[++k]]) >= 0) {499if (v >>= cinfo->Al) {500arith_encode(cinfo, st + 1, 1);501arith_encode(cinfo, entropy->fixed_bin, 0);502break;503}504} else {505v = -v;506if (v >>= cinfo->Al) {507arith_encode(cinfo, st + 1, 1);508arith_encode(cinfo, entropy->fixed_bin, 1);509break;510}511}512arith_encode(cinfo, st + 1, 0);513st += 3;514}515st += 2;516/* Figure F.8: Encoding the magnitude category of v */517m = 0;518if (v -= 1) {519arith_encode(cinfo, st, 1);520m = 1;521v2 = v;522if (v2 >>= 1) {523arith_encode(cinfo, st, 1);524m <<= 1;525st = entropy->ac_stats[tbl] +526(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);527while (v2 >>= 1) {528arith_encode(cinfo, st, 1);529m <<= 1;530st += 1;531}532}533}534arith_encode(cinfo, st, 0);535/* Figure F.9: Encoding the magnitude bit pattern of v */536st += 14;537while (m >>= 1)538arith_encode(cinfo, st, (m & v) ? 1 : 0);539}540/* Encode EOB decision only if k < cinfo->Se */541if (k < cinfo->Se) {542st = entropy->ac_stats[tbl] + 3 * k;543arith_encode(cinfo, st, 1);544}545546return TRUE;547}548549550/*551* MCU encoding for DC successive approximation refinement scan.552* Note: we assume such scans can be multi-component,553* although the spec is not very clear on the point.554*/555556METHODDEF(boolean)557encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)558{559arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;560unsigned char *st;561int Al, blkn;562563/* Emit restart marker if needed */564if (cinfo->restart_interval) {565if (entropy->restarts_to_go == 0) {566emit_restart(cinfo, entropy->next_restart_num);567entropy->restarts_to_go = cinfo->restart_interval;568entropy->next_restart_num++;569entropy->next_restart_num &= 7;570}571entropy->restarts_to_go--;572}573574st = entropy->fixed_bin; /* use fixed probability estimation */575Al = cinfo->Al;576577/* Encode the MCU data blocks */578for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {579/* We simply emit the Al'th bit of the DC coefficient value. */580arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);581}582583return TRUE;584}585586587/*588* MCU encoding for AC successive approximation refinement scan.589*/590591METHODDEF(boolean)592encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)593{594arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;595const int * natural_order;596JBLOCKROW block;597unsigned char *st;598int tbl, k, ke, kex;599int v;600601/* Emit restart marker if needed */602if (cinfo->restart_interval) {603if (entropy->restarts_to_go == 0) {604emit_restart(cinfo, entropy->next_restart_num);605entropy->restarts_to_go = cinfo->restart_interval;606entropy->next_restart_num++;607entropy->next_restart_num &= 7;608}609entropy->restarts_to_go--;610}611612natural_order = cinfo->natural_order;613614/* Encode the MCU data block */615block = MCU_data[0];616tbl = cinfo->cur_comp_info[0]->ac_tbl_no;617618/* Section G.1.3.3: Encoding of AC coefficients */619620/* Establish EOB (end-of-block) index */621ke = cinfo->Se;622do {623/* We must apply the point transform by Al. For AC coefficients this624* is an integer division with rounding towards 0. To do this portably625* in C, we shift after obtaining the absolute value.626*/627if ((v = (*block)[natural_order[ke]]) >= 0) {628if (v >>= cinfo->Al) break;629} else {630v = -v;631if (v >>= cinfo->Al) break;632}633} while (--ke);634635/* Establish EOBx (previous stage end-of-block) index */636for (kex = ke; kex > 0; kex--)637if ((v = (*block)[natural_order[kex]]) >= 0) {638if (v >>= cinfo->Ah) break;639} else {640v = -v;641if (v >>= cinfo->Ah) break;642}643644/* Figure G.10: Encode_AC_Coefficients_SA */645for (k = cinfo->Ss - 1; k < ke;) {646st = entropy->ac_stats[tbl] + 3 * k;647if (k >= kex)648arith_encode(cinfo, st, 0); /* EOB decision */649for (;;) {650if ((v = (*block)[natural_order[++k]]) >= 0) {651if (v >>= cinfo->Al) {652if (v >> 1) /* previously nonzero coef */653arith_encode(cinfo, st + 2, (v & 1));654else { /* newly nonzero coef */655arith_encode(cinfo, st + 1, 1);656arith_encode(cinfo, entropy->fixed_bin, 0);657}658break;659}660} else {661v = -v;662if (v >>= cinfo->Al) {663if (v >> 1) /* previously nonzero coef */664arith_encode(cinfo, st + 2, (v & 1));665else { /* newly nonzero coef */666arith_encode(cinfo, st + 1, 1);667arith_encode(cinfo, entropy->fixed_bin, 1);668}669break;670}671}672arith_encode(cinfo, st + 1, 0);673st += 3;674}675}676/* Encode EOB decision only if k < cinfo->Se */677if (k < cinfo->Se) {678st = entropy->ac_stats[tbl] + 3 * k;679arith_encode(cinfo, st, 1);680}681682return TRUE;683}684685686/*687* Encode and output one MCU's worth of arithmetic-compressed coefficients.688*/689690METHODDEF(boolean)691encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)692{693arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;694const int * natural_order;695JBLOCKROW block;696unsigned char *st;697int tbl, k, ke;698int v, v2, m;699int blkn, ci;700jpeg_component_info * compptr;701702/* Emit restart marker if needed */703if (cinfo->restart_interval) {704if (entropy->restarts_to_go == 0) {705emit_restart(cinfo, entropy->next_restart_num);706entropy->restarts_to_go = cinfo->restart_interval;707entropy->next_restart_num++;708entropy->next_restart_num &= 7;709}710entropy->restarts_to_go--;711}712713natural_order = cinfo->natural_order;714715/* Encode the MCU data blocks */716for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {717block = MCU_data[blkn];718ci = cinfo->MCU_membership[blkn];719compptr = cinfo->cur_comp_info[ci];720721/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */722723tbl = compptr->dc_tbl_no;724725/* Table F.4: Point to statistics bin S0 for DC coefficient coding */726st = entropy->dc_stats[tbl] + entropy->dc_context[ci];727728/* Figure F.4: Encode_DC_DIFF */729if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {730arith_encode(cinfo, st, 0);731entropy->dc_context[ci] = 0; /* zero diff category */732} else {733entropy->last_dc_val[ci] = (*block)[0];734arith_encode(cinfo, st, 1);735/* Figure F.6: Encoding nonzero value v */736/* Figure F.7: Encoding the sign of v */737if (v > 0) {738arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */739st += 2; /* Table F.4: SP = S0 + 2 */740entropy->dc_context[ci] = 4; /* small positive diff category */741} else {742v = -v;743arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */744st += 3; /* Table F.4: SN = S0 + 3 */745entropy->dc_context[ci] = 8; /* small negative diff category */746}747/* Figure F.8: Encoding the magnitude category of v */748m = 0;749if (v -= 1) {750arith_encode(cinfo, st, 1);751m = 1;752v2 = v;753st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */754while (v2 >>= 1) {755arith_encode(cinfo, st, 1);756m <<= 1;757st += 1;758}759}760arith_encode(cinfo, st, 0);761/* Section F.1.4.4.1.2: Establish dc_context conditioning category */762if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))763entropy->dc_context[ci] = 0; /* zero diff category */764else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))765entropy->dc_context[ci] += 8; /* large diff category */766/* Figure F.9: Encoding the magnitude bit pattern of v */767st += 14;768while (m >>= 1)769arith_encode(cinfo, st, (m & v) ? 1 : 0);770}771772/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */773774if ((ke = cinfo->lim_Se) == 0) continue;775tbl = compptr->ac_tbl_no;776777/* Establish EOB (end-of-block) index */778do {779if ((*block)[natural_order[ke]]) break;780} while (--ke);781782/* Figure F.5: Encode_AC_Coefficients */783for (k = 0; k < ke;) {784st = entropy->ac_stats[tbl] + 3 * k;785arith_encode(cinfo, st, 0); /* EOB decision */786while ((v = (*block)[natural_order[++k]]) == 0) {787arith_encode(cinfo, st + 1, 0);788st += 3;789}790arith_encode(cinfo, st + 1, 1);791/* Figure F.6: Encoding nonzero value v */792/* Figure F.7: Encoding the sign of v */793if (v > 0) {794arith_encode(cinfo, entropy->fixed_bin, 0);795} else {796v = -v;797arith_encode(cinfo, entropy->fixed_bin, 1);798}799st += 2;800/* Figure F.8: Encoding the magnitude category of v */801m = 0;802if (v -= 1) {803arith_encode(cinfo, st, 1);804m = 1;805v2 = v;806if (v2 >>= 1) {807arith_encode(cinfo, st, 1);808m <<= 1;809st = entropy->ac_stats[tbl] +810(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);811while (v2 >>= 1) {812arith_encode(cinfo, st, 1);813m <<= 1;814st += 1;815}816}817}818arith_encode(cinfo, st, 0);819/* Figure F.9: Encoding the magnitude bit pattern of v */820st += 14;821while (m >>= 1)822arith_encode(cinfo, st, (m & v) ? 1 : 0);823}824/* Encode EOB decision only if k < cinfo->lim_Se */825if (k < cinfo->lim_Se) {826st = entropy->ac_stats[tbl] + 3 * k;827arith_encode(cinfo, st, 1);828}829}830831return TRUE;832}833834835/*836* Initialize for an arithmetic-compressed scan.837*/838839METHODDEF(void)840start_pass (j_compress_ptr cinfo, boolean gather_statistics)841{842arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;843int ci, tbl;844jpeg_component_info * compptr;845846if (gather_statistics)847/* Make sure to avoid that in the master control logic!848* We are fully adaptive here and need no extra849* statistics gathering pass!850*/851ERREXIT(cinfo, JERR_NOT_COMPILED);852853/* We assume jcmaster.c already validated the progressive scan parameters. */854855/* Select execution routines */856if (cinfo->progressive_mode) {857if (cinfo->Ah == 0) {858if (cinfo->Ss == 0)859entropy->pub.encode_mcu = encode_mcu_DC_first;860else861entropy->pub.encode_mcu = encode_mcu_AC_first;862} else {863if (cinfo->Ss == 0)864entropy->pub.encode_mcu = encode_mcu_DC_refine;865else866entropy->pub.encode_mcu = encode_mcu_AC_refine;867}868} else869entropy->pub.encode_mcu = encode_mcu;870871/* Allocate & initialize requested statistics areas */872for (ci = 0; ci < cinfo->comps_in_scan; ci++) {873compptr = cinfo->cur_comp_info[ci];874/* DC needs no table for refinement scan */875if (cinfo->Ss == 0 && cinfo->Ah == 0) {876tbl = compptr->dc_tbl_no;877if (tbl < 0 || tbl >= NUM_ARITH_TBLS)878ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);879if (entropy->dc_stats[tbl] == NULL)880entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)881((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);882MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);883/* Initialize DC predictions to 0 */884entropy->last_dc_val[ci] = 0;885entropy->dc_context[ci] = 0;886}887/* AC needs no table when not present */888if (cinfo->Se) {889tbl = compptr->ac_tbl_no;890if (tbl < 0 || tbl >= NUM_ARITH_TBLS)891ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);892if (entropy->ac_stats[tbl] == NULL)893entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)894((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);895MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);896#ifdef CALCULATE_SPECTRAL_CONDITIONING897if (cinfo->progressive_mode)898/* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */899cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);900#endif901}902}903904/* Initialize arithmetic encoding variables */905entropy->c = 0;906entropy->a = 0x10000L;907entropy->sc = 0;908entropy->zc = 0;909entropy->ct = 11;910entropy->buffer = -1; /* empty */911912/* Initialize restart stuff */913entropy->restarts_to_go = cinfo->restart_interval;914entropy->next_restart_num = 0;915}916917918/*919* Module initialization routine for arithmetic entropy encoding.920*/921922GLOBAL(void)923jinit_arith_encoder (j_compress_ptr cinfo)924{925arith_entropy_ptr entropy;926int i;927928entropy = (arith_entropy_ptr)929(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,930SIZEOF(arith_entropy_encoder));931cinfo->entropy = &entropy->pub;932entropy->pub.start_pass = start_pass;933entropy->pub.finish_pass = finish_pass;934935/* Mark tables unallocated */936for (i = 0; i < NUM_ARITH_TBLS; i++) {937entropy->dc_stats[i] = NULL;938entropy->ac_stats[i] = NULL;939}940941/* Initialize index for fixed probability estimation */942entropy->fixed_bin[0] = 113;943}944945946