/*1* jdhuff.c2*3* Copyright (C) 1991-1997, Thomas G. Lane.4* Modified 2006-2013 by Guido Vollbeding.5* This file is part of the Independent JPEG Group's software.6* For conditions of distribution and use, see the accompanying README file.7*8* This file contains Huffman entropy decoding routines.9* Both sequential and progressive modes are supported in this single module.10*11* Much of the complexity here has to do with supporting input suspension.12* If the data source module demands suspension, we want to be able to back13* up to the start of the current MCU. To do this, we copy state variables14* into local working storage, and update them back to the permanent15* storage only upon successful completion of an MCU.16*/1718#define JPEG_INTERNALS19#include "jinclude.h"20#include "jpeglib.h"212223/* Derived data constructed for each Huffman table */2425#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */2627typedef struct {28/* Basic tables: (element [0] of each array is unused) */29INT32 maxcode[18]; /* largest code of length k (-1 if none) */30/* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */31INT32 valoffset[17]; /* huffval[] offset for codes of length k */32/* valoffset[k] = huffval[] index of 1st symbol of code length k, less33* the smallest code of length k; so given a code of length k, the34* corresponding symbol is huffval[code + valoffset[k]]35*/3637/* Link to public Huffman table (needed only in jpeg_huff_decode) */38JHUFF_TBL *pub;3940/* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of41* the input data stream. If the next Huffman code is no more42* than HUFF_LOOKAHEAD bits long, we can obtain its length and43* the corresponding symbol directly from these tables.44*/45int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */46UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */47} d_derived_tbl;484950/*51* Fetching the next N bits from the input stream is a time-critical operation52* for the Huffman decoders. We implement it with a combination of inline53* macros and out-of-line subroutines. Note that N (the number of bits54* demanded at one time) never exceeds 15 for JPEG use.55*56* We read source bytes into get_buffer and dole out bits as needed.57* If get_buffer already contains enough bits, they are fetched in-line58* by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough59* bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer60* as full as possible (not just to the number of bits needed; this61* prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).62* Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.63* On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains64* at least the requested number of bits --- dummy zeroes are inserted if65* necessary.66*/6768typedef INT32 bit_buf_type; /* type of bit-extraction buffer */69#define BIT_BUF_SIZE 32 /* size of buffer in bits */7071/* If long is > 32 bits on your machine, and shifting/masking longs is72* reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE73* appropriately should be a win. Unfortunately we can't define the size74* with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)75* because not all machines measure sizeof in 8-bit bytes.76*/7778typedef struct { /* Bitreading state saved across MCUs */79bit_buf_type get_buffer; /* current bit-extraction buffer */80int bits_left; /* # of unused bits in it */81} bitread_perm_state;8283typedef struct { /* Bitreading working state within an MCU */84/* Current data source location */85/* We need a copy, rather than munging the original, in case of suspension */86const JOCTET * next_input_byte; /* => next byte to read from source */87size_t bytes_in_buffer; /* # of bytes remaining in source buffer */88/* Bit input buffer --- note these values are kept in register variables,89* not in this struct, inside the inner loops.90*/91bit_buf_type get_buffer; /* current bit-extraction buffer */92int bits_left; /* # of unused bits in it */93/* Pointer needed by jpeg_fill_bit_buffer. */94j_decompress_ptr cinfo; /* back link to decompress master record */95} bitread_working_state;9697/* Macros to declare and load/save bitread local variables. */98#define BITREAD_STATE_VARS \99register bit_buf_type get_buffer; \100register int bits_left; \101bitread_working_state br_state102103#define BITREAD_LOAD_STATE(cinfop,permstate) \104br_state.cinfo = cinfop; \105br_state.next_input_byte = cinfop->src->next_input_byte; \106br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \107get_buffer = permstate.get_buffer; \108bits_left = permstate.bits_left;109110#define BITREAD_SAVE_STATE(cinfop,permstate) \111cinfop->src->next_input_byte = br_state.next_input_byte; \112cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \113permstate.get_buffer = get_buffer; \114permstate.bits_left = bits_left115116/*117* These macros provide the in-line portion of bit fetching.118* Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer119* before using GET_BITS, PEEK_BITS, or DROP_BITS.120* The variables get_buffer and bits_left are assumed to be locals,121* but the state struct might not be (jpeg_huff_decode needs this).122* CHECK_BIT_BUFFER(state,n,action);123* Ensure there are N bits in get_buffer; if suspend, take action.124* val = GET_BITS(n);125* Fetch next N bits.126* val = PEEK_BITS(n);127* Fetch next N bits without removing them from the buffer.128* DROP_BITS(n);129* Discard next N bits.130* The value N should be a simple variable, not an expression, because it131* is evaluated multiple times.132*/133134#define CHECK_BIT_BUFFER(state,nbits,action) \135{ if (bits_left < (nbits)) { \136if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \137{ action; } \138get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }139140#define GET_BITS(nbits) \141(((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits))142143#define PEEK_BITS(nbits) \144(((int) (get_buffer >> (bits_left - (nbits)))) & BIT_MASK(nbits))145146#define DROP_BITS(nbits) \147(bits_left -= (nbits))148149150/*151* Code for extracting next Huffman-coded symbol from input bit stream.152* Again, this is time-critical and we make the main paths be macros.153*154* We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits155* without looping. Usually, more than 95% of the Huffman codes will be 8156* or fewer bits long. The few overlength codes are handled with a loop,157* which need not be inline code.158*159* Notes about the HUFF_DECODE macro:160* 1. Near the end of the data segment, we may fail to get enough bits161* for a lookahead. In that case, we do it the hard way.162* 2. If the lookahead table contains no entry, the next code must be163* more than HUFF_LOOKAHEAD bits long.164* 3. jpeg_huff_decode returns -1 if forced to suspend.165*/166167#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \168{ register int nb, look; \169if (bits_left < HUFF_LOOKAHEAD) { \170if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \171get_buffer = state.get_buffer; bits_left = state.bits_left; \172if (bits_left < HUFF_LOOKAHEAD) { \173nb = 1; goto slowlabel; \174} \175} \176look = PEEK_BITS(HUFF_LOOKAHEAD); \177if ((nb = htbl->look_nbits[look]) != 0) { \178DROP_BITS(nb); \179result = htbl->look_sym[look]; \180} else { \181nb = HUFF_LOOKAHEAD+1; \182slowlabel: \183if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \184{ failaction; } \185get_buffer = state.get_buffer; bits_left = state.bits_left; \186} \187}188189190/*191* Expanded entropy decoder object for Huffman decoding.192*193* The savable_state subrecord contains fields that change within an MCU,194* but must not be updated permanently until we complete the MCU.195*/196197typedef struct {198unsigned int EOBRUN; /* remaining EOBs in EOBRUN */199int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */200} savable_state;201202/* This macro is to work around compilers with missing or broken203* structure assignment. You'll need to fix this code if you have204* such a compiler and you change MAX_COMPS_IN_SCAN.205*/206207#ifndef NO_STRUCT_ASSIGN208#define ASSIGN_STATE(dest,src) ((dest) = (src))209#else210#if MAX_COMPS_IN_SCAN == 4211#define ASSIGN_STATE(dest,src) \212((dest).EOBRUN = (src).EOBRUN, \213(dest).last_dc_val[0] = (src).last_dc_val[0], \214(dest).last_dc_val[1] = (src).last_dc_val[1], \215(dest).last_dc_val[2] = (src).last_dc_val[2], \216(dest).last_dc_val[3] = (src).last_dc_val[3])217#endif218#endif219220221typedef struct {222struct jpeg_entropy_decoder pub; /* public fields */223224/* These fields are loaded into local variables at start of each MCU.225* In case of suspension, we exit WITHOUT updating them.226*/227bitread_perm_state bitstate; /* Bit buffer at start of MCU */228savable_state saved; /* Other state at start of MCU */229230/* These fields are NOT loaded into local working state. */231boolean insufficient_data; /* set TRUE after emitting warning */232unsigned int restarts_to_go; /* MCUs left in this restart interval */233234/* Following two fields used only in progressive mode */235236/* Pointers to derived tables (these workspaces have image lifespan) */237d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];238239d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */240241/* Following fields used only in sequential mode */242243/* Pointers to derived tables (these workspaces have image lifespan) */244d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];245d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];246247/* Precalculated info set up by start_pass for use in decode_mcu: */248249/* Pointers to derived tables to be used for each block within an MCU */250d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];251d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];252/* Whether we care about the DC and AC coefficient values for each block */253int coef_limit[D_MAX_BLOCKS_IN_MCU];254} huff_entropy_decoder;255256typedef huff_entropy_decoder * huff_entropy_ptr;257258259static const int jpeg_zigzag_order[8][8] = {260{ 0, 1, 5, 6, 14, 15, 27, 28 },261{ 2, 4, 7, 13, 16, 26, 29, 42 },262{ 3, 8, 12, 17, 25, 30, 41, 43 },263{ 9, 11, 18, 24, 31, 40, 44, 53 },264{ 10, 19, 23, 32, 39, 45, 52, 54 },265{ 20, 22, 33, 38, 46, 51, 55, 60 },266{ 21, 34, 37, 47, 50, 56, 59, 61 },267{ 35, 36, 48, 49, 57, 58, 62, 63 }268};269270static const int jpeg_zigzag_order7[7][7] = {271{ 0, 1, 5, 6, 14, 15, 27 },272{ 2, 4, 7, 13, 16, 26, 28 },273{ 3, 8, 12, 17, 25, 29, 38 },274{ 9, 11, 18, 24, 30, 37, 39 },275{ 10, 19, 23, 31, 36, 40, 45 },276{ 20, 22, 32, 35, 41, 44, 46 },277{ 21, 33, 34, 42, 43, 47, 48 }278};279280static const int jpeg_zigzag_order6[6][6] = {281{ 0, 1, 5, 6, 14, 15 },282{ 2, 4, 7, 13, 16, 25 },283{ 3, 8, 12, 17, 24, 26 },284{ 9, 11, 18, 23, 27, 32 },285{ 10, 19, 22, 28, 31, 33 },286{ 20, 21, 29, 30, 34, 35 }287};288289static const int jpeg_zigzag_order5[5][5] = {290{ 0, 1, 5, 6, 14 },291{ 2, 4, 7, 13, 15 },292{ 3, 8, 12, 16, 21 },293{ 9, 11, 17, 20, 22 },294{ 10, 18, 19, 23, 24 }295};296297static const int jpeg_zigzag_order4[4][4] = {298{ 0, 1, 5, 6 },299{ 2, 4, 7, 12 },300{ 3, 8, 11, 13 },301{ 9, 10, 14, 15 }302};303304static const int jpeg_zigzag_order3[3][3] = {305{ 0, 1, 5 },306{ 2, 4, 6 },307{ 3, 7, 8 }308};309310static const int jpeg_zigzag_order2[2][2] = {311{ 0, 1 },312{ 2, 3 }313};314315316/*317* Compute the derived values for a Huffman table.318* This routine also performs some validation checks on the table.319*/320321LOCAL(void)322jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,323d_derived_tbl ** pdtbl)324{325JHUFF_TBL *htbl;326d_derived_tbl *dtbl;327int p, i, l, si, numsymbols;328int lookbits, ctr;329char huffsize[257];330unsigned int huffcode[257];331unsigned int code;332333/* Note that huffsize[] and huffcode[] are filled in code-length order,334* paralleling the order of the symbols themselves in htbl->huffval[].335*/336337/* Find the input Huffman table */338if (tblno < 0 || tblno >= NUM_HUFF_TBLS)339ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);340htbl =341isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];342if (htbl == NULL)343ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);344345/* Allocate a workspace if we haven't already done so. */346if (*pdtbl == NULL)347*pdtbl = (d_derived_tbl *)348(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,349SIZEOF(d_derived_tbl));350dtbl = *pdtbl;351dtbl->pub = htbl; /* fill in back link */352353/* Figure C.1: make table of Huffman code length for each symbol */354355p = 0;356for (l = 1; l <= 16; l++) {357i = (int) htbl->bits[l];358if (i < 0 || p + i > 256) /* protect against table overrun */359ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);360while (i--)361huffsize[p++] = (char) l;362}363huffsize[p] = 0;364numsymbols = p;365366/* Figure C.2: generate the codes themselves */367/* We also validate that the counts represent a legal Huffman code tree. */368369code = 0;370si = huffsize[0];371p = 0;372while (huffsize[p]) {373while (((int) huffsize[p]) == si) {374huffcode[p++] = code;375code++;376}377/* code is now 1 more than the last code used for codelength si; but378* it must still fit in si bits, since no code is allowed to be all ones.379*/380if (((INT32) code) >= (((INT32) 1) << si))381ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);382code <<= 1;383si++;384}385386/* Figure F.15: generate decoding tables for bit-sequential decoding */387388p = 0;389for (l = 1; l <= 16; l++) {390if (htbl->bits[l]) {391/* valoffset[l] = huffval[] index of 1st symbol of code length l,392* minus the minimum code of length l393*/394dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];395p += htbl->bits[l];396dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */397} else {398dtbl->maxcode[l] = -1; /* -1 if no codes of this length */399}400}401dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */402403/* Compute lookahead tables to speed up decoding.404* First we set all the table entries to 0, indicating "too long";405* then we iterate through the Huffman codes that are short enough and406* fill in all the entries that correspond to bit sequences starting407* with that code.408*/409410MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));411412p = 0;413for (l = 1; l <= HUFF_LOOKAHEAD; l++) {414for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {415/* l = current code's length, p = its index in huffcode[] & huffval[]. */416/* Generate left-justified code followed by all possible bit sequences */417lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);418for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {419dtbl->look_nbits[lookbits] = l;420dtbl->look_sym[lookbits] = htbl->huffval[p];421lookbits++;422}423}424}425426/* Validate symbols as being reasonable.427* For AC tables, we make no check, but accept all byte values 0..255.428* For DC tables, we require the symbols to be in range 0..15.429* (Tighter bounds could be applied depending on the data depth and mode,430* but this is sufficient to ensure safe decoding.)431*/432if (isDC) {433for (i = 0; i < numsymbols; i++) {434int sym = htbl->huffval[i];435if (sym < 0 || sym > 15)436ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);437}438}439}440441442/*443* Out-of-line code for bit fetching.444* Note: current values of get_buffer and bits_left are passed as parameters,445* but are returned in the corresponding fields of the state struct.446*447* On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width448* of get_buffer to be used. (On machines with wider words, an even larger449* buffer could be used.) However, on some machines 32-bit shifts are450* quite slow and take time proportional to the number of places shifted.451* (This is true with most PC compilers, for instance.) In this case it may452* be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the453* average shift distance at the cost of more calls to jpeg_fill_bit_buffer.454*/455456#ifdef SLOW_SHIFT_32457#define MIN_GET_BITS 15 /* minimum allowable value */458#else459#define MIN_GET_BITS (BIT_BUF_SIZE-7)460#endif461462463LOCAL(boolean)464jpeg_fill_bit_buffer (bitread_working_state * state,465register bit_buf_type get_buffer, register int bits_left,466int nbits)467/* Load up the bit buffer to a depth of at least nbits */468{469/* Copy heavily used state fields into locals (hopefully registers) */470register const JOCTET * next_input_byte = state->next_input_byte;471register size_t bytes_in_buffer = state->bytes_in_buffer;472j_decompress_ptr cinfo = state->cinfo;473474/* Attempt to load at least MIN_GET_BITS bits into get_buffer. */475/* (It is assumed that no request will be for more than that many bits.) */476/* We fail to do so only if we hit a marker or are forced to suspend. */477478if (cinfo->unread_marker == 0) { /* cannot advance past a marker */479while (bits_left < MIN_GET_BITS) {480register int c;481482/* Attempt to read a byte */483if (bytes_in_buffer == 0) {484if (! (*cinfo->src->fill_input_buffer) (cinfo))485return FALSE;486next_input_byte = cinfo->src->next_input_byte;487bytes_in_buffer = cinfo->src->bytes_in_buffer;488}489bytes_in_buffer--;490c = GETJOCTET(*next_input_byte++);491492/* If it's 0xFF, check and discard stuffed zero byte */493if (c == 0xFF) {494/* Loop here to discard any padding FF's on terminating marker,495* so that we can save a valid unread_marker value. NOTE: we will496* accept multiple FF's followed by a 0 as meaning a single FF data497* byte. This data pattern is not valid according to the standard.498*/499do {500if (bytes_in_buffer == 0) {501if (! (*cinfo->src->fill_input_buffer) (cinfo))502return FALSE;503next_input_byte = cinfo->src->next_input_byte;504bytes_in_buffer = cinfo->src->bytes_in_buffer;505}506bytes_in_buffer--;507c = GETJOCTET(*next_input_byte++);508} while (c == 0xFF);509510if (c == 0) {511/* Found FF/00, which represents an FF data byte */512c = 0xFF;513} else {514/* Oops, it's actually a marker indicating end of compressed data.515* Save the marker code for later use.516* Fine point: it might appear that we should save the marker into517* bitread working state, not straight into permanent state. But518* once we have hit a marker, we cannot need to suspend within the519* current MCU, because we will read no more bytes from the data520* source. So it is OK to update permanent state right away.521*/522cinfo->unread_marker = c;523/* See if we need to insert some fake zero bits. */524goto no_more_bytes;525}526}527528/* OK, load c into get_buffer */529get_buffer = (get_buffer << 8) | c;530bits_left += 8;531} /* end while */532} else {533no_more_bytes:534/* We get here if we've read the marker that terminates the compressed535* data segment. There should be enough bits in the buffer register536* to satisfy the request; if so, no problem.537*/538if (nbits > bits_left) {539/* Uh-oh. Report corrupted data to user and stuff zeroes into540* the data stream, so that we can produce some kind of image.541* We use a nonvolatile flag to ensure that only one warning message542* appears per data segment.543*/544if (! ((huff_entropy_ptr) cinfo->entropy)->insufficient_data) {545WARNMS(cinfo, JWRN_HIT_MARKER);546((huff_entropy_ptr) cinfo->entropy)->insufficient_data = TRUE;547}548/* Fill the buffer with zero bits */549get_buffer <<= MIN_GET_BITS - bits_left;550bits_left = MIN_GET_BITS;551}552}553554/* Unload the local registers */555state->next_input_byte = next_input_byte;556state->bytes_in_buffer = bytes_in_buffer;557state->get_buffer = get_buffer;558state->bits_left = bits_left;559560return TRUE;561}562563564/*565* Figure F.12: extend sign bit.566* On some machines, a shift and sub will be faster than a table lookup.567*/568569#ifdef AVOID_TABLES570571#define BIT_MASK(nbits) ((1<<(nbits))-1)572#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))573574#else575576#define BIT_MASK(nbits) bmask[nbits]577#define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))578579static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */580{ 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,5810x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };582583#endif /* AVOID_TABLES */584585586/*587* Out-of-line code for Huffman code decoding.588*/589590LOCAL(int)591jpeg_huff_decode (bitread_working_state * state,592register bit_buf_type get_buffer, register int bits_left,593d_derived_tbl * htbl, int min_bits)594{595register int l = min_bits;596register INT32 code;597598/* HUFF_DECODE has determined that the code is at least min_bits */599/* bits long, so fetch that many bits in one swoop. */600601CHECK_BIT_BUFFER(*state, l, return -1);602code = GET_BITS(l);603604/* Collect the rest of the Huffman code one bit at a time. */605/* This is per Figure F.16 in the JPEG spec. */606607while (code > htbl->maxcode[l]) {608code <<= 1;609CHECK_BIT_BUFFER(*state, 1, return -1);610code |= GET_BITS(1);611l++;612}613614/* Unload the local registers */615state->get_buffer = get_buffer;616state->bits_left = bits_left;617618/* With garbage input we may reach the sentinel value l = 17. */619620if (l > 16) {621WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);622return 0; /* fake a zero as the safest result */623}624625return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];626}627628629/*630* Finish up at the end of a Huffman-compressed scan.631*/632633METHODDEF(void)634finish_pass_huff (j_decompress_ptr cinfo)635{636huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;637638/* Throw away any unused bits remaining in bit buffer; */639/* include any full bytes in next_marker's count of discarded bytes */640cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;641entropy->bitstate.bits_left = 0;642}643644645/*646* Check for a restart marker & resynchronize decoder.647* Returns FALSE if must suspend.648*/649650LOCAL(boolean)651process_restart (j_decompress_ptr cinfo)652{653huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;654int ci;655656finish_pass_huff(cinfo);657658/* Advance past the RSTn marker */659if (! (*cinfo->marker->read_restart_marker) (cinfo))660return FALSE;661662/* Re-initialize DC predictions to 0 */663for (ci = 0; ci < cinfo->comps_in_scan; ci++)664entropy->saved.last_dc_val[ci] = 0;665/* Re-init EOB run count, too */666entropy->saved.EOBRUN = 0;667668/* Reset restart counter */669entropy->restarts_to_go = cinfo->restart_interval;670671/* Reset out-of-data flag, unless read_restart_marker left us smack up672* against a marker. In that case we will end up treating the next data673* segment as empty, and we can avoid producing bogus output pixels by674* leaving the flag set.675*/676if (cinfo->unread_marker == 0)677entropy->insufficient_data = FALSE;678679return TRUE;680}681682683/*684* Huffman MCU decoding.685* Each of these routines decodes and returns one MCU's worth of686* Huffman-compressed coefficients.687* The coefficients are reordered from zigzag order into natural array order,688* but are not dequantized.689*690* The i'th block of the MCU is stored into the block pointed to by691* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.692* (Wholesale zeroing is usually a little faster than retail...)693*694* We return FALSE if data source requested suspension. In that case no695* changes have been made to permanent state. (Exception: some output696* coefficients may already have been assigned. This is harmless for697* spectral selection, since we'll just re-assign them on the next call.698* Successive approximation AC refinement has to be more careful, however.)699*/700701/*702* MCU decoding for DC initial scan (either spectral selection,703* or first pass of successive approximation).704*/705706METHODDEF(boolean)707decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)708{709huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;710int Al = cinfo->Al;711register int s, r;712int blkn, ci;713JBLOCKROW block;714BITREAD_STATE_VARS;715savable_state state;716d_derived_tbl * tbl;717jpeg_component_info * compptr;718719/* Process restart marker if needed; may have to suspend */720if (cinfo->restart_interval) {721if (entropy->restarts_to_go == 0)722if (! process_restart(cinfo))723return FALSE;724}725726/* If we've run out of data, just leave the MCU set to zeroes.727* This way, we return uniform gray for the remainder of the segment.728*/729if (! entropy->insufficient_data) {730731/* Load up working state */732BITREAD_LOAD_STATE(cinfo,entropy->bitstate);733ASSIGN_STATE(state, entropy->saved);734735/* Outer loop handles each block in the MCU */736737for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {738block = MCU_data[blkn];739ci = cinfo->MCU_membership[blkn];740compptr = cinfo->cur_comp_info[ci];741tbl = entropy->derived_tbls[compptr->dc_tbl_no];742743/* Decode a single block's worth of coefficients */744745/* Section F.2.2.1: decode the DC coefficient difference */746HUFF_DECODE(s, br_state, tbl, return FALSE, label1);747if (s) {748CHECK_BIT_BUFFER(br_state, s, return FALSE);749r = GET_BITS(s);750s = HUFF_EXTEND(r, s);751}752753/* Convert DC difference to actual value, update last_dc_val */754s += state.last_dc_val[ci];755state.last_dc_val[ci] = s;756/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */757(*block)[0] = (JCOEF) (s << Al);758}759760/* Completed MCU, so update state */761BITREAD_SAVE_STATE(cinfo,entropy->bitstate);762ASSIGN_STATE(entropy->saved, state);763}764765/* Account for restart interval (no-op if not using restarts) */766entropy->restarts_to_go--;767768return TRUE;769}770771772/*773* MCU decoding for AC initial scan (either spectral selection,774* or first pass of successive approximation).775*/776777METHODDEF(boolean)778decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)779{780huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;781register int s, k, r;782unsigned int EOBRUN;783int Se, Al;784const int * natural_order;785JBLOCKROW block;786BITREAD_STATE_VARS;787d_derived_tbl * tbl;788789/* Process restart marker if needed; may have to suspend */790if (cinfo->restart_interval) {791if (entropy->restarts_to_go == 0)792if (! process_restart(cinfo))793return FALSE;794}795796/* If we've run out of data, just leave the MCU set to zeroes.797* This way, we return uniform gray for the remainder of the segment.798*/799if (! entropy->insufficient_data) {800801Se = cinfo->Se;802Al = cinfo->Al;803natural_order = cinfo->natural_order;804805/* Load up working state.806* We can avoid loading/saving bitread state if in an EOB run.807*/808EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */809810/* There is always only one block per MCU */811812if (EOBRUN) /* if it's a band of zeroes... */813EOBRUN--; /* ...process it now (we do nothing) */814else {815BITREAD_LOAD_STATE(cinfo,entropy->bitstate);816block = MCU_data[0];817tbl = entropy->ac_derived_tbl;818819for (k = cinfo->Ss; k <= Se; k++) {820HUFF_DECODE(s, br_state, tbl, return FALSE, label2);821r = s >> 4;822s &= 15;823if (s) {824k += r;825CHECK_BIT_BUFFER(br_state, s, return FALSE);826r = GET_BITS(s);827s = HUFF_EXTEND(r, s);828/* Scale and output coefficient in natural (dezigzagged) order */829(*block)[natural_order[k]] = (JCOEF) (s << Al);830} else {831if (r != 15) { /* EOBr, run length is 2^r + appended bits */832if (r) { /* EOBr, r > 0 */833EOBRUN = 1 << r;834CHECK_BIT_BUFFER(br_state, r, return FALSE);835r = GET_BITS(r);836EOBRUN += r;837EOBRUN--; /* this band is processed at this moment */838}839break; /* force end-of-band */840}841k += 15; /* ZRL: skip 15 zeroes in band */842}843}844845BITREAD_SAVE_STATE(cinfo,entropy->bitstate);846}847848/* Completed MCU, so update state */849entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */850}851852/* Account for restart interval (no-op if not using restarts) */853entropy->restarts_to_go--;854855return TRUE;856}857858859/*860* MCU decoding for DC successive approximation refinement scan.861* Note: we assume such scans can be multi-component,862* although the spec is not very clear on the point.863*/864865METHODDEF(boolean)866decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)867{868huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;869int p1, blkn;870BITREAD_STATE_VARS;871872/* Process restart marker if needed; may have to suspend */873if (cinfo->restart_interval) {874if (entropy->restarts_to_go == 0)875if (! process_restart(cinfo))876return FALSE;877}878879/* Not worth the cycles to check insufficient_data here,880* since we will not change the data anyway if we read zeroes.881*/882883/* Load up working state */884BITREAD_LOAD_STATE(cinfo,entropy->bitstate);885886p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */887888/* Outer loop handles each block in the MCU */889890for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {891/* Encoded data is simply the next bit of the two's-complement DC value */892CHECK_BIT_BUFFER(br_state, 1, return FALSE);893if (GET_BITS(1))894MCU_data[blkn][0][0] |= p1;895/* Note: since we use |=, repeating the assignment later is safe */896}897898/* Completed MCU, so update state */899BITREAD_SAVE_STATE(cinfo,entropy->bitstate);900901/* Account for restart interval (no-op if not using restarts) */902entropy->restarts_to_go--;903904return TRUE;905}906907908/*909* MCU decoding for AC successive approximation refinement scan.910*/911912METHODDEF(boolean)913decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)914{915huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;916register int s, k, r;917unsigned int EOBRUN;918int Se, p1, m1;919const int * natural_order;920JBLOCKROW block;921JCOEFPTR thiscoef;922BITREAD_STATE_VARS;923d_derived_tbl * tbl;924int num_newnz;925int newnz_pos[DCTSIZE2];926927/* Process restart marker if needed; may have to suspend */928if (cinfo->restart_interval) {929if (entropy->restarts_to_go == 0)930if (! process_restart(cinfo))931return FALSE;932}933934/* If we've run out of data, don't modify the MCU.935*/936if (! entropy->insufficient_data) {937938Se = cinfo->Se;939p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */940m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */941natural_order = cinfo->natural_order;942943/* Load up working state */944BITREAD_LOAD_STATE(cinfo,entropy->bitstate);945EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */946947/* There is always only one block per MCU */948block = MCU_data[0];949tbl = entropy->ac_derived_tbl;950951/* If we are forced to suspend, we must undo the assignments to any newly952* nonzero coefficients in the block, because otherwise we'd get confused953* next time about which coefficients were already nonzero.954* But we need not undo addition of bits to already-nonzero coefficients;955* instead, we can test the current bit to see if we already did it.956*/957num_newnz = 0;958959/* initialize coefficient loop counter to start of band */960k = cinfo->Ss;961962if (EOBRUN == 0) {963do {964HUFF_DECODE(s, br_state, tbl, goto undoit, label3);965r = s >> 4;966s &= 15;967if (s) {968if (s != 1) /* size of new coef should always be 1 */969WARNMS(cinfo, JWRN_HUFF_BAD_CODE);970CHECK_BIT_BUFFER(br_state, 1, goto undoit);971if (GET_BITS(1))972s = p1; /* newly nonzero coef is positive */973else974s = m1; /* newly nonzero coef is negative */975} else {976if (r != 15) {977EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */978if (r) {979CHECK_BIT_BUFFER(br_state, r, goto undoit);980r = GET_BITS(r);981EOBRUN += r;982}983break; /* rest of block is handled by EOB logic */984}985/* note s = 0 for processing ZRL */986}987/* Advance over already-nonzero coefs and r still-zero coefs,988* appending correction bits to the nonzeroes. A correction bit is 1989* if the absolute value of the coefficient must be increased.990*/991do {992thiscoef = *block + natural_order[k];993if (*thiscoef) {994CHECK_BIT_BUFFER(br_state, 1, goto undoit);995if (GET_BITS(1)) {996if ((*thiscoef & p1) == 0) { /* do nothing if already set it */997if (*thiscoef >= 0)998*thiscoef += p1;999else1000*thiscoef += m1;1001}1002}1003} else {1004if (--r < 0)1005break; /* reached target zero coefficient */1006}1007k++;1008} while (k <= Se);1009if (s) {1010int pos = natural_order[k];1011/* Output newly nonzero coefficient */1012(*block)[pos] = (JCOEF) s;1013/* Remember its position in case we have to suspend */1014newnz_pos[num_newnz++] = pos;1015}1016k++;1017} while (k <= Se);1018}10191020if (EOBRUN) {1021/* Scan any remaining coefficient positions after the end-of-band1022* (the last newly nonzero coefficient, if any). Append a correction1023* bit to each already-nonzero coefficient. A correction bit is 11024* if the absolute value of the coefficient must be increased.1025*/1026do {1027thiscoef = *block + natural_order[k];1028if (*thiscoef) {1029CHECK_BIT_BUFFER(br_state, 1, goto undoit);1030if (GET_BITS(1)) {1031if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */1032if (*thiscoef >= 0)1033*thiscoef += p1;1034else1035*thiscoef += m1;1036}1037}1038}1039k++;1040} while (k <= Se);1041/* Count one block completed in EOB run */1042EOBRUN--;1043}10441045/* Completed MCU, so update state */1046BITREAD_SAVE_STATE(cinfo,entropy->bitstate);1047entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */1048}10491050/* Account for restart interval (no-op if not using restarts) */1051entropy->restarts_to_go--;10521053return TRUE;10541055undoit:1056/* Re-zero any output coefficients that we made newly nonzero */1057while (num_newnz)1058(*block)[newnz_pos[--num_newnz]] = 0;10591060return FALSE;1061}106210631064/*1065* Decode one MCU's worth of Huffman-compressed coefficients,1066* partial blocks.1067*/10681069METHODDEF(boolean)1070decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)1071{1072huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1073const int * natural_order;1074int Se, blkn;1075BITREAD_STATE_VARS;1076savable_state state;10771078/* Process restart marker if needed; may have to suspend */1079if (cinfo->restart_interval) {1080if (entropy->restarts_to_go == 0)1081if (! process_restart(cinfo))1082return FALSE;1083}10841085/* If we've run out of data, just leave the MCU set to zeroes.1086* This way, we return uniform gray for the remainder of the segment.1087*/1088if (! entropy->insufficient_data) {10891090natural_order = cinfo->natural_order;1091Se = cinfo->lim_Se;10921093/* Load up working state */1094BITREAD_LOAD_STATE(cinfo,entropy->bitstate);1095ASSIGN_STATE(state, entropy->saved);10961097/* Outer loop handles each block in the MCU */10981099for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1100JBLOCKROW block = MCU_data[blkn];1101d_derived_tbl * htbl;1102register int s, k, r;1103int coef_limit, ci;11041105/* Decode a single block's worth of coefficients */11061107/* Section F.2.2.1: decode the DC coefficient difference */1108htbl = entropy->dc_cur_tbls[blkn];1109HUFF_DECODE(s, br_state, htbl, return FALSE, label1);11101111htbl = entropy->ac_cur_tbls[blkn];1112k = 1;1113coef_limit = entropy->coef_limit[blkn];1114if (coef_limit) {1115/* Convert DC difference to actual value, update last_dc_val */1116if (s) {1117CHECK_BIT_BUFFER(br_state, s, return FALSE);1118r = GET_BITS(s);1119s = HUFF_EXTEND(r, s);1120}1121ci = cinfo->MCU_membership[blkn];1122s += state.last_dc_val[ci];1123state.last_dc_val[ci] = s;1124/* Output the DC coefficient */1125(*block)[0] = (JCOEF) s;11261127/* Section F.2.2.2: decode the AC coefficients */1128/* Since zeroes are skipped, output area must be cleared beforehand */1129for (; k < coef_limit; k++) {1130HUFF_DECODE(s, br_state, htbl, return FALSE, label2);11311132r = s >> 4;1133s &= 15;11341135if (s) {1136k += r;1137CHECK_BIT_BUFFER(br_state, s, return FALSE);1138r = GET_BITS(s);1139s = HUFF_EXTEND(r, s);1140/* Output coefficient in natural (dezigzagged) order.1141* Note: the extra entries in natural_order[] will save us1142* if k > Se, which could happen if the data is corrupted.1143*/1144(*block)[natural_order[k]] = (JCOEF) s;1145} else {1146if (r != 15)1147goto EndOfBlock;1148k += 15;1149}1150}1151} else {1152if (s) {1153CHECK_BIT_BUFFER(br_state, s, return FALSE);1154DROP_BITS(s);1155}1156}11571158/* Section F.2.2.2: decode the AC coefficients */1159/* In this path we just discard the values */1160for (; k <= Se; k++) {1161HUFF_DECODE(s, br_state, htbl, return FALSE, label3);11621163r = s >> 4;1164s &= 15;11651166if (s) {1167k += r;1168CHECK_BIT_BUFFER(br_state, s, return FALSE);1169DROP_BITS(s);1170} else {1171if (r != 15)1172break;1173k += 15;1174}1175}11761177EndOfBlock: ;1178}11791180/* Completed MCU, so update state */1181BITREAD_SAVE_STATE(cinfo,entropy->bitstate);1182ASSIGN_STATE(entropy->saved, state);1183}11841185/* Account for restart interval (no-op if not using restarts) */1186entropy->restarts_to_go--;11871188return TRUE;1189}119011911192/*1193* Decode one MCU's worth of Huffman-compressed coefficients,1194* full-size blocks.1195*/11961197METHODDEF(boolean)1198decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)1199{1200huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1201int blkn;1202BITREAD_STATE_VARS;1203savable_state state;12041205/* Process restart marker if needed; may have to suspend */1206if (cinfo->restart_interval) {1207if (entropy->restarts_to_go == 0)1208if (! process_restart(cinfo))1209return FALSE;1210}12111212/* If we've run out of data, just leave the MCU set to zeroes.1213* This way, we return uniform gray for the remainder of the segment.1214*/1215if (! entropy->insufficient_data) {12161217/* Load up working state */1218BITREAD_LOAD_STATE(cinfo,entropy->bitstate);1219ASSIGN_STATE(state, entropy->saved);12201221/* Outer loop handles each block in the MCU */12221223for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1224JBLOCKROW block = MCU_data[blkn];1225d_derived_tbl * htbl;1226register int s, k, r;1227int coef_limit, ci;12281229/* Decode a single block's worth of coefficients */12301231/* Section F.2.2.1: decode the DC coefficient difference */1232htbl = entropy->dc_cur_tbls[blkn];1233HUFF_DECODE(s, br_state, htbl, return FALSE, label1);12341235htbl = entropy->ac_cur_tbls[blkn];1236k = 1;1237coef_limit = entropy->coef_limit[blkn];1238if (coef_limit) {1239/* Convert DC difference to actual value, update last_dc_val */1240if (s) {1241CHECK_BIT_BUFFER(br_state, s, return FALSE);1242r = GET_BITS(s);1243s = HUFF_EXTEND(r, s);1244}1245ci = cinfo->MCU_membership[blkn];1246s += state.last_dc_val[ci];1247state.last_dc_val[ci] = s;1248/* Output the DC coefficient */1249(*block)[0] = (JCOEF) s;12501251/* Section F.2.2.2: decode the AC coefficients */1252/* Since zeroes are skipped, output area must be cleared beforehand */1253for (; k < coef_limit; k++) {1254HUFF_DECODE(s, br_state, htbl, return FALSE, label2);12551256r = s >> 4;1257s &= 15;12581259if (s) {1260k += r;1261CHECK_BIT_BUFFER(br_state, s, return FALSE);1262r = GET_BITS(s);1263s = HUFF_EXTEND(r, s);1264/* Output coefficient in natural (dezigzagged) order.1265* Note: the extra entries in jpeg_natural_order[] will save us1266* if k >= DCTSIZE2, which could happen if the data is corrupted.1267*/1268(*block)[jpeg_natural_order[k]] = (JCOEF) s;1269} else {1270if (r != 15)1271goto EndOfBlock;1272k += 15;1273}1274}1275} else {1276if (s) {1277CHECK_BIT_BUFFER(br_state, s, return FALSE);1278DROP_BITS(s);1279}1280}12811282/* Section F.2.2.2: decode the AC coefficients */1283/* In this path we just discard the values */1284for (; k < DCTSIZE2; k++) {1285HUFF_DECODE(s, br_state, htbl, return FALSE, label3);12861287r = s >> 4;1288s &= 15;12891290if (s) {1291k += r;1292CHECK_BIT_BUFFER(br_state, s, return FALSE);1293DROP_BITS(s);1294} else {1295if (r != 15)1296break;1297k += 15;1298}1299}13001301EndOfBlock: ;1302}13031304/* Completed MCU, so update state */1305BITREAD_SAVE_STATE(cinfo,entropy->bitstate);1306ASSIGN_STATE(entropy->saved, state);1307}13081309/* Account for restart interval (no-op if not using restarts) */1310entropy->restarts_to_go--;13111312return TRUE;1313}131413151316/*1317* Initialize for a Huffman-compressed scan.1318*/13191320METHODDEF(void)1321start_pass_huff_decoder (j_decompress_ptr cinfo)1322{1323huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1324int ci, blkn, tbl, i;1325jpeg_component_info * compptr;13261327if (cinfo->progressive_mode) {1328/* Validate progressive scan parameters */1329if (cinfo->Ss == 0) {1330if (cinfo->Se != 0)1331goto bad;1332} else {1333/* need not check Ss/Se < 0 since they came from unsigned bytes */1334if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)1335goto bad;1336/* AC scans may have only one component */1337if (cinfo->comps_in_scan != 1)1338goto bad;1339}1340if (cinfo->Ah != 0) {1341/* Successive approximation refinement scan: must have Al = Ah-1. */1342if (cinfo->Ah-1 != cinfo->Al)1343goto bad;1344}1345if (cinfo->Al > 13) { /* need not check for < 0 */1346/* Arguably the maximum Al value should be less than 13 for 8-bit precision,1347* but the spec doesn't say so, and we try to be liberal about what we1348* accept. Note: large Al values could result in out-of-range DC1349* coefficients during early scans, leading to bizarre displays due to1350* overflows in the IDCT math. But we won't crash.1351*/1352bad:1353ERREXIT4(cinfo, JERR_BAD_PROGRESSION,1354cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);1355}1356/* Update progression status, and verify that scan order is legal.1357* Note that inter-scan inconsistencies are treated as warnings1358* not fatal errors ... not clear if this is right way to behave.1359*/1360for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1361int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;1362int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];1363if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */1364WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);1365for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {1366int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];1367if (cinfo->Ah != expected)1368WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);1369coef_bit_ptr[coefi] = cinfo->Al;1370}1371}13721373/* Select MCU decoding routine */1374if (cinfo->Ah == 0) {1375if (cinfo->Ss == 0)1376entropy->pub.decode_mcu = decode_mcu_DC_first;1377else1378entropy->pub.decode_mcu = decode_mcu_AC_first;1379} else {1380if (cinfo->Ss == 0)1381entropy->pub.decode_mcu = decode_mcu_DC_refine;1382else1383entropy->pub.decode_mcu = decode_mcu_AC_refine;1384}13851386for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1387compptr = cinfo->cur_comp_info[ci];1388/* Make sure requested tables are present, and compute derived tables.1389* We may build same derived table more than once, but it's not expensive.1390*/1391if (cinfo->Ss == 0) {1392if (cinfo->Ah == 0) { /* DC refinement needs no table */1393tbl = compptr->dc_tbl_no;1394jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,1395& entropy->derived_tbls[tbl]);1396}1397} else {1398tbl = compptr->ac_tbl_no;1399jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,1400& entropy->derived_tbls[tbl]);1401/* remember the single active table */1402entropy->ac_derived_tbl = entropy->derived_tbls[tbl];1403}1404/* Initialize DC predictions to 0 */1405entropy->saved.last_dc_val[ci] = 0;1406}14071408/* Initialize private state variables */1409entropy->saved.EOBRUN = 0;1410} else {1411/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.1412* This ought to be an error condition, but we make it a warning because1413* there are some baseline files out there with all zeroes in these bytes.1414*/1415if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||1416((cinfo->is_baseline || cinfo->Se < DCTSIZE2) &&1417cinfo->Se != cinfo->lim_Se))1418WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);14191420/* Select MCU decoding routine */1421/* We retain the hard-coded case for full-size blocks.1422* This is not necessary, but it appears that this version is slightly1423* more performant in the given implementation.1424* With an improved implementation we would prefer a single optimized1425* function.1426*/1427if (cinfo->lim_Se != DCTSIZE2-1)1428entropy->pub.decode_mcu = decode_mcu_sub;1429else1430entropy->pub.decode_mcu = decode_mcu;14311432for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1433compptr = cinfo->cur_comp_info[ci];1434/* Compute derived values for Huffman tables */1435/* We may do this more than once for a table, but it's not expensive */1436tbl = compptr->dc_tbl_no;1437jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,1438& entropy->dc_derived_tbls[tbl]);1439if (cinfo->lim_Se) { /* AC needs no table when not present */1440tbl = compptr->ac_tbl_no;1441jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,1442& entropy->ac_derived_tbls[tbl]);1443}1444/* Initialize DC predictions to 0 */1445entropy->saved.last_dc_val[ci] = 0;1446}14471448/* Precalculate decoding info for each block in an MCU of this scan */1449for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1450ci = cinfo->MCU_membership[blkn];1451compptr = cinfo->cur_comp_info[ci];1452/* Precalculate which table to use for each block */1453entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];1454entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];1455/* Decide whether we really care about the coefficient values */1456if (compptr->component_needed) {1457ci = compptr->DCT_v_scaled_size;1458i = compptr->DCT_h_scaled_size;1459switch (cinfo->lim_Se) {1460case (1*1-1):1461entropy->coef_limit[blkn] = 1;1462break;1463case (2*2-1):1464if (ci <= 0 || ci > 2) ci = 2;1465if (i <= 0 || i > 2) i = 2;1466entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1];1467break;1468case (3*3-1):1469if (ci <= 0 || ci > 3) ci = 3;1470if (i <= 0 || i > 3) i = 3;1471entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1];1472break;1473case (4*4-1):1474if (ci <= 0 || ci > 4) ci = 4;1475if (i <= 0 || i > 4) i = 4;1476entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1];1477break;1478case (5*5-1):1479if (ci <= 0 || ci > 5) ci = 5;1480if (i <= 0 || i > 5) i = 5;1481entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1];1482break;1483case (6*6-1):1484if (ci <= 0 || ci > 6) ci = 6;1485if (i <= 0 || i > 6) i = 6;1486entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1];1487break;1488case (7*7-1):1489if (ci <= 0 || ci > 7) ci = 7;1490if (i <= 0 || i > 7) i = 7;1491entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1];1492break;1493default:1494if (ci <= 0 || ci > 8) ci = 8;1495if (i <= 0 || i > 8) i = 8;1496entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];1497break;1498}1499} else {1500entropy->coef_limit[blkn] = 0;1501}1502}1503}15041505/* Initialize bitread state variables */1506entropy->bitstate.bits_left = 0;1507entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */1508entropy->insufficient_data = FALSE;15091510/* Initialize restart counter */1511entropy->restarts_to_go = cinfo->restart_interval;1512}151315141515/*1516* Module initialization routine for Huffman entropy decoding.1517*/15181519GLOBAL(void)1520jinit_huff_decoder (j_decompress_ptr cinfo)1521{1522huff_entropy_ptr entropy;1523int i;15241525entropy = (huff_entropy_ptr)1526(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,1527SIZEOF(huff_entropy_decoder));1528cinfo->entropy = &entropy->pub;1529entropy->pub.start_pass = start_pass_huff_decoder;1530entropy->pub.finish_pass = finish_pass_huff;15311532if (cinfo->progressive_mode) {1533/* Create progression status table */1534int *coef_bit_ptr, ci;1535cinfo->coef_bits = (int (*)[DCTSIZE2])1536(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,1537cinfo->num_components*DCTSIZE2*SIZEOF(int));1538coef_bit_ptr = & cinfo->coef_bits[0][0];1539for (ci = 0; ci < cinfo->num_components; ci++)1540for (i = 0; i < DCTSIZE2; i++)1541*coef_bit_ptr++ = -1;15421543/* Mark derived tables unallocated */1544for (i = 0; i < NUM_HUFF_TBLS; i++) {1545entropy->derived_tbls[i] = NULL;1546}1547} else {1548/* Mark tables unallocated */1549for (i = 0; i < NUM_HUFF_TBLS; i++) {1550entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;1551}1552}1553}155415551556