Debian Codegraph @

converter/other/giftopnm.c

raw
1 /* +-------------------------------------------------------------------+ */
2 /* | Copyright 1990, 1991, 1993, David Koblas. ([email protected]) | */
3 /* | Permission to use, copy, modify, and distribute this software | */
4 /* | and its documentation for any purpose and without fee is hereby | */
5 /* | granted, provided that the above copyright notice appear in all | */
6 /* | copies and that both that copyright notice and this permission | */
7 /* | notice appear in supporting documentation. This software is | */
8 /* | provided "as is" without express or implied warranty. | */
9 /* +-------------------------------------------------------------------+ */
10
11 /* There is a copy of the GIF89 specification, as defined by its inventor,
12 Compuserve, in 1990 at:
13 http://www.w3.org/Graphics/GIF/spec-gif89a.txt
14
15 This covers the high level format, but does not cover how the "data"
16 contents of a GIF image represent the raster of color table indices.
17 An appendix describes extensions to Lempel-Ziv that GIF makes (variable
18 length compression codes and the clear and end codes), but does not
19 describe the Lempel-Ziv base.
20 */
21
22 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
23 #define _XOPEN_SOURCE 500 /* Make sure strdup() is in string.h */
24 #define _BSD_SOURCE /* for strcaseeq */
25 #include <string.h>
26 #include <assert.h>
27 #include <stdbool.h>
28
29 #include "pm_config.h"
30 #include "pm_c_util.h"
31 #include "mallocvar.h"
32 #include "nstring.h"
33 #include "shhopt.h"
34 #include "pnm.h"
35
36 #define GIFMAXVAL 255
37 #define MAXCOLORMAPSIZE 256
38
39 #define CM_RED 0
40 #define CM_GRN 1
41 #define CM_BLU 2
42
43 #define MAX_LZW_BITS 12
44
45 #ifndef FASTPBMRENDER
46 #define FASTPBMRENDER true
47 #endif
48
49 static const bool useFastPbmRender = FASTPBMRENDER;
50
51 #ifndef REPORTLZWCODES
52 #define REPORTLZWCODES false
53 #endif
54
55 static const bool wantLzwCodes = REPORTLZWCODES;
56 /* In verbose output, include all the LZW codes */
57
58
59
60 static void
61 readFile(FILE * const ifP,
62 unsigned char * const buffer,
63 size_t const len,
64 const char ** const errorP) {
65 /*----------------------------------------------------------------------------
66 Read the next 'len' bytes from *ifP into 'buffer'.
67
68 Fail if there aren't that many bytes to read.
69 -----------------------------------------------------------------------------*/
70 size_t bytesRead;
71
72 bytesRead = fread(buffer, 1, len, ifP);
73
74 if (bytesRead == len)
75 *errorP = NULL;
76 else {
77 if (ferror(ifP))
78 pm_asprintf(errorP, "Error reading file. errno=%d (%s)",
79 errno, strerror(errno));
80 else if (feof(ifP))
81 pm_asprintf(errorP, "End of file encountered");
82 else
83 pm_asprintf(errorP, "Short read -- %u bytes of %u",
84 (unsigned)bytesRead, (unsigned)len);
85 }
86 }
87
88
89
90 struct CmdlineInfo {
91 /* All the information the user supplied in the command line,
92 in a form easy for the program to use.
93 */
94 const char * inputFilespec; /* Filespecs of input files */
95 unsigned int verbose; /* -verbose option */
96 unsigned int comments; /* -comments option */
97 bool allImages; /* He wants all the images */
98 unsigned int imageNum;
99 /* image number he wants from input, starting at 0. Undefined
100 if allImages is true
101 */
102 const char * alphaFileName;
103 unsigned int quitearly;
104 unsigned int repair;
105 };
106
107
108
109 static void
110 parseCommandLine(int argc, const char ** argv,
111 struct CmdlineInfo * const cmdlineP) {
112 /*----------------------------------------------------------------------------
113 Note that the file spec array we return is stored in the storage that
114 was passed to us as the argv array.
115 -----------------------------------------------------------------------------*/
116 optEntry * option_def; /* Used by OPTENT3 */
117 optStruct3 opt;
118
119 unsigned int alphaSpec, imageSpec;
120 const char * image;
121
122 unsigned int option_def_index;
123
124 MALLOCARRAY_NOFAIL(option_def, 100);
125
126 option_def_index = 0; /* incremented by OPTENTRY */
127 OPTENT3(0, "verbose", OPT_FLAG, NULL,
128 &cmdlineP->verbose, 0);
129 OPTENT3(0, "comments", OPT_FLAG, NULL,
130 &cmdlineP->comments, 0);
131 OPTENT3(0, "quitearly", OPT_FLAG, NULL,
132 &cmdlineP->quitearly, 0);
133 OPTENT3(0, "repair", OPT_FLAG, NULL,
134 &cmdlineP->repair, 0);
135 OPTENT3(0, "image", OPT_STRING, &image,
136 &imageSpec, 0);
137 OPTENT3(0, "alphaout", OPT_STRING, &cmdlineP->alphaFileName,
138 &alphaSpec, 0);
139
140 opt.opt_table = option_def;
141 opt.short_allowed = false; /* We have no short (old-fashioned) options */
142 opt.allowNegNum = false; /* We have no parms that are negative numbers */
143
144 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
145 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
146
147 free(option_def);
148
149 if (!imageSpec) {
150 cmdlineP->imageNum = 0;
151 cmdlineP->allImages = false;
152 } else {
153 if (strcaseeq(image, "all")) {
154 cmdlineP->allImages = true;
155 } else {
156 char * tailptr;
157
158 long const imageNum = strtol(image, &tailptr, 10);
159
160 if (*tailptr != '\0')
161 pm_error("Invalid value for '-image' option. Must be either "
162 "a number or 'all'. You specified '%s'", image);
163 else if (imageNum < 0)
164 pm_error("Invalid value for '-image' option. Must be "
165 "positive. You specified %ld", imageNum);
166 else if (imageNum == 0)
167 pm_error("Invalid value for 'image' option. You specified "
168 "zero. The first image is 1.");
169
170 cmdlineP->allImages = false;
171 cmdlineP->imageNum = (unsigned int) imageNum - 1;
172 }
173 }
174
175 if (argc-1 == 0)
176 cmdlineP->inputFilespec = "-";
177 else if (argc-1 != 1)
178 pm_error("Program takes zero or one argument (filename). You "
179 "specified %d", argc-1);
180 else
181 cmdlineP->inputFilespec = argv[1];
182
183 if (!alphaSpec)
184 cmdlineP->alphaFileName = NULL;
185 }
186
187
188
189 typedef struct {
190 unsigned char map[MAXCOLORMAPSIZE][3];
191 unsigned int size;
192 } GifColorMap;
193
194 /*----------------------------------------------------------------------
195 On GIF color maps:
196
197 The color map can have any number of colors up to 256. If the color map
198 size is not a power of 2 the table is padded up. The LZW "clear" control
199 code is always placed at a power of 2.
200
201 The color map and code table of an image with three colors (black, white
202 and red) will look like this:
203
204 0: black
205 1: white
206 2: red
207 3: (unused)
208 4: clear code
209 5: end code
210 6: first LZW string code
211 7: second LZW string code
212 ...
213 4095: last LZW string code
214
215 Some GIFs have odd color maps.
216
217 (1) Some encoders use fixed color maps. A GIF image produced by this
218 kind of encoder may have colors in the table which never appear in
219 the image.
220
221 Note that we make the decision on whether the output should be PBM,
222 PGM or PPM by scanning through the color map, not the entire image.
223 Any unused colors will influence our decision.
224
225 (2) There are GIF editors which allow one to rewrite the color map.
226 These programs will produce color maps with multiple entries for the
227 same color.
228
229 (3) Some encoders put the transparent code outside the color map.
230 (In the above example, the unused value 3.) Around 2000 there were
231 several encoders that did this, including "Animation Gif Maker
232 (GifAnim)". As of 2012, such images are rare. We reject them with
233 an error message unless -repair is specified.
234 -----------------------------------------------------------------------*/
235
236
237 struct GifScreen {
238 unsigned int width;
239 unsigned int height;
240 bool hasGlobalColorMap;
241 /* The stream has a global color map, to wit 'colorMap'.
242 (If the stream doesn't have a global color map, the individual
243 images must each have a local color map)
244 */
245 GifColorMap colorMap;
246 /* The global color map for the stream. Meaningful only if
247 'hasGlobalColorMap' is true.
248 */
249 unsigned int colorResolution;
250 unsigned int background;
251 unsigned int aspectRatio;
252 /* Aspect ratio of each pixel, times 64, minus 15. (i.e. 1 => 1:4).
253 But Zero means 1:1.
254 */
255 bool hasGray;
256 /* Boolean: global colormap has at least one gray color
257 (not counting black and white)
258 */
259 bool hasColor;
260 /* Boolean: global colormap has at least one non-gray,
261 non-black, non-white color
262 */
263 };
264
265 struct Gif89 {
266 bool haveTransColor;
267 /* The GIF specifies a transparent background color */
268 unsigned int transparentIndex;
269 /* The color index of the color which is the transparent
270 background color.
271
272 Meaningful only when 'haveTransColor' is true
273 */
274 bool haveDelayTime;
275 unsigned int delayTime;
276 bool haveInputFlag;
277 unsigned char inputFlag;
278 bool haveDisposal;
279 unsigned char disposal;
280 };
281
282 static void
283 initGif89(struct Gif89 * const gif89P) {
284 gif89P->haveTransColor = false;
285 gif89P->haveDelayTime = false;
286 gif89P->haveInputFlag = false;
287 gif89P->haveDisposal = false;
288 }
289
290
291
292 static bool verbose;
293 static bool showComment;
294
295
296
297 static void
298 readColorMap(FILE * const ifP,
299 unsigned int const cmapSize,
300 GifColorMap * const cmapP,
301 bool * const hasGrayP,
302 bool * const hasColorP) {
303 /*----------------------------------------------------------------------------
304 Read a color map from a GIF stream, where the stream is on *ifP,
305 which is positioned to a color map, which is 'cmapSize' bytes long.
306
307 Return as *cmapP that color map.
308
309 Furthermore, analyze that color map and return *hasGrayP == true iff it
310 contains any gray (black and white don't count) and *hasColorP == true iff
311 it contains anything that is not gray or black or white.
312 -----------------------------------------------------------------------------*/
313 unsigned int i;
314 unsigned char rgb[3];
315
316 assert(cmapSize <= MAXCOLORMAPSIZE);
317
318 *hasGrayP = false; /* initial assumption */
319 *hasColorP = false; /* initial assumption */
320
321 for (i = 0; i < cmapSize; ++i) {
322 const char * error;
323 readFile(ifP, rgb, sizeof(rgb), &error);
324 if (error)
325 pm_error("Unable to read Color %u from colormap. %s", i, error);
326
327 cmapP->map[i][CM_RED] = rgb[0] ;
328 cmapP->map[i][CM_GRN] = rgb[1] ;
329 cmapP->map[i][CM_BLU] = rgb[2] ;
330
331 if (rgb[0] == rgb[1] && rgb[1] == rgb[2]) {
332 if (rgb[0] != 0 && rgb[0] != GIFMAXVAL)
333 *hasGrayP = true;
334 } else
335 *hasColorP = true;
336 }
337 cmapP->size = cmapSize;
338 }
339
340
341
342 static bool zeroDataBlock = false;
343 /* the most recently read DataBlock was an EOD marker, i.e. had
344 zero length
345 */
346
347 static void
348 getDataBlock(FILE * const ifP,
349 unsigned char * const buf,
350 bool * const eofP,
351 unsigned int * const lengthP,
352 const char ** const errorP) {
353 /*----------------------------------------------------------------------------
354 Read a DataBlock from file 'ifP', return it at 'buf'.
355
356 The first byte of the datablock is the length, in pure binary, of the
357 rest of the datablock. We return the data portion (not the length byte)
358 of the datablock at 'buf', and its length as *lengthP.
359
360 Except that if we hit EOF or have an I/O error reading the first
361 byte (size field) of the DataBlock, we return *eofP == true and
362 *lengthP == 0.
363
364 We return *eofP == false if we don't hit EOF or have an I/O error.
365
366 If we hit EOF or have an I/O error reading the data portion of the
367 DataBlock, we exit the program with pm_error().
368 -----------------------------------------------------------------------------*/
369 long const pos = ftell(ifP);
370
371 unsigned char count;
372 const char * error;
373
374 readFile(ifP, &count, sizeof(count), &error);
375
376 if (error) {
377 pm_message("EOF or error in reading DataBlock size from file. %s",
378 error);
379 pm_strfree(error);
380 *errorP = NULL;
381 *eofP = true;
382 *lengthP = 0;
383 } else {
384 if (verbose)
385 pm_message("%d byte block at Position %ld", count, pos);
386 *eofP = false;
387 *lengthP = count;
388
389 if (count == 0) {
390 *errorP = NULL;
391 zeroDataBlock = true;
392 } else {
393 const char * error;
394
395 zeroDataBlock = false;
396 readFile(ifP, buf, count, &error);
397
398 if (error) {
399 pm_asprintf(errorP,
400 "Unable to read data portion of %u byte "
401 "DataBlock from file. %s", count, error);
402 pm_strfree(error);
403 } else
404 *errorP = NULL;
405 }
406 }
407 }
408
409
410
411 static void
412 readThroughEod(FILE * const ifP) {
413 /*----------------------------------------------------------------------------
414 Read the file 'ifP' through the next EOD marker. An EOD marker is a
415 a zero length data block.
416
417 If there is no EOD marker between the present file position and EOF,
418 we read to EOF and issue warning message about a missing EOD marker.
419 -----------------------------------------------------------------------------*/
420 unsigned char buf[256];
421 bool eod;
422
423 eod = false; /* initial value */
424 while (!eod) {
425 bool eof;
426 unsigned int count;
427 const char * error;
428
429 getDataBlock(ifP, buf, &eof, &count, &error);
430 if (error || eof)
431 pm_message("EOF encountered before EOD marker. The GIF "
432 "file is malformed, but we are proceeding "
433 "anyway as if an EOD marker were at the end "
434 "of the file.");
435 if (error || eof || count == 0)
436 eod = true;
437 }
438 }
439
440
441
442 static void
443 doPlainTextExtension(FILE * const ifP) {
444 #if 0
445 /* incomplete code fragment, attempt to handle Plain Text Extension */
446 GetDataBlock(ifP, (unsigned char*) buf, &eof, &length);
447
448 lpos = LM_to_uint(buf[0], buf[1]);
449 tpos = LM_to_uint(buf[2], buf[3]);
450 width = LM_to_uint(buf[4], buf[5]);
451 height = LM_to_uint(buf[6], buf[7]);
452 cellw = buf[8];
453 cellh = buf[9];
454 foreground = buf[10];
455 background = buf[11];
456 #else
457 readThroughEod(ifP);
458 #endif
459 }
460
461
462
463 static void
464 doCommentExtension(FILE * const ifP) {
465 /*----------------------------------------------------------------------------
466 Read the rest of a comment extension from the input file 'ifP' and handle
467 it.
468
469 We ought to deal with the possibility that the comment is not text. I.e.
470 it could have nonprintable characters or embedded nulls. I don't know if
471 the GIF spec requires regular text or not.
472 -----------------------------------------------------------------------------*/
473 char buf[256];
474 unsigned int blocklen;
475 bool done;
476
477 done = false;
478 while (!done) {
479 bool eof;
480 const char * error;
481 getDataBlock(ifP, (unsigned char*) buf, &eof, &blocklen, &error);
482 if (error)
483 pm_error("Error reading a data block in a comment extension. %s",
484 error);
485 if (blocklen == 0 || eof)
486 done = true;
487 else {
488 buf[blocklen] = '\0';
489 if (showComment) {
490 pm_message("gif comment: %s", buf);
491 }
492 }
493 }
494 }
495
496
497
498 static unsigned int
499 LM_to_uint(unsigned char const a,
500 unsigned char const b) {
501
502 return ((unsigned int)b << 8) | ((unsigned int) a << 0);
503 }
504
505
506
507 static void
508 doGraphicControlExtension(FILE * const ifP,
509 struct Gif89 * const gif89P) {
510
511 bool eof;
512 unsigned int length;
513 unsigned char buf[256];
514 const char * error;
515
516 getDataBlock(ifP, buf, &eof, &length, &error);
517 if (error)
518 pm_error("Error reading 1st data block of Graphic Control Extension");
519 if (eof)
520 pm_error("EOF/error encountered reading "
521 "1st DataBlock of Graphic Control Extension.");
522 else if (length < 4)
523 pm_error("graphic control extension 1st DataBlock too short. "
524 "It must be at least 4 bytes; it is %d bytes.",
525 length);
526 else {
527 gif89P->haveDisposal = true;
528 gif89P->disposal = (buf[0] >> 2) & 0x7;
529 gif89P->haveInputFlag = true;
530 gif89P->inputFlag = (buf[0] >> 1) & 0x1;
531 gif89P->haveDelayTime = true;
532 gif89P->delayTime = LM_to_uint(buf[1], buf[2]);
533 if ((buf[0] & 0x1) != 0) {
534 gif89P->haveTransColor = true;
535 gif89P->transparentIndex = buf[3];
536 }
537 readThroughEod(ifP);
538 }
539 }
540
541
542
543 static void
544 doExtension(FILE * const ifP,
545 unsigned char const label,
546 struct Gif89 * const gif89P) {
547
548 const char * str;
549
550 switch (label) {
551 case 0x01: /* Plain Text Extension */
552 str = pm_strdup("Plain Text");
553 doPlainTextExtension(ifP);
554 break;
555 case 0xff: /* Application Extension */
556 str = pm_strdup("Application");
557 readThroughEod(ifP);
558 break;
559 case 0xfe: /* Comment Extension */
560 str = pm_strdup("Comment");
561 doCommentExtension(ifP);
562 break;
563 case 0xf9: /* Graphic Control Extension */
564 str = pm_strdup("Graphic Control");
565 doGraphicControlExtension(ifP, gif89P);
566 break;
567 default: {
568 pm_asprintf(&str, "UNKNOWN (0x%02x)", label);
569 pm_message("Ignoring unrecognized extension (type 0x%02x)", label);
570 readThroughEod(ifP);
571 } break;
572 }
573 if (verbose)
574 pm_message(" got a '%s' extension", str);
575 pm_strfree(str);
576 }
577
578
579
580 struct GetCodeState {
581 unsigned char buf[280];
582 /* This is the buffer through which we read the data from the
583 stream. We must buffer it because we have to read whole data
584 blocks at a time, but our client wants one code at a time.
585 The buffer typically contains the contents of one data block
586 plus two bytes from the previous data block.
587 */
588 int bufCount;
589 /* This is the number of bytes of contents in buf[]. */
590 int curbit;
591 /* The bit number (starting at 0) within buf[] of the next bit
592 to be returned. If the next bit to be returned is not yet in
593 buf[] (we've already returned everything in there), this points
594 one beyond the end of the buffer contents.
595 */
596 bool streamExhausted;
597 /* The last time we read from the input stream, we got an EOD marker
598 or EOF or an error that prevents further reading of the stream.
599 */
600 };
601
602
603
604 static void
605 getAnotherBlock(FILE * const ifP,
606 struct GetCodeState * const gsP,
607 const char ** const errorP) {
608
609 unsigned int count;
610 unsigned int assumedCount;
611 bool eof;
612
613 /* Shift buffer down so last two bytes are now the
614 first two bytes. Shift 'curbit' cursor, which must
615 be somewhere in or immediately after those two
616 bytes, accordingly.
617 */
618 gsP->buf[0] = gsP->buf[gsP->bufCount-2];
619 gsP->buf[1] = gsP->buf[gsP->bufCount-1];
620
621 gsP->curbit -= (gsP->bufCount-2)*8;
622 gsP->bufCount = 2;
623
624 /* Add the next block to the buffer */
625 getDataBlock(ifP, &gsP->buf[gsP->bufCount], &eof, &count, errorP);
626 if (*errorP)
627 gsP->streamExhausted = true;
628 else {
629 if (eof) {
630 pm_message("EOF encountered in image "
631 "before EOD marker. The GIF "
632 "file is malformed, but we are proceeding "
633 "anyway as if an EOD marker were at the end "
634 "of the file.");
635 assumedCount = 0;
636 } else
637 assumedCount = count;
638
639 gsP->streamExhausted = (assumedCount == 0);
640
641 gsP->bufCount += assumedCount;
642 }
643 }
644
645
646
647 static struct GetCodeState getCodeState;
648
649 static void
650 getCode_init(struct GetCodeState * const getCodeStateP) {
651
652 /* Fake a previous data block */
653 getCodeStateP->buf[0] = 0;
654 getCodeStateP->buf[1] = 0;
655 getCodeStateP->bufCount = 2;
656 getCodeStateP->curbit = getCodeStateP->bufCount * 8;
657 getCodeStateP->streamExhausted = false;
658 }
659
660
661
662 static unsigned int
663 bitsOfLeBuffer(const unsigned char * const buf,
664 unsigned int const start,
665 unsigned int const len) {
666 /*----------------------------------------------------------------------------
667 Return a string of 'len' bits (up to 16) starting at bit 'start' of buffer
668 buf[].
669
670 In the buffer, the bits are numbered Intel-style, with the first bit of a
671 byte being the least significant bit. So bit 3 is the "16" bit of the
672 first byte of buf[].
673
674 We return the string as an integer such that its pure binary encoding with
675 the bits numbered Intel-style is the string. E.g. the string 0,1,1
676 yields six.
677 -----------------------------------------------------------------------------*/
678 uint32_t codeBlock;
679 /* The 3 whole bytes of the buffer that contain the requested
680 bit string
681 */
682
683 assert(len <= 16);
684
685 if (BYTE_ORDER == LITTLE_ENDIAN && UNALIGNED_OK)
686 /* Fast path */
687 codeBlock = *(uint32_t *) & buf[start/8];
688 else
689 /* logic works for little endian too */
690 codeBlock =
691 (buf[start/8+0] << 0) |
692 (buf[start/8+1] << 8) |
693 (buf[start/8+2] << 16);
694
695 return (unsigned int)
696 (codeBlock >> (start % 8)) & ((1 << len) - 1);
697 }
698
699
700
701 static void
702 getCode_get(struct GetCodeState * const gsP,
703 FILE * const ifP,
704 int const codeSize,
705 bool * const eofP,
706 unsigned int * const codeP,
707 const char ** const errorP) {
708 /*----------------------------------------------------------------------------
709 Read and return the next lzw code from the file *ifP.
710
711 'codeSize' is the number of bits in the code we are to get.
712
713 Return *eofP == true iff we hit the end of the stream. That means a legal
714 end of stream, marked by an EOD marker, not just end of file. An end of
715 file in the middle of the GIF stream is an error.
716
717 If there are bits left in the stream, but not 'codeSize' of them, we
718 call that a success with *eofP == true.
719
720 Return the code read (assuming *eofP == false and *errorP == NULL)
721 as *codeP.
722 -----------------------------------------------------------------------------*/
723
724 *errorP = NULL;
725
726 while (gsP->curbit + codeSize > gsP->bufCount * 8 &&
727 !gsP->streamExhausted && !*errorP)
728 /* Not enough left in buffer to satisfy request. Get the next
729 data block into the buffer.
730
731 Note that a data block may be as small as one byte, so we may need
732 to do this multiple times to get the full code. (This probably
733 never happens in practice).
734 */
735 getAnotherBlock(ifP, gsP, errorP);
736
737 if (!*errorP) {
738 if (gsP->curbit + codeSize > gsP->bufCount * 8) {
739 /* The buffer still doesn't have enough bits in it; that means
740 there were no data blocks left to read.
741 */
742 *eofP = true;
743
744 {
745 int const bitsUnused = gsP->bufCount * 8 - gsP->curbit;
746 if (bitsUnused > 0)
747 pm_message("Stream ends with a partial code "
748 "(%d bits left in file; "
749 "expected a %d bit code). Ignoring.",
750 bitsUnused, codeSize);
751 }
752 } else {
753 *codeP = bitsOfLeBuffer(gsP->buf, gsP->curbit, codeSize);
754
755 if (verbose && wantLzwCodes)
756 pm_message("LZW code=0x%03x [%d]", *codeP, codeSize);
757
758 gsP->curbit += codeSize;
759 *eofP = false;
760 }
761 }
762 }
763
764
765
766 struct Stack {
767 /* Stack grows from low addresses to high addresses */
768 unsigned char * stack; /* malloc'ed array */
769 unsigned char * sp; /* stack pointer */
770 unsigned char * top; /* next word above top of stack */
771 };
772
773
774
775 static void
776 initStack(struct Stack * const stackP, unsigned int const size) {
777
778 MALLOCARRAY(stackP->stack, size);
779 if (stackP->stack == NULL)
780 pm_error("Unable to allocate %d-word stack.", size);
781 stackP->sp = stackP->stack;
782 stackP->top = stackP->stack + size;
783 }
784
785
786
787 static void
788 pushStack(struct Stack * const stackP, unsigned char const value) {
789
790 if (stackP->sp >= stackP->top)
791 pm_error("stack overflow");
792
793 *(stackP->sp++) = value;
794 }
795
796
797
798 static bool
799 stackIsEmpty(const struct Stack * const stackP) {
800 return stackP->sp == stackP->stack;
801 }
802
803
804
805 static unsigned char
806 popStack(struct Stack * const stackP) {
807
808 if (stackP->sp <= stackP->stack)
809 pm_error("stack underflow");
810
811 return *(--stackP->sp);
812 }
813
814
815
816 static void
817 termStack(struct Stack * const stackP) {
818 free(stackP->stack);
819 stackP->stack = NULL;
820 }
821
822
823
824 /*----------------------------------------------------------------------------
825 Some notes on LZW.
826
827 LZW is an extension of Limpel-Ziv. The two extensions are:
828
829 1) In Limpel-Ziv, codes are all the same number of bits. In
830 LZW, they start out small and increase as the stream progresses.
831
832 2) LZW has a clear code that resets the string table and code
833 size.
834
835 The LZW code space is allocated as follows:
836
837 The true data elements are dataWidth bits wide, so the maximum
838 value of a true data element is 2**dataWidth-1. We call that
839 maxDataVal. The first byte in the stream tells you what dataWidth
840 is.
841
842 LZW codes 0 - maxDataVal are direct codes. Each one represents
843 the true data element whose value is that of the LZW code itself.
844 No decompression is required.
845
846 maxDataVal + 1 and up are compression codes. They encode
847 true data elements:
848
849 maxDataVal + 1 is the clear code.
850
851 maxDataVal + 2 is the end code.
852
853 maxDataVal + 3 and up are string codes. Each string code
854 represents a string of true data elements. The translation from a
855 string code to the string of true data elements varies as the stream
856 progresses. In the beginning and after every clear code, the
857 translation table is empty, so no string codes are valid. As the
858 stream progresses, the table gets filled and more string codes
859 become valid.
860
861 At the beginning of the stream, string codes are represented by
862 dataWidth + 1 bits. When enough codes have been defined to use up that
863 space, they start being represented by dataWidth + 2 bits, and so on.
864
865 What we call 'dataWidth', others call the "minimum code size," which is a
866 misnomer, because the minimum code size in a stream must be at least one
867 more than 'dataWidth', to accommmodate the clear and end codes.
868 -----------------------------------------------------------------------------*/
869
870 static int const maxLzwCodeCt = (1<<MAX_LZW_BITS);
871
872 typedef struct {
873 /*----------------------------------------------------------------------------
874 An entry in the decompressor LZW code table.
875 -----------------------------------------------------------------------------*/
876 unsigned int next;
877 /* The next code in the expansion after the one this entry specifies;
878 this is either another index into the LZW code table or a direct
879 code, which means it's the last data element in the expansion.
880 */
881 unsigned int dataElement;
882 /* The data element (color map index or gray level) to add to the
883 expansion for this entry.
884 */
885 } CodeTableEntry;
886
887 typedef struct {
888 struct Stack stack;
889 bool fresh;
890 /* The stream is right after a clear code or at the very beginning */
891 unsigned int codeSize;
892 /* The current code size -- each LZW code in this part of the image
893 is this many bits. Ergo, we read this many bits at a time from
894 the stream.
895 */
896 unsigned int maxCodeCt;
897 /* The maximum number of LZW codes that can be represented with the
898 current code size. (1 << codeSize)
899 */
900 unsigned int nextTableSlot;
901 /* Index in the code translation table of the next free entry */
902 unsigned int firstcode;
903 /* This is always a true data element code */
904 unsigned int prevcode;
905 /* The code just before, in the image, the one we're processing now */
906
907 /* The following are constant for the life of the decompressor */
908 FILE * ifP;
909 unsigned int initCodeSize;
910 /* The code size, in bits, at the start of the stream and immediately
911 after a Clear code.
912 */
913 unsigned int cmapSize;
914 unsigned int maxDataVal;
915 unsigned int clearCode;
916 unsigned int endCode;
917 bool haveTransColor;
918 unsigned int transparentIndex;
919 /* meaningful only when 'haveTransColor' is true */
920 bool tolerateBadInput;
921 /* We are to tolerate bad input data as best we can, rather than
922 just declaring an error and bailing out.
923 */
924 CodeTableEntry table[(1 << MAX_LZW_BITS)]; /* LZW code table */
925 /* This contains the strings of expansions of LZW string codes, in
926 linked list form. table[N] gives the first data element for the
927 string with string code N and the LZW code for the rest of the
928 string. The latter is often a string code itself, which can also
929 be looked up in this table.
930 */
931 } Decompressor;
932
933
934
935 static void
936 resetDecompressor(Decompressor * const decompP) {
937
938 decompP->codeSize = decompP->initCodeSize;
939 decompP->maxCodeCt = 1 << decompP->codeSize;
940 decompP->nextTableSlot = decompP->maxDataVal + 3;
941 decompP->fresh = true;
942 }
943
944
945
946 static void
947 validateTransparentIndex(unsigned int const transparentIndex,
948 bool const tolerateBadInput,
949 unsigned int const cmapSize,
950 unsigned int const maxDataVal) {
951
952 if (transparentIndex >= cmapSize) {
953 if (tolerateBadInput) {
954 if (transparentIndex > maxDataVal)
955 pm_error("Invalid transparent index value: %u",
956 transparentIndex);
957 } else {
958 pm_error("Invalid transparent index value %d in image with "
959 "only %u colors. %s",
960 transparentIndex, cmapSize,
961 transparentIndex <= maxDataVal ?
962 "" :
963 "Use the -repair option to try to render the "
964 "image overriding this error.");
965 }
966 }
967 }
968
969
970
971 static void
972 lzwInit(Decompressor * const decompP,
973 FILE * const ifP,
974 int const dataWidth,
975 unsigned int const cmapSize,
976 bool const haveTransColor,
977 unsigned int const transparentIndex,
978 bool const tolerateBadInput) {
979
980 unsigned int const maxDataVal = (1 << dataWidth) - 1;
981
982 if (verbose)
983 pm_message("Image says the data width is %u bits", dataWidth);
984
985 decompP->ifP = ifP;
986 decompP->initCodeSize = dataWidth + 1;
987 decompP->cmapSize = cmapSize;
988 decompP->tolerateBadInput = tolerateBadInput;
989 decompP->maxDataVal = maxDataVal;
990 decompP->clearCode = maxDataVal + 1;
991 decompP->endCode = maxDataVal + 2;
992
993 if (verbose)
994 pm_message("Initial code size is %u bits; clear code = 0x%03x, "
995 "end code = 0x%03x",
996 decompP->initCodeSize,
997 decompP->clearCode, decompP->endCode);
998
999 /* The entries in the translation table for true data codes are
1000 constant throughout the image. For PBM output we make an
1001 adjustment later. Once set entries never change.
1002 */
1003 {
1004 unsigned int i;
1005 for (i = 0; i <= maxDataVal; ++i) {
1006 decompP->table[i].next = 0;
1007 decompP->table[i].dataElement = i < cmapSize ? i : 0;
1008 }
1009 }
1010 decompP->haveTransColor = haveTransColor;
1011 decompP->transparentIndex = transparentIndex;
1012
1013 if (haveTransColor)
1014 validateTransparentIndex(transparentIndex, tolerateBadInput,
1015 cmapSize, maxDataVal);
1016
1017 resetDecompressor(decompP);
1018
1019 getCode_init(&getCodeState);
1020
1021 decompP->fresh = true;
1022
1023 initStack(&decompP->stack, maxLzwCodeCt);
1024
1025 assert(decompP->initCodeSize < sizeof(decompP->maxDataVal) * 8 + 1);
1026 }
1027
1028
1029
1030 static void
1031 lzwAdjustForPBM(Decompressor * const decompP,
1032 GifColorMap const cmap) {
1033 /*----------------------------------------------------------------------------
1034 In the PBM case we use the table index value directly instead of looking up
1035 the color map for each pixel.
1036
1037 Note that cmap.size is not always 2.
1038
1039 Similar logic should work for PGM.
1040 ----------------------------------------------------------------------------*/
1041 unsigned int i;
1042 for (i = 0; i < cmap.size; ++i)
1043 decompP->table[i].dataElement =
1044 cmap.map[i][0] == 0 ? PBM_BLACK : PBM_WHITE;
1045 }
1046
1047
1048
1049 static void
1050 lzwTerm(Decompressor * const decompP) {
1051
1052 termStack(&decompP->stack);
1053 }
1054
1055
1056
1057 static void
1058 pushWholeStringOnStack(Decompressor * const decompP,
1059 unsigned int const code0) {
1060 /*----------------------------------------------------------------------------
1061 Get the whole string that compression code 'code0' represents and push
1062 it onto the code stack so the leftmost code is on top. Set
1063 decompP->firstcode to the first (leftmost) code in that string.
1064 -----------------------------------------------------------------------------*/
1065 unsigned int code;
1066 unsigned int stringCount;
1067
1068 for (stringCount = 0, code = code0;
1069 code > decompP->maxDataVal;
1070 ++stringCount, code = decompP->table[code].next
1071 ) {
1072
1073 pushStack(&decompP->stack, decompP->table[code].dataElement);
1074 }
1075 decompP->firstcode = decompP->table[code].dataElement;
1076 pushStack(&decompP->stack, decompP->firstcode);
1077 }
1078
1079
1080
1081 static void
1082 addLzwStringCode(Decompressor * const decompP) {
1083
1084 if (decompP->nextTableSlot < maxLzwCodeCt) {
1085 decompP->table[decompP->nextTableSlot].next =
1086 decompP->prevcode;
1087 decompP->table[decompP->nextTableSlot].dataElement =
1088 decompP->firstcode;
1089 ++decompP->nextTableSlot;
1090 if (decompP->nextTableSlot >= decompP->maxCodeCt) {
1091 /* We've used up all the codes of the current code size.
1092 Future codes in the stream will have codes one bit longer.
1093 But there's an exception if we're already at the LZW
1094 maximum, in which case the codes will simply continue
1095 the same size and no new ones will be defined.
1096 */
1097 if (decompP->codeSize < MAX_LZW_BITS) {
1098 ++decompP->codeSize;
1099 decompP->maxCodeCt = 1 << decompP->codeSize;
1100 }
1101 }
1102 }
1103 }
1104
1105
1106
1107 static void
1108 expandCodeOntoStack(Decompressor * const decompP,
1109 unsigned int const incode,
1110 const char ** const errorP) {
1111 /*----------------------------------------------------------------------------
1112 'incode' is an LZW string code. It represents a string of true data
1113 elements, as defined by the string translation table in *decompP.
1114
1115 Expand the code to a string of LZW direct codes and push them onto the
1116 stack such that the leftmost code is on top.
1117
1118 Also add to the translation table where appropriate.
1119
1120 Iff the translation table contains a cycle (which means the LZW stream
1121 from which it was built is invalid), fail (return text explanation
1122 as *errorP).
1123 -----------------------------------------------------------------------------*/
1124 unsigned int code;
1125 const char * gifError;
1126
1127 gifError = NULL; /* Initial value */
1128
1129 if (incode <= decompP->maxDataVal) {
1130 if (incode < decompP->cmapSize)
1131 code = incode; /* Direct index */
1132 else if (decompP->tolerateBadInput &&
1133 decompP->haveTransColor &&
1134 decompP->table[incode].dataElement ==
1135 decompP->transparentIndex)
1136 /* transparent code outside cmap exceptional case */
1137 code = incode;
1138 else
1139 pm_asprintf(&gifError, "Invalid color code %u. "
1140 "Valid color values are 0 - %u",
1141 incode, decompP->cmapSize - 1);
1142 } else if (incode < decompP->nextTableSlot)
1143 /* LZW string, defined */
1144 code = incode;
1145 else if (incode == decompP->nextTableSlot) {
1146 /* It's a code that isn't in our translation table yet.
1147 */
1148 if (decompP->fresh)
1149 pm_asprintf(&gifError, "LZW string code encountered with "
1150 "decompressor in fresh state");
1151 else {
1152 if (wantLzwCodes && verbose)
1153 pm_message ("LZW code valid, but not in decoder table");
1154
1155 pushStack(&decompP->stack, decompP->firstcode);
1156 code = decompP->prevcode;
1157 }
1158 } else
1159 pm_asprintf(&gifError, "LZW string code %u "
1160 "is neither a previously defined one nor the "
1161 "next in sequence to define (%u)",
1162 incode, decompP->nextTableSlot);
1163
1164 if (gifError) {
1165 pm_asprintf(errorP, "INVALID GIF IMAGE: %s", gifError);
1166 pm_strfree(gifError);
1167 } else {
1168 pushWholeStringOnStack(decompP, code);
1169
1170 addLzwStringCode(decompP);
1171
1172 decompP->prevcode = incode;
1173
1174 *errorP = NULL;
1175 }
1176 }
1177
1178
1179
1180 static void
1181 lzwReadByteFresh(struct GetCodeState * const getCodeStateP,
1182 Decompressor * const decompP,
1183 bool * const endOfImageP,
1184 unsigned char * const dataReadP,
1185 const char ** const errorP) {
1186 /*----------------------------------------------------------------------------
1187 Read off all initial clear codes, read the first non-clear code, and return
1188 it as *dataReadP.
1189
1190 Iff we hit end of image in so doing, return *endOfImageP true and nothing as
1191 *dataReadP. One way we hit end of image is for that first non-clear code to
1192 be an end code.
1193
1194 Assume the decompressor is fresh, i.e. there are no strings in the table
1195 yet, so the next code must be a direct true data code.
1196 -----------------------------------------------------------------------------*/
1197 unsigned int code;
1198 bool eof;
1199
1200 assert(decompP->fresh); /* Entry requirement */
1201
1202 decompP->fresh = false;
1203
1204 do {
1205 getCode_get(getCodeStateP, decompP->ifP, decompP->codeSize,
1206 &eof, &code, errorP);
1207 } while (!*errorP && !eof && code == decompP->clearCode);
1208
1209 if (!*errorP) {
1210 if (eof)
1211 *endOfImageP = true;
1212 else if (code == decompP->endCode) {
1213 if (!zeroDataBlock)
1214 readThroughEod(decompP->ifP);
1215 *endOfImageP = true;
1216 } else if (code >= decompP->cmapSize) {
1217 pm_asprintf(errorP, "Error in GIF image: invalid color code %u. "
1218 "Valid color values are: 0 - %u",
1219 code, decompP->cmapSize-1);
1220 /* Set these values in order to avoid errors in the -repair
1221 case
1222 */
1223 decompP->prevcode = decompP->firstcode = 0;
1224
1225 *endOfImageP = false;
1226 } else { /* valid code */
1227 decompP->prevcode = code;
1228 decompP->firstcode = decompP->table[code].dataElement;
1229 *dataReadP = decompP->firstcode;
1230 *endOfImageP = false;
1231 }
1232 }
1233 }
1234
1235
1236
1237 static void
1238 lzwReadByte(Decompressor * const decompP,
1239 unsigned char * const dataReadP,
1240 bool * const endOfImageP,
1241 const char ** const errorP) {
1242 /*----------------------------------------------------------------------------
1243 Return the next data element of the decompressed image. In the context
1244 of a GIF, a data element is the color table index of one pixel.
1245
1246 We read and return the next byte of the decompressed image.
1247
1248 If we can't, because the stream is too corrupted to make sense out of
1249 it or the stream ends, we fail (return text description of why as
1250 *errorP).
1251
1252 We forgive the case that the "end" code is the end of the stream --
1253 not followed by an EOD marker (zero length DataBlock).
1254
1255 Iff we can't read a byte because we've hit the end of the image,
1256 we return *endOfImageP = true.
1257 -----------------------------------------------------------------------------*/
1258 if (!stackIsEmpty(&decompP->stack)) {
1259 *errorP = NULL;
1260 *endOfImageP = false;
1261 *dataReadP = popStack(&decompP->stack);
1262 } else if (decompP->fresh) {
1263 lzwReadByteFresh(&getCodeState, decompP, endOfImageP, dataReadP,
1264 errorP);
1265 } else {
1266 unsigned int code;
1267 bool eof;
1268 getCode_get(&getCodeState, decompP->ifP, decompP->codeSize,
1269 &eof, &code, errorP);
1270 if (!*errorP) {
1271 if (eof)
1272 pm_asprintf(errorP,
1273 "Premature end of file; no proper GIF closing");
1274 else {
1275 if (code == decompP->clearCode) {
1276 resetDecompressor(decompP);
1277 lzwReadByteFresh(&getCodeState, decompP, endOfImageP,
1278 dataReadP, errorP);
1279 } else {
1280 if (code == decompP->endCode) {
1281 if (!zeroDataBlock)
1282 readThroughEod(decompP->ifP);
1283 *endOfImageP = true;
1284 *errorP = NULL;
1285 } else {
1286 *endOfImageP = false;
1287 expandCodeOntoStack(decompP, code, errorP);
1288 if (!*errorP)
1289 *dataReadP = popStack(&decompP->stack);
1290 }
1291 }
1292 }
1293 }
1294 }
1295 }
1296
1297
1298
1299 enum pass {MULT8PLUS0, MULT8PLUS4, MULT4PLUS2, MULT2PLUS1};
1300
1301 static void
1302 bumpRowInterlace(unsigned int const rows,
1303 unsigned int * const rowP,
1304 enum pass * const passP) {
1305 /*----------------------------------------------------------------------------
1306 Move *pixelCursorP to the next row in the interlace pattern.
1307 -----------------------------------------------------------------------------*/
1308 /* There are 4 passes:
1309 MULT8PLUS0: Rows 8, 16, 24, 32, etc.
1310 MULT8PLUS4: Rows 4, 12, 20, 28, etc.
1311 MULT4PLUS2: Rows 2, 6, 10, 14, etc.
1312 MULT2PLUS1: Rows 1, 3, 5, 7, 9, etc.
1313 */
1314
1315 switch (*passP) {
1316 case MULT8PLUS0:
1317 *rowP += 8;
1318 break;
1319 case MULT8PLUS4:
1320 *rowP += 8;
1321 break;
1322 case MULT4PLUS2:
1323 *rowP += 4;
1324 break;
1325 case MULT2PLUS1:
1326 *rowP += 2;
1327 break;
1328 }
1329 /* Set the proper pass for the next read. Note that if there are
1330 more than 4 rows, the sequence of passes is sequential, but
1331 when there are fewer than 4, we may skip e.g. from MULT8PLUS0
1332 to MULT4PLUS2.
1333 */
1334 while (*rowP >= rows && *passP != MULT2PLUS1) {
1335 switch (*passP) {
1336 case MULT8PLUS0:
1337 *passP = MULT8PLUS4;
1338 *rowP = 4;
1339 break;
1340 case MULT8PLUS4:
1341 *passP = MULT4PLUS2;
1342 *rowP = 2;
1343 break;
1344 case MULT4PLUS2:
1345 *passP = MULT2PLUS1;
1346 *rowP = 1;
1347 break;
1348 case MULT2PLUS1:
1349 /* We've read the entire image */
1350 break;
1351 }
1352 }
1353 }
1354
1355
1356
1357 static void
1358 renderRow(unsigned char * const cmapIndexRow,
1359 unsigned int const cols,
1360 GifColorMap const cmap,
1361 bool const haveTransColor,
1362 unsigned int const transparentIndex,
1363 FILE * const imageOutfile,
1364 int const format,
1365 xel * const xelrow,
1366 FILE * const alphaFileP,
1367 bit * const alphabits) {
1368 /*----------------------------------------------------------------------------
1369 Convert one row of cmap indexes to PPM/PGM/PBM output.
1370
1371 The row is *xelrow, which is 'cols' columns wide and has pixels of format
1372 'format'.
1373
1374 Render the alpha row to *alphaFileP iff 'alphabits' is non-NULL. If
1375 'haveTransColor' is false, render all white (i.e. the row is
1376 opaque). 'alphabits' is otherwise just a one-row buffer for us to use
1377 in rendering the alpha row.
1378
1379 imageOutfile is NULL if user wants only the alpha file.
1380 ----------------------------------------------------------------------------*/
1381 if (alphabits) {
1382 unsigned int col;
1383
1384 for (col=0; col < cols; ++col) {
1385 alphabits[col] =
1386 (haveTransColor && cmapIndexRow[col] == transparentIndex) ?
1387 PBM_BLACK : PBM_WHITE;
1388 }
1389 pbm_writepbmrow(alphaFileP, alphabits, cols, false);
1390 }
1391
1392 if (imageOutfile) {
1393 if (useFastPbmRender && format == PBM_FORMAT && !haveTransColor) {
1394
1395 bit * const bitrow = cmapIndexRow;
1396
1397 pbm_writepbmrow(imageOutfile, bitrow, cols, false);
1398 } else {
1399 /* PPM, PGM and PBM with transparent */
1400 unsigned int col;
1401 for (col = 0; col < cols; ++col) {
1402 unsigned char const cmapIndex = cmapIndexRow[col];
1403 const unsigned char * const color = cmap.map[cmapIndex];
1404 assert(cmapIndex < cmap.size);
1405 PPM_ASSIGN(xelrow[col],
1406 color[CM_RED], color[CM_GRN],color[CM_BLU]);
1407 }
1408 pnm_writepnmrow(imageOutfile, xelrow, cols,
1409 GIFMAXVAL, format, false);
1410 }
1411 }
1412 }
1413
1414
1415
1416 static void
1417 verifyPixelRead(bool const endOfImage,
1418 const char * const readError,
1419 unsigned int const cols,
1420 unsigned int const rows,
1421 const char ** const errorP) {
1422
1423 if (readError)
1424 *errorP = pm_strdup(readError);
1425 else {
1426 if (endOfImage)
1427 pm_asprintf(errorP,
1428 "Error in GIF image: Not enough raster data to fill "
1429 "%u x %u dimensions. "
1430 "The image has proper ending sequence, so "
1431 "this is not just a truncated file.",
1432 cols, rows);
1433 else
1434 *errorP = NULL;
1435 }
1436 }
1437
1438
1439
1440 static int
1441 pnmFormat(bool const hasGray,
1442 bool const hasColor) {
1443 /*----------------------------------------------------------------------------
1444 The proper PNM format (PBM, PGM, or PPM) for an image described
1445 by 'hasGray' and 'hasColor'.
1446 -----------------------------------------------------------------------------*/
1447 int format;
1448
1449 if (hasColor) {
1450 format = PPM_FORMAT;
1451 } else if (hasGray) {
1452 format = PGM_FORMAT;
1453 } else {
1454 format = PBM_FORMAT;
1455 }
1456
1457 return format;
1458 }
1459
1460
1461
1462 static void
1463 makePnmRow(Decompressor * const decompP,
1464 unsigned int const cols,
1465 unsigned int const rows,
1466 bool const fillWithZero,
1467 unsigned char *const cmapIndexRow,
1468 const char ** const errorP) {
1469
1470 bool fillingWithZero;
1471 unsigned int col;
1472
1473 *errorP = NULL; /* initial value */
1474
1475 for (col = 0, fillingWithZero = fillWithZero;
1476 col < cols;
1477 ++col) {
1478
1479 unsigned char colorIndex;
1480
1481 if (fillingWithZero)
1482 colorIndex = 0;
1483 else {
1484 const char * readError;
1485 unsigned char readColorIndex;
1486 bool endOfImage;
1487
1488 lzwReadByte(decompP, &readColorIndex, &endOfImage, &readError);
1489
1490 verifyPixelRead(endOfImage, readError, cols, rows, errorP);
1491
1492 if (readError)
1493 pm_strfree(readError);
1494
1495 if (*errorP) {
1496 /* Caller may want to try to ignore this error, so we
1497 fill out the row with zeroes. Note that we can't possibly
1498 have another error while doing that.
1499 */
1500 fillingWithZero = true;
1501 colorIndex = 0;
1502 } else
1503 colorIndex = readColorIndex;
1504 }
1505 cmapIndexRow[col] = colorIndex;
1506 }
1507 }
1508
1509
1510
1511 static void
1512 convertRaster(Decompressor * const decompP,
1513 unsigned int const cols,
1514 unsigned int const rows,
1515 GifColorMap const cmap,
1516 bool const interlace,
1517 FILE * const imageOutFileP,
1518 FILE * const alphaFileP,
1519 bool const hasGray,
1520 bool const hasColor) {
1521 /*----------------------------------------------------------------------------
1522 Read the raster from the GIF decompressor *decompP, and write it as a
1523 complete PNM stream (starting with the header) on *imageOutFileP and
1524 *alphaFileP.
1525
1526 Assume that raster is 'cols' x 'rows', refers to colormap 'cmap', and is
1527 interlaced iff 'interlace' is true.
1528
1529 Assume the image has gray levels and/or color per 'hasGray' and 'hasColor'.
1530 -----------------------------------------------------------------------------*/
1531 int const format = pnmFormat(hasGray, hasColor);
1532
1533 enum pass pass;
1534 bool fillingMissingPixels;
1535 unsigned int row;
1536 unsigned char ** cmapIndexArray;
1537 bit * alphabits;
1538 xel * xelrow;
1539 unsigned int outrow;
1540 /* Non-interlace: outrow is always 0: cmapIndexRow keeps pointing
1541 to the single row in array.
1542
1543 Interlace: outrow is modified with each call to bumpRowInterface().
1544 */
1545
1546 MALLOCARRAY2(cmapIndexArray, interlace ? rows : 1 , cols);
1547
1548 if (verbose)
1549 pm_message("writing a %s file", pnm_formattypenm(format));
1550
1551 if (imageOutFileP)
1552 pnm_writepnminit(imageOutFileP, cols, rows, GIFMAXVAL, format, false);
1553 if (alphaFileP)
1554 pbm_writepbminit(alphaFileP, cols, rows, false);
1555
1556 xelrow = pnm_allocrow(cols);
1557 if (!xelrow)
1558 pm_error("couldn't alloc space for image" );
1559
1560 if (alphaFileP) {
1561 alphabits = pbm_allocrow(cols);
1562 if (!alphabits)
1563 pm_error("couldn't alloc space for alpha image" );
1564 } else
1565 alphabits = NULL;
1566
1567 fillingMissingPixels = false; /* initial value */
1568 pass = MULT8PLUS0;
1569 outrow = 0;
1570
1571 for (row = 0; row < rows; ++row) {
1572 const char * problem;
1573 makePnmRow(decompP, cols, rows, fillingMissingPixels,
1574 cmapIndexArray[outrow], &problem);
1575
1576 if (problem) {
1577 /* makePnmRow() recovered from the problem and produced an output
1578 row, stuffed with zeroes as necessary
1579 */
1580 if (decompP->tolerateBadInput) {
1581 pm_message("WARNING: %s. "
1582 "Filling bottom %u rows with arbitrary color",
1583 problem, rows - row);
1584 fillingMissingPixels = true;
1585 } else
1586 pm_error("Unable to read input image. %s "
1587 "(Output row: %u). "
1588 "Use the -repair option to try to salvage "
1589 "some of the image",
1590 problem, interlace ? outrow : row);
1591 }
1592
1593 if (interlace)
1594 bumpRowInterlace(rows, &outrow, &pass);
1595 else
1596 renderRow(cmapIndexArray[outrow], cols, cmap,
1597 decompP->haveTransColor, decompP->transparentIndex,
1598 imageOutFileP, format, xelrow, alphaFileP, alphabits);
1599 }
1600 /* All rows decompressed (and rendered and output if non-interlaced) */
1601 if (interlace) {
1602 unsigned int row;
1603 for (row = 0; row < rows; ++row)
1604 renderRow(cmapIndexArray[row], cols, cmap,
1605 decompP->haveTransColor, decompP->transparentIndex,
1606 imageOutFileP, format, xelrow, alphaFileP, alphabits);
1607 }
1608
1609 pnm_freerow(xelrow);
1610 if (alphabits)
1611 pbm_freerow(alphabits);
1612 pm_freearray2((void **)cmapIndexArray);
1613 }
1614
1615
1616
1617 static void
1618 skipExtraneousData(Decompressor * const decompP) {
1619
1620 unsigned char byteRead;
1621 bool endOfImage;
1622 const char * error;
1623
1624 endOfImage = false; /* initial value */
1625
1626 lzwReadByte(decompP, &byteRead, &endOfImage, &error);
1627
1628 if (error)
1629 pm_strfree(error);
1630 else {
1631 if (!endOfImage) {
1632 pm_message("Extraneous data at end of image. "
1633 "Skipped to end of image");
1634
1635 while (!endOfImage && !error)
1636 lzwReadByte(decompP, &byteRead, &endOfImage, &error);
1637
1638 if (error) {
1639 pm_message("Error encountered skipping to end of image: %s",
1640 error);
1641 pm_strfree(error);
1642 }
1643 }
1644 }
1645 }
1646
1647
1648
1649 static void
1650 issueTransparencyMessage(bool const haveTransColor,
1651 unsigned int const transparentIndex,
1652 GifColorMap const cmap) {
1653 /*----------------------------------------------------------------------------
1654 If user wants verbose output, tell him whether there is a transparent
1655 background color ('haveTransColor') and if so what it is
1656 ('transparentIndex').
1657
1658 Some GIFs put transparentIndex outside the color map. Allow this only
1659 with "-repair", checked in lzwInit(). Here we issue a warning and report
1660 the substitute color.
1661 -----------------------------------------------------------------------------*/
1662 if (verbose) {
1663 if (haveTransColor) {
1664 if (transparentIndex >= cmap.size) {
1665 const unsigned char * const color = cmap.map[0];
1666 pm_message("WARNING: Transparent index %u "
1667 "is outside color map. "
1668 "substitute background color: rgb:%02x/%02x/%02x ",
1669 transparentIndex,
1670 color[CM_RED],
1671 color[CM_GRN],
1672 color[CM_BLU]
1673 );
1674 } else {
1675 const unsigned char * const color = cmap.map[transparentIndex];
1676 pm_message("transparent background color: rgb:%02x/%02x/%02x "
1677 "Index %u",
1678 color[CM_RED],
1679 color[CM_GRN],
1680 color[CM_BLU],
1681 transparentIndex
1682 );
1683 }
1684 } else
1685 pm_message("no transparency");
1686 }
1687 }
1688
1689
1690
1691 static void
1692 readImageData(FILE * const ifP,
1693 unsigned int const cols,
1694 unsigned int const rows,
1695 GifColorMap const cmap,
1696 bool const interlace,
1697 bool const haveTransColor,
1698 unsigned int const transparentIndex,
1699 FILE * const imageOutFileP,
1700 FILE * const alphaFileP,
1701 bool const hasGray,
1702 bool const hasColor,
1703 bool const tolerateBadInput) {
1704
1705 unsigned char lzwDataWidth;
1706 Decompressor decomp;
1707 const char * error;
1708
1709 readFile(ifP, &lzwDataWidth, sizeof(lzwDataWidth), &error);
1710 if (error)
1711 pm_error("Can't read GIF stream "
1712 "right after an image separator; no "
1713 "image data follows. %s", error);
1714
1715 if (lzwDataWidth+1 > MAX_LZW_BITS)
1716 pm_error("Invalid data width (bits for a true data item) "
1717 "in image data: %u. "
1718 "Maximum allowable code size in GIF is %u, "
1719 "and a code has to be wide enough to accommodate both "
1720 "all possible data values and two control codes",
1721 lzwDataWidth, MAX_LZW_BITS);
1722
1723 lzwInit(&decomp, ifP, lzwDataWidth, cmap.size,
1724 haveTransColor, transparentIndex, tolerateBadInput);
1725
1726 issueTransparencyMessage(haveTransColor, transparentIndex, cmap);
1727
1728 if (useFastPbmRender && !hasGray && ! hasColor && !haveTransColor) {
1729 if (verbose)
1730 pm_message("Using fast PBM rendering");
1731 lzwAdjustForPBM(&decomp, cmap);
1732 }
1733 convertRaster(&decomp, cols, rows, cmap, interlace,
1734 imageOutFileP, alphaFileP,
1735 hasGray, hasColor);
1736
1737 skipExtraneousData(&decomp);
1738
1739 lzwTerm(&decomp);
1740 }
1741
1742
1743
1744 static void
1745 warnUserNotSquare(unsigned int const aspectRatio) {
1746
1747 const char * baseMsg =
1748 "warning - input pixels are not square, "
1749 "but we are rendering them as square pixels "
1750 "in the output";
1751
1752 if (pm_have_float_format()) {
1753 float const r = ((float)aspectRatio + 15.0 ) / 64.0;
1754
1755 pm_message("%s. To fix the output, run it through "
1756 "'pamscale -%cscale %g'",
1757 baseMsg,
1758 r < 1.0 ? 'x' : 'y',
1759 r < 1.0 ? 1.0 / r : r );
1760 } else
1761 pm_message("%s", baseMsg);
1762 }
1763
1764
1765
1766 static void
1767 readGifHeader(FILE * const gifFileP,
1768 struct GifScreen * const gifScreenP) {
1769 /*----------------------------------------------------------------------------
1770 Read the GIF stream header off the file *gifFileP, which is present
1771 positioned to the beginning of a GIF stream. Return the info from it
1772 as *gifScreenP.
1773 -----------------------------------------------------------------------------*/
1774 #define GLOBALCOLORMAP 0x80
1775
1776 unsigned char buf[16];
1777 char version[4];
1778 unsigned int cmapSize;
1779 const char * error;
1780
1781 readFile(gifFileP, buf, 6, &error);
1782 if (error)
1783 pm_error("Error reading magic number. %s", error);
1784
1785 if (!strneq((char *)buf, "GIF", 3))
1786 pm_error("File does not contain a GIF stream. It does not start "
1787 "with 'GIF'.");
1788
1789 strncpy(version, (char *)buf + 3, 3);
1790 version[3] = '\0';
1791
1792 if (verbose)
1793 pm_message("GIF format version is '%s'", version);
1794
1795 if ((!streq(version, "87a")) && (!streq(version, "89a")))
1796 pm_error("Bad version number, not '87a' or '89a'" );
1797
1798 readFile(gifFileP, buf, 7, &error);
1799 if (error)
1800 pm_error("Failed to read screen descriptor. %s", error);
1801
1802 gifScreenP->width = LM_to_uint(buf[0],buf[1]);
1803 gifScreenP->height = LM_to_uint(buf[2],buf[3]);
1804 cmapSize = 1 << ((buf[4] & 0x07) + 1);
1805 gifScreenP->colorResolution = (buf[4] & 0x70 >> 3) + 1;
1806 gifScreenP->background = buf[5];
1807 gifScreenP->aspectRatio = buf[6];
1808
1809 if (verbose) {
1810 pm_message("GIF Width = %u GIF Height = %u "
1811 "Pixel aspect ratio = %u (%f:1)",
1812 gifScreenP->width, gifScreenP->height,
1813 gifScreenP->aspectRatio,
1814 gifScreenP->aspectRatio == 0 ?
1815 1 : (gifScreenP->aspectRatio + 15) / 64.0);
1816 pm_message("Global color count = %u Color Resolution = %u",
1817 cmapSize, gifScreenP->colorResolution);
1818 }
1819 if (buf[4] & GLOBALCOLORMAP) {
1820 gifScreenP->hasGlobalColorMap = true;
1821 readColorMap(gifFileP, cmapSize, &gifScreenP->colorMap,
1822 &gifScreenP->hasGray, &gifScreenP->hasColor);
1823 if (verbose) {
1824 pm_message("Global color map %s grays, %s colors",
1825 gifScreenP->hasGray ? "contains" : "doesn't contain",
1826 gifScreenP->hasColor ? "contains" : "doesn't contain");
1827 }
1828 } else
1829 gifScreenP->hasGlobalColorMap = false;
1830
1831 if (gifScreenP->aspectRatio != 0 && gifScreenP->aspectRatio != 49)
1832 warnUserNotSquare(gifScreenP->aspectRatio);
1833
1834 #undef GLOBALCOLORMAP
1835 }
1836
1837
1838
1839 static void
1840 readExtensions(FILE* const ifP,
1841 struct Gif89 * const gif89P,
1842 bool * const eodP,
1843 const char ** const errorP) {
1844 /*----------------------------------------------------------------------------
1845 Read extension blocks from the GIF stream to which the file *ifP is
1846 positioned. Read up through the image separator that begins the
1847 next image or GIF stream terminator.
1848
1849 If we encounter EOD (end of GIF stream) before we find an image
1850 separator, we return *eodP == true. Else *eodP == false.
1851
1852 If we hit end of file before an EOD marker, we fail.
1853 -----------------------------------------------------------------------------*/
1854 bool imageStart;
1855 bool eod;
1856
1857 *errorP = NULL; /* initial value */
1858
1859 eod = false;
1860 imageStart = false;
1861
1862 /* Read the image descriptor */
1863 while (!imageStart && !eod && !*errorP) {
1864 unsigned char c;
1865 const char * error;
1866
1867 readFile(ifP, &c, sizeof(c), &error);
1868
1869 if (error) {
1870 pm_asprintf(errorP, "File read error where start of image "
1871 "descriptor or end of GIF expected. %s",
1872 error);
1873 pm_strfree(error);
1874 } else {
1875 if (c == ';') { /* GIF terminator */
1876 eod = true;
1877 } else if (c == '!') { /* Extension */
1878 unsigned char functionCode;
1879 const char * error;
1880
1881 readFile(ifP, &functionCode, 1, &error);
1882
1883 if (error) {
1884 pm_asprintf(errorP, "Failed to read function code "
1885 "of GIF extension (immediately after the '!' "
1886 "extension delimiter) from input. %s", error);
1887 pm_strfree(error);
1888 } else {
1889 doExtension(ifP, functionCode, gif89P);
1890 }
1891 } else if (c == ',')
1892 imageStart = true;
1893 else
1894 pm_message("Encountered invalid character 0x%02x while "
1895 "seeking extension block, ignoring", (int)c);
1896 }
1897 }
1898 *eodP = eod;
1899 }
1900
1901
1902
1903 struct GifImageHeader {
1904 /*----------------------------------------------------------------------------
1905 Information in the header (first 9 bytes) of a GIF image.
1906 -----------------------------------------------------------------------------*/
1907 bool hasLocalColormap;
1908 /* The image has its own color map. Its size is 'localColorMapSize' */
1909 /* (If an image does not have its own color map, the image uses the
1910 global color map for the GIF stream)
1911 */
1912 unsigned int localColorMapSize;
1913 /* Meaningful only if 'hasLocalColormap' is true. */
1914
1915 /* Position of the image (max 65535) */
1916 unsigned int lpos;
1917 unsigned int tpos;
1918
1919 /* Dimensions of the image (max 65535) */
1920 unsigned int cols;
1921 unsigned int rows;
1922
1923 bool interlaced;
1924 };
1925
1926
1927
1928 static void
1929 reportImageHeader(struct GifImageHeader const imageHeader) {
1930
1931 pm_message("reading %u by %u%s GIF image",
1932 imageHeader.cols, imageHeader.rows,
1933 imageHeader.interlaced ? " interlaced" : "" );
1934
1935 if (imageHeader.lpos > 0 || imageHeader.tpos > 0)
1936 pm_message(" Image left position: %u top position: %u",
1937 imageHeader.lpos, imageHeader.tpos);
1938
1939 if (imageHeader.hasLocalColormap)
1940 pm_message(" Uses local colormap of %u colors",
1941 imageHeader.localColorMapSize);
1942 else
1943 pm_message(" Uses global colormap");
1944 }
1945
1946
1947
1948 static void
1949 readImageHeader(FILE * const ifP,
1950 struct GifImageHeader * const imageHeaderP) {
1951
1952 #define LOCALCOLORMAP 0x80
1953 #define INTERLACE 0x40
1954
1955 unsigned char buf[16];
1956 const char * error;
1957
1958 readFile(ifP, buf, 9, &error);
1959 if (error)
1960 pm_error("couldn't read left/top/width/height. %s", error);
1961
1962 imageHeaderP->hasLocalColormap = !!(buf[8] & LOCALCOLORMAP);
1963 imageHeaderP->localColorMapSize = 1u << ((buf[8] & 0x07) + 1);
1964 imageHeaderP->lpos = LM_to_uint(buf[0], buf[1]);
1965 imageHeaderP->tpos = LM_to_uint(buf[2], buf[3]);
1966 imageHeaderP->cols = LM_to_uint(buf[4], buf[5]);
1967 imageHeaderP->rows = LM_to_uint(buf[6], buf[7]);
1968 imageHeaderP->interlaced = !!(buf[8] & INTERLACE);
1969
1970 if (verbose)
1971 reportImageHeader(*imageHeaderP);
1972
1973 #undef INTERLACE
1974 #undef LOCALCOLORMAP
1975 }
1976
1977
1978
1979 static void
1980 validateWithinGlobalScreen(struct GifImageHeader const imageHeader,
1981 struct GifScreen const gifScreen) {
1982
1983 unsigned long int const rpos = imageHeader.lpos + imageHeader.cols;
1984 unsigned long int const bpos = imageHeader.tpos + imageHeader.rows;
1985
1986 if (rpos > gifScreen.width)
1987 pm_error("Image right end (%lu) is outside global screen: %u x %u",
1988 rpos, gifScreen.width, gifScreen.height);
1989 if (bpos > gifScreen.height)
1990 pm_error("Image bottom end (%lu) is outside global screen: "
1991 "%u x %u",
1992 bpos, gifScreen.width, gifScreen.height);
1993 }
1994
1995
1996
1997 static void
1998 skipImageData(FILE * const ifP) {
1999 unsigned char lzwMinCodeSize;
2000 const char * error;
2001
2002 readFile(ifP, &lzwMinCodeSize, sizeof(lzwMinCodeSize), &error);
2003 if (error) {
2004 pm_message("Unable to read file to skip image DataBlock. %s", error);
2005 pm_strfree(error);
2006 }
2007 readThroughEod(ifP);
2008 }
2009
2010
2011
2012 static void
2013 convertImage(FILE * const ifP,
2014 bool const skipIt,
2015 FILE * const imageoutFileP,
2016 FILE * const alphafileP,
2017 struct GifScreen const gifScreen,
2018 struct Gif89 const gif89,
2019 bool const tolerateBadInput) {
2020 /*----------------------------------------------------------------------------
2021 Read a single GIF image from the current position of file 'ifP'.
2022
2023 If 'skipIt' is true, don't do anything else. Otherwise, write the
2024 image to the current position of files *imageoutFileP and *alphafileP.
2025 If *alphafileP is NULL, though, don't write any alpha information.
2026 -----------------------------------------------------------------------------*/
2027 struct GifImageHeader imageHeader;
2028 GifColorMap localColorMap;
2029 const GifColorMap * currentColorMapP;
2030 bool hasGray, hasColor;
2031
2032 readImageHeader(ifP, &imageHeader);
2033
2034 validateWithinGlobalScreen(imageHeader, gifScreen);
2035
2036 if (imageHeader.hasLocalColormap) {
2037 readColorMap(ifP, imageHeader.localColorMapSize, &localColorMap,
2038 &hasGray, &hasColor);
2039 currentColorMapP = &localColorMap;
2040 } else if (gifScreen.hasGlobalColorMap) {
2041 currentColorMapP = &gifScreen.colorMap;
2042 hasGray = gifScreen.hasGray;
2043 hasColor = gifScreen.hasColor;
2044 } else {
2045 pm_error("Invalid GIF: "
2046 "Image has no local color map and stream has no global "
2047 "color map either.");
2048 }
2049
2050 if (!skipIt) {
2051 readImageData(ifP, imageHeader.cols, imageHeader.rows,
2052 *currentColorMapP,
2053 imageHeader.interlaced,
2054 gif89.haveTransColor, gif89.transparentIndex,
2055 imageoutFileP, alphafileP,
2056 hasGray, hasColor,
2057 tolerateBadInput);
2058 } else
2059 skipImageData(ifP);
2060 }
2061
2062
2063
2064 static void
2065 disposeOfReadExtensionsError(const char * const error,
2066 bool const tolerateBadInput,
2067 unsigned int const imageSeq,
2068 bool * const eodP) {
2069 if (error) {
2070 if (tolerateBadInput)
2071 pm_message("Error accessing Image %u of stream; no further "
2072 "images can be accessed. %s",
2073 imageSeq, error);
2074 else
2075 pm_error("Error accessing Image %u of stream. %s",
2076 imageSeq, error);
2077 pm_strfree(error);
2078 *eodP = true;
2079 }
2080 }
2081
2082
2083
2084 static void
2085 convertImages(FILE * const ifP,
2086 bool const allImages,
2087 unsigned int const requestedImageSeq,
2088 bool const drainStream,
2089 FILE * const imageOutFileP,
2090 FILE * const alphaFileP,
2091 bool const tolerateBadInput) {
2092 /*----------------------------------------------------------------------------
2093 Read a GIF stream from file 'ifP' and write one or more images from
2094 it as PNM images to file 'imageOutFileP'. If the images have transparency
2095 and 'alphafile' is non-NULL, write PGM alpha masks to file 'alphaFileP'.
2096
2097 'allImages' means Caller wants all the images in the stream.
2098
2099 'requestedImageSeq' is meaningful only when 'allImages' is false. It
2100 is the sequence number of the one image Caller wants from the stream,
2101 with the first image being 0.
2102
2103 'drainInput' means to read the entire GIF stream, even after
2104 reading the image Caller asked for. We read the stream, not just
2105 the file it's in, so we still recognize certain errors in the GIF
2106 format in the tail of the stream and there may yet be more stuff in
2107 the file when we return.
2108 -----------------------------------------------------------------------------*/
2109 unsigned int imageSeq;
2110 /* Sequence within GIF stream of image we are currently processing.
2111 First is 0.
2112 */
2113 struct GifScreen gifScreen;
2114 struct Gif89 gif89;
2115 bool eod;
2116 /* We've read through the GIF terminator character */
2117
2118 /* Set 'gif89' to initial values, to be updated as we encounter the
2119 relevant extensions in the GIF stream.
2120 */
2121 initGif89(&gif89);
2122
2123 readGifHeader(ifP, &gifScreen);
2124
2125 for (imageSeq = 0, eod = false;
2126 !eod && (allImages || imageSeq <= requestedImageSeq || drainStream);
2127 ++imageSeq) {
2128
2129 const char * error;
2130
2131 readExtensions(ifP, &gif89, &eod, &error);
2132
2133 disposeOfReadExtensionsError(error, tolerateBadInput, imageSeq, &eod);
2134
2135 if (eod) {
2136 /* GIF stream ends before image with sequence imageSeq */
2137 if (!allImages && (imageSeq <= requestedImageSeq))
2138 pm_error("You requested Image %d, but "
2139 "only %d image%s found in GIF stream",
2140 requestedImageSeq + 1,
2141 imageSeq, imageSeq > 1 ? "s" : "");
2142 } else {
2143 if (verbose)
2144 pm_message("Reading Image Sequence %u", imageSeq);
2145
2146 convertImage(ifP, !allImages && (imageSeq != requestedImageSeq),
2147 imageOutFileP, alphaFileP, gifScreen, gif89,
2148 tolerateBadInput);
2149 }
2150 }
2151 }
2152
2153
2154
2155 int
2156 main(int argc, const char **argv) {
2157
2158 struct CmdlineInfo cmdline;
2159 FILE * ifP;
2160 FILE * alphaFileP;
2161 FILE * imageOutFileP;
2162
2163 pm_proginit(&argc, argv);
2164
2165 parseCommandLine(argc, argv, &cmdline);
2166 verbose = cmdline.verbose;
2167 showComment = cmdline.comments;
2168
2169 ifP = pm_openr(cmdline.inputFilespec);
2170
2171 if (cmdline.alphaFileName == NULL)
2172 alphaFileP = NULL;
2173 else
2174 alphaFileP = pm_openw(cmdline.alphaFileName);
2175
2176 if (alphaFileP && streq(cmdline.alphaFileName, "-"))
2177 imageOutFileP = NULL;
2178 else
2179 imageOutFileP = stdout;
2180
2181 convertImages(ifP, cmdline.allImages, cmdline.imageNum,
2182 !cmdline.quitearly, imageOutFileP, alphaFileP,
2183 cmdline.repair);
2184
2185 pm_close(ifP);
2186 if (imageOutFileP != NULL)
2187 pm_close(imageOutFileP);
2188 if (alphaFileP != NULL)
2189 pm_close(alphaFileP);
2190
2191 return 0;
2192 }
2193
2194
2195