home *** CD-ROM | disk | FTP | other *** search
/ Otherware / Otherware_1_SB_Development.iso / mac / developm / source / povsrc.sit / SOURCE / GIFDECOD.C < prev    next >
Encoding:
C/C++ Source or Header  |  1992-07-03  |  14.8 KB  |  479 lines

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