home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume5 / pbm3 / part4 / giftopbm.c < prev    next >
C/C++ Source or Header  |  1989-02-03  |  13KB  |  461 lines

  1. /*-
  2.  * gif2ras.c - Converts from a Compuserve GIF (tm) image to a Sun Raster image.
  3.  *
  4.  * Copyright (c) 1988 by Patrick J. Naughton
  5.  *
  6.  * Author: Patrick J. Naughton
  7.  * naughton@wind.sun.com
  8.  *
  9.  * Permission to use, copy, modify, and distribute this software and its
  10.  * documentation for any purpose and without fee is hereby granted,
  11.  * provided that the above copyright notice appear in all copies and that
  12.  * both that copyright notice and this permission notice appear in
  13.  * supporting documentation.
  14.  *
  15.  * This file is provided AS IS with no warranties of any kind.  The author
  16.  * shall have no liability with respect to the infringement of copyrights,
  17.  * trade secrets or any patents by this file or any part thereof.  In no
  18.  * event will the author be liable for any lost revenue or profits or
  19.  * other special, indirect and consequential damages.
  20.  *
  21.  * Comments and additions should be sent to the author:
  22.  *
  23.  *                     Patrick J. Naughton
  24.  *                     Sun Microsystems, Inc.
  25.  *                     2550 Garcia Ave, MS 14-40
  26.  *                     Mountain View, CA 94043
  27.  *                     (415) 336-1080
  28.  *
  29.  * Revision History:
  30.  * 28-Aug-88: Modified by Jef Poskanzer to output PBM instead of Sun raster.
  31.  * 27-Jul-88: Updated to use libpixrect to fix 386i byteswapping problems.
  32.  * 11-Apr-88: Converted to C and changed to write Sun rasterfiles.
  33.  * 19-Jan-88: GIFSLOW.PAS posted to comp.graphics by Jim Briebel,
  34.  *            a Turbo Pascal 4.0 program to painfully slowly display
  35.  *            GIF images on an EGA equipped IBM-PC.
  36.  *
  37.  * Description:
  38.  *   This program takes a Compuserve "Graphics Interchange Format" or "GIF"
  39.  * file as input and writes a file known as a Sun rasterfile.  This datafile
  40.  * can be loaded by the NeWS "readcanvas" operator and is of the same format
  41.  * as the files in /usr/NeWS/smi/*.  Under X11R2 there is a program called
  42.  * xraster to display these files.
  43.  *
  44.  * Portability:
  45.  *   To make this program convert to some image format other than PBM
  46.  * format simply seach for the tag "PBMS:" in the source and
  47.  * replace these simple mechanisms with the appropriate ones for the
  48.  * other output format.  I have marked all (six) PBM Specific pieces
  49.  * of code with this comment.
  50.  *
  51.  * SS: compile with "cc -o gif2ras -O gif2ras.c -lpixrect"
  52.  * PBMS: compile with "cc -o giftopbm -O giftopbm.c libpbm.a
  53.  */
  54.  
  55. #include <stdio.h>
  56. #ifdef notdefSS
  57. #include <pixrect/pixrect_hs.h> /* SS: main Pixrect header file */
  58. #endif notdefSS
  59. #include <sys/types.h>
  60. #include "pbm.h"        /* PBMS: main PBM header file */
  61.  
  62. typedef int boolean;
  63. #define True (1)
  64. #define False (0)
  65.  
  66. #define NEXTSHORT (*ptr++ + (0x100 * *ptr++))
  67. #define NEXTBYTE (*ptr++)
  68. #define IMAGESEP 0x2c
  69. #define INTERLACEMASK 0x40
  70. #define COLORMAPMASK 0x80
  71.  
  72. int BitOffset = 0,        /* Bit Offset of next code */
  73.     XC = 0, YC = 0,        /* Output X and Y coords of current pixel */
  74.     Pass = 0,            /* Used by output routine if interlaced pic */
  75.     OutCount = 0,        /* Decompressor output 'stack count' */
  76.     RWidth, RHeight,        /* screen dimensions */
  77.     Width, Height,        /* image dimensions */
  78.     LeftOfs, TopOfs,        /* image offset */
  79.     BitsPerPixel,        /* Bits per pixel, read from GIF header */
  80.     ColorMapSize,        /* number of colors */
  81.     CodeSize,            /* Code size, read from GIF header */
  82.     InitCodeSize,        /* Starting code size, used during Clear */
  83.     Code,            /* Value returned by ReadCode */
  84.     MaxCode,            /* limiting value for current code size */
  85.     ClearCode,            /* GIF clear code */
  86.     EOFCode,            /* GIF end-of-information code */
  87.     CurCode, OldCode, InCode,    /* Decompressor variables */
  88.     FirstFree,            /* First free code, generated per GIF spec */
  89.     FreeCode,            /* Decompressor, next free slot in hash table */
  90.     FinChar,            /* Decompressor variable */
  91.     BitMask,            /* AND mask for data size */
  92.     ReadMask;            /* Code AND mask for current code size */
  93.  
  94. boolean Interlace, HasColormap;
  95.  
  96. #ifdef notdefSS
  97. /* SS: defined in pixrect/pixrect_hs.h */
  98. Pixrect *Output;        /* The Sun Pixrect */
  99. colormap_t Colormap;        /* The Pixrect Colormap */
  100. u_char *Image;            /* The result array */
  101. #endif notdefSS
  102. /* PBMS: defined in pbm.h */
  103. bit **bits;            /* The PBM bit array */
  104.  
  105. u_char *RawGIF;            /* The heap array to hold it, raw */
  106. u_char *Raster;            /* The raster data stream, unblocked */
  107.  
  108.     /* The hash table used by the decompressor */
  109. int Prefix[4096];
  110. int Suffix[4096];
  111.  
  112.     /* An output array used by the decompressor */
  113. int OutCode[1025];
  114.  
  115.     /* The color map, read from the GIF header */
  116. u_char Red[256], Green[256], Blue[256];
  117.  
  118. char *id = "GIF87a";
  119.  
  120. char *pname;            /* program name (used for error messages) */
  121.  
  122. void
  123. error(s1, s2)
  124. char *s1, *s2;
  125. {
  126.     fprintf(stderr, s1, pname, s2);
  127.     exit(1);
  128. }
  129.  
  130.  
  131. main(argc, argv)
  132. int argc;
  133. char *argv[];
  134. {
  135. FILE *fp;
  136. char *infname = argv[1];
  137. char *outfname = argv[2];
  138. int filesize;
  139. register u_char ch, ch1;
  140. register u_char *ptr, *ptr1;
  141. register int i;
  142.  
  143.     setbuf(stderr, NULL);
  144.     pname = argv[0];
  145.  
  146.     if (argc < 3)
  147.     error("usage: %s GIFfile rasterfile\n", NULL);
  148.  
  149.     if (!(fp = fopen(infname, "r")))
  150.     error("%s: %s not found.\n", infname);
  151.  
  152.     /* find the size of the file */
  153.  
  154.     fseek(fp, 0L, 2);
  155.     filesize = ftell(fp);
  156.     fseek(fp, 0L, 0);
  157.  
  158.     if (!(ptr = RawGIF = (u_char *) malloc(filesize)))
  159.     error("%s: not enough memory to read gif file.\n", NULL);
  160.  
  161.     if (!(Raster = (u_char *) malloc(filesize)))
  162.     error("%s: not enough memory to read gif file.\n", NULL);
  163.  
  164.     fread(ptr, filesize, 1, fp);
  165.  
  166.     if (strncmp(ptr, id, 6))
  167.     error("%s: %s is not a GIF file.\n", infname);
  168.     ptr += 6;
  169.  
  170. /* Get variables from the GIF screen descriptor */
  171.  
  172.     RWidth = NEXTSHORT;        /* screen dimensions... not used. */
  173.     RHeight = NEXTSHORT;
  174.  
  175.     ch = NEXTBYTE;
  176.     HasColormap = ((ch & COLORMAPMASK) ? True : False);
  177.  
  178.     BitsPerPixel = (ch & 7) + 1;
  179.     ColorMapSize = 1 << BitsPerPixel;
  180.     BitMask = ColorMapSize - 1;
  181.  
  182.     ch = NEXTBYTE;        /* background color... not used. */
  183.  
  184.     if (NEXTBYTE)        /* supposed to be NULL */
  185.     error("%s: %s is a corrupt GIF file.\n", infname);
  186.  
  187. /* Read in global colormap. */
  188.  
  189.     if (HasColormap) {
  190.     fprintf(stderr, "%s is %d bits per pixel, (%d colors).\n",
  191.         infname, BitsPerPixel, ColorMapSize);
  192.     for (i = 0; i < ColorMapSize; i++) {
  193.         Red[i] = NEXTBYTE;
  194.         Green[i] = NEXTBYTE;
  195.         Blue[i] = NEXTBYTE;
  196.     }
  197.  
  198. #ifdef notdefSS
  199. /* SS: Fill in the Pixrect colormap struct */
  200.     Colormap.type = RMT_EQUAL_RGB;
  201.     Colormap.length = ColorMapSize;
  202.     Colormap.map[0] = Red;
  203.     Colormap.map[1] = Green;
  204.     Colormap.map[2] = Blue;
  205. #endif notdefSS
  206.     /* PBMS: PBM only handles bitmaps.  Reject any pixmaps here. */
  207.     if (BitsPerPixel != 1)
  208.         error("%s: %s has more than one bit per pixel - it's not a bitmap.\n", infname);
  209.     }
  210.     else error("%s: %s does not have a colormap.\n", infname);
  211.  
  212.  
  213. /* Check for image seperator */
  214.  
  215.     if (NEXTBYTE != IMAGESEP)
  216.     error("%s: %s is a corrupt GIF file.\n", infname);
  217.  
  218. /* Now read in values from the image descriptor */
  219.  
  220.     LeftOfs = NEXTSHORT;
  221.     TopOfs = NEXTSHORT;
  222.     Width = NEXTSHORT;
  223.     Height = NEXTSHORT;
  224.     Interlace = ((NEXTBYTE & INTERLACEMASK) ? True : False);
  225.  
  226.     fprintf(stderr, "Reading a %d by %d %sinterlaced image...",
  227.         Width, Height, (Interlace) ? "" : "non-");
  228.     
  229.  
  230. /* Note that I ignore the possible existence of a local color map.
  231.  * I'm told there aren't many files around that use them, and the spec
  232.  * says it's defined for future use.  This could lead to an error
  233.  * reading some files. 
  234.  */
  235.  
  236. /* Start reading the raster data. First we get the intial code size
  237.  * and compute decompressor constant values, based on this code size.
  238.  */
  239.  
  240.     CodeSize = NEXTBYTE;
  241.     ClearCode = (1 << CodeSize);
  242.     EOFCode = ClearCode + 1;
  243.     FreeCode = FirstFree = ClearCode + 2;
  244.  
  245. /* The GIF spec has it that the code size is the code size used to
  246.  * compute the above values is the code size given in the file, but the
  247.  * code size used in compression/decompression is the code size given in
  248.  * the file plus one. (thus the ++).
  249.  */
  250.  
  251.     CodeSize++;
  252.     InitCodeSize = CodeSize;
  253.     MaxCode = (1 << CodeSize);
  254.     ReadMask = MaxCode - 1;
  255.  
  256. /* Read the raster data.  Here we just transpose it from the GIF array
  257.  * to the Raster array, turning it from a series of blocks into one long
  258.  * data stream, which makes life much easier for ReadCode().
  259.  */
  260.  
  261.     ptr1 = Raster;
  262.     do {
  263.     ch = ch1 = NEXTBYTE;
  264.     while (ch--) *ptr1++ = NEXTBYTE;
  265.     } while(ch1);
  266.  
  267.     free(RawGIF);        /* We're done with the raw data now... */
  268.  
  269.     fprintf(stderr, "done.\n");
  270.     fprintf(stderr, "Decompressing...");
  271.  
  272.  
  273. #ifdef notdefSS
  274. /* SS: Allocate the Sun Pixrect and make "Image" point to the image data. */
  275.     Output = mem_create(Width, Height, 8);
  276.     if (Output == (Pixrect *) NULL)
  277.     error("%s: not enough memory for output data.\n", NULL);
  278.     Image = (u_char *) mpr_d(Output)->md_image;
  279. #endif notdefSS
  280. /* PBMS: Allocate the PBM bit array. */
  281.     bits = pbm_allocarray(Width, Height);
  282.  
  283.  
  284. /* Decompress the file, continuing until you see the GIF EOF code.
  285.  * One obvious enhancement is to add checking for corrupt files here.
  286.  */
  287.  
  288.     Code = ReadCode();
  289.     while (Code != EOFCode) {
  290.  
  291. /* Clear code sets everything back to its initial value, then reads the
  292.  * immediately subsequent code as uncompressed data.
  293.  */
  294.  
  295.     if (Code == ClearCode) {
  296.         CodeSize = InitCodeSize;
  297.         MaxCode = (1 << CodeSize);
  298.         ReadMask = MaxCode - 1;
  299.         FreeCode = FirstFree;
  300.         CurCode = OldCode = Code = ReadCode();
  301.         FinChar = CurCode & BitMask;
  302.         AddToPixel(FinChar);
  303.     }
  304.     else {
  305.  
  306. /* If not a clear code, then must be data: save same as CurCode and InCode */
  307.  
  308.         CurCode = InCode = Code;
  309.  
  310. /* If greater or equal to FreeCode, not in the hash table yet;
  311.  * repeat the last character decoded
  312.  */
  313.  
  314.         if (CurCode >= FreeCode) {
  315.         CurCode = OldCode;
  316.         OutCode[OutCount++] = FinChar;
  317.         }
  318.  
  319. /* Unless this code is raw data, pursue the chain pointed to by CurCode
  320.  * through the hash table to its end; each code in the chain puts its
  321.  * associated output code on the output queue.
  322.  */
  323.  
  324.         while (CurCode > BitMask) {
  325.         OutCode[OutCount++] = Suffix[CurCode];
  326.         CurCode = Prefix[CurCode];
  327.         } 
  328.  
  329. /* The last code in the chain is treated as raw data. */
  330.  
  331.         FinChar = CurCode & BitMask;
  332.         OutCode[OutCount++] = FinChar;
  333.  
  334. /* Now we put the data out to the Output routine.
  335.  * It's been stacked LIFO, so deal with it that way...
  336.  */
  337.  
  338.         for (i = OutCount - 1; i >= 0; i--)
  339.         AddToPixel(OutCode[i]);
  340.         OutCount = 0;
  341.  
  342. /* Build the hash table on-the-fly. No table is stored in the file. */
  343.  
  344.         Prefix[FreeCode] = OldCode;
  345.         Suffix[FreeCode] = FinChar;
  346.         OldCode = InCode;
  347.  
  348. /* Point to the next slot in the table.  If we exceed the current
  349.  * MaxCode value, increment the code size unless it's already 12.  If it
  350.  * is, do nothing: the next code decompressed better be CLEAR
  351.  */
  352.  
  353.         FreeCode++;
  354.         if (FreeCode >= MaxCode) {
  355.         if (CodeSize < 12) {
  356.             CodeSize++;
  357.             MaxCode *= 2;
  358.             ReadMask = (1 << CodeSize) - 1;
  359.         }
  360.         }
  361.     }
  362.     Code = ReadCode();
  363.     }
  364.  
  365.     free(Raster);
  366.  
  367.     fprintf(stderr, "done.\n");
  368.  
  369.     if (!(fp = fopen(outfname, "w")))
  370.     error("%s: can't create %s.\n", outfname);
  371.  
  372. #ifdef notdefSS
  373. /* SS: Pixrect Rasterfile output code. */
  374.     fprintf(stderr, "Writing Sun Rasterfile: %s...", outfname);
  375.     if (pr_dump(Output, fp, &Colormap, RT_STANDARD, 0) == PIX_ERR)
  376.     error("%s: error writing Sun Rasterfile: %s\n", outfname);
  377. #endif notdefSS
  378. /* PBMS: PBM output code. */
  379.     pbm_writepbm(stdout, bits, Width, Height);
  380.  
  381.     fclose(fp);
  382.  
  383.     fprintf(stderr, "done.\n");
  384. }
  385.  
  386.  
  387. /* Fetch the next code from the raster data stream.  The codes can be
  388.  * any length from 3 to 12 bits, packed into 8-bit bytes, so we have to
  389.  * maintain our location in the Raster array as a BIT Offset.  We compute
  390.  * the byte Offset into the raster array by dividing this by 8, pick up
  391.  * three bytes, compute the bit Offset into our 24-bit chunk, shift to
  392.  * bring the desired code to the bottom, then mask it off and return it. 
  393.  */
  394. ReadCode()
  395. {
  396. int RawCode, ByteOffset;
  397.  
  398.     ByteOffset = BitOffset / 8;
  399.     RawCode = Raster[ByteOffset] + (0x100 * Raster[ByteOffset + 1]);
  400.     if (CodeSize >= 8)
  401.     RawCode += (0x10000 * Raster[ByteOffset + 2]);
  402.     RawCode >>= (BitOffset % 8);
  403.     BitOffset += CodeSize;
  404.     return(RawCode & ReadMask);
  405. }
  406.  
  407.  
  408. AddToPixel(Index)
  409. u_char Index;
  410. {
  411. #ifdef notdefSS
  412.     *(Image + YC * Width + XC) = Index;
  413. #endif notdefSS
  414. /* PBMS: Store a pixel. */
  415.     bits[YC][XC] = Index;
  416.  
  417. /* Update the X-coordinate, and if it overflows, update the Y-coordinate */
  418.  
  419.     if (++XC == Width) {
  420.  
  421. /* If a non-interlaced picture, just increment YC to the next scan line. 
  422.  * If it's interlaced, deal with the interlace as described in the GIF
  423.  * spec.  Put the decoded scan line out to the screen if we haven't gone
  424.  * past the bottom of it
  425.  */
  426.  
  427.     XC = 0;
  428.     if (!Interlace) YC++;
  429.     else {
  430.         switch (Pass) {
  431.         case 0:
  432.             YC += 8;
  433.             if (YC >= Height) {
  434.             Pass++;
  435.             YC = 4;
  436.             }
  437.         break;
  438.         case 1:
  439.             YC += 8;
  440.             if (YC >= Height) {
  441.             Pass++;
  442.             YC = 2;
  443.             }
  444.         break;
  445.         case 2:
  446.             YC += 4;
  447.             if (YC >= Height) {
  448.             Pass++;
  449.             YC = 1;
  450.             }
  451.         break;
  452.         case 3:
  453.             YC += 2;
  454.         break;
  455.         default:
  456.         break;
  457.         }
  458.     }
  459.     }
  460. }
  461.