Path: blob/master/3rdparty/libjpeg-turbo/src/jdphuff.c
16337 views
/*1* jdphuff.c2*3* This file was part of the Independent JPEG Group's software:4* Copyright (C) 1995-1997, Thomas G. Lane.5* libjpeg-turbo Modifications:6* Copyright (C) 2015-2016, D. R. Commander.7* For conditions of distribution and use, see the accompanying README.ijg8* file.9*10* This file contains Huffman entropy decoding routines for progressive JPEG.11*12* Much of the complexity here has to do with supporting input suspension.13* If the data source module demands suspension, we want to be able to back14* up to the start of the current MCU. To do this, we copy state variables15* into local working storage, and update them back to the permanent16* storage only upon successful completion of an MCU.17*/1819#define JPEG_INTERNALS20#include "jinclude.h"21#include "jpeglib.h"22#include "jdhuff.h" /* Declarations shared with jdhuff.c */232425#ifdef D_PROGRESSIVE_SUPPORTED2627/*28* Expanded entropy decoder object for progressive Huffman decoding.29*30* The savable_state subrecord contains fields that change within an MCU,31* but must not be updated permanently until we complete the MCU.32*/3334typedef struct {35unsigned int EOBRUN; /* remaining EOBs in EOBRUN */36int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */37} savable_state;3839/* This macro is to work around compilers with missing or broken40* structure assignment. You'll need to fix this code if you have41* such a compiler and you change MAX_COMPS_IN_SCAN.42*/4344#ifndef NO_STRUCT_ASSIGN45#define ASSIGN_STATE(dest,src) ((dest) = (src))46#else47#if MAX_COMPS_IN_SCAN == 448#define ASSIGN_STATE(dest,src) \49((dest).EOBRUN = (src).EOBRUN, \50(dest).last_dc_val[0] = (src).last_dc_val[0], \51(dest).last_dc_val[1] = (src).last_dc_val[1], \52(dest).last_dc_val[2] = (src).last_dc_val[2], \53(dest).last_dc_val[3] = (src).last_dc_val[3])54#endif55#endif565758typedef struct {59struct jpeg_entropy_decoder pub; /* public fields */6061/* These fields are loaded into local variables at start of each MCU.62* In case of suspension, we exit WITHOUT updating them.63*/64bitread_perm_state bitstate; /* Bit buffer at start of MCU */65savable_state saved; /* Other state at start of MCU */6667/* These fields are NOT loaded into local working state. */68unsigned int restarts_to_go; /* MCUs left in this restart interval */6970/* Pointers to derived tables (these workspaces have image lifespan) */71d_derived_tbl *derived_tbls[NUM_HUFF_TBLS];7273d_derived_tbl *ac_derived_tbl; /* active table during an AC scan */74} phuff_entropy_decoder;7576typedef phuff_entropy_decoder *phuff_entropy_ptr;7778/* Forward declarations */79METHODDEF(boolean) decode_mcu_DC_first (j_decompress_ptr cinfo,80JBLOCKROW *MCU_data);81METHODDEF(boolean) decode_mcu_AC_first (j_decompress_ptr cinfo,82JBLOCKROW *MCU_data);83METHODDEF(boolean) decode_mcu_DC_refine (j_decompress_ptr cinfo,84JBLOCKROW *MCU_data);85METHODDEF(boolean) decode_mcu_AC_refine (j_decompress_ptr cinfo,86JBLOCKROW *MCU_data);878889/*90* Initialize for a Huffman-compressed scan.91*/9293METHODDEF(void)94start_pass_phuff_decoder (j_decompress_ptr cinfo)95{96phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;97boolean is_DC_band, bad;98int ci, coefi, tbl;99d_derived_tbl **pdtbl;100int *coef_bit_ptr;101jpeg_component_info *compptr;102103is_DC_band = (cinfo->Ss == 0);104105/* Validate scan parameters */106bad = FALSE;107if (is_DC_band) {108if (cinfo->Se != 0)109bad = TRUE;110} else {111/* need not check Ss/Se < 0 since they came from unsigned bytes */112if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)113bad = TRUE;114/* AC scans may have only one component */115if (cinfo->comps_in_scan != 1)116bad = TRUE;117}118if (cinfo->Ah != 0) {119/* Successive approximation refinement scan: must have Al = Ah-1. */120if (cinfo->Al != cinfo->Ah-1)121bad = TRUE;122}123if (cinfo->Al > 13) /* need not check for < 0 */124bad = TRUE;125/* Arguably the maximum Al value should be less than 13 for 8-bit precision,126* but the spec doesn't say so, and we try to be liberal about what we127* accept. Note: large Al values could result in out-of-range DC128* coefficients during early scans, leading to bizarre displays due to129* overflows in the IDCT math. But we won't crash.130*/131if (bad)132ERREXIT4(cinfo, JERR_BAD_PROGRESSION,133cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);134/* Update progression status, and verify that scan order is legal.135* Note that inter-scan inconsistencies are treated as warnings136* not fatal errors ... not clear if this is right way to behave.137*/138for (ci = 0; ci < cinfo->comps_in_scan; ci++) {139int cindex = cinfo->cur_comp_info[ci]->component_index;140coef_bit_ptr = & cinfo->coef_bits[cindex][0];141if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */142WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);143for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {144int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];145if (cinfo->Ah != expected)146WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);147coef_bit_ptr[coefi] = cinfo->Al;148}149}150151/* Select MCU decoding routine */152if (cinfo->Ah == 0) {153if (is_DC_band)154entropy->pub.decode_mcu = decode_mcu_DC_first;155else156entropy->pub.decode_mcu = decode_mcu_AC_first;157} else {158if (is_DC_band)159entropy->pub.decode_mcu = decode_mcu_DC_refine;160else161entropy->pub.decode_mcu = decode_mcu_AC_refine;162}163164for (ci = 0; ci < cinfo->comps_in_scan; ci++) {165compptr = cinfo->cur_comp_info[ci];166/* Make sure requested tables are present, and compute derived tables.167* We may build same derived table more than once, but it's not expensive.168*/169if (is_DC_band) {170if (cinfo->Ah == 0) { /* DC refinement needs no table */171tbl = compptr->dc_tbl_no;172pdtbl = (d_derived_tbl **)(entropy->derived_tbls) + tbl;173jpeg_make_d_derived_tbl(cinfo, TRUE, tbl, pdtbl);174}175} else {176tbl = compptr->ac_tbl_no;177pdtbl = (d_derived_tbl **)(entropy->derived_tbls) + tbl;178jpeg_make_d_derived_tbl(cinfo, FALSE, tbl, pdtbl);179/* remember the single active table */180entropy->ac_derived_tbl = entropy->derived_tbls[tbl];181}182/* Initialize DC predictions to 0 */183entropy->saved.last_dc_val[ci] = 0;184}185186/* Initialize bitread state variables */187entropy->bitstate.bits_left = 0;188entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */189entropy->pub.insufficient_data = FALSE;190191/* Initialize private state variables */192entropy->saved.EOBRUN = 0;193194/* Initialize restart counter */195entropy->restarts_to_go = cinfo->restart_interval;196}197198199/*200* Figure F.12: extend sign bit.201* On some machines, a shift and add will be faster than a table lookup.202*/203204#define AVOID_TABLES205#ifdef AVOID_TABLES206207#define NEG_1 ((unsigned)-1)208#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((NEG_1)<<(s)) + 1) : (x))209210#else211212#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))213214static const int extend_test[16] = /* entry n is 2**(n-1) */215{ 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,2160x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };217218static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */219{ 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,220((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,221((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,222((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };223224#endif /* AVOID_TABLES */225226227/*228* Check for a restart marker & resynchronize decoder.229* Returns FALSE if must suspend.230*/231232LOCAL(boolean)233process_restart (j_decompress_ptr cinfo)234{235phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;236int ci;237238/* Throw away any unused bits remaining in bit buffer; */239/* include any full bytes in next_marker's count of discarded bytes */240cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;241entropy->bitstate.bits_left = 0;242243/* Advance past the RSTn marker */244if (! (*cinfo->marker->read_restart_marker) (cinfo))245return FALSE;246247/* Re-initialize DC predictions to 0 */248for (ci = 0; ci < cinfo->comps_in_scan; ci++)249entropy->saved.last_dc_val[ci] = 0;250/* Re-init EOB run count, too */251entropy->saved.EOBRUN = 0;252253/* Reset restart counter */254entropy->restarts_to_go = cinfo->restart_interval;255256/* Reset out-of-data flag, unless read_restart_marker left us smack up257* against a marker. In that case we will end up treating the next data258* segment as empty, and we can avoid producing bogus output pixels by259* leaving the flag set.260*/261if (cinfo->unread_marker == 0)262entropy->pub.insufficient_data = FALSE;263264return TRUE;265}266267268/*269* Huffman MCU decoding.270* Each of these routines decodes and returns one MCU's worth of271* Huffman-compressed coefficients.272* The coefficients are reordered from zigzag order into natural array order,273* but are not dequantized.274*275* The i'th block of the MCU is stored into the block pointed to by276* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.277*278* We return FALSE if data source requested suspension. In that case no279* changes have been made to permanent state. (Exception: some output280* coefficients may already have been assigned. This is harmless for281* spectral selection, since we'll just re-assign them on the next call.282* Successive approximation AC refinement has to be more careful, however.)283*/284285/*286* MCU decoding for DC initial scan (either spectral selection,287* or first pass of successive approximation).288*/289290METHODDEF(boolean)291decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)292{293phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;294int Al = cinfo->Al;295register int s, r;296int blkn, ci;297JBLOCKROW block;298BITREAD_STATE_VARS;299savable_state state;300d_derived_tbl *tbl;301jpeg_component_info *compptr;302303/* Process restart marker if needed; may have to suspend */304if (cinfo->restart_interval) {305if (entropy->restarts_to_go == 0)306if (! process_restart(cinfo))307return FALSE;308}309310/* If we've run out of data, just leave the MCU set to zeroes.311* This way, we return uniform gray for the remainder of the segment.312*/313if (! entropy->pub.insufficient_data) {314315/* Load up working state */316BITREAD_LOAD_STATE(cinfo,entropy->bitstate);317ASSIGN_STATE(state, entropy->saved);318319/* Outer loop handles each block in the MCU */320321for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {322block = MCU_data[blkn];323ci = cinfo->MCU_membership[blkn];324compptr = cinfo->cur_comp_info[ci];325tbl = entropy->derived_tbls[compptr->dc_tbl_no];326327/* Decode a single block's worth of coefficients */328329/* Section F.2.2.1: decode the DC coefficient difference */330HUFF_DECODE(s, br_state, tbl, return FALSE, label1);331if (s) {332CHECK_BIT_BUFFER(br_state, s, return FALSE);333r = GET_BITS(s);334s = HUFF_EXTEND(r, s);335}336337/* Convert DC difference to actual value, update last_dc_val */338s += state.last_dc_val[ci];339state.last_dc_val[ci] = s;340/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */341(*block)[0] = (JCOEF) LEFT_SHIFT(s, Al);342}343344/* Completed MCU, so update state */345BITREAD_SAVE_STATE(cinfo,entropy->bitstate);346ASSIGN_STATE(entropy->saved, state);347}348349/* Account for restart interval (no-op if not using restarts) */350entropy->restarts_to_go--;351352return TRUE;353}354355356/*357* MCU decoding for AC initial scan (either spectral selection,358* or first pass of successive approximation).359*/360361METHODDEF(boolean)362decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)363{364phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;365int Se = cinfo->Se;366int Al = cinfo->Al;367register int s, k, r;368unsigned int EOBRUN;369JBLOCKROW block;370BITREAD_STATE_VARS;371d_derived_tbl *tbl;372373/* Process restart marker if needed; may have to suspend */374if (cinfo->restart_interval) {375if (entropy->restarts_to_go == 0)376if (! process_restart(cinfo))377return FALSE;378}379380/* If we've run out of data, just leave the MCU set to zeroes.381* This way, we return uniform gray for the remainder of the segment.382*/383if (! entropy->pub.insufficient_data) {384385/* Load up working state.386* We can avoid loading/saving bitread state if in an EOB run.387*/388EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */389390/* There is always only one block per MCU */391392if (EOBRUN > 0) /* if it's a band of zeroes... */393EOBRUN--; /* ...process it now (we do nothing) */394else {395BITREAD_LOAD_STATE(cinfo,entropy->bitstate);396block = MCU_data[0];397tbl = entropy->ac_derived_tbl;398399for (k = cinfo->Ss; k <= Se; k++) {400HUFF_DECODE(s, br_state, tbl, return FALSE, label2);401r = s >> 4;402s &= 15;403if (s) {404k += r;405CHECK_BIT_BUFFER(br_state, s, return FALSE);406r = GET_BITS(s);407s = HUFF_EXTEND(r, s);408/* Scale and output coefficient in natural (dezigzagged) order */409(*block)[jpeg_natural_order[k]] = (JCOEF) LEFT_SHIFT(s, Al);410} else {411if (r == 15) { /* ZRL */412k += 15; /* skip 15 zeroes in band */413} else { /* EOBr, run length is 2^r + appended bits */414EOBRUN = 1 << r;415if (r) { /* EOBr, r > 0 */416CHECK_BIT_BUFFER(br_state, r, return FALSE);417r = GET_BITS(r);418EOBRUN += r;419}420EOBRUN--; /* this band is processed at this moment */421break; /* force end-of-band */422}423}424}425426BITREAD_SAVE_STATE(cinfo,entropy->bitstate);427}428429/* Completed MCU, so update state */430entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */431}432433/* Account for restart interval (no-op if not using restarts) */434entropy->restarts_to_go--;435436return TRUE;437}438439440/*441* MCU decoding for DC successive approximation refinement scan.442* Note: we assume such scans can be multi-component, although the spec443* is not very clear on the point.444*/445446METHODDEF(boolean)447decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)448{449phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;450int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */451int blkn;452JBLOCKROW block;453BITREAD_STATE_VARS;454455/* Process restart marker if needed; may have to suspend */456if (cinfo->restart_interval) {457if (entropy->restarts_to_go == 0)458if (! process_restart(cinfo))459return FALSE;460}461462/* Not worth the cycles to check insufficient_data here,463* since we will not change the data anyway if we read zeroes.464*/465466/* Load up working state */467BITREAD_LOAD_STATE(cinfo,entropy->bitstate);468469/* Outer loop handles each block in the MCU */470471for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {472block = MCU_data[blkn];473474/* Encoded data is simply the next bit of the two's-complement DC value */475CHECK_BIT_BUFFER(br_state, 1, return FALSE);476if (GET_BITS(1))477(*block)[0] |= p1;478/* Note: since we use |=, repeating the assignment later is safe */479}480481/* Completed MCU, so update state */482BITREAD_SAVE_STATE(cinfo,entropy->bitstate);483484/* Account for restart interval (no-op if not using restarts) */485entropy->restarts_to_go--;486487return TRUE;488}489490491/*492* MCU decoding for AC successive approximation refinement scan.493*/494495METHODDEF(boolean)496decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)497{498phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;499int Se = cinfo->Se;500int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */501int m1 = (NEG_1) << cinfo->Al; /* -1 in the bit position being coded */502register int s, k, r;503unsigned int EOBRUN;504JBLOCKROW block;505JCOEFPTR thiscoef;506BITREAD_STATE_VARS;507d_derived_tbl *tbl;508int num_newnz;509int newnz_pos[DCTSIZE2];510511/* Process restart marker if needed; may have to suspend */512if (cinfo->restart_interval) {513if (entropy->restarts_to_go == 0)514if (! process_restart(cinfo))515return FALSE;516}517518/* If we've run out of data, don't modify the MCU.519*/520if (! entropy->pub.insufficient_data) {521522/* Load up working state */523BITREAD_LOAD_STATE(cinfo,entropy->bitstate);524EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */525526/* There is always only one block per MCU */527block = MCU_data[0];528tbl = entropy->ac_derived_tbl;529530/* If we are forced to suspend, we must undo the assignments to any newly531* nonzero coefficients in the block, because otherwise we'd get confused532* next time about which coefficients were already nonzero.533* But we need not undo addition of bits to already-nonzero coefficients;534* instead, we can test the current bit to see if we already did it.535*/536num_newnz = 0;537538/* initialize coefficient loop counter to start of band */539k = cinfo->Ss;540541if (EOBRUN == 0) {542for (; k <= Se; k++) {543HUFF_DECODE(s, br_state, tbl, goto undoit, label3);544r = s >> 4;545s &= 15;546if (s) {547if (s != 1) /* size of new coef should always be 1 */548WARNMS(cinfo, JWRN_HUFF_BAD_CODE);549CHECK_BIT_BUFFER(br_state, 1, goto undoit);550if (GET_BITS(1))551s = p1; /* newly nonzero coef is positive */552else553s = m1; /* newly nonzero coef is negative */554} else {555if (r != 15) {556EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */557if (r) {558CHECK_BIT_BUFFER(br_state, r, goto undoit);559r = GET_BITS(r);560EOBRUN += r;561}562break; /* rest of block is handled by EOB logic */563}564/* note s = 0 for processing ZRL */565}566/* Advance over already-nonzero coefs and r still-zero coefs,567* appending correction bits to the nonzeroes. A correction bit is 1568* if the absolute value of the coefficient must be increased.569*/570do {571thiscoef = *block + jpeg_natural_order[k];572if (*thiscoef != 0) {573CHECK_BIT_BUFFER(br_state, 1, goto undoit);574if (GET_BITS(1)) {575if ((*thiscoef & p1) == 0) { /* do nothing if already set it */576if (*thiscoef >= 0)577*thiscoef += p1;578else579*thiscoef += m1;580}581}582} else {583if (--r < 0)584break; /* reached target zero coefficient */585}586k++;587} while (k <= Se);588if (s) {589int pos = jpeg_natural_order[k];590/* Output newly nonzero coefficient */591(*block)[pos] = (JCOEF) s;592/* Remember its position in case we have to suspend */593newnz_pos[num_newnz++] = pos;594}595}596}597598if (EOBRUN > 0) {599/* Scan any remaining coefficient positions after the end-of-band600* (the last newly nonzero coefficient, if any). Append a correction601* bit to each already-nonzero coefficient. A correction bit is 1602* if the absolute value of the coefficient must be increased.603*/604for (; k <= Se; k++) {605thiscoef = *block + jpeg_natural_order[k];606if (*thiscoef != 0) {607CHECK_BIT_BUFFER(br_state, 1, goto undoit);608if (GET_BITS(1)) {609if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */610if (*thiscoef >= 0)611*thiscoef += p1;612else613*thiscoef += m1;614}615}616}617}618/* Count one block completed in EOB run */619EOBRUN--;620}621622/* Completed MCU, so update state */623BITREAD_SAVE_STATE(cinfo,entropy->bitstate);624entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */625}626627/* Account for restart interval (no-op if not using restarts) */628entropy->restarts_to_go--;629630return TRUE;631632undoit:633/* Re-zero any output coefficients that we made newly nonzero */634while (num_newnz > 0)635(*block)[newnz_pos[--num_newnz]] = 0;636637return FALSE;638}639640641/*642* Module initialization routine for progressive Huffman entropy decoding.643*/644645GLOBAL(void)646jinit_phuff_decoder (j_decompress_ptr cinfo)647{648phuff_entropy_ptr entropy;649int *coef_bit_ptr;650int ci, i;651652entropy = (phuff_entropy_ptr)653(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,654sizeof(phuff_entropy_decoder));655cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;656entropy->pub.start_pass = start_pass_phuff_decoder;657658/* Mark derived tables unallocated */659for (i = 0; i < NUM_HUFF_TBLS; i++) {660entropy->derived_tbls[i] = NULL;661}662663/* Create progression status table */664cinfo->coef_bits = (int (*)[DCTSIZE2])665(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,666cinfo->num_components*DCTSIZE2*sizeof(int));667coef_bit_ptr = & cinfo->coef_bits[0][0];668for (ci = 0; ci < cinfo->num_components; ci++)669for (i = 0; i < DCTSIZE2; i++)670*coef_bit_ptr++ = -1;671}672673#endif /* D_PROGRESSIVE_SUPPORTED */674675676