home *** CD-ROM | disk | FTP | other *** search
/ Chestnut's Multimedia Mania / MM_MANIA.ISO / graphics / povsrc20 / gifdecod.c < prev    next >
C/C++ Source or Header  |  1993-08-06  |  16KB  |  489 lines

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