Path: blob/master/3rdparty/libjpeg-turbo/src/jcarith.c
16337 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, 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 the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).12*13* Both sequential and progressive modes are supported in this single module.14*15* Suspension is not currently supported in this module.16*/1718#define JPEG_INTERNALS19#include "jinclude.h"20#include "jpeglib.h"212223/* Expanded entropy encoder object for arithmetic encoding. */2425typedef struct {26struct jpeg_entropy_encoder pub; /* public fields */2728JLONG c; /* C register, base of coding interval, layout as in sec. D.1.3 */29JLONG a; /* A register, normalized size of coding interval */30JLONG sc; /* counter for stacked 0xFF values which might overflow */31JLONG zc; /* counter for pending 0x00 output values which might *32* be discarded at the end ("Pacman" termination) */33int ct; /* bit shift counter, determines when next byte will be written */34int buffer; /* buffer for most recent output byte != 0xFF */3536int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */37int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */3839unsigned int restarts_to_go; /* MCUs left in this restart interval */40int next_restart_num; /* next restart number to write (0-7) */4142/* Pointers to statistics areas (these workspaces have image lifespan) */43unsigned char *dc_stats[NUM_ARITH_TBLS];44unsigned char *ac_stats[NUM_ARITH_TBLS];4546/* Statistics bin for coding with fixed probability 0.5 */47unsigned char fixed_bin[4];48} arith_entropy_encoder;4950typedef arith_entropy_encoder *arith_entropy_ptr;5152/* The following two definitions specify the allocation chunk size53* for the statistics area.54* According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least55* 49 statistics bins for DC, and 245 statistics bins for AC coding.56*57* We use a compact representation with 1 byte per statistics bin,58* thus the numbers directly represent byte sizes.59* This 1 byte per statistics bin contains the meaning of the MPS60* (more probable symbol) in the highest bit (mask 0x80), and the61* index into the probability estimation state machine table62* in the lower bits (mask 0x7F).63*/6465#define DC_STAT_BINS 6466#define AC_STAT_BINS 2566768/* NOTE: Uncomment the following #define if you want to use the69* given formula for calculating the AC conditioning parameter Kx70* for spectral selection progressive coding in section G.1.3.271* of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4).72* Although the spec and P&M authors claim that this "has proven73* to give good results for 8 bit precision samples", I'm not74* convinced yet that this is really beneficial.75* Early tests gave only very marginal compression enhancements76* (a few - around 5 or so - bytes even for very large files),77* which would turn out rather negative if we'd suppress the78* DAC (Define Arithmetic Conditioning) marker segments for79* the default parameters in the future.80* Note that currently the marker writing module emits 12-byte81* DAC segments for a full-component scan in a color image.82* This is not worth worrying about IMHO. However, since the83* spec defines the default values to be used if the tables84* are omitted (unlike Huffman tables, which are required85* anyway), one might optimize this behaviour in the future,86* and then it would be disadvantageous to use custom tables if87* they don't provide sufficient gain to exceed the DAC size.88*89* On the other hand, I'd consider it as a reasonable result90* that the conditioning has no significant influence on the91* compression performance. This means that the basic92* statistical model is already rather stable.93*94* Thus, at the moment, we use the default conditioning values95* anyway, and do not use the custom formula.96*97#define CALCULATE_SPECTRAL_CONDITIONING98*/99100/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than JLONG.101* We assume that int right shift is unsigned if JLONG right shift is,102* which should be safe.103*/104105#ifdef RIGHT_SHIFT_IS_UNSIGNED106#define ISHIFT_TEMPS int ishift_temp;107#define IRIGHT_SHIFT(x,shft) \108((ishift_temp = (x)) < 0 ? \109(ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \110(ishift_temp >> (shft)))111#else112#define ISHIFT_TEMPS113#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))114#endif115116117LOCAL(void)118emit_byte (int val, j_compress_ptr cinfo)119/* Write next output byte; we do not support suspension in this module. */120{121struct jpeg_destination_mgr *dest = cinfo->dest;122123*dest->next_output_byte++ = (JOCTET) val;124if (--dest->free_in_buffer == 0)125if (! (*dest->empty_output_buffer) (cinfo))126ERREXIT(cinfo, JERR_CANT_SUSPEND);127}128129130/*131* Finish up at the end of an arithmetic-compressed scan.132*/133134METHODDEF(void)135finish_pass (j_compress_ptr cinfo)136{137arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;138JLONG temp;139140/* Section D.1.8: Termination of encoding */141142/* Find the e->c in the coding interval with the largest143* number of trailing zero bits */144if ((temp = (e->a - 1 + e->c) & 0xFFFF0000L) < e->c)145e->c = temp + 0x8000L;146else147e->c = temp;148/* Send remaining bytes to output */149e->c <<= e->ct;150if (e->c & 0xF8000000L) {151/* One final overflow has to be handled */152if (e->buffer >= 0) {153if (e->zc)154do emit_byte(0x00, cinfo);155while (--e->zc);156emit_byte(e->buffer + 1, cinfo);157if (e->buffer + 1 == 0xFF)158emit_byte(0x00, cinfo);159}160e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */161e->sc = 0;162} else {163if (e->buffer == 0)164++e->zc;165else if (e->buffer >= 0) {166if (e->zc)167do emit_byte(0x00, cinfo);168while (--e->zc);169emit_byte(e->buffer, cinfo);170}171if (e->sc) {172if (e->zc)173do emit_byte(0x00, cinfo);174while (--e->zc);175do {176emit_byte(0xFF, cinfo);177emit_byte(0x00, cinfo);178} while (--e->sc);179}180}181/* Output final bytes only if they are not 0x00 */182if (e->c & 0x7FFF800L) {183if (e->zc) /* output final pending zero bytes */184do emit_byte(0x00, cinfo);185while (--e->zc);186emit_byte((e->c >> 19) & 0xFF, cinfo);187if (((e->c >> 19) & 0xFF) == 0xFF)188emit_byte(0x00, cinfo);189if (e->c & 0x7F800L) {190emit_byte((e->c >> 11) & 0xFF, cinfo);191if (((e->c >> 11) & 0xFF) == 0xFF)192emit_byte(0x00, cinfo);193}194}195}196197198/*199* The core arithmetic encoding routine (common in JPEG and JBIG).200* This needs to go as fast as possible.201* Machine-dependent optimization facilities202* are not utilized in this portable implementation.203* However, this code should be fairly efficient and204* may be a good base for further optimizations anyway.205*206* Parameter 'val' to be encoded may be 0 or 1 (binary decision).207*208* Note: I've added full "Pacman" termination support to the209* byte output routines, which is equivalent to the optional210* Discard_final_zeros procedure (Figure D.15) in the spec.211* Thus, we always produce the shortest possible output212* stream compliant to the spec (no trailing zero bytes,213* except for FF stuffing).214*215* I've also introduced a new scheme for accessing216* the probability estimation state machine table,217* derived from Markus Kuhn's JBIG implementation.218*/219220LOCAL(void)221arith_encode (j_compress_ptr cinfo, unsigned char *st, int val)222{223register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;224register unsigned char nl, nm;225register JLONG qe, temp;226register int sv;227228/* Fetch values from our compact representation of Table D.2:229* Qe values and probability estimation state machine230*/231sv = *st;232qe = jpeg_aritab[sv & 0x7F]; /* => Qe_Value */233nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */234nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */235236/* Encode & estimation procedures per sections D.1.4 & D.1.5 */237e->a -= qe;238if (val != (sv >> 7)) {239/* Encode the less probable symbol */240if (e->a >= qe) {241/* If the interval size (qe) for the less probable symbol (LPS)242* is larger than the interval size for the MPS, then exchange243* the two symbols for coding efficiency, otherwise code the LPS244* as usual: */245e->c += e->a;246e->a = qe;247}248*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */249} else {250/* Encode the more probable symbol */251if (e->a >= 0x8000L)252return; /* A >= 0x8000 -> ready, no renormalization required */253if (e->a < qe) {254/* If the interval size (qe) for the less probable symbol (LPS)255* is larger than the interval size for the MPS, then exchange256* the two symbols for coding efficiency: */257e->c += e->a;258e->a = qe;259}260*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */261}262263/* Renormalization & data output per section D.1.6 */264do {265e->a <<= 1;266e->c <<= 1;267if (--e->ct == 0) {268/* Another byte is ready for output */269temp = e->c >> 19;270if (temp > 0xFF) {271/* Handle overflow over all stacked 0xFF bytes */272if (e->buffer >= 0) {273if (e->zc)274do emit_byte(0x00, cinfo);275while (--e->zc);276emit_byte(e->buffer + 1, cinfo);277if (e->buffer + 1 == 0xFF)278emit_byte(0x00, cinfo);279}280e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */281e->sc = 0;282/* Note: The 3 spacer bits in the C register guarantee283* that the new buffer byte can't be 0xFF here284* (see page 160 in the P&M JPEG book). */285e->buffer = temp & 0xFF; /* new output byte, might overflow later */286} else if (temp == 0xFF) {287++e->sc; /* stack 0xFF byte (which might overflow later) */288} else {289/* Output all stacked 0xFF bytes, they will not overflow any more */290if (e->buffer == 0)291++e->zc;292else if (e->buffer >= 0) {293if (e->zc)294do emit_byte(0x00, cinfo);295while (--e->zc);296emit_byte(e->buffer, cinfo);297}298if (e->sc) {299if (e->zc)300do emit_byte(0x00, cinfo);301while (--e->zc);302do {303emit_byte(0xFF, cinfo);304emit_byte(0x00, cinfo);305} while (--e->sc);306}307e->buffer = temp & 0xFF; /* new output byte (can still overflow) */308}309e->c &= 0x7FFFFL;310e->ct += 8;311}312} while (e->a < 0x8000L);313}314315316/*317* Emit a restart marker & resynchronize predictions.318*/319320LOCAL(void)321emit_restart (j_compress_ptr cinfo, int restart_num)322{323arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;324int ci;325jpeg_component_info *compptr;326327finish_pass(cinfo);328329emit_byte(0xFF, cinfo);330emit_byte(JPEG_RST0 + restart_num, cinfo);331332/* Re-initialize statistics areas */333for (ci = 0; ci < cinfo->comps_in_scan; ci++) {334compptr = cinfo->cur_comp_info[ci];335/* DC needs no table for refinement scan */336if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {337MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);338/* Reset DC predictions to 0 */339entropy->last_dc_val[ci] = 0;340entropy->dc_context[ci] = 0;341}342/* AC needs no table when not present */343if (cinfo->progressive_mode == 0 || cinfo->Se) {344MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);345}346}347348/* Reset arithmetic encoding variables */349entropy->c = 0;350entropy->a = 0x10000L;351entropy->sc = 0;352entropy->zc = 0;353entropy->ct = 11;354entropy->buffer = -1; /* empty */355}356357358/*359* MCU encoding for DC initial scan (either spectral selection,360* or first pass of successive approximation).361*/362363METHODDEF(boolean)364encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)365{366arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;367JBLOCKROW block;368unsigned char *st;369int blkn, ci, tbl;370int v, v2, m;371ISHIFT_TEMPS372373/* Emit restart marker if needed */374if (cinfo->restart_interval) {375if (entropy->restarts_to_go == 0) {376emit_restart(cinfo, entropy->next_restart_num);377entropy->restarts_to_go = cinfo->restart_interval;378entropy->next_restart_num++;379entropy->next_restart_num &= 7;380}381entropy->restarts_to_go--;382}383384/* Encode the MCU data blocks */385for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {386block = MCU_data[blkn];387ci = cinfo->MCU_membership[blkn];388tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;389390/* Compute the DC value after the required point transform by Al.391* This is simply an arithmetic right shift.392*/393m = IRIGHT_SHIFT((int) ((*block)[0]), cinfo->Al);394395/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */396397/* Table F.4: Point to statistics bin S0 for DC coefficient coding */398st = entropy->dc_stats[tbl] + entropy->dc_context[ci];399400/* Figure F.4: Encode_DC_DIFF */401if ((v = m - entropy->last_dc_val[ci]) == 0) {402arith_encode(cinfo, st, 0);403entropy->dc_context[ci] = 0; /* zero diff category */404} else {405entropy->last_dc_val[ci] = m;406arith_encode(cinfo, st, 1);407/* Figure F.6: Encoding nonzero value v */408/* Figure F.7: Encoding the sign of v */409if (v > 0) {410arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */411st += 2; /* Table F.4: SP = S0 + 2 */412entropy->dc_context[ci] = 4; /* small positive diff category */413} else {414v = -v;415arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */416st += 3; /* Table F.4: SN = S0 + 3 */417entropy->dc_context[ci] = 8; /* small negative diff category */418}419/* Figure F.8: Encoding the magnitude category of v */420m = 0;421if (v -= 1) {422arith_encode(cinfo, st, 1);423m = 1;424v2 = v;425st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */426while (v2 >>= 1) {427arith_encode(cinfo, st, 1);428m <<= 1;429st += 1;430}431}432arith_encode(cinfo, st, 0);433/* Section F.1.4.4.1.2: Establish dc_context conditioning category */434if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))435entropy->dc_context[ci] = 0; /* zero diff category */436else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))437entropy->dc_context[ci] += 8; /* large diff category */438/* Figure F.9: Encoding the magnitude bit pattern of v */439st += 14;440while (m >>= 1)441arith_encode(cinfo, st, (m & v) ? 1 : 0);442}443}444445return TRUE;446}447448449/*450* MCU encoding for AC initial scan (either spectral selection,451* or first pass of successive approximation).452*/453454METHODDEF(boolean)455encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)456{457arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;458JBLOCKROW block;459unsigned char *st;460int tbl, k, ke;461int v, v2, m;462463/* Emit restart marker if needed */464if (cinfo->restart_interval) {465if (entropy->restarts_to_go == 0) {466emit_restart(cinfo, entropy->next_restart_num);467entropy->restarts_to_go = cinfo->restart_interval;468entropy->next_restart_num++;469entropy->next_restart_num &= 7;470}471entropy->restarts_to_go--;472}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 */481for (ke = cinfo->Se; ke > 0; ke--)482/* We must apply the point transform by Al. For AC coefficients this483* is an integer division with rounding towards 0. To do this portably484* in C, we shift after obtaining the absolute value.485*/486if ((v = (*block)[jpeg_natural_order[ke]]) >= 0) {487if (v >>= cinfo->Al) break;488} else {489v = -v;490if (v >>= cinfo->Al) break;491}492493/* Figure F.5: Encode_AC_Coefficients */494for (k = cinfo->Ss; k <= ke; k++) {495st = entropy->ac_stats[tbl] + 3 * (k - 1);496arith_encode(cinfo, st, 0); /* EOB decision */497for (;;) {498if ((v = (*block)[jpeg_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); st += 3; k++;513}514st += 2;515/* Figure F.8: Encoding the magnitude category of v */516m = 0;517if (v -= 1) {518arith_encode(cinfo, st, 1);519m = 1;520v2 = v;521if (v2 >>= 1) {522arith_encode(cinfo, st, 1);523m <<= 1;524st = entropy->ac_stats[tbl] +525(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);526while (v2 >>= 1) {527arith_encode(cinfo, st, 1);528m <<= 1;529st += 1;530}531}532}533arith_encode(cinfo, st, 0);534/* Figure F.9: Encoding the magnitude bit pattern of v */535st += 14;536while (m >>= 1)537arith_encode(cinfo, st, (m & v) ? 1 : 0);538}539/* Encode EOB decision only if k <= cinfo->Se */540if (k <= cinfo->Se) {541st = entropy->ac_stats[tbl] + 3 * (k - 1);542arith_encode(cinfo, st, 1);543}544545return TRUE;546}547548549/*550* MCU encoding for DC successive approximation refinement scan.551*/552553METHODDEF(boolean)554encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)555{556arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;557unsigned char *st;558int Al, blkn;559560/* Emit restart marker if needed */561if (cinfo->restart_interval) {562if (entropy->restarts_to_go == 0) {563emit_restart(cinfo, entropy->next_restart_num);564entropy->restarts_to_go = cinfo->restart_interval;565entropy->next_restart_num++;566entropy->next_restart_num &= 7;567}568entropy->restarts_to_go--;569}570571st = entropy->fixed_bin; /* use fixed probability estimation */572Al = cinfo->Al;573574/* Encode the MCU data blocks */575for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {576/* We simply emit the Al'th bit of the DC coefficient value. */577arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);578}579580return TRUE;581}582583584/*585* MCU encoding for AC successive approximation refinement scan.586*/587588METHODDEF(boolean)589encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)590{591arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;592JBLOCKROW block;593unsigned char *st;594int tbl, k, ke, kex;595int v;596597/* Emit restart marker if needed */598if (cinfo->restart_interval) {599if (entropy->restarts_to_go == 0) {600emit_restart(cinfo, entropy->next_restart_num);601entropy->restarts_to_go = cinfo->restart_interval;602entropy->next_restart_num++;603entropy->next_restart_num &= 7;604}605entropy->restarts_to_go--;606}607608/* Encode the MCU data block */609block = MCU_data[0];610tbl = cinfo->cur_comp_info[0]->ac_tbl_no;611612/* Section G.1.3.3: Encoding of AC coefficients */613614/* Establish EOB (end-of-block) index */615for (ke = cinfo->Se; ke > 0; ke--)616/* We must apply the point transform by Al. For AC coefficients this617* is an integer division with rounding towards 0. To do this portably618* in C, we shift after obtaining the absolute value.619*/620if ((v = (*block)[jpeg_natural_order[ke]]) >= 0) {621if (v >>= cinfo->Al) break;622} else {623v = -v;624if (v >>= cinfo->Al) break;625}626627/* Establish EOBx (previous stage end-of-block) index */628for (kex = ke; kex > 0; kex--)629if ((v = (*block)[jpeg_natural_order[kex]]) >= 0) {630if (v >>= cinfo->Ah) break;631} else {632v = -v;633if (v >>= cinfo->Ah) break;634}635636/* Figure G.10: Encode_AC_Coefficients_SA */637for (k = cinfo->Ss; k <= ke; k++) {638st = entropy->ac_stats[tbl] + 3 * (k - 1);639if (k > kex)640arith_encode(cinfo, st, 0); /* EOB decision */641for (;;) {642if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {643if (v >>= cinfo->Al) {644if (v >> 1) /* previously nonzero coef */645arith_encode(cinfo, st + 2, (v & 1));646else { /* newly nonzero coef */647arith_encode(cinfo, st + 1, 1);648arith_encode(cinfo, entropy->fixed_bin, 0);649}650break;651}652} else {653v = -v;654if (v >>= cinfo->Al) {655if (v >> 1) /* previously nonzero coef */656arith_encode(cinfo, st + 2, (v & 1));657else { /* newly nonzero coef */658arith_encode(cinfo, st + 1, 1);659arith_encode(cinfo, entropy->fixed_bin, 1);660}661break;662}663}664arith_encode(cinfo, st + 1, 0); st += 3; k++;665}666}667/* Encode EOB decision only if k <= cinfo->Se */668if (k <= cinfo->Se) {669st = entropy->ac_stats[tbl] + 3 * (k - 1);670arith_encode(cinfo, st, 1);671}672673return TRUE;674}675676677/*678* Encode and output one MCU's worth of arithmetic-compressed coefficients.679*/680681METHODDEF(boolean)682encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)683{684arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;685jpeg_component_info *compptr;686JBLOCKROW block;687unsigned char *st;688int blkn, ci, tbl, k, ke;689int v, v2, m;690691/* Emit restart marker if needed */692if (cinfo->restart_interval) {693if (entropy->restarts_to_go == 0) {694emit_restart(cinfo, entropy->next_restart_num);695entropy->restarts_to_go = cinfo->restart_interval;696entropy->next_restart_num++;697entropy->next_restart_num &= 7;698}699entropy->restarts_to_go--;700}701702/* Encode the MCU data blocks */703for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {704block = MCU_data[blkn];705ci = cinfo->MCU_membership[blkn];706compptr = cinfo->cur_comp_info[ci];707708/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */709710tbl = compptr->dc_tbl_no;711712/* Table F.4: Point to statistics bin S0 for DC coefficient coding */713st = entropy->dc_stats[tbl] + entropy->dc_context[ci];714715/* Figure F.4: Encode_DC_DIFF */716if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {717arith_encode(cinfo, st, 0);718entropy->dc_context[ci] = 0; /* zero diff category */719} else {720entropy->last_dc_val[ci] = (*block)[0];721arith_encode(cinfo, st, 1);722/* Figure F.6: Encoding nonzero value v */723/* Figure F.7: Encoding the sign of v */724if (v > 0) {725arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */726st += 2; /* Table F.4: SP = S0 + 2 */727entropy->dc_context[ci] = 4; /* small positive diff category */728} else {729v = -v;730arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */731st += 3; /* Table F.4: SN = S0 + 3 */732entropy->dc_context[ci] = 8; /* small negative diff category */733}734/* Figure F.8: Encoding the magnitude category of v */735m = 0;736if (v -= 1) {737arith_encode(cinfo, st, 1);738m = 1;739v2 = v;740st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */741while (v2 >>= 1) {742arith_encode(cinfo, st, 1);743m <<= 1;744st += 1;745}746}747arith_encode(cinfo, st, 0);748/* Section F.1.4.4.1.2: Establish dc_context conditioning category */749if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))750entropy->dc_context[ci] = 0; /* zero diff category */751else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))752entropy->dc_context[ci] += 8; /* large diff category */753/* Figure F.9: Encoding the magnitude bit pattern of v */754st += 14;755while (m >>= 1)756arith_encode(cinfo, st, (m & v) ? 1 : 0);757}758759/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */760761tbl = compptr->ac_tbl_no;762763/* Establish EOB (end-of-block) index */764for (ke = DCTSIZE2 - 1; ke > 0; ke--)765if ((*block)[jpeg_natural_order[ke]]) break;766767/* Figure F.5: Encode_AC_Coefficients */768for (k = 1; k <= ke; k++) {769st = entropy->ac_stats[tbl] + 3 * (k - 1);770arith_encode(cinfo, st, 0); /* EOB decision */771while ((v = (*block)[jpeg_natural_order[k]]) == 0) {772arith_encode(cinfo, st + 1, 0); st += 3; k++;773}774arith_encode(cinfo, st + 1, 1);775/* Figure F.6: Encoding nonzero value v */776/* Figure F.7: Encoding the sign of v */777if (v > 0) {778arith_encode(cinfo, entropy->fixed_bin, 0);779} else {780v = -v;781arith_encode(cinfo, entropy->fixed_bin, 1);782}783st += 2;784/* Figure F.8: Encoding the magnitude category of v */785m = 0;786if (v -= 1) {787arith_encode(cinfo, st, 1);788m = 1;789v2 = v;790if (v2 >>= 1) {791arith_encode(cinfo, st, 1);792m <<= 1;793st = entropy->ac_stats[tbl] +794(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);795while (v2 >>= 1) {796arith_encode(cinfo, st, 1);797m <<= 1;798st += 1;799}800}801}802arith_encode(cinfo, st, 0);803/* Figure F.9: Encoding the magnitude bit pattern of v */804st += 14;805while (m >>= 1)806arith_encode(cinfo, st, (m & v) ? 1 : 0);807}808/* Encode EOB decision only if k <= DCTSIZE2 - 1 */809if (k <= DCTSIZE2 - 1) {810st = entropy->ac_stats[tbl] + 3 * (k - 1);811arith_encode(cinfo, st, 1);812}813}814815return TRUE;816}817818819/*820* Initialize for an arithmetic-compressed scan.821*/822823METHODDEF(void)824start_pass (j_compress_ptr cinfo, boolean gather_statistics)825{826arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;827int ci, tbl;828jpeg_component_info *compptr;829830if (gather_statistics)831/* Make sure to avoid that in the master control logic!832* We are fully adaptive here and need no extra833* statistics gathering pass!834*/835ERREXIT(cinfo, JERR_NOT_COMPILED);836837/* We assume jcmaster.c already validated the progressive scan parameters. */838839/* Select execution routines */840if (cinfo->progressive_mode) {841if (cinfo->Ah == 0) {842if (cinfo->Ss == 0)843entropy->pub.encode_mcu = encode_mcu_DC_first;844else845entropy->pub.encode_mcu = encode_mcu_AC_first;846} else {847if (cinfo->Ss == 0)848entropy->pub.encode_mcu = encode_mcu_DC_refine;849else850entropy->pub.encode_mcu = encode_mcu_AC_refine;851}852} else853entropy->pub.encode_mcu = encode_mcu;854855/* Allocate & initialize requested statistics areas */856for (ci = 0; ci < cinfo->comps_in_scan; ci++) {857compptr = cinfo->cur_comp_info[ci];858/* DC needs no table for refinement scan */859if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {860tbl = compptr->dc_tbl_no;861if (tbl < 0 || tbl >= NUM_ARITH_TBLS)862ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);863if (entropy->dc_stats[tbl] == NULL)864entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)865((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);866MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);867/* Initialize DC predictions to 0 */868entropy->last_dc_val[ci] = 0;869entropy->dc_context[ci] = 0;870}871/* AC needs no table when not present */872if (cinfo->progressive_mode == 0 || cinfo->Se) {873tbl = compptr->ac_tbl_no;874if (tbl < 0 || tbl >= NUM_ARITH_TBLS)875ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);876if (entropy->ac_stats[tbl] == NULL)877entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)878((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);879MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);880#ifdef CALCULATE_SPECTRAL_CONDITIONING881if (cinfo->progressive_mode)882/* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */883cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);884#endif885}886}887888/* Initialize arithmetic encoding variables */889entropy->c = 0;890entropy->a = 0x10000L;891entropy->sc = 0;892entropy->zc = 0;893entropy->ct = 11;894entropy->buffer = -1; /* empty */895896/* Initialize restart stuff */897entropy->restarts_to_go = cinfo->restart_interval;898entropy->next_restart_num = 0;899}900901902/*903* Module initialization routine for arithmetic entropy encoding.904*/905906GLOBAL(void)907jinit_arith_encoder (j_compress_ptr cinfo)908{909arith_entropy_ptr entropy;910int i;911912entropy = (arith_entropy_ptr)913(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,914sizeof(arith_entropy_encoder));915cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;916entropy->pub.start_pass = start_pass;917entropy->pub.finish_pass = finish_pass;918919/* Mark tables unallocated */920for (i = 0; i < NUM_ARITH_TBLS; i++) {921entropy->dc_stats[i] = NULL;922entropy->ac_stats[i] = NULL;923}924925/* Initialize index for fixed probability estimation */926entropy->fixed_bin[0] = 113;927}928929930