home *** CD-ROM | disk | FTP | other *** search
/ Media Share 9 / MEDIASHARE_09.ISO / graphics / gif-util.zip / DGIF_LIB.C < prev    next >
C/C++ Source or Header  |  1989-08-01  |  29KB  |  793 lines

  1. /*****************************************************************************
  2. *   "Gif-Lib" - Yet another gif library.                     *
  3. *                                         *
  4. * Written by:  Gershon Elber            IBM PC Ver 0.1,    Jun. 1989    *
  5. ******************************************************************************
  6. * The kernel of the GIF Decoding process can be found here.             *
  7. ******************************************************************************
  8. * History:                                     *
  9. * 16 Jun 89 - Version 1.0 by Gershon Elber.                     *
  10. *****************************************************************************/
  11.  
  12. #include <io.h>
  13. #include <fcntl.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <alloc.h>
  17. #include <string.h>
  18. #include <sys\stat.h>
  19. #include "gif_lib.h"
  20. #include "gif_hash.h"
  21.  
  22. #define PROGRAM_NAME    "GIF_LIBRARY"
  23. #define VERSION        "ß Version 1.0, "
  24.  
  25. #define COMMENT_EXT_FUNC_CODE    'C'   /* Extension function code for comment */
  26. #define GIF_STAMP    "GIF87a"      /* First chars in file - GIF stamp */
  27. #define GIF_STAMP_LEN    sizeof(GIF_STAMP) - 1
  28.  
  29. #define LZ_MAX_CODE    4095        /* Biggest code possible in 12 bits. */
  30. #define LZ_BITS        12
  31.  
  32. #define FILE_STATE_READ        0x01/* 1 write, 0 read - EGIF_LIB compatible */
  33.  
  34. #define FLUSH_OUTPUT        4096     /* Impossible code, to signal flush */
  35. #define FIRST_CODE        4097     /* Impossible code, to signal first */
  36. #define NO_SUCH_CODE        4098     /* Impossible code, to signal empty */
  37.  
  38. #define IS_READABLE(Private)    (!(Private -> FileState & FILE_STATE_READ))
  39.  
  40. typedef struct GifFilePrivateType {
  41.     int FileState,
  42.     FileHandle,                 /* Where all this data goes to! */
  43.     BitsPerPixel,         /* Bits per pixel (Codes uses at list this + 1) */
  44.     ClearCode,                    /* The CLEAR LZ code */
  45.     EOFCode,                      /* The EOF LZ code */
  46.     RunningCode,             /* The next code algorithm can generate */
  47.     RunningBits, /* The number of bits required to represent RunningCode */
  48.     MaxCode1,/* 1 bigger than maximum possible code, in RunningBits bits */
  49.     LastCode,             /* The code before the current code */
  50.     CrntCode,                   /* Current algorithm code */
  51.     StackPtr,              /* For character stack (see below) */
  52.     CrntShiftState;             /* Number of bits in CrntShiftDWord */
  53.     unsigned long CrntShiftDWord,      /* For bytes decomposition into codes */
  54.           PixelCount;            /* Number of pixels in image */
  55.     FILE *File;                           /* File as stream */
  56.     ByteType Buf[256];                /* Compressed input is buffered here */
  57.     ByteType Stack[LZ_MAX_CODE];      /* Decoded pixels are stacked here */
  58.     ByteType Suffix[LZ_MAX_CODE+1];        /* So we can trace the codes */
  59.     unsigned int Prefix[LZ_MAX_CODE+1];
  60. } GifFilePrivateType;
  61.  
  62. extern int _GifError;
  63.  
  64. static char *VersionStr =
  65.     PROGRAM_NAME
  66.     "    IBMPC "
  67.     VERSION
  68.     "    Gershon Elber,    "
  69.     __DATE__ ",   " __TIME__ "\n"
  70.     "(C) Copyright 1989 Gershon Elber, Non commercial use only.\n";
  71.  
  72. static int DGifGetWord(FILE *File, int *Word);
  73. static int DGifSetupDecompress(GifFileType *GifFile);
  74. static int DGifDecompressLine(GifFileType *GifFile, PixelType *Line, int LineLen);
  75. static int DGifGetPrefixChar(unsigned int *Prefix, int Code, int ClearCode);
  76. static int DGifDecompressInput(GifFilePrivateType *Private, int *Code);
  77. static int DGifBufferedInput(FILE *File, ByteType *Buf, ByteType *NextByte);
  78.  
  79. /******************************************************************************
  80. *   Open a new gif file for read, given by its name.                  *
  81. *   Returns GifFileType pointer dynamically allocated which serves as the gif *
  82. * info record. _GifError is cleared if succesfull.                  *
  83. ******************************************************************************/
  84. GifFileType *DGifOpenFileName(char *FileName)
  85. {
  86.     int FileHandle;
  87.  
  88.     if ((FileHandle = open(FileName, O_RDONLY | O_BINARY)) == -1) {
  89.     _GifError = D_GIF_ERR_OpenFailed;
  90.     return NULL;
  91.     }
  92.  
  93.     return DGifOpenFileHandle(FileHandle);
  94. }
  95.  
  96. /******************************************************************************
  97. *   Update a new gif file, given its file handle.                  *
  98. *   Returns GifFileType pointer dynamically allocated which serves as the gif *
  99. * info record. _GifError is cleared if succesfull.                  *
  100. ******************************************************************************/
  101. GifFileType *DGifOpenFileHandle(int FileHandle)
  102. {
  103.     char Buf[GIF_STAMP_LEN+1];
  104.     GifFileType *GifFile;
  105.     GifFilePrivateType *Private;
  106.     FILE *f;
  107.  
  108.     setmode(FileHandle, O_BINARY);       /* Make sure it is in binary mode */
  109.     f = fdopen(FileHandle, "rb");           /* Make it into a stream: */
  110.     setvbuf(f, NULL, _IOFBF, FILE_BUFFER_SIZE);/* And increase stream buffer */
  111.  
  112.     if ((GifFile = (GifFileType *) malloc(sizeof(GifFileType))) == NULL) {
  113.     _GifError = D_GIF_ERR_NotEnoughMem;
  114.     return NULL;
  115.     }
  116.  
  117.     if ((Private = (GifFilePrivateType *) malloc(sizeof(GifFilePrivateType)))
  118.     == NULL) {
  119.     _GifError = D_GIF_ERR_NotEnoughMem;
  120.     free((char *) GifFile);
  121.     return NULL;
  122.     }
  123.     GifFile -> Private = (void *) Private;
  124.     GifFile -> SColorMap = GifFile -> IColorMap = NULL;
  125.     Private -> FileHandle = FileHandle;
  126.     Private -> File = f;
  127.     Private -> FileState = 0; /* Make sure bit 0 = 0 (File opened for read) */
  128.  
  129.     /* Lets see if this is GIF file: */
  130.     if (fread(Buf, 1, GIF_STAMP_LEN, Private -> File) != GIF_STAMP_LEN) {
  131.     _GifError = D_GIF_ERR_ReadFailed;
  132.     free((char *) Private);
  133.     free((char *) GifFile);
  134.     return NULL;
  135.     }
  136.  
  137.     Buf[GIF_STAMP_LEN] = 0;
  138.     if (strcmp(GIF_STAMP, Buf) != 0) {
  139.     _GifError = D_GIF_ERR_NotGifFile;
  140.     free((char *) Private);
  141.     free((char *) GifFile);
  142.     return NULL;
  143.     }
  144.  
  145.     if (DGifGetScreenDesc(GifFile) == ERROR) {
  146.     free((char *) Private);
  147.     free((char *) GifFile);
  148.     return NULL;
  149.     }
  150.  
  151.     _GifError = 0;
  152.  
  153.     return GifFile;
  154. }
  155.  
  156. /******************************************************************************
  157. *   This routine should be called before any other DGif calls. Note that      *
  158. * this routine is called automatically from DGif file open routines.          *
  159. ******************************************************************************/
  160. int DGifGetScreenDesc(GifFileType *GifFile)
  161. {
  162.     int Size, i;
  163.     ByteType Buf[3];
  164.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  165.  
  166.     if (!IS_READABLE(Private)) {
  167.     /* This file was NOT open for reading: */
  168.     _GifError = D_GIF_ERR_NotReadable;
  169.     return ERROR;
  170.     }
  171.  
  172.     /* Put the screen descriptor into the file: */
  173.     if (DGifGetWord(Private -> File, &GifFile -> SWidth) == ERROR ||
  174.     DGifGetWord(Private -> File, &GifFile -> SHeight) == ERROR)
  175.     return ERROR;
  176.  
  177.     if (fread(Buf, 1, 3, Private -> File) != 3) {
  178.     _GifError = D_GIF_ERR_ReadFailed;
  179.     return ERROR;
  180.     }
  181.     GifFile -> SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1;
  182.     GifFile -> SBitsPerPixel = (Buf[0] & 0x07) + 1;
  183.     GifFile -> SBackGroundColor = Buf[1];
  184.     if (Buf[0] & 0x80) {             /* Do we have global color map? */
  185.     Size = (1 << GifFile -> SBitsPerPixel);
  186.     GifFile -> SColorMap =
  187.         (GifColorType *) malloc(sizeof(GifColorType) * Size);
  188.     for (i=0; i<Size; i++) {        /* Get the global color map: */
  189.         if (fread(Buf, 1, 3, Private -> File) != 3) {
  190.         _GifError = D_GIF_ERR_ReadFailed;
  191.         return ERROR;
  192.         }
  193.         GifFile -> SColorMap[i].Red = Buf[0];
  194.         GifFile -> SColorMap[i].Green = Buf[1];
  195.         GifFile -> SColorMap[i].Blue = Buf[2];
  196.     }
  197.     }
  198.  
  199.     return OK;
  200. }
  201.  
  202. /******************************************************************************
  203. *   This routine should be called before any attemp to read an image.         *
  204. ******************************************************************************/
  205. int DGifGetRecordType(GifFileType *GifFile, GifRecordType *Type)
  206. {
  207.     ByteType Buf;
  208.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  209.  
  210.     if (!IS_READABLE(Private)) {
  211.     /* This file was NOT open for reading: */
  212.     _GifError = D_GIF_ERR_NotReadable;
  213.     return ERROR;
  214.     }
  215.  
  216.     if (fread(&Buf, 1, 1, Private -> File) != 1) {
  217.     _GifError = D_GIF_ERR_ReadFailed;
  218.     return ERROR;
  219.     }
  220.  
  221.     switch (Buf) {
  222.     case ',':
  223.         *Type = IMAGE_DESC_RECORD_TYPE;
  224.         break;
  225.     case '!':
  226.         *Type = EXTENSION_RECORD_TYPE;
  227.         break;
  228.     case ';':
  229.         *Type = TERMINATE_RECORD_TYPE;
  230.         break;
  231.     default:
  232.         *Type = UNDEFINED_RECORD_TYPE;
  233.         _GifError = D_GIF_ERR_WrongRecord;
  234.         return ERROR;
  235.     }
  236.  
  237.     return OK;
  238. }
  239.  
  240. /******************************************************************************
  241. *   This routine should be called before any attemp to read an image.         *
  242. *   Note it is assumed the Image desc. header (',') has been read.          *
  243. ******************************************************************************/
  244. int DGifGetImageDesc(GifFileType *GifFile)
  245. {
  246.     int Size, i;
  247.     ByteType Buf[3];
  248.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  249.  
  250.     if (!IS_READABLE(Private)) {
  251.     /* This file was NOT open for reading: */
  252.     _GifError = D_GIF_ERR_NotReadable;
  253.     return ERROR;
  254.     }
  255.  
  256.     if (DGifGetWord(Private -> File, &GifFile -> ILeft) == ERROR ||
  257.     DGifGetWord(Private -> File, &GifFile -> ITop) == ERROR ||
  258.     DGifGetWord(Private -> File, &GifFile -> IWidth) == ERROR ||
  259.     DGifGetWord(Private -> File, &GifFile -> IHeight) == ERROR)
  260.     return ERROR;
  261.     if (fread(Buf, 1, 1, Private -> File) != 1) {
  262.     _GifError = D_GIF_ERR_ReadFailed;
  263.     return ERROR;
  264.     }
  265.     GifFile -> IBitsPerPixel = (Buf[0] & 0x07) + 1;
  266.     GifFile -> IInterlace = (Buf[0] & 0x40);
  267.     if (Buf[0] & 0x80) {        /* Does this image have local color map? */
  268.     Size = (1 << GifFile -> IBitsPerPixel);
  269.     if (GifFile -> IColorMap) free((char *) GifFile -> IColorMap);
  270.     GifFile -> IColorMap =
  271.         (GifColorType *) malloc(sizeof(GifColorType) * Size);
  272.     for (i=0; i<Size; i++) {       /* Get the image local color map: */
  273.         if (fread(Buf, 1, 3, Private -> File) != 3) {
  274.         _GifError = D_GIF_ERR_ReadFailed;
  275.         return ERROR;
  276.         }
  277.         GifFile -> IColorMap[i].Red = Buf[0];
  278.         GifFile -> IColorMap[i].Green = Buf[1];
  279.         GifFile -> IColorMap[i].Blue = Buf[2];
  280.     }
  281.     }
  282.  
  283.     Private -> PixelCount = (long) GifFile -> IWidth *
  284.                 (long) GifFile -> IHeight;
  285.  
  286.     DGifSetupDecompress(GifFile);   /* Reset decompress algorithm parameters */
  287.  
  288.     return OK;
  289. }
  290.  
  291. /******************************************************************************
  292. *  Get one full scanned line (Line) of length LineLen from GIF file.          *
  293. ******************************************************************************/
  294. int DGifGetLine(GifFileType *GifFile, PixelType *Line, int LineLen)
  295. {
  296.     ByteType *Dummy;
  297.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  298.  
  299.     if (!IS_READABLE(Private)) {
  300.     /* This file was NOT open for reading: */
  301.     _GifError = D_GIF_ERR_NotReadable;
  302.     return ERROR;
  303.     }
  304.  
  305.     if (!LineLen) LineLen = GifFile -> IWidth;
  306.     if ((Private -> PixelCount -= LineLen) < 0) {
  307.     _GifError = D_GIF_ERR_DataTooBig;
  308.     return ERROR;
  309.     }
  310.  
  311.     if (DGifDecompressLine(GifFile, Line, LineLen) == OK) {
  312.     if (Private -> PixelCount == 0) {
  313.         /* We probably would not be called any more, so lets clean          */
  314.         /* everything before we return: need to flush out all rest of    */
  315.         /* image until empty block (size 0) detected. We use GetCodeNext */
  316.         do if (DGifGetCodeNext(GifFile, &Dummy) == ERROR) return ERROR;
  317.         while (Dummy != NULL);
  318.     }
  319.     return OK;
  320.     }
  321.     else return ERROR;
  322. }
  323.  
  324. /******************************************************************************
  325. * Put one pixel (Pixel) into GIF file.                          *
  326. ******************************************************************************/
  327. int DGifGetPixel(GifFileType *GifFile, PixelType Pixel)
  328. {
  329.     ByteType *Dummy;
  330.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  331.  
  332.     if (!IS_READABLE(Private)) {
  333.     /* This file was NOT open for reading: */
  334.     _GifError = D_GIF_ERR_NotReadable;
  335.     return ERROR;
  336.     }
  337.  
  338.     if (--Private -> PixelCount < 0)
  339.     {
  340.     _GifError = D_GIF_ERR_DataTooBig;
  341.     return ERROR;
  342.     }
  343.  
  344.     if (DGifDecompressLine(GifFile, &Pixel, 1) == OK) {
  345.     if (Private -> PixelCount == 0) {
  346.         /* We probably would not be called any more, so lets clean          */
  347.         /* everything before we return: need to flush out all rest of    */
  348.         /* image until empty block (size 0) detected. We use GetCodeNext */
  349.         do if (DGifGetCodeNext(GifFile, &Dummy) == ERROR) return ERROR;
  350.         while (Dummy != NULL);
  351.     }
  352.     return OK;
  353.     }
  354.     else return ERROR;
  355. }
  356.  
  357. /******************************************************************************
  358. *   Get an extension block (see GIF manual) from gif file. This routine only  *
  359. * returns the first data block, and DGifGetExtensionNext shouldbe called      *
  360. * after this one until NULL extension is returned.                  *
  361. *   The Extension should NOT be freed by the user (not dynamically allocated).*
  362. *   Note it is assumed the Extension desc. header ('!') has been read.          *
  363. ******************************************************************************/
  364. int DGifGetExtension(GifFileType *GifFile, int *ExtCode, ByteType **Extension)
  365. {
  366.     ByteType Buf;
  367.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  368.  
  369.     if (!IS_READABLE(Private)) {
  370.     /* This file was NOT open for reading: */
  371.     _GifError = D_GIF_ERR_NotReadable;
  372.     return ERROR;
  373.     }
  374.  
  375.     if (fread(&Buf, 1, 1, Private -> File) != 1) {
  376.     _GifError = D_GIF_ERR_ReadFailed;
  377.     return ERROR;
  378.     }
  379.     *ExtCode = Buf;
  380.  
  381.     return DGifGetExtensionNext(GifFile, Extension);
  382. }
  383.  
  384. /******************************************************************************
  385. *   Get a following extension block (see GIF manual) from gif file. This      *
  386. * routine sould be called until NULL Extension is returned.              *
  387. *   The Extension should NOT be freed by the user (not dynamically allocated).*
  388. ******************************************************************************/
  389. int DGifGetExtensionNext(GifFileType *GifFile, ByteType **Extension)
  390. {
  391.     ByteType Buf;
  392.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  393.  
  394.     if (fread(&Buf, 1, 1, Private -> File) != 1) {
  395.     _GifError = D_GIF_ERR_ReadFailed;
  396.     return ERROR;
  397.     }
  398.     if (Buf > 0) {
  399.     *Extension = Private -> Buf;            /* Use private unused buffer */
  400.     (*Extension)[0] = Buf; /* Pascal strings notation (pos. 0 is length) */
  401.     if (fread(&((*Extension)[1]), 1, Buf, Private -> File) != Buf) {
  402.         _GifError = D_GIF_ERR_ReadFailed;
  403.         return ERROR;
  404.     }
  405.     }
  406.     else *Extension = NULL;
  407.  
  408.     return OK;
  409. }
  410.  
  411. /******************************************************************************
  412. *   This routine should be called last, to close GIF file.              *
  413. ******************************************************************************/
  414. int DGifCloseFile(GifFileType *GifFile)
  415. {
  416.     GifFilePrivateType *Private;
  417.     FILE *File;
  418.  
  419.     if (GifFile == NULL) return ERROR;
  420.  
  421.     Private = (GifFilePrivateType *) GifFile -> Private;
  422.  
  423.     if (!IS_READABLE(Private)) {
  424.     /* This file was NOT open for reading: */
  425.     _GifError = D_GIF_ERR_NotReadable;
  426.     return ERROR;
  427.     }
  428.  
  429.     File = Private -> File;
  430.  
  431.     if (GifFile -> IColorMap) free((char *) GifFile -> IColorMap);
  432.     if (GifFile -> SColorMap) free((char *) GifFile -> SColorMap);
  433.     if (Private) free((char *) Private);
  434.     free(GifFile);
  435.  
  436.     if (fclose(File) != 0) {
  437.     _GifError = D_GIF_ERR_CloseFailed;
  438.     return ERROR;
  439.     }
  440.     return OK;
  441. }
  442.  
  443. /******************************************************************************
  444. *   Get 2 bytes (word) from the given file:                      *
  445. ******************************************************************************/
  446. static int DGifGetWord(FILE *File, int *Word)
  447. {
  448.     unsigned char c[2];
  449.  
  450.     if (fread(c, 1, 2, File) != 2) {
  451.     _GifError = D_GIF_ERR_ReadFailed;
  452.     return ERROR;
  453.     }
  454.  
  455.     *Word = (((unsigned int) c[1]) << 8) + c[0];
  456.     return OK;
  457. }
  458.  
  459. /******************************************************************************
  460. *   Get the image code in compressed form. his routine can be called if the   *
  461. * information needed to be piped out as is. Obviously this is much faster     *
  462. * than decoding and encoding again. This routine should be followed by calls  *
  463. * to DGifGetCodeNext, until NULL block is returned.                  *
  464. *   The block should NOT be freed by the user (not dynamically allocated).    *
  465. ******************************************************************************/
  466. int DGifGetCode(GifFileType *GifFile, int *CodeSize, ByteType **CodeBlock)
  467. {
  468.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  469.  
  470.     if (!IS_READABLE(Private)) {
  471.     /* This file was NOT open for reading: */
  472.     _GifError = D_GIF_ERR_NotReadable;
  473.     return ERROR;
  474.     }
  475.  
  476.     *CodeSize = Private -> BitsPerPixel;
  477.  
  478.     return DGifGetCodeNext(GifFile, CodeBlock);
  479. }
  480.  
  481. /******************************************************************************
  482. *   Continue to get the image code in compressed form. This routine should be *
  483. * called until NULL block is returned.                          *
  484. *   The block should NOT be freed by the user (not dynamically allocated).    *
  485. ******************************************************************************/
  486. int DGifGetCodeNext(GifFileType *GifFile, ByteType **CodeBlock)
  487. {
  488.     ByteType Buf;
  489.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  490.  
  491.     if (fread(&Buf, 1, 1, Private -> File) != 1) {
  492.     _GifError = D_GIF_ERR_ReadFailed;
  493.     return ERROR;
  494.     }
  495.  
  496.     if (Buf > 0) {
  497.     *CodeBlock = Private -> Buf;        /* Use private unused buffer */
  498.     (*CodeBlock)[0] = Buf; /* Pascal strings notation (pos. 0 is length) */
  499.     if (fread(&((*CodeBlock)[1]), 1, Buf, Private -> File) != Buf) {
  500.         _GifError = D_GIF_ERR_ReadFailed;
  501.         return ERROR;
  502.     }
  503.     }
  504.     else {
  505.     *CodeBlock = NULL;
  506.     Private -> Buf[0] = 0;           /* Make sure the buffer is empty! */
  507.     Private -> PixelCount = 0;    /* And local info. indicate image read */
  508.     }
  509.  
  510.     return OK;
  511. }
  512.  
  513. /******************************************************************************
  514. *   Setup the LZ decompression for this image:                      *
  515. ******************************************************************************/
  516. static int DGifSetupDecompress(GifFileType *GifFile)
  517. {
  518.     int i, BitsPerPixel;
  519.     ByteType CodeSize;
  520.     unsigned int *Prefix;
  521.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  522.  
  523.     fread(&CodeSize, 1, 1, Private -> File);     /* Read Code size from file */
  524.     BitsPerPixel = CodeSize;
  525.  
  526.     Private -> Buf[0] = 0;                   /* Input Buffer empty */
  527.     Private -> BitsPerPixel = BitsPerPixel;
  528.     Private -> ClearCode = (1 << BitsPerPixel);
  529.     Private -> EOFCode = Private -> ClearCode + 1;
  530.     Private -> RunningCode = Private -> EOFCode + 1;
  531.     Private -> RunningBits = BitsPerPixel + 1;      /* Number of bits per code */
  532.     Private -> MaxCode1 = 1 << Private -> RunningBits;      /* Max. code + 1 */
  533.     Private -> StackPtr = 0;             /* No pixels on the pixel stack */
  534.     Private -> LastCode = NO_SUCH_CODE;
  535.     Private -> CrntShiftState = 0;     /* No information in CrntShiftDWord */
  536.     Private -> CrntShiftDWord = 0;
  537.  
  538.     Prefix = Private -> Prefix;
  539.     for (i=0; i<LZ_MAX_CODE; i++) Prefix[i] = NO_SUCH_CODE;
  540.  
  541.     return OK;
  542. }
  543.  
  544. /******************************************************************************
  545. *   The LZ decompression routine:                          *
  546. *   This version decompress the given gif file into Line of length LineLen.   *
  547. *   This routine can be called few times (one per scan line, for example), in *
  548. * order the complete the whole image.                          *
  549. ******************************************************************************/
  550. static int DGifDecompressLine(GifFileType *GifFile, PixelType *Line, int LineLen)
  551. {
  552.     int i = 0, j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr;
  553.     ByteType *Stack, *Suffix;
  554.     unsigned int *Prefix;
  555.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  556.  
  557.     StackPtr = Private -> StackPtr;
  558.     Prefix = Private -> Prefix;
  559.     Suffix = Private -> Suffix;
  560.     Stack = Private -> Stack;
  561.     EOFCode = Private -> EOFCode;
  562.     ClearCode = Private -> ClearCode;
  563.     LastCode = Private -> LastCode;
  564.  
  565.     if (StackPtr != 0) {
  566.     /* Let pop the stack off before continueing to read the gif file: */
  567.     while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr];
  568.     }
  569.  
  570.     while (i < LineLen) {                /* Decode LineLen items. */
  571.     if (DGifDecompressInput(Private, &CrntCode) == ERROR) return ERROR;
  572.  
  573.     if (CrntCode == EOFCode) {
  574.         /* Note however that usually we will not be here as we will stop */
  575.         /* decoding as soon as we got all the pixel, or EOF code will    */
  576.         /* not be read at all, and DGifGetLine/Pixel clean everything.   */
  577.         if (i != LineLen - 1 || Private -> PixelCount != 0) {
  578.         _GifError = D_GIF_ERR_EOFTooSoon;
  579.         return ERROR;
  580.         }
  581.         i++;
  582.     }
  583.     else
  584.     if (CrntCode == ClearCode) {
  585.         /* We need to start over again: */
  586.         for (j=0; j<LZ_MAX_CODE; j++) Prefix[j] = NO_SUCH_CODE;
  587.         Private -> RunningCode = Private -> EOFCode + 1;
  588.         Private -> RunningBits = Private -> BitsPerPixel + 1;
  589.         Private -> MaxCode1 = 1 << Private -> RunningBits;
  590.         LastCode = Private -> LastCode = NO_SUCH_CODE;
  591.     }
  592.     else {
  593.         /* Its regular code - if in pixel range simply add it to output  */
  594.         /* stream, otherwise trace to codes linked list until the prefix */
  595.         /* is in pixel range:                         */
  596.         if (CrntCode < ClearCode) {
  597.         /* This is simple - its pixel scalar, so add it to output:   */
  598.         Line[i++] = CrntCode;
  599.         }
  600.         else {
  601.         /* Its a code to needed to be traced: trace the linked list  */
  602.         /* until the prefix is a pixel, while pushing the suffix     */
  603.         /* pixels on our stack. If we done, pop the stack in reverse */
  604.         /* (thats what stack is good for!) order to output.         */
  605.         if (Prefix[CrntCode] == NO_SUCH_CODE) {
  606.             /* Only allowed if CrntCode is exactly the running code: */
  607.             /* In that case CrntCode = XXXCode, CrntCode or the         */
  608.             /* prefix code is last code and the suffix char is         */
  609.             /* exactly the prefix of last code!                 */
  610.             if (CrntCode == Private -> RunningCode - 2) {
  611.             CrntPrefix = LastCode;
  612.             Suffix[Private -> RunningCode - 2] =
  613.             Stack[StackPtr++] = DGifGetPrefixChar(Prefix,
  614.                             LastCode, ClearCode);
  615.             }
  616.             else {
  617.             _GifError = D_GIF_ERR_ImageDefect;
  618.             return ERROR;
  619.             }
  620.         }
  621.         else CrntPrefix = CrntCode;
  622.  
  623.         /* Now (if image is O.K.) we should not get and NO_SUCH_CODE */
  624.         /* During the trace. As we might loop forever, in case of    */
  625.         /* defective image, we count the number of loops we trace    */
  626.         /* and stop if we got LZ_MAX_CODE. obviously we can not      */
  627.         /* loop more than that.                         */
  628.         j = 0;
  629.         while (j++ <= LZ_MAX_CODE &&
  630.                CrntPrefix > ClearCode &&
  631.                CrntPrefix <= LZ_MAX_CODE) {
  632.             Stack[StackPtr++] =    Suffix[CrntPrefix];
  633.             CrntPrefix = Prefix[CrntPrefix];
  634.         }
  635.         if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) {
  636.             _GifError = D_GIF_ERR_ImageDefect;
  637.             return ERROR;
  638.         }
  639.         /* Push the last character on stack: */
  640.         Stack[StackPtr++] = CrntPrefix;
  641.  
  642.         /* Now lets pop all the stack into output: */
  643.         while (StackPtr != 0 && i < LineLen)
  644.             Line[i++] = Stack[--StackPtr];
  645.         }
  646.         if (LastCode != NO_SUCH_CODE) {
  647.         Prefix[Private -> RunningCode - 2] = LastCode;
  648.  
  649.         if (CrntCode == Private -> RunningCode - 2) {
  650.             /* Only allowed if CrntCode is exactly the running code: */
  651.             /* In that case CrntCode = XXXCode, CrntCode or the         */
  652.             /* prefix code is last code and the suffix char is         */
  653.             /* exactly the prefix of last code!                 */
  654.             Suffix[Private -> RunningCode - 2] =
  655.             DGifGetPrefixChar(Prefix, LastCode, ClearCode);
  656.         }
  657.         else {
  658.             Suffix[Private -> RunningCode - 2] =
  659.             DGifGetPrefixChar(Prefix, CrntCode, ClearCode);
  660.         }
  661.         }
  662.         LastCode = CrntCode;
  663.     }
  664.     }
  665.  
  666.     Private -> LastCode = LastCode;
  667.     Private -> StackPtr = StackPtr;
  668.  
  669.     return OK;
  670. }
  671.  
  672. /******************************************************************************
  673. * Routine to trace the Prefixes linked list until we get a prefix which is    *
  674. * not code, but a pixel value (less than ClearCode). Returns that pixel value.*
  675. * If image is defective, we might loop here forever, so we limit the loops to *
  676. * the maximum possible if image O.k. - LZ_MAX_CODE times.              *
  677. ******************************************************************************/
  678. static int DGifGetPrefixChar(unsigned int *Prefix, int Code, int ClearCode)
  679. {
  680.     int i = 0;
  681.  
  682.     while (Code > ClearCode && i++ <= LZ_MAX_CODE) Code = Prefix[Code];
  683.     return Code;
  684. }
  685.  
  686. /******************************************************************************
  687. *   Interface for accessing the LZ codes directly. Set Code to the real code  *
  688. * (12bits), or to -1 if EOF code is returned.                      *
  689. ******************************************************************************/
  690. int DGifGetLZCodes(GifFileType *GifFile, int *Code)
  691. {
  692.     ByteType *CodeBlock;
  693.     GifFilePrivateType *Private = (GifFilePrivateType *) GifFile -> Private;
  694.  
  695.     if (!IS_READABLE(Private)) {
  696.     /* This file was NOT open for reading: */
  697.     _GifError = D_GIF_ERR_NotReadable;
  698.     return ERROR;
  699.     }
  700.  
  701.     if (DGifDecompressInput(Private, Code) == ERROR) return ERROR;
  702.  
  703.     if (*Code == Private -> EOFCode) {
  704.     /* Skip rest of codes (hopefully only NULL terminating block): */
  705.     do if (DGifGetCodeNext(GifFile, &CodeBlock) == ERROR) return ERROR;
  706.     while (CodeBlock != NULL);
  707.  
  708.     *Code = -1;
  709.     }
  710.     else
  711.     if (*Code == Private -> ClearCode) {
  712.     /* We need to start over again: */
  713.     Private -> RunningCode = Private -> EOFCode + 1;
  714.     Private -> RunningBits = Private -> BitsPerPixel + 1;
  715.     Private -> MaxCode1 = 1 << Private -> RunningBits;
  716.     }
  717.  
  718.     return OK;
  719. }
  720.  
  721. /******************************************************************************
  722. *   The LZ decompression input routine:                          *
  723. *   This routine is responsable for the decompression of the bit stream from  *
  724. * 8 bits (bytes) packets, into the real codes.                      *
  725. *   Returns OK if read succesfully.                          *
  726. ******************************************************************************/
  727. static int DGifDecompressInput(GifFilePrivateType *Private, int *Code)
  728. {
  729.     ByteType NextByte;
  730.     static unsigned int CodeMasks[] = {
  731.     0x0000, 0x0001, 0x0003, 0x0007,
  732.     0x000f, 0x001f, 0x003f, 0x007f,
  733.     0x00ff, 0x01ff, 0x03ff, 0x07ff,
  734.     0x0fff
  735.     };
  736.  
  737.     while (Private -> CrntShiftState < Private -> RunningBits) {
  738.     /* Needs to get more bytes from input stream for next code: */
  739.     if (DGifBufferedInput(Private -> File, Private -> Buf, &NextByte)
  740.         == ERROR) {
  741.         return ERROR;
  742.     }
  743.     Private -> CrntShiftDWord |=
  744.         ((unsigned long) NextByte) << Private -> CrntShiftState;
  745.     Private -> CrntShiftState += 8;
  746.     }
  747.     *Code = Private -> CrntShiftDWord & CodeMasks[Private -> RunningBits];
  748.  
  749.     Private -> CrntShiftDWord >>= Private -> RunningBits;
  750.     Private -> CrntShiftState -= Private -> RunningBits;
  751.  
  752.     /* If code cannt fit into RunningBits bits, must raise its size. Note */
  753.     /* however that codes above 4095 are used for special signaling.      */
  754.     if (++Private -> RunningCode > Private -> MaxCode1 &&
  755.     Private -> RunningBits < LZ_BITS) {
  756.     Private -> MaxCode1 <<= 1;
  757.     Private -> RunningBits++;
  758.     }
  759.     return OK;
  760. }
  761.  
  762. /******************************************************************************
  763. *   This routines read one gif data block at a time and buffers it internally *
  764. * so that the decompression routine could access it.                  *
  765. *   The routine returns the next byte from its internal buffer (or read next  *
  766. * block in if buffer empty) and returns OK if succesful.              *
  767. ******************************************************************************/
  768. static int DGifBufferedInput(FILE *File, ByteType *Buf, ByteType *NextByte)
  769. {
  770.     if (Buf[0] == 0) {
  771.     /* Needs to read the next buffer - this one is empty: */
  772.     if (fread(Buf, 1, 1, File) != 1)
  773.     {
  774.         _GifError = D_GIF_ERR_ReadFailed;
  775.         return ERROR;
  776.     }
  777.     if (fread(&Buf[1], 1, Buf[0], File) != Buf[0])
  778.     {
  779.         _GifError = D_GIF_ERR_ReadFailed;
  780.         return ERROR;
  781.     }
  782.     *NextByte = Buf[1];
  783.     Buf[1] = 2;       /* We use now the second place as last char read! */
  784.     Buf[0]--;
  785.     }
  786.     else {
  787.     *NextByte = Buf[Buf[1]++];
  788.     Buf[0]--;
  789.     }
  790.  
  791.     return OK;
  792. }
  793.