Debian Codegraph @

pTk/mTk/generic/tkImgGIF.c

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