Path: blob/master/src/java.desktop/share/native/libjavajpeg/jdphuff.c
41149 views
/*1* reserved comment block2* DO NOT REMOVE OR ALTER!3*/4/*5* jdphuff.c6*7* Copyright (C) 1995-1997, Thomas G. Lane.8* This file is part of the Independent JPEG Group's software.9* For conditions of distribution and use, see the accompanying README file.10*11* This file contains Huffman entropy decoding routines for progressive JPEG.12*13* Much of the complexity here has to do with supporting input suspension.14* If the data source module demands suspension, we want to be able to back15* up to the start of the current MCU. To do this, we copy state variables16* into local working storage, and update them back to the permanent17* storage only upon successful completion of an MCU.18*/1920#define JPEG_INTERNALS21#include "jinclude.h"22#include "jpeglib.h"23#include "jdhuff.h" /* Declarations shared with jdhuff.c */242526#ifdef D_PROGRESSIVE_SUPPORTED2728/*29* Expanded entropy decoder object for progressive Huffman decoding.30*31* The savable_state subrecord contains fields that change within an MCU,32* but must not be updated permanently until we complete the MCU.33*/3435typedef struct {36unsigned int EOBRUN; /* remaining EOBs in EOBRUN */37int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */38} savable_state;3940/* This macro is to work around compilers with missing or broken41* structure assignment. You'll need to fix this code if you have42* such a compiler and you change MAX_COMPS_IN_SCAN.43*/4445#ifndef NO_STRUCT_ASSIGN46#define ASSIGN_STATE(dest,src) ((dest) = (src))47#else48#if MAX_COMPS_IN_SCAN == 449#define ASSIGN_STATE(dest,src) \50((dest).EOBRUN = (src).EOBRUN, \51(dest).last_dc_val[0] = (src).last_dc_val[0], \52(dest).last_dc_val[1] = (src).last_dc_val[1], \53(dest).last_dc_val[2] = (src).last_dc_val[2], \54(dest).last_dc_val[3] = (src).last_dc_val[3])55#endif56#endif575859typedef struct {60struct jpeg_entropy_decoder pub; /* public fields */6162/* These fields are loaded into local variables at start of each MCU.63* In case of suspension, we exit WITHOUT updating them.64*/65bitread_perm_state bitstate; /* Bit buffer at start of MCU */66savable_state saved; /* Other state at start of MCU */6768/* These fields are NOT loaded into local working state. */69unsigned int restarts_to_go; /* MCUs left in this restart interval */7071/* Pointers to derived tables (these workspaces have image lifespan) */72d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];7374d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */75} phuff_entropy_decoder;7677typedef phuff_entropy_decoder * phuff_entropy_ptr;7879/* Forward declarations */80METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,81JBLOCKROW *MCU_data));82METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,83JBLOCKROW *MCU_data));84METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,85JBLOCKROW *MCU_data));86METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,87JBLOCKROW *MCU_data));888990/*91* Initialize for a Huffman-compressed scan.92*/9394METHODDEF(void)95start_pass_phuff_decoder (j_decompress_ptr cinfo)96{97phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;98boolean is_DC_band, bad;99int ci, coefi, tbl;100int *coef_bit_ptr;101jpeg_component_info * compptr;102103is_DC_band = (cinfo->Ss == 0);104105/* Validate scan parameters */106bad = FALSE;107if (is_DC_band) {108if (cinfo->Se != 0)109bad = TRUE;110} else {111/* need not check Ss/Se < 0 since they came from unsigned bytes */112if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)113bad = TRUE;114/* AC scans may have only one component */115if (cinfo->comps_in_scan != 1)116bad = TRUE;117}118if (cinfo->Ah != 0) {119/* Successive approximation refinement scan: must have Al = Ah-1. */120if (cinfo->Al != cinfo->Ah-1)121bad = TRUE;122}123if (cinfo->Al > 13) /* need not check for < 0 */124bad = TRUE;125/* Arguably the maximum Al value should be less than 13 for 8-bit precision,126* but the spec doesn't say so, and we try to be liberal about what we127* accept. Note: large Al values could result in out-of-range DC128* coefficients during early scans, leading to bizarre displays due to129* overflows in the IDCT math. But we won't crash.130*/131if (bad)132ERREXIT4(cinfo, JERR_BAD_PROGRESSION,133cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);134/* Update progression status, and verify that scan order is legal.135* Note that inter-scan inconsistencies are treated as warnings136* not fatal errors ... not clear if this is right way to behave.137*/138for (ci = 0; ci < cinfo->comps_in_scan; ci++) {139int cindex = cinfo->cur_comp_info[ci]->component_index;140coef_bit_ptr = & cinfo->coef_bits[cindex][0];141if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */142WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);143for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {144int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];145if (cinfo->Ah != expected)146WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);147coef_bit_ptr[coefi] = cinfo->Al;148}149}150151/* Select MCU decoding routine */152if (cinfo->Ah == 0) {153if (is_DC_band)154entropy->pub.decode_mcu = decode_mcu_DC_first;155else156entropy->pub.decode_mcu = decode_mcu_AC_first;157} else {158if (is_DC_band)159entropy->pub.decode_mcu = decode_mcu_DC_refine;160else161entropy->pub.decode_mcu = decode_mcu_AC_refine;162}163164for (ci = 0; ci < cinfo->comps_in_scan; ci++) {165compptr = cinfo->cur_comp_info[ci];166/* Make sure requested tables are present, and compute derived tables.167* We may build same derived table more than once, but it's not expensive.168*/169if (is_DC_band) {170if (cinfo->Ah == 0) { /* DC refinement needs no table */171tbl = compptr->dc_tbl_no;172jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,173& entropy->derived_tbls[tbl]);174}175} else {176tbl = compptr->ac_tbl_no;177jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,178& entropy->derived_tbls[tbl]);179/* remember the single active table */180entropy->ac_derived_tbl = entropy->derived_tbls[tbl];181}182/* Initialize DC predictions to 0 */183entropy->saved.last_dc_val[ci] = 0;184}185186/* Initialize bitread state variables */187entropy->bitstate.bits_left = 0;188entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */189entropy->pub.insufficient_data = FALSE;190191/* Initialize private state variables */192entropy->saved.EOBRUN = 0;193194/* Initialize restart counter */195entropy->restarts_to_go = cinfo->restart_interval;196}197198199/*200* Figure F.12: extend sign bit.201* On some machines, a shift and add will be faster than a table lookup.202*/203204#ifdef AVOID_TABLES205206#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))207208#else209210#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))211212static const int extend_test[16] = /* entry n is 2**(n-1) */213{ 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,2140x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };215216static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */217{ 0,218(int)(((unsigned)(~0)<<1) + 1), (int)(((unsigned)(~0)<<2) + 1),219(int)(((unsigned)(~0)<<3) + 1), (int)(((unsigned)(~0)<<4) + 1),220(int)(((unsigned)(~0)<<5) + 1), (int)(((unsigned)(~0)<<6) + 1),221(int)(((unsigned)(~0)<<7) + 1), (int)(((unsigned)(~0)<<8) + 1),222(int)(((unsigned)(~0)<<9) + 1), (int)(((unsigned)(~0)<<10) + 1),223(int)(((unsigned)(~0)<<11) + 1), (int)(((unsigned)(~0)<<12) + 1),224(int)(((unsigned)(~0)<<13) + 1), (int)(((unsigned)(~0)<<14) + 1),225(int)(((unsigned)(~0)<<15) + 1) };226227#endif /* AVOID_TABLES */228229230/*231* Check for a restart marker & resynchronize decoder.232* Returns FALSE if must suspend.233*/234235LOCAL(boolean)236process_restart (j_decompress_ptr cinfo)237{238phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;239int ci;240241/* Throw away any unused bits remaining in bit buffer; */242/* include any full bytes in next_marker's count of discarded bytes */243cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;244entropy->bitstate.bits_left = 0;245246/* Advance past the RSTn marker */247if (! (*cinfo->marker->read_restart_marker) (cinfo))248return FALSE;249250/* Re-initialize DC predictions to 0 */251for (ci = 0; ci < cinfo->comps_in_scan; ci++)252entropy->saved.last_dc_val[ci] = 0;253/* Re-init EOB run count, too */254entropy->saved.EOBRUN = 0;255256/* Reset restart counter */257entropy->restarts_to_go = cinfo->restart_interval;258259/* Reset out-of-data flag, unless read_restart_marker left us smack up260* against a marker. In that case we will end up treating the next data261* segment as empty, and we can avoid producing bogus output pixels by262* leaving the flag set.263*/264if (cinfo->unread_marker == 0)265entropy->pub.insufficient_data = FALSE;266267return TRUE;268}269270271/*272* Huffman MCU decoding.273* Each of these routines decodes and returns one MCU's worth of274* Huffman-compressed coefficients.275* The coefficients are reordered from zigzag order into natural array order,276* but are not dequantized.277*278* The i'th block of the MCU is stored into the block pointed to by279* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.280*281* We return FALSE if data source requested suspension. In that case no282* changes have been made to permanent state. (Exception: some output283* coefficients may already have been assigned. This is harmless for284* spectral selection, since we'll just re-assign them on the next call.285* Successive approximation AC refinement has to be more careful, however.)286*/287288/*289* MCU decoding for DC initial scan (either spectral selection,290* or first pass of successive approximation).291*/292293METHODDEF(boolean)294decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)295{296phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;297int Al = cinfo->Al;298register int s, r;299int blkn, ci;300JBLOCKROW block;301BITREAD_STATE_VARS;302savable_state state;303d_derived_tbl * tbl;304jpeg_component_info * compptr;305306/* Process restart marker if needed; may have to suspend */307if (cinfo->restart_interval) {308if (entropy->restarts_to_go == 0)309if (! process_restart(cinfo))310return FALSE;311}312313/* If we've run out of data, just leave the MCU set to zeroes.314* This way, we return uniform gray for the remainder of the segment.315*/316if (! entropy->pub.insufficient_data) {317318/* Load up working state */319BITREAD_LOAD_STATE(cinfo,entropy->bitstate);320ASSIGN_STATE(state, entropy->saved);321322/* Outer loop handles each block in the MCU */323324for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {325block = MCU_data[blkn];326ci = cinfo->MCU_membership[blkn];327compptr = cinfo->cur_comp_info[ci];328tbl = entropy->derived_tbls[compptr->dc_tbl_no];329330/* Decode a single block's worth of coefficients */331332/* Section F.2.2.1: decode the DC coefficient difference */333HUFF_DECODE(s, br_state, tbl, return FALSE, label1);334if (s) {335CHECK_BIT_BUFFER(br_state, s, return FALSE);336r = GET_BITS(s);337s = HUFF_EXTEND(r, s);338}339340/* Convert DC difference to actual value, update last_dc_val */341s += state.last_dc_val[ci];342state.last_dc_val[ci] = s;343/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */344(*block)[0] = (JCOEF) (s << Al);345}346347/* Completed MCU, so update state */348BITREAD_SAVE_STATE(cinfo,entropy->bitstate);349ASSIGN_STATE(entropy->saved, state);350}351352/* Account for restart interval (no-op if not using restarts) */353entropy->restarts_to_go--;354355return TRUE;356}357358359/*360* MCU decoding for AC initial scan (either spectral selection,361* or first pass of successive approximation).362*/363364METHODDEF(boolean)365decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)366{367phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;368int Se = cinfo->Se;369int Al = cinfo->Al;370register int s, k, r;371unsigned int EOBRUN;372JBLOCKROW block;373BITREAD_STATE_VARS;374d_derived_tbl * tbl;375376/* Process restart marker if needed; may have to suspend */377if (cinfo->restart_interval) {378if (entropy->restarts_to_go == 0)379if (! process_restart(cinfo))380return FALSE;381}382383/* If we've run out of data, just leave the MCU set to zeroes.384* This way, we return uniform gray for the remainder of the segment.385*/386if (! entropy->pub.insufficient_data) {387388/* Load up working state.389* We can avoid loading/saving bitread state if in an EOB run.390*/391EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */392393/* There is always only one block per MCU */394395if (EOBRUN > 0) /* if it's a band of zeroes... */396EOBRUN--; /* ...process it now (we do nothing) */397else {398BITREAD_LOAD_STATE(cinfo,entropy->bitstate);399block = MCU_data[0];400tbl = entropy->ac_derived_tbl;401402for (k = cinfo->Ss; k <= Se; k++) {403HUFF_DECODE(s, br_state, tbl, return FALSE, label2);404r = s >> 4;405s &= 15;406if (s) {407k += r;408CHECK_BIT_BUFFER(br_state, s, return FALSE);409r = GET_BITS(s);410s = HUFF_EXTEND(r, s);411/* Scale and output coefficient in natural (dezigzagged) order */412(*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);413} else {414if (r == 15) { /* ZRL */415k += 15; /* skip 15 zeroes in band */416} else { /* EOBr, run length is 2^r + appended bits */417EOBRUN = 1 << r;418if (r) { /* EOBr, r > 0 */419CHECK_BIT_BUFFER(br_state, r, return FALSE);420r = GET_BITS(r);421EOBRUN += r;422}423EOBRUN--; /* this band is processed at this moment */424break; /* force end-of-band */425}426}427}428429BITREAD_SAVE_STATE(cinfo,entropy->bitstate);430}431432/* Completed MCU, so update state */433entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */434}435436/* Account for restart interval (no-op if not using restarts) */437entropy->restarts_to_go--;438439return TRUE;440}441442443/*444* MCU decoding for DC successive approximation refinement scan.445* Note: we assume such scans can be multi-component, although the spec446* is not very clear on the point.447*/448449METHODDEF(boolean)450decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)451{452phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;453int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */454int blkn;455JBLOCKROW block;456BITREAD_STATE_VARS;457458/* Process restart marker if needed; may have to suspend */459if (cinfo->restart_interval) {460if (entropy->restarts_to_go == 0)461if (! process_restart(cinfo))462return FALSE;463}464465/* Not worth the cycles to check insufficient_data here,466* since we will not change the data anyway if we read zeroes.467*/468469/* Load up working state */470BITREAD_LOAD_STATE(cinfo,entropy->bitstate);471472/* Outer loop handles each block in the MCU */473474for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {475block = MCU_data[blkn];476477/* Encoded data is simply the next bit of the two's-complement DC value */478CHECK_BIT_BUFFER(br_state, 1, return FALSE);479if (GET_BITS(1))480(*block)[0] |= p1;481/* Note: since we use |=, repeating the assignment later is safe */482}483484/* Completed MCU, so update state */485BITREAD_SAVE_STATE(cinfo,entropy->bitstate);486487/* Account for restart interval (no-op if not using restarts) */488entropy->restarts_to_go--;489490return TRUE;491}492493494/*495* MCU decoding for AC successive approximation refinement scan.496*/497498METHODDEF(boolean)499decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)500{501phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;502int Se = cinfo->Se;503int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */504int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */505register int s, k, r;506unsigned int EOBRUN;507JBLOCKROW block;508JCOEFPTR thiscoef;509BITREAD_STATE_VARS;510d_derived_tbl * tbl;511int num_newnz;512int newnz_pos[DCTSIZE2];513514/* Process restart marker if needed; may have to suspend */515if (cinfo->restart_interval) {516if (entropy->restarts_to_go == 0)517if (! process_restart(cinfo))518return FALSE;519}520521/* If we've run out of data, don't modify the MCU.522*/523if (! entropy->pub.insufficient_data) {524525/* Load up working state */526BITREAD_LOAD_STATE(cinfo,entropy->bitstate);527EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */528529/* There is always only one block per MCU */530block = MCU_data[0];531tbl = entropy->ac_derived_tbl;532533/* If we are forced to suspend, we must undo the assignments to any newly534* nonzero coefficients in the block, because otherwise we'd get confused535* next time about which coefficients were already nonzero.536* But we need not undo addition of bits to already-nonzero coefficients;537* instead, we can test the current bit to see if we already did it.538*/539num_newnz = 0;540541/* initialize coefficient loop counter to start of band */542k = cinfo->Ss;543544if (EOBRUN == 0) {545for (; k <= Se; k++) {546HUFF_DECODE(s, br_state, tbl, goto undoit, label3);547r = s >> 4;548s &= 15;549if (s) {550if (s != 1) /* size of new coef should always be 1 */551WARNMS(cinfo, JWRN_HUFF_BAD_CODE);552CHECK_BIT_BUFFER(br_state, 1, goto undoit);553if (GET_BITS(1))554s = p1; /* newly nonzero coef is positive */555else556s = m1; /* newly nonzero coef is negative */557} else {558if (r != 15) {559EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */560if (r) {561CHECK_BIT_BUFFER(br_state, r, goto undoit);562r = GET_BITS(r);563EOBRUN += r;564}565break; /* rest of block is handled by EOB logic */566}567/* note s = 0 for processing ZRL */568}569/* Advance over already-nonzero coefs and r still-zero coefs,570* appending correction bits to the nonzeroes. A correction bit is 1571* if the absolute value of the coefficient must be increased.572*/573do {574thiscoef = *block + jpeg_natural_order[k];575if (*thiscoef != 0) {576CHECK_BIT_BUFFER(br_state, 1, goto undoit);577if (GET_BITS(1)) {578if ((*thiscoef & p1) == 0) { /* do nothing if already set it */579if (*thiscoef >= 0)580*thiscoef += p1;581else582*thiscoef += m1;583}584}585} else {586if (--r < 0)587break; /* reached target zero coefficient */588}589k++;590} while (k <= Se);591if (s) {592int pos = jpeg_natural_order[k];593/* Output newly nonzero coefficient */594(*block)[pos] = (JCOEF) s;595/* Remember its position in case we have to suspend */596newnz_pos[num_newnz++] = pos;597}598}599}600601if (EOBRUN > 0) {602/* Scan any remaining coefficient positions after the end-of-band603* (the last newly nonzero coefficient, if any). Append a correction604* bit to each already-nonzero coefficient. A correction bit is 1605* if the absolute value of the coefficient must be increased.606*/607for (; k <= Se; k++) {608thiscoef = *block + jpeg_natural_order[k];609if (*thiscoef != 0) {610CHECK_BIT_BUFFER(br_state, 1, goto undoit);611if (GET_BITS(1)) {612if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */613if (*thiscoef >= 0)614*thiscoef += p1;615else616*thiscoef += m1;617}618}619}620}621/* Count one block completed in EOB run */622EOBRUN--;623}624625/* Completed MCU, so update state */626BITREAD_SAVE_STATE(cinfo,entropy->bitstate);627entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */628}629630/* Account for restart interval (no-op if not using restarts) */631entropy->restarts_to_go--;632633return TRUE;634635undoit:636/* Re-zero any output coefficients that we made newly nonzero */637while (num_newnz > 0)638(*block)[newnz_pos[--num_newnz]] = 0;639640return FALSE;641}642643644/*645* Module initialization routine for progressive Huffman entropy decoding.646*/647648GLOBAL(void)649jinit_phuff_decoder (j_decompress_ptr cinfo)650{651phuff_entropy_ptr entropy;652int *coef_bit_ptr;653int ci, i;654655entropy = (phuff_entropy_ptr)656(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,657SIZEOF(phuff_entropy_decoder));658cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;659entropy->pub.start_pass = start_pass_phuff_decoder;660661/* Mark derived tables unallocated */662for (i = 0; i < NUM_HUFF_TBLS; i++) {663entropy->derived_tbls[i] = NULL;664}665666/* Create progression status table */667cinfo->coef_bits = (int (*)[DCTSIZE2])668(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,669cinfo->num_components*DCTSIZE2*SIZEOF(int));670coef_bit_ptr = & cinfo->coef_bits[0][0];671for (ci = 0; ci < cinfo->num_components; ci++)672for (i = 0; i < DCTSIZE2; i++)673*coef_bit_ptr++ = -1;674}675676#endif /* D_PROGRESSIVE_SUPPORTED */677678679