Path: blob/master/thirdparty/libjpeg-turbo/src/jcarith.c
9904 views
/*1* jcarith.c2*3* This file was part of the Independent JPEG Group's software:4* Developed 1997-2009 by Guido Vollbeding.5* libjpeg-turbo Modifications:6* Copyright (C) 2015, 2018, 2021-2022, D. R. Commander.7* For conditions of distribution and use, see the accompanying README.ijg8* file.9*10* This file contains portable arithmetic entropy encoding routines for JPEG11* (implementing Recommendation ITU-T T.81 | ISO/IEC 10918-1).12*13* Both sequential and progressive modes are supported in this single module.14*15* Suspension is not currently supported in this module.16*17* NOTE: All referenced figures are from18* Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.19*/2021#define JPEG_INTERNALS22#include "jinclude.h"23#include "jpeglib.h"242526/* Expanded entropy encoder object for arithmetic encoding. */2728typedef struct {29struct jpeg_entropy_encoder pub; /* public fields */3031JLONG c; /* C register, base of coding interval, layout as in sec. D.1.3 */32JLONG a; /* A register, normalized size of coding interval */33JLONG sc; /* counter for stacked 0xFF values which might overflow */34JLONG zc; /* counter for pending 0x00 output values which might *35* be discarded at the end ("Pacman" termination) */36int ct; /* bit shift counter, determines when next byte will be written */37int buffer; /* buffer for most recent output byte != 0xFF */3839int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */40int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */4142unsigned int restarts_to_go; /* MCUs left in this restart interval */43int next_restart_num; /* next restart number to write (0-7) */4445/* Pointers to statistics areas (these workspaces have image lifespan) */46unsigned char *dc_stats[NUM_ARITH_TBLS];47unsigned char *ac_stats[NUM_ARITH_TBLS];4849/* Statistics bin for coding with fixed probability 0.5 */50unsigned char fixed_bin[4];51} arith_entropy_encoder;5253typedef arith_entropy_encoder *arith_entropy_ptr;5455/* The following two definitions specify the allocation chunk size56* for the statistics area.57* According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least58* 49 statistics bins for DC, and 245 statistics bins for AC coding.59*60* We use a compact representation with 1 byte per statistics bin,61* thus the numbers directly represent byte sizes.62* This 1 byte per statistics bin contains the meaning of the MPS63* (more probable symbol) in the highest bit (mask 0x80), and the64* index into the probability estimation state machine table65* in the lower bits (mask 0x7F).66*/6768#define DC_STAT_BINS 6469#define AC_STAT_BINS 2567071/* NOTE: Uncomment the following #define if you want to use the72* given formula for calculating the AC conditioning parameter Kx73* for spectral selection progressive coding in section G.1.3.274* of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4).75* Although the spec and P&M authors claim that this "has proven76* to give good results for 8 bit precision samples", I'm not77* convinced yet that this is really beneficial.78* Early tests gave only very marginal compression enhancements79* (a few - around 5 or so - bytes even for very large files),80* which would turn out rather negative if we'd suppress the81* DAC (Define Arithmetic Conditioning) marker segments for82* the default parameters in the future.83* Note that currently the marker writing module emits 12-byte84* DAC segments for a full-component scan in a color image.85* This is not worth worrying about IMHO. However, since the86* spec defines the default values to be used if the tables87* are omitted (unlike Huffman tables, which are required88* anyway), one might optimize this behaviour in the future,89* and then it would be disadvantageous to use custom tables if90* they don't provide sufficient gain to exceed the DAC size.91*92* On the other hand, I'd consider it as a reasonable result93* that the conditioning has no significant influence on the94* compression performance. This means that the basic95* statistical model is already rather stable.96*97* Thus, at the moment, we use the default conditioning values98* anyway, and do not use the custom formula.99*100#define CALCULATE_SPECTRAL_CONDITIONING101*/102103/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than JLONG.104* We assume that int right shift is unsigned if JLONG right shift is,105* which should be safe.106*/107108#ifdef RIGHT_SHIFT_IS_UNSIGNED109#define ISHIFT_TEMPS int ishift_temp;110#define IRIGHT_SHIFT(x, shft) \111((ishift_temp = (x)) < 0 ? \112(ishift_temp >> (shft)) | ((~0) << (16 - (shft))) : \113(ishift_temp >> (shft)))114#else115#define ISHIFT_TEMPS116#define IRIGHT_SHIFT(x, shft) ((x) >> (shft))117#endif118119120LOCAL(void)121emit_byte(int val, j_compress_ptr cinfo)122/* Write next output byte; we do not support suspension in this module. */123{124struct jpeg_destination_mgr *dest = cinfo->dest;125126*dest->next_output_byte++ = (JOCTET)val;127if (--dest->free_in_buffer == 0)128if (!(*dest->empty_output_buffer) (cinfo))129ERREXIT(cinfo, JERR_CANT_SUSPEND);130}131132133/*134* Finish up at the end of an arithmetic-compressed scan.135*/136137METHODDEF(void)138finish_pass(j_compress_ptr cinfo)139{140arith_entropy_ptr e = (arith_entropy_ptr)cinfo->entropy;141JLONG temp;142143/* Section D.1.8: Termination of encoding */144145/* Find the e->c in the coding interval with the largest146* number of trailing zero bits */147if ((temp = (e->a - 1 + e->c) & 0xFFFF0000UL) < e->c)148e->c = temp + 0x8000L;149else150e->c = temp;151/* Send remaining bytes to output */152e->c <<= e->ct;153if (e->c & 0xF8000000UL) {154/* One final overflow has to be handled */155if (e->buffer >= 0) {156if (e->zc)157do emit_byte(0x00, cinfo);158while (--e->zc);159emit_byte(e->buffer + 1, cinfo);160if (e->buffer + 1 == 0xFF)161emit_byte(0x00, cinfo);162}163e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */164e->sc = 0;165} else {166if (e->buffer == 0)167++e->zc;168else if (e->buffer >= 0) {169if (e->zc)170do emit_byte(0x00, cinfo);171while (--e->zc);172emit_byte(e->buffer, cinfo);173}174if (e->sc) {175if (e->zc)176do emit_byte(0x00, cinfo);177while (--e->zc);178do {179emit_byte(0xFF, cinfo);180emit_byte(0x00, cinfo);181} while (--e->sc);182}183}184/* Output final bytes only if they are not 0x00 */185if (e->c & 0x7FFF800L) {186if (e->zc) /* output final pending zero bytes */187do emit_byte(0x00, cinfo);188while (--e->zc);189emit_byte((e->c >> 19) & 0xFF, cinfo);190if (((e->c >> 19) & 0xFF) == 0xFF)191emit_byte(0x00, cinfo);192if (e->c & 0x7F800L) {193emit_byte((e->c >> 11) & 0xFF, cinfo);194if (((e->c >> 11) & 0xFF) == 0xFF)195emit_byte(0x00, cinfo);196}197}198}199200201/*202* The core arithmetic encoding routine (common in JPEG and JBIG).203* This needs to go as fast as possible.204* Machine-dependent optimization facilities205* are not utilized in this portable implementation.206* However, this code should be fairly efficient and207* may be a good base for further optimizations anyway.208*209* Parameter 'val' to be encoded may be 0 or 1 (binary decision).210*211* Note: I've added full "Pacman" termination support to the212* byte output routines, which is equivalent to the optional213* Discard_final_zeros procedure (Figure D.15) in the spec.214* Thus, we always produce the shortest possible output215* stream compliant to the spec (no trailing zero bytes,216* except for FF stuffing).217*218* I've also introduced a new scheme for accessing219* the probability estimation state machine table,220* derived from Markus Kuhn's JBIG implementation.221*/222223LOCAL(void)224arith_encode(j_compress_ptr cinfo, unsigned char *st, int val)225{226register arith_entropy_ptr e = (arith_entropy_ptr)cinfo->entropy;227register unsigned char nl, nm;228register JLONG qe, temp;229register int sv;230231/* Fetch values from our compact representation of Table D.2:232* Qe values and probability estimation state machine233*/234sv = *st;235qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */236nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */237nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */238239/* Encode & estimation procedures per sections D.1.4 & D.1.5 */240e->a -= qe;241if (val != (sv >> 7)) {242/* Encode the less probable symbol */243if (e->a >= qe) {244/* If the interval size (qe) for the less probable symbol (LPS)245* is larger than the interval size for the MPS, then exchange246* the two symbols for coding efficiency, otherwise code the LPS247* as usual: */248e->c += e->a;249e->a = qe;250}251*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */252} else {253/* Encode the more probable symbol */254if (e->a >= 0x8000L)255return; /* A >= 0x8000 -> ready, no renormalization required */256if (e->a < qe) {257/* If the interval size (qe) for the less probable symbol (LPS)258* is larger than the interval size for the MPS, then exchange259* the two symbols for coding efficiency: */260e->c += e->a;261e->a = qe;262}263*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */264}265266/* Renormalization & data output per section D.1.6 */267do {268e->a <<= 1;269e->c <<= 1;270if (--e->ct == 0) {271/* Another byte is ready for output */272temp = e->c >> 19;273if (temp > 0xFF) {274/* Handle overflow over all stacked 0xFF bytes */275if (e->buffer >= 0) {276if (e->zc)277do emit_byte(0x00, cinfo);278while (--e->zc);279emit_byte(e->buffer + 1, cinfo);280if (e->buffer + 1 == 0xFF)281emit_byte(0x00, cinfo);282}283e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */284e->sc = 0;285/* Note: The 3 spacer bits in the C register guarantee286* that the new buffer byte can't be 0xFF here287* (see page 160 in the P&M JPEG book). */288e->buffer = temp & 0xFF; /* new output byte, might overflow later */289} else if (temp == 0xFF) {290++e->sc; /* stack 0xFF byte (which might overflow later) */291} else {292/* Output all stacked 0xFF bytes, they will not overflow any more */293if (e->buffer == 0)294++e->zc;295else if (e->buffer >= 0) {296if (e->zc)297do emit_byte(0x00, cinfo);298while (--e->zc);299emit_byte(e->buffer, cinfo);300}301if (e->sc) {302if (e->zc)303do emit_byte(0x00, cinfo);304while (--e->zc);305do {306emit_byte(0xFF, cinfo);307emit_byte(0x00, cinfo);308} while (--e->sc);309}310e->buffer = temp & 0xFF; /* new output byte (can still overflow) */311}312e->c &= 0x7FFFFL;313e->ct += 8;314}315} while (e->a < 0x8000L);316}317318319/*320* Emit a restart marker & resynchronize predictions.321*/322323LOCAL(void)324emit_restart(j_compress_ptr cinfo, int restart_num)325{326arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;327int ci;328jpeg_component_info *compptr;329330finish_pass(cinfo);331332emit_byte(0xFF, cinfo);333emit_byte(JPEG_RST0 + restart_num, cinfo);334335/* Re-initialize statistics areas */336for (ci = 0; ci < cinfo->comps_in_scan; ci++) {337compptr = cinfo->cur_comp_info[ci];338/* DC needs no table for refinement scan */339if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {340memset(entropy->dc_stats[compptr->dc_tbl_no], 0, DC_STAT_BINS);341/* Reset DC predictions to 0 */342entropy->last_dc_val[ci] = 0;343entropy->dc_context[ci] = 0;344}345/* AC needs no table when not present */346if (cinfo->progressive_mode == 0 || cinfo->Se) {347memset(entropy->ac_stats[compptr->ac_tbl_no], 0, AC_STAT_BINS);348}349}350351/* Reset arithmetic encoding variables */352entropy->c = 0;353entropy->a = 0x10000L;354entropy->sc = 0;355entropy->zc = 0;356entropy->ct = 11;357entropy->buffer = -1; /* empty */358}359360361/*362* MCU encoding for DC initial scan (either spectral selection,363* or first pass of successive approximation).364*/365366METHODDEF(boolean)367encode_mcu_DC_first(j_compress_ptr cinfo, JBLOCKROW *MCU_data)368{369arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;370JBLOCKROW block;371unsigned char *st;372int blkn, ci, tbl;373int v, v2, m;374ISHIFT_TEMPS375376/* Emit restart marker if needed */377if (cinfo->restart_interval) {378if (entropy->restarts_to_go == 0) {379emit_restart(cinfo, entropy->next_restart_num);380entropy->restarts_to_go = cinfo->restart_interval;381entropy->next_restart_num++;382entropy->next_restart_num &= 7;383}384entropy->restarts_to_go--;385}386387/* Encode the MCU data blocks */388for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {389block = MCU_data[blkn];390ci = cinfo->MCU_membership[blkn];391tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;392393/* Compute the DC value after the required point transform by Al.394* This is simply an arithmetic right shift.395*/396m = IRIGHT_SHIFT((int)((*block)[0]), cinfo->Al);397398/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */399400/* Table F.4: Point to statistics bin S0 for DC coefficient coding */401st = entropy->dc_stats[tbl] + entropy->dc_context[ci];402403/* Figure F.4: Encode_DC_DIFF */404if ((v = m - entropy->last_dc_val[ci]) == 0) {405arith_encode(cinfo, st, 0);406entropy->dc_context[ci] = 0; /* zero diff category */407} else {408entropy->last_dc_val[ci] = m;409arith_encode(cinfo, st, 1);410/* Figure F.6: Encoding nonzero value v */411/* Figure F.7: Encoding the sign of v */412if (v > 0) {413arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */414st += 2; /* Table F.4: SP = S0 + 2 */415entropy->dc_context[ci] = 4; /* small positive diff category */416} else {417v = -v;418arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */419st += 3; /* Table F.4: SN = S0 + 3 */420entropy->dc_context[ci] = 8; /* small negative diff category */421}422/* Figure F.8: Encoding the magnitude category of v */423m = 0;424if (v -= 1) {425arith_encode(cinfo, st, 1);426m = 1;427v2 = v;428st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */429while (v2 >>= 1) {430arith_encode(cinfo, st, 1);431m <<= 1;432st += 1;433}434}435arith_encode(cinfo, st, 0);436/* Section F.1.4.4.1.2: Establish dc_context conditioning category */437if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))438entropy->dc_context[ci] = 0; /* zero diff category */439else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))440entropy->dc_context[ci] += 8; /* large diff category */441/* Figure F.9: Encoding the magnitude bit pattern of v */442st += 14;443while (m >>= 1)444arith_encode(cinfo, st, (m & v) ? 1 : 0);445}446}447448return TRUE;449}450451452/*453* MCU encoding for AC initial scan (either spectral selection,454* or first pass of successive approximation).455*/456457METHODDEF(boolean)458encode_mcu_AC_first(j_compress_ptr cinfo, JBLOCKROW *MCU_data)459{460arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;461JBLOCKROW block;462unsigned char *st;463int tbl, k, ke;464int v, v2, m;465466/* Emit restart marker if needed */467if (cinfo->restart_interval) {468if (entropy->restarts_to_go == 0) {469emit_restart(cinfo, entropy->next_restart_num);470entropy->restarts_to_go = cinfo->restart_interval;471entropy->next_restart_num++;472entropy->next_restart_num &= 7;473}474entropy->restarts_to_go--;475}476477/* Encode the MCU data block */478block = MCU_data[0];479tbl = cinfo->cur_comp_info[0]->ac_tbl_no;480481/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */482483/* Establish EOB (end-of-block) index */484for (ke = cinfo->Se; ke > 0; ke--)485/* We must apply the point transform by Al. For AC coefficients this486* is an integer division with rounding towards 0. To do this portably487* in C, we shift after obtaining the absolute value.488*/489if ((v = (*block)[jpeg_natural_order[ke]]) >= 0) {490if (v >>= cinfo->Al) break;491} else {492v = -v;493if (v >>= cinfo->Al) break;494}495496/* Figure F.5: Encode_AC_Coefficients */497for (k = cinfo->Ss; k <= ke; k++) {498st = entropy->ac_stats[tbl] + 3 * (k - 1);499arith_encode(cinfo, st, 0); /* EOB decision */500for (;;) {501if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {502if (v >>= cinfo->Al) {503arith_encode(cinfo, st + 1, 1);504arith_encode(cinfo, entropy->fixed_bin, 0);505break;506}507} else {508v = -v;509if (v >>= cinfo->Al) {510arith_encode(cinfo, st + 1, 1);511arith_encode(cinfo, entropy->fixed_bin, 1);512break;513}514}515arith_encode(cinfo, st + 1, 0); st += 3; k++;516}517st += 2;518/* Figure F.8: Encoding the magnitude category of v */519m = 0;520if (v -= 1) {521arith_encode(cinfo, st, 1);522m = 1;523v2 = v;524if (v2 >>= 1) {525arith_encode(cinfo, st, 1);526m <<= 1;527st = entropy->ac_stats[tbl] +528(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);529while (v2 >>= 1) {530arith_encode(cinfo, st, 1);531m <<= 1;532st += 1;533}534}535}536arith_encode(cinfo, st, 0);537/* Figure F.9: Encoding the magnitude bit pattern of v */538st += 14;539while (m >>= 1)540arith_encode(cinfo, st, (m & v) ? 1 : 0);541}542/* Encode EOB decision only if k <= cinfo->Se */543if (k <= cinfo->Se) {544st = entropy->ac_stats[tbl] + 3 * (k - 1);545arith_encode(cinfo, st, 1);546}547548return TRUE;549}550551552/*553* MCU encoding for DC successive approximation refinement scan.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;595JBLOCKROW block;596unsigned char *st;597int tbl, k, ke, kex;598int v;599600/* Emit restart marker if needed */601if (cinfo->restart_interval) {602if (entropy->restarts_to_go == 0) {603emit_restart(cinfo, entropy->next_restart_num);604entropy->restarts_to_go = cinfo->restart_interval;605entropy->next_restart_num++;606entropy->next_restart_num &= 7;607}608entropy->restarts_to_go--;609}610611/* Encode the MCU data block */612block = MCU_data[0];613tbl = cinfo->cur_comp_info[0]->ac_tbl_no;614615/* Section G.1.3.3: Encoding of AC coefficients */616617/* Establish EOB (end-of-block) index */618for (ke = cinfo->Se; ke > 0; ke--)619/* We must apply the point transform by Al. For AC coefficients this620* is an integer division with rounding towards 0. To do this portably621* in C, we shift after obtaining the absolute value.622*/623if ((v = (*block)[jpeg_natural_order[ke]]) >= 0) {624if (v >>= cinfo->Al) break;625} else {626v = -v;627if (v >>= cinfo->Al) break;628}629630/* Establish EOBx (previous stage end-of-block) index */631for (kex = ke; kex > 0; kex--)632if ((v = (*block)[jpeg_natural_order[kex]]) >= 0) {633if (v >>= cinfo->Ah) break;634} else {635v = -v;636if (v >>= cinfo->Ah) break;637}638639/* Figure G.10: Encode_AC_Coefficients_SA */640for (k = cinfo->Ss; k <= ke; k++) {641st = entropy->ac_stats[tbl] + 3 * (k - 1);642if (k > kex)643arith_encode(cinfo, st, 0); /* EOB decision */644for (;;) {645if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {646if (v >>= cinfo->Al) {647if (v >> 1) /* previously nonzero coef */648arith_encode(cinfo, st + 2, (v & 1));649else { /* newly nonzero coef */650arith_encode(cinfo, st + 1, 1);651arith_encode(cinfo, entropy->fixed_bin, 0);652}653break;654}655} else {656v = -v;657if (v >>= cinfo->Al) {658if (v >> 1) /* previously nonzero coef */659arith_encode(cinfo, st + 2, (v & 1));660else { /* newly nonzero coef */661arith_encode(cinfo, st + 1, 1);662arith_encode(cinfo, entropy->fixed_bin, 1);663}664break;665}666}667arith_encode(cinfo, st + 1, 0); st += 3; k++;668}669}670/* Encode EOB decision only if k <= cinfo->Se */671if (k <= cinfo->Se) {672st = entropy->ac_stats[tbl] + 3 * (k - 1);673arith_encode(cinfo, st, 1);674}675676return TRUE;677}678679680/*681* Encode and output one MCU's worth of arithmetic-compressed coefficients.682*/683684METHODDEF(boolean)685encode_mcu(j_compress_ptr cinfo, JBLOCKROW *MCU_data)686{687arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;688jpeg_component_info *compptr;689JBLOCKROW block;690unsigned char *st;691int blkn, ci, tbl, k, ke;692int v, v2, m;693694/* Emit restart marker if needed */695if (cinfo->restart_interval) {696if (entropy->restarts_to_go == 0) {697emit_restart(cinfo, entropy->next_restart_num);698entropy->restarts_to_go = cinfo->restart_interval;699entropy->next_restart_num++;700entropy->next_restart_num &= 7;701}702entropy->restarts_to_go--;703}704705/* Encode the MCU data blocks */706for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {707block = MCU_data[blkn];708ci = cinfo->MCU_membership[blkn];709compptr = cinfo->cur_comp_info[ci];710711/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */712713tbl = compptr->dc_tbl_no;714715/* Table F.4: Point to statistics bin S0 for DC coefficient coding */716st = entropy->dc_stats[tbl] + entropy->dc_context[ci];717718/* Figure F.4: Encode_DC_DIFF */719if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {720arith_encode(cinfo, st, 0);721entropy->dc_context[ci] = 0; /* zero diff category */722} else {723entropy->last_dc_val[ci] = (*block)[0];724arith_encode(cinfo, st, 1);725/* Figure F.6: Encoding nonzero value v */726/* Figure F.7: Encoding the sign of v */727if (v > 0) {728arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */729st += 2; /* Table F.4: SP = S0 + 2 */730entropy->dc_context[ci] = 4; /* small positive diff category */731} else {732v = -v;733arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */734st += 3; /* Table F.4: SN = S0 + 3 */735entropy->dc_context[ci] = 8; /* small negative diff category */736}737/* Figure F.8: Encoding the magnitude category of v */738m = 0;739if (v -= 1) {740arith_encode(cinfo, st, 1);741m = 1;742v2 = v;743st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */744while (v2 >>= 1) {745arith_encode(cinfo, st, 1);746m <<= 1;747st += 1;748}749}750arith_encode(cinfo, st, 0);751/* Section F.1.4.4.1.2: Establish dc_context conditioning category */752if (m < (int)((1L << cinfo->arith_dc_L[tbl]) >> 1))753entropy->dc_context[ci] = 0; /* zero diff category */754else if (m > (int)((1L << cinfo->arith_dc_U[tbl]) >> 1))755entropy->dc_context[ci] += 8; /* large diff category */756/* Figure F.9: Encoding the magnitude bit pattern of v */757st += 14;758while (m >>= 1)759arith_encode(cinfo, st, (m & v) ? 1 : 0);760}761762/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */763764tbl = compptr->ac_tbl_no;765766/* Establish EOB (end-of-block) index */767for (ke = DCTSIZE2 - 1; ke > 0; ke--)768if ((*block)[jpeg_natural_order[ke]]) break;769770/* Figure F.5: Encode_AC_Coefficients */771for (k = 1; k <= ke; k++) {772st = entropy->ac_stats[tbl] + 3 * (k - 1);773arith_encode(cinfo, st, 0); /* EOB decision */774while ((v = (*block)[jpeg_natural_order[k]]) == 0) {775arith_encode(cinfo, st + 1, 0); st += 3; k++;776}777arith_encode(cinfo, st + 1, 1);778/* Figure F.6: Encoding nonzero value v */779/* Figure F.7: Encoding the sign of v */780if (v > 0) {781arith_encode(cinfo, entropy->fixed_bin, 0);782} else {783v = -v;784arith_encode(cinfo, entropy->fixed_bin, 1);785}786st += 2;787/* Figure F.8: Encoding the magnitude category of v */788m = 0;789if (v -= 1) {790arith_encode(cinfo, st, 1);791m = 1;792v2 = v;793if (v2 >>= 1) {794arith_encode(cinfo, st, 1);795m <<= 1;796st = entropy->ac_stats[tbl] +797(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);798while (v2 >>= 1) {799arith_encode(cinfo, st, 1);800m <<= 1;801st += 1;802}803}804}805arith_encode(cinfo, st, 0);806/* Figure F.9: Encoding the magnitude bit pattern of v */807st += 14;808while (m >>= 1)809arith_encode(cinfo, st, (m & v) ? 1 : 0);810}811/* Encode EOB decision only if k <= DCTSIZE2 - 1 */812if (k <= DCTSIZE2 - 1) {813st = entropy->ac_stats[tbl] + 3 * (k - 1);814arith_encode(cinfo, st, 1);815}816}817818return TRUE;819}820821822/*823* Initialize for an arithmetic-compressed scan.824*/825826METHODDEF(void)827start_pass(j_compress_ptr cinfo, boolean gather_statistics)828{829arith_entropy_ptr entropy = (arith_entropy_ptr)cinfo->entropy;830int ci, tbl;831jpeg_component_info *compptr;832833if (gather_statistics)834/* Make sure to avoid that in the master control logic!835* We are fully adaptive here and need no extra836* statistics gathering pass!837*/838ERREXIT(cinfo, JERR_NOTIMPL);839840/* We assume jcmaster.c already validated the progressive scan parameters. */841842/* Select execution routines */843if (cinfo->progressive_mode) {844if (cinfo->Ah == 0) {845if (cinfo->Ss == 0)846entropy->pub.encode_mcu = encode_mcu_DC_first;847else848entropy->pub.encode_mcu = encode_mcu_AC_first;849} else {850if (cinfo->Ss == 0)851entropy->pub.encode_mcu = encode_mcu_DC_refine;852else853entropy->pub.encode_mcu = encode_mcu_AC_refine;854}855} else856entropy->pub.encode_mcu = encode_mcu;857858/* Allocate & initialize requested statistics areas */859for (ci = 0; ci < cinfo->comps_in_scan; ci++) {860compptr = cinfo->cur_comp_info[ci];861/* DC needs no table for refinement scan */862if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {863tbl = compptr->dc_tbl_no;864if (tbl < 0 || tbl >= NUM_ARITH_TBLS)865ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);866if (entropy->dc_stats[tbl] == NULL)867entropy->dc_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)868((j_common_ptr)cinfo, JPOOL_IMAGE, DC_STAT_BINS);869memset(entropy->dc_stats[tbl], 0, DC_STAT_BINS);870/* Initialize DC predictions to 0 */871entropy->last_dc_val[ci] = 0;872entropy->dc_context[ci] = 0;873}874/* AC needs no table when not present */875if (cinfo->progressive_mode == 0 || cinfo->Se) {876tbl = compptr->ac_tbl_no;877if (tbl < 0 || tbl >= NUM_ARITH_TBLS)878ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);879if (entropy->ac_stats[tbl] == NULL)880entropy->ac_stats[tbl] = (unsigned char *)(*cinfo->mem->alloc_small)881((j_common_ptr)cinfo, JPOOL_IMAGE, AC_STAT_BINS);882memset(entropy->ac_stats[tbl], 0, AC_STAT_BINS);883#ifdef CALCULATE_SPECTRAL_CONDITIONING884if (cinfo->progressive_mode)885/* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */886cinfo->arith_ac_K[tbl] = cinfo->Ss +887((8 + cinfo->Se - cinfo->Ss) >> 4);888#endif889}890}891892/* Initialize arithmetic encoding variables */893entropy->c = 0;894entropy->a = 0x10000L;895entropy->sc = 0;896entropy->zc = 0;897entropy->ct = 11;898entropy->buffer = -1; /* empty */899900/* Initialize restart stuff */901entropy->restarts_to_go = cinfo->restart_interval;902entropy->next_restart_num = 0;903}904905906/*907* Module initialization routine for arithmetic entropy encoding.908*/909910GLOBAL(void)911jinit_arith_encoder(j_compress_ptr cinfo)912{913arith_entropy_ptr entropy;914int i;915916entropy = (arith_entropy_ptr)917(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,918sizeof(arith_entropy_encoder));919cinfo->entropy = (struct jpeg_entropy_encoder *)entropy;920entropy->pub.start_pass = start_pass;921entropy->pub.finish_pass = finish_pass;922923/* Mark tables unallocated */924for (i = 0; i < NUM_ARITH_TBLS; i++) {925entropy->dc_stats[i] = NULL;926entropy->ac_stats[i] = NULL;927}928929/* Initialize index for fixed probability estimation */930entropy->fixed_bin[0] = 113;931}932933934