home *** CD-ROM | disk | FTP | other *** search
/ Mega A/V / mega_av.zip / mega_av / GRAPHUTL / FRPOR172.ZIP / DECODER.C < prev    next >
C/C++ Source or Header  |  1992-03-15  |  14KB  |  462 lines

  1. /* DECODE.C - An LZW decoder for GIF
  2.  * Copyright (C) 1987, by Steven A. Bennett
  3.  *
  4.  * Permission is given by the author to freely redistribute and include
  5.  * this code in any program as long as this credit is given where due.
  6.  *
  7.  * In accordance with the above, I want to credit Steve Wilhite who wrote
  8.  * the code which this is heavily inspired by...
  9.  *
  10.  * GIF and 'Graphics Interchange Format' are trademarks (tm) of
  11.  * Compuserve, Incorporated, an H&R Block Company.
  12.  *
  13.  * Release Notes: This file contains a decoder routine for GIF images
  14.  * which is similar, structurally, to the original routine by Steve Wilhite.
  15.  * It is, however, somewhat noticably faster in most cases.
  16.  *
  17.  == This routine was modified for use in FRACTINT in two ways.
  18.  ==
  19.  == 1) The original #includes were folded into the routine strictly to hold
  20.  ==    down the number of files we were dealing with.
  21.  ==
  22.  == 2) The 'stack', 'suffix', 'prefix', and 'decoderline' arrays were changed from
  23.  ==    static and 'malloc()'ed to external only so that the assembler
  24.  ==    program could use the same array space for several independent
  25.  ==    chunks of code.    Also, 'stack' was renamed to 'dstack' for TASM
  26.  ==    compatibility.
  27.  ==
  28.  == 3) The 'out_line()' external function has been changed to reference
  29.  ==    '*outln()' for flexibility (in particular, 3D transformations)
  30.  ==
  31.  == 4) A call to 'keypressed()' has been added after the 'outln()' calls
  32.  ==    to check for the presenc of a key-press as a bail-out signal
  33.  ==
  34.  == (Bert Tyler and Timothy Wegner)
  35.  */
  36.  
  37. /* Rev ??/??/?? - Initial Release
  38.  * Rev 01/02/91 - Revised by Mike Gelvin
  39.  *                    altered logic to allow newcode to input a line at a time
  40.  *                    altered logic to allow decoder to place characters
  41.  *                        directly into the output buffer if they fit
  42. */
  43.  
  44. /***** C Library Includes ***********************************************/
  45. #include <stdio.h>
  46.  
  47. /***** Application Includes *********************************************/
  48. #include "port.h"
  49.  
  50. /***** Application Function Prototypes **********************************/
  51. short decoder(short);
  52. static short get_next_code(void);
  53.  
  54. /* extern short get_byte()
  55.  *
  56.  *   - This external (machine specific) function is expected to return
  57.  * either the next byte from the GIF file, or a negative number, as
  58.  * defined in ERRS.H.
  59.  */
  60. extern short get_byte(void);
  61. extern short get_bytes(BYTE *,int);
  62.  
  63. extern int keypressed(void);
  64.  
  65. /* extern short out_line(pixels, linelen)
  66.  *     UBYTE pixels[];
  67.  *     short linelen;
  68.  *
  69.  *   - This function takes a full line of pixels (one byte per pixel) and
  70.  * displays them (or does whatever your program wants with them...).  It
  71.  * should return zero, or negative if an error or some other event occurs
  72.  * which would require aborting the decode process...  Note that the length
  73.  * passed will almost always be equal to the line length passed to the
  74.  * decoder function, with the sole exception occurring when an ending code
  75.  * occurs in an odd place in the GIF file...  In any case, linelen will be
  76.  * equal to the number of pixels passed...
  77.  */
  78. extern short out_line();
  79. short (*outln)(BYTE *,short) = out_line;
  80.  
  81. /***** Local Static Variables *******************************************/
  82. /* Various error codes used by decoder
  83.  * and my own routines...   It's okay
  84.  * for you to define whatever you want,
  85.  * as long as it's negative...  It will be
  86.  * returned intact up the various subroutine
  87.  * levels...
  88.  */
  89. #define OUT_OF_MEMORY -10
  90. #define BAD_CODE_SIZE -20
  91. #define READ_ERROR -1
  92. #define WRITE_ERROR -2
  93. #define OPEN_ERROR -3
  94. #define CREATE_ERROR -4
  95.  
  96. #define MAX_CODES   4095
  97.  
  98. #define NOPE 0
  99. #define YUP -1
  100.  
  101. static short curr_size;            /* The current code size */
  102.  
  103. #ifndef XFRACT
  104. static short far sizeofstring[MAX_CODES+1];
  105. #else
  106. static short sizeofstring[MAX_CODES+1];    /* size of string list */
  107. #endif
  108.  
  109. /* The following static variables are used
  110.  * for seperating out codes
  111.  */
  112. static short navail_bytes;        /* # bytes left in block */
  113. static short nbits_left;        /* # bits left in current byte */
  114. static BYTE byte_buff[257];    /* Current block, reuse shared mem */
  115. static BYTE *pbytes;        /* Pointer to next byte in block */
  116. static unsigned short ret_code;
  117.  
  118. static short code_mask[13] = {
  119.      0,
  120.      0x0001, 0x0003,
  121.      0x0007, 0x000F,
  122.      0x001F, 0x003F,
  123.      0x007F, 0x00FF,
  124.      0x01FF, 0x03FF,
  125.      0x07FF, 0x0FFF
  126.      };
  127.  
  128. /***** External Variables ***********************************************/
  129. /* extern short bad_code_count;
  130.  *
  131.  * This value is the only other global required by the using program, and
  132.  * is incremented each time an out of range code is read by the decoder.
  133.  * When this value is non-zero after a decode, your GIF file is probably
  134.  * corrupt in some way...
  135.  */
  136. extern short bad_code_count;
  137.  
  138. /* whups, here are more globals, added by PB: */
  139. extern short skipxdots; /* 0 to get every dot, 1 for every 2nd, 2 every 3rd, ... */
  140. extern short skipydots; /* ditto for rows */
  141.  
  142. /*
  143. I removed the LOCAL identifiers in the arrays below and replaced them
  144. with 'extern's so as to declare (and re-use) the space elsewhere.
  145. The arrays are actually declared in the assembler source.
  146.                         Bert Tyler
  147. */
  148. extern BYTE dstack[MAX_CODES + 1];            /* Stack for storing pixels */
  149. extern BYTE suffix[MAX_CODES + 1];            /* Suffix table */
  150. extern unsigned short prefix[MAX_CODES + 1];        /* Prefix linked list */
  151. extern BYTE decoderline[2];                /* decoded line goes here */
  152.  
  153.  
  154. /* The reason we have these seperated like this instead of using
  155.  * a structure like the original Wilhite code did, is because this
  156.  * stuff generally produces significantly faster code when compiled...
  157.  * This code is full of similar speedups...  (For a good book on writing
  158.  * C for speed or for space optomisation, see Efficient C by Tom Plum,
  159.  * published by Plum-Hall Associates...)
  160.  */
  161.  
  162.  
  163. /***** Program **********************************************************/
  164. /* short decoder(linewidth)
  165.  *    short linewidth;            * Pixels per line of image *
  166.  *
  167.  * - This function decodes an LZW image, according to the method used
  168.  * in the GIF spec.  Every *linewidth* "characters" (ie. pixels) decoded
  169.  * will generate a call to out_line(), which is a user specific function
  170.  * to display a line of pixels.  The function gets its codes from
  171.  * get_next_code() which is responsible for reading blocks of data and
  172.  * seperating them into the proper size codes.    Finally, get_byte() is
  173.  * the global routine to read the next byte from the GIF file.
  174.  *
  175.  * It is generally a good idea to have linewidth correspond to the actual
  176.  * width of a line (as specified in the Image header) to make your own
  177.  * code a bit simpler, but it isn't absolutely necessary.
  178.  *
  179.  * Returns: 0 if successful, else negative.  (See ERRS.H)
  180.  *
  181.  */
  182. short decoder( short linewidth)
  183. {
  184.     BYTE *sp;
  185.     short code;
  186.     short old_code;
  187.     short ret;
  188.     short c;
  189.     short size;
  190.     short i;
  191.     short j;
  192.     short fastloop;
  193.     short bufcnt;                    /* how many empty spaces left in buffer */
  194.     short xskip;
  195.     short slot;                        /* Last read code */
  196.     short newcodes;                    /* First available code */
  197.     BYTE *bufptr;
  198.     short yskip;
  199.     short top_slot;                    /* Highest code for current size */
  200.     short clear;                    /* Value for a clear code */
  201.     short ending;                    /* Value for a ending code */
  202.     BYTE out_value;
  203.  
  204.  
  205.     /* Initialize for decoding a new image...
  206.     */
  207.  
  208.     if ((size = get_byte()) < 0)
  209.         return(size);
  210.     if (size < 2 || 9 < size)
  211.         return(BAD_CODE_SIZE);
  212.  
  213.     curr_size = size + 1;
  214.     top_slot = 1 << curr_size;
  215.     clear = 1 << size;
  216.     ending = clear + 1;
  217.     slot = newcodes = ending + 1;
  218.     navail_bytes = nbits_left = sizeofstring[slot] = xskip = yskip
  219.         = old_code = 0;
  220.     out_value = 0;
  221. for (i = 0; i < slot; i++)
  222. {    sizeofstring[i] = 0;
  223. }
  224.     
  225.     /* Initialize in case they forgot to put in a clear code.
  226.      * (This shouldn't happen, but we'll try and decode it anyway...)
  227.     */
  228.  
  229.     /* Set up the stack pointer and decode buffer pointer
  230.     */
  231.     sp = dstack;
  232.     bufptr = decoderline;
  233.     bufcnt = linewidth;
  234.  
  235.     /* This is the main loop.  For each code we get we pass through the
  236.      * linked list of prefix codes, pushing the corresponding "character" for
  237.      * each code onto the stack.  When the list reaches a single "character"
  238.      * we push that on the stack too, and then start unstacking each
  239.      * character for output in the correct order.  Special handling is
  240.      * included for the clear code, and the whole thing ends when we get
  241.      * an ending code.
  242.     */
  243.     while ((c = get_next_code()) != ending)
  244.     {
  245.  
  246.         /* If we had a file error, return without completing the decode
  247.         */
  248.         if (c < 0)
  249.             return(0);
  250.  
  251.         /* If the code is a clear code, reinitialize all necessary items.
  252.         */
  253.         if (c == clear)
  254.         {
  255.             curr_size = size + 1;
  256.             slot = newcodes;
  257.             sizeofstring[slot] = 0;
  258.             top_slot = 1 << curr_size;
  259.  
  260.             /* Continue reading codes until we get a non-clear code
  261.              * (Another unlikely, but possible case...)
  262.             */
  263.             while ((c = get_next_code()) == clear)
  264.             ;
  265.  
  266.             /* If we get an ending code immediately after a clear code
  267.              * (Yet another unlikely case), then break out of the loop.
  268.             */
  269.             if (c == ending)
  270.                 break;
  271.  
  272.             /* Finally, if the code is beyond the range of already set codes,
  273.              * (This one had better NOT happen...    I have no idea what will
  274.              * result from this, but I doubt it will look good...) then set it
  275.              * to color zero.
  276.             */
  277.             if (c >= slot)
  278.                 c = 0;
  279.  
  280.             old_code = out_value = c;
  281.  
  282.             /* And let us not forget to put the char into the buffer... */
  283.             *sp++ = c;
  284.         }
  285.         else
  286.         {
  287.  
  288.             /* In this case, it's not a clear code or an ending code, so
  289.              * it must be a code code...  So we can now decode the code into
  290.              * a stack of character codes. (Clear as mud, right?)
  291.             */
  292.             code = c;
  293.  
  294.             /* Here we go again with one of those off chances...  If, on the
  295.              * off chance, the code we got is beyond the range of those already
  296.              * set up (Another thing which had better NOT happen...) we trick
  297.              * the decoder into thinking it actually got the next slot avail.
  298.             */
  299.  
  300.             if (code >= slot)
  301.             {
  302.                 if (code > slot)
  303.                 {
  304.                     ++bad_code_count;
  305.                     c = slot;
  306.                 }
  307.                 code = old_code;
  308.                 *sp++ = out_value;
  309.             }
  310.  
  311.             /* Here we scan back along the linked list of prefixes.  If they can
  312.              * fit into the output buffer then transfer them direct.  ELSE push
  313.              * them into the stack until we are down to enough characters that
  314.              * they do fit.  Output the line then fall through to unstack the ones
  315.              * that would not fit.
  316.             */
  317.             fastloop = NOPE;
  318.             while (code >= newcodes)
  319.             {    j = i = sizeofstring[code];
  320.                 if (i > 0 && bufcnt - i > 0 && skipxdots == 0)
  321.                 {
  322.                     fastloop = YUP;
  323.  
  324.                     do
  325.                     {    *(bufptr + j) = suffix[code];
  326.                         code = prefix[code];
  327.                     } while(--j > 0);
  328.                     *bufptr = (BYTE)code;
  329.                     bufptr += ++i;
  330.                     bufcnt -= i;
  331.                     if (bufcnt == 0) /* finished an input row? */
  332.                     {    if (--yskip < 0)
  333.                         {
  334.                             if ((ret = (*outln)(decoderline, bufptr - decoderline)) < 0)
  335.                                 return(ret);
  336.                             yskip = skipydots;
  337.                         }
  338.                         if (keypressed())
  339.                             return(-1);
  340.                         bufptr = decoderline;
  341.                         bufcnt = linewidth;
  342.                         xskip = 0;
  343.                     }
  344.                 }
  345.                 else
  346.                 {
  347.                     *sp++ = suffix[code];
  348.                     code = prefix[code];
  349.                 }
  350.             }
  351.  
  352.             /* Push the last character on the stack, and set up the new
  353.              * prefix and suffix, and if the required slot number is greater
  354.              * than that allowed by the current bit size, increase the bit
  355.              * size.  (NOTE - If we are all full, we *don't* save the new
  356.              * suffix and prefix...  I'm not certain if this is correct...
  357.              * it might be more proper to overwrite the last code...
  358.             */
  359.             if (fastloop == NOPE)
  360.                 *sp++ = (BYTE)code;
  361.  
  362.             if (slot < top_slot)
  363.             {
  364.                 sizeofstring[slot] = sizeofstring[old_code]+1;
  365.                 suffix[slot] = out_value = (BYTE)code;
  366.                 prefix[slot++] = old_code;
  367.                 old_code = c;
  368.             }
  369.             if (slot >= top_slot)
  370.                 if (curr_size < 12)
  371.                 {
  372.                     top_slot <<= 1;
  373.                     ++curr_size;
  374.                 }
  375.         }
  376.         while (sp > dstack)
  377.         {
  378.             --sp;
  379.             if (--xskip < 0)
  380.             {
  381.                 xskip = skipxdots;
  382.                 *bufptr++ = *sp;
  383.             }
  384.             if (--bufcnt == 0) /* finished an input row? */
  385.             {    if (--yskip < 0)
  386.                 {
  387.                     if ((ret = (*outln)(decoderline, bufptr - decoderline)) < 0)
  388.                         return(ret);
  389.                     yskip = skipydots;
  390.                 }
  391.                 if (keypressed())
  392.                     return(-1);
  393.                 bufptr = decoderline;
  394.                 bufcnt = linewidth;
  395.                 xskip = 0;
  396.             }
  397.         }
  398.  
  399.     }
  400.     /* PB note that if last line is incomplete, we're not going to try
  401.      * to emit it;  original code did, but did so via out_line and therefore
  402.      * couldn't have worked well in all cases...
  403.     */
  404.     return(0);
  405. }
  406.  
  407.  
  408.  
  409.  
  410. /***** Program **********************************************************/
  411. /* get_next_code()
  412.  * - gets the next code from the GIF file.  Returns the code, or else
  413.  * a negative number in case of file errors...
  414.  */
  415. static short get_next_code()
  416. {
  417.     static BYTE b1;                /* Current byte */
  418.     static unsigned short ret_code;
  419.  
  420.     if (nbits_left == 0)
  421.     {
  422.         if (navail_bytes <= 0)
  423.         {
  424.  
  425.             /* Out of bytes in current block, so read next block
  426.             */
  427.             pbytes = byte_buff;
  428.             if ((navail_bytes = get_byte()) < 0)
  429.                 return(navail_bytes);
  430.             else
  431.                 if (navail_bytes)
  432.                     get_bytes(byte_buff,navail_bytes);
  433.         }
  434.         b1 = *pbytes++;
  435.         nbits_left = 8;
  436.         --navail_bytes;
  437.     }
  438.  
  439.     ret_code = b1 >> (8 - nbits_left);
  440.     while (curr_size > nbits_left)
  441.     {
  442.         if (navail_bytes <= 0)
  443.         {
  444.  
  445.             /* Out of bytes in current block, so read next block
  446.             */
  447.             pbytes = byte_buff;
  448.             if ((navail_bytes = get_byte()) < 0)
  449.                 return(navail_bytes);
  450.             else
  451.                 if (navail_bytes)
  452.                     get_bytes(byte_buff,navail_bytes);
  453.         }
  454.         b1 = *pbytes++;
  455.         ret_code |= b1 << nbits_left;
  456.         nbits_left += 8;
  457.         --navail_bytes;
  458.     }
  459.     nbits_left -= curr_size;
  460.     return(ret_code & code_mask[curr_size]);
  461. }
  462.