/*1* jdhuff.c2*3* Copyright (C) 1991-1997, Thomas G. Lane.4* Modified 2006-2020 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)343htbl = jpeg_std_huff_table((j_common_ptr) cinfo, isDC, tblno);344345/* Allocate a workspace if we haven't already done so. */346if (*pdtbl == NULL)347*pdtbl = (d_derived_tbl *) (*cinfo->mem->alloc_small)348((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(d_derived_tbl));349dtbl = *pdtbl;350dtbl->pub = htbl; /* fill in back link */351352/* Figure C.1: make table of Huffman code length for each symbol */353354p = 0;355for (l = 1; l <= 16; l++) {356i = (int) htbl->bits[l];357if (i < 0 || p + i > 256) /* protect against table overrun */358ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);359while (i--)360huffsize[p++] = (char) l;361}362huffsize[p] = 0;363numsymbols = p;364365/* Figure C.2: generate the codes themselves */366/* We also validate that the counts represent a legal Huffman code tree. */367368code = 0;369si = huffsize[0];370p = 0;371while (huffsize[p]) {372while (((int) huffsize[p]) == si) {373huffcode[p++] = code;374code++;375}376/* code is now 1 more than the last code used for codelength si; but377* it must still fit in si bits, since no code is allowed to be all ones.378*/379if (((INT32) code) >= (((INT32) 1) << si))380ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);381code <<= 1;382si++;383}384385/* Figure F.15: generate decoding tables for bit-sequential decoding */386387p = 0;388for (l = 1; l <= 16; l++) {389if (htbl->bits[l]) {390/* valoffset[l] = huffval[] index of 1st symbol of code length l,391* minus the minimum code of length l392*/393dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];394p += htbl->bits[l];395dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */396} else {397dtbl->maxcode[l] = -1; /* -1 if no codes of this length */398}399}400dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */401402/* Compute lookahead tables to speed up decoding.403* First we set all the table entries to 0, indicating "too long";404* then we iterate through the Huffman codes that are short enough and405* fill in all the entries that correspond to bit sequences starting406* with that code.407*/408409MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));410411p = 0;412for (l = 1; l <= HUFF_LOOKAHEAD; l++) {413for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {414/* l = current code's length, p = its index in huffcode[] & huffval[]. */415/* Generate left-justified code followed by all possible bit sequences */416lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);417for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {418dtbl->look_nbits[lookbits] = l;419dtbl->look_sym[lookbits] = htbl->huffval[p];420lookbits++;421}422}423}424425/* Validate symbols as being reasonable.426* For AC tables, we make no check, but accept all byte values 0..255.427* For DC tables, we require the symbols to be in range 0..15.428* (Tighter bounds could be applied depending on the data depth and mode,429* but this is sufficient to ensure safe decoding.)430*/431if (isDC) {432for (i = 0; i < numsymbols; i++) {433int sym = htbl->huffval[i];434if (sym < 0 || sym > 15)435ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);436}437}438}439440441/*442* Out-of-line code for bit fetching.443* Note: current values of get_buffer and bits_left are passed as parameters,444* but are returned in the corresponding fields of the state struct.445*446* On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width447* of get_buffer to be used. (On machines with wider words, an even larger448* buffer could be used.) However, on some machines 32-bit shifts are449* quite slow and take time proportional to the number of places shifted.450* (This is true with most PC compilers, for instance.) In this case it may451* be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the452* average shift distance at the cost of more calls to jpeg_fill_bit_buffer.453*/454455#ifdef SLOW_SHIFT_32456#define MIN_GET_BITS 15 /* minimum allowable value */457#else458#define MIN_GET_BITS (BIT_BUF_SIZE-7)459#endif460461462LOCAL(boolean)463jpeg_fill_bit_buffer (bitread_working_state * state,464register bit_buf_type get_buffer, register int bits_left,465int nbits)466/* Load up the bit buffer to a depth of at least nbits */467{468/* Copy heavily used state fields into locals (hopefully registers) */469register const JOCTET * next_input_byte = state->next_input_byte;470register size_t bytes_in_buffer = state->bytes_in_buffer;471j_decompress_ptr cinfo = state->cinfo;472473/* Attempt to load at least MIN_GET_BITS bits into get_buffer. */474/* (It is assumed that no request will be for more than that many bits.) */475/* We fail to do so only if we hit a marker or are forced to suspend. */476477if (cinfo->unread_marker == 0) { /* cannot advance past a marker */478while (bits_left < MIN_GET_BITS) {479register int c;480481/* Attempt to read a byte */482if (bytes_in_buffer == 0) {483if (! (*cinfo->src->fill_input_buffer) (cinfo))484return FALSE;485next_input_byte = cinfo->src->next_input_byte;486bytes_in_buffer = cinfo->src->bytes_in_buffer;487}488bytes_in_buffer--;489c = GETJOCTET(*next_input_byte++);490491/* If it's 0xFF, check and discard stuffed zero byte */492if (c == 0xFF) {493/* Loop here to discard any padding FF's on terminating marker,494* so that we can save a valid unread_marker value. NOTE: we will495* accept multiple FF's followed by a 0 as meaning a single FF data496* byte. This data pattern is not valid according to the standard.497*/498do {499if (bytes_in_buffer == 0) {500if (! (*cinfo->src->fill_input_buffer) (cinfo))501return FALSE;502next_input_byte = cinfo->src->next_input_byte;503bytes_in_buffer = cinfo->src->bytes_in_buffer;504}505bytes_in_buffer--;506c = GETJOCTET(*next_input_byte++);507} while (c == 0xFF);508509if (c == 0) {510/* Found FF/00, which represents an FF data byte */511c = 0xFF;512} else {513/* Oops, it's actually a marker indicating end of compressed data.514* Save the marker code for later use.515* Fine point: it might appear that we should save the marker into516* bitread working state, not straight into permanent state. But517* once we have hit a marker, we cannot need to suspend within the518* current MCU, because we will read no more bytes from the data519* source. So it is OK to update permanent state right away.520*/521cinfo->unread_marker = c;522/* See if we need to insert some fake zero bits. */523goto no_more_bytes;524}525}526527/* OK, load c into get_buffer */528get_buffer = (get_buffer << 8) | c;529bits_left += 8;530} /* end while */531} else {532no_more_bytes:533/* We get here if we've read the marker that terminates the compressed534* data segment. There should be enough bits in the buffer register535* to satisfy the request; if so, no problem.536*/537if (nbits > bits_left) {538/* Uh-oh. Report corrupted data to user and stuff zeroes into539* the data stream, so that we can produce some kind of image.540* We use a nonvolatile flag to ensure that only one warning message541* appears per data segment.542*/543if (! ((huff_entropy_ptr) cinfo->entropy)->insufficient_data) {544WARNMS(cinfo, JWRN_HIT_MARKER);545((huff_entropy_ptr) cinfo->entropy)->insufficient_data = TRUE;546}547/* Fill the buffer with zero bits */548get_buffer <<= MIN_GET_BITS - bits_left;549bits_left = MIN_GET_BITS;550}551}552553/* Unload the local registers */554state->next_input_byte = next_input_byte;555state->bytes_in_buffer = bytes_in_buffer;556state->get_buffer = get_buffer;557state->bits_left = bits_left;558559return TRUE;560}561562563/*564* Figure F.12: extend sign bit.565* On some machines, a shift and sub will be faster than a table lookup.566*/567568#ifdef AVOID_TABLES569570#define BIT_MASK(nbits) ((1<<(nbits))-1)571#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))572573#else574575#define BIT_MASK(nbits) bmask[nbits]576#define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))577578static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */579{ 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,5800x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };581582#endif /* AVOID_TABLES */583584585/*586* Out-of-line code for Huffman code decoding.587*/588589LOCAL(int)590jpeg_huff_decode (bitread_working_state * state,591register bit_buf_type get_buffer, register int bits_left,592d_derived_tbl * htbl, int min_bits)593{594register int l = min_bits;595register INT32 code;596597/* HUFF_DECODE has determined that the code is at least min_bits */598/* bits long, so fetch that many bits in one swoop. */599600CHECK_BIT_BUFFER(*state, l, return -1);601code = GET_BITS(l);602603/* Collect the rest of the Huffman code one bit at a time. */604/* This is per Figure F.16 in the JPEG spec. */605606while (code > htbl->maxcode[l]) {607code <<= 1;608CHECK_BIT_BUFFER(*state, 1, return -1);609code |= GET_BITS(1);610l++;611}612613/* Unload the local registers */614state->get_buffer = get_buffer;615state->bits_left = bits_left;616617/* With garbage input we may reach the sentinel value l = 17. */618619if (l > 16) {620WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);621return 0; /* fake a zero as the safest result */622}623624return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];625}626627628/*629* Finish up at the end of a Huffman-compressed scan.630*/631632METHODDEF(void)633finish_pass_huff (j_decompress_ptr cinfo)634{635huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;636637/* Throw away any unused bits remaining in bit buffer; */638/* include any full bytes in next_marker's count of discarded bytes */639cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;640entropy->bitstate.bits_left = 0;641}642643644/*645* Check for a restart marker & resynchronize decoder.646* Returns FALSE if must suspend.647*/648649LOCAL(boolean)650process_restart (j_decompress_ptr cinfo)651{652huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;653int ci;654655finish_pass_huff(cinfo);656657/* Advance past the RSTn marker */658if (! (*cinfo->marker->read_restart_marker) (cinfo))659return FALSE;660661/* Re-initialize DC predictions to 0 */662for (ci = 0; ci < cinfo->comps_in_scan; ci++)663entropy->saved.last_dc_val[ci] = 0;664/* Re-init EOB run count, too */665entropy->saved.EOBRUN = 0;666667/* Reset restart counter */668entropy->restarts_to_go = cinfo->restart_interval;669670/* Reset out-of-data flag, unless read_restart_marker left us smack up671* against a marker. In that case we will end up treating the next data672* segment as empty, and we can avoid producing bogus output pixels by673* leaving the flag set.674*/675if (cinfo->unread_marker == 0)676entropy->insufficient_data = FALSE;677678return TRUE;679}680681682/*683* Huffman MCU decoding.684* Each of these routines decodes and returns one MCU's worth of685* Huffman-compressed coefficients.686* The coefficients are reordered from zigzag order into natural array order,687* but are not dequantized.688*689* The i'th block of the MCU is stored into the block pointed to by690* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.691* (Wholesale zeroing is usually a little faster than retail...)692*693* We return FALSE if data source requested suspension. In that case no694* changes have been made to permanent state. (Exception: some output695* coefficients may already have been assigned. This is harmless for696* spectral selection, since we'll just re-assign them on the next call.697* Successive approximation AC refinement has to be more careful, however.)698*/699700/*701* MCU decoding for DC initial scan (either spectral selection,702* or first pass of successive approximation).703*/704705METHODDEF(boolean)706decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKARRAY MCU_data)707{708huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;709int Al = cinfo->Al;710register int s, r;711int blkn, ci;712JBLOCKROW block;713BITREAD_STATE_VARS;714savable_state state;715d_derived_tbl * tbl;716jpeg_component_info * compptr;717718/* Process restart marker if needed; may have to suspend */719if (cinfo->restart_interval) {720if (entropy->restarts_to_go == 0)721if (! process_restart(cinfo))722return FALSE;723}724725/* If we've run out of data, just leave the MCU set to zeroes.726* This way, we return uniform gray for the remainder of the segment.727*/728if (! entropy->insufficient_data) {729730/* Load up working state */731BITREAD_LOAD_STATE(cinfo, entropy->bitstate);732ASSIGN_STATE(state, entropy->saved);733734/* Outer loop handles each block in the MCU */735736for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {737block = MCU_data[blkn];738ci = cinfo->MCU_membership[blkn];739compptr = cinfo->cur_comp_info[ci];740tbl = entropy->derived_tbls[compptr->dc_tbl_no];741742/* Decode a single block's worth of coefficients */743744/* Section F.2.2.1: decode the DC coefficient difference */745HUFF_DECODE(s, br_state, tbl, return FALSE, label1);746if (s) {747CHECK_BIT_BUFFER(br_state, s, return FALSE);748r = GET_BITS(s);749s = HUFF_EXTEND(r, s);750}751752/* Convert DC difference to actual value, update last_dc_val */753s += state.last_dc_val[ci];754state.last_dc_val[ci] = s;755/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */756(*block)[0] = (JCOEF) (s << Al);757}758759/* Completed MCU, so update state */760BITREAD_SAVE_STATE(cinfo, entropy->bitstate);761ASSIGN_STATE(entropy->saved, state);762}763764/* Account for restart interval if using restarts */765if (cinfo->restart_interval)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, JBLOCKARRAY 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) {800801/* Load up working state.802* We can avoid loading/saving bitread state if in an EOB run.803*/804EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */805806/* There is always only one block per MCU */807808if (EOBRUN) /* if it's a band of zeroes... */809EOBRUN--; /* ...process it now (we do nothing) */810else {811BITREAD_LOAD_STATE(cinfo, entropy->bitstate);812Se = cinfo->Se;813Al = cinfo->Al;814natural_order = cinfo->natural_order;815block = MCU_data[0];816tbl = entropy->ac_derived_tbl;817818for (k = cinfo->Ss; k <= Se; k++) {819HUFF_DECODE(s, br_state, tbl, return FALSE, label2);820r = s >> 4;821s &= 15;822if (s) {823k += r;824CHECK_BIT_BUFFER(br_state, s, return FALSE);825r = GET_BITS(s);826s = HUFF_EXTEND(r, s);827/* Scale and output coefficient in natural (dezigzagged) order */828(*block)[natural_order[k]] = (JCOEF) (s << Al);829} else {830if (r != 15) { /* EOBr, run length is 2^r + appended bits */831if (r) { /* EOBr, r > 0 */832EOBRUN = 1 << r;833CHECK_BIT_BUFFER(br_state, r, return FALSE);834r = GET_BITS(r);835EOBRUN += r;836EOBRUN--; /* this band is processed at this moment */837}838break; /* force end-of-band */839}840k += 15; /* ZRL: skip 15 zeroes in band */841}842}843844BITREAD_SAVE_STATE(cinfo, entropy->bitstate);845}846847/* Completed MCU, so update state */848entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */849}850851/* Account for restart interval if using restarts */852if (cinfo->restart_interval)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, JBLOCKARRAY MCU_data)867{868huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;869JCOEF p1;870int blkn;871BITREAD_STATE_VARS;872873/* Process restart marker if needed; may have to suspend */874if (cinfo->restart_interval) {875if (entropy->restarts_to_go == 0)876if (! process_restart(cinfo))877return FALSE;878}879880/* Not worth the cycles to check insufficient_data here,881* since we will not change the data anyway if we read zeroes.882*/883884/* Load up working state */885BITREAD_LOAD_STATE(cinfo, entropy->bitstate);886887p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */888889/* Outer loop handles each block in the MCU */890891for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {892/* Encoded data is simply the next bit of the two's-complement DC value */893CHECK_BIT_BUFFER(br_state, 1, return FALSE);894if (GET_BITS(1))895MCU_data[blkn][0][0] |= p1;896/* Note: since we use |=, repeating the assignment later is safe */897}898899/* Completed MCU, so update state */900BITREAD_SAVE_STATE(cinfo, entropy->bitstate);901902/* Account for restart interval if using restarts */903if (cinfo->restart_interval)904entropy->restarts_to_go--;905906return TRUE;907}908909910/*911* MCU decoding for AC successive approximation refinement scan.912*/913914METHODDEF(boolean)915decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKARRAY MCU_data)916{917huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;918register int s, k, r;919unsigned int EOBRUN;920int Se;921JCOEF p1, m1;922const int * natural_order;923JBLOCKROW block;924JCOEFPTR thiscoef;925BITREAD_STATE_VARS;926d_derived_tbl * tbl;927int num_newnz;928int newnz_pos[DCTSIZE2];929930/* Process restart marker if needed; may have to suspend */931if (cinfo->restart_interval) {932if (entropy->restarts_to_go == 0)933if (! process_restart(cinfo))934return FALSE;935}936937/* If we've run out of data, don't modify the MCU.938*/939if (! entropy->insufficient_data) {940941Se = cinfo->Se;942p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */943m1 = -p1; /* -1 in the bit position being coded */944natural_order = cinfo->natural_order;945946/* Load up working state */947BITREAD_LOAD_STATE(cinfo, entropy->bitstate);948EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */949950/* There is always only one block per MCU */951block = MCU_data[0];952tbl = entropy->ac_derived_tbl;953954/* If we are forced to suspend, we must undo the assignments to any newly955* nonzero coefficients in the block, because otherwise we'd get confused956* next time about which coefficients were already nonzero.957* But we need not undo addition of bits to already-nonzero coefficients;958* instead, we can test the current bit to see if we already did it.959*/960num_newnz = 0;961962/* initialize coefficient loop counter to start of band */963k = cinfo->Ss;964965if (EOBRUN == 0) {966do {967HUFF_DECODE(s, br_state, tbl, goto undoit, label3);968r = s >> 4;969s &= 15;970if (s) {971if (s != 1) /* size of new coef should always be 1 */972WARNMS(cinfo, JWRN_HUFF_BAD_CODE);973CHECK_BIT_BUFFER(br_state, 1, goto undoit);974if (GET_BITS(1))975s = p1; /* newly nonzero coef is positive */976else977s = m1; /* newly nonzero coef is negative */978} else {979if (r != 15) {980EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */981if (r) {982CHECK_BIT_BUFFER(br_state, r, goto undoit);983r = GET_BITS(r);984EOBRUN += r;985}986break; /* rest of block is handled by EOB logic */987}988/* note s = 0 for processing ZRL */989}990/* Advance over already-nonzero coefs and r still-zero coefs,991* appending correction bits to the nonzeroes. A correction bit is 1992* if the absolute value of the coefficient must be increased.993*/994do {995thiscoef = *block + natural_order[k];996if (*thiscoef) {997CHECK_BIT_BUFFER(br_state, 1, goto undoit);998if (GET_BITS(1)) {999if ((*thiscoef & p1) == 0) { /* do nothing if already set it */1000if (*thiscoef >= 0)1001*thiscoef += p1;1002else1003*thiscoef += m1;1004}1005}1006} else {1007if (--r < 0)1008break; /* reached target zero coefficient */1009}1010k++;1011} while (k <= Se);1012if (s) {1013int pos = natural_order[k];1014/* Output newly nonzero coefficient */1015(*block)[pos] = (JCOEF) s;1016/* Remember its position in case we have to suspend */1017newnz_pos[num_newnz++] = pos;1018}1019k++;1020} while (k <= Se);1021}10221023if (EOBRUN) {1024/* Scan any remaining coefficient positions after the end-of-band1025* (the last newly nonzero coefficient, if any). Append a correction1026* bit to each already-nonzero coefficient. A correction bit is 11027* if the absolute value of the coefficient must be increased.1028*/1029do {1030thiscoef = *block + natural_order[k];1031if (*thiscoef) {1032CHECK_BIT_BUFFER(br_state, 1, goto undoit);1033if (GET_BITS(1)) {1034if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */1035if (*thiscoef >= 0)1036*thiscoef += p1;1037else1038*thiscoef += m1;1039}1040}1041}1042k++;1043} while (k <= Se);1044/* Count one block completed in EOB run */1045EOBRUN--;1046}10471048/* Completed MCU, so update state */1049BITREAD_SAVE_STATE(cinfo, entropy->bitstate);1050entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */1051}10521053/* Account for restart interval if using restarts */1054if (cinfo->restart_interval)1055entropy->restarts_to_go--;10561057return TRUE;10581059undoit:1060/* Re-zero any output coefficients that we made newly nonzero */1061while (num_newnz)1062(*block)[newnz_pos[--num_newnz]] = 0;10631064return FALSE;1065}106610671068/*1069* Decode one MCU's worth of Huffman-compressed coefficients,1070* partial blocks.1071*/10721073METHODDEF(boolean)1074decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKARRAY MCU_data)1075{1076huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1077const int * natural_order;1078int Se, blkn;1079BITREAD_STATE_VARS;1080savable_state state;10811082/* Process restart marker if needed; may have to suspend */1083if (cinfo->restart_interval) {1084if (entropy->restarts_to_go == 0)1085if (! process_restart(cinfo))1086return FALSE;1087}10881089/* If we've run out of data, just leave the MCU set to zeroes.1090* This way, we return uniform gray for the remainder of the segment.1091*/1092if (! entropy->insufficient_data) {10931094natural_order = cinfo->natural_order;1095Se = cinfo->lim_Se;10961097/* Load up working state */1098BITREAD_LOAD_STATE(cinfo, entropy->bitstate);1099ASSIGN_STATE(state, entropy->saved);11001101/* Outer loop handles each block in the MCU */11021103for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1104JBLOCKROW block = MCU_data[blkn];1105d_derived_tbl * htbl;1106register int s, k, r;1107int coef_limit, ci;11081109/* Decode a single block's worth of coefficients */11101111/* Section F.2.2.1: decode the DC coefficient difference */1112htbl = entropy->dc_cur_tbls[blkn];1113HUFF_DECODE(s, br_state, htbl, return FALSE, label1);11141115htbl = entropy->ac_cur_tbls[blkn];1116k = 1;1117coef_limit = entropy->coef_limit[blkn];1118if (coef_limit) {1119/* Convert DC difference to actual value, update last_dc_val */1120if (s) {1121CHECK_BIT_BUFFER(br_state, s, return FALSE);1122r = GET_BITS(s);1123s = HUFF_EXTEND(r, s);1124}1125ci = cinfo->MCU_membership[blkn];1126s += state.last_dc_val[ci];1127state.last_dc_val[ci] = s;1128/* Output the DC coefficient */1129(*block)[0] = (JCOEF) s;11301131/* Section F.2.2.2: decode the AC coefficients */1132/* Since zeroes are skipped, output area must be cleared beforehand */1133for (; k < coef_limit; k++) {1134HUFF_DECODE(s, br_state, htbl, return FALSE, label2);11351136r = s >> 4;1137s &= 15;11381139if (s) {1140k += r;1141CHECK_BIT_BUFFER(br_state, s, return FALSE);1142r = GET_BITS(s);1143s = HUFF_EXTEND(r, s);1144/* Output coefficient in natural (dezigzagged) order.1145* Note: the extra entries in natural_order[] will save us1146* if k > Se, which could happen if the data is corrupted.1147*/1148(*block)[natural_order[k]] = (JCOEF) s;1149} else {1150if (r != 15)1151goto EndOfBlock;1152k += 15;1153}1154}1155} else {1156if (s) {1157CHECK_BIT_BUFFER(br_state, s, return FALSE);1158DROP_BITS(s);1159}1160}11611162/* Section F.2.2.2: decode the AC coefficients */1163/* In this path we just discard the values */1164for (; k <= Se; k++) {1165HUFF_DECODE(s, br_state, htbl, return FALSE, label3);11661167r = s >> 4;1168s &= 15;11691170if (s) {1171k += r;1172CHECK_BIT_BUFFER(br_state, s, return FALSE);1173DROP_BITS(s);1174} else {1175if (r != 15)1176break;1177k += 15;1178}1179}11801181EndOfBlock: ;1182}11831184/* Completed MCU, so update state */1185BITREAD_SAVE_STATE(cinfo, entropy->bitstate);1186ASSIGN_STATE(entropy->saved, state);1187}11881189/* Account for restart interval if using restarts */1190if (cinfo->restart_interval)1191entropy->restarts_to_go--;11921193return TRUE;1194}119511961197/*1198* Decode one MCU's worth of Huffman-compressed coefficients,1199* full-size blocks.1200*/12011202METHODDEF(boolean)1203decode_mcu (j_decompress_ptr cinfo, JBLOCKARRAY MCU_data)1204{1205huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1206int blkn;1207BITREAD_STATE_VARS;1208savable_state state;12091210/* Process restart marker if needed; may have to suspend */1211if (cinfo->restart_interval) {1212if (entropy->restarts_to_go == 0)1213if (! process_restart(cinfo))1214return FALSE;1215}12161217/* If we've run out of data, just leave the MCU set to zeroes.1218* This way, we return uniform gray for the remainder of the segment.1219*/1220if (! entropy->insufficient_data) {12211222/* Load up working state */1223BITREAD_LOAD_STATE(cinfo, entropy->bitstate);1224ASSIGN_STATE(state, entropy->saved);12251226/* Outer loop handles each block in the MCU */12271228for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1229JBLOCKROW block = MCU_data[blkn];1230d_derived_tbl * htbl;1231register int s, k, r;1232int coef_limit, ci;12331234/* Decode a single block's worth of coefficients */12351236/* Section F.2.2.1: decode the DC coefficient difference */1237htbl = entropy->dc_cur_tbls[blkn];1238HUFF_DECODE(s, br_state, htbl, return FALSE, label1);12391240htbl = entropy->ac_cur_tbls[blkn];1241k = 1;1242coef_limit = entropy->coef_limit[blkn];1243if (coef_limit) {1244/* Convert DC difference to actual value, update last_dc_val */1245if (s) {1246CHECK_BIT_BUFFER(br_state, s, return FALSE);1247r = GET_BITS(s);1248s = HUFF_EXTEND(r, s);1249}1250ci = cinfo->MCU_membership[blkn];1251s += state.last_dc_val[ci];1252state.last_dc_val[ci] = s;1253/* Output the DC coefficient */1254(*block)[0] = (JCOEF) s;12551256/* Section F.2.2.2: decode the AC coefficients */1257/* Since zeroes are skipped, output area must be cleared beforehand */1258for (; k < coef_limit; k++) {1259HUFF_DECODE(s, br_state, htbl, return FALSE, label2);12601261r = s >> 4;1262s &= 15;12631264if (s) {1265k += r;1266CHECK_BIT_BUFFER(br_state, s, return FALSE);1267r = GET_BITS(s);1268s = HUFF_EXTEND(r, s);1269/* Output coefficient in natural (dezigzagged) order.1270* Note: the extra entries in jpeg_natural_order[] will save us1271* if k >= DCTSIZE2, which could happen if the data is corrupted.1272*/1273(*block)[jpeg_natural_order[k]] = (JCOEF) s;1274} else {1275if (r != 15)1276goto EndOfBlock;1277k += 15;1278}1279}1280} else {1281if (s) {1282CHECK_BIT_BUFFER(br_state, s, return FALSE);1283DROP_BITS(s);1284}1285}12861287/* Section F.2.2.2: decode the AC coefficients */1288/* In this path we just discard the values */1289for (; k < DCTSIZE2; k++) {1290HUFF_DECODE(s, br_state, htbl, return FALSE, label3);12911292r = s >> 4;1293s &= 15;12941295if (s) {1296k += r;1297CHECK_BIT_BUFFER(br_state, s, return FALSE);1298DROP_BITS(s);1299} else {1300if (r != 15)1301break;1302k += 15;1303}1304}13051306EndOfBlock: ;1307}13081309/* Completed MCU, so update state */1310BITREAD_SAVE_STATE(cinfo, entropy->bitstate);1311ASSIGN_STATE(entropy->saved, state);1312}13131314/* Account for restart interval if using restarts */1315if (cinfo->restart_interval)1316entropy->restarts_to_go--;13171318return TRUE;1319}132013211322/*1323* Initialize for a Huffman-compressed scan.1324*/13251326METHODDEF(void)1327start_pass_huff_decoder (j_decompress_ptr cinfo)1328{1329huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;1330int ci, blkn, tbl, i;1331jpeg_component_info * compptr;13321333if (cinfo->progressive_mode) {1334/* Validate progressive scan parameters */1335if (cinfo->Ss == 0) {1336if (cinfo->Se != 0)1337goto bad;1338} else {1339/* need not check Ss/Se < 0 since they came from unsigned bytes */1340if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)1341goto bad;1342/* AC scans may have only one component */1343if (cinfo->comps_in_scan != 1)1344goto bad;1345}1346if (cinfo->Ah != 0) {1347/* Successive approximation refinement scan: must have Al = Ah-1. */1348if (cinfo->Ah-1 != cinfo->Al)1349goto bad;1350}1351if (cinfo->Al > 13) { /* need not check for < 0 */1352/* Arguably the maximum Al value should be less than 13 for 8-bit1353* precision, but the spec doesn't say so, and we try to be liberal1354* about what we accept. Note: large Al values could result in1355* out-of-range DC coefficients during early scans, leading to bizarre1356* displays due to overflows in the IDCT math. But we won't crash.1357*/1358bad:1359ERREXIT4(cinfo, JERR_BAD_PROGRESSION,1360cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);1361}1362/* Update progression status, and verify that scan order is legal.1363* Note that inter-scan inconsistencies are treated as warnings1364* not fatal errors ... not clear if this is right way to behave.1365*/1366for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1367int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;1368int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];1369if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */1370WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);1371for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {1372int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];1373if (cinfo->Ah != expected)1374WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);1375coef_bit_ptr[coefi] = cinfo->Al;1376}1377}13781379/* Select MCU decoding routine */1380if (cinfo->Ah == 0) {1381if (cinfo->Ss == 0)1382entropy->pub.decode_mcu = decode_mcu_DC_first;1383else1384entropy->pub.decode_mcu = decode_mcu_AC_first;1385} else {1386if (cinfo->Ss == 0)1387entropy->pub.decode_mcu = decode_mcu_DC_refine;1388else1389entropy->pub.decode_mcu = decode_mcu_AC_refine;1390}13911392for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1393compptr = cinfo->cur_comp_info[ci];1394/* Make sure requested tables are present, and compute derived tables.1395* We may build same derived table more than once, but it's not expensive.1396*/1397if (cinfo->Ss == 0) {1398if (cinfo->Ah == 0) { /* DC refinement needs no table */1399tbl = compptr->dc_tbl_no;1400jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,1401& entropy->derived_tbls[tbl]);1402}1403} else {1404tbl = compptr->ac_tbl_no;1405jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,1406& entropy->derived_tbls[tbl]);1407/* remember the single active table */1408entropy->ac_derived_tbl = entropy->derived_tbls[tbl];1409}1410/* Initialize DC predictions to 0 */1411entropy->saved.last_dc_val[ci] = 0;1412}14131414/* Initialize private state variables */1415entropy->saved.EOBRUN = 0;1416} else {1417/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.1418* This ought to be an error condition, but we make it a warning because1419* there are some baseline files out there with all zeroes in these bytes.1420*/1421if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||1422((cinfo->is_baseline || cinfo->Se < DCTSIZE2) &&1423cinfo->Se != cinfo->lim_Se))1424WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);14251426/* Select MCU decoding routine */1427/* We retain the hard-coded case for full-size blocks.1428* This is not necessary, but it appears that this version is slightly1429* more performant in the given implementation.1430* With an improved implementation we would prefer a single optimized1431* function.1432*/1433if (cinfo->lim_Se != DCTSIZE2-1)1434entropy->pub.decode_mcu = decode_mcu_sub;1435else1436entropy->pub.decode_mcu = decode_mcu;14371438for (ci = 0; ci < cinfo->comps_in_scan; ci++) {1439compptr = cinfo->cur_comp_info[ci];1440/* Compute derived values for Huffman tables */1441/* We may do this more than once for a table, but it's not expensive */1442tbl = compptr->dc_tbl_no;1443jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,1444& entropy->dc_derived_tbls[tbl]);1445if (cinfo->lim_Se) { /* AC needs no table when not present */1446tbl = compptr->ac_tbl_no;1447jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,1448& entropy->ac_derived_tbls[tbl]);1449}1450/* Initialize DC predictions to 0 */1451entropy->saved.last_dc_val[ci] = 0;1452}14531454/* Precalculate decoding info for each block in an MCU of this scan */1455for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {1456ci = cinfo->MCU_membership[blkn];1457compptr = cinfo->cur_comp_info[ci];1458/* Precalculate which table to use for each block */1459entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];1460entropy->ac_cur_tbls[blkn] = /* AC needs no table when not present */1461cinfo->lim_Se ? entropy->ac_derived_tbls[compptr->ac_tbl_no] : NULL;1462/* Decide whether we really care about the coefficient values */1463if (compptr->component_needed) {1464ci = compptr->DCT_v_scaled_size;1465i = compptr->DCT_h_scaled_size;1466switch (cinfo->lim_Se) {1467case (1*1-1):1468entropy->coef_limit[blkn] = 1;1469break;1470case (2*2-1):1471if (ci <= 0 || ci > 2) ci = 2;1472if (i <= 0 || i > 2) i = 2;1473entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1];1474break;1475case (3*3-1):1476if (ci <= 0 || ci > 3) ci = 3;1477if (i <= 0 || i > 3) i = 3;1478entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1];1479break;1480case (4*4-1):1481if (ci <= 0 || ci > 4) ci = 4;1482if (i <= 0 || i > 4) i = 4;1483entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1];1484break;1485case (5*5-1):1486if (ci <= 0 || ci > 5) ci = 5;1487if (i <= 0 || i > 5) i = 5;1488entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1];1489break;1490case (6*6-1):1491if (ci <= 0 || ci > 6) ci = 6;1492if (i <= 0 || i > 6) i = 6;1493entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1];1494break;1495case (7*7-1):1496if (ci <= 0 || ci > 7) ci = 7;1497if (i <= 0 || i > 7) i = 7;1498entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1];1499break;1500default:1501if (ci <= 0 || ci > 8) ci = 8;1502if (i <= 0 || i > 8) i = 8;1503entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];1504}1505} else {1506entropy->coef_limit[blkn] = 0;1507}1508}1509}15101511/* Initialize bitread state variables */1512entropy->bitstate.bits_left = 0;1513entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */1514entropy->insufficient_data = FALSE;15151516/* Initialize restart counter */1517entropy->restarts_to_go = cinfo->restart_interval;1518}151915201521/*1522* Module initialization routine for Huffman entropy decoding.1523*/15241525GLOBAL(void)1526jinit_huff_decoder (j_decompress_ptr cinfo)1527{1528huff_entropy_ptr entropy;1529int i;15301531entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small)1532((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_decoder));1533cinfo->entropy = &entropy->pub;1534entropy->pub.start_pass = start_pass_huff_decoder;1535entropy->pub.finish_pass = finish_pass_huff;15361537if (cinfo->progressive_mode) {1538/* Create progression status table */1539int *coef_bit_ptr, ci;1540cinfo->coef_bits = (int (*)[DCTSIZE2]) (*cinfo->mem->alloc_small)1541((j_common_ptr) cinfo, JPOOL_IMAGE,1542cinfo->num_components * DCTSIZE2 * SIZEOF(int));1543coef_bit_ptr = & cinfo->coef_bits[0][0];1544for (ci = 0; ci < cinfo->num_components; ci++)1545for (i = 0; i < DCTSIZE2; i++)1546*coef_bit_ptr++ = -1;15471548/* Mark derived tables unallocated */1549for (i = 0; i < NUM_HUFF_TBLS; i++) {1550entropy->derived_tbls[i] = NULL;1551}1552} else {1553/* Mark derived tables unallocated */1554for (i = 0; i < NUM_HUFF_TBLS; i++) {1555entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;1556}1557}1558}155915601561