home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / library / dos / grafik / giflib11 / lib / dgif_lib.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-09-06  |  29.5 KB  |  829 lines

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