Debian Codegraph @

pTk/mTk/additions/imgGIF.c

raw
1 /*
2 * imgGIF.c --
3 *
4 * A photo image file handler for GIF files. Reads 87a and 89a GIF
5 * files. At present, there only is a file write function. GIF images may be
6 * read using the -data option of the photo image. The data may be
7 * given as a binary string in a Tcl_Obj or by representing
8 * the data as BASE64 encoded ascii. Derived from the giftoppm code
9 * found in the pbmplus package and tkImgFmtPPM.c in the tk4.0b2
10 * distribution.
11 *
12 * Copyright (c) Reed Wade ([email protected]), University of Tennessee
13 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
14 * Copyright (c) 1997 Australian National University
15 *
16 * See the file "license.terms" for information on usage and redistribution
17 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
18 *
19 * This file also contains code from the giftoppm program, which is
20 * copyrighted as follows:
21 *
22 * +-------------------------------------------------------------------+
23 * | Copyright 1990, David Koblas. |
24 * | Permission to use, copy, modify, and distribute this software |
25 * | and its documentation for any purpose and without fee is hereby |
26 * | granted, provided that the above copyright notice appear in all |
27 * | copies and that both that copyright notice and this permission |
28 * | notice appear in supporting documentation. This software is |
29 * | provided "as is" without express or implied warranty. |
30 * +-------------------------------------------------------------------+
31 *
32 * RCS: @(#) $Id: tkImgGIF.c,v 1.14 2000/03/30 19:44:41 ericm Exp $
33 */
34
35 #include "tk.h"
36 #include "tkVMacro.h"
37 #include "imgInt.h"
38 #include <string.h>
39 #include <stdlib.h>
40
41 /*
42 * Non-ASCII encoding support:
43 * Most data in a GIF image is binary and is treated as such. However,
44 * a few key bits are stashed in ASCII. If we try to compare those pieces
45 * to the char they represent, it will fail on any non-ASCII (eg, EBCDIC)
46 * system. To accomodate these systems, we test against the numeric value
47 * of the ASCII characters instead of the characters themselves. This is
48 * encoding independant.
49 */
50
51 # define GIF87a "\x47\x49\x46\x38\x37\x61" /* ASCII GIF87a */
52 # define GIF89a "\x47\x49\x46\x38\x39\x61" /* ASCII GIF89a */
53 # define GIF_TERMINATOR 0x3b /* ASCII ; */
54 # define GIF_EXTENSION 0x21 /* ASCII ! */
55 # define GIF_START 0x2c /* ASCII , */
56
57 /*
58 * The format record for the GIF file format:
59 */
60
61 static int ChanMatchGIF _ANSI_ARGS_((Tcl_Channel chan, struct Tcl_Obj *fileName,
62 struct Tcl_Obj *format, int *widthPtr, int *heightPtr, Tcl_Interp *interp));
63 static int ObjMatchGIF _ANSI_ARGS_((struct Tcl_Obj *data,
64 struct Tcl_Obj *format, int *widthPtr, int *heightPtr, Tcl_Interp *interp));
65 static int ChanReadGIF _ANSI_ARGS_((Tcl_Interp *interp,
66 Tcl_Channel chan, struct Tcl_Obj *fileName, struct Tcl_Obj *format,
67 Tk_PhotoHandle imageHandle, int destX, int destY,
68 int width, int height, int srcX, int srcY));
69 static int ObjReadGIF _ANSI_ARGS_((Tcl_Interp *interp,
70 Tcl_Obj *data, Tcl_Obj *format,
71 Tk_PhotoHandle imageHandle, int destX, int destY,
72 int width, int height, int srcX, int srcY));
73 static int ChanWriteGIF _ANSI_ARGS_(( Tcl_Interp *interp,
74 char *filename, Tcl_Obj *format,
75 Tk_PhotoImageBlock *blockPtr));
76 static int StringWriteGIF _ANSI_ARGS_((Tcl_Interp *interp,
77 Tcl_Obj *format, Tk_PhotoImageBlock *blockPtr));
78 static int CommonReadGIF _ANSI_ARGS_((Tcl_Interp *interp,
79 MFile *handle, CONST char *fileName, Tcl_Obj *format,
80 Tk_PhotoHandle imageHandle, int destX, int destY,
81 int width, int height, int srcX, int srcY));
82 static int CommonWriteGIF _ANSI_ARGS_((Tcl_Interp *interp,
83 MFile *handle, Tcl_Obj *format,
84 Tk_PhotoImageBlock *blockPtr));
85
86 Tk_PhotoImageFormat imgFmtGIF = {
87 "gif", /* name */
88 ChanMatchGIF, /* fileMatchProc */
89 ObjMatchGIF, /* stringMatchProc */
90 ChanReadGIF, /* fileReadProc */
91 ObjReadGIF, /* stringReadProc */
92 ChanWriteGIF, /* fileWriteProc */
93 StringWriteGIF, /* stringWriteProc */
94 };
95
96 #define INTERLACE 0x40
97 #define LOCALCOLORMAP 0x80
98 #define BitSet(byte, bit) (((byte) & (bit)) == (bit))
99 #define MAXCOLORMAPSIZE 256
100 #define CM_RED 0
101 #define CM_GREEN 1
102 #define CM_BLUE 2
103 #define CM_ALPHA 3
104 #define MAX_LWZ_BITS 12
105 #define LM_to_uint(a,b) (((b)<<8)|(a))
106 #define ReadOK(handle,buffer,len) (ImgRead(handle, buffer, len) == len)
107
108 /*
109 * Prototypes for local procedures defined in this file:
110 */
111
112 static int DoExtension _ANSI_ARGS_((MFile *handle, int label,
113 int *transparent));
114 static int GetCode _ANSI_ARGS_((MFile *handle, int code_size,
115 int flag));
116 static int GetDataBlock _ANSI_ARGS_((MFile *handle,
117 unsigned char *buf));
118 static int ReadColorMap _ANSI_ARGS_((MFile *handle, int number,
119 unsigned char buffer[MAXCOLORMAPSIZE][4]));
120 static int ReadGIFHeader _ANSI_ARGS_((MFile *handle,
121 int *widthPtr, int *heightPtr));
122 static int ReadImage _ANSI_ARGS_((Tcl_Interp *interp,
123 char *imagePtr, MFile *handle, int len, int rows,
124 unsigned char cmap[MAXCOLORMAPSIZE][4],
125 int width, int height, int srcX, int srcY,
126 int interlace, int transparent));
127
128
129 /*
130 *----------------------------------------------------------------------
131 *
132 * ChanMatchGIF --
133 *
134 * This procedure is invoked by the photo image type to see if
135 * a channel contains image data in GIF format.
136 *
137 * Results:
138 * The return value is 1 if the first characters in channel chan
139 * look like GIF data, and 0 otherwise.
140 *
141 * Side effects:
142 * The access position in f may change.
143 *
144 *----------------------------------------------------------------------
145 */
146
147 static int
148 ChanMatchGIF(chan, fileName, format, widthPtr, heightPtr, interp)
149 Tcl_Channel chan; /* The image channel, open for reading. */
150 struct Tcl_Obj *fileName; /* The name of the image file. */
151 struct Tcl_Obj *format; /* User-specified format object, or NULL. */
152 int *widthPtr, *heightPtr; /* The dimensions of the image are
153 * returned here if the file is a valid
154 * raw GIF file. */
155 Tcl_Interp *interp;
156 {
157 MFile handle;
158
159 ImgFixChanMatchProc(&interp, &chan, &fileName, &format, &widthPtr, &heightPtr);
160
161 handle.data = (char *) chan;
162 handle.state = IMG_CHAN;
163
164 return ReadGIFHeader(&handle, widthPtr, heightPtr);
165 }
166
167 /*
168 *----------------------------------------------------------------------
169 *
170 * ChanReadGIF --
171 *
172 * This procedure is called by the photo image type to read
173 * GIF format data from a channel and write it into a given
174 * photo image.
175 *
176 * Results:
177 * A standard TCL completion code. If TCL_ERROR is returned
178 * then an error message is left in the interp's result.
179 *
180 * Side effects:
181 * The access position in channel chan is changed, and new data is
182 * added to the image given by imageHandle.
183 *
184 *----------------------------------------------------------------------
185 */
186
187 static int
188 ChanReadGIF(interp, chan, fileName, format, imageHandle, destX, destY,
189 width, height, srcX, srcY)
190 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
191 Tcl_Channel chan; /* The image channel, open for reading. */
192 struct Tcl_Obj *fileName; /* The name of the image file. */
193 struct Tcl_Obj *format; /* User-specified format object, or NULL. */
194 Tk_PhotoHandle imageHandle; /* The photo image to write into. */
195 int destX, destY; /* Coordinates of top-left pixel in
196 * photo image to be written to. */
197 int width, height; /* Dimensions of block of photo image to
198 * be written to. */
199 int srcX, srcY; /* Coordinates of top-left pixel to be used
200 * in image being read. */
201 {
202 MFile handle;
203 int nBytes;
204
205 handle.data = (char *) chan;
206 handle.state = IMG_CHAN;
207
208 return CommonReadGIF(interp, &handle, Tcl_GetStringFromObj(fileName,&nBytes), format,
209 imageHandle, destX, destY, width, height, srcX, srcY);
210 }
211
212 /*
213 *----------------------------------------------------------------------
214 *
215 * CommonReadGIF --
216 *
217 * This procedure is called by the photo image type to read
218 * GIF format data from a file and write it into a given
219 * photo image.
220 *
221 * Results:
222 * A standard TCL completion code. If TCL_ERROR is returned
223 * then an error message is left in the interp's result.
224 *
225 * Side effects:
226 * The access position in file f is changed, and new data is
227 * added to the image given by imageHandle.
228 *
229 *----------------------------------------------------------------------
230 */
231
232 typedef struct myblock {
233 Tk_PhotoImageBlock ck;
234 int dummy; /* extra space for offset[3], if not included already
235 in Tk_PhotoImageBlock */
236 } myblock;
237
238 #define block bl.ck
239
240 static int
241 CommonReadGIF(interp, handle, fileName, format, imageHandle, destX, destY,
242 width, height, srcX, srcY)
243 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
244 MFile *handle; /* The image file, open for reading. */
245 CONST char *fileName; /* The name of the image file. */
246 Tcl_Obj *format; /* User-specified format object, or NULL. */
247 Tk_PhotoHandle imageHandle; /* The photo image to write into. */
248 int destX, destY; /* Coordinates of top-left pixel in
249 * photo image to be written to. */
250 int width, height; /* Dimensions of block of photo image to
251 * be written to. */
252 int srcX, srcY; /* Coordinates of top-left pixel to be used
253 * in image being read. */
254 {
255 int fileWidth, fileHeight;
256 int nBytes, index = 0, objc = 0;
257 Tcl_Obj **objv = NULL;
258 myblock bl;
259 unsigned char buf[100];
260 unsigned char *trashBuffer = NULL;
261 int bitPixel;
262 unsigned int colorResolution;
263 unsigned int background;
264 unsigned int aspectRatio;
265 unsigned char colorMap[MAXCOLORMAPSIZE][4];
266 int transparent = -1;
267
268 if (ImgListObjGetElements(interp, format, &objc, &objv) != TCL_OK) {
269 return TCL_ERROR;
270 }
271 if (objc > 1) {
272 char *c = Tcl_GetStringFromObj(objv[1], &nBytes);
273 if ((objc > 3) || ((objc == 3) && ((c[0] != '-') ||
274 (c[1] != 'i') || strncmp(c, "-index", strlen(c))))) {
275 Tcl_AppendResult(interp, "invalid format: \"",
276 ImgGetStringFromObj(format, NULL), "\"", (char *) NULL);
277 return TCL_ERROR;
278 }
279 }
280 if (objc > 1) {
281 if (Tcl_GetIntFromObj(interp, objv[objc-1], &index) != TCL_OK) {
282 return TCL_ERROR;
283 }
284 }
285
286 if (!ReadGIFHeader(handle, &fileWidth, &fileHeight)) {
287 Tcl_AppendResult(interp, "couldn't read GIF header from file \"",
288 fileName, "\"", NULL);
289 return TCL_ERROR;
290 }
291 if ((fileWidth <= 0) || (fileHeight <= 0)) {
292 Tcl_AppendResult(interp, "GIF image file \"", fileName,
293 "\" has dimension(s) <= 0", (char *) NULL);
294 return TCL_ERROR;
295 }
296
297 if (ImgRead(handle, buf, 3) != 3) {
298 return TCL_OK;
299 }
300
301 bitPixel = 2<<(buf[0]&0x07);
302 colorResolution = ((((unsigned int) buf[0]&0x70)>>3)+1);
303 background = buf[1];
304 aspectRatio = buf[2];
305
306 if (BitSet(buf[0], LOCALCOLORMAP)) { /* Global Colormap */
307 if (!ReadColorMap(handle, bitPixel, colorMap)) {
308 Tcl_AppendResult(interp, "error reading color map",
309 (char *) NULL);
310 return TCL_ERROR;
311 }
312 }
313
314 if ((srcX + width) > fileWidth) {
315 width = fileWidth - srcX;
316 }
317 if ((srcY + height) > fileHeight) {
318 height = fileHeight - srcY;
319 }
320 if ((width <= 0) || (height <= 0)
321 || (srcX >= fileWidth) || (srcY >= fileHeight)) {
322 return TCL_OK;
323 }
324
325 Tk_PhotoExpand(imageHandle, destX + width, destY + height);
326
327 block.pixelSize = 4;
328 block.offset[0] = 0;
329 block.offset[1] = 1;
330 block.offset[2] = 2;
331 block.offset[3] = 3;
332 block.pixelPtr = NULL;
333
334 while (1) {
335 if (ImgRead(handle, buf, 1) != 1) {
336 /*
337 * Premature end of image. We should really notify
338 * the user, but for now just show garbage.
339 */
340
341 break;
342 }
343
344 if (buf[0] == GIF_TERMINATOR) {
345 /*
346 * GIF terminator.
347 */
348
349 Tcl_AppendResult(interp,"no image data for this index",
350 (char *) NULL);
351 goto error;
352 }
353
354 if (buf[0] == GIF_EXTENSION) {
355 /*
356 * This is a GIF extension.
357 */
358
359 if (ImgRead(handle, buf, 1) != 1) {
360 Tcl_AppendResult(interp,
361 "error reading extension function code in GIF image",
362 (char *) NULL);
363 goto error;
364 }
365 if (DoExtension(handle, buf[0], &transparent) < 0) {
366 Tcl_AppendResult(interp, "error reading extension in GIF image",
367 (char *) NULL);
368 goto error;
369 }
370 continue;
371 }
372
373 if (buf[0] != GIF_START) {
374 /*
375 * Not a valid start character; ignore it.
376 */
377 continue;
378 }
379
380 if (ImgRead(handle, buf, 9) != 9) {
381 Tcl_AppendResult(interp,
382 "couldn't read left/top/width/height in GIF image",
383 (char *) NULL);
384 goto error;
385 }
386
387 fileWidth = LM_to_uint(buf[4],buf[5]);
388 fileHeight = LM_to_uint(buf[6],buf[7]);
389
390 bitPixel = 2<<(buf[8]&0x07);
391
392 if (index--) {
393 /* this is not the image we want to read: skip it. */
394 if (BitSet(buf[8], LOCALCOLORMAP)) {
395 if (!ReadColorMap(handle, bitPixel, colorMap)) {
396 Tcl_AppendResult(interp,
397 "error reading color map", (char *) NULL);
398 goto error;
399 }
400 }
401
402 /* If we've not yet allocated a trash buffer, do so now */
403 if (trashBuffer == NULL) {
404 nBytes = fileWidth * fileHeight * 3;
405 trashBuffer =
406 (unsigned char *) ckalloc((unsigned int) nBytes);
407 }
408
409 /*
410 * Slurp! Process the data for this image and stuff it in a
411 * trash buffer.
412 *
413 * Yes, it might be more efficient here to *not* store the data
414 * (we're just going to throw it away later). However, I elected
415 * to implement it this way for good reasons. First, I wanted to
416 * avoid duplicating the (fairly complex) LWZ decoder in ReadImage.
417 * Fine, you say, why didn't you just modify it to allow the use of
418 * a NULL specifier for the output buffer? I tried that, but it
419 * negatively impacted the performance of what I think will be the
420 * common case: reading the first image in the file. Rather than
421 * marginally improve the speed of the less frequent case, I chose
422 * to maintain high performance for the common case.
423 */
424 if (ReadImage(interp, trashBuffer, handle, fileWidth,
425 fileHeight, colorMap, 0, 0, 0, 0, 0, -1) != TCL_OK) {
426 goto error;
427 }
428 continue;
429 }
430
431 /* If a trash buffer has been allocated, free it now */
432 if (trashBuffer != NULL) {
433 ckfree((char *)trashBuffer);
434 trashBuffer = NULL;
435 }
436 if (BitSet(buf[8], LOCALCOLORMAP)) {
437 if (!ReadColorMap(handle, bitPixel, colorMap)) {
438 Tcl_AppendResult(interp, "error reading color map",
439 (char *) NULL);
440 goto error;
441 }
442 }
443
444 index = LM_to_uint(buf[0],buf[1]);
445 srcX -= index;
446 if (srcX<0) {
447 destX -= srcX; width += srcX;
448 srcX = 0;
449 }
450
451 if (width > fileWidth) {
452 width = fileWidth;
453 }
454
455 index = LM_to_uint(buf[2],buf[3]);
456 srcY -= index;
457 if (index > srcY) {
458 destY -= srcY; height += srcY;
459 srcY = 0;
460 }
461 if (height > fileHeight) {
462 height = fileHeight;
463 }
464
465 if ((width <= 0) || (height <= 0)) {
466 block.pixelPtr = 0;
467 goto noerror;
468 }
469
470 block.width = width;
471 block.height = height;
472 block.pixelSize = (transparent>=0)?4:3;
473 block.pitch = block.pixelSize * width;
474 nBytes = block.pitch * height;
475 block.pixelPtr = (unsigned char *) ckalloc((unsigned) nBytes);
476
477 if (ReadImage(interp, (char *) block.pixelPtr, handle, width, height,
478 colorMap, fileWidth, fileHeight, srcX, srcY,
479 BitSet(buf[8], INTERLACE), transparent) != TCL_OK) {
480 goto error;
481 }
482 break;
483 }
484
485 if (transparent == -1) {
486 Tk_PhotoPutBlock(imageHandle, &block, destX, destY, width, height, TK_PHOTO_COMPOSITE_SET);
487 } else {
488 ImgPhotoPutBlock(imageHandle, &block, destX, destY, width, height);
489 }
490
491 noerror:
492 if (block.pixelPtr) {
493 ckfree((char *) block.pixelPtr);
494 }
495 return TCL_OK;
496
497 error:
498 if (block.pixelPtr) {
499 ckfree((char *) block.pixelPtr);
500 }
501 return TCL_ERROR;
502
503 }
504
505 /*
506 *----------------------------------------------------------------------
507 *
508 * ObjMatchGIF --
509 *
510 * This procedure is invoked by the photo image type to see if
511 * an object contains image data in GIF format.
512 *
513 * Results:
514 * The return value is 1 if the first characters in the object are
515 * like GIF data, and 0 otherwise.
516 *
517 * Side effects:
518 * the size of the image is placed in widthPtr and heightPtr.
519 *
520 *----------------------------------------------------------------------
521 */
522
523 static int
524 ObjMatchGIF(data, format, widthPtr, heightPtr, interp)
525 Tcl_Obj *data; /* the object containing the image data */
526 Tcl_Obj *format; /* the image format object */
527 int *widthPtr; /* where to put the image width */
528 int *heightPtr; /* where to put the image height */
529 Tcl_Interp *interp; /* interpreter */
530 {
531 MFile handle;
532
533 ImgFixObjMatchProc(&interp, &data, &format, &widthPtr, &heightPtr);
534
535 if (!ImgReadInit(data, 'G', &handle)) {
536 return 0;
537 }
538 return ReadGIFHeader(&handle, widthPtr, heightPtr);
539 }
540
541 /*
542 *----------------------------------------------------------------------
543 *
544 * ObjReadGIF --
545 *
546 * This procedure is called by the photo image type to read
547 * GIF format data from a base64 encoded string, and give it to
548 * the photo image.
549 *
550 * Results:
551 * A standard TCL completion code. If TCL_ERROR is returned
552 * then an error message is left in the interp's result.
553 *
554 * Side effects:
555 * new data is added to the image given by imageHandle. This
556 * procedure calls FileReadGif by redefining the operation of
557 * fprintf temporarily.
558 *
559 *----------------------------------------------------------------------
560 */
561
562 static int
563 ObjReadGIF(interp, data, format, imageHandle,
564 destX, destY, width, height, srcX, srcY)
565 Tcl_Interp *interp; /* interpreter for reporting errors in */
566 Tcl_Obj *data; /* object containing the image */
567 Tcl_Obj *format; /* format object if any */
568 Tk_PhotoHandle imageHandle; /* the image to write this data into */
569 int destX, destY; /* The rectangular region of the */
570 int width, height; /* image to copy */
571 int srcX, srcY;
572 {
573 MFile handle;
574
575 ImgReadInit(data, 'G', &handle);
576 return CommonReadGIF(interp, &handle, "inline data", format,
577 imageHandle, destX, destY, width, height, srcX, srcY);
578 }
579
580 /*
581 *----------------------------------------------------------------------
582 *
583 * ReadGIFHeader --
584 *
585 * This procedure reads the GIF header from the beginning of a
586 * GIF file and returns the dimensions of the image.
587 *
588 * Results:
589 * The return value is 1 if file "f" appears to start with
590 * a valid GIF header, 0 otherwise. If the header is valid,
591 * then *widthPtr and *heightPtr are modified to hold the
592 * dimensions of the image.
593 *
594 * Side effects:
595 * The access position in f advances.
596 *
597 *----------------------------------------------------------------------
598 */
599
600 static int
601 ReadGIFHeader(handle, widthPtr, heightPtr)
602 MFile *handle; /* Image file to read the header from */
603 int *widthPtr, *heightPtr; /* The dimensions of the image are
604 * returned here. */
605 {
606 unsigned char buf[7];
607
608 if ((ImgRead(handle, buf, 6) != 6)
609 || ((strncmp(GIF87a, (char *) buf, 6) != 0)
610 && (strncmp(GIF89a, (char *) buf, 6) != 0))) {
611 return 0;
612 }
613
614 if (ImgRead(handle, buf, 4) != 4) {
615 return 0;
616 }
617
618 *widthPtr = LM_to_uint(buf[0],buf[1]);
619 *heightPtr = LM_to_uint(buf[2],buf[3]);
620 return 1;
621 }
622
623 /*
624 *-----------------------------------------------------------------
625 * The code below is copied from the giftoppm program and modified
626 * just slightly.
627 *-----------------------------------------------------------------
628 */
629
630 static int
631 ReadColorMap(handle, number, buffer)
632 MFile *handle;
633 int number;
634 unsigned char buffer[MAXCOLORMAPSIZE][4];
635 {
636 int i;
637 unsigned char rgb[3];
638
639 for (i = 0; i < number; ++i) {
640 if (! ReadOK(handle, rgb, sizeof(rgb))) {
641 return 0;
642 }
643
644 if (buffer) {
645 buffer[i][CM_RED] = rgb[0] ;
646 buffer[i][CM_GREEN] = rgb[1] ;
647 buffer[i][CM_BLUE] = rgb[2] ;
648 buffer[i][CM_ALPHA] = 255 ;
649 }
650 }
651 return 1;
652 }
653
654
655
656 static int
657 DoExtension(handle, label, transparent)
658 MFile *handle;
659 int label;
660 int *transparent;
661 {
662 static unsigned char buf[256];
663 int count;
664
665 switch (label) {
666 case 0x01: /* Plain Text Extension */
667 break;
668
669 case 0xff: /* Application Extension */
670 break;
671
672 case 0xfe: /* Comment Extension */
673 do {
674 count = GetDataBlock(handle, (unsigned char*) buf);
675 } while (count > 0);
676 return count;
677
678 case 0xf9: /* Graphic Control Extension */
679 count = GetDataBlock(handle, (unsigned char*) buf);
680 if (count < 0) {
681 return 1;
682 }
683 if ((buf[0] & 0x1) != 0) {
684 *transparent = buf[3];
685 }
686
687 do {
688 count = GetDataBlock(handle, (unsigned char*) buf);
689 } while (count > 0);
690 return count;
691 }
692
693 do {
694 count = GetDataBlock(handle, (unsigned char*) buf);
695 } while (count > 0);
696 return count;
697 }
698
699 static int ZeroDataBlock = 0;
700
701 static int
702 GetDataBlock(handle, buf)
703 MFile *handle;
704 unsigned char *buf;
705 {
706 unsigned char count;
707
708 if (! ReadOK(handle,&count,1)) {
709 return -1;
710 }
711
712 ZeroDataBlock = count == 0;
713
714 if ((count != 0) && (! ReadOK(handle, buf, count))) {
715 return -1;
716 }
717
718 return count;
719 }
720
721
722
723 /*
724 *----------------------------------------------------------------------
725 *
726 * ReadImage --
727 *
728 * Process a GIF image from a given source, with a given height,
729 * width, transparency, etc.
730 *
731 * This code is based on the code found in the ImageMagick GIF decoder,
732 * which is (c) 2000 ImageMagick Studio.
733 *
734 * Some thoughts on our implementation:
735 * It sure would be nice if ReadImage didn't take 11 parameters! I think
736 * that if we were smarter, we could avoid doing that.
737 *
738 * Possible further optimizations: we could pull the GetCode function
739 * directly into ReadImage, which would improve our speed.
740 *
741 * Results:
742 * Processes a GIF image and loads the pixel data into a memory array.
743 *
744 * Side effects:
745 * None.
746 *
747 *----------------------------------------------------------------------
748 */
749
750 static int
751 ReadImage(interp, imagePtr, handle, len, rows, cmap,
752 width, height, srcX, srcY, interlace, transparent)
753 Tcl_Interp *interp;
754 char *imagePtr;
755 MFile *handle;
756 int len, rows;
757 unsigned char cmap[MAXCOLORMAPSIZE][4];
758 int width, height;
759 int srcX, srcY;
760 int interlace;
761 int transparent;
762 {
763 unsigned char initialCodeSize;
764 int v;
765 int xpos = 0, ypos = 0, pass = 0, i;
766 register char *pixelPtr;
767 CONST static int interlaceStep[] = { 8, 8, 4, 2 };
768 CONST static int interlaceStart[] = { 0, 4, 2, 1 };
769 unsigned short prefix[(1 << MAX_LWZ_BITS)];
770 unsigned char append[(1 << MAX_LWZ_BITS)];
771 unsigned char stack[(1 << MAX_LWZ_BITS)*2];
772 register unsigned char *top;
773 int codeSize, clearCode, inCode, endCode, oldCode, maxCode,
774 code, firstCode;
775
776 /*
777 * Initialize the decoder
778 */
779 if (! ReadOK(handle,&initialCodeSize,1) || inititalCodeSize > MAX_LWZ_BITS) {
780 Tcl_AppendResult(interp, "error reading GIF image: ",
781 Tcl_PosixError(interp), (char *) NULL);
782 return TCL_ERROR;
783 }
784 if (transparent!=-1) {
785 cmap[transparent][CM_RED] = 0;
786 cmap[transparent][CM_GREEN] = 0;
787 cmap[transparent][CM_BLUE] = 0;
788 cmap[transparent][CM_ALPHA] = 0;
789 }
790
791 pixelPtr = imagePtr;
792
793 /* Initialize the decoder */
794 /* Set values for "special" numbers:
795 * clear code reset the decoder
796 * end code stop decoding
797 * code size size of the next code to retrieve
798 * max code next available table position
799 */
800 clearCode = 1 << (int) initialCodeSize;
801 endCode = clearCode + 1;
802 codeSize = (int) initialCodeSize + 1;
803 maxCode = clearCode + 2;
804 oldCode = -1;
805 firstCode = -1;
806
807 memset((void *)prefix, 0, (1 << MAX_LWZ_BITS) * sizeof(short));
808 memset((void *)append, 0, (1 << MAX_LWZ_BITS) * sizeof(char));
809 for (i = 0; i < clearCode; i++) {
810 append[i] = i;
811 }
812 top = stack;
813
814 GetCode(handle, 0, 1);
815
816 /* Read until we finish the image */
817 for (i = 0, ypos = 0; i < rows; i++) {
818 for (xpos = 0; xpos < len; ) {
819
820 if (top == stack) {
821 /* Bummer -- our stack is empty. Now we have to work! */
822 code = GetCode(handle, codeSize, 0);
823 if (code < 0) {
824 return TCL_OK;
825 }
826
827 if (code > maxCode || code == endCode) {
828 /*
829 * If we're doing things right, we should never
830 * receive a code that is greater than our current
831 * maximum code. If we do, bail, because our decoder
832 * does not yet have that code set up.
833 *
834 * If the code is the magic endCode value, quit.
835 */
836 return TCL_OK;
837 }
838
839 if (code == clearCode) {
840 /* Reset the decoder */
841 codeSize = initialCodeSize + 1;
842 maxCode = clearCode + 2;
843 oldCode = -1;
844 continue;
845 }
846
847 if (oldCode == -1) {
848 /*
849 * Last pass reset the decoder, so the first code we
850 * see must be a singleton. Seed the stack with it,
851 * and set up the old/first code pointers for
852 * insertion into the string table. We can't just
853 * roll this into the clearCode test above, because
854 * at that point we have not yet read the next code.
855 */
856 *top++=append[code];
857 oldCode = code;
858 firstCode = code;
859 continue;
860 }
861
862 inCode = code;
863
864 if (code == maxCode) {
865 /*
866 * maxCode is always one bigger than our highest assigned
867 * code. If the code we see is equal to maxCode, then
868 * we are about to add a new string to the table. ???
869 */
870 *top++ = firstCode;
871 code = oldCode;
872 }
873
874 while (code > clearCode) {
875 /*
876 * Populate the stack by tracing the string in the
877 * string table from its tail to its head
878 */
879 *top++ = append[code];
880 code = prefix[code];
881 }
882 firstCode = append[code];
883
884 /*
885 * If there's no more room in our string table, quit.
886 * Otherwise, add a new string to the table
887 */
888 if (maxCode >= (1 << MAX_LWZ_BITS)) {
889 return TCL_OK;
890 }
891
892 /* Push the head of the string onto the stack */
893 *top++ = firstCode;
894
895 /* Add a new string to the string table */
896 prefix[maxCode] = oldCode;
897 append[maxCode] = firstCode;
898 maxCode++;
899
900 /* maxCode tells us the maximum code value we can accept.
901 * If we see that we need more bits to represent it than
902 * we are requesting from the unpacker, we need to increase
903 * the number we ask for.
904 */
905 if ((maxCode >= (1 << codeSize))
906 && (maxCode < (1<<MAX_LWZ_BITS))) {
907 codeSize++;
908 }
909 oldCode = inCode;
910 }
911
912 /* Pop the next color index off the stack */
913 v = *(--top);
914 if (v < 0) {
915 return TCL_OK;
916 }
917
918 /*
919 * If pixelPtr is null, we're skipping this image (presumably
920 * there are more in the file and we will be called to read
921 * one of them later)
922 */
923 *pixelPtr++ = cmap[v][CM_RED];
924 *pixelPtr++ = cmap[v][CM_GREEN];
925 *pixelPtr++ = cmap[v][CM_BLUE];
926 if (transparent >= 0) {
927 *pixelPtr++ = cmap[v][CM_ALPHA];
928 }
929 xpos++;
930
931 }
932
933 /* If interlacing, the next ypos is not just +1 */
934 if (interlace) {
935 ypos += interlaceStep[pass];
936 while (ypos >= height) {
937 pass++;
938 if (pass > 3) {
939 return TCL_OK;
940 }
941 ypos = interlaceStart[pass];
942 }
943 } else {
944 ypos++;
945 }
946 pixelPtr = imagePtr + (ypos) * len * ((transparent>=0)?4:3);
947 }
948 return TCL_OK;
949 }
950
951 /*
952 *----------------------------------------------------------------------
953 *
954 * GetCode --
955 *
956 * Extract the next compression code from the file. In GIF's, the
957 * compression codes are between 3 and 12 bits long and are then
958 * packed into 8 bit bytes, left to right, for example:
959 * bbbaaaaa
960 * dcccccbb
961 * eeeedddd
962 * ...
963 * We use a byte buffer read from the file and a sliding window
964 * to unpack the bytes. Thanks to ImageMagick for the sliding window
965 * idea.
966 * args: handle the handle to read from
967 * code_size size of the code to extract
968 * flag boolean indicating whether the extractor
969 * should be reset or not
970 *
971 * Results:
972 * code the next compression code
973 *
974 * Side effects:
975 * May consume more input from chan.
976 *
977 *----------------------------------------------------------------------
978 */
979
980 static int
981 GetCode(handle, code_size, flag)
982 MFile *handle;
983 int code_size;
984 int flag;
985 {
986 static unsigned char buf[280];
987 static int bytes = 0, done;
988 static unsigned char *c;
989
990 static unsigned int window;
991 static int bitsInWindow = 0;
992 int ret;
993
994 if (flag) {
995 /* Initialize the decoder */
996 bitsInWindow = 0;
997 bytes = 0;
998 window = 0;
999 done = 0;
1000 c = NULL;
1001 return 0;
1002 }
1003
1004 while (bitsInWindow < code_size) {
1005 /* Not enough bits in our window to cover the request */
1006 if (done) {
1007 return -1;
1008 }
1009 if (bytes == 0) {
1010 /* Not enough bytes in our buffer to add to the window */
1011 bytes = GetDataBlock(handle, buf);
1012 c = buf;
1013 if (bytes <= 0) {
1014 done = 1;
1015 break;
1016 }
1017 }
1018 /* Tack another byte onto the window, see if that's enough */
1019 window += (*c) << bitsInWindow;
1020 c++;
1021 bitsInWindow += 8;
1022 bytes--;
1023 }
1024
1025
1026 /* The next code will always be the last code_size bits of the window */
1027 ret = window & ((1 << code_size) - 1);
1028
1029 /* Shift data in the window to put the next code at the end */
1030 window >>= code_size;
1031 bitsInWindow -= code_size;
1032 return ret;
1033 }
1034
1035 /*
1036 * This software is copyrighted as noted below. It may be freely copied,
1037 * modified, and redistributed, provided that the copyright notice is
1038 * preserved on all copies.
1039 *
1040 * There is no warranty or other guarantee of fitness for this software,
1041 * it is provided solely "as is". Bug reports or fixes may be sent
1042 * to the author, who may or may not act on them as he desires.
1043 *
1044 * You may not include this software in a program or other software product
1045 * without supplying the source, or without informing the end-user that the
1046 * source is available for no extra charge.
1047 *
1048 * If you modify this software, you should include a notice giving the
1049 * name of the person performing the modification, the date of modification,
1050 * and the reason for such modification.
1051 */
1052
1053
1054
1055
1056
1057
1058 /*
1059 * ChanWriteGIF - writes a image in GIF format.
1060 *-------------------------------------------------------------------------
1061 * Author: Lolo
1062 * Engeneering Projects Area
1063 * Department of Mining
1064 * University of Oviedo
1065 * e-mail [email protected]
1066 * [email protected]
1067 * Date: Fri September 20 1996
1068 *
1069 * Modified for transparency handling (gif89a) and miGIF compression
1070 * by Jan Nijtmans <[email protected]>
1071 *
1072 *----------------------------------------------------------------------
1073 * FileWriteGIF-
1074 *
1075 * This procedure is called by the photo image type to write
1076 * GIF format data from a photo image into a given file
1077 *
1078 * Results:
1079 * A standard TCL completion code. If TCL_ERROR is returned
1080 * then an error message is left in the interp's result.
1081 *
1082 *----------------------------------------------------------------------
1083 */
1084
1085 /*
1086 * Types, defines and variables needed to write and compress a GIF.
1087 */
1088
1089 typedef int (* ifunptr) _ANSI_ARGS_((void));
1090
1091 #define LSB(a) ((unsigned char) (((short)(a)) & 0x00FF))
1092 #define MSB(a) ((unsigned char) (((short)(a)) >> 8))
1093
1094 #define GIFBITS 12
1095 #define HSIZE 5003 /* 80% occupancy */
1096
1097 static int ssize;
1098 static int csize;
1099 static int rsize;
1100 static unsigned char *pixelo;
1101 static int pixelSize;
1102 static int pixelPitch;
1103 static int greenOffset;
1104 static int blueOffset;
1105 static int alphaOffset;
1106 static int num;
1107 static unsigned char mapa[MAXCOLORMAPSIZE][3];
1108
1109 /*
1110 * Definition of new functions to write GIFs
1111 */
1112
1113 static int color _ANSI_ARGS_((int red,int green, int blue));
1114 static void compress _ANSI_ARGS_((int init_bits, MFile *handle,
1115 ifunptr readValue));
1116 static int nuevo _ANSI_ARGS_((int red, int green ,int blue,
1117 unsigned char mapa[MAXCOLORMAPSIZE][3]));
1118 static int savemap _ANSI_ARGS_((Tk_PhotoImageBlock *blockPtr,
1119 unsigned char mapa[MAXCOLORMAPSIZE][3]));
1120 static int ReadValue _ANSI_ARGS_((void));
1121 static int no_bits _ANSI_ARGS_((int colors));
1122
1123 static int
1124 ChanWriteGIF (interp, filename, format, blockPtr)
1125 Tcl_Interp *interp; /* Interpreter to use for reporting errors. */
1126 char *filename;
1127 Tcl_Obj *format;
1128 Tk_PhotoImageBlock *blockPtr;
1129 {
1130 Tcl_Channel chan = NULL;
1131 MFile handle;
1132 int result;
1133
1134 chan = ImgOpenFileChannel(interp, filename, 0644);
1135 if (!chan) {
1136 return TCL_ERROR;
1137 }
1138
1139 handle.data = (char *) chan;
1140 handle.state = IMG_CHAN;
1141
1142 result = CommonWriteGIF(interp, &handle, format, blockPtr);
1143 if (Tcl_Close(interp, chan) == TCL_ERROR) {
1144 return TCL_ERROR;
1145 }
1146 return result;
1147 }
1148
1149 static int
1150 StringWriteGIF(interp, format, blockPtr)
1151 Tcl_Interp *interp;
1152 Tcl_Obj *format;
1153 Tk_PhotoImageBlock *blockPtr;
1154 {
1155 int result;
1156 MFile handle;
1157 Tcl_DString data;
1158 Tcl_DString *dataPtr;
1159
1160 ImgFixStringWriteProc(&data, &interp, &dataPtr, &format, &blockPtr);
1161
1162 Tcl_DStringSetLength(dataPtr, 1024);
1163 ImgWriteInit(dataPtr, &handle);
1164
1165 result = CommonWriteGIF(interp, &handle, format, blockPtr);
1166 ImgPutc(IMG_DONE, &handle);
1167
1168 if ((result == TCL_OK) && (dataPtr == &data)) {
1169 Tcl_DStringResult(interp, dataPtr);
1170 }
1171 return result;
1172 }
1173
1174 static int
1175 CommonWriteGIF(interp, handle, format, blockPtr)
1176 Tcl_Interp *interp;
1177 MFile *handle;
1178 Tcl_Obj *format;
1179 Tk_PhotoImageBlock *blockPtr;
1180 {
1181 int resolution;
1182 long numcolormap;
1183
1184 long width,height,x;
1185 unsigned char c;
1186 unsigned int top,left;
1187 int num;
1188
1189 top = 0;
1190 left = 0;
1191
1192 pixelSize=blockPtr->pixelSize;
1193 greenOffset=blockPtr->offset[1]-blockPtr->offset[0];
1194 blueOffset=blockPtr->offset[2]-blockPtr->offset[0];
1195 alphaOffset = blockPtr->offset[0];
1196 if (alphaOffset < blockPtr->offset[2]) {
1197 alphaOffset = blockPtr->offset[2];
1198 }
1199 if (++alphaOffset < pixelSize) {
1200 alphaOffset -= blockPtr->offset[0];
1201 } else {
1202 alphaOffset = 0;
1203 }
1204
1205 ImgWrite(handle, (CONST char *) (alphaOffset ? GIF89a:GIF87a), 6);
1206
1207 for (x=0;x<MAXCOLORMAPSIZE;x++) {
1208 mapa[x][CM_RED] = 255;
1209 mapa[x][CM_GREEN] = 255;
1210 mapa[x][CM_BLUE] = 255;
1211 }
1212
1213
1214 width=blockPtr->width;
1215 height=blockPtr->height;
1216 pixelo=blockPtr->pixelPtr + blockPtr->offset[0];
1217 pixelPitch=blockPtr->pitch;
1218 if ((num=savemap(blockPtr,mapa))<0) {
1219 Tcl_AppendResult(interp, "too many colors", (char *) NULL);
1220 return TCL_ERROR;
1221 }
1222 if (num<3) num=3;
1223 c=LSB(width);
1224 ImgPutc(c,handle);
1225 c=MSB(width);
1226 ImgPutc(c,handle);
1227 c=LSB(height);
1228 ImgPutc(c,handle);
1229 c=MSB(height);
1230 ImgPutc(c,handle);
1231
1232 c= (1 << 7) | (no_bits(num) << 4) | (no_bits(num));
1233 ImgPutc(c,handle);
1234 resolution = no_bits(num)+1;
1235
1236 numcolormap=1 << resolution;
1237
1238 /* background color */
1239
1240 ImgPutc(0,handle);
1241
1242 /* zero for future expansion */
1243
1244 ImgPutc(0,handle);
1245
1246 for (x=0; x<numcolormap ;x++) {
1247 ImgPutc(mapa[x][CM_RED],handle);
1248 ImgPutc(mapa[x][CM_GREEN],handle);
1249 ImgPutc(mapa[x][CM_BLUE],handle);
1250 }
1251
1252 /*
1253 * Write out extension for transparent colour index, if necessary.
1254 */
1255
1256 if (alphaOffset) {
1257 ImgWrite(handle, "!\371\4\1\0\0\0", 8);
1258 }
1259
1260 c = GIF_START;
1261 ImgPutc(c,handle);
1262 c=LSB(top);
1263 ImgPutc(c,handle);
1264 c=MSB(top);
1265 ImgPutc(c,handle);
1266 c=LSB(left);
1267 ImgPutc(c,handle);
1268 c=MSB(left);
1269 ImgPutc(c,handle);
1270
1271 c=LSB(width);
1272 ImgPutc(c,handle);
1273 c=MSB(width);
1274 ImgPutc(c,handle);
1275
1276 c=LSB(height);
1277 ImgPutc(c,handle);
1278 c=MSB(height);
1279 ImgPutc(c,handle);
1280
1281 c=0;
1282 ImgPutc(c,handle);
1283 c=resolution;
1284 ImgPutc(c,handle);
1285
1286 ssize = rsize = blockPtr->width;
1287 csize = blockPtr->height;
1288 compress(resolution+1, handle, ReadValue);
1289
1290 ImgPutc(0,handle);
1291 c = GIF_TERMINATOR;
1292 ImgPutc(c,handle);
1293
1294 return TCL_OK;
1295 }
1296
1297 static int
1298 color(red, green, blue)
1299 int red;
1300 int green;
1301 int blue;
1302 {
1303 int x;
1304 for (x=(alphaOffset != 0);x<=MAXCOLORMAPSIZE;x++) {
1305 if ((mapa[x][CM_RED]==red) && (mapa[x][CM_GREEN]==green) &&
1306 (mapa[x][CM_BLUE]==blue)) {
1307 return x;
1308 }
1309 }
1310 return -1;
1311 }
1312
1313
1314 static int
1315 nuevo(red, green, blue, mapa)
1316 int red,green,blue;
1317 unsigned char mapa[MAXCOLORMAPSIZE][3];
1318 {
1319 int x;
1320 for (x=(alphaOffset != 0);x<num;x++) {
1321 if ((mapa[x][CM_RED]==red) && (mapa[x][CM_GREEN]==green) &&
1322 (mapa[x][CM_BLUE]==blue)) {
1323 return 0;
1324 }
1325 }
1326 return 1;
1327 }
1328
1329 static int
1330 savemap(blockPtr,mapa)
1331 Tk_PhotoImageBlock *blockPtr;
1332 unsigned char mapa[MAXCOLORMAPSIZE][3];
1333 {
1334 unsigned char *colores;
1335 int x,y;
1336 unsigned char red,green,blue;
1337
1338 if (alphaOffset) {
1339 num = 1;
1340 mapa[0][CM_RED] = 0xd9;
1341 mapa[0][CM_GREEN] = 0xd9;
1342 mapa[0][CM_BLUE] = 0xd9;
1343 } else {
1344 num = 0;
1345 }
1346
1347 for(y=0;y<blockPtr->height;y++) {
1348 colores=blockPtr->pixelPtr + blockPtr->offset[0]
1349 + y * blockPtr->pitch;
1350 for(x=0;x<blockPtr->width;x++) {
1351 if (!alphaOffset || (colores[alphaOffset] != 0)) {
1352 red = colores[0];
1353 green = colores[greenOffset];
1354 blue = colores[blueOffset];
1355 if (nuevo(red,green,blue,mapa)) {
1356 if (num>255)
1357 return -1;
1358
1359 mapa[num][CM_RED]=red;
1360 mapa[num][CM_GREEN]=green;
1361 mapa[num][CM_BLUE]=blue;
1362 num++;
1363 }
1364 }
1365 colores += pixelSize;
1366 }
1367 }
1368 return num;
1369 }
1370
1371 static int
1372 ReadValue()
1373 {
1374 unsigned int col;
1375
1376 if (csize == 0) {
1377 return EOF;
1378 }
1379 if (alphaOffset && (pixelo[alphaOffset]==0)) {
1380 col = 0;
1381 } else {
1382 col = color(pixelo[0],pixelo[greenOffset],pixelo[blueOffset]);
1383 }
1384 pixelo += pixelSize;
1385 if (--ssize <= 0) {
1386 ssize = rsize;
1387 csize--;
1388 pixelo += pixelPitch - (rsize * pixelSize);
1389 }
1390
1391 return col;
1392 }
1393
1394 /*
1395 * Return the number of bits ( -1 ) to represent a given
1396 * number of colors ( ex: 256 colors => 7 ).
1397 */
1398 static int
1399 no_bits( colors )
1400 int colors;
1401 {
1402 register int bits = 0;
1403
1404 colors--;
1405 while ( colors >> bits ) {
1406 bits++;
1407 }
1408
1409 return (bits-1);
1410 }
1411
1412
1413
1414 /*-----------------------------------------------------------------------
1415 *
1416 * miGIF Compression - mouse and ivo's GIF-compatible compression
1417 *
1418 * -run length encoding compression routines-
1419 *
1420 * Copyright (C) 1998 Hutchison Avenue Software Corporation
1421 * http://www.hasc.com
1422 * [email protected]
1423 *
1424 * Permission to use, copy, modify, and distribute this software and its
1425 * documentation for any purpose and without fee is hereby granted, provided
1426 * that the above copyright notice appear in all copies and that both that
1427 * copyright notice and this permission notice appear in supporting
1428 * documentation. This software is provided "AS IS." The Hutchison Avenue
1429 * Software Corporation disclaims all warranties, either express or implied,
1430 * including but not limited to implied warranties of merchantability and
1431 * fitness for a particular purpose, with respect to this code and accompanying
1432 * documentation.
1433 *
1434 * The miGIF compression routines do not, strictly speaking, generate files
1435 * conforming to the GIF spec, since the image data is not LZW-compressed
1436 * (this is the point: in order to avoid transgression of the Unisys patent
1437 * on the LZW algorithm.) However, miGIF generates data streams that any
1438 * reasonably sane LZW decompresser will decompress to what we want.
1439 *
1440 * miGIF compression uses run length encoding. It compresses horizontal runs
1441 * of pixels of the same color. This type of compression gives good results
1442 * on images with many runs, for example images with lines, text and solid
1443 * shapes on a solid-colored background. It gives little or no compression
1444 * on images with few runs, for example digital or scanned photos.
1445 *
1446 * der Mouse
1447 * [email protected]
1448 * 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B
1449 *
1450 * [email protected]
1451 *
1452 * The Graphics Interchange Format(c) is the Copyright property of
1453 * CompuServe Incorporated. GIF(sm) is a Service Mark property of
1454 * CompuServe Incorporated.
1455 *
1456 */
1457
1458 static int rl_pixel;
1459 static int rl_basecode;
1460 static int rl_count;
1461 static int rl_table_pixel;
1462 static int rl_table_max;
1463 static int just_cleared;
1464 static int out_bits;
1465 static int out_bits_init;
1466 static int out_count;
1467 static int out_bump;
1468 static int out_bump_init;
1469 static int out_clear;
1470 static int out_clear_init;
1471 static int max_ocodes;
1472 static int code_clear;
1473 static int code_eof;
1474 static unsigned int obuf;
1475 static int obits;
1476 static MFile *ofile;
1477 static unsigned char oblock[MAXCOLORMAPSIZE];
1478 static int oblen;
1479
1480 /* Used only when debugging GIF compression code */
1481 /* #define DEBUGGING_ENVARS */
1482
1483 #ifdef DEBUGGING_ENVARS
1484
1485 static int verbose_set = 0;
1486 static int verbose;
1487 #define VERBOSE (verbose_set?verbose:set_verbose())
1488
1489 static int set_verbose(void)
1490 {
1491 verbose = !!getenv("GIF_VERBOSE");
1492 verbose_set = 1;
1493 return(verbose);
1494 }
1495
1496 #else
1497
1498 #define VERBOSE 0
1499
1500 #endif
1501
1502
1503 static CONST char *
1504 binformat(v, nbits)
1505 unsigned int v;
1506 int nbits;
1507 {
1508 static char bufs[8][64];
1509 static int bhand = 0;
1510 unsigned int bit;
1511 int bno;
1512 char *bp;
1513
1514 bhand --;
1515 if (bhand < 0) bhand = (sizeof(bufs)/sizeof(bufs[0]))-1;
1516 bp = &bufs[bhand][0];
1517 for (bno=nbits-1,bit=1<<bno;bno>=0;bno--,bit>>=1)
1518 { *bp++ = (v & bit) ? '1' : '0';
1519 if (((bno&3) == 0) && (bno != 0)) *bp++ = '.';
1520 }
1521 *bp = '\0';
1522 return(&bufs[bhand][0]);
1523 }
1524
1525 static void write_block()
1526 {
1527 int i;
1528 unsigned char c;
1529
1530 if (VERBOSE)
1531 { printf("write_block %d:",oblen);
1532 for (i=0;i<oblen;i++) printf(" %02x",oblock[i]);
1533 printf("\n");
1534 }
1535 c = oblen;
1536 ImgWrite(ofile, (CONST char *) &c, 1);
1537 ImgWrite(ofile, &oblock[0], oblen);
1538 oblen = 0;
1539 }
1540
1541 static void
1542 block_out(c)
1543 unsigned char c;
1544 {
1545 if (VERBOSE) printf("block_out %s\n",binformat(c,8));
1546 oblock[oblen++] = c;
1547 if (oblen >= 255) write_block();
1548 }
1549
1550 static void block_flush()
1551 {
1552 if (VERBOSE) printf("block_flush\n");
1553 if (oblen > 0) write_block();
1554 }
1555
1556 static void output(val)
1557 int val;
1558 {
1559 if (VERBOSE) printf("output %s [%s %d %d]\n",binformat(val,out_bits),binformat(obuf,obits),obits,out_bits);
1560 obuf |= val << obits;
1561 obits += out_bits;
1562 while (obits >= 8)
1563 { block_out(obuf&0xff);
1564 obuf >>= 8;
1565 obits -= 8;
1566 }
1567 if (VERBOSE) printf("output leaving [%s %d]\n",binformat(obuf,obits),obits);
1568 }
1569
1570 static void output_flush()
1571 {
1572 if (VERBOSE) printf("output_flush\n");
1573 if (obits > 0) block_out(obuf);
1574 block_flush();
1575 }
1576
1577 static void did_clear()
1578 {
1579 if (VERBOSE) printf("did_clear\n");
1580 out_bits = out_bits_init;
1581 out_bump = out_bump_init;
1582 out_clear = out_clear_init;
1583 out_count = 0;
1584 rl_table_max = 0;
1585 just_cleared = 1;
1586 }
1587
1588 static void
1589 output_plain(c)
1590 int c;
1591 {
1592 if (VERBOSE) printf("output_plain %s\n",binformat(c,out_bits));
1593 just_cleared = 0;
1594 output(c);
1595 out_count ++;
1596 if (out_count >= out_bump)
1597 { out_bits ++;
1598 out_bump += 1 << (out_bits - 1);
1599 }
1600 if (out_count >= out_clear)
1601 { output(code_clear);
1602 did_clear();
1603 }
1604 }
1605
1606 static unsigned int isqrt(x)
1607 unsigned int x;
1608 {
1609 unsigned int r;
1610 unsigned int v;
1611
1612 if (x < 2) return(x);
1613 for (v=x,r=1;v;v>>=2,r<<=1) ;
1614 while (1)
1615 { v = ((x / r) + r) / 2;
1616 if ((v == r) || (v == r+1)) return(r);
1617 r = v;
1618 }
1619 }
1620
1621 static unsigned int
1622 compute_triangle_count(count, nrepcodes)
1623 unsigned int count;
1624 unsigned int nrepcodes;
1625 {
1626 unsigned int perrep;
1627 unsigned int cost;
1628
1629 cost = 0;
1630 perrep = (nrepcodes * (nrepcodes+1)) / 2;
1631 while (count >= perrep)
1632 { cost += nrepcodes;
1633 count -= perrep;
1634 }
1635 if (count > 0)
1636 { unsigned int n;
1637 n = isqrt(count);
1638 while ((n*(n+1)) >= 2*count) n --;
1639 while ((n*(n+1)) < 2*count) n ++;
1640 cost += n;
1641 }
1642 return(cost);
1643 }
1644
1645 static void max_out_clear()
1646 {
1647 out_clear = max_ocodes;
1648 }
1649
1650 static void reset_out_clear()
1651 {
1652 out_clear = out_clear_init;
1653 if (out_count >= out_clear)
1654 { output(code_clear);
1655 did_clear();
1656 }
1657 }
1658
1659 static void
1660 rl_flush_fromclear(count)
1661 int count;
1662 {
1663 int n;
1664
1665 if (VERBOSE) printf("rl_flush_fromclear %d\n",count);
1666 max_out_clear();
1667 rl_table_pixel = rl_pixel;
1668 n = 1;
1669 while (count > 0)
1670 { if (n == 1)
1671 { rl_table_max = 1;
1672 output_plain(rl_pixel);
1673 count --;
1674 }
1675 else if (count >= n)
1676 { rl_table_max = n;
1677 output_plain(rl_basecode+n-2);
1678 count -= n;
1679 }
1680 else if (count == 1)
1681 { rl_table_max ++;
1682 output_plain(rl_pixel);
1683 count = 0;
1684 }
1685 else
1686 { rl_table_max ++;
1687 output_plain(rl_basecode+count-2);
1688 count = 0;
1689 }
1690 if (out_count == 0) n = 1; else n ++;
1691 }
1692 reset_out_clear();
1693 if (VERBOSE) printf("rl_flush_fromclear leaving table_max=%d\n",rl_table_max);
1694 }
1695
1696 static void rl_flush_clearorrep(count)
1697 int count;
1698 {
1699 int withclr;
1700
1701 if (VERBOSE) printf("rl_flush_clearorrep %d\n",count);
1702 withclr = 1 + compute_triangle_count(count,max_ocodes);
1703 if (withclr < count)
1704 { output(code_clear);
1705 did_clear();
1706 rl_flush_fromclear(count);
1707 }
1708 else
1709 { for (;count>0;count--) output_plain(rl_pixel);
1710 }
1711 }
1712
1713 static void rl_flush_withtable(count)
1714 int count;
1715 {
1716 int repmax;
1717 int repleft;
1718 int leftover;
1719
1720 if (VERBOSE) printf("rl_flush_withtable %d\n",count);
1721 repmax = count / rl_table_max;
1722 leftover = count % rl_table_max;
1723 repleft = (leftover ? 1 : 0);
1724 if (out_count+repmax+repleft > max_ocodes)
1725 { repmax = max_ocodes - out_count;
1726 leftover = count - (repmax * rl_table_max);
1727 repleft = 1 + compute_triangle_count(leftover,max_ocodes);
1728 }
1729 if (VERBOSE) printf("rl_flush_withtable repmax=%d leftover=%d repleft=%d\n",repmax,leftover,repleft);
1730 if (1+(int) compute_triangle_count(count,max_ocodes) < repmax+repleft)
1731 { output(code_clear);
1732 did_clear();
1733 rl_flush_fromclear(count);
1734 return;
1735 }
1736 max_out_clear();
1737 for (;repmax>0;repmax--) output_plain(rl_basecode+rl_table_max-2);
1738 if (leftover)
1739 { if (just_cleared)
1740 { rl_flush_fromclear(leftover);
1741 }
1742 else if (leftover == 1)
1743 { output_plain(rl_pixel);
1744 }
1745 else
1746 { output_plain(rl_basecode+leftover-2);
1747 }
1748 }
1749 reset_out_clear();
1750 }
1751
1752 static void rl_flush()
1753 {
1754 if (VERBOSE) printf("rl_flush [ %d %d\n",rl_count,rl_pixel);
1755 if (rl_count == 1)
1756 { output_plain(rl_pixel);
1757 rl_count = 0;
1758 if (VERBOSE) printf("rl_flush ]\n");
1759 return;
1760 }
1761 if (just_cleared)
1762 { rl_flush_fromclear(rl_count);
1763 }
1764 else if ((rl_table_max < 2) || (rl_table_pixel != rl_pixel))
1765 { rl_flush_clearorrep(rl_count);
1766 }
1767 else
1768 { rl_flush_withtable(rl_count);
1769 }
1770 if (VERBOSE) printf("rl_flush ]\n");
1771 rl_count = 0;
1772 }
1773
1774
1775 static void compress( init_bits, handle, readValue )
1776 int init_bits;
1777 MFile *handle;
1778 ifunptr readValue;
1779 {
1780 int c;
1781
1782 ofile = handle;
1783 obuf = 0;
1784 obits = 0;
1785 oblen = 0;
1786 code_clear = 1 << (init_bits - 1);
1787 code_eof = code_clear + 1;
1788 rl_basecode = code_eof + 1;
1789 out_bump_init = (1 << (init_bits - 1)) - 1;
1790 /* for images with a lot of runs, making out_clear_init larger will
1791 give better compression. */
1792 out_clear_init = (init_bits <= 3) ? 9 : (out_bump_init-1);
1793 #ifdef DEBUGGING_ENVARS
1794 { CONST char *ocienv;
1795 ocienv = getenv("GIF_OUT_CLEAR_INIT");
1796 if (ocienv)
1797 { out_clear_init = atoi(ocienv);
1798 if (VERBOSE) printf("[overriding out_clear_init to %d]\n",out_clear_init);
1799 }
1800 }
1801 #endif
1802 out_bits_init = init_bits;
1803 max_ocodes = (1 << GIFBITS) - ((1 << (out_bits_init - 1)) + 3);
1804 did_clear();
1805 output(code_clear);
1806 rl_count = 0;
1807 while (1)
1808 { c = readValue();
1809 if ((rl_count > 0) && (c != rl_pixel)) rl_flush();
1810 if (c == EOF) break;
1811 if (rl_pixel == c)
1812 { rl_count ++;
1813 }
1814 else
1815 { rl_pixel = c;
1816 rl_count = 1;
1817 }
1818 }
1819 output(code_eof);
1820 output_flush();
1821 }
1822
1823 /*-----------------------------------------------------------------------
1824 *
1825 * End of miGIF section - See copyright notice at start of section.
1826 *
1827 *-----------------------------------------------------------------------*/
1828