gifload.c 28.5 KB
Newer Older
1
2
3
4
5
/* GIF loading file filter for The GIMP 1.3/1.4
 * +-------------------------------------------------------------------+
 * |  Copyright Adam D. Moss, Peter Mattis, Spencer Kimball            |
 * +-------------------------------------------------------------------+
 * Version 1.50.4 - 2003/06/03
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
6
7
 *                        Adam D. Moss - <adam@gimp.org> <adam@foxbox.org>
 */
8
9
10
11
12
13
14
15
16

/* Copyright notice for old GIF code from which this plugin was long ago */
/* derived (David Koblas has kindly granted permission to relicense):    */
/* +-------------------------------------------------------------------+ */
/* | Copyright 1990, 1991, 1993, David Koblas.  (koblas@extra.com)     | */
/* +-------------------------------------------------------------------+ */
/* Also...
 * 'This filter uses code taken from the "giftopnm" and "ppmtogif" programs
 *    which are part of the "netpbm" package.'
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
17
 */
18
/* Additionally...
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
19
20
 *  "The Graphics Interchange Format(c) is the Copyright property of
 *  CompuServe Incorporated.  GIF(sm) is a Service Mark property of
21
 *  CompuServe Incorporated."
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
22
23
24
25
26
 */

/*
 * REVISION HISTORY
 *
27
28
29
30
31
32
33
34
 * 2003/06/03
 * 1.50.04 - When initializing the LZW state, watch out for a completely
 *     bogus input_code_size [based on fix by Raphael Quinet]
 *     Also, fix a stupid old bug when clearing the code table between
 *     subimages.  (Enables us to deal better with errors when the stream is
 *     corrupted pretty early in a subimage.) [adam]
 *     Minor-version-bump to distinguish between gimp1.2/1.4 branches.
 *
35
36
37
38
 * 2000/03/31
 * 1.00.03 - Just mildly more useful comments/messages concerning frame
 *     disposals.
 *
39
 * 1999/11/20
40
41
42
43
44
45
 * 1.00.02 - Fixed a couple of possible infinite loops where an
 *     error condition was not being checked.  Also changed some g_message()s
 *     back to g_warning()s as they should be (don't get carried away with
 *     the user feedback fellahs, no-one wants to be told of every single
 *     corrupt byte and block in its own little window.  :-( ).
 *
46
 * 1999/11/11
47
48
49
50
 * 1.00.01 - Fixed an uninitialized variable which has been around
 *     forever... thanks to jrb@redhat.com for noticing that there
 *     was a problem somewhere!
 *
51
 * 1999/03/20
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
 * 1.00.00 - GIF load-only code split from main GIF plugin.
 *
 * For previous revision information, please consult the comments
 * in the 'gif' plugin.
 */

/*
 * TODO (more *'s means more important!)
 *
 * - PDB stuff for comments
 *
 * - Remove unused colourmap entries for GRAYSCALE images.
 */

66
#include "config.h"
67

68
#include <errno.h>
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
69
#include <string.h>
70

71
#include <glib/gstdio.h>
72
73
74

#include <libgimp/gimp.h>

75
#include "libgimp/stdplugins-intl.h"
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


/* uncomment the line below for a little debugging info */
/* #define GIFDEBUG yesplease */


/* Does the version of GIMP we're compiling for support
   data attachments to images?  ('Parasites') */
#define FACEHUGGERS aieee
/* PS: I know that technically facehuggers aren't parasites,
   the pupal-forms are.  But facehuggers are ky00te. */


/* Declare some local functions.
 */
static void   query      (void);
92
93
94
95
96
97
static void   run        (const gchar      *name,
                          gint              nparams,
                          const GimpParam  *param,
                          gint             *nreturn_vals,
                          GimpParam       **return_vals);
static gint32 load_image (const gchar      *filename);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
98
99


100
static guchar      used_cmap[3][256];
101
static GimpRunMode run_mode;
102
103
104
static guchar      highest_used_index;
static gboolean    promote_to_rgb   = FALSE;
static guchar      gimp_cmap[768];
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
105
#ifdef FACEHUGGERS
Sven Neumann's avatar
Sven Neumann committed
106
GimpParasite*      comment_parasite = NULL;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
107
108
109
#endif


Sven Neumann's avatar
Sven Neumann committed
110
GimpPlugInInfo PLUG_IN_INFO =
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
111
{
112
113
114
115
  NULL,  /* init_proc  */
  NULL,  /* quit_proc  */
  query, /* query_proc */
  run,   /* run_proc   */
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
116
117
118
119
120
121
};


MAIN ()

static void
122
query (void)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
123
{
Sven Neumann's avatar
Sven Neumann committed
124
  static GimpParamDef load_args[] =
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
125
  {
Sven Neumann's avatar
Sven Neumann committed
126
127
128
    { GIMP_PDB_INT32, "run_mode", "Interactive, non-interactive" },
    { GIMP_PDB_STRING, "filename", "The name of the file to load" },
    { GIMP_PDB_STRING, "raw_filename", "The name entered" }
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
129
  };
Sven Neumann's avatar
Sven Neumann committed
130
  static GimpParamDef load_return_vals[] =
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
131
  {
Sven Neumann's avatar
Sven Neumann committed
132
    { GIMP_PDB_IMAGE, "image", "Output image" }
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
133
134
135
  };

  gimp_install_procedure ("file_gif_load",
Marc Lehmann's avatar
Marc Lehmann committed
136
                          "loads files of Compuserve GIF file format",
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
137
138
139
140
                          "FIXME: write help for gif_load",
                          "Spencer Kimball, Peter Mattis, Adam Moss, David Koblas",
                          "Spencer Kimball, Peter Mattis, Adam Moss, David Koblas",
                          "1995-1997",
141
                          N_("GIF image"),
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
142
			  NULL,
Sven Neumann's avatar
Sven Neumann committed
143
                          GIMP_PLUGIN,
144
145
                          G_N_ELEMENTS (load_args),
                          G_N_ELEMENTS (load_return_vals),
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
146
147
                          load_args, load_return_vals);

148
  gimp_register_file_handler_mime ("file_gif_load", "image/gif");
149
150
151
152
  gimp_register_magic_load_handler ("file_gif_load",
				    "gif",
				    "",
				    "0,string,GIF8");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
153
154
155
156
}


static void
157
158
159
160
161
run (const gchar      *name,
     gint              nparams,
     const GimpParam  *param,
     gint             *nreturn_vals,
     GimpParam       **return_vals)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
162
{
163
164
165
  static GimpParam   values[2];
  GimpPDBStatusType  status = GIMP_PDB_SUCCESS;
  gint32             image_ID;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
166
167
168

  run_mode = param[0].data.d_int32;

169
170
  INIT_I18N ();

171
172
  *nreturn_vals = 1;
  *return_vals  = values;
Sven Neumann's avatar
Sven Neumann committed
173
174
  values[0].type          = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

  if (strcmp (name, "file_gif_load") == 0)
    {
      image_ID = load_image (param[1].data.d_string);

      /* The GIF format only tells you how many bits per pixel
       *  are in the image, not the actual number of used indices (D'OH!)
       *
       * So if we're not careful, repeated load/save of a transparent GIF
       *  without intermediate indexed->RGB->indexed pumps up the number of
       *  bits used, as we add an index each time for the transparent
       *  colour.  Ouch.  We either do some heavier analysis at save-time,
       *  or trim down the number of GIMP colours at load-time.  We do the
       *  latter for now.
       */
#ifdef GIFDEBUG
      g_print ("GIF: Highest used index is %d\n", highest_used_index);
#endif
      if (!promote_to_rgb)
	{
195
	  gimp_image_set_colormap (image_ID, gimp_cmap, highest_used_index+1);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
196
197
198
199
	}

      if (image_ID != -1)
        {
200
	  *nreturn_vals = 2;
Sven Neumann's avatar
Sven Neumann committed
201
          values[1].type         = GIMP_PDB_IMAGE;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
202
203
204
205
          values[1].data.d_image = image_ID;
        }
      else
        {
Sven Neumann's avatar
Sven Neumann committed
206
          status = GIMP_PDB_EXECUTION_ERROR;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
207
208
        }
    }
209
210
  else
    {
Sven Neumann's avatar
Sven Neumann committed
211
      status = GIMP_PDB_CALLING_ERROR;
212
213
214
    }

  values[0].data.d_status = status;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
215
216
217
218
219
220
221
222
223
}


#define MAXCOLORMAPSIZE  256

#define CM_RED           0
#define CM_GREEN         1
#define CM_BLUE          2

224
#define MAX_LZW_BITS     12
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266

#define INTERLACE          0x40
#define LOCALCOLORMAP      0x80
#define BitSet(byte, bit)  (((byte) & (bit)) == (bit))

#define ReadOK(file,buffer,len) (fread(buffer, len, 1, file) != 0)
#define LM_to_uint(a,b)         (((b)<<8)|(a))

#define GRAYSCALE        1
#define COLOR            2

typedef unsigned char CMap[3][MAXCOLORMAPSIZE];

static struct
{
  unsigned int Width;
  unsigned int Height;
  CMap ColorMap;
  unsigned int BitPixel;
  unsigned int ColorResolution;
  unsigned int Background;
  unsigned int AspectRatio;
  /*
   **
   */
  int GrayScale;
} GifScreen;

static struct
{
  int transparent;
  int delayTime;
  int inputFlag;
  int disposal;
} Gif89 = { -1, -1, -1, 0 };

int verbose = FALSE;
int showComment = TRUE;
char *globalcomment = NULL;
gint globalusecomment = TRUE;

static int ReadColorMap (FILE *, int, CMap, int *);
267
static int DoExtension  (FILE *, int);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
268
static int GetDataBlock (FILE *, unsigned char *);
269
270
271
272
static int GetCode      (FILE *, int, int);
static int LZWReadByte  (FILE *, int, int);
static gint32 ReadImage (FILE *, const gchar *,
                         int, int, CMap, int, int, int, int,
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
273
274
275
276
			 guint, guint, guint, guint);


static gint32
277
load_image (const gchar *filename)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
278
279
280
281
282
283
284
285
286
287
288
289
290
{
  FILE *fd;
  char * name_buf;
  unsigned char buf[16];
  unsigned char c;
  CMap localColorMap;
  int grayScale;
  int useGlobalColormap;
  int bitPixel;
  int imageCount = 0;
  char version[4];
  gint32 image_ID = -1;

291
  fd = g_fopen (filename, "rb");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
292
293
  if (!fd)
    {
294
      g_message (_("Could not open '%s' for reading: %s"),
295
                 gimp_filename_to_utf8 (filename), g_strerror (errno));
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
296
297
298
      return -1;
    }

299
300
  name_buf = g_strdup_printf (_("Opening '%s'..."),
                              gimp_filename_to_utf8 (filename));
301
302
  gimp_progress_init (name_buf);
  g_free (name_buf);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
303
304
305

  if (!ReadOK (fd, buf, 6))
    {
306
      g_message ("Error reading magic number");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
307
308
309
310
311
      return -1;
    }

  if (strncmp ((char *) buf, "GIF", 3) != 0)
    {
312
      g_message (_("This is not a GIF file"));
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
313
314
315
316
317
318
319
320
      return -1;
    }

  strncpy (version, (char *) buf + 3, 3);
  version[3] = '\0';

  if ((strcmp (version, "87a") != 0) && (strcmp (version, "89a") != 0))
    {
321
      g_message ("Bad version number, not '87a' or '89a'");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
322
323
324
325
326
      return -1;
    }

  if (!ReadOK (fd, buf, 7))
    {
327
      g_message ("Failed to read screen descriptor");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
      return -1;
    }

  GifScreen.Width = LM_to_uint (buf[0], buf[1]);
  GifScreen.Height = LM_to_uint (buf[2], buf[3]);
  GifScreen.BitPixel = 2 << (buf[4] & 0x07);
  GifScreen.ColorResolution = (((buf[4] & 0x70) >> 3) + 1);
  GifScreen.Background = buf[5];
  GifScreen.AspectRatio = buf[6];

  if (BitSet (buf[4], LOCALCOLORMAP))
    {
      /* Global Colormap */
      if (ReadColorMap (fd, GifScreen.BitPixel, GifScreen.ColorMap, &GifScreen.GrayScale))
	{
343
	  g_message ("Error reading global colormap");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
344
345
346
347
348
349
	  return -1;
	}
    }

  if (GifScreen.AspectRatio != 0 && GifScreen.AspectRatio != 49)
    {
350
      g_message (_("Non-square pixels.  Image might look squashed."));
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
351
352
353
354
    }


  highest_used_index = 0;
355

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
356
357
358
359
360

  for (;;)
    {
      if (!ReadOK (fd, &c, 1))
	{
361
	  g_message ("EOF / read error on image data");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
	  return image_ID; /* will be -1 if failed on first image! */
	}

      if (c == ';')
	{
	  /* GIF terminator */
	  return image_ID;
	}

      if (c == '!')
	{
	  /* Extension */
	  if (!ReadOK (fd, &c, 1))
	    {
376
	      g_message ("EOF / read error on extension function code");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
377
378
379
380
381
382
383
384
385
	      return image_ID; /* will be -1 if failed on first image! */
	    }
	  DoExtension (fd, c);
	  continue;
	}

      if (c != ',')
	{
	  /* Not a valid start character */
386
	  g_printerr ("GIF: bogus character 0x%02x, ignoring.\n", (int) c);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
387
388
389
390
391
392
393
	  continue;
	}

      ++imageCount;

      if (!ReadOK (fd, buf, 9))
	{
394
	  g_message ("Couldn't read left/top/width/height");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
395
396
397
398
399
400
401
402
403
404
405
	  return image_ID; /* will be -1 if failed on first image! */
	}

      useGlobalColormap = !BitSet (buf[8], LOCALCOLORMAP);

      bitPixel = 1 << ((buf[8] & 0x07) + 1);

      if (!useGlobalColormap)
	{
	  if (ReadColorMap (fd, bitPixel, localColorMap, &grayScale))
	    {
406
	      g_message ("Error reading local colormap");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
407
408
	      return image_ID; /* will be -1 if failed on first image! */
	    }
409

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
410
411
412
413
414
415
416
417
	  image_ID = ReadImage (fd, filename, LM_to_uint (buf[4], buf[5]),
				LM_to_uint (buf[6], buf[7]),
				localColorMap, bitPixel,
				grayScale,
				BitSet (buf[8], INTERLACE), imageCount,
				(guint) LM_to_uint (buf[0], buf[1]),
				(guint) LM_to_uint (buf[2], buf[3]),
				GifScreen.Width,
418
				GifScreen.Height);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
419
420
421
422
423
424
425
426
427
428
429
	}
      else
	{
	  image_ID = ReadImage (fd, filename, LM_to_uint (buf[4], buf[5]),
				LM_to_uint (buf[6], buf[7]),
				GifScreen.ColorMap, GifScreen.BitPixel,
				GifScreen.GrayScale,
				BitSet (buf[8], INTERLACE), imageCount,
				(guint) LM_to_uint (buf[0], buf[1]),
				(guint) LM_to_uint (buf[2], buf[3]),
				GifScreen.Width,
430
				GifScreen.Height);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
431
432
433
434
435
	}

#ifdef FACEHUGGERS
      if (comment_parasite != NULL)
	{
Marc Lehmann's avatar
Marc Lehmann committed
436
	  gimp_image_parasite_attach (image_ID, comment_parasite);
Sven Neumann's avatar
Sven Neumann committed
437
	  gimp_parasite_free (comment_parasite);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
	  comment_parasite = NULL;
	}
#endif

    }

  return image_ID;
}

static int
ReadColorMap (FILE *fd,
	      int   number,
	      CMap  buffer,
	      int  *format)
{
  int i;
  unsigned char rgb[3];
  int flag;

  flag = TRUE;

  for (i = 0; i < number; ++i)
    {
      if (!ReadOK (fd, rgb, sizeof (rgb)))
	{
463
	  g_message ("Bad colormap");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
	  return TRUE;
	}

      buffer[CM_RED][i] = rgb[0];
      buffer[CM_GREEN][i] = rgb[1];
      buffer[CM_BLUE][i] = rgb[2];

      flag &= (rgb[0] == rgb[1] && rgb[1] == rgb[2]);
    }

  *format = (flag) ? GRAYSCALE : COLOR;

  return FALSE;
}

static int
DoExtension (FILE *fd,
	     int   label)
{
483
  static guchar buf[256];
484
  gchar        *str;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502

  switch (label)
    {
    case 0x01:			/* Plain Text Extension */
      str = "Plain Text Extension";
#ifdef notdef
      if (GetDataBlock (fd, (unsigned char *) buf) == 0)
	;

      lpos = LM_to_uint (buf[0], buf[1]);
      tpos = LM_to_uint (buf[2], buf[3]);
      width = LM_to_uint (buf[4], buf[5]);
      height = LM_to_uint (buf[6], buf[7]);
      cellw = buf[8];
      cellh = buf[9];
      foreground = buf[10];
      background = buf[11];

503
      while (GetDataBlock (fd, (unsigned char *) buf) > 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
	{
	  PPM_ASSIGN (image[ypos][xpos],
		      cmap[CM_RED][v],
		      cmap[CM_GREEN][v],
		      cmap[CM_BLUE][v]);
	  ++index;
	}

      return FALSE;
#else
      break;
#endif
    case 0xff:			/* Application Extension */
      str = "Application Extension";
      break;
    case 0xfe:			/* Comment Extension */
      str = "Comment Extension";
521
      while (GetDataBlock (fd, (unsigned char *) buf) > 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
522
523
	{
#ifdef FACEHUGGERS
524
525
526
527
528
          if (!g_utf8_validate (buf, -1, NULL))
            continue;

	  if (comment_parasite)
            gimp_parasite_free (comment_parasite);
529

530
531
532
	  comment_parasite = gimp_parasite_new ("gimp-comment",
                                                GIMP_PARASITE_PERSISTENT,
                                                strlen(buf) + 1, buf);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#else
	  if (showComment)
	    g_print ("GIF: gif comment: %s\n", buf);
#endif
	}
      return TRUE;
      break;
    case 0xf9:			/* Graphic Control Extension */
      str = "Graphic Control Extension";
      (void) GetDataBlock (fd, (unsigned char *) buf);
      Gif89.disposal = (buf[0] >> 2) & 0x7;
      Gif89.inputFlag = (buf[0] >> 1) & 0x1;
      Gif89.delayTime = LM_to_uint (buf[1], buf[2]);
      if ((buf[0] & 0x1) != 0)
	Gif89.transparent = buf[3];
      else
	Gif89.transparent = -1;

551
      while (GetDataBlock (fd, (unsigned char *) buf) > 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
552
553
554
555
556
557
558
559
560
561
562
563
564
	;
      return FALSE;
      break;
    default:
      str = (char *)buf;
      sprintf ((char *)buf, "UNKNOWN (0x%02x)", label);
      break;
    }

#ifdef GIFDEBUG
  g_print ("GIF: got a '%s'\n", str);
#endif

565
  while (GetDataBlock (fd, (unsigned char *) buf) > 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
    ;

  return FALSE;
}

int ZeroDataBlock = FALSE;

static int
GetDataBlock (FILE          *fd,
	      unsigned char *buf)
{
  unsigned char count;

  if (!ReadOK (fd, &count, 1))
    {
581
      g_message ("Error in getting DataBlock size");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
582
583
584
585
586
587
588
      return -1;
    }

  ZeroDataBlock = count == 0;

  if ((count != 0) && (!ReadOK (fd, buf, count)))
    {
589
      g_message ("Error in reading DataBlock");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
590
591
592
593
594
595
596
597
598
599
600
601
602
      return -1;
    }

  return count;
}

static int
GetCode (FILE *fd,
	 int   code_size,
	 int   flag)
{
  static unsigned char buf[280];
  static int curbit, lastbit, done, last_byte;
603
  int i, j, ret, count;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
604
605
606
607
608
609

  if (flag)
    {
      curbit = 0;
      lastbit = 0;
      done = FALSE;
Adam D. Moss's avatar
Adam D. Moss committed
610
      last_byte = 2;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
611
612
613
614
615
616
617
618
619
      return 0;
    }

  if ((curbit + code_size) >= lastbit)
    {
      if (done)
	{
	  if (curbit >= lastbit)
	    {
620
	      g_message ("Ran off the end of my bits");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
621
622
623
624
	      gimp_quit ();
	    }
	  return -1;
	}
625

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
626
627
628
      buf[0] = buf[last_byte - 2];
      buf[1] = buf[last_byte - 1];

629
      if ((count = GetDataBlock (fd, &buf[2])) <= 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
	done = TRUE;

      last_byte = 2 + count;
      curbit = (curbit - lastbit) + 16;
      lastbit = (2 + count) * 8;
    }

  ret = 0;
  for (i = curbit, j = 0; j < code_size; ++i, ++j)
    ret |= ((buf[i / 8] & (1 << (i % 8))) != 0) << j;

  curbit += code_size;

  return ret;
}

static int
647
LZWReadByte (FILE *fd,
648
	     int   just_reset_LZW,
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
649
650
651
652
653
654
655
656
	     int   input_code_size)
{
  static int fresh = FALSE;
  int code, incode;
  static int code_size, set_code_size;
  static int max_code, max_code_size;
  static int firstcode, oldcode;
  static int clear_code, end_code;
657
658
  static int table[2][(1 << MAX_LZW_BITS)];
  static int stack[(1 << (MAX_LZW_BITS)) * 2], *sp;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
659
660
  register int i;

661
  if (just_reset_LZW)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
662
    {
663
664
      if (input_code_size > MAX_LZW_BITS)
	{
665
	  g_message("Value out of range for code size (corrupted file?)");
666
667
668
	  return -1;
	}

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
669
670
671
672
673
674
675
676
677
678
679
      set_code_size = input_code_size;
      code_size = set_code_size + 1;
      clear_code = 1 << set_code_size;
      end_code = clear_code + 1;
      max_code_size = 2 * clear_code;
      max_code = clear_code + 2;

      GetCode (fd, 0, TRUE);

      fresh = TRUE;

680
681
      sp = stack;

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
682
683
684
685
686
      for (i = 0; i < clear_code; ++i)
	{
	  table[0][i] = 0;
	  table[1][i] = i;
	}
687
      for (; i < (1 << MAX_LZW_BITS); ++i)
688
689
690
691
	{
	  table[0][i] = 0;
	  table[1][i] = 0;
	}
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718

      return 0;
    }
  else if (fresh)
    {
      fresh = FALSE;
      do
	{
	  firstcode = oldcode =
	    GetCode (fd, code_size, FALSE);
	}
      while (firstcode == clear_code);
      return firstcode;
    }

  if (sp > stack)
    return *--sp;

  while ((code = GetCode (fd, code_size, FALSE)) >= 0)
    {
      if (code == clear_code)
	{
	  for (i = 0; i < clear_code; ++i)
	    {
	      table[0][i] = 0;
	      table[1][i] = i;
	    }
719
	  for (; i < (1 << MAX_LZW_BITS); ++i)
720
721
722
723
	    {
	      table[0][i] = 0;
	      table[1][i] = 0;
	    }
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
	  code_size = set_code_size + 1;
	  max_code_size = 2 * clear_code;
	  max_code = clear_code + 2;
	  sp = stack;
	  firstcode = oldcode =
	    GetCode (fd, code_size, FALSE);
	  return firstcode;
	}
      else if (code == end_code)
	{
	  int count;
	  unsigned char buf[260];

	  if (ZeroDataBlock)
	    return -2;

	  while ((count = GetDataBlock (fd, buf)) > 0)
	    ;

	  if (count != 0)
744
	    g_print ("GIF: missing EOD in data stream (common occurence)");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
	  return -2;
	}

      incode = code;

      if (code >= max_code)
	{
	  *sp++ = firstcode;
	  code = oldcode;
	}

      while (code >= clear_code)
	{
	  *sp++ = table[1][code];
	  if (code == table[0][code])
	    {
761
	      g_message ("Circular table entry.  Corrupt file.");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
762
763
764
765
766
767
768
	      gimp_quit ();
	    }
	  code = table[0][code];
	}

      *sp++ = firstcode = table[1][code];

769
      if ((code = max_code) < (1 << MAX_LZW_BITS))
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
770
771
772
773
774
	{
	  table[0][code] = oldcode;
	  table[1][code] = firstcode;
	  ++max_code;
	  if ((max_code >= max_code_size) &&
775
	      (max_code_size < (1 << MAX_LZW_BITS)))
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
	    {
	      max_code_size *= 2;
	      ++code_size;
	    }
	}

      oldcode = incode;

      if (sp > stack)
	return *--sp;
    }
  return code;
}

static gint32
791
792
793
794
795
796
797
798
799
800
801
802
803
ReadImage (FILE        *fd,
	   const gchar *filename,
	   gint         len,
	   gint         height,
	   CMap         cmap,
	   gint         ncols,
	   gint         format,
	   gint         interlace,
	   gint         number,
	   guint        leftpos,
	   guint        toppos,
	   guint        screenwidth,
	   guint        screenheight)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
804
{
805
  static gint32 image_ID   = -1;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
806
807
808
  static gint frame_number = 1;

  gint32 layer_ID;
Sven Neumann's avatar
Sven Neumann committed
809
810
  GimpPixelRgn pixel_rgn;
  GimpDrawable *drawable;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
811
812
813
814
815
816
  guchar *dest, *temp;
  guchar c;
  gint xpos = 0, ypos = 0, pass = 0;
  gint cur_progress, max_progress;
  gint v;
  gint i, j;
817
  gchar *framename;
818
  gchar *framename_ptr;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
819
820
821
  gboolean alpha_frame = FALSE;
  static int previous_disposal;

822
823
824
825
826
827
  /* Guard against bogus frame size */
  if (len < 1 || height < 1)
    {
      g_message ("Bogus frame dimensions");
      return -1;
    }
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
828
829
830
831
832
833

  /*
   **  Initialize the Compression routines
   */
  if (!ReadOK (fd, &c, 1))
    {
834
      g_message ("EOF / read error on image data");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
835
836
837
      return -1;
    }

838
  if (LZWReadByte (fd, TRUE, c) < 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
839
    {
840
      g_message ("Error while reading");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
841
842
843
844
845
      return -1;
    }

  if (frame_number == 1 )
    {
846
847
848
849
850
851
852
      /* Guard against bogus logical screen size values */
      if (screenwidth == 0)
	screenwidth = len;

      if (screenheight == 0)
	screenheight = height;

Sven Neumann's avatar
Sven Neumann committed
853
      image_ID = gimp_image_new (screenwidth, screenheight, GIMP_INDEXED);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
854
855
856
857
858
859
860
861
862
      gimp_image_set_filename (image_ID, filename);

      for (i = 0, j = 0; i < ncols; i++)
	{
	  used_cmap[0][i] = gimp_cmap[j++] = cmap[0][i];
	  used_cmap[1][i] = gimp_cmap[j++] = cmap[1][i];
	  used_cmap[2][i] = gimp_cmap[j++] = cmap[2][i];
	}

863
      gimp_image_set_colormap (image_ID, gimp_cmap, ncols);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
864
865

      if (Gif89.delayTime < 0)
866
	framename = g_strdup (_("Background"));
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
867
      else
868
869
	framename = g_strdup_printf (_("Background (%d%s)"),
                                     10 * Gif89.delayTime, "ms");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
870
871
872
873
874
875
876

      previous_disposal = Gif89.disposal;

      if (Gif89.transparent == -1)
	{
	  layer_ID = gimp_layer_new (image_ID, framename,
				     len, height,
Sven Neumann's avatar
Sven Neumann committed
877
				     GIMP_INDEXED_IMAGE, 100, GIMP_NORMAL_MODE);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
878
879
880
881
882
	}
      else
	{
	  layer_ID = gimp_layer_new (image_ID, framename,
				     len, height,
Sven Neumann's avatar
Sven Neumann committed
883
				     GIMP_INDEXEDA_IMAGE, 100, GIMP_NORMAL_MODE);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
884
885
	  alpha_frame=TRUE;
	}
886
887

      g_free (framename);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    }
  else /* NOT FIRST FRAME */
    {
      /* If the colourmap is now different, we have to promote to
	 RGB! */
      if (!promote_to_rgb)
	{
	  for (i=0;i<ncols;i++)
	    {
	      if (
		  (used_cmap[0][i] != cmap[0][i]) ||
		  (used_cmap[1][i] != cmap[1][i]) ||
		  (used_cmap[2][i] != cmap[2][i])
		  )
		{ /* Everything is RGB(A) from now on... sigh. */
		  promote_to_rgb = TRUE;
904

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
905
906
907
908
		  /* Promote everything we have so far into RGB(A) */
#ifdef GIFDEBUG
		  g_print ("GIF: Promoting image to RGB...\n");
#endif
909
		  gimp_image_convert_rgb (image_ID);
910

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
911
912
913
914
915
916
		  break;
		}
	    }
	}

      if (Gif89.delayTime < 0)
917
	framename = g_strdup_printf (_("Frame %d"), frame_number);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
918
      else
919
920
	framename = g_strdup_printf (_("Frame %d (%d%s)"),
                                     frame_number, 10 * Gif89.delayTime, "ms");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
921
922
923

      switch (previous_disposal)
	{
924
	case 0x00:
925
	  break; /* 'don't care' */
926
	case 0x01:
927
928
929
930
	  framename_ptr = framename;
	  framename = g_strconcat (framename, " (combine)", NULL);
	  g_free (framename_ptr);
	  break;
931
	case 0x02:
932
	  framename_ptr = framename;
933
	  framename = g_strconcat (framename, " (replace)", NULL);
934
935
	  g_free (framename_ptr);
	  break;
936
937
938
	case 0x03:  /* Rarely-used, and unhandled by many
		       loaders/players (including GIMP: we treat as
		       'combine' mode). */
939
	  framename_ptr = framename;
940
	  framename = g_strconcat (framename, " (combine) (!)", NULL);
941
942
	  g_free (framename_ptr);
	  break;
943
	case 0x04: /* I've seen a composite of this type. stvo_online_banner2.gif */
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
944
	case 0x05:
945
	case 0x06: /* I've seen a composite of this type. bn31.Gif */
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
946
	case 0x07:
947
948
949
	  framename_ptr = framename;
	  framename = g_strconcat (framename, " (unknown disposal)", NULL);
	  g_free (framename_ptr);
950
951
952
953
 	  g_message (_("GIF: Undocumented GIF composite type %d is "
 		       "not handled.  Animation might not play or "
 		       "re-save perfectly."),
		     previous_disposal);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
954
	  break;
955
	default:
956
	  g_message ("Disposal word got corrupted.  Bug.");
957
	  break;
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
958
959
960
	}
      previous_disposal = Gif89.disposal;

961
      layer_ID = gimp_layer_new (image_ID, framename,
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
962
				 len, height,
963
964
				 promote_to_rgb ?
                                 GIMP_RGBA_IMAGE : GIMP_INDEXEDA_IMAGE,
Sven Neumann's avatar
Sven Neumann committed
965
				 100, GIMP_NORMAL_MODE);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
966
      alpha_frame = TRUE;
967
      g_free (framename);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
    }

  frame_number++;

  gimp_image_add_layer (image_ID, layer_ID, 0);
  gimp_layer_translate (layer_ID, (gint)leftpos, (gint)toppos);

  drawable = gimp_drawable_get (layer_ID);

  cur_progress = 0;
  max_progress = height;

  if (alpha_frame)
    dest = (guchar *) g_malloc (len * height *
				(promote_to_rgb ? 4 : 2));
  else
    dest = (guchar *) g_malloc (len * height);

  if (verbose)
987
988
    g_print ("GIF: reading %d by %d%s GIF image, ncols=%d\n",
	     len, height, interlace ? " interlaced" : "", ncols);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
989
990
991

  if (!alpha_frame && promote_to_rgb)
    {
992
993
994
      /* I don't see how one would easily construct a GIF in which
 	 this could happen, but it's a mad mad world. */
      g_message ("Ouch!  Can't handle non-alpha RGB frames.\n"
995
996
                 "Please file a bug report in GIMP's bugzilla.");
      gimp_quit ();
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
997
998
    }

999
  while ((v = LZWReadByte (fd, FALSE, c)) >= 0)
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
    {
      if (alpha_frame)
	{
	  if (((guchar)v > highest_used_index) && !(v == Gif89.transparent))
	    highest_used_index = (guchar)v;

	  if (promote_to_rgb)
	    {
	      temp = dest + ( (ypos * len) + xpos ) * 4;
	      *(temp  ) = (guchar) cmap[0][v];
	      *(temp+1) = (guchar) cmap[1][v];
	      *(temp+2) = (guchar) cmap[2][v];
	      *(temp+3) = (guchar) ((v == Gif89.transparent) ? 0 : 255);
	    }
	  else
	    {
	      temp = dest + ( (ypos * len) + xpos ) * 2;
	      *temp = (guchar) v;
	      *(temp+1) = (guchar) ((v == Gif89.transparent) ? 0 : 255);
	    }
	}
      else
	{
	  if ((guchar)v > highest_used_index)
	    highest_used_index = (guchar)v;

	  temp = dest + (ypos * len) + xpos;
	  *temp = (guchar) v;
	}

      xpos++;
      if (xpos == len)
	{
	  xpos = 0;
	  if (interlace)
	    {
	      switch (pass)
		{
		case 0:
		case 1:
		  ypos += 8;
		  break;
		case 2:
		  ypos += 4;
		  break;
		case 3:
		  ypos += 2;
		  break;
		}

	      if (ypos >= height)
		{
		  pass++;
		  switch (pass)
		    {
		    case 1:
		      ypos = 4;
		      break;
		    case 2:
		      ypos = 2;
		      break;
		    case 3:
		      ypos = 1;
		      break;
		    default:
		      goto fini;
		    }
		}
	    }
	  else
	    {
	      ypos++;
	    }

1074
1075
1076
          cur_progress++;
          if ((cur_progress % 16) == 0)
            gimp_progress_update ((double) cur_progress / (double) max_progress);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
1077
	}
1078

Adam D. Moss's avatar
hooray    
Adam D. Moss committed
1079
1080
1081
1082
1083
      if (ypos >= height)
	break;
    }

fini:
1084
  if (LZWReadByte (fd, FALSE, c) >= 0)
1085
    g_print ("GIF: too much input data, ignoring extra...\n");
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
1086

1087
1088
1089
1090
  gimp_pixel_rgn_init (&pixel_rgn, drawable,
                       0, 0, drawable->width, drawable->height, TRUE, FALSE);
  gimp_pixel_rgn_set_rect (&pixel_rgn, dest,
                           0, 0, drawable->width, drawable->height);
Adam D. Moss's avatar
hooray    
Adam D. Moss committed
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

  g_free (dest);

  gimp_drawable_flush (drawable);
  gimp_drawable_detach (drawable);

  return image_ID;
}



/* ppmtogif.c - read a portable pixmap and produce a GIF file
**
** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>.A
** Lempel-Zim compression based on "compress".
**
** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl>
**
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
**
** The Graphics Interchange Format(c) is the Copyright property of
** CompuServe Incorporated.  GIF(sm) is a Service Mark property of
** CompuServe Incorporated.
*/

#define MAXCOLORS 256

/*
 * Pointer to function returning an int
 */
typedef int (*ifunptr) (int, int);

/*
 * a code_int must be able to hold 2**BITS values of type int, and also -1
 */
typedef int code_int;

#ifdef SIGNED_COMPARE_SLOW
typedef unsigned long int count_int;
typedef unsigned short int count_short;
#else /*SIGNED_COMPARE_SLOW */
typedef long int count_int;
#endif /*SIGNED_COMPARE_SLOW */



int rowstride;
guchar *pixels;
int cur_progress;
int max_progress;




/* public */



/***************************************************************************
 *
 *  GIFCOMPR.C       - GIF Image compression routines
 *
 *  Lempel-Ziv compression based on 'compress'.  GIF modifications by
 *  David Rowley (mgardi@watdcsu.waterloo.edu)
 *
 ***************************************************************************/

/*
 * General DEFINEs
 */

#define GIF_BITS    12

#define HSIZE  5003		/* 80% occupancy */

#ifdef NO_UCHAR
typedef char char_type;
#else /*NO_UCHAR */
typedef unsigned char char_type;
#endif /*NO_UCHAR */

/*

 * GIF Image compression - modified 'compress'
 *
 * Based on: compress.c - File compression ala IEEE Computer, June 1984.
 *
 * By Authors:  Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
 *              Jim McKie               (decvax!mcvax!jim)
 *              Steve Davies            (decvax!vax135!petsd!peora!srd)
 *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
 *              James A. Woods          (decvax!ihnp4!ames!jaw)
 *              Joe Orost               (decvax!vax135!petsd!joe)
 *
 */

#define ARGVAL() (*++(*argv) || (--argc && *++argv))

#ifdef COMPATIBLE		/* But wrong! */
#define MAXCODE(Mn_bits)        ((code_int) 1 << (Mn_bits) - 1)
#else /*COMPATIBLE */
#define MAXCODE(Mn_bits)        (((code_int) 1 << (Mn_bits)) - 1)
#endif /*COMPATIBLE */


const code_int hsize = HSIZE;	/* the original reason for this being
				   variable was "for dynamic table sizing",
				   but since it was never actually changed
				   I made it const   --Adam. */


/* The End */