home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / mac / source / macgif.shr / macgif.shar
Encoding:
Text File  |  1989-05-21  |  33.9 KB  |  1,227 lines

  1. #! /bin/sh
  2. # This is a shell archive, meaning:
  3. # 1. Remove everything above the #! /bin/sh line.
  4. # 2. Save the resulting text in a file.
  5. # 3. Execute the file with /bin/sh (not csh) to create the files:
  6. #
  7. #    gif2ras.c
  8. #
  9. # This archive created: Fri May 12 20:22:24 1989
  10. # By:    Roger L. Long (bytebug@dhw68k.cts.com)
  11. export PATH; PATH=/bin:$PATH
  12. echo shar: extracting "'gif2ras.c'" '(14611 characters)'
  13. if test -f 'gif2ras.c'
  14. then
  15.     echo shar: will not over-write existing file "'gif2ras.c'"
  16. else
  17. sed 's/^X//' << \SHAR_EOF > 'gif2ras.c'
  18. X/*
  19. X * gif2ras.c - Converts from a Compuserve GIF (tm) image to a Sun Raster image.
  20. X *
  21. X * Copyright (c) 1988 by Patrick J. Naughton
  22. X *
  23. X * Author: Patrick J. Naughton
  24. X * naughton@wind.sun.com
  25. X *
  26. X * Permission to use, copy, modify, and distribute this software and its
  27. X * documentation for any purpose and without fee is hereby granted,
  28. X * provided that the above copyright notice appear in all copies and that
  29. X * both that copyright notice and this permission notice appear in
  30. X * supporting documentation.
  31. X *
  32. X * This file is provided AS IS with no warranties of any kind.  The author
  33. X * shall have no liability with respect to the infringement of copyrights,
  34. X * trade secrets or any patents by this file or any part thereof.  In no
  35. X * event will the author be liable for any lost revenue or profits or
  36. X * other special, indirect and consequential damages.
  37. X *
  38. X * Comments and additions should be sent to the author:
  39. X *
  40. X *                     Patrick J. Naughton
  41. X *                     Sun Microsystems, Inc.
  42. X *                     2550 Garcia Ave, MS 14-40
  43. X *                     Mountain View, CA 94043
  44. X *                     (415) 336-1080
  45. X *
  46. X * Revision History:
  47. X * 28-Aug-88: Modified by Jef Poskanzer to output PBM instead of Sun raster.
  48. X * 27-Jul-88: Updated to use libpixrect to fix 386i byteswapping problems.
  49. X * 11-Apr-88: Converted to C and changed to write Sun rasterfiles.
  50. X * 19-Jan-88: GIFSLOW.PAS posted to comp.graphics by Jim Briebel,
  51. X *            a Turbo Pascal 4.0 program to painfully slowly display
  52. X *            GIF images on an EGA equipped IBM-PC.
  53. X *
  54. X * Description:
  55. X *   This program takes a Compuserve "Graphics Interchange Format" or "GIF"
  56. X * file as input and writes a file known as a Sun rasterfile.  This datafile
  57. X * can be loaded by the NeWS "readcanvas" operator and is of the same format
  58. X * as the files in /usr/NeWS/smi/*.  Under X11R2 there is a program called
  59. X * xraster to display these files.
  60. X *
  61. X * Portability:
  62. X *   To make this program convert to some image format other than PBM
  63. X * format simply seach for the tag "PBMS:" in the source and
  64. X * replace these simple mechanisms with the appropriate ones for the
  65. X * other output format.  I have marked all (six) PBM Specific pieces
  66. X * of code with this comment.
  67. X *
  68. X * SS: compile with "cc -o gif2ras -O gif2ras.c -lpixrect"
  69. X * PBMS: compile with "cc -o giftopbm -O giftopbm.c libpbm.a
  70. X */
  71. X
  72. X#include <stdio.h>
  73. X#ifdef notdefSS
  74. X#include <pixrect/pixrect_hs.h> /* SS: main Pixrect header file */
  75. X#endif notdefSS
  76. X#include <sys/types.h>
  77. X#include "pbm.h"                /* PBMS: main PBM header file */
  78. X
  79. Xtypedef int boolean;
  80. X#define True (1)
  81. X#define False (0)
  82. X
  83. X#define NEXTSHORT (*ptr++ + (0x100 * *ptr++))
  84. X#define NEXTBYTE (*ptr++)
  85. X#define IMAGESEP 0x2c
  86. X#define INTERLACEMASK 0x40
  87. X#define COLORMAPMASK 0x80
  88. X
  89. Xint BitOffset = 0,              /* Bit Offset of next code */
  90. X    XC = 0, YC = 0,             /* Output X and Y coords of current pixel */
  91. X    Pass = 0,                   /* Used by output routine if interlaced pic */
  92. X    OutCount = 0,               /* Decompressor output 'stack count' */
  93. X    RWidth, RHeight,            /* screen dimensions */
  94. X    Width, Height,              /* image dimensions */
  95. X    LeftOfs, TopOfs,            /* image offset */
  96. X    BitsPerPixel,               /* Bits per pixel, read from GIF header */
  97. X    ColorMapSize,               /* number of colors */
  98. X    CodeSize,                   /* Code size, read from GIF header */
  99. X    InitCodeSize,               /* Starting code size, used during Clear */
  100. X    Code,                       /* Value returned by ReadCode */
  101. X    MaxCode,                    /* limiting value for current code size */
  102. X    ClearCode,                  /* GIF clear code */
  103. X    EOFCode,                    /* GIF end-of-information code */
  104. X    CurCode, OldCode, InCode,   /* Decompressor variables */
  105. X    FirstFree,                  /* First free code, generated per GIF spec */
  106. X    FreeCode,                   /* Decompressor, next free slot in hash table */
  107. X    FinChar,                    /* Decompressor variable */
  108. X    BitMask,                    /* AND mask for data size */
  109. X    ReadMask;                   /* Code AND mask for current code size */
  110. X
  111. Xboolean Interlace, HasColormap;
  112. X
  113. X#ifdef notdefSS
  114. X/* SS: defined in pixrect/pixrect_hs.h */
  115. XPixrect *Output;                /* The Sun Pixrect */
  116. Xcolormap_t Colormap;            /* The Pixrect Colormap */
  117. Xu_char *Image;                  /* The result array */
  118. X#endif notdefSS
  119. X/* PBMS: defined in pbm.h */
  120. Xbit **bits;                     /* The PBM bit array */
  121. X
  122. Xu_char *RawGIF;                 /* The heap array to hold it, raw */
  123. Xu_char *Raster;                 /* The raster data stream, unblocked */
  124. X
  125. X    /* The hash table used by the decompressor */
  126. Xint Prefix[4096];
  127. Xint Suffix[4096];
  128. X
  129. X    /* An output array used by the decompressor */
  130. Xint OutCode[1025];
  131. X
  132. X    /* The color map, read from the GIF header */
  133. Xu_char Red[256], Green[256], Blue[256];
  134. X
  135. Xchar *id = "GIF87a";
  136. X
  137. Xchar *pname;                    /* program name (used for error messages) */
  138. X
  139. Xvoid
  140. Xerror(s1, s2)
  141. Xchar *s1, *s2;
  142. X{
  143. X    fprintf(stderr, s1, pname, s2);
  144. X    exit(1);
  145. X}
  146. X
  147. X
  148. Xmain(argc, argv)
  149. Xint argc;
  150. Xchar *argv[];
  151. X{
  152. XFILE *fp;
  153. Xchar *infname = argv[1];
  154. Xchar *outfname = argv[2];
  155. Xint filesize;
  156. Xregister u_char ch, ch1;
  157. Xregister u_char *ptr, *ptr1;
  158. Xregister int i;
  159. X
  160. X    setbuf(stderr, NULL);
  161. X    pname = argv[0];
  162. X
  163. X    if (argc < 3)
  164. X        error("usage: %s GIFfile rasterfile\n", NULL);
  165. X
  166. X    if (!(fp = fopen(infname, "r")))
  167. X        error("%s: %s not found.\n", infname);
  168. X
  169. X    /* find the size of the file */
  170. X
  171. X    fseek(fp, 0L, 2);
  172. X    filesize = ftell(fp);
  173. X    fseek(fp, 0L, 0);
  174. X
  175. X    if (!(ptr = RawGIF = (u_char *) malloc(filesize)))
  176. X        error("%s: not enough memory to read gif file.\n", NULL);
  177. X
  178. X    if (!(Raster = (u_char *) malloc(filesize)))
  179. X        error("%s: not enough memory to read gif file.\n", NULL);
  180. X
  181. X    fread(ptr, filesize, 1, fp);
  182. X
  183. X    if (strncmp(ptr, id, 6))
  184. X        error("%s: %s is not a GIF file.\n", infname);
  185. X    ptr += 6;
  186. X
  187. X/* Get variables from the GIF screen descriptor */
  188. X
  189. X    RWidth = NEXTSHORT;         /* screen dimensions... not used. */
  190. X    RHeight = NEXTSHORT;
  191. X
  192. X    ch = NEXTBYTE;
  193. X    HasColormap = ((ch & COLORMAPMASK) ? True : False);
  194. X
  195. X    BitsPerPixel = (ch & 7) + 1;
  196. X    ColorMapSize = 1 << BitsPerPixel;
  197. X    BitMask = ColorMapSize - 1;
  198. X
  199. X    ch = NEXTBYTE;              /* background color... not used. */
  200. X
  201. X    if (NEXTBYTE)               /* supposed to be NULL */
  202. X        error("%s: %s is a corrupt GIF file.\n", infname);
  203. X
  204. X/* Read in global colormap. */
  205. X
  206. X    if (HasColormap) {
  207. X        fprintf(stderr, "%s is %d bits per pixel, (%d colors).\n",
  208. X                infname, BitsPerPixel, ColorMapSize);
  209. X        for (i = 0; i < ColorMapSize; i++) {
  210. X            Red[i] = NEXTBYTE;
  211. X            Green[i] = NEXTBYTE;
  212. X            Blue[i] = NEXTBYTE;
  213. X        }
  214. X
  215. X#ifdef notdefSS
  216. X/* SS: Fill in the Pixrect colormap struct */
  217. X        Colormap.type = RMT_EQUAL_RGB;
  218. X        Colormap.length = ColorMapSize;
  219. X        Colormap.map[0] = Red;
  220. X        Colormap.map[1] = Green;
  221. X        Colormap.map[2] = Blue;
  222. X#endif notdefSS
  223. X        /* PBMS: PBM only handles bitmaps.  Reject any pixmaps here. */
  224. X        if (BitsPerPixel != 1)
  225. X            error("%s: %s has more than one bit per pixel - it's not a bitmap.\n
  226. X", infname);
  227. X    }
  228. X    else error("%s: %s does not have a colormap.\n", infname);
  229. X
  230. X
  231. X/* Check for image seperator */
  232. X
  233. X    if (NEXTBYTE != IMAGESEP)
  234. X        error("%s: %s is a corrupt GIF file.\n", infname);
  235. X
  236. X/* Now read in values from the image descriptor */
  237. X
  238. X    LeftOfs = NEXTSHORT;
  239. X    TopOfs = NEXTSHORT;
  240. X    Width = NEXTSHORT;
  241. X    Height = NEXTSHORT;
  242. X    Interlace = ((NEXTBYTE & INTERLACEMASK) ? True : False);
  243. X
  244. X    fprintf(stderr, "Reading a %d by %d %sinterlaced image...",
  245. X        Width, Height, (Interlace) ? "" : "non-");
  246. X
  247. X
  248. X/* Note that I ignore the possible existence of a local color map.
  249. X * I'm told there aren't many files around that use them, and the spec
  250. X * says it's defined for future use.  This could lead to an error
  251. X * reading some files.
  252. X */
  253. X
  254. X/* Start reading the raster data. First we get the intial code size
  255. X * and compute decompressor constant values, based on this code size.
  256. X */
  257. X
  258. X    CodeSize = NEXTBYTE;
  259. X    ClearCode = (1 << CodeSize);
  260. X    EOFCode = ClearCode + 1;
  261. X    FreeCode = FirstFree = ClearCode + 2;
  262. X
  263. X/* The GIF spec has it that the code size is the code size used to
  264. X * compute the above values is the code size given in the file, but the
  265. X * code size used in compression/decompression is the code size given in
  266. X * the file plus one. (thus the ++).
  267. X */
  268. X
  269. X    CodeSize++;
  270. X    InitCodeSize = CodeSize;
  271. X    MaxCode = (1 << CodeSize);
  272. X    ReadMask = MaxCode - 1;
  273. X
  274. X/* Read the raster data.  Here we just transpose it from the GIF array
  275. X * to the Raster array, turning it from a series of blocks into one long
  276. X * data stream, which makes life much easier for ReadCode().
  277. X */
  278. X
  279. X    ptr1 = Raster;
  280. X    do {
  281. X        ch = ch1 = NEXTBYTE;
  282. X        while (ch--) *ptr1++ = NEXTBYTE;
  283. X    } while(ch1);
  284. X
  285. X    free(RawGIF);               /* We're done with the raw data now... */
  286. X
  287. X    fprintf(stderr, "done.\n");
  288. X    fprintf(stderr, "Decompressing...");
  289. X
  290. X
  291. X#ifdef notdefSS
  292. X/* SS: Allocate the Sun Pixrect and make "Image" point to the image data. */
  293. X    Output = mem_create(Width, Height, 8);
  294. X    if (Output == (Pixrect *) NULL)
  295. X        error("%s: not enough memory for output data.\n", NULL);
  296. X    Image = (u_char *) mpr_d(Output)->md_image;
  297. X#endif notdefSS
  298. X/* PBMS: Allocate the PBM bit array. */
  299. X    bits = pbm_allocarray(Width, Height);
  300. X
  301. X
  302. X/* Decompress the file, continuing until you see the GIF EOF code.
  303. X * One obvious enhancement is to add checking for corrupt files here.
  304. X */
  305. X
  306. X    Code = ReadCode();
  307. X    while (Code != EOFCode) {
  308. X
  309. X/* Clear code sets everything back to its initial value, then reads the
  310. X * immediately subsequent code as uncompressed data.
  311. X */
  312. X
  313. X        if (Code == ClearCode) {
  314. X            CodeSize = InitCodeSize;
  315. X            MaxCode = (1 << CodeSize);
  316. X            ReadMask = MaxCode - 1;
  317. X            FreeCode = FirstFree;
  318. X            CurCode = OldCode = Code = ReadCode();
  319. X            FinChar = CurCode & BitMask;
  320. X            AddToPixel(FinChar);
  321. X        }
  322. X        else {
  323. X
  324. X/* If not a clear code, then must be data: save same as CurCode and InCode */
  325. X
  326. X            CurCode = InCode = Code;
  327. X
  328. X/* If greater or equal to FreeCode, not in the hash table yet;
  329. X * repeat the last character decoded
  330. X */
  331. X
  332. X            if (CurCode >= FreeCode) {
  333. X                CurCode = OldCode;
  334. X                OutCode[OutCount++] = FinChar;
  335. X            }
  336. X
  337. X/* Unless this code is raw data, pursue the chain pointed to by CurCode
  338. X * through the hash table to its end; each code in the chain puts its
  339. X * associated output code on the output queue.
  340. X */
  341. X
  342. X            while (CurCode > BitMask) {
  343. X                OutCode[OutCount++] = Suffix[CurCode];
  344. X                CurCode = Prefix[CurCode];
  345. X            }
  346. X
  347. X/* The last code in the chain is treated as raw data. */
  348. X
  349. X            FinChar = CurCode & BitMask;
  350. X            OutCode[OutCount++] = FinChar;
  351. X
  352. X/* Now we put the data out to the Output routine.
  353. X * It's been stacked LIFO, so deal with it that way...
  354. X */
  355. X
  356. X            for (i = OutCount - 1; i >= 0; i--)
  357. X                AddToPixel(OutCode[i]);
  358. X            OutCount = 0;
  359. X
  360. X/* Build the hash table on-the-fly. No table is stored in the file. */
  361. X
  362. X            Prefix[FreeCode] = OldCode;
  363. X            Suffix[FreeCode] = FinChar;
  364. X            OldCode = InCode;
  365. X
  366. X/* Point to the next slot in the table.  If we exceed the current
  367. X * MaxCode value, increment the code size unless it's already 12.  If it
  368. X * is, do nothing: the next code decompressed better be CLEAR
  369. X */
  370. X
  371. X            FreeCode++;
  372. X            if (FreeCode >= MaxCode) {
  373. X                if (CodeSize < 12) {
  374. X                    CodeSize++;
  375. X                    MaxCode *= 2;
  376. X                    ReadMask = (1 << CodeSize) - 1;
  377. X                }
  378. X            }
  379. X        }
  380. X        Code = ReadCode();
  381. X    }
  382. X
  383. X    free(Raster);
  384. X
  385. X    fprintf(stderr, "done.\n");
  386. X
  387. X    if (!(fp = fopen(outfname, "w")))
  388. X        error("%s: can't create %s.\n", outfname);
  389. X
  390. X#ifdef notdefSS
  391. X/* SS: Pixrect Rasterfile output code. */
  392. X    fprintf(stderr, "Writing Sun Rasterfile: %s...", outfname);
  393. X    if (pr_dump(Output, fp, &Colormap, RT_STANDARD, 0) == PIX_ERR)
  394. X        error("%s: error writing Sun Rasterfile: %s\n", outfname);
  395. X#endif notdefSS
  396. X/* PBMS: PBM output code. */
  397. X    pbm_writepbm(stdout, bits, Width, Height);
  398. X
  399. X    fclose(fp);
  400. X
  401. X    fprintf(stderr, "done.\n");
  402. X}
  403. X
  404. X
  405. X/* Fetch the next code from the raster data stream.  The codes can be
  406. X * any length from 3 to 12 bits, packed into 8-bit bytes, so we have to
  407. X * maintain our location in the Raster array as a BIT Offset.  We compute
  408. X * the byte Offset into the raster array by dividing this by 8, pick up
  409. X * three bytes, compute the bit Offset into our 24-bit chunk, shift to
  410. X * bring the desired code to the bottom, then mask it off and return it.
  411. X */
  412. XReadCode()
  413. X{
  414. Xint RawCode, ByteOffset;
  415. X
  416. X    ByteOffset = BitOffset / 8;
  417. X    RawCode = Raster[ByteOffset] + (0x100 * Raster[ByteOffset + 1]);
  418. X    if (CodeSize >= 8)
  419. X        RawCode += (0x10000 * Raster[ByteOffset + 2]);
  420. X    RawCode >>= (BitOffset % 8);
  421. X    BitOffset += CodeSize;
  422. X    return(RawCode & ReadMask);
  423. X}
  424. X
  425. X
  426. XAddToPixel(Index)
  427. Xu_char Index;
  428. X{
  429. X#ifdef notdefSS
  430. X    *(Image + YC * Width + XC) = Index;
  431. X#endif notdefSS
  432. X/* PBMS: Store a pixel. */
  433. X    bits[YC][XC] = Index;
  434. X
  435. X/* Update the X-coordinate, and if it overflows, update the Y-coordinate */
  436. X
  437. X    if (++XC == Width) {
  438. X
  439. X/* If a non-interlaced picture, just increment YC to the next scan line.
  440. X * If it's interlaced, deal with the interlace as described in the GIF
  441. X * spec.  Put the decoded scan line out to the screen if we haven't gone
  442. X * past the bottom of it
  443. X */
  444. X
  445. X        XC = 0;
  446. X        if (!Interlace) YC++;
  447. X        else {
  448. X            switch (Pass) {
  449. X                case 0:
  450. X                    YC += 8;
  451. X                    if (YC >= Height) {
  452. X                        Pass++;
  453. X                        YC = 4;
  454. X                    }
  455. X                break;
  456. X                case 1:
  457. X                    YC += 8;
  458. X                    if (YC >= Height) {
  459. X                        Pass++;
  460. X                        YC = 2;
  461. X                    }
  462. X                break;
  463. X                case 2:
  464. X                    YC += 4;
  465. X                    if (YC >= Height) {
  466. X                        Pass++;
  467. X                        YC = 1;
  468. X                    }
  469. X                break;
  470. X                case 3:
  471. X                    YC += 2;
  472. X                break;
  473. X                default:
  474. X                break;
  475. X            }
  476. X        }
  477. X    }
  478. X}
  479. SHAR_EOF
  480. if test 14611 -ne "`wc -c < 'gif2ras.c'`"
  481. then
  482.     echo shar: error transmitting "'gif2ras.c'" '(should have been 14611 characters)'
  483. fi
  484. fi # end of overwriting check
  485. #    End of shell archive
  486. exit 0
  487. #! /bin/sh
  488. # This is a shell archive, meaning:
  489. # 1. Remove everything above the #! /bin/sh line.
  490. # 2. Save the resulting text in a file.
  491. # 3. Execute the file with /bin/sh (not csh) to create the files:
  492. #
  493. #    gifcompr.c
  494. #    gifencod.c
  495. #
  496. # This archive created: Fri May 12 20:26:46 1989
  497. # By:    Roger L. Long (bytebug@dhw68k.cts.com)
  498. export PATH; PATH=/bin:$PATH
  499. echo shar: extracting "'gifcompr.c'" '(11182 characters)'
  500. if test -f 'gifcompr.c'
  501. then
  502.     echo shar: will not over-write existing file "'gifcompr.c'"
  503. else
  504. sed 's/^X//' << \SHAR_EOF > 'gifcompr.c'
  505. X/***************************************************************************
  506. X *
  507. X *  GIFENCOD.C       - GIF Image compression routines
  508. X *
  509. X *  Lempel-Ziv compression based on 'compress'.  GIF modifications by
  510. X *  David Rowley (mgardi@watdcsu.waterloo.edu)
  511. X *
  512. X ***************************************************************************/
  513. X
  514. X/*
  515. X * General DEFINEs
  516. X */
  517. X#define min(a,b)        ((a>b) ? b : a)
  518. X
  519. X#define BITS    12
  520. X#define MSDOS   1
  521. X
  522. X#define HSIZE  5003            /* 80% occupancy */
  523. X
  524. X/*
  525. X * Pointer to function returning an int
  526. X */
  527. Xtypedef int (* ifunptr)();
  528. X
  529. X/*
  530. X * a code_int must be able to hold 2**BITS values of type int, and also -1
  531. X */
  532. Xtypedef int             code_int;
  533. X
  534. X#ifdef SIGNED_COMPARE_SLOW
  535. Xtypedef unsigned long int count_int;
  536. Xtypedef unsigned short int count_short;
  537. X#else
  538. Xtypedef long int          count_int;
  539. X#endif
  540. X
  541. X#ifdef NO_UCHAR
  542. X typedef char   char_type;
  543. X#else
  544. X typedef        unsigned char   char_type;
  545. X#endif /* UCHAR */
  546. X
  547. X/*
  548. X *
  549. X * GIF Image compression - modified 'compress'
  550. X *
  551. X * Based on: compress.c - File compression ala IEEE Computer, June 1984.
  552. X *
  553. X * By Authors:  Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
  554. X *              Jim McKie               (decvax!mcvax!jim)
  555. X *              Steve Davies            (decvax!vax135!petsd!peora!srd)
  556. X *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
  557. X *              James A. Woods          (decvax!ihnp4!ames!jaw)
  558. X *              Joe Orost               (decvax!vax135!petsd!joe)
  559. X *
  560. X */
  561. X#include <stdio.h>
  562. X#include <ctype.h>
  563. X#include <signal.h>
  564. X
  565. X#define ARGVAL() (*++(*argv) || (--argc && *++argv))
  566. X
  567. Xstatic int n_bits;                        /* number of bits/code */
  568. Xstatic int maxbits = BITS;                /* user settable max # bits/code */
  569. Xstatic code_int maxcode;                  /* maximum code, given n_bits */
  570. Xstatic code_int maxmaxcode = (code_int)1 << BITS; /* should NEVER generate this
  571. Xcode */
  572. X#ifdef COMPATIBLE               /* But wrong! */
  573. X# define MAXCODE(n_bits)        ((code_int) 1 << (n_bits) - 1)
  574. X#else
  575. X# define MAXCODE(n_bits)        (((code_int) 1 << (n_bits)) - 1)
  576. X#endif /* COMPATIBLE */
  577. X
  578. Xstatic count_int htab [HSIZE];
  579. Xstatic unsigned short codetab [HSIZE];
  580. X#define HashTabOf(i)       htab[i]
  581. X#define CodeTabOf(i)    codetab[i]
  582. X
  583. Xstatic code_int hsize = HSIZE;                 /* for dynamic table sizing */
  584. Xstatic count_int fsize;
  585. X
  586. X/*
  587. X * To save much memory, we overlay the table used by compress() with those
  588. X * used by decompress().  The tab_prefix table is the same size and type
  589. X * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  590. X * get this from the beginning of htab.  The output stack uses the rest
  591. X * of htab, and contains characters.  There is plenty of room for any
  592. X * possible stack (stack used to be 8000 characters).
  593. X */
  594. X
  595. X#define tab_prefixof(i) CodeTabOf(i)
  596. X#define tab_suffixof(i)        ((char_type *)(htab))[i]
  597. X#define de_stack               ((char_type *)&tab_suffixof((code_int)1<<BITS))
  598. X
  599. Xstatic code_int free_ent = 0;                  /* first unused entry */
  600. Xstatic int exit_stat = 0;
  601. X
  602. X/*
  603. X * block compression parameters -- after all codes are used up,
  604. X * and compression rate changes, start over.
  605. X */
  606. Xstatic int clear_flg = 0;
  607. X
  608. Xstatic int offset;
  609. Xstatic long int in_count = 1;            /* length of input */
  610. Xstatic long int out_count = 0;           /* # of codes output (for debugging) */
  611. X
  612. X/*
  613. X * compress stdin to stdout
  614. X *
  615. X * Algorithm:  use open addressing double hashing (no chaining) on the
  616. X * prefix code / next character combination.  We do a variant of Knuth's
  617. X * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  618. X * secondary probe.  Here, the modular division first probe is gives way
  619. X * to a faster exclusive-or manipulation.  Also do block compression with
  620. X * an adaptive reset, whereby the code table is cleared when the compression
  621. X * ratio decreases, but after the table fills.  The variable-length output
  622. X * codes are re-sized at this point, and a special CLEAR code is generated
  623. X * for the decompressor.  Late addition:  construct the table according to
  624. X * file size for noticeable speed improvement on small files.  Please direct
  625. X * questions about this implementation to ames!jaw.
  626. X */
  627. X
  628. Xstatic int g_init_bits;
  629. Xstatic FILE *g_outfile;
  630. X
  631. Xstatic int ClearCode;
  632. Xstatic int EOFCode;
  633. X
  634. Xcompress( init_bits, outfile, ReadValue )
  635. Xint init_bits;
  636. XFILE *outfile;
  637. Xifunptr ReadValue;
  638. X{
  639. X    register long fcode;
  640. X    register code_int i = 0;
  641. X    register int c;
  642. X    register code_int ent;
  643. X    register code_int disp;
  644. X    register code_int hsize_reg;
  645. X    register int hshift;
  646. X
  647. X    /*
  648. X     * Set up the globals:  g_init_bits - initial number of bits
  649. X     *                      g_outfile   - pointer to output file
  650. X     */
  651. X    g_init_bits = init_bits;
  652. X    g_outfile = outfile;
  653. X
  654. X    /*
  655. X     * Set up the necessary values
  656. X     */
  657. X    offset = 0;
  658. X    out_count = 0;
  659. X    clear_flg = 0;
  660. X    in_count = 1;
  661. X    maxcode = MAXCODE(n_bits = g_init_bits);
  662. X
  663. X    ClearCode = (1 << (init_bits - 1));
  664. X    EOFCode = ClearCode + 1;
  665. X    free_ent = ClearCode + 2;
  666. X
  667. X    char_init();
  668. X
  669. X    ent = GIFNextPixel( ReadValue );
  670. X
  671. X    hshift = 0;
  672. X    for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  673. X        hshift++;
  674. X    hshift = 8 - hshift;                /* set hash code range bound */
  675. X
  676. X    hsize_reg = hsize;
  677. X    cl_hash( (count_int) hsize_reg);            /* clear hash table */
  678. X
  679. X    output( (code_int)ClearCode );
  680. X
  681. X#ifdef SIGNED_COMPARE_SLOW
  682. X    while ( (c = GIFNextPixel( ReadValue )) != (unsigned) EOF ) {
  683. X#else
  684. X    while ( (c = GIFNextPixel( ReadValue )) != EOF ) {
  685. X#endif
  686. X
  687. X        in_count++;
  688. X
  689. X        fcode = (long) (((long) c << maxbits) + ent);
  690. X        i = (((code_int)c << hshift) ~ ent);    /* xor hashing */
  691. X
  692. X        if ( HashTabOf (i) == fcode ) {
  693. X            ent = CodeTabOf (i);
  694. X            continue;
  695. X        } else if ( (long)HashTabOf (i) < 0 )      /* empty slot */
  696. X            goto nomatch;
  697. X        disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
  698. X        if ( i == 0 )
  699. X            disp = 1;
  700. Xprobe:
  701. X        if ( (i -= disp) < 0 )
  702. X            i += hsize_reg;
  703. X
  704. X        if ( HashTabOf (i) == fcode ) {
  705. X            ent = CodeTabOf (i);
  706. X            continue;
  707. X        }
  708. X        if ( (long)HashTabOf (i) > 0 )
  709. X            goto probe;
  710. Xnomatch:
  711. X        output ( (code_int) ent );
  712. X        out_count++;
  713. X        ent = c;
  714. X#ifdef SIGNED_COMPARE_SLOW
  715. X        if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  716. X#else
  717. X        if ( free_ent < maxmaxcode ) {
  718. X#endif
  719. X            CodeTabOf (i) = free_ent++; /* code -> hashtable */
  720. X            HashTabOf (i) = fcode;
  721. X        } else
  722. X                cl_block();
  723. X    }
  724. X    /*
  725. X     * Put out the final code.
  726. X     */
  727. X    output( (code_int)ent );
  728. X    out_count++;
  729. X    output( (code_int) EOFCode );
  730. X
  731. X    return;
  732. X}
  733. X
  734. X/*****************************************************************
  735. X * TAG( output )
  736. X *
  737. X * Output the given code.
  738. X * Inputs:
  739. X *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
  740. X *              that n_bits =< (long)wordsize - 1.
  741. X * Outputs:
  742. X *      Outputs code to the file.
  743. X * Assumptions:
  744. X *      Chars are 8 bits long.
  745. X * Algorithm:
  746. X *      Maintain a BITS character long buffer (so that 8 codes will
  747. X * fit in it exactly).  Use the VAX insv instruction to insert each
  748. X * code in turn.  When the buffer fills up empty it and start over.
  749. X */
  750. X
  751. Xstatic unsigned long cur_accum = 0;
  752. Xstatic int  cur_bits = 0;
  753. X
  754. Xstatic
  755. Xunsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
  756. X                                  0x001F, 0x003F, 0x007F, 0x00FF,
  757. X                                  0x01FF, 0x03FF, 0x07FF, 0x0FFF,
  758. X                                  0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  759. X
  760. Xstatic
  761. Xoutput( code )
  762. Xcode_int  code;
  763. X{
  764. X    cur_accum &= masks[ cur_bits ];
  765. X
  766. X    if( cur_bits > 0 )
  767. X        cur_accum |= ((long)code << cur_bits);
  768. X    else
  769. X        cur_accum = code;
  770. X
  771. X    cur_bits += n_bits;
  772. X
  773. X    while( cur_bits >= 8 ) {
  774. X        char_out( (unsigned int)(cur_accum & 0xff) );
  775. X        cur_accum >>= 8;
  776. X        cur_bits -= 8;
  777. X    }
  778. X
  779. X    /*
  780. X     * If the next entry is going to be too big for the code size,
  781. X     * then increase it, if possible.
  782. X     */
  783. X   if ( free_ent > maxcode || clear_flg ) {
  784. X
  785. X            if( clear_flg ) {
  786. X
  787. X                maxcode = MAXCODE (n_bits = g_init_bits);
  788. X                clear_flg = 0;
  789. X
  790. X            } else {
  791. X
  792. X                n_bits++;
  793. X                if ( n_bits == maxbits )
  794. X                    maxcode = maxmaxcode;
  795. X                else
  796. X                    maxcode = MAXCODE(n_bits);
  797. X            }
  798. X        }
  799. X
  800. X    if( code == EOFCode ) {
  801. X        /*
  802. X         * At EOF, write the rest of the buffer.
  803. X         */
  804. X        while( cur_bits > 0 ) {
  805. X                char_out( (unsigned int)(cur_accum & 0xff) );
  806. X                cur_accum >>= 8;
  807. X                cur_bits -= 8;
  808. X        }
  809. X
  810. X        flush_char();
  811. X
  812. X        fflush( g_outfile );
  813. X
  814. X        if( ferror( g_outfile ) )
  815. X                writeerr();
  816. X    }
  817. X}
  818. X
  819. X/*
  820. X * Clear out the hash table
  821. X */
  822. Xstatic
  823. Xcl_block ()             /* table clear for block compress */
  824. X{
  825. X
  826. X        cl_hash ( (count_int) hsize );
  827. X        free_ent = ClearCode + 2;
  828. X        clear_flg = 1;
  829. X
  830. X        output( (code_int)ClearCode );
  831. X}
  832. X
  833. Xstatic
  834. Xcl_hash(hsize)          /* reset code table */
  835. Xregister count_int hsize;
  836. X{
  837. X
  838. X        register count_int *htab_p = htab+hsize;
  839. X
  840. X        register long i;
  841. X        register long m1 = -1;
  842. X
  843. X        i = hsize - 16;
  844. X        do {                            /* might use Sys V memset(3) here */
  845. X                *(htab_p-16) = m1;
  846. X                *(htab_p-15) = m1;
  847. X                *(htab_p-14) = m1;
  848. X                *(htab_p-13) = m1;
  849. X                *(htab_p-12) = m1;
  850. X                *(htab_p-11) = m1;
  851. X                *(htab_p-10) = m1;
  852. X                *(htab_p-9) = m1;
  853. X                *(htab_p-8) = m1;
  854. X                *(htab_p-7) = m1;
  855. X                *(htab_p-6) = m1;
  856. X                *(htab_p-5) = m1;
  857. X                *(htab_p-4) = m1;
  858. X                *(htab_p-3) = m1;
  859. X                *(htab_p-2) = m1;
  860. X                *(htab_p-1) = m1;
  861. X                htab_p -= 16;
  862. X        } while ((i -= 16) >= 0);
  863. X
  864. X        for ( i += 16; i > 0; i-- )
  865. X                *--htab_p = m1;
  866. X}
  867. X
  868. Xstatic
  869. Xwriteerr()
  870. X{
  871. X        printf( "error writing output file\n" );
  872. X        exit(1);
  873. X}
  874. X
  875. X/******************************************************************************
  876. X *
  877. X * GIF Specific routines
  878. X *
  879. X ******************************************************************************/
  880. X
  881. X/*
  882. X * Number of characters so far in this 'packet'
  883. X */
  884. Xstatic int a_count;
  885. X
  886. X/*
  887. X * Set up the 'byte output' routine
  888. X */
  889. Xstatic
  890. Xchar_init()
  891. X{
  892. X        a_count = 0;
  893. X}
  894. X
  895. X/*
  896. X * Define the storage for the packet accumulator
  897. X */
  898. Xstatic char accum[ 256 ];
  899. X
  900. X/*
  901. X * Add a character to the end of the current packet, and if it is 254
  902. X * characters, flush the packet to disk.
  903. X */
  904. Xstatic
  905. Xchar_out( c )
  906. Xint c;
  907. X{
  908. X        accum[ a_count++ ] = c;
  909. X        if( a_count >= 254 )
  910. X                flush_char();
  911. X}
  912. X
  913. X/*
  914. X * Flush the packet to disk, and reset the accumulator
  915. X */
  916. Xstatic
  917. Xflush_char()
  918. X{
  919. X        if( a_count > 0 ) {
  920. X                fputc( a_count, g_outfile );
  921. X                fwrite( accum, 1, a_count, g_outfile );
  922. X                a_count = 0;
  923. X        }
  924. X}
  925. X
  926. X/* The End */
  927. SHAR_EOF
  928. if test 11182 -ne "`wc -c < 'gifcompr.c'`"
  929. then
  930.     echo shar: error transmitting "'gifcompr.c'" '(should have been 11182 characters)'
  931. fi
  932. fi # end of overwriting check
  933. echo shar: extracting "'gifencod.c'" '(5916 characters)'
  934. if test -f 'gifencod.c'
  935. then
  936.     echo shar: will not over-write existing file "'gifencod.c'"
  937. else
  938. sed 's/^X//' << \SHAR_EOF > 'gifencod.c'
  939. X
  940. X/*****************************************************************************
  941. X *
  942. X * GIFENCODE.C    - GIF Image compression interface
  943. X *
  944. X * GIFEncode( FName, GHeight, GWidth, GInterlace, Background,
  945. X *            BitsPerPixel, Red, Green, Blue, GetPixel )
  946. X *
  947. X *****************************************************************************/
  948. X
  949. X#include <stdio.h>
  950. X
  951. X/*
  952. X * Pointer to function returning an int
  953. X */
  954. Xtypedef int (* ifunptr)();
  955. X
  956. X#define TRUE 1
  957. X#define FALSE 0
  958. X
  959. Xstatic int Width, Height;
  960. Xstatic int curx, cury;
  961. Xstatic long CountDown;
  962. Xstatic int Pass = 0;
  963. Xstatic int Interlace;
  964. X
  965. X/*
  966. X * Bump the 'curx' and 'cury' to point to the next pixel
  967. X */
  968. Xstatic
  969. XBumpPixel()
  970. X{
  971. X        /*
  972. X         * Bump the current X position
  973. X         */
  974. X        curx++;
  975. X
  976. X        /*
  977. X         * If we are at the end of a scan line, set curx back to the beginning
  978. X         * If we are interlaced, bump the cury to the appropriate spot,
  979. X         * otherwise, just increment it.
  980. X         */
  981. X        if( curx == Width ) {
  982. X                curx = 0;
  983. X
  984. X                if( !Interlace )
  985. X                        cury++;
  986. X                else {
  987. X                     switch( Pass ) {
  988. X
  989. X                       case 0:
  990. X                          cury += 8;
  991. X                          if( cury >= Height ) {
  992. X                                Pass++;
  993. X                                cury = 4;
  994. X                          }
  995. X                          break;
  996. X
  997. X                       case 1:
  998. X                          cury += 8;
  999. X                          if( cury >= Height ) {
  1000. X                                Pass++;
  1001. X                                cury = 2;
  1002. X                          }
  1003. X                          break;
  1004. X
  1005. X                       case 2:
  1006. X                          cury += 4;
  1007. X                          if( cury >= Height ) {
  1008. X                             Pass++;
  1009. X                             cury = 1;
  1010. X                          }
  1011. X                          break;
  1012. X
  1013. X                       case 3:
  1014. X                          cury += 2;
  1015. X                          break;
  1016. X                        }
  1017. X                }
  1018. X        }
  1019. X}
  1020. X
  1021. X/*
  1022. X * Return the next pixel from the image
  1023. X */
  1024. XGIFNextPixel( getpixel )
  1025. Xifunptr getpixel;
  1026. X{
  1027. X        int r;
  1028. X
  1029. X        if( CountDown == 0 )
  1030. X                return EOF;
  1031. X
  1032. X        CountDown--;
  1033. X
  1034. X        r = ( * getpixel )( curx, cury );
  1035. X
  1036. X        BumpPixel();
  1037. X
  1038. X        return r;
  1039. X}
  1040. X
  1041. X/* public */
  1042. X
  1043. XGIFEncode( FName, GWidth, GHeight, GInterlace, Background,
  1044. X           BitsPerPixel, Red, Green, Blue, GetPixel )
  1045. X
  1046. Xchar *FName;
  1047. Xint GWidth, GHeight;
  1048. Xint GInterlace;
  1049. Xint Background;
  1050. Xint BitsPerPixel;
  1051. Xint Red[], Green[], Blue[];
  1052. Xifunptr GetPixel;
  1053. X
  1054. X{
  1055. X        FILE *fp;
  1056. X        int B;
  1057. X        int RWidth, RHeight;
  1058. X        int LeftOfs, TopOfs;
  1059. X        int Resolution;
  1060. X        int ColorMapSize;
  1061. X        int InitCodeSize;
  1062. X        int i;
  1063. X
  1064. X        Interlace = GInterlace;
  1065. X
  1066. X        ColorMapSize = 1 << BitsPerPixel;
  1067. X
  1068. X        RWidth = Width = GWidth;
  1069. X        RHeight = Height = GHeight;
  1070. X        LeftOfs = TopOfs = 0;
  1071. X
  1072. X        Resolution = BitsPerPixel;
  1073. X
  1074. X        /*
  1075. X         * Calculate number of bits we are expecting
  1076. X         */
  1077. X        CountDown = (long)Width * (long)Height;
  1078. X
  1079. X        /*
  1080. X         * Indicate which pass we are on (if interlace)
  1081. X         */
  1082. X        Pass = 0;
  1083. X
  1084. X        /*
  1085. X         * The initial code size
  1086. X         */
  1087. X        if( BitsPerPixel <= 1 )
  1088. X                InitCodeSize = 2;
  1089. X        else
  1090. X                InitCodeSize = BitsPerPixel;
  1091. X
  1092. X        /*
  1093. X         * Set up the current x and y position
  1094. X         */
  1095. X        curx = cury = 0;
  1096. X
  1097. X        /*
  1098. X         * Open the GIF file for binary write
  1099. X         */
  1100. X        fp = fopen( FName, "wb" );
  1101. X
  1102. X        if( fp == (FILE *)0 ) {
  1103. X                printf( "error: could not open output file\n" );
  1104. X                exit(1);
  1105. X        }
  1106. X
  1107. X        /*
  1108. X         * Write the Magic header
  1109. X         */
  1110. X        fwrite( "GIF87a", 1, 6, fp );
  1111. X
  1112. X        /*
  1113. X         * Write out the screen width and height
  1114. X         */
  1115. X        Putword( RWidth, fp );
  1116. X        Putword( RHeight, fp );
  1117. X
  1118. X        /*
  1119. X         * Indicate that there is a global colour map
  1120. X         */
  1121. X        B = 0x80;       /* Yes, there is a color map */
  1122. X
  1123. X        /*
  1124. X         * OR in the resolution
  1125. X         */
  1126. X        B |= (Resolution - 1) << 5;
  1127. X
  1128. X        /*
  1129. X         * OR in the Bits per Pixel
  1130. X         */
  1131. X        B |= (BitsPerPixel - 1);
  1132. X
  1133. X        /*
  1134. X         * Write it out
  1135. X         */
  1136. X        fputc( B, fp );
  1137. X
  1138. X        /*
  1139. X         * Write out the Background colour
  1140. X         */
  1141. X        fputc( Background, fp );
  1142. X
  1143. X        /*
  1144. X         * Byte of 0's (future expansion)
  1145. X         */
  1146. X        fputc( 0, fp );
  1147. X
  1148. X        /*
  1149. X         * Write out the Global Colour Map
  1150. X         */
  1151. X        for( i=0; i<ColorMapSize; i++ ) {
  1152. X                fputc( Red[i], fp );
  1153. X                fputc( Green[i], fp );
  1154. X                fputc( Blue[i], fp );
  1155. X        }
  1156. X
  1157. X        /*
  1158. X         * Write an Image separator
  1159. X         */
  1160. X        fputc( ',', fp );
  1161. X
  1162. X        /*
  1163. X         * Write the Image header
  1164. X         */
  1165. X
  1166. X        Putword( LeftOfs, fp );
  1167. X        Putword( TopOfs, fp );
  1168. X        Putword( Width, fp );
  1169. X        Putword( Height, fp );
  1170. X
  1171. X        /*
  1172. X         * Write out whether or not the image is interlaced
  1173. X         */
  1174. X        if( Interlace )
  1175. X                fputc( 0x40, fp );
  1176. X        else
  1177. X                fputc( 0x00, fp );
  1178. X
  1179. X        /*
  1180. X         * Write out the initial code size
  1181. X         */
  1182. X        fputc( InitCodeSize, fp );
  1183. X
  1184. X        /*
  1185. X         * Go and actually compress the data
  1186. X         */
  1187. X        compress( InitCodeSize+1, fp, GetPixel );
  1188. X
  1189. X        /*
  1190. X         * Write out a Zero-length packet (to end the series)
  1191. X         */
  1192. X        fputc( 0, fp );
  1193. X
  1194. X        /*
  1195. X         * Write the GIF file terminator
  1196. X         */
  1197. X        fputc( ';', fp );
  1198. X
  1199. X        /*
  1200. X         * And close the file
  1201. X         */
  1202. X        fclose( fp );
  1203. X
  1204. X}
  1205. X
  1206. X/*
  1207. X * Write out a word to the GIF file
  1208. X */
  1209. Xstatic
  1210. XPutword( w, fp )
  1211. Xint w;
  1212. XFILE *fp;
  1213. X{
  1214. X        fputc( w & 0xff, fp );
  1215. X        fputc( (w / 256) & 0xff, fp );
  1216. X}
  1217. X
  1218. SHAR_EOF
  1219. if test 5916 -ne "`wc -c < 'gifencod.c'`"
  1220. then
  1221.     echo shar: error transmitting "'gifencod.c'" '(should have been 5916 characters)'
  1222. fi
  1223. fi # end of overwriting check
  1224. #    End of shell archive
  1225. exit 0
  1226. ---
  1227.