Path: blob/master/src/java.desktop/share/native/libjavajpeg/jdhuff.c
41149 views
/*1* reserved comment block2* DO NOT REMOVE OR ALTER!3*/4/*5* jdhuff.c6*7* Copyright (C) 1991-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.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 jdphuff.c */242526/*27* Expanded entropy decoder object for Huffman decoding.28*29* The savable_state subrecord contains fields that change within an MCU,30* but must not be updated permanently until we complete the MCU.31*/3233typedef struct {34int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */35} savable_state;3637/* This macro is to work around compilers with missing or broken38* structure assignment. You'll need to fix this code if you have39* such a compiler and you change MAX_COMPS_IN_SCAN.40*/4142#ifndef NO_STRUCT_ASSIGN43#define ASSIGN_STATE(dest,src) ((dest) = (src))44#else45#if MAX_COMPS_IN_SCAN == 446#define ASSIGN_STATE(dest,src) \47((dest).last_dc_val[0] = (src).last_dc_val[0], \48(dest).last_dc_val[1] = (src).last_dc_val[1], \49(dest).last_dc_val[2] = (src).last_dc_val[2], \50(dest).last_dc_val[3] = (src).last_dc_val[3])51#endif52#endif535455typedef struct {56struct jpeg_entropy_decoder pub; /* public fields */5758/* These fields are loaded into local variables at start of each MCU.59* In case of suspension, we exit WITHOUT updating them.60*/61bitread_perm_state bitstate; /* Bit buffer at start of MCU */62savable_state saved; /* Other state at start of MCU */6364/* These fields are NOT loaded into local working state. */65unsigned int restarts_to_go; /* MCUs left in this restart interval */6667/* Pointers to derived tables (these workspaces have image lifespan) */68d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];69d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];7071/* Precalculated info set up by start_pass for use in decode_mcu: */7273/* Pointers to derived tables to be used for each block within an MCU */74d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];75d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];76/* Whether we care about the DC and AC coefficient values for each block */77boolean dc_needed[D_MAX_BLOCKS_IN_MCU];78boolean ac_needed[D_MAX_BLOCKS_IN_MCU];79} huff_entropy_decoder;8081typedef huff_entropy_decoder * huff_entropy_ptr;828384/*85* Initialize for a Huffman-compressed scan.86*/8788METHODDEF(void)89start_pass_huff_decoder (j_decompress_ptr cinfo)90{91huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;92int ci, blkn, dctbl, actbl;93jpeg_component_info * compptr;9495/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.96* This ought to be an error condition, but we make it a warning because97* there are some baseline files out there with all zeroes in these bytes.98*/99if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||100cinfo->Ah != 0 || cinfo->Al != 0)101WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);102103for (ci = 0; ci < cinfo->comps_in_scan; ci++) {104compptr = cinfo->cur_comp_info[ci];105dctbl = compptr->dc_tbl_no;106actbl = compptr->ac_tbl_no;107/* Compute derived values for Huffman tables */108/* We may do this more than once for a table, but it's not expensive */109jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,110& entropy->dc_derived_tbls[dctbl]);111jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,112& entropy->ac_derived_tbls[actbl]);113/* Initialize DC predictions to 0 */114entropy->saved.last_dc_val[ci] = 0;115}116117/* Precalculate decoding info for each block in an MCU of this scan */118for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {119ci = cinfo->MCU_membership[blkn];120compptr = cinfo->cur_comp_info[ci];121/* Precalculate which table to use for each block */122entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];123entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];124/* Decide whether we really care about the coefficient values */125if (compptr->component_needed) {126entropy->dc_needed[blkn] = TRUE;127/* we don't need the ACs if producing a 1/8th-size image */128entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);129} else {130entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;131}132}133134/* Initialize bitread state variables */135entropy->bitstate.bits_left = 0;136entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */137entropy->pub.insufficient_data = FALSE;138139/* Initialize restart counter */140entropy->restarts_to_go = cinfo->restart_interval;141}142143144/*145* Compute the derived values for a Huffman table.146* This routine also performs some validation checks on the table.147*148* Note this is also used by jdphuff.c.149*/150151GLOBAL(void)152jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,153d_derived_tbl ** pdtbl)154{155JHUFF_TBL *htbl;156d_derived_tbl *dtbl;157int p, i, l, si, numsymbols;158int lookbits, ctr;159char huffsize[257];160unsigned int huffcode[257];161unsigned int code;162163/* Note that huffsize[] and huffcode[] are filled in code-length order,164* paralleling the order of the symbols themselves in htbl->huffval[].165*/166167/* Find the input Huffman table */168if (tblno < 0 || tblno >= NUM_HUFF_TBLS)169ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);170htbl =171isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];172if (htbl == NULL)173ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);174175/* Allocate a workspace if we haven't already done so. */176if (*pdtbl == NULL)177*pdtbl = (d_derived_tbl *)178(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,179SIZEOF(d_derived_tbl));180dtbl = *pdtbl;181dtbl->pub = htbl; /* fill in back link */182183/* Figure C.1: make table of Huffman code length for each symbol */184185p = 0;186for (l = 1; l <= 16; l++) {187i = (int) htbl->bits[l];188if (i < 0 || p + i > 256) /* protect against table overrun */189ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);190while (i--)191huffsize[p++] = (char) l;192}193huffsize[p] = 0;194numsymbols = p;195196/* Figure C.2: generate the codes themselves */197/* We also validate that the counts represent a legal Huffman code tree. */198199code = 0;200si = huffsize[0];201p = 0;202while (huffsize[p]) {203while (((int) huffsize[p]) == si) {204huffcode[p++] = code;205code++;206}207/* code is now 1 more than the last code used for codelength si; but208* it must still fit in si bits, since no code is allowed to be all ones.209*/210if (((INT32) code) >= (((INT32) 1) << si))211ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);212code <<= 1;213si++;214}215216/* Figure F.15: generate decoding tables for bit-sequential decoding */217218p = 0;219for (l = 1; l <= 16; l++) {220if (htbl->bits[l]) {221/* valoffset[l] = huffval[] index of 1st symbol of code length l,222* minus the minimum code of length l223*/224dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];225p += htbl->bits[l];226dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */227} else {228dtbl->maxcode[l] = -1; /* -1 if no codes of this length */229}230}231dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */232233/* Compute lookahead tables to speed up decoding.234* First we set all the table entries to 0, indicating "too long";235* then we iterate through the Huffman codes that are short enough and236* fill in all the entries that correspond to bit sequences starting237* with that code.238*/239240MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));241242p = 0;243for (l = 1; l <= HUFF_LOOKAHEAD; l++) {244for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {245/* l = current code's length, p = its index in huffcode[] & huffval[]. */246/* Generate left-justified code followed by all possible bit sequences */247lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);248for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {249dtbl->look_nbits[lookbits] = l;250dtbl->look_sym[lookbits] = htbl->huffval[p];251lookbits++;252}253}254}255256/* Validate symbols as being reasonable.257* For AC tables, we make no check, but accept all byte values 0..255.258* For DC tables, we require the symbols to be in range 0..15.259* (Tighter bounds could be applied depending on the data depth and mode,260* but this is sufficient to ensure safe decoding.)261*/262if (isDC) {263for (i = 0; i < numsymbols; i++) {264int sym = htbl->huffval[i];265if (sym < 0 || sym > 15)266ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);267}268}269}270271272/*273* Out-of-line code for bit fetching (shared with jdphuff.c).274* See jdhuff.h for info about usage.275* Note: current values of get_buffer and bits_left are passed as parameters,276* but are returned in the corresponding fields of the state struct.277*278* On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width279* of get_buffer to be used. (On machines with wider words, an even larger280* buffer could be used.) However, on some machines 32-bit shifts are281* quite slow and take time proportional to the number of places shifted.282* (This is true with most PC compilers, for instance.) In this case it may283* be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the284* average shift distance at the cost of more calls to jpeg_fill_bit_buffer.285*/286287#ifdef SLOW_SHIFT_32288#define MIN_GET_BITS 15 /* minimum allowable value */289#else290#define MIN_GET_BITS (BIT_BUF_SIZE-7)291#endif292293294GLOBAL(boolean)295jpeg_fill_bit_buffer (bitread_working_state * state,296register bit_buf_type get_buffer, register int bits_left,297int nbits)298/* Load up the bit buffer to a depth of at least nbits */299{300/* Copy heavily used state fields into locals (hopefully registers) */301register const JOCTET * next_input_byte = state->next_input_byte;302register size_t bytes_in_buffer = state->bytes_in_buffer;303j_decompress_ptr cinfo = state->cinfo;304305/* Attempt to load at least MIN_GET_BITS bits into get_buffer. */306/* (It is assumed that no request will be for more than that many bits.) */307/* We fail to do so only if we hit a marker or are forced to suspend. */308309if (cinfo->unread_marker == 0) { /* cannot advance past a marker */310while (bits_left < MIN_GET_BITS) {311register int c;312313/* Attempt to read a byte */314if (bytes_in_buffer == 0) {315if (! (*cinfo->src->fill_input_buffer) (cinfo))316return FALSE;317next_input_byte = cinfo->src->next_input_byte;318bytes_in_buffer = cinfo->src->bytes_in_buffer;319}320bytes_in_buffer--;321c = GETJOCTET(*next_input_byte++);322323/* If it's 0xFF, check and discard stuffed zero byte */324if (c == 0xFF) {325/* Loop here to discard any padding FF's on terminating marker,326* so that we can save a valid unread_marker value. NOTE: we will327* accept multiple FF's followed by a 0 as meaning a single FF data328* byte. This data pattern is not valid according to the standard.329*/330do {331if (bytes_in_buffer == 0) {332if (! (*cinfo->src->fill_input_buffer) (cinfo))333return FALSE;334next_input_byte = cinfo->src->next_input_byte;335bytes_in_buffer = cinfo->src->bytes_in_buffer;336}337bytes_in_buffer--;338c = GETJOCTET(*next_input_byte++);339} while (c == 0xFF);340341if (c == 0) {342/* Found FF/00, which represents an FF data byte */343c = 0xFF;344} else {345/* Oops, it's actually a marker indicating end of compressed data.346* Save the marker code for later use.347* Fine point: it might appear that we should save the marker into348* bitread working state, not straight into permanent state. But349* once we have hit a marker, we cannot need to suspend within the350* current MCU, because we will read no more bytes from the data351* source. So it is OK to update permanent state right away.352*/353cinfo->unread_marker = c;354/* See if we need to insert some fake zero bits. */355goto no_more_bytes;356}357}358359/* OK, load c into get_buffer */360get_buffer = (get_buffer << 8) | c;361bits_left += 8;362} /* end while */363} else {364no_more_bytes:365/* We get here if we've read the marker that terminates the compressed366* data segment. There should be enough bits in the buffer register367* to satisfy the request; if so, no problem.368*/369if (nbits > bits_left) {370/* Uh-oh. Report corrupted data to user and stuff zeroes into371* the data stream, so that we can produce some kind of image.372* We use a nonvolatile flag to ensure that only one warning message373* appears per data segment.374*/375if (! cinfo->entropy->insufficient_data) {376WARNMS(cinfo, JWRN_HIT_MARKER);377cinfo->entropy->insufficient_data = TRUE;378}379/* Fill the buffer with zero bits */380get_buffer <<= MIN_GET_BITS - bits_left;381bits_left = MIN_GET_BITS;382}383}384385/* Unload the local registers */386state->next_input_byte = next_input_byte;387state->bytes_in_buffer = bytes_in_buffer;388state->get_buffer = get_buffer;389state->bits_left = bits_left;390391return TRUE;392}393394395/*396* Out-of-line code for Huffman code decoding.397* See jdhuff.h for info about usage.398*/399400GLOBAL(int)401jpeg_huff_decode (bitread_working_state * state,402register bit_buf_type get_buffer, register int bits_left,403d_derived_tbl * htbl, int min_bits)404{405register int l = min_bits;406register INT32 code;407408/* HUFF_DECODE has determined that the code is at least min_bits */409/* bits long, so fetch that many bits in one swoop. */410411CHECK_BIT_BUFFER(*state, l, return -1);412code = GET_BITS(l);413414/* Collect the rest of the Huffman code one bit at a time. */415/* This is per Figure F.16 in the JPEG spec. */416417while (code > htbl->maxcode[l]) {418code <<= 1;419CHECK_BIT_BUFFER(*state, 1, return -1);420code |= GET_BITS(1);421l++;422}423424/* Unload the local registers */425state->get_buffer = get_buffer;426state->bits_left = bits_left;427428/* With garbage input we may reach the sentinel value l = 17. */429430if (l > 16) {431WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);432return 0; /* fake a zero as the safest result */433}434435return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];436}437438439/*440* Figure F.12: extend sign bit.441* On some machines, a shift and add will be faster than a table lookup.442*/443444#ifdef AVOID_TABLES445446#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))447448#else449450#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))451452static const int extend_test[16] = /* entry n is 2**(n-1) */453{ 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,4540x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };455456static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */457{ 0,458(int)(((unsigned)(~0)<<1) + 1), (int)(((unsigned)(~0)<<2) + 1),459(int)(((unsigned)(~0)<<3) + 1), (int)(((unsigned)(~0)<<4) + 1),460(int)(((unsigned)(~0)<<5) + 1), (int)(((unsigned)(~0)<<6) + 1),461(int)(((unsigned)(~0)<<7) + 1), (int)(((unsigned)(~0)<<8) + 1),462(int)(((unsigned)(~0)<<9) + 1), (int)(((unsigned)(~0)<<10) + 1),463(int)(((unsigned)(~0)<<11) + 1), (int)(((unsigned)(~0)<<12) + 1),464(int)(((unsigned)(~0)<<13) + 1), (int)(((unsigned)(~0)<<14) + 1),465(int)(((unsigned)(~0)<<15) + 1) };466467#endif /* AVOID_TABLES */468469470/*471* Check for a restart marker & resynchronize decoder.472* Returns FALSE if must suspend.473*/474475LOCAL(boolean)476process_restart (j_decompress_ptr cinfo)477{478huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;479int ci;480481/* Throw away any unused bits remaining in bit buffer; */482/* include any full bytes in next_marker's count of discarded bytes */483cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;484entropy->bitstate.bits_left = 0;485486/* Advance past the RSTn marker */487if (! (*cinfo->marker->read_restart_marker) (cinfo))488return FALSE;489490/* Re-initialize DC predictions to 0 */491for (ci = 0; ci < cinfo->comps_in_scan; ci++)492entropy->saved.last_dc_val[ci] = 0;493494/* Reset restart counter */495entropy->restarts_to_go = cinfo->restart_interval;496497/* Reset out-of-data flag, unless read_restart_marker left us smack up498* against a marker. In that case we will end up treating the next data499* segment as empty, and we can avoid producing bogus output pixels by500* leaving the flag set.501*/502if (cinfo->unread_marker == 0)503entropy->pub.insufficient_data = FALSE;504505return TRUE;506}507508509/*510* Decode and return one MCU's worth of Huffman-compressed coefficients.511* The coefficients are reordered from zigzag order into natural array order,512* but are not dequantized.513*514* The i'th block of the MCU is stored into the block pointed to by515* MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.516* (Wholesale zeroing is usually a little faster than retail...)517*518* Returns FALSE if data source requested suspension. In that case no519* changes have been made to permanent state. (Exception: some output520* coefficients may already have been assigned. This is harmless for521* this module, since we'll just re-assign them on the next call.)522*/523524METHODDEF(boolean)525decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)526{527huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;528int blkn;529BITREAD_STATE_VARS;530savable_state state;531532/* Process restart marker if needed; may have to suspend */533if (cinfo->restart_interval) {534if (entropy->restarts_to_go == 0)535if (! process_restart(cinfo))536return FALSE;537}538539/* If we've run out of data, just leave the MCU set to zeroes.540* This way, we return uniform gray for the remainder of the segment.541*/542if (! entropy->pub.insufficient_data) {543544/* Load up working state */545BITREAD_LOAD_STATE(cinfo,entropy->bitstate);546ASSIGN_STATE(state, entropy->saved);547548/* Outer loop handles each block in the MCU */549550for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {551JBLOCKROW block = MCU_data[blkn];552d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];553d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];554register int s, k, r;555556/* Decode a single block's worth of coefficients */557558/* Section F.2.2.1: decode the DC coefficient difference */559HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);560if (s) {561CHECK_BIT_BUFFER(br_state, s, return FALSE);562r = GET_BITS(s);563s = HUFF_EXTEND(r, s);564}565566if (entropy->dc_needed[blkn]) {567/* Convert DC difference to actual value, update last_dc_val */568int ci = cinfo->MCU_membership[blkn];569s += state.last_dc_val[ci];570state.last_dc_val[ci] = s;571/* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */572(*block)[0] = (JCOEF) s;573}574575if (entropy->ac_needed[blkn]) {576577/* Section F.2.2.2: decode the AC coefficients */578/* Since zeroes are skipped, output area must be cleared beforehand */579for (k = 1; k < DCTSIZE2; k++) {580HUFF_DECODE(s, br_state, actbl, return FALSE, label2);581582r = s >> 4;583s &= 15;584585if (s) {586k += r;587CHECK_BIT_BUFFER(br_state, s, return FALSE);588r = GET_BITS(s);589s = HUFF_EXTEND(r, s);590/* Output coefficient in natural (dezigzagged) order.591* Note: the extra entries in jpeg_natural_order[] will save us592* if k >= DCTSIZE2, which could happen if the data is corrupted.593*/594(*block)[jpeg_natural_order[k]] = (JCOEF) s;595} else {596if (r != 15)597break;598k += 15;599}600}601602} else {603604/* Section F.2.2.2: decode the AC coefficients */605/* In this path we just discard the values */606for (k = 1; k < DCTSIZE2; k++) {607HUFF_DECODE(s, br_state, actbl, return FALSE, label3);608609r = s >> 4;610s &= 15;611612if (s) {613k += r;614CHECK_BIT_BUFFER(br_state, s, return FALSE);615DROP_BITS(s);616} else {617if (r != 15)618break;619k += 15;620}621}622623}624}625626/* Completed MCU, so update state */627BITREAD_SAVE_STATE(cinfo,entropy->bitstate);628ASSIGN_STATE(entropy->saved, state);629}630631/* Account for restart interval (no-op if not using restarts) */632entropy->restarts_to_go--;633634return TRUE;635}636637638/*639* Module initialization routine for Huffman entropy decoding.640*/641642GLOBAL(void)643jinit_huff_decoder (j_decompress_ptr cinfo)644{645huff_entropy_ptr entropy;646int i;647648entropy = (huff_entropy_ptr)649(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,650SIZEOF(huff_entropy_decoder));651cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;652entropy->pub.start_pass = start_pass_huff_decoder;653entropy->pub.decode_mcu = decode_mcu;654655/* Mark tables unallocated */656for (i = 0; i < NUM_HUFF_TBLS; i++) {657entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;658}659}660661662