home *** CD-ROM | disk | FTP | other *** search
/ Windows Graphics Programming / Feng_Yuan_Win32_GDI_DirectX.iso / Samples / include / jlib / jdhuff.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-16  |  22.1 KB  |  712 lines

  1. //-------------------------------------------------------------------------//
  2. //          Windows Graphics Programming: Win32 GDI and DirectDraw         //
  3. //                        ISBN  0-13-086985-6                              //
  4. //                                                                         //
  5. //  Modified by: Yuan, Feng                             www.fengyuan.com   //
  6. //  Changes    : C++, exception, in-memory source, BGR byte order          //
  7. //  Version    : 1.00.000, May 31, 2000                                    //
  8. //-------------------------------------------------------------------------//
  9.  
  10. /*
  11.  * jdhuff.c
  12.  *
  13.  * Copyright (C) 1991-1997, Thomas G. Lane.
  14.  * This file is part of the Independent JPEG Group's software.
  15.  * For conditions of distribution and use, see the accompanying README file.
  16.  *
  17.  * This file contains Huffman entropy decoding routines.
  18.  *
  19.  * Much of the complexity here has to do with supporting input suspension.
  20.  * If the data source module demands suspension, we want to be able to back
  21.  * up to the start of the current MCU.  To do this, we copy state variables
  22.  * into local working storage, and update them back to the permanent
  23.  * storage only upon successful completion of an MCU.
  24.  */
  25.  
  26. #define JPEG_INTERNALS
  27. #include "jinclude.h"
  28. #include "jpeglib.h"
  29. #include "jdhuff.h"        /* Declarations shared with jdphuff.c */
  30.  
  31.  
  32. /*
  33.  * Expanded entropy decoder object for Huffman decoding.
  34.  *
  35.  * The savable_state subrecord contains fields that change within an MCU,
  36.  * but must not be updated permanently until we complete the MCU.
  37.  */
  38.  
  39. typedef struct {
  40.   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  41. } savable_state;
  42.  
  43. /* This macro is to work around compilers with missing or broken
  44.  * structure assignment.  You'll need to fix this code if you have
  45.  * such a compiler and you change MAX_COMPS_IN_SCAN.
  46.  */
  47.  
  48. #ifndef NO_STRUCT_ASSIGN
  49. #define ASSIGN_STATE(dest,src)  ((dest) = (src))
  50. #else
  51. #if MAX_COMPS_IN_SCAN == 4
  52. #define ASSIGN_STATE(dest,src)  \
  53.     ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  54.      (dest).last_dc_val[1] = (src).last_dc_val[1], \
  55.      (dest).last_dc_val[2] = (src).last_dc_val[2], \
  56.      (dest).last_dc_val[3] = (src).last_dc_val[3])
  57. #endif
  58. #endif
  59.  
  60.  
  61. typedef struct {
  62.   struct jpeg_entropy_decoder pub; /* public fields */
  63.  
  64.   /* These fields are loaded into local variables at start of each MCU.
  65.    * In case of suspension, we exit WITHOUT updating them.
  66.    */
  67.   bitread_perm_state bitstate;    /* Bit buffer at start of MCU */
  68.   savable_state saved;        /* Other state at start of MCU */
  69.  
  70.   /* These fields are NOT loaded into local working state. */
  71.   unsigned int restarts_to_go;    /* MCUs left in this restart interval */
  72.  
  73.   /* Pointers to derived tables (these workspaces have image lifespan) */
  74.   d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  75.   d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  76.  
  77.   /* Precalculated info set up by start_pass for use in decode_mcu: */
  78.  
  79.   /* Pointers to derived tables to be used for each block within an MCU */
  80.   d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  81.   d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  82.   /* Whether we care about the DC and AC coefficient values for each block */
  83.   boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  84.   boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  85. } huff_entropy_decoder;
  86.  
  87. typedef huff_entropy_decoder * huff_entropy_ptr;
  88.  
  89.  
  90. /*
  91.  * Initialize for a Huffman-compressed scan.
  92.  */
  93.  
  94. void start_pass_huff_decoder (j_decompress_ptr cinfo)
  95. {
  96.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  97.   int ci, blkn, dctbl, actbl;
  98.   jpeg_component_info * compptr;
  99.  
  100.   /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  101.    * This ought to be an error condition, but we make it a warning because
  102.    * there are some baseline files out there with all zeroes in these bytes.
  103.    */
  104.   if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  105.       cinfo->Ah != 0 || cinfo->Al != 0)
  106.     cinfo->WARNMS(JWRN_NOT_SEQUENTIAL);
  107.  
  108.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  109.     compptr = cinfo->cur_comp_info[ci];
  110.     dctbl = compptr->dc_tbl_no;
  111.     actbl = compptr->ac_tbl_no;
  112.     /* Compute derived values for Huffman tables */
  113.     /* We may do this more than once for a table, but it's not expensive */
  114.     jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  115.                 & entropy->dc_derived_tbls[dctbl]);
  116.     jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  117.                 & entropy->ac_derived_tbls[actbl]);
  118.     /* Initialize DC predictions to 0 */
  119.     entropy->saved.last_dc_val[ci] = 0;
  120.   }
  121.  
  122.   /* Precalculate decoding info for each block in an MCU of this scan */
  123.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  124.     ci = cinfo->MCU_membership[blkn];
  125.     compptr = cinfo->cur_comp_info[ci];
  126.     /* Precalculate which table to use for each block */
  127.     entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  128.     entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  129.     /* Decide whether we really care about the coefficient values */
  130.     if (compptr->component_needed) {
  131.       entropy->dc_needed[blkn] = TRUE;
  132.       /* we don't need the ACs if producing a 1/8th-size image */
  133.       entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  134.     } else {
  135.       entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  136.     }
  137.   }
  138.  
  139.   /* Initialize bitread state variables */
  140.   entropy->bitstate.bits_left = 0;
  141.   entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  142.   entropy->pub.insufficient_data = FALSE;
  143.  
  144.   /* Initialize restart counter */
  145.   entropy->restarts_to_go = cinfo->restart_interval;
  146. }
  147.  
  148.  
  149. /*
  150.  * Compute the derived values for a Huffman table.
  151.  * This routine also performs some validation checks on the table.
  152.  *
  153.  * Note this is also used by jdphuff.c.
  154.  */
  155.  
  156. GLOBAL(void)
  157. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  158.              d_derived_tbl ** pdtbl)
  159. {
  160.   JHUFF_TBL *htbl;
  161.   d_derived_tbl *dtbl;
  162.   int p, i, l, si, numsymbols;
  163.   int lookbits, ctr;
  164.   char huffsize[257];
  165.   unsigned int huffcode[257];
  166.   unsigned int code;
  167.  
  168.   /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169.    * paralleling the order of the symbols themselves in htbl->huffval[].
  170.    */
  171.  
  172.   /* Find the input Huffman table */
  173.   if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  174.     cinfo->ERREXIT1(JERR_NO_HUFF_TABLE, tblno);
  175.   htbl =
  176.     isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  177.   if (htbl == NULL)
  178.     cinfo->ERREXIT1(JERR_NO_HUFF_TABLE, tblno);
  179.  
  180.   /* Allocate a workspace if we haven't already done so. */
  181.   if (*pdtbl == NULL)
  182.     *pdtbl = (d_derived_tbl *)
  183.       cinfo->mem->alloc_small(JPOOL_IMAGE, sizeof(d_derived_tbl));
  184.   dtbl = *pdtbl;
  185.   dtbl->pub = htbl;        /* fill in back link */
  186.   
  187.   /* Figure C.1: make table of Huffman code length for each symbol */
  188.  
  189.   p = 0;
  190.   for (l = 1; l <= 16; l++) {
  191.     i = (int) htbl->bits[l];
  192.     if (i < 0 || p + i > 256)    /* protect against table overrun */
  193.       cinfo->ERREXIT(JERR_BAD_HUFF_TABLE);
  194.     while (i--)
  195.       huffsize[p++] = (char) l;
  196.   }
  197.   huffsize[p] = 0;
  198.   numsymbols = p;
  199.   
  200.   /* Figure C.2: generate the codes themselves */
  201.   /* We also validate that the counts represent a legal Huffman code tree. */
  202.   
  203.   code = 0;
  204.   si = huffsize[0];
  205.   p = 0;
  206.   while (huffsize[p]) {
  207.     while (((int) huffsize[p]) == si) {
  208.       huffcode[p++] = code;
  209.       code++;
  210.     }
  211.     /* code is now 1 more than the last code used for codelength si; but
  212.      * it must still fit in si bits, since no code is allowed to be all ones.
  213.      */
  214.     if (((long) code) >= (((long) 1) << si))
  215.       cinfo->ERREXIT(JERR_BAD_HUFF_TABLE);
  216.     code <<= 1;
  217.     si++;
  218.   }
  219.  
  220.   /* Figure F.15: generate decoding tables for bit-sequential decoding */
  221.  
  222.   p = 0;
  223.   for (l = 1; l <= 16; l++) {
  224.     if (htbl->bits[l]) {
  225.       /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  226.        * minus the minimum code of length l
  227.        */
  228.       dtbl->valoffset[l] = (long) p - (long) huffcode[p];
  229.       p += htbl->bits[l];
  230.       dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  231.     } else {
  232.       dtbl->maxcode[l] = -1;    /* -1 if no codes of this length */
  233.     }
  234.   }
  235.   dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  236.  
  237.   /* Compute lookahead tables to speed up decoding.
  238.    * First we set all the table entries to 0, indicating "too long";
  239.    * then we iterate through the Huffman codes that are short enough and
  240.    * fill in all the entries that correspond to bit sequences starting
  241.    * with that code.
  242.    */
  243.  
  244.     memset(dtbl->look_nbits, 0, sizeof(dtbl->look_nbits));
  245.  
  246.   p = 0;
  247.   for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  248.     for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  249.       /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  250.       /* Generate left-justified code followed by all possible bit sequences */
  251.       lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  252.       for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  253.     dtbl->look_nbits[lookbits] = l;
  254.     dtbl->look_sym[lookbits] = htbl->huffval[p];
  255.     lookbits++;
  256.       }
  257.     }
  258.   }
  259.  
  260.   /* Validate symbols as being reasonable.
  261.    * For AC tables, we make no check, but accept all byte values 0..255.
  262.    * For DC tables, we require the symbols to be in range 0..15.
  263.    * (Tighter bounds could be applied depending on the data depth and mode,
  264.    * but this is sufficient to ensure safe decoding.)
  265.    */
  266.   if (isDC) {
  267.     for (i = 0; i < numsymbols; i++) {
  268.       int sym = htbl->huffval[i];
  269.       if (sym < 0 || sym > 15)
  270.     cinfo->ERREXIT(JERR_BAD_HUFF_TABLE);
  271.     }
  272.   }
  273. }
  274.  
  275.  
  276. /*
  277.  * Out-of-line code for bit fetching (shared with jdphuff.c).
  278.  * See jdhuff.h for info about usage.
  279.  * Note: current values of get_buffer and bits_left are passed as parameters,
  280.  * but are returned in the corresponding fields of the state struct.
  281.  *
  282.  * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  283.  * of get_buffer to be used.  (On machines with wider words, an even larger
  284.  * buffer could be used.)  However, on some machines 32-bit shifts are
  285.  * quite slow and take time proportional to the number of places shifted.
  286.  * (This is true with most PC compilers, for instance.)  In this case it may
  287.  * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
  288.  * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  289.  */
  290.  
  291. #ifdef SLOW_SHIFT_32
  292. #define MIN_GET_BITS  15    /* minimum allowable value */
  293. #else
  294. #define MIN_GET_BITS  (BIT_BUF_SIZE-7)
  295. #endif
  296.  
  297. // Load up the bit buffer to a depth of at least nbits 
  298. boolean bitread_working_state::jpeg_fill_bit_buffer(bit_buf_type get_buffer, int bits_left, int nbits)
  299. {
  300.     // Copy heavily used state fields into locals (hopefully registers)
  301.     const JOCTET * next_input_byte  = m_next_input_byte;
  302.     size_t bytes_in_buffer            = m_bytes_in_buffer;
  303.     j_decompress_ptr cinfo            = m_cinfo;
  304.  
  305.     /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  306.     /* (It is assumed that no request will be for more than that many bits.) */
  307.     /* We fail to do so only if we hit a marker or are forced to suspend. */
  308.  
  309.     if (cinfo->unread_marker == 0) /* cannot advance past a marker */
  310.     {
  311.         while (bits_left < MIN_GET_BITS) 
  312.         {
  313.             /* Attempt to read a byte */
  314.             if (bytes_in_buffer == 0) 
  315.             {
  316.                 if (! cinfo->src->fill_input_buffer(cinfo))
  317.                     return FALSE;
  318.                 next_input_byte = cinfo->src->next_input_byte;
  319.                 bytes_in_buffer = cinfo->src->bytes_in_buffer;
  320.             }
  321.       
  322.             bytes_in_buffer--;
  323.             
  324.             int c = GETJOCTET(*next_input_byte++);
  325.  
  326.             /* If it's 0xFF, check and discard stuffed zero byte */
  327.             if (c == 0xFF) 
  328.             {
  329.                 /* Loop here to discard any padding FF's on terminating marker,
  330.                 * so that we can save a valid unread_marker value.  NOTE: we will
  331.                 * accept multiple FF's followed by a 0 as meaning a single FF data
  332.                 * byte.  This data pattern is not valid according to the standard.
  333.                 */
  334.                 do 
  335.                 {
  336.                     if (bytes_in_buffer == 0) 
  337.                     {
  338.                         if (! cinfo->src->fill_input_buffer(cinfo))
  339.                             return FALSE;
  340.                         next_input_byte = cinfo->src->next_input_byte;
  341.                         bytes_in_buffer = cinfo->src->bytes_in_buffer;
  342.                     }
  343.                     bytes_in_buffer--;
  344.                     c = GETJOCTET(*next_input_byte++);
  345.                 } 
  346.                 while (c == 0xFF);
  347.  
  348.                 if (c == 0) 
  349.                 {
  350.                     /* Found FF/00, which represents an FF data byte */
  351.                     c = 0xFF;
  352.                 } 
  353.                 else 
  354.                 {
  355.                     /* Oops, it's actually a marker indicating end of compressed data.
  356.                     * Save the marker code for later use.
  357.                     * Fine point: it might appear that we should save the marker into
  358.                     * bitread working state, not straight into permanent state.  But
  359.                     * once we have hit a marker, we cannot need to suspend within the
  360.                     * current MCU, because we will read no more bytes from the data
  361.                     * source.  So it is OK to update permanent state right away.
  362.                     */
  363.                     cinfo->unread_marker = c;
  364.                     /* See if we need to insert some fake zero bits. */
  365.                     goto no_more_bytes;
  366.                 }
  367.             }
  368.  
  369.             /* OK, load c into get_buffer */
  370.             get_buffer = (get_buffer << 8) | c;
  371.             bits_left += 8;
  372.         } /* end while */
  373.     } 
  374.     else 
  375.     {
  376.         no_more_bytes:
  377.         /* We get here if we've read the marker that terminates the compressed
  378.         * data segment.  There should be enough bits in the buffer register
  379.         * to satisfy the request; if so, no problem.
  380.         */
  381.         if (nbits > bits_left) 
  382.         {
  383.             /* Uh-oh.  Report corrupted data to user and stuff zeroes into
  384.             * the data stream, so that we can produce some kind of image.
  385.             * We use a nonvolatile flag to ensure that only one warning message
  386.             * appears per data segment.
  387.             */
  388.             if (! cinfo->entropy->insufficient_data) 
  389.             {
  390.                 cinfo->WARNMS(JWRN_HIT_MARKER);
  391.                 cinfo->entropy->insufficient_data = TRUE;
  392.             }
  393.             /* Fill the buffer with zero bits */
  394.             get_buffer <<= MIN_GET_BITS - bits_left;
  395.             bits_left = MIN_GET_BITS;
  396.         }
  397.     }
  398.  
  399.     /* Unload the local registers */
  400.     m_next_input_byte = next_input_byte;
  401.     m_bytes_in_buffer = bytes_in_buffer;
  402.     m_get_buffer = get_buffer;
  403.     m_bits_left = bits_left;
  404.  
  405.     return TRUE;
  406. }
  407.  
  408.  
  409. /*
  410.  * Out-of-line code for Huffman code decoding.
  411.  * See jdhuff.h for info about usage.
  412.  */
  413.  
  414. int bitread_working_state::jpeg_huff_decode (bit_buf_type get_buffer, int bits_left, d_derived_tbl * htbl, int min_bits)
  415. {
  416.     register int i = min_bits;
  417.     register long code;
  418.  
  419.     /* HUFF_DECODE has determined that the code is at least min_bits */
  420.     /* bits long, so fetch that many bits in one swoop. */
  421.  
  422. /*    if ( bits_left>16 )
  423.     {
  424.         code = GET_BITS(i);
  425.  
  426.         // Collect the rest of the Huffman code one bit at a time. 
  427.         // This is per Figure F.16 in the JPEG spec. 
  428.  
  429.         while (code > htbl->maxcode[i]) 
  430.         {
  431.             code = (code << 1) | GET_BITS(1);
  432.             i++;
  433.         }
  434.  
  435.     }
  436.     else */
  437.     {
  438.         if ( ! CHECK_BIT_BUFFER(i, bits_left, get_buffer) )
  439.             return -1;
  440.     
  441.         code = GET_BITS(i);
  442.  
  443.         /* Collect the rest of the Huffman code one bit at a time. */
  444.         /* This is per Figure F.16 in the JPEG spec. */
  445.  
  446.         while (code > htbl->maxcode[i]) 
  447.         {
  448.             code <<= 1;
  449.         
  450.             if ( ! CHECK_BIT_BUFFER(1, bits_left, get_buffer ) )
  451.                 return -1;
  452.         
  453.             code |= GET_BITS(1);
  454.             i++;
  455.         }
  456.     }
  457.  
  458.     /* Unload the local registers */
  459.     m_get_buffer = get_buffer;
  460.     m_bits_left  = bits_left;
  461.  
  462.     /* With garbage input we may reach the sentinel value l = 17. */
  463.  
  464.     if (i > 16) 
  465.     {
  466.         m_cinfo->WARNMS(JWRN_HUFF_BAD_CODE);
  467.         return 0;            /* fake a zero as the safest result */
  468.     }
  469.  
  470.     return htbl->pub->huffval[ (int) (code + htbl->valoffset[i]) ];
  471. }
  472.  
  473.  
  474. /*
  475.  * Figure F.12: extend sign bit.
  476.  * On some machines, a shift and add will be faster than a table lookup.
  477.  */
  478.  
  479. #ifdef AVOID_TABLES
  480.  
  481. #define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  482.  
  483. #else
  484.  
  485. #define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  486.  
  487. static const int extend_test[16] =   /* entry n is 2**(n-1) */
  488.   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  489.     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  490.  
  491. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  492.   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  493.     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  494.     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  495.     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  496.  
  497. #endif /* AVOID_TABLES */
  498.  
  499.  
  500. /*
  501.  * Check for a restart marker & resynchronize decoder.
  502.  * Returns FALSE if must suspend.
  503.  */
  504.  
  505. LOCAL(boolean)
  506. process_restart (j_decompress_ptr cinfo)
  507. {
  508.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  509.   int ci;
  510.  
  511.   /* Throw away any unused bits remaining in bit buffer; */
  512.   /* include any full bytes in next_marker's count of discarded bytes */
  513.   cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  514.   entropy->bitstate.bits_left = 0;
  515.  
  516.   /* Advance past the RSTn marker */
  517.   if (! (*cinfo->marker->read_restart_marker) (cinfo))
  518.     return FALSE;
  519.  
  520.   /* Re-initialize DC predictions to 0 */
  521.   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  522.     entropy->saved.last_dc_val[ci] = 0;
  523.  
  524.   /* Reset restart counter */
  525.   entropy->restarts_to_go = cinfo->restart_interval;
  526.  
  527.   /* Reset out-of-data flag, unless read_restart_marker left us smack up
  528.    * against a marker.  In that case we will end up treating the next data
  529.    * segment as empty, and we can avoid producing bogus output pixels by
  530.    * leaving the flag set.
  531.    */
  532.   if (cinfo->unread_marker == 0)
  533.     entropy->pub.insufficient_data = FALSE;
  534.  
  535.   return TRUE;
  536. }
  537.  
  538.  
  539. /*
  540.  * Decode and return one MCU's worth of Huffman-compressed coefficients.
  541.  * The coefficients are reordered from zigzag order into natural array order,
  542.  * but are not dequantized.
  543.  *
  544.  * The i'th block of the MCU is stored into the block pointed to by
  545.  * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  546.  * (Wholesale zeroing is usually a little faster than retail...)
  547.  *
  548.  * Returns FALSE if data source requested suspension.  In that case no
  549.  * changes have been made to permanent state.  (Exception: some output
  550.  * coefficients may already have been assigned.  This is harmless for
  551.  * this module, since we'll just re-assign them on the next call.)
  552.  */
  553.  
  554. boolean decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  555. {
  556.   huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  557.   int blkn;
  558.   BITREAD_STATE_VARS;
  559.   savable_state state;
  560.  
  561.   /* Process restart marker if needed; may have to suspend */
  562.   if (cinfo->restart_interval) {
  563.     if (entropy->restarts_to_go == 0)
  564.       if (! process_restart(cinfo))
  565.     return FALSE;
  566.   }
  567.  
  568.     // If we've run out of data, just leave the MCU set to zeroes.
  569.     // This way, we return uniform gray for the remainder of the segment.
  570.     
  571.     if (! entropy->pub.insufficient_data) 
  572.     {
  573.         /* Load up working state */
  574.         BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  575.         ASSIGN_STATE(state, entropy->saved);
  576.  
  577.         // Outer loop handles each block in the MCU
  578.  
  579.         for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) 
  580.         {
  581.             JBLOCKROW block = MCU_data[blkn];
  582.             d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  583.             d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  584.             register int s, k, r;
  585.  
  586.             /* Decode a single block's worth of coefficients */
  587.  
  588.             /* Section F.2.2.1: decode the DC coefficient difference */
  589.             if ( ! br_state.HUFF_DECODE(s, bits_left, get_buffer, dctbl) )
  590.                 return FALSE;
  591.       
  592.             if (s) 
  593.             {
  594.                 if ( ! br_state.CHECK_BIT_BUFFER(s, bits_left, get_buffer) )
  595.                     return FALSE;
  596.                 
  597.                 r = GET_BITS(s);
  598.                 s = HUFF_EXTEND(r, s);
  599.             }
  600.  
  601.             if (entropy->dc_needed[blkn]) 
  602.             {
  603.                 /* Convert DC difference to actual value, update last_dc_val */
  604.                 int ci = cinfo->MCU_membership[blkn];
  605.                 s += state.last_dc_val[ci];
  606.                 state.last_dc_val[ci] = s;
  607.                 /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  608.                 (*block)[0] = (JCOEF) s;
  609.             }
  610.  
  611.             if (entropy->ac_needed[blkn]) 
  612.             {
  613.  
  614.                 /* Section F.2.2.2: decode the AC coefficients */
  615.                 /* Since zeroes are skipped, output area must be cleared beforehand */
  616.                 
  617.                 for (k = 1; k < DCTSIZE2; k++) 
  618.                 {
  619.                     if ( ! br_state.HUFF_DECODE(s, bits_left, get_buffer, actbl) )
  620.                         return FALSE;
  621.       
  622.                     r = s >> 4;
  623.                     s &= 15;
  624.       
  625.                     if (s) 
  626.                     {
  627.                         k += r;
  628.                         
  629.                         if ( ! br_state.CHECK_BIT_BUFFER(s, bits_left, get_buffer) )
  630.                             return FALSE;
  631.                         
  632.                         r = GET_BITS(s);
  633.                         s = HUFF_EXTEND(r, s);
  634.                         /* Output coefficient in natural (dezigzagged) order.
  635.                         * Note: the extra entries in jpeg_natural_order[] will save us
  636.                         * if k >= DCTSIZE2, which could happen if the data is corrupted.
  637.                         */
  638.                         (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  639.                     } 
  640.                     else 
  641.                     {
  642.                         if (r != 15)
  643.                             break;
  644.                         k += 15;
  645.                     }
  646.                 }
  647.             } 
  648.             else 
  649.             {
  650.                 /* Section F.2.2.2: decode the AC coefficients */
  651.                 /* In this path we just discard the values */
  652.                 for (k = 1; k < DCTSIZE2; k++) 
  653.                 {
  654.                     if ( ! br_state.HUFF_DECODE(s, bits_left, get_buffer, actbl) )
  655.                         return FALSE;
  656.       
  657.                     r = s >> 4;
  658.                     s &= 15;
  659.       
  660.                     if (s) 
  661.                     {
  662.                         k += r;
  663.                         
  664.                         if ( ! br_state.CHECK_BIT_BUFFER(s, bits_left, get_buffer) )
  665.                             return FALSE;
  666.                         
  667.                         DROP_BITS(s);
  668.                     } 
  669.                     else 
  670.                     {
  671.                         if (r != 15)
  672.                             break;
  673.                         k += 15;
  674.                     }
  675.                 }
  676.             }
  677.         }
  678.  
  679.         /* Completed MCU, so update state */
  680.         BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  681.         ASSIGN_STATE(entropy->saved, state);
  682.     }
  683.  
  684.     /* Account for restart interval (no-op if not using restarts) */
  685.     entropy->restarts_to_go--;
  686.  
  687.     return TRUE;
  688. }
  689.  
  690.  
  691. /*
  692.  * Module initialization routine for Huffman entropy decoding.
  693.  */
  694.  
  695. GLOBAL(void)
  696. jinit_huff_decoder (j_decompress_ptr cinfo)
  697. {
  698.     huff_entropy_ptr entropy;
  699.  
  700.     entropy = (huff_entropy_ptr)
  701.         cinfo->mem->alloc_small(JPOOL_IMAGE, sizeof(huff_entropy_decoder));
  702.     cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  703.     entropy->pub.start_pass = start_pass_huff_decoder;
  704.     entropy->pub.decode_mcu = decode_mcu;
  705.  
  706.     /* Mark tables unallocated */
  707.     for (int i = 0; i < NUM_HUFF_TBLS; i++) 
  708.     {
  709.         entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  710.     }
  711. }
  712.