Changeset 283 for trunk/libjpeg/jdhuff.c


Ignore:
Timestamp:
Jan 4, 2010, 8:20:18 PM (12 years ago)
Author:
rbri
Message:

JPEG plugin: libjpeg updated to version 7

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/libjpeg/jdhuff.c

    r15 r283  
    33 *
    44 * Copyright (C) 1991-1997, Thomas G. Lane.
     5 * Modified 2006-2009 by Guido Vollbeding.
    56 * This file is part of the Independent JPEG Group's software.
    67 * For conditions of distribution and use, see the accompanying README file.
    78 *
    89 * This file contains Huffman entropy decoding routines.
     10 * Both sequential and progressive modes are supported in this single module.
    911 *
    1012 * Much of the complexity here has to do with supporting input suspension.
     
    1820#include "jinclude.h"
    1921#include "jpeglib.h"
    20 #include "jdhuff.h"             /* Declarations shared with jdphuff.c */
     22
     23
     24/* Derived data constructed for each Huffman table */
     25
     26#define HUFF_LOOKAHEAD  8       /* # of bits of lookahead */
     27
     28typedef struct {
     29  /* Basic tables: (element [0] of each array is unused) */
     30  INT32 maxcode[18];            /* largest code of length k (-1 if none) */
     31  /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
     32  INT32 valoffset[17];          /* huffval[] offset for codes of length k */
     33  /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
     34   * the smallest code of length k; so given a code of length k, the
     35   * corresponding symbol is huffval[code + valoffset[k]]
     36   */
     37
     38  /* Link to public Huffman table (needed only in jpeg_huff_decode) */
     39  JHUFF_TBL *pub;
     40
     41  /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
     42   * the input data stream.  If the next Huffman code is no more
     43   * than HUFF_LOOKAHEAD bits long, we can obtain its length and
     44   * the corresponding symbol directly from these tables.
     45   */
     46  int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
     47  UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
     48} d_derived_tbl;
     49
     50
     51/*
     52 * Fetching the next N bits from the input stream is a time-critical operation
     53 * for the Huffman decoders.  We implement it with a combination of inline
     54 * macros and out-of-line subroutines.  Note that N (the number of bits
     55 * demanded at one time) never exceeds 15 for JPEG use.
     56 *
     57 * We read source bytes into get_buffer and dole out bits as needed.
     58 * If get_buffer already contains enough bits, they are fetched in-line
     59 * by the macros CHECK_BIT_BUFFER and GET_BITS.  When there aren't enough
     60 * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
     61 * as full as possible (not just to the number of bits needed; this
     62 * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
     63 * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
     64 * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
     65 * at least the requested number of bits --- dummy zeroes are inserted if
     66 * necessary.
     67 */
     68
     69typedef INT32 bit_buf_type;     /* type of bit-extraction buffer */
     70#define BIT_BUF_SIZE  32        /* size of buffer in bits */
     71
     72/* If long is > 32 bits on your machine, and shifting/masking longs is
     73 * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
     74 * appropriately should be a win.  Unfortunately we can't define the size
     75 * with something like  #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
     76 * because not all machines measure sizeof in 8-bit bytes.
     77 */
     78
     79typedef struct {                /* Bitreading state saved across MCUs */
     80  bit_buf_type get_buffer;      /* current bit-extraction buffer */
     81  int bits_left;                /* # of unused bits in it */
     82} bitread_perm_state;
     83
     84typedef struct {                /* Bitreading working state within an MCU */
     85  /* Current data source location */
     86  /* We need a copy, rather than munging the original, in case of suspension */
     87  const JOCTET * next_input_byte; /* => next byte to read from source */
     88  size_t bytes_in_buffer;       /* # of bytes remaining in source buffer */
     89  /* Bit input buffer --- note these values are kept in register variables,
     90   * not in this struct, inside the inner loops.
     91   */
     92  bit_buf_type get_buffer;      /* current bit-extraction buffer */
     93  int bits_left;                /* # of unused bits in it */
     94  /* Pointer needed by jpeg_fill_bit_buffer. */
     95  j_decompress_ptr cinfo;       /* back link to decompress master record */
     96} bitread_working_state;
     97
     98/* Macros to declare and load/save bitread local variables. */
     99#define BITREAD_STATE_VARS  \
     100        register bit_buf_type get_buffer;  \
     101        register int bits_left;  \
     102        bitread_working_state br_state
     103
     104#define BITREAD_LOAD_STATE(cinfop,permstate)  \
     105        br_state.cinfo = cinfop; \
     106        br_state.next_input_byte = cinfop->src->next_input_byte; \
     107        br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
     108        get_buffer = permstate.get_buffer; \
     109        bits_left = permstate.bits_left;
     110
     111#define BITREAD_SAVE_STATE(cinfop,permstate)  \
     112        cinfop->src->next_input_byte = br_state.next_input_byte; \
     113        cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
     114        permstate.get_buffer = get_buffer; \
     115        permstate.bits_left = bits_left
     116
     117/*
     118 * These macros provide the in-line portion of bit fetching.
     119 * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
     120 * before using GET_BITS, PEEK_BITS, or DROP_BITS.
     121 * The variables get_buffer and bits_left are assumed to be locals,
     122 * but the state struct might not be (jpeg_huff_decode needs this).
     123 *      CHECK_BIT_BUFFER(state,n,action);
     124 *              Ensure there are N bits in get_buffer; if suspend, take action.
     125 *      val = GET_BITS(n);
     126 *              Fetch next N bits.
     127 *      val = PEEK_BITS(n);
     128 *              Fetch next N bits without removing them from the buffer.
     129 *      DROP_BITS(n);
     130 *              Discard next N bits.
     131 * The value N should be a simple variable, not an expression, because it
     132 * is evaluated multiple times.
     133 */
     134
     135#define CHECK_BIT_BUFFER(state,nbits,action) \
     136        { if (bits_left < (nbits)) {  \
     137            if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits))  \
     138              { action; }  \
     139            get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
     140
     141#define GET_BITS(nbits) \
     142        (((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits))
     143
     144#define PEEK_BITS(nbits) \
     145        (((int) (get_buffer >> (bits_left -  (nbits)))) & BIT_MASK(nbits))
     146
     147#define DROP_BITS(nbits) \
     148        (bits_left -= (nbits))
     149
     150
     151/*
     152 * Code for extracting next Huffman-coded symbol from input bit stream.
     153 * Again, this is time-critical and we make the main paths be macros.
     154 *
     155 * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
     156 * without looping.  Usually, more than 95% of the Huffman codes will be 8
     157 * or fewer bits long.  The few overlength codes are handled with a loop,
     158 * which need not be inline code.
     159 *
     160 * Notes about the HUFF_DECODE macro:
     161 * 1. Near the end of the data segment, we may fail to get enough bits
     162 *    for a lookahead.  In that case, we do it the hard way.
     163 * 2. If the lookahead table contains no entry, the next code must be
     164 *    more than HUFF_LOOKAHEAD bits long.
     165 * 3. jpeg_huff_decode returns -1 if forced to suspend.
     166 */
     167
     168#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
     169{ register int nb, look; \
     170  if (bits_left < HUFF_LOOKAHEAD) { \
     171    if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
     172    get_buffer = state.get_buffer; bits_left = state.bits_left; \
     173    if (bits_left < HUFF_LOOKAHEAD) { \
     174      nb = 1; goto slowlabel; \
     175    } \
     176  } \
     177  look = PEEK_BITS(HUFF_LOOKAHEAD); \
     178  if ((nb = htbl->look_nbits[look]) != 0) { \
     179    DROP_BITS(nb); \
     180    result = htbl->look_sym[look]; \
     181  } else { \
     182    nb = HUFF_LOOKAHEAD+1; \
     183slowlabel: \
     184    if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
     185        { failaction; } \
     186    get_buffer = state.get_buffer; bits_left = state.bits_left; \
     187  } \
     188}
    21189
    22190
     
    29197
    30198typedef struct {
    31   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
     199  unsigned int EOBRUN;                  /* remaining EOBs in EOBRUN */
     200  int last_dc_val[MAX_COMPS_IN_SCAN];   /* last DC coef for each component */
    32201} savable_state;
    33202
     
    42211#if MAX_COMPS_IN_SCAN == 4
    43212#define ASSIGN_STATE(dest,src)  \
    44         ((dest).last_dc_val[0] = (src).last_dc_val[0], \
     213        ((dest).EOBRUN = (src).EOBRUN, \
     214         (dest).last_dc_val[0] = (src).last_dc_val[0], \
    45215         (dest).last_dc_val[1] = (src).last_dc_val[1], \
    46216         (dest).last_dc_val[2] = (src).last_dc_val[2], \
     
    62232  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
    63233
     234  /* Following two fields used only in progressive mode */
     235
     236  /* Pointers to derived tables (these workspaces have image lifespan) */
     237  d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
     238
     239  d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
     240
     241  /* Following fields used only in sequential mode */
     242
    64243  /* Pointers to derived tables (these workspaces have image lifespan) */
    65244  d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
     
    72251  d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
    73252  /* Whether we care about the DC and AC coefficient values for each block */
    74   boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
    75   boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
     253  int coef_limit[D_MAX_BLOCKS_IN_MCU];
    76254} huff_entropy_decoder;
    77255
     
    79257
    80258
    81 /*
    82  * Initialize for a Huffman-compressed scan.
    83  */
    84 
    85 METHODDEF(void)
    86 start_pass_huff_decoder (j_decompress_ptr cinfo)
    87 {
    88   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
    89   int ci, blkn, dctbl, actbl;
    90   jpeg_component_info * compptr;
    91 
    92   /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
    93    * This ought to be an error condition, but we make it a warning because
    94    * there are some baseline files out there with all zeroes in these bytes.
    95    */
    96   if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
    97       cinfo->Ah != 0 || cinfo->Al != 0)
    98     WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
    99 
    100   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
    101     compptr = cinfo->cur_comp_info[ci];
    102     dctbl = compptr->dc_tbl_no;
    103     actbl = compptr->ac_tbl_no;
    104     /* Compute derived values for Huffman tables */
    105     /* We may do this more than once for a table, but it's not expensive */
    106     jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
    107                             & entropy->dc_derived_tbls[dctbl]);
    108     jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
    109                             & entropy->ac_derived_tbls[actbl]);
    110     /* Initialize DC predictions to 0 */
    111     entropy->saved.last_dc_val[ci] = 0;
    112   }
    113 
    114   /* Precalculate decoding info for each block in an MCU of this scan */
    115   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
    116     ci = cinfo->MCU_membership[blkn];
    117     compptr = cinfo->cur_comp_info[ci];
    118     /* Precalculate which table to use for each block */
    119     entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
    120     entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
    121     /* Decide whether we really care about the coefficient values */
    122     if (compptr->component_needed) {
    123       entropy->dc_needed[blkn] = TRUE;
    124       /* we don't need the ACs if producing a 1/8th-size image */
    125       entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
    126     } else {
    127       entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
    128     }
    129   }
    130 
    131   /* Initialize bitread state variables */
    132   entropy->bitstate.bits_left = 0;
    133   entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
    134   entropy->pub.insufficient_data = FALSE;
    135 
    136   /* Initialize restart counter */
    137   entropy->restarts_to_go = cinfo->restart_interval;
    138 }
     259static 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};
    139269
    140270
     
    142272 * Compute the derived values for a Huffman table.
    143273 * This routine also performs some validation checks on the table.
    144  *
    145  * Note this is also used by jdphuff.c.
    146  */
    147 
    148 GLOBAL(void)
     274 */
     275
     276LOCAL(void)
    149277jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
    150278                         d_derived_tbl ** pdtbl)
     
    268396
    269397/*
    270  * Out-of-line code for bit fetching (shared with jdphuff.c).
    271  * See jdhuff.h for info about usage.
     398 * Out-of-line code for bit fetching.
    272399 * Note: current values of get_buffer and bits_left are passed as parameters,
    273400 * but are returned in the corresponding fields of the state struct.
     
    289416
    290417
    291 GLOBAL(boolean)
     418LOCAL(boolean)
    292419jpeg_fill_bit_buffer (bitread_working_state * state,
    293420                      register bit_buf_type get_buffer, register int bits_left,
     
    391518
    392519/*
     520 * Figure F.12: extend sign bit.
     521 * On some machines, a shift and sub will be faster than a table lookup.
     522 */
     523
     524#ifdef AVOID_TABLES
     525
     526#define BIT_MASK(nbits)   ((1<<(nbits))-1)
     527#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
     528
     529#else
     530
     531#define BIT_MASK(nbits)   bmask[nbits]
     532#define HUFF_EXTEND(x,s)  ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
     533
     534static const int bmask[16] =    /* bmask[n] is mask for n rightmost bits */
     535  { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
     536    0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
     537
     538#endif /* AVOID_TABLES */
     539
     540
     541/*
    393542 * Out-of-line code for Huffman code decoding.
    394  * See jdhuff.h for info about usage.
    395  */
    396 
    397 GLOBAL(int)
     543 */
     544
     545LOCAL(int)
    398546jpeg_huff_decode (bitread_working_state * state,
    399547                  register bit_buf_type get_buffer, register int bits_left,
     
    435583
    436584/*
    437  * Figure F.12: extend sign bit.
    438  * On some machines, a shift and add will be faster than a table lookup.
    439  */
    440 
    441 #ifdef AVOID_TABLES
    442 
    443 #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
    444 
    445 #else
    446 
    447 #define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
    448 
    449 static const int extend_test[16] =   /* entry n is 2**(n-1) */
    450   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
    451     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
    452 
    453 static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
    454   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
    455     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
    456     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
    457     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
    458 
    459 #endif /* AVOID_TABLES */
    460 
    461 
    462 /*
    463585 * Check for a restart marker & resynchronize decoder.
    464586 * Returns FALSE if must suspend.
     
    483605  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
    484606    entropy->saved.last_dc_val[ci] = 0;
     607  /* Re-init EOB run count, too */
     608  entropy->saved.EOBRUN = 0;
    485609
    486610  /* Reset restart counter */
     
    500624
    501625/*
    502  * Decode and return one MCU's worth of Huffman-compressed coefficients.
     626 * Huffman MCU decoding.
     627 * Each of these routines decodes and returns one MCU's worth of
     628 * Huffman-compressed coefficients.
    503629 * The coefficients are reordered from zigzag order into natural array order,
    504630 * but are not dequantized.
    505631 *
    506632 * The i'th block of the MCU is stored into the block pointed to by
    507  * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
     633 * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
    508634 * (Wholesale zeroing is usually a little faster than retail...)
    509635 *
    510  * Returns FALSE if data source requested suspension.  In that case no
     636 * We return FALSE if data source requested suspension.  In that case no
    511637 * changes have been made to permanent state.  (Exception: some output
    512638 * coefficients may already have been assigned.  This is harmless for
    513  * this module, since we'll just re-assign them on the next call.)
     639 * spectral selection, since we'll just re-assign them on the next call.
     640 * Successive approximation AC refinement has to be more careful, however.)
     641 */
     642
     643/*
     644 * MCU decoding for DC initial scan (either spectral selection,
     645 * or first pass of successive approximation).
     646 */
     647
     648METHODDEF(boolean)
     649decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
     650{   
     651  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
     652  int Al = cinfo->Al;
     653  register int s, r;
     654  int blkn, ci;
     655  JBLOCKROW block;
     656  BITREAD_STATE_VARS;
     657  savable_state state;
     658  d_derived_tbl * tbl;
     659  jpeg_component_info * compptr;
     660
     661  /* Process restart marker if needed; may have to suspend */
     662  if (cinfo->restart_interval) {
     663    if (entropy->restarts_to_go == 0)
     664      if (! process_restart(cinfo))
     665        return FALSE;
     666  }
     667
     668  /* If we've run out of data, just leave the MCU set to zeroes.
     669   * This way, we return uniform gray for the remainder of the segment.
     670   */
     671  if (! entropy->pub.insufficient_data) {
     672
     673    /* Load up working state */
     674    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
     675    ASSIGN_STATE(state, entropy->saved);
     676
     677    /* Outer loop handles each block in the MCU */
     678
     679    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
     680      block = MCU_data[blkn];
     681      ci = cinfo->MCU_membership[blkn];
     682      compptr = cinfo->cur_comp_info[ci];
     683      tbl = entropy->derived_tbls[compptr->dc_tbl_no];
     684
     685      /* Decode a single block's worth of coefficients */
     686
     687      /* Section F.2.2.1: decode the DC coefficient difference */
     688      HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
     689      if (s) {
     690        CHECK_BIT_BUFFER(br_state, s, return FALSE);
     691        r = GET_BITS(s);
     692        s = HUFF_EXTEND(r, s);
     693      }
     694
     695      /* Convert DC difference to actual value, update last_dc_val */
     696      s += state.last_dc_val[ci];
     697      state.last_dc_val[ci] = s;
     698      /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
     699      (*block)[0] = (JCOEF) (s << Al);
     700    }
     701
     702    /* Completed MCU, so update state */
     703    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
     704    ASSIGN_STATE(entropy->saved, state);
     705  }
     706
     707  /* Account for restart interval (no-op if not using restarts) */
     708  entropy->restarts_to_go--;
     709
     710  return TRUE;
     711}
     712
     713
     714/*
     715 * MCU decoding for AC initial scan (either spectral selection,
     716 * or first pass of successive approximation).
     717 */
     718
     719METHODDEF(boolean)
     720decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
     721{   
     722  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
     723  int Se = cinfo->Se;
     724  int Al = cinfo->Al;
     725  register int s, k, r;
     726  unsigned int EOBRUN;
     727  JBLOCKROW block;
     728  BITREAD_STATE_VARS;
     729  d_derived_tbl * tbl;
     730
     731  /* Process restart marker if needed; may have to suspend */
     732  if (cinfo->restart_interval) {
     733    if (entropy->restarts_to_go == 0)
     734      if (! process_restart(cinfo))
     735        return FALSE;
     736  }
     737
     738  /* If we've run out of data, just leave the MCU set to zeroes.
     739   * This way, we return uniform gray for the remainder of the segment.
     740   */
     741  if (! entropy->pub.insufficient_data) {
     742
     743    /* Load up working state.
     744     * We can avoid loading/saving bitread state if in an EOB run.
     745     */
     746    EOBRUN = entropy->saved.EOBRUN;     /* only part of saved state we need */
     747
     748    /* There is always only one block per MCU */
     749
     750    if (EOBRUN > 0)             /* if it's a band of zeroes... */
     751      EOBRUN--;                 /* ...process it now (we do nothing) */
     752    else {
     753      BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
     754      block = MCU_data[0];
     755      tbl = entropy->ac_derived_tbl;
     756
     757      for (k = cinfo->Ss; k <= Se; k++) {
     758        HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
     759        r = s >> 4;
     760        s &= 15;
     761        if (s) {
     762          k += r;
     763          CHECK_BIT_BUFFER(br_state, s, return FALSE);
     764          r = GET_BITS(s);
     765          s = HUFF_EXTEND(r, s);
     766          /* Scale and output coefficient in natural (dezigzagged) order */
     767          (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
     768        } else {
     769          if (r == 15) {        /* ZRL */
     770            k += 15;            /* skip 15 zeroes in band */
     771          } else {              /* EOBr, run length is 2^r + appended bits */
     772            EOBRUN = 1 << r;
     773            if (r) {            /* EOBr, r > 0 */
     774              CHECK_BIT_BUFFER(br_state, r, return FALSE);
     775              r = GET_BITS(r);
     776              EOBRUN += r;
     777            }
     778            EOBRUN--;           /* this band is processed at this moment */
     779            break;              /* force end-of-band */
     780          }
     781        }
     782      }
     783
     784      BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
     785    }
     786
     787    /* Completed MCU, so update state */
     788    entropy->saved.EOBRUN = EOBRUN;     /* only part of saved state we need */
     789  }
     790
     791  /* Account for restart interval (no-op if not using restarts) */
     792  entropy->restarts_to_go--;
     793
     794  return TRUE;
     795}
     796
     797
     798/*
     799 * MCU decoding for DC successive approximation refinement scan.
     800 * Note: we assume such scans can be multi-component, although the spec
     801 * is not very clear on the point.
     802 */
     803
     804METHODDEF(boolean)
     805decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
     806{   
     807  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
     808  int p1 = 1 << cinfo->Al;      /* 1 in the bit position being coded */
     809  int blkn;
     810  JBLOCKROW block;
     811  BITREAD_STATE_VARS;
     812
     813  /* Process restart marker if needed; may have to suspend */
     814  if (cinfo->restart_interval) {
     815    if (entropy->restarts_to_go == 0)
     816      if (! process_restart(cinfo))
     817        return FALSE;
     818  }
     819
     820  /* Not worth the cycles to check insufficient_data here,
     821   * since we will not change the data anyway if we read zeroes.
     822   */
     823
     824  /* Load up working state */
     825  BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
     826
     827  /* Outer loop handles each block in the MCU */
     828
     829  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
     830    block = MCU_data[blkn];
     831
     832    /* Encoded data is simply the next bit of the two's-complement DC value */
     833    CHECK_BIT_BUFFER(br_state, 1, return FALSE);
     834    if (GET_BITS(1))
     835      (*block)[0] |= p1;
     836    /* Note: since we use |=, repeating the assignment later is safe */
     837  }
     838
     839  /* Completed MCU, so update state */
     840  BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
     841
     842  /* Account for restart interval (no-op if not using restarts) */
     843  entropy->restarts_to_go--;
     844
     845  return TRUE;
     846}
     847
     848
     849/*
     850 * MCU decoding for AC successive approximation refinement scan.
     851 */
     852
     853METHODDEF(boolean)
     854decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
     855{   
     856  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
     857  int Se = cinfo->Se;
     858  int p1 = 1 << cinfo->Al;      /* 1 in the bit position being coded */
     859  int m1 = (-1) << cinfo->Al;   /* -1 in the bit position being coded */
     860  register int s, k, r;
     861  unsigned int EOBRUN;
     862  JBLOCKROW block;
     863  JCOEFPTR thiscoef;
     864  BITREAD_STATE_VARS;
     865  d_derived_tbl * tbl;
     866  int num_newnz;
     867  int newnz_pos[DCTSIZE2];
     868
     869  /* Process restart marker if needed; may have to suspend */
     870  if (cinfo->restart_interval) {
     871    if (entropy->restarts_to_go == 0)
     872      if (! process_restart(cinfo))
     873        return FALSE;
     874  }
     875
     876  /* If we've run out of data, don't modify the MCU.
     877   */
     878  if (! entropy->pub.insufficient_data) {
     879
     880    /* Load up working state */
     881    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
     882    EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
     883
     884    /* There is always only one block per MCU */
     885    block = MCU_data[0];
     886    tbl = entropy->ac_derived_tbl;
     887
     888    /* If we are forced to suspend, we must undo the assignments to any newly
     889     * nonzero coefficients in the block, because otherwise we'd get confused
     890     * next time about which coefficients were already nonzero.
     891     * But we need not undo addition of bits to already-nonzero coefficients;
     892     * instead, we can test the current bit to see if we already did it.
     893     */
     894    num_newnz = 0;
     895
     896    /* initialize coefficient loop counter to start of band */
     897    k = cinfo->Ss;
     898
     899    if (EOBRUN == 0) {
     900      for (; k <= Se; k++) {
     901        HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
     902        r = s >> 4;
     903        s &= 15;
     904        if (s) {
     905          if (s != 1)           /* size of new coef should always be 1 */
     906            WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
     907          CHECK_BIT_BUFFER(br_state, 1, goto undoit);
     908          if (GET_BITS(1))
     909            s = p1;             /* newly nonzero coef is positive */
     910          else
     911            s = m1;             /* newly nonzero coef is negative */
     912        } else {
     913          if (r != 15) {
     914            EOBRUN = 1 << r;    /* EOBr, run length is 2^r + appended bits */
     915            if (r) {
     916              CHECK_BIT_BUFFER(br_state, r, goto undoit);
     917              r = GET_BITS(r);
     918              EOBRUN += r;
     919            }
     920            break;              /* rest of block is handled by EOB logic */
     921          }
     922          /* note s = 0 for processing ZRL */
     923        }
     924        /* Advance over already-nonzero coefs and r still-zero coefs,
     925         * appending correction bits to the nonzeroes.  A correction bit is 1
     926         * if the absolute value of the coefficient must be increased.
     927         */
     928        do {
     929          thiscoef = *block + jpeg_natural_order[k];
     930          if (*thiscoef != 0) {
     931            CHECK_BIT_BUFFER(br_state, 1, goto undoit);
     932            if (GET_BITS(1)) {
     933              if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
     934                if (*thiscoef >= 0)
     935                  *thiscoef += p1;
     936                else
     937                  *thiscoef += m1;
     938              }
     939            }
     940          } else {
     941            if (--r < 0)
     942              break;            /* reached target zero coefficient */
     943          }
     944          k++;
     945        } while (k <= Se);
     946        if (s) {
     947          int pos = jpeg_natural_order[k];
     948          /* Output newly nonzero coefficient */
     949          (*block)[pos] = (JCOEF) s;
     950          /* Remember its position in case we have to suspend */
     951          newnz_pos[num_newnz++] = pos;
     952        }
     953      }
     954    }
     955
     956    if (EOBRUN > 0) {
     957      /* Scan any remaining coefficient positions after the end-of-band
     958       * (the last newly nonzero coefficient, if any).  Append a correction
     959       * bit to each already-nonzero coefficient.  A correction bit is 1
     960       * if the absolute value of the coefficient must be increased.
     961       */
     962      for (; k <= Se; k++) {
     963        thiscoef = *block + jpeg_natural_order[k];
     964        if (*thiscoef != 0) {
     965          CHECK_BIT_BUFFER(br_state, 1, goto undoit);
     966          if (GET_BITS(1)) {
     967            if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
     968              if (*thiscoef >= 0)
     969                *thiscoef += p1;
     970              else
     971                *thiscoef += m1;
     972            }
     973          }
     974        }
     975      }
     976      /* Count one block completed in EOB run */
     977      EOBRUN--;
     978    }
     979
     980    /* Completed MCU, so update state */
     981    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
     982    entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
     983  }
     984
     985  /* Account for restart interval (no-op if not using restarts) */
     986  entropy->restarts_to_go--;
     987
     988  return TRUE;
     989
     990undoit:
     991  /* Re-zero any output coefficients that we made newly nonzero */
     992  while (num_newnz > 0)
     993    (*block)[newnz_pos[--num_newnz]] = 0;
     994
     995  return FALSE;
     996}
     997
     998
     999/*
     1000 * Decode one MCU's worth of Huffman-compressed coefficients.
    5141001 */
    5151002
     
    5421029    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
    5431030      JBLOCKROW block = MCU_data[blkn];
    544       d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
    545       d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
     1031      d_derived_tbl * htbl;
    5461032      register int s, k, r;
     1033      int coef_limit, ci;
    5471034
    5481035      /* Decode a single block's worth of coefficients */
    5491036
    5501037      /* Section F.2.2.1: decode the DC coefficient difference */
    551       HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
    552       if (s) {
    553         CHECK_BIT_BUFFER(br_state, s, return FALSE);
    554         r = GET_BITS(s);
    555         s = HUFF_EXTEND(r, s);
    556       }
    557 
    558       if (entropy->dc_needed[blkn]) {
     1038      htbl = entropy->dc_cur_tbls[blkn];
     1039      HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
     1040
     1041      htbl = entropy->ac_cur_tbls[blkn];
     1042      k = 1;
     1043      coef_limit = entropy->coef_limit[blkn];
     1044      if (coef_limit) {
    5591045        /* Convert DC difference to actual value, update last_dc_val */
    560         int ci = cinfo->MCU_membership[blkn];
     1046        if (s) {
     1047          CHECK_BIT_BUFFER(br_state, s, return FALSE);
     1048          r = GET_BITS(s);
     1049          s = HUFF_EXTEND(r, s);
     1050        }
     1051        ci = cinfo->MCU_membership[blkn];
    5611052        s += state.last_dc_val[ci];
    5621053        state.last_dc_val[ci] = s;
    563         /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
     1054        /* Output the DC coefficient */
    5641055        (*block)[0] = (JCOEF) s;
    565       }
    566 
    567       if (entropy->ac_needed[blkn]) {
    5681056
    5691057        /* Section F.2.2.2: decode the AC coefficients */
    5701058        /* Since zeroes are skipped, output area must be cleared beforehand */
    571         for (k = 1; k < DCTSIZE2; k++) {
    572           HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
    573      
     1059        for (; k < coef_limit; k++) {
     1060          HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
     1061
    5741062          r = s >> 4;
    5751063          s &= 15;
    576      
     1064
    5771065          if (s) {
    5781066            k += r;
     
    5871075          } else {
    5881076            if (r != 15)
    589               break;
     1077              goto EndOfBlock;
    5901078            k += 15;
    5911079          }
    5921080        }
    593 
    5941081      } else {
    595 
    596         /* Section F.2.2.2: decode the AC coefficients */
    597         /* In this path we just discard the values */
    598         for (k = 1; k < DCTSIZE2; k++) {
    599           HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
    600      
    601           r = s >> 4;
    602           s &= 15;
    603      
    604           if (s) {
    605             k += r;
    606             CHECK_BIT_BUFFER(br_state, s, return FALSE);
    607             DROP_BITS(s);
    608           } else {
    609             if (r != 15)
    610               break;
    611             k += 15;
    612           }
     1082        if (s) {
     1083          CHECK_BIT_BUFFER(br_state, s, return FALSE);
     1084          DROP_BITS(s);
    6131085        }
    614 
    6151086      }
     1087
     1088      /* Section F.2.2.2: decode the AC coefficients */
     1089      /* In this path we just discard the values */
     1090      for (; k < DCTSIZE2; k++) {
     1091        HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
     1092
     1093        r = s >> 4;
     1094        s &= 15;
     1095
     1096        if (s) {
     1097          k += r;
     1098          CHECK_BIT_BUFFER(br_state, s, return FALSE);
     1099          DROP_BITS(s);
     1100        } else {
     1101          if (r != 15)
     1102            break;
     1103          k += 15;
     1104        }
     1105      }
     1106
     1107      EndOfBlock: ;
    6161108    }
    6171109
     
    6251117
    6261118  return TRUE;
     1119}
     1120
     1121
     1122/*
     1123 * Initialize for a Huffman-compressed scan.
     1124 */
     1125
     1126METHODDEF(void)
     1127start_pass_huff_decoder (j_decompress_ptr cinfo)
     1128{
     1129  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
     1130  int ci, blkn, dctbl, actbl, i;
     1131  jpeg_component_info * compptr;
     1132
     1133  if (cinfo->progressive_mode) {
     1134    /* Validate progressive scan parameters */
     1135    if (cinfo->Ss == 0) {
     1136      if (cinfo->Se != 0)
     1137        goto bad;
     1138    } else {
     1139      /* need not check Ss/Se < 0 since they came from unsigned bytes */
     1140      if (cinfo->Se < cinfo->Ss || cinfo->Se >= DCTSIZE2)
     1141        goto bad;
     1142      /* AC scans may have only one component */
     1143      if (cinfo->comps_in_scan != 1)
     1144        goto bad;
     1145    }
     1146    if (cinfo->Ah != 0) {
     1147      /* Successive approximation refinement scan: must have Al = Ah-1. */
     1148      if (cinfo->Ah-1 != cinfo->Al)
     1149        goto bad;
     1150    }
     1151    if (cinfo->Al > 13) {       /* need not check for < 0 */
     1152      /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
     1153       * but the spec doesn't say so, and we try to be liberal about what we
     1154       * accept.  Note: large Al values could result in out-of-range DC
     1155       * coefficients during early scans, leading to bizarre displays due to
     1156       * overflows in the IDCT math.  But we won't crash.
     1157       */
     1158      bad:
     1159      ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
     1160               cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
     1161    }
     1162    /* Update progression status, and verify that scan order is legal.
     1163     * Note that inter-scan inconsistencies are treated as warnings
     1164     * not fatal errors ... not clear if this is right way to behave.
     1165     */
     1166    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
     1167      int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
     1168      int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
     1169      if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
     1170        WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
     1171      for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
     1172        int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
     1173        if (cinfo->Ah != expected)
     1174          WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
     1175        coef_bit_ptr[coefi] = cinfo->Al;
     1176      }
     1177    }
     1178
     1179    /* Select MCU decoding routine */
     1180    if (cinfo->Ah == 0) {
     1181      if (cinfo->Ss == 0)
     1182        entropy->pub.decode_mcu = decode_mcu_DC_first;
     1183      else
     1184        entropy->pub.decode_mcu = decode_mcu_AC_first;
     1185    } else {
     1186      if (cinfo->Ss == 0)
     1187        entropy->pub.decode_mcu = decode_mcu_DC_refine;
     1188      else
     1189        entropy->pub.decode_mcu = decode_mcu_AC_refine;
     1190    }
     1191
     1192    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
     1193      compptr = cinfo->cur_comp_info[ci];
     1194      /* Make sure requested tables are present, and compute derived tables.
     1195       * We may build same derived table more than once, but it's not expensive.
     1196       */
     1197      if (cinfo->Ss == 0) {
     1198        if (cinfo->Ah == 0) {   /* DC refinement needs no table */
     1199          i = compptr->dc_tbl_no;
     1200          jpeg_make_d_derived_tbl(cinfo, TRUE, i,
     1201                                  & entropy->derived_tbls[i]);
     1202        }
     1203      } else {
     1204        i = compptr->ac_tbl_no;
     1205        jpeg_make_d_derived_tbl(cinfo, FALSE, i,
     1206                                & entropy->derived_tbls[i]);
     1207        /* remember the single active table */
     1208        entropy->ac_derived_tbl = entropy->derived_tbls[i];
     1209      }
     1210      /* Initialize DC predictions to 0 */
     1211      entropy->saved.last_dc_val[ci] = 0;
     1212    }
     1213
     1214    /* Initialize private state variables */
     1215    entropy->saved.EOBRUN = 0;
     1216  } else {
     1217    /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
     1218     * This ought to be an error condition, but we make it a warning because
     1219     * there are some baseline files out there with all zeroes in these bytes.
     1220     */
     1221    if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
     1222        cinfo->Ah != 0 || cinfo->Al != 0)
     1223      WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
     1224
     1225    /* Select MCU decoding routine */
     1226    entropy->pub.decode_mcu = decode_mcu;
     1227
     1228    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
     1229      compptr = cinfo->cur_comp_info[ci];
     1230      dctbl = compptr->dc_tbl_no;
     1231      actbl = compptr->ac_tbl_no;
     1232      /* Compute derived values for Huffman tables */
     1233      /* We may do this more than once for a table, but it's not expensive */
     1234      jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
     1235                              & entropy->dc_derived_tbls[dctbl]);
     1236      jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
     1237                              & entropy->ac_derived_tbls[actbl]);
     1238      /* Initialize DC predictions to 0 */
     1239      entropy->saved.last_dc_val[ci] = 0;
     1240    }
     1241
     1242    /* Precalculate decoding info for each block in an MCU of this scan */
     1243    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
     1244      ci = cinfo->MCU_membership[blkn];
     1245      compptr = cinfo->cur_comp_info[ci];
     1246      /* Precalculate which table to use for each block */
     1247      entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
     1248      entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
     1249      /* Decide whether we really care about the coefficient values */
     1250      if (compptr->component_needed) {
     1251        ci = compptr->DCT_v_scaled_size;
     1252        if (ci <= 0 || ci > 8) ci = 8;
     1253        i = compptr->DCT_h_scaled_size;
     1254        if (i <= 0 || i > 8) i = 8;
     1255        entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
     1256      } else {
     1257        entropy->coef_limit[blkn] = 0;
     1258      }
     1259    }
     1260  }
     1261
     1262  /* Initialize bitread state variables */
     1263  entropy->bitstate.bits_left = 0;
     1264  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
     1265  entropy->pub.insufficient_data = FALSE;
     1266
     1267  /* Initialize restart counter */
     1268  entropy->restarts_to_go = cinfo->restart_interval;
    6271269}
    6281270
     
    6431285  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
    6441286  entropy->pub.start_pass = start_pass_huff_decoder;
    645   entropy->pub.decode_mcu = decode_mcu;
    646 
    647   /* Mark tables unallocated */
    648   for (i = 0; i < NUM_HUFF_TBLS; i++) {
    649     entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
     1287
     1288  if (cinfo->progressive_mode) {
     1289    /* Create progression status table */
     1290    int *coef_bit_ptr, ci;
     1291    cinfo->coef_bits = (int (*)[DCTSIZE2])
     1292      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
     1293                                  cinfo->num_components*DCTSIZE2*SIZEOF(int));
     1294    coef_bit_ptr = & cinfo->coef_bits[0][0];
     1295    for (ci = 0; ci < cinfo->num_components; ci++)
     1296      for (i = 0; i < DCTSIZE2; i++)
     1297        *coef_bit_ptr++ = -1;
     1298
     1299    /* Mark derived tables unallocated */
     1300    for (i = 0; i < NUM_HUFF_TBLS; i++) {
     1301      entropy->derived_tbls[i] = NULL;
     1302    }
     1303  } else {
     1304    /* Mark tables unallocated */
     1305    for (i = 0; i < NUM_HUFF_TBLS; i++) {
     1306      entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
     1307    }
    6501308  }
    6511309}
Note: See TracChangeset for help on using the changeset viewer.