/*1* jcarith.c2*3* Developed 1997-2020 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((int) ((e->c >> 19) & 0xFF), cinfo);184if (((e->c >> 19) & 0xFF) == 0xFF)185emit_byte(0x00, cinfo);186if (e->c & 0x7F800L) {187emit_byte((int) ((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). */282/* New output byte, might overflow later */283e->buffer = (int) (temp & 0xFF);284} else if (temp == 0xFF) {285++e->sc; /* stack 0xFF byte (which might overflow later) */286} else {287/* Output all stacked 0xFF bytes, they will not overflow any more */288if (e->buffer == 0)289++e->zc;290else if (e->buffer >= 0) {291if (e->zc)292do emit_byte(0x00, cinfo);293while (--e->zc);294emit_byte(e->buffer, cinfo);295}296if (e->sc) {297if (e->zc)298do emit_byte(0x00, cinfo);299while (--e->zc);300do {301emit_byte(0xFF, cinfo);302emit_byte(0x00, cinfo);303} while (--e->sc);304}305/* New output byte (can still overflow) */306e->buffer = (int) (temp & 0xFF);307}308e->c &= 0x7FFFFL;309e->ct += 8;310}311} while (e->a < 0x8000L);312}313314315/*316* Emit a restart marker & resynchronize predictions.317*/318319LOCAL(void)320emit_restart (j_compress_ptr cinfo, int restart_num)321{322arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;323int ci;324jpeg_component_info * compptr;325326finish_pass(cinfo);327328emit_byte(0xFF, cinfo);329emit_byte(JPEG_RST0 + restart_num, cinfo);330331/* Re-initialize statistics areas */332for (ci = 0; ci < cinfo->comps_in_scan; ci++) {333compptr = cinfo->cur_comp_info[ci];334/* DC needs no table for refinement scan */335if (cinfo->Ss == 0 && cinfo->Ah == 0) {336MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);337/* Reset DC predictions to 0 */338entropy->last_dc_val[ci] = 0;339entropy->dc_context[ci] = 0;340}341/* AC needs no table when not present */342if (cinfo->Se) {343MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);344}345}346347/* Reset arithmetic encoding variables */348entropy->c = 0;349entropy->a = 0x10000L;350entropy->sc = 0;351entropy->zc = 0;352entropy->ct = 11;353entropy->buffer = -1; /* empty */354}355356357/*358* MCU encoding for DC initial scan (either spectral selection,359* or first pass of successive approximation).360*/361362METHODDEF(boolean)363encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)364{365arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;366unsigned char *st;367int blkn, ci, tbl;368int v, v2, m;369ISHIFT_TEMPS370371/* Emit restart marker if needed */372if (cinfo->restart_interval) {373if (entropy->restarts_to_go == 0) {374emit_restart(cinfo, entropy->next_restart_num);375entropy->restarts_to_go = cinfo->restart_interval;376entropy->next_restart_num++;377entropy->next_restart_num &= 7;378}379entropy->restarts_to_go--;380}381382/* Encode the MCU data blocks */383for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {384ci = cinfo->MCU_membership[blkn];385tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;386387/* Compute the DC value after the required point transform by Al.388* This is simply an arithmetic right shift.389*/390m = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);391392/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */393394/* Table F.4: Point to statistics bin S0 for DC coefficient coding */395st = entropy->dc_stats[tbl] + entropy->dc_context[ci];396397/* Figure F.4: Encode_DC_DIFF */398if ((v = m - entropy->last_dc_val[ci]) == 0) {399arith_encode(cinfo, st, 0);400entropy->dc_context[ci] = 0; /* zero diff category */401} else {402entropy->last_dc_val[ci] = m;403arith_encode(cinfo, st, 1);404/* Figure F.6: Encoding nonzero value v */405/* Figure F.7: Encoding the sign of v */406if (v > 0) {407arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */408st += 2; /* Table F.4: SP = S0 + 2 */409entropy->dc_context[ci] = 4; /* small positive diff category */410} else {411v = -v;412arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */413st += 3; /* Table F.4: SN = S0 + 3 */414entropy->dc_context[ci] = 8; /* small negative diff category */415}416/* Figure F.8: Encoding the magnitude category of v */417m = 0;418if (v -= 1) {419arith_encode(cinfo, st, 1);420m = 1;421v2 = v;422st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */423while (v2 >>= 1) {424arith_encode(cinfo, st, 1);425m <<= 1;426st += 1;427}428}429arith_encode(cinfo, st, 0);430/* Section F.1.4.4.1.2: Establish dc_context conditioning category */431if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))432entropy->dc_context[ci] = 0; /* zero diff category */433else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))434entropy->dc_context[ci] += 8; /* large diff category */435/* Figure F.9: Encoding the magnitude bit pattern of v */436st += 14;437while (m >>= 1)438arith_encode(cinfo, st, (m & v) ? 1 : 0);439}440}441442return TRUE;443}444445446/*447* MCU encoding for AC initial scan (either spectral selection,448* or first pass of successive approximation).449*/450451METHODDEF(boolean)452encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)453{454arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;455const int * natural_order;456JBLOCKROW block;457unsigned char *st;458int tbl, k, ke;459int v, v2, m;460461/* Emit restart marker if needed */462if (cinfo->restart_interval) {463if (entropy->restarts_to_go == 0) {464emit_restart(cinfo, entropy->next_restart_num);465entropy->restarts_to_go = cinfo->restart_interval;466entropy->next_restart_num++;467entropy->next_restart_num &= 7;468}469entropy->restarts_to_go--;470}471472natural_order = cinfo->natural_order;473474/* Encode the MCU data block */475block = MCU_data[0];476tbl = cinfo->cur_comp_info[0]->ac_tbl_no;477478/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */479480/* Establish EOB (end-of-block) index */481ke = cinfo->Se;482do {483/* We must apply the point transform by Al. For AC coefficients this484* is an integer division with rounding towards 0. To do this portably485* in C, we shift after obtaining the absolute value.486*/487if ((v = (*block)[natural_order[ke]]) >= 0) {488if (v >>= cinfo->Al) break;489} else {490v = -v;491if (v >>= cinfo->Al) break;492}493} while (--ke);494495/* Figure F.5: Encode_AC_Coefficients */496for (k = cinfo->Ss - 1; k < ke;) {497st = entropy->ac_stats[tbl] + 3 * k;498arith_encode(cinfo, st, 0); /* EOB decision */499for (;;) {500if ((v = (*block)[natural_order[++k]]) >= 0) {501if (v >>= cinfo->Al) {502arith_encode(cinfo, st + 1, 1);503arith_encode(cinfo, entropy->fixed_bin, 0);504break;505}506} else {507v = -v;508if (v >>= cinfo->Al) {509arith_encode(cinfo, st + 1, 1);510arith_encode(cinfo, entropy->fixed_bin, 1);511break;512}513}514arith_encode(cinfo, st + 1, 0);515st += 3;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;545arith_encode(cinfo, st, 1);546}547548return TRUE;549}550551552/*553* MCU encoding for DC successive approximation refinement scan.554* Note: we assume such scans can be multi-component,555* although the spec is not very clear on the point.556*/557558METHODDEF(boolean)559encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)560{561arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;562unsigned char *st;563int Al, blkn;564565/* Emit restart marker if needed */566if (cinfo->restart_interval) {567if (entropy->restarts_to_go == 0) {568emit_restart(cinfo, entropy->next_restart_num);569entropy->restarts_to_go = cinfo->restart_interval;570entropy->next_restart_num++;571entropy->next_restart_num &= 7;572}573entropy->restarts_to_go--;574}575576st = entropy->fixed_bin; /* use fixed probability estimation */577Al = cinfo->Al;578579/* Encode the MCU data blocks */580for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {581/* We simply emit the Al'th bit of the DC coefficient value. */582arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);583}584585return TRUE;586}587588589/*590* MCU encoding for AC successive approximation refinement scan.591*/592593METHODDEF(boolean)594encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)595{596arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;597const int * natural_order;598JBLOCKROW block;599unsigned char *st;600int tbl, k, ke, kex;601int v;602603/* Emit restart marker if needed */604if (cinfo->restart_interval) {605if (entropy->restarts_to_go == 0) {606emit_restart(cinfo, entropy->next_restart_num);607entropy->restarts_to_go = cinfo->restart_interval;608entropy->next_restart_num++;609entropy->next_restart_num &= 7;610}611entropy->restarts_to_go--;612}613614natural_order = cinfo->natural_order;615616/* Encode the MCU data block */617block = MCU_data[0];618tbl = cinfo->cur_comp_info[0]->ac_tbl_no;619620/* Section G.1.3.3: Encoding of AC coefficients */621622/* Establish EOB (end-of-block) index */623ke = cinfo->Se;624do {625/* We must apply the point transform by Al. For AC coefficients this626* is an integer division with rounding towards 0. To do this portably627* in C, we shift after obtaining the absolute value.628*/629if ((v = (*block)[natural_order[ke]]) >= 0) {630if (v >>= cinfo->Al) break;631} else {632v = -v;633if (v >>= cinfo->Al) break;634}635} while (--ke);636637/* Establish EOBx (previous stage end-of-block) index */638for (kex = ke; kex > 0; kex--)639if ((v = (*block)[natural_order[kex]]) >= 0) {640if (v >>= cinfo->Ah) break;641} else {642v = -v;643if (v >>= cinfo->Ah) break;644}645646/* Figure G.10: Encode_AC_Coefficients_SA */647for (k = cinfo->Ss - 1; k < ke;) {648st = entropy->ac_stats[tbl] + 3 * k;649if (k >= kex)650arith_encode(cinfo, st, 0); /* EOB decision */651for (;;) {652if ((v = (*block)[natural_order[++k]]) >= 0) {653if (v >>= cinfo->Al) {654if (v >> 1) /* previously nonzero coef */655arith_encode(cinfo, st + 2, (v & 1));656else { /* newly nonzero coef */657arith_encode(cinfo, st + 1, 1);658arith_encode(cinfo, entropy->fixed_bin, 0);659}660break;661}662} else {663v = -v;664if (v >>= cinfo->Al) {665if (v >> 1) /* previously nonzero coef */666arith_encode(cinfo, st + 2, (v & 1));667else { /* newly nonzero coef */668arith_encode(cinfo, st + 1, 1);669arith_encode(cinfo, entropy->fixed_bin, 1);670}671break;672}673}674arith_encode(cinfo, st + 1, 0);675st += 3;676}677}678/* Encode EOB decision only if k < cinfo->Se */679if (k < cinfo->Se) {680st = entropy->ac_stats[tbl] + 3 * k;681arith_encode(cinfo, st, 1);682}683684return TRUE;685}686687688/*689* Encode and output one MCU's worth of arithmetic-compressed coefficients.690*/691692METHODDEF(boolean)693encode_mcu (j_compress_ptr cinfo, JBLOCKARRAY MCU_data)694{695arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;696const int * natural_order;697JBLOCKROW block;698unsigned char *st;699int tbl, k, ke;700int v, v2, m;701int blkn, ci;702jpeg_component_info * compptr;703704/* Emit restart marker if needed */705if (cinfo->restart_interval) {706if (entropy->restarts_to_go == 0) {707emit_restart(cinfo, entropy->next_restart_num);708entropy->restarts_to_go = cinfo->restart_interval;709entropy->next_restart_num++;710entropy->next_restart_num &= 7;711}712entropy->restarts_to_go--;713}714715natural_order = cinfo->natural_order;716717/* Encode the MCU data blocks */718for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {719block = MCU_data[blkn];720ci = cinfo->MCU_membership[blkn];721compptr = cinfo->cur_comp_info[ci];722723/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */724725tbl = compptr->dc_tbl_no;726727/* Table F.4: Point to statistics bin S0 for DC coefficient coding */728st = entropy->dc_stats[tbl] + entropy->dc_context[ci];729730/* Figure F.4: Encode_DC_DIFF */731if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {732arith_encode(cinfo, st, 0);733entropy->dc_context[ci] = 0; /* zero diff category */734} else {735entropy->last_dc_val[ci] = (*block)[0];736arith_encode(cinfo, st, 1);737/* Figure F.6: Encoding nonzero value v */738/* Figure F.7: Encoding the sign of v */739if (v > 0) {740arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */741st += 2; /* Table F.4: SP = S0 + 2 */742entropy->dc_context[ci] = 4; /* small positive diff category */743} else {744v = -v;745arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */746st += 3; /* Table F.4: SN = S0 + 3 */747entropy->dc_context[ci] = 8; /* small negative diff category */748}749/* Figure F.8: Encoding the magnitude category of v */750m = 0;751if (v -= 1) {752arith_encode(cinfo, st, 1);753m = 1;754v2 = v;755st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */756while (v2 >>= 1) {757arith_encode(cinfo, st, 1);758m <<= 1;759st += 1;760}761}762arith_encode(cinfo, st, 0);763/* Section F.1.4.4.1.2: Establish dc_context conditioning category */764if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))765entropy->dc_context[ci] = 0; /* zero diff category */766else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))767entropy->dc_context[ci] += 8; /* large diff category */768/* Figure F.9: Encoding the magnitude bit pattern of v */769st += 14;770while (m >>= 1)771arith_encode(cinfo, st, (m & v) ? 1 : 0);772}773774/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */775776if ((ke = cinfo->lim_Se) == 0) continue;777tbl = compptr->ac_tbl_no;778779/* Establish EOB (end-of-block) index */780do {781if ((*block)[natural_order[ke]]) break;782} while (--ke);783784/* Figure F.5: Encode_AC_Coefficients */785for (k = 0; k < ke;) {786st = entropy->ac_stats[tbl] + 3 * k;787arith_encode(cinfo, st, 0); /* EOB decision */788while ((v = (*block)[natural_order[++k]]) == 0) {789arith_encode(cinfo, st + 1, 0);790st += 3;791}792arith_encode(cinfo, st + 1, 1);793/* Figure F.6: Encoding nonzero value v */794/* Figure F.7: Encoding the sign of v */795if (v > 0) {796arith_encode(cinfo, entropy->fixed_bin, 0);797} else {798v = -v;799arith_encode(cinfo, entropy->fixed_bin, 1);800}801st += 2;802/* Figure F.8: Encoding the magnitude category of v */803m = 0;804if (v -= 1) {805arith_encode(cinfo, st, 1);806m = 1;807v2 = v;808if (v2 >>= 1) {809arith_encode(cinfo, st, 1);810m <<= 1;811st = entropy->ac_stats[tbl] +812(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);813while (v2 >>= 1) {814arith_encode(cinfo, st, 1);815m <<= 1;816st += 1;817}818}819}820arith_encode(cinfo, st, 0);821/* Figure F.9: Encoding the magnitude bit pattern of v */822st += 14;823while (m >>= 1)824arith_encode(cinfo, st, (m & v) ? 1 : 0);825}826/* Encode EOB decision only if k < cinfo->lim_Se */827if (k < cinfo->lim_Se) {828st = entropy->ac_stats[tbl] + 3 * k;829arith_encode(cinfo, st, 1);830}831}832833return TRUE;834}835836837/*838* Initialize for an arithmetic-compressed scan.839*/840841METHODDEF(void)842start_pass (j_compress_ptr cinfo, boolean gather_statistics)843{844arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;845int ci, tbl;846jpeg_component_info * compptr;847848if (gather_statistics)849/* Make sure to avoid that in the master control logic!850* We are fully adaptive here and need no extra851* statistics gathering pass!852*/853ERREXIT(cinfo, JERR_NOT_COMPILED);854855/* We assume jcmaster.c already validated the progressive scan parameters. */856857/* Select execution routines */858if (cinfo->progressive_mode) {859if (cinfo->Ah == 0) {860if (cinfo->Ss == 0)861entropy->pub.encode_mcu = encode_mcu_DC_first;862else863entropy->pub.encode_mcu = encode_mcu_AC_first;864} else {865if (cinfo->Ss == 0)866entropy->pub.encode_mcu = encode_mcu_DC_refine;867else868entropy->pub.encode_mcu = encode_mcu_AC_refine;869}870} else871entropy->pub.encode_mcu = encode_mcu;872873/* Allocate & initialize requested statistics areas */874for (ci = 0; ci < cinfo->comps_in_scan; ci++) {875compptr = cinfo->cur_comp_info[ci];876/* DC needs no table for refinement scan */877if (cinfo->Ss == 0 && cinfo->Ah == 0) {878tbl = compptr->dc_tbl_no;879if (tbl < 0 || tbl >= NUM_ARITH_TBLS)880ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);881if (entropy->dc_stats[tbl] == NULL)882entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)883((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);884MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);885/* Initialize DC predictions to 0 */886entropy->last_dc_val[ci] = 0;887entropy->dc_context[ci] = 0;888}889/* AC needs no table when not present */890if (cinfo->Se) {891tbl = compptr->ac_tbl_no;892if (tbl < 0 || tbl >= NUM_ARITH_TBLS)893ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);894if (entropy->ac_stats[tbl] == NULL)895entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)896((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);897MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);898#ifdef CALCULATE_SPECTRAL_CONDITIONING899if (cinfo->progressive_mode)900/* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */901cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);902#endif903}904}905906/* Initialize arithmetic encoding variables */907entropy->c = 0;908entropy->a = 0x10000L;909entropy->sc = 0;910entropy->zc = 0;911entropy->ct = 11;912entropy->buffer = -1; /* empty */913914/* Initialize restart stuff */915entropy->restarts_to_go = cinfo->restart_interval;916entropy->next_restart_num = 0;917}918919920/*921* Module initialization routine for arithmetic entropy encoding.922*/923924GLOBAL(void)925jinit_arith_encoder (j_compress_ptr cinfo)926{927arith_entropy_ptr entropy;928int i;929930entropy = (arith_entropy_ptr) (*cinfo->mem->alloc_small)931((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(arith_entropy_encoder));932cinfo->entropy = &entropy->pub;933entropy->pub.start_pass = start_pass;934entropy->pub.finish_pass = finish_pass;935936/* Mark tables unallocated */937for (i = 0; i < NUM_ARITH_TBLS; i++) {938entropy->dc_stats[i] = NULL;939entropy->ac_stats[i] = NULL;940}941942/* Initialize index for fixed probability estimation */943entropy->fixed_bin[0] = 113;944}945946947