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