Path: blob/master/thirdparty/libjpeg-turbo/src/jdhuff.c
9904 views
/*1* jdhuff.c2*3* This file was part of the Independent JPEG Group's software:4* Copyright (C) 1991-1997, Thomas G. Lane.5* Lossless JPEG Modifications:6* Copyright (C) 1999, Ken Murchison.7* libjpeg-turbo Modifications:8* Copyright (C) 2009-2011, 2016, 2018-2019, 2022, D. R. Commander.9* Copyright (C) 2018, Matthias Räncker.10* For conditions of distribution and use, see the accompanying README.ijg11* file.12*13* This file contains Huffman entropy decoding routines.14*15* Much of the complexity here has to do with supporting input suspension.16* If the data source module demands suspension, we want to be able to back17* up to the start of the current MCU. To do this, we copy state variables18* into local working storage, and update them back to the permanent19* storage only upon successful completion of an MCU.20*21* NOTE: All referenced figures are from22* Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.23*/2425#define JPEG_INTERNALS26#include "jinclude.h"27#include "jpeglib.h"28#include "jdhuff.h" /* Declarations shared with jd*huff.c */29#include "jpegapicomp.h"30#include "jstdhuff.c"313233/*34* Expanded entropy decoder object for Huffman decoding.35*36* The savable_state subrecord contains fields that change within an MCU,37* but must not be updated permanently until we complete the MCU.38*/3940typedef struct {41int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */42} savable_state;4344typedef struct {45struct jpeg_entropy_decoder pub; /* public fields */4647/* These fields are loaded into local variables at start of each MCU.48* In case of suspension, we exit WITHOUT updating them.49*/50bitread_perm_state bitstate; /* Bit buffer at start of MCU */51savable_state saved; /* Other state at start of MCU */5253/* These fields are NOT loaded into local working state. */54unsigned int restarts_to_go; /* MCUs left in this restart interval */5556/* Pointers to derived tables (these workspaces have image lifespan) */57d_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];58d_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];5960/* Precalculated info set up by start_pass for use in decode_mcu: */6162/* Pointers to derived tables to be used for each block within an MCU */63d_derived_tbl *dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];64d_derived_tbl *ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];65/* Whether we care about the DC and AC coefficient values for each block */66boolean dc_needed[D_MAX_BLOCKS_IN_MCU];67boolean ac_needed[D_MAX_BLOCKS_IN_MCU];68} huff_entropy_decoder;6970typedef huff_entropy_decoder *huff_entropy_ptr;717273/*74* Initialize for a Huffman-compressed scan.75*/7677METHODDEF(void)78start_pass_huff_decoder(j_decompress_ptr cinfo)79{80huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;81int ci, blkn, dctbl, actbl;82d_derived_tbl **pdtbl;83jpeg_component_info *compptr;8485/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.86* This ought to be an error condition, but we make it a warning because87* there are some baseline files out there with all zeroes in these bytes.88*/89if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||90cinfo->Ah != 0 || cinfo->Al != 0)91WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);9293for (ci = 0; ci < cinfo->comps_in_scan; ci++) {94compptr = cinfo->cur_comp_info[ci];95dctbl = compptr->dc_tbl_no;96actbl = compptr->ac_tbl_no;97/* Compute derived values for Huffman tables */98/* We may do this more than once for a table, but it's not expensive */99pdtbl = (d_derived_tbl **)(entropy->dc_derived_tbls) + dctbl;100jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl, pdtbl);101pdtbl = (d_derived_tbl **)(entropy->ac_derived_tbls) + actbl;102jpeg_make_d_derived_tbl(cinfo, FALSE, actbl, pdtbl);103/* Initialize DC predictions to 0 */104entropy->saved.last_dc_val[ci] = 0;105}106107/* Precalculate decoding info for each block in an MCU of this scan */108for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {109ci = cinfo->MCU_membership[blkn];110compptr = cinfo->cur_comp_info[ci];111/* Precalculate which table to use for each block */112entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];113entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];114/* Decide whether we really care about the coefficient values */115if (compptr->component_needed) {116entropy->dc_needed[blkn] = TRUE;117/* we don't need the ACs if producing a 1/8th-size image */118entropy->ac_needed[blkn] = (compptr->_DCT_scaled_size > 1);119} else {120entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;121}122}123124/* Initialize bitread state variables */125entropy->bitstate.bits_left = 0;126entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */127entropy->pub.insufficient_data = FALSE;128129/* Initialize restart counter */130entropy->restarts_to_go = cinfo->restart_interval;131}132133134/*135* Compute the derived values for a Huffman table.136* This routine also performs some validation checks on the table.137*138* Note this is also used by jdphuff.c and jdlhuff.c.139*/140141GLOBAL(void)142jpeg_make_d_derived_tbl(j_decompress_ptr cinfo, boolean isDC, int tblno,143d_derived_tbl **pdtbl)144{145JHUFF_TBL *htbl;146d_derived_tbl *dtbl;147int p, i, l, si, numsymbols;148int lookbits, ctr;149char huffsize[257];150unsigned int huffcode[257];151unsigned int code;152153/* Note that huffsize[] and huffcode[] are filled in code-length order,154* paralleling the order of the symbols themselves in htbl->huffval[].155*/156157/* Find the input Huffman table */158if (tblno < 0 || tblno >= NUM_HUFF_TBLS)159ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);160htbl =161isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];162if (htbl == NULL)163ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);164165/* Allocate a workspace if we haven't already done so. */166if (*pdtbl == NULL)167*pdtbl = (d_derived_tbl *)168(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,169sizeof(d_derived_tbl));170dtbl = *pdtbl;171dtbl->pub = htbl; /* fill in back link */172173/* Figure C.1: make table of Huffman code length for each symbol */174175p = 0;176for (l = 1; l <= 16; l++) {177i = (int)htbl->bits[l];178if (i < 0 || p + i > 256) /* protect against table overrun */179ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);180while (i--)181huffsize[p++] = (char)l;182}183huffsize[p] = 0;184numsymbols = p;185186/* Figure C.2: generate the codes themselves */187/* We also validate that the counts represent a legal Huffman code tree. */188189code = 0;190si = huffsize[0];191p = 0;192while (huffsize[p]) {193while (((int)huffsize[p]) == si) {194huffcode[p++] = code;195code++;196}197/* code is now 1 more than the last code used for codelength si; but198* it must still fit in si bits, since no code is allowed to be all ones.199*/200if (((JLONG)code) >= (((JLONG)1) << si))201ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);202code <<= 1;203si++;204}205206/* Figure F.15: generate decoding tables for bit-sequential decoding */207208p = 0;209for (l = 1; l <= 16; l++) {210if (htbl->bits[l]) {211/* valoffset[l] = huffval[] index of 1st symbol of code length l,212* minus the minimum code of length l213*/214dtbl->valoffset[l] = (JLONG)p - (JLONG)huffcode[p];215p += htbl->bits[l];216dtbl->maxcode[l] = huffcode[p - 1]; /* maximum code of length l */217} else {218dtbl->maxcode[l] = -1; /* -1 if no codes of this length */219}220}221dtbl->valoffset[17] = 0;222dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */223224/* Compute lookahead tables to speed up decoding.225* First we set all the table entries to 0, indicating "too long";226* then we iterate through the Huffman codes that are short enough and227* fill in all the entries that correspond to bit sequences starting228* with that code.229*/230231for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++)232dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;233234p = 0;235for (l = 1; l <= HUFF_LOOKAHEAD; l++) {236for (i = 1; i <= (int)htbl->bits[l]; i++, p++) {237/* l = current code's length, p = its index in huffcode[] & huffval[]. */238/* Generate left-justified code followed by all possible bit sequences */239lookbits = huffcode[p] << (HUFF_LOOKAHEAD - l);240for (ctr = 1 << (HUFF_LOOKAHEAD - l); ctr > 0; ctr--) {241dtbl->lookup[lookbits] = (l << HUFF_LOOKAHEAD) | htbl->huffval[p];242lookbits++;243}244}245}246247/* Validate symbols as being reasonable.248* For AC tables, we make no check, but accept all byte values 0..255.249* For DC tables, we require the symbols to be in range 0..15 in lossy mode250* and 0..16 in lossless mode. (Tighter bounds could be applied depending on251* the data depth and mode, but this is sufficient to ensure safe decoding.)252*/253if (isDC) {254for (i = 0; i < numsymbols; i++) {255int sym = htbl->huffval[i];256if (sym < 0 || sym > (cinfo->master->lossless ? 16 : 15))257ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);258}259}260}261262263/*264* Out-of-line code for bit fetching (shared with jdphuff.c and jdlhuff.c).265* See jdhuff.h for info about usage.266* Note: current values of get_buffer and bits_left are passed as parameters,267* but are returned in the corresponding fields of the state struct.268*269* On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width270* of get_buffer to be used. (On machines with wider words, an even larger271* buffer could be used.) However, on some machines 32-bit shifts are272* quite slow and take time proportional to the number of places shifted.273* (This is true with most PC compilers, for instance.) In this case it may274* be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the275* average shift distance at the cost of more calls to jpeg_fill_bit_buffer.276*/277278#ifdef SLOW_SHIFT_32279#define MIN_GET_BITS 15 /* minimum allowable value */280#else281#define MIN_GET_BITS (BIT_BUF_SIZE - 7)282#endif283284285GLOBAL(boolean)286jpeg_fill_bit_buffer(bitread_working_state *state,287register bit_buf_type get_buffer, register int bits_left,288int nbits)289/* Load up the bit buffer to a depth of at least nbits */290{291/* Copy heavily used state fields into locals (hopefully registers) */292register const JOCTET *next_input_byte = state->next_input_byte;293register size_t bytes_in_buffer = state->bytes_in_buffer;294j_decompress_ptr cinfo = state->cinfo;295296/* Attempt to load at least MIN_GET_BITS bits into get_buffer. */297/* (It is assumed that no request will be for more than that many bits.) */298/* We fail to do so only if we hit a marker or are forced to suspend. */299300if (cinfo->unread_marker == 0) { /* cannot advance past a marker */301while (bits_left < MIN_GET_BITS) {302register int c;303304/* Attempt to read a byte */305if (bytes_in_buffer == 0) {306if (!(*cinfo->src->fill_input_buffer) (cinfo))307return FALSE;308next_input_byte = cinfo->src->next_input_byte;309bytes_in_buffer = cinfo->src->bytes_in_buffer;310}311bytes_in_buffer--;312c = *next_input_byte++;313314/* If it's 0xFF, check and discard stuffed zero byte */315if (c == 0xFF) {316/* Loop here to discard any padding FF's on terminating marker,317* so that we can save a valid unread_marker value. NOTE: we will318* accept multiple FF's followed by a 0 as meaning a single FF data319* byte. This data pattern is not valid according to the standard.320*/321do {322if (bytes_in_buffer == 0) {323if (!(*cinfo->src->fill_input_buffer) (cinfo))324return FALSE;325next_input_byte = cinfo->src->next_input_byte;326bytes_in_buffer = cinfo->src->bytes_in_buffer;327}328bytes_in_buffer--;329c = *next_input_byte++;330} while (c == 0xFF);331332if (c == 0) {333/* Found FF/00, which represents an FF data byte */334c = 0xFF;335} else {336/* Oops, it's actually a marker indicating end of compressed data.337* Save the marker code for later use.338* Fine point: it might appear that we should save the marker into339* bitread working state, not straight into permanent state. But340* once we have hit a marker, we cannot need to suspend within the341* current MCU, because we will read no more bytes from the data342* source. So it is OK to update permanent state right away.343*/344cinfo->unread_marker = c;345/* See if we need to insert some fake zero bits. */346goto no_more_bytes;347}348}349350/* OK, load c into get_buffer */351get_buffer = (get_buffer << 8) | c;352bits_left += 8;353} /* end while */354} else {355no_more_bytes:356/* We get here if we've read the marker that terminates the compressed357* data segment. There should be enough bits in the buffer register358* to satisfy the request; if so, no problem.359*/360if (nbits > bits_left) {361/* Uh-oh. Report corrupted data to user and stuff zeroes into362* the data stream, so that we can produce some kind of image.363* We use a nonvolatile flag to ensure that only one warning message364* appears per data segment.365*/366if (!cinfo->entropy->insufficient_data) {367WARNMS(cinfo, JWRN_HIT_MARKER);368cinfo->entropy->insufficient_data = TRUE;369}370/* Fill the buffer with zero bits */371get_buffer <<= MIN_GET_BITS - bits_left;372bits_left = MIN_GET_BITS;373}374}375376/* Unload the local registers */377state->next_input_byte = next_input_byte;378state->bytes_in_buffer = bytes_in_buffer;379state->get_buffer = get_buffer;380state->bits_left = bits_left;381382return TRUE;383}384385386/* Macro version of the above, which performs much better but does not387handle markers. We have to hand off any blocks with markers to the388slower routines. */389390#define GET_BYTE { \391register int c0, c1; \392c0 = *buffer++; \393c1 = *buffer; \394/* Pre-execute most common case */ \395get_buffer = (get_buffer << 8) | c0; \396bits_left += 8; \397if (c0 == 0xFF) { \398/* Pre-execute case of FF/00, which represents an FF data byte */ \399buffer++; \400if (c1 != 0) { \401/* Oops, it's actually a marker indicating end of compressed data. */ \402cinfo->unread_marker = c1; \403/* Back out pre-execution and fill the buffer with zero bits */ \404buffer -= 2; \405get_buffer &= ~0xFF; \406} \407} \408}409410#if SIZEOF_SIZE_T == 8 || defined(_WIN64) || (defined(__x86_64__) && defined(__ILP32__))411412/* Pre-fetch 48 bytes, because the holding register is 64-bit */413#define FILL_BIT_BUFFER_FAST \414if (bits_left <= 16) { \415GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE \416}417418#else419420/* Pre-fetch 16 bytes, because the holding register is 32-bit */421#define FILL_BIT_BUFFER_FAST \422if (bits_left <= 16) { \423GET_BYTE GET_BYTE \424}425426#endif427428429/*430* Out-of-line code for Huffman code decoding.431* See jdhuff.h for info about usage.432*/433434GLOBAL(int)435jpeg_huff_decode(bitread_working_state *state,436register bit_buf_type get_buffer, register int bits_left,437d_derived_tbl *htbl, int min_bits)438{439register int l = min_bits;440register JLONG code;441442/* HUFF_DECODE has determined that the code is at least min_bits */443/* bits long, so fetch that many bits in one swoop. */444445CHECK_BIT_BUFFER(*state, l, return -1);446code = GET_BITS(l);447448/* Collect the rest of the Huffman code one bit at a time. */449/* This is per Figure F.16. */450451while (code > htbl->maxcode[l]) {452code <<= 1;453CHECK_BIT_BUFFER(*state, 1, return -1);454code |= GET_BITS(1);455l++;456}457458/* Unload the local registers */459state->get_buffer = get_buffer;460state->bits_left = bits_left;461462/* With garbage input we may reach the sentinel value l = 17. */463464if (l > 16) {465WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);466return 0; /* fake a zero as the safest result */467}468469return htbl->pub->huffval[(int)(code + htbl->valoffset[l])];470}471472473/*474* Figure F.12: extend sign bit.475* On some machines, a shift and add will be faster than a table lookup.476*/477478#define AVOID_TABLES479#ifdef AVOID_TABLES480481#define NEG_1 ((unsigned int)-1)482#define HUFF_EXTEND(x, s) \483((x) + ((((x) - (1 << ((s) - 1))) >> 31) & (((NEG_1) << (s)) + 1)))484485#else486487#define HUFF_EXTEND(x, s) \488((x) < extend_test[s] ? (x) + extend_offset[s] : (x))489490static const int extend_test[16] = { /* entry n is 2**(n-1) */4910, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,4920x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000493};494495static const int extend_offset[16] = { /* entry n is (-1 << n) + 1 */4960, ((-1) << 1) + 1, ((-1) << 2) + 1, ((-1) << 3) + 1, ((-1) << 4) + 1,497((-1) << 5) + 1, ((-1) << 6) + 1, ((-1) << 7) + 1, ((-1) << 8) + 1,498((-1) << 9) + 1, ((-1) << 10) + 1, ((-1) << 11) + 1, ((-1) << 12) + 1,499((-1) << 13) + 1, ((-1) << 14) + 1, ((-1) << 15) + 1500};501502#endif /* AVOID_TABLES */503504505/*506* Check for a restart marker & resynchronize decoder.507* Returns FALSE if must suspend.508*/509510LOCAL(boolean)511process_restart(j_decompress_ptr cinfo)512{513huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;514int ci;515516/* Throw away any unused bits remaining in bit buffer; */517/* include any full bytes in next_marker's count of discarded bytes */518cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;519entropy->bitstate.bits_left = 0;520521/* Advance past the RSTn marker */522if (!(*cinfo->marker->read_restart_marker) (cinfo))523return FALSE;524525/* Re-initialize DC predictions to 0 */526for (ci = 0; ci < cinfo->comps_in_scan; ci++)527entropy->saved.last_dc_val[ci] = 0;528529/* Reset restart counter */530entropy->restarts_to_go = cinfo->restart_interval;531532/* Reset out-of-data flag, unless read_restart_marker left us smack up533* against a marker. In that case we will end up treating the next data534* segment as empty, and we can avoid producing bogus output pixels by535* leaving the flag set.536*/537if (cinfo->unread_marker == 0)538entropy->pub.insufficient_data = FALSE;539540return TRUE;541}542543544#if defined(__has_feature)545#if __has_feature(undefined_behavior_sanitizer)546__attribute__((no_sanitize("signed-integer-overflow"),547no_sanitize("unsigned-integer-overflow")))548#endif549#endif550LOCAL(boolean)551decode_mcu_slow(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)552{553huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;554BITREAD_STATE_VARS;555int blkn;556savable_state state;557/* Outer loop handles each block in the MCU */558559/* Load up working state */560BITREAD_LOAD_STATE(cinfo, entropy->bitstate);561state = entropy->saved;562563for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {564JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;565d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];566d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];567register int s, k, r;568569/* Decode a single block's worth of coefficients */570571/* Section F.2.2.1: decode the DC coefficient difference */572HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);573if (s) {574CHECK_BIT_BUFFER(br_state, s, return FALSE);575r = GET_BITS(s);576s = HUFF_EXTEND(r, s);577}578579if (entropy->dc_needed[blkn]) {580/* Convert DC difference to actual value, update last_dc_val */581int ci = cinfo->MCU_membership[blkn];582/* Certain malformed JPEG images produce repeated DC coefficient583* differences of 2047 or -2047, which causes state.last_dc_val[ci] to584* grow until it overflows or underflows a 32-bit signed integer. This585* behavior is, to the best of our understanding, innocuous, and it is586* unclear how to work around it without potentially affecting587* performance. Thus, we (hopefully temporarily) suppress UBSan integer588* overflow errors for this function and decode_mcu_fast().589*/590s += state.last_dc_val[ci];591state.last_dc_val[ci] = s;592if (block) {593/* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */594(*block)[0] = (JCOEF)s;595}596}597598if (entropy->ac_needed[blkn] && block) {599600/* Section F.2.2.2: decode the AC coefficients */601/* Since zeroes are skipped, output area must be cleared beforehand */602for (k = 1; k < DCTSIZE2; k++) {603HUFF_DECODE(s, br_state, actbl, return FALSE, label2);604605r = s >> 4;606s &= 15;607608if (s) {609k += r;610CHECK_BIT_BUFFER(br_state, s, return FALSE);611r = GET_BITS(s);612s = HUFF_EXTEND(r, s);613/* Output coefficient in natural (dezigzagged) order.614* Note: the extra entries in jpeg_natural_order[] will save us615* if k >= DCTSIZE2, which could happen if the data is corrupted.616*/617(*block)[jpeg_natural_order[k]] = (JCOEF)s;618} else {619if (r != 15)620break;621k += 15;622}623}624625} else {626627/* Section F.2.2.2: decode the AC coefficients */628/* In this path we just discard the values */629for (k = 1; k < DCTSIZE2; k++) {630HUFF_DECODE(s, br_state, actbl, return FALSE, label3);631632r = s >> 4;633s &= 15;634635if (s) {636k += r;637CHECK_BIT_BUFFER(br_state, s, return FALSE);638DROP_BITS(s);639} else {640if (r != 15)641break;642k += 15;643}644}645}646}647648/* Completed MCU, so update state */649BITREAD_SAVE_STATE(cinfo, entropy->bitstate);650entropy->saved = state;651return TRUE;652}653654655#if defined(__has_feature)656#if __has_feature(undefined_behavior_sanitizer)657__attribute__((no_sanitize("signed-integer-overflow"),658no_sanitize("unsigned-integer-overflow")))659#endif660#endif661LOCAL(boolean)662decode_mcu_fast(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)663{664huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;665BITREAD_STATE_VARS;666JOCTET *buffer;667int blkn;668savable_state state;669/* Outer loop handles each block in the MCU */670671/* Load up working state */672BITREAD_LOAD_STATE(cinfo, entropy->bitstate);673buffer = (JOCTET *)br_state.next_input_byte;674state = entropy->saved;675676for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {677JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;678d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];679d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];680register int s, k, r, l;681682HUFF_DECODE_FAST(s, l, dctbl);683if (s) {684FILL_BIT_BUFFER_FAST685r = GET_BITS(s);686s = HUFF_EXTEND(r, s);687}688689if (entropy->dc_needed[blkn]) {690int ci = cinfo->MCU_membership[blkn];691/* Refer to the comment in decode_mcu_slow() regarding the supression of692* a UBSan integer overflow error in this line of code.693*/694s += state.last_dc_val[ci];695state.last_dc_val[ci] = s;696if (block)697(*block)[0] = (JCOEF)s;698}699700if (entropy->ac_needed[blkn] && block) {701702for (k = 1; k < DCTSIZE2; k++) {703HUFF_DECODE_FAST(s, l, actbl);704r = s >> 4;705s &= 15;706707if (s) {708k += r;709FILL_BIT_BUFFER_FAST710r = GET_BITS(s);711s = HUFF_EXTEND(r, s);712(*block)[jpeg_natural_order[k]] = (JCOEF)s;713} else {714if (r != 15) break;715k += 15;716}717}718719} else {720721for (k = 1; k < DCTSIZE2; k++) {722HUFF_DECODE_FAST(s, l, actbl);723r = s >> 4;724s &= 15;725726if (s) {727k += r;728FILL_BIT_BUFFER_FAST729DROP_BITS(s);730} else {731if (r != 15) break;732k += 15;733}734}735}736}737738if (cinfo->unread_marker != 0) {739cinfo->unread_marker = 0;740return FALSE;741}742743br_state.bytes_in_buffer -= (buffer - br_state.next_input_byte);744br_state.next_input_byte = buffer;745BITREAD_SAVE_STATE(cinfo, entropy->bitstate);746entropy->saved = state;747return TRUE;748}749750751/*752* Decode and return one MCU's worth of Huffman-compressed coefficients.753* The coefficients are reordered from zigzag order into natural array order,754* but are not dequantized.755*756* The i'th block of the MCU is stored into the block pointed to by757* MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.758* (Wholesale zeroing is usually a little faster than retail...)759*760* Returns FALSE if data source requested suspension. In that case no761* changes have been made to permanent state. (Exception: some output762* coefficients may already have been assigned. This is harmless for763* this module, since we'll just re-assign them on the next call.)764*/765766#define BUFSIZE (DCTSIZE2 * 8)767768METHODDEF(boolean)769decode_mcu(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)770{771huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;772int usefast = 1;773774/* Process restart marker if needed; may have to suspend */775if (cinfo->restart_interval) {776if (entropy->restarts_to_go == 0)777if (!process_restart(cinfo))778return FALSE;779usefast = 0;780}781782if (cinfo->src->bytes_in_buffer < BUFSIZE * (size_t)cinfo->blocks_in_MCU ||783cinfo->unread_marker != 0)784usefast = 0;785786/* If we've run out of data, just leave the MCU set to zeroes.787* This way, we return uniform gray for the remainder of the segment.788*/789if (!entropy->pub.insufficient_data) {790791if (usefast) {792if (!decode_mcu_fast(cinfo, MCU_data)) goto use_slow;793} else {794use_slow:795if (!decode_mcu_slow(cinfo, MCU_data)) return FALSE;796}797798}799800/* Account for restart interval (no-op if not using restarts) */801if (cinfo->restart_interval)802entropy->restarts_to_go--;803804return TRUE;805}806807808/*809* Module initialization routine for Huffman entropy decoding.810*/811812GLOBAL(void)813jinit_huff_decoder(j_decompress_ptr cinfo)814{815huff_entropy_ptr entropy;816int i;817818/* Motion JPEG frames typically do not include the Huffman tables if they819are the default tables. Thus, if the tables are not set by the time820the Huffman decoder is initialized (usually within the body of821jpeg_start_decompress()), we set them to default values. */822std_huff_tables((j_common_ptr)cinfo);823824entropy = (huff_entropy_ptr)825(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,826sizeof(huff_entropy_decoder));827cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;828entropy->pub.start_pass = start_pass_huff_decoder;829entropy->pub.decode_mcu = decode_mcu;830831/* Mark tables unallocated */832for (i = 0; i < NUM_HUFF_TBLS; i++) {833entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;834}835}836837838