home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / OSK / GRAPHICS / JPEGSRC.V4.lzh / jdhuff.c < prev    next >
Text File  |  1993-01-14  |  12KB  |  417 lines

  1. /*
  2.  * jdhuff.c
  3.  *
  4.  * Copyright (C) 1991, 1992, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains Huffman entropy decoding routines.
  9.  * These routines are invoked via the methods entropy_decode
  10.  * and entropy_decode_init/term.
  11.  */
  12.  
  13. #include "jinclude.h"
  14.  
  15.  
  16. /* Static variables to avoid passing 'round extra parameters */
  17.  
  18. static decompress_info_ptr dcinfo;
  19.  
  20. static INT32 get_buffer;    /* current bit-extraction buffer */
  21. static int bits_left;        /* # of unused bits in it */
  22. static boolean printed_eod;    /* flag to suppress multiple end-of-data msgs */
  23.  
  24. LOCAL void
  25. fix_huff_tbl (HUFF_TBL * htbl)
  26. /* Compute derived values for a Huffman table */
  27. {
  28.   int p, i, l, si;
  29.   char huffsize[257];
  30.   UINT16 huffcode[257];
  31.   UINT16 code;
  32.   
  33.   /* Figure C.1: make table of Huffman code length for each symbol */
  34.   /* Note that this is in code-length order. */
  35.  
  36.   p = 0;
  37.   for (l = 1; l <= 16; l++) {
  38.     for (i = 1; i <= (int) htbl->bits[l]; i++)
  39.       huffsize[p++] = (char) l;
  40.   }
  41.   huffsize[p] = 0;
  42.   
  43.   /* Figure C.2: generate the codes themselves */
  44.   /* Note that this is in code-length order. */
  45.   
  46.   code = 0;
  47.   si = huffsize[0];
  48.   p = 0;
  49.   while (huffsize[p]) {
  50.     while (((int) huffsize[p]) == si) {
  51.       huffcode[p++] = code;
  52.       code++;
  53.     }
  54.     code <<= 1;
  55.     si++;
  56.   }
  57.  
  58.   /* We don't bother to fill in the encoding tables ehufco[] and ehufsi[], */
  59.   /* since they are not used for decoding. */
  60.  
  61.   /* Figure F.15: generate decoding tables */
  62.  
  63.   p = 0;
  64.   for (l = 1; l <= 16; l++) {
  65.     if (htbl->bits[l]) {
  66.       htbl->valptr[l] = p;    /* huffval[] index of 1st sym of code len l */
  67.       htbl->mincode[l] = huffcode[p]; /* minimum code of length l */
  68.       p += htbl->bits[l];
  69.       htbl->maxcode[l] = huffcode[p-1];    /* maximum code of length l */
  70.     } else {
  71.       htbl->maxcode[l] = -1;
  72.     }
  73.   }
  74.   htbl->maxcode[17] = 0xFFFFFL;    /* ensures huff_DECODE terminates */
  75. }
  76.  
  77.  
  78. /*
  79.  * Code for extracting the next N bits from the input stream.
  80.  * (N never exceeds 15 for JPEG data.)
  81.  * This needs to go as fast as possible!
  82.  *
  83.  * We read source bytes into get_buffer and dole out bits as needed.
  84.  * If get_buffer already contains enough bits, they are fetched in-line
  85.  * by the macros get_bits() and get_bit().  When there aren't enough bits,
  86.  * fill_bit_buffer is called; it will attempt to fill get_buffer to the
  87.  * "high water mark", then extract the desired number of bits.  The idea,
  88.  * of course, is to minimize the function-call overhead cost of entering
  89.  * fill_bit_buffer.
  90.  * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  91.  * of get_buffer to be used.  (On machines with wider words, an even larger
  92.  * buffer could be used.)  However, on some machines 32-bit shifts are
  93.  * relatively slow and take time proportional to the number of places shifted.
  94.  * (This is true with most PC compilers, for instance.)  In this case it may
  95.  * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
  96.  * average shift distance at the cost of more calls to fill_bit_buffer.
  97.  */
  98.  
  99. #ifdef SLOW_SHIFT_32
  100. #define MIN_GET_BITS  15    /* minimum allowable value */
  101. #else
  102. #define MIN_GET_BITS  25    /* max value for 32-bit get_buffer */
  103. #endif
  104.  
  105. static const int bmask[16] =    /* bmask[n] is mask for n rightmost bits */
  106.   { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  107.     0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
  108.  
  109.  
  110. LOCAL int
  111. fill_bit_buffer (int nbits)
  112. /* Load up the bit buffer and do get_bits(nbits) */
  113. {
  114.   /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  115.   while (bits_left < MIN_GET_BITS) {
  116.     register int c = JGETC(dcinfo);
  117.     
  118.     /* If it's 0xFF, check and discard stuffed zero byte */
  119.     if (c == 0xFF) {
  120.       int c2 = JGETC(dcinfo);
  121.       if (c2 != 0) {
  122.     /* Oops, it's actually a marker indicating end of compressed data. */
  123.     /* Better put it back for use later */
  124.     JUNGETC(c2,dcinfo);
  125.     JUNGETC(c,dcinfo);
  126.     /* There should be enough bits still left in the data segment; */
  127.     /* if so, just break out of the while loop. */
  128.     if (bits_left >= nbits)
  129.       break;
  130.     /* Uh-oh.  Report corrupted data to user and stuff zeroes into
  131.      * the data stream, so we can produce some kind of image.
  132.      * Note that this will be repeated for each byte demanded for the
  133.      * rest of the segment; this is a bit slow but not unreasonably so.
  134.      * The main thing is to avoid getting a zillion warnings, hence:
  135.      */
  136.     if (! printed_eod) {
  137.       WARNMS(dcinfo->emethods, "Corrupt JPEG data: premature end of data segment");
  138.       printed_eod = TRUE;
  139.     }
  140.     c = 0;            /* insert a zero byte into bit buffer */
  141.       }
  142.     }
  143.  
  144.     /* OK, load c into get_buffer */
  145.     get_buffer = (get_buffer << 8) | c;
  146.     bits_left += 8;
  147.   }
  148.  
  149.   /* Having filled get_buffer, extract desired bits (this simplifies macros) */
  150.   bits_left -= nbits;
  151.   return ((int) (get_buffer >> bits_left)) & bmask[nbits];
  152. }
  153.  
  154.  
  155. /* Macros to make things go at some speed! */
  156. /* NB: parameter to get_bits should be simple variable, not expression */
  157.  
  158. #define get_bits(nbits) \
  159.     (bits_left >= (nbits) ? \
  160.      ((int) (get_buffer >> (bits_left -= (nbits)))) & bmask[nbits] : \
  161.      fill_bit_buffer(nbits))
  162.  
  163. #define get_bit() \
  164.     (bits_left ? \
  165.      ((int) (get_buffer >> (--bits_left))) & 1 : \
  166.      fill_bit_buffer(1))
  167.  
  168.  
  169. /* Figure F.16: extract next coded symbol from input stream */
  170.   
  171. INLINE
  172. LOCAL int
  173. huff_DECODE (HUFF_TBL * htbl)
  174. {
  175.   register int l;
  176.   register INT32 code;
  177.   
  178.   code = get_bit();
  179.   l = 1;
  180.   while (code > htbl->maxcode[l]) {
  181.     code = (code << 1) | get_bit();
  182.     l++;
  183.   }
  184.  
  185.   /* With garbage input we may reach the sentinel value l = 17. */
  186.  
  187.   if (l > 16) {
  188.     WARNMS(dcinfo->emethods, "Corrupt JPEG data: bad Huffman code");
  189.     return 0;            /* fake a zero as the safest result */
  190.   }
  191.  
  192.   return htbl->huffval[ htbl->valptr[l] + ((int) (code - htbl->mincode[l])) ];
  193. }
  194.  
  195.  
  196. /* Figure F.12: extend sign bit */
  197.  
  198. #define huff_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  199.  
  200. static const int extend_test[16] =   /* entry n is 2**(n-1) */
  201.   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  202.     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  203.  
  204. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  205.   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  206.     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  207.     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  208.     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  209.  
  210.  
  211. /*
  212.  * Initialize for a Huffman-compressed scan.
  213.  * This is invoked after reading the SOS marker.
  214.  */
  215.  
  216. METHODDEF void
  217. huff_decoder_init (decompress_info_ptr cinfo)
  218. {
  219.   short ci;
  220.   jpeg_component_info * compptr;
  221.  
  222.   /* Initialize static variables */
  223.   dcinfo = cinfo;
  224.   bits_left = 0;
  225.   printed_eod = FALSE;
  226.  
  227.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  228.     compptr = cinfo->cur_comp_info[ci];
  229.     /* Make sure requested tables are present */
  230.     if (cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no] == NULL ||
  231.     cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no] == NULL)
  232.       ERREXIT(cinfo->emethods, "Use of undefined Huffman table");
  233.     /* Compute derived values for Huffman tables */
  234.     /* We may do this more than once for same table, but it's not a big deal */
  235.     fix_huff_tbl(cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no]);
  236.     fix_huff_tbl(cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
  237.     /* Initialize DC predictions to 0 */
  238.     cinfo->last_dc_val[ci] = 0;
  239.   }
  240.  
  241.   /* Initialize restart stuff */
  242.   cinfo->restarts_to_go = cinfo->restart_interval;
  243.   cinfo->next_restart_num = 0;
  244. }
  245.  
  246.  
  247. /*
  248.  * Check for a restart marker & resynchronize decoder.
  249.  */
  250.  
  251. LOCAL void
  252. process_restart (decompress_info_ptr cinfo)
  253. {
  254.   int c, nbytes;
  255.   short ci;
  256.  
  257.   /* Throw away any unused bits remaining in bit buffer */
  258.   nbytes = bits_left / 8;    /* count any full bytes loaded into buffer */
  259.   bits_left = 0;
  260.   printed_eod = FALSE;        /* next segment can get another warning */
  261.  
  262.   /* Scan for next JPEG marker */
  263.   do {
  264.     do {            /* skip any non-FF bytes */
  265.       nbytes++;
  266.       c = JGETC(cinfo);
  267.     } while (c != 0xFF);
  268.     do {            /* skip any duplicate FFs */
  269.       /* we don't increment nbytes here since extra FFs are legal */
  270.       c = JGETC(cinfo);
  271.     } while (c == 0xFF);
  272.   } while (c == 0);        /* repeat if it was a stuffed FF/00 */
  273.  
  274.   if (nbytes != 1)
  275.     WARNMS2(cinfo->emethods,
  276.         "Corrupt JPEG data: %d extraneous bytes before marker 0x%02x",
  277.         nbytes-1, c);
  278.  
  279.   if (c != (RST0 + cinfo->next_restart_num)) {
  280.     /* Uh-oh, the restart markers have been messed up too. */
  281.     /* Let the file-format module try to figure out how to resync. */
  282.     (*cinfo->methods->resync_to_restart) (cinfo, c);
  283.   } else
  284.     TRACEMS1(cinfo->emethods, 2, "RST%d", cinfo->next_restart_num);
  285.  
  286.   /* Re-initialize DC predictions to 0 */
  287.   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  288.     cinfo->last_dc_val[ci] = 0;
  289.  
  290.   /* Update restart state */
  291.   cinfo->restarts_to_go = cinfo->restart_interval;
  292.   cinfo->next_restart_num = (cinfo->next_restart_num + 1) & 7;
  293. }
  294.  
  295.  
  296. /* ZAG[i] is the natural-order position of the i'th element of zigzag order.
  297.  * If the incoming data is corrupted, huff_decode_mcu could attempt to
  298.  * reference values beyond the end of the array.  To avoid a wild store,
  299.  * we put some extra zeroes after the real entries.
  300.  */
  301.  
  302. static const short ZAG[DCTSIZE2+16] = {
  303.   0,  1,  8, 16,  9,  2,  3, 10,
  304.  17, 24, 32, 25, 18, 11,  4,  5,
  305.  12, 19, 26, 33, 40, 48, 41, 34,
  306.  27, 20, 13,  6,  7, 14, 21, 28,
  307.  35, 42, 49, 56, 57, 50, 43, 36,
  308.  29, 22, 15, 23, 30, 37, 44, 51,
  309.  58, 59, 52, 45, 38, 31, 39, 46,
  310.  53, 60, 61, 54, 47, 55, 62, 63,
  311.   0,  0,  0,  0,  0,  0,  0,  0, /* extra entries in case k>63 below */
  312.   0,  0,  0,  0,  0,  0,  0,  0
  313. };
  314.  
  315.  
  316. /*
  317.  * Decode and return one MCU's worth of Huffman-compressed coefficients.
  318.  * This routine also handles quantization descaling and zigzag reordering
  319.  * of coefficient values.
  320.  *
  321.  * The i'th block of the MCU is stored into the block pointed to by
  322.  * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  323.  * (Wholesale zeroing is usually a little faster than retail...)
  324.  */
  325.  
  326. METHODDEF void
  327. huff_decode_mcu (decompress_info_ptr cinfo, JBLOCKROW *MCU_data)
  328. {
  329.   register int s, k, r;
  330.   short blkn, ci;
  331.   register JBLOCKROW block;
  332.   register QUANT_TBL_PTR quanttbl;
  333.   HUFF_TBL *dctbl;
  334.   HUFF_TBL *actbl;
  335.   jpeg_component_info * compptr;
  336.  
  337.   /* Account for restart interval, process restart marker if needed */
  338.   if (cinfo->restart_interval) {
  339.     if (cinfo->restarts_to_go == 0)
  340.       process_restart(cinfo);
  341.     cinfo->restarts_to_go--;
  342.   }
  343.  
  344.   /* Outer loop handles each block in the MCU */
  345.  
  346.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  347.     block = MCU_data[blkn];
  348.     ci = cinfo->MCU_membership[blkn];
  349.     compptr = cinfo->cur_comp_info[ci];
  350.     quanttbl = cinfo->quant_tbl_ptrs[compptr->quant_tbl_no];
  351.     actbl = cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no];
  352.     dctbl = cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no];
  353.  
  354.     /* Decode a single block's worth of coefficients */
  355.  
  356.     /* Section F.2.2.1: decode the DC coefficient difference */
  357.     s = huff_DECODE(dctbl);
  358.     if (s) {
  359.       r = get_bits(s);
  360.       s = huff_EXTEND(r, s);
  361.     }
  362.  
  363.     /* Convert DC difference to actual value, update last_dc_val */
  364.     s += cinfo->last_dc_val[ci];
  365.     cinfo->last_dc_val[ci] = (JCOEF) s;
  366.     /* Descale and output the DC coefficient (assumes ZAG[0] = 0) */
  367.     (*block)[0] = (JCOEF) (((JCOEF) s) * quanttbl[0]);
  368.     
  369.     /* Section F.2.2.2: decode the AC coefficients */
  370.     /* Since zero values are skipped, output area must be zeroed beforehand */
  371.     for (k = 1; k < DCTSIZE2; k++) {
  372.       r = huff_DECODE(actbl);
  373.       
  374.       s = r & 15;
  375.       r = r >> 4;
  376.       
  377.       if (s) {
  378.     k += r;
  379.     r = get_bits(s);
  380.     s = huff_EXTEND(r, s);
  381.     /* Descale coefficient and output in natural (dezigzagged) order */
  382.     (*block)[ZAG[k]] = (JCOEF) (((JCOEF) s) * quanttbl[k]);
  383.       } else {
  384.     if (r != 15)
  385.       break;
  386.     k += 15;
  387.       }
  388.     }
  389.   }
  390. }
  391.  
  392.  
  393. /*
  394.  * Finish up at the end of a Huffman-compressed scan.
  395.  */
  396.  
  397. METHODDEF void
  398. huff_decoder_term (decompress_info_ptr cinfo)
  399. {
  400.   /* No work needed */
  401. }
  402.  
  403.  
  404. /*
  405.  * The method selection routine for Huffman entropy decoding.
  406.  */
  407.  
  408. GLOBAL void
  409. jseldhuffman (decompress_info_ptr cinfo)
  410. {
  411.   if (! cinfo->arith_code) {
  412.     cinfo->methods->entropy_decode_init = huff_decoder_init;
  413.     cinfo->methods->entropy_decode = huff_decode_mcu;
  414.     cinfo->methods->entropy_decode_term = huff_decoder_term;
  415.   }
  416. }
  417.