Debian Codegraph @

converter/other/pamtogif.c

raw
1 /*=============================================================================
2 pamtogif
3 ===============================================================================
4 Convert a Netpbm image to GIF
5
6 History and copyright information is at the end of the file.
7 =============================================================================*/
8
9 #include <assert.h>
10 #include <string.h>
11 #include <stdbool.h>
12
13 #include "pm_c_util.h"
14 #include "mallocvar.h"
15 #include "shhopt.h"
16 #include "nstring.h"
17 #include "pam.h"
18 #include "pammap.h"
19
20 #define MAXCMAPSIZE 256
21
22 static bool verbose;
23
24
25 enum TransparencyType {TRANS_NONE, TRANS_COLOR, TRANS_ALPHA};
26 /* The source of transparency for the GIF: nothing is transparent,
27 All pixels of a certain color are transparent, or the alpha plane
28 in the input tells what is transparent.
29 */
30
31 typedef unsigned int StringCode;
32 /* A code to be place in the GIF raster. It represents
33 a string of one or more pixels. You interpret this in the context
34 of a current code size. The lower half of the values representable
35 in the current code size represent singleton strings and the value
36 is simply the value of the one pixel in the string. The first two
37 values in the upper half of the range are the clear code and EOF
38 code, respectively. The rest of the values represent multi-pixel
39 strings. The mapping between value and the sequence of pixels
40 changes throughout the image.
41
42 Ergo, this data structure must be at least BITS bits wide.
43 */
44
45
46 struct Cmap {
47 /* This is the information for the GIF colormap (aka palette). */
48
49 struct pam pam;
50 /* Gives depth and maxval for colors in color[] */
51 tuple color[MAXCMAPSIZE];
52 /* Maps a color index, as is found in the raster part of the
53 GIF, to color.
54 */
55 unsigned int cmapSize;
56 /* Number of entries in the GIF colormap. I.e. number of colors
57 in the image, plus possibly one fake transparency color.
58 */
59 bool haveTransparent;
60 /* The colormap contains an entry for transparent pixels */
61 unsigned int transparent;
62 /* color index number in GIF palette of the color that is to
63 be transparent.
64
65 Meaningful only if 'haveTransparent' is true.
66 */
67 tuplehash tuplehash;
68 /* A hash table to translate color to GIF colormap index. */
69 };
70
71 struct CmdlineInfo {
72 /* All the information the user supplied in the command line,
73 in a form easy for the program to use.
74 */
75 const char *input_filespec; /* Filespec of input file */
76 const char *alphacolor; /* -alphacolor option value or default */
77 unsigned int interlace; /* -interlace option value */
78 unsigned int sort; /* -sort option value */
79 const char *mapfile; /* -mapfile option value. NULL if none. */
80 const char *transparent; /* -transparent option value. NULL if none. */
81 const char *comment; /* -comment option value; NULL if none */
82 unsigned int nolzw; /* -nolzw option */
83 unsigned int noclear; /* -noclear option */
84 float aspect; /* -aspect option value (the ratio). */
85 unsigned int verbose;
86 };
87
88
89
90
91
92 static unsigned int
93 pamAlphaPlane(struct pam * const pamP) {
94 /*----------------------------------------------------------------------------
95 The number of the alpha plane, or zero if there is no alpha plane, as
96 indicated by *pamP.
97
98 Note that the alpha plane is never zero in any Netpbm tuple type.
99 -----------------------------------------------------------------------------*/
100 unsigned int alphaPlane;
101
102 if (streq(pamP->tuple_type, "RGB_ALPHA"))
103 alphaPlane = 3;
104 else if (streq(pamP->tuple_type, "GRAYSCALE_ALPHA"))
105 alphaPlane = 1;
106 else if (streq(pamP->tuple_type, "BLACKANDWHITE_ALPHA"))
107 alphaPlane = 1;
108 else
109 alphaPlane = 0;
110
111 if (alphaPlane >= pamP->depth)
112 pm_error("Tuple type is '%s', but depth (%u) is less than %u",
113 pamP->tuple_type, pamP->depth, alphaPlane + 1);
114
115 return alphaPlane;
116 }
117
118
119
120 static void
121 parseCommandLine(int argc, const char ** argv,
122 struct CmdlineInfo * const cmdlineP) {
123 /*----------------------------------------------------------------------------
124 Parse the program arguments (given by argc and argv) into a form
125 the program can deal with more easily -- a cmdline_info structure.
126 If the syntax is invalid, issue a message and exit the program via
127 pm_error().
128
129 Note that the file spec array we return is stored in the storage that
130 was passed to us as the argv array.
131 -----------------------------------------------------------------------------*/
132 optEntry * option_def; /* malloc'ed */
133 optStruct3 opt; /* set by OPTENT3 */
134 unsigned int option_def_index;
135
136 unsigned int aspectSpec;
137
138 MALLOCARRAY_NOFAIL(option_def, 100);
139
140 option_def_index = 0; /* incremented by OPTENT3 */
141 OPTENT3(0, "interlace", OPT_FLAG,
142 NULL, &cmdlineP->interlace, 0);
143 OPTENT3(0, "sort", OPT_FLAG,
144 NULL, &cmdlineP->sort, 0);
145 OPTENT3(0, "nolzw", OPT_FLAG,
146 NULL, &cmdlineP->nolzw, 0);
147 OPTENT3(0, "noclear", OPT_FLAG,
148 NULL, &cmdlineP->noclear, 0);
149 OPTENT3(0, "mapfile", OPT_STRING,
150 &cmdlineP->mapfile, NULL, 0);
151 OPTENT3(0, "transparent", OPT_STRING,
152 &cmdlineP->transparent, NULL, 0);
153 OPTENT3(0, "comment", OPT_STRING,
154 &cmdlineP->comment, NULL, 0);
155 OPTENT3(0, "alphacolor", OPT_STRING,
156 &cmdlineP->alphacolor, NULL, 0);
157 OPTENT3(0, "aspect", OPT_FLOAT,
158 &cmdlineP->aspect, &aspectSpec, 0);
159 OPTENT3(0, "verbose", OPT_FLAG,
160 NULL, &cmdlineP->verbose, 0);
161
162 /* Set the defaults */
163 cmdlineP->mapfile = NULL;
164 cmdlineP->transparent = NULL; /* no transparency */
165 cmdlineP->comment = NULL; /* no comment */
166 cmdlineP->alphacolor = "rgb:0/0/0";
167 /* We could say "black" here, but then we depend on the color names
168 database existing.
169 */
170
171 opt.opt_table = option_def;
172 opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
173 opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */
174
175 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
176 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
177
178 if (argc-1 == 0)
179 cmdlineP->input_filespec = "-";
180 else if (argc-1 != 1)
181 pm_error("Program takes zero or one argument (filename). You "
182 "specified %d", argc-1);
183 else
184 cmdlineP->input_filespec = argv[1];
185
186 if (aspectSpec) {
187 if (cmdlineP->aspect < 0.25 || cmdlineP->aspect > 4.21875)
188 pm_error("Invalid -aspect value: %f. "
189 "GIF allows only the range 0.25-4.0 .",
190 cmdlineP->aspect);
191 else if (cmdlineP->aspect > 4.0)
192 pm_message("Warning: "
193 "You specified an aspect ratio over 4.0: %f. "
194 "This will result in an invalid GIF.",
195 cmdlineP->aspect);
196 } else
197 cmdlineP->aspect = 1.0;
198 }
199
200
201
202 /*
203 * Write out a word to the GIF file
204 */
205 static void
206 Putword(int const w, FILE * const fp) {
207
208 fputc( w & 0xff, fp );
209 fputc( (w / 256) & 0xff, fp );
210 }
211
212
213
214 static int
215 closestColor(tuple const color,
216 struct pam * const pamP,
217 const struct Cmap * const cmapP) {
218 /*----------------------------------------------------------------------------
219 Return the colormap index of the color in the colormap *cmapP
220 that is closest to the color 'color', whose format is specified by
221 *pamP.
222
223 Also add 'color' to the colormap hash, with the colormap index we
224 are returning. Caller must ensure that the color is not already in
225 there.
226 -----------------------------------------------------------------------------*/
227 unsigned int const nComp = pamP->depth >= 3 ? 3 : 1;
228 /* Number of color components (not alpha) in 'color' */
229
230 unsigned int i;
231 unsigned int imin, dmin;
232 int fits;
233
234 dmin = UINT_MAX;
235 imin = 0;
236 for (i = 0; i < cmapP->cmapSize; ++i) {
237 unsigned int distance;
238 unsigned int plane;
239
240 for (distance = 0, plane = 0; plane < nComp; ++plane)
241 /* Divide by 4 is to avoid arithmetic overflow */
242 distance += SQR(color[plane] - cmapP->color[i][plane]) / 4;
243
244 if (distance < dmin) {
245 dmin = distance;
246 imin = i;
247 }
248 }
249 pnm_addtotuplehash(pamP, cmapP->tuplehash, color, imin, &fits);
250
251 return imin;
252 }
253
254
255
256 enum pass {MULT8PLUS0, MULT8PLUS4, MULT4PLUS2, MULT2PLUS1};
257
258
259 typedef struct {
260 struct pam pam;
261 /* Description of input file/image. The position of the file
262 is also part of the state of this rowReader.
263 */
264 pm_filepos rasterPos;
265 /* Position in file fileP of the start of the raster */
266 bool interlace;
267 /* We're accessing the image in interlace fashion */
268 bool eof;
269 /* The image is at EOF (we have returned all of the rows) */
270 unsigned int nextRow;
271 /* Number of row to which input file is positioned;
272 meaningless if 'eof'.
273 */
274 enum pass pass;
275 /* The interlace pass. Undefined if !interlace */
276 tuple * discardBuffer;
277 /* A bitbucket for rows we read in order to advance the file
278 position.
279 */
280 } RowReader;
281
282
283
284 static RowReader *
285 rowReader_create(struct pam * const pamP,
286 pm_filepos const rasterPos,
287 bool const interlace) {
288
289 RowReader * rdrP;
290
291 MALLOCVAR_NOFAIL(rdrP);
292
293 rdrP->pam = *pamP;
294 rdrP->rasterPos = rasterPos;
295 rdrP->interlace = interlace;
296 rdrP->eof = FALSE;
297 rdrP->pass = MULT8PLUS0;
298
299 pm_seek2(rdrP->pam.file, &rasterPos, sizeof(rasterPos));
300 rdrP->nextRow = 0;
301
302 rdrP->discardBuffer = pnm_allocpamrow(&rdrP->pam);
303
304 return rdrP;
305 }
306
307
308
309 static void
310 rowReader_destroy(RowReader * const rdrP) {
311
312 pnm_freepamrow(rdrP->discardBuffer);
313 free(rdrP);
314 }
315
316
317
318 static void
319 rowReader_skipRows(RowReader * const rdrP,
320 unsigned int const rowCount,
321 bool * const eofP) {
322 /*----------------------------------------------------------------------------
323 Skip over the next 'rowCount' rows of the input file.
324
325 Iff there aren't at least 'rowCount' rows left, return *eofP == TRUE.
326 -----------------------------------------------------------------------------*/
327 if (rdrP->nextRow + rowCount >= rdrP->pam.height)
328 *eofP = TRUE;
329 else {
330 /* This could be made faster if need be by adding a libnetpbm
331 row skip function. Except with the plain formats, that could
332 just compute the next row position and fseek() to it.
333 pnm_readpamrow() with NULL for the output pointer would be a
334 good interface for a row skip function.
335 */
336 unsigned int i;
337
338 *eofP = FALSE;
339
340 for (i = 0; i < rowCount; ++i)
341 pnm_readpamrow(&rdrP->pam, rdrP->discardBuffer);
342
343 rdrP->nextRow += rowCount;
344 }
345 }
346
347
348
349 static void
350 rowReader_gotoNextInterlaceRow(RowReader * const rdrP) {
351 /*----------------------------------------------------------------------------
352 Position reader to the next row in the interlace pattern, assuming it
353 is now positioned immediately after the current row.
354 -----------------------------------------------------------------------------*/
355 bool endOfPass;
356
357 /* There are 4 passes:
358 MULT8PLUS0: Rows 0, 8, 16, 24, 32, etc.
359 MULT8PLUS4: Rows 4, 12, 20, 28, etc.
360 MULT4PLUS2: Rows 2, 6, 10, 14, etc.
361 MULT2PLUS1: Rows 1, 3, 5, 7, 9, etc.
362 */
363
364 switch (rdrP->pass) {
365 case MULT8PLUS0:
366 rowReader_skipRows(rdrP, 7, &endOfPass);
367 break;
368 case MULT8PLUS4:
369 rowReader_skipRows(rdrP, 7, &endOfPass);
370 break;
371 case MULT4PLUS2:
372 rowReader_skipRows(rdrP, 3, &endOfPass);
373 break;
374 case MULT2PLUS1:
375 rowReader_skipRows(rdrP, 1, &endOfPass);
376 break;
377 }
378
379 /* Note that if there are more than 4 rows, the sequence of passes
380 is sequential, but when there are fewer than 4, reading may skip
381 e.g. from MULT8PLUS0 to MULT4PLUS2.
382 */
383 while (endOfPass && !rdrP->eof) {
384 pm_seek2(rdrP->pam.file, &rdrP->rasterPos, sizeof(rdrP->rasterPos));
385 rdrP->nextRow = 0;
386
387 switch (rdrP->pass) {
388 case MULT8PLUS0:
389 rdrP->pass = MULT8PLUS4;
390 rowReader_skipRows(rdrP, 4, &endOfPass);
391 break;
392 case MULT8PLUS4:
393 rdrP->pass = MULT4PLUS2;
394 rowReader_skipRows(rdrP, 2, &endOfPass);
395 break;
396 case MULT4PLUS2:
397 rdrP->pass = MULT2PLUS1;
398 rowReader_skipRows(rdrP, 1, &endOfPass);
399 break;
400 case MULT2PLUS1:
401 rdrP->eof = TRUE;
402 break;
403 }
404 }
405 }
406
407
408
409 static void
410 rowReader_gotoNextStraightRow(RowReader * const rdrP) {
411 /*----------------------------------------------------------------------------
412 Position reader to the next row in a straight, non-interlace
413 pattern, assuming the file is now positioned immediately after the
414 current row.
415
416 This is trivial, since the next row _is_ immediately after the current
417 row, except in the case that there are no more rows.
418 -----------------------------------------------------------------------------*/
419 if (rdrP->nextRow >= rdrP->pam.height)
420 rdrP->eof = TRUE;
421 }
422
423
424
425 static void
426 rowReader_read(RowReader * const rdrP,
427 tuple * const tuplerow) {
428
429 if (rdrP->eof)
430 pm_error("INTERNAL ERROR: rowReader attempted to read beyond end "
431 "of image");
432
433 pnm_readpamrow(&rdrP->pam, tuplerow);
434 ++rdrP->nextRow;
435
436 if (rdrP->interlace)
437 rowReader_gotoNextInterlaceRow(rdrP);
438 else
439 rowReader_gotoNextStraightRow(rdrP);
440 }
441
442
443
444 static unsigned int
445 gifPixel(struct pam * const pamP,
446 tuple const tuple,
447 unsigned int const alphaPlane,
448 sample const alphaThreshold,
449 const struct Cmap * const cmapP) {
450 /*----------------------------------------------------------------------------
451 Return the colormap index of the tuple 'tuple', whose format is described
452 by *pamP, using colormap *cmapP.
453
454 'alphaPlane' is the number of the plane in 'tuple' to use for transparency,
455 or zero if we aren't to use any plane for transparency. (note that Caller
456 cannot specify plane 0 for transparency).
457
458 'alphaThreshold' is the alpha level below which we consider a pixel
459 transparent for GIF purposes.
460
461 If 'alphaPlane' is nonzero, we assume *cmapP contains a transparent
462 entry.
463 -----------------------------------------------------------------------------*/
464 int colorIndex;
465
466 if (alphaPlane && tuple[alphaPlane] < alphaThreshold) {
467 assert(cmapP->haveTransparent);
468 colorIndex = cmapP->transparent;
469 } else {
470 int found;
471
472 pnm_lookuptuple(pamP, cmapP->tuplehash, tuple,
473 &found, &colorIndex);
474
475 if (!found)
476 colorIndex = closestColor(tuple, pamP, cmapP);
477 }
478 assert(colorIndex >= 0);
479 return (unsigned int) colorIndex;
480 }
481
482
483
484 static void
485 writeTransparentColorIndexExtension(FILE * const ofP,
486 unsigned int const transColorIndex) {
487 /*----------------------------------------------------------------------------
488 Write out extension for transparent color index.
489 -----------------------------------------------------------------------------*/
490 fputc('!', ofP);
491 fputc(0xf9, ofP);
492 fputc(4, ofP);
493 fputc(1, ofP);
494 fputc(0, ofP);
495 fputc(0, ofP);
496 fputc(transColorIndex, ofP);
497 fputc(0, ofP);
498 }
499
500
501
502 static void
503 writeCommentExtension(FILE * const ofP,
504 char const comment[]) {
505 /*----------------------------------------------------------------------------
506 Write out extension for a comment
507 -----------------------------------------------------------------------------*/
508 unsigned int const maxSegmentSize = 255;
509
510 const char * segment;
511
512 fputc('!', ofP); /* Identifies an extension */
513 fputc(0xfe, ofP); /* Identifies a comment */
514
515 /* Write it out in segments no longer than 255 characters */
516 for (segment = &comment[0];
517 segment < comment + strlen(comment);
518 segment += maxSegmentSize) {
519
520 unsigned int const lengthThisSegment =
521 MIN(maxSegmentSize, strlen(segment));
522
523 fputc(lengthThisSegment, ofP);
524
525 fwrite(segment, 1, lengthThisSegment, ofP);
526 }
527
528 fputc(0, ofP); /* No more comment blocks in this extension */
529 }
530
531
532
533 /***************************************************************************
534 *
535 * GIFCOMPR.C - GIF Image compression routines
536 *
537 * Lempel-Ziv compression based on 'compress'. GIF modifications by
538 * David Rowley ([email protected])
539 *
540 ***************************************************************************/
541
542 /*
543 * General DEFINEs
544 */
545
546 #define BITS 12
547
548 /*
549 *
550 * GIF Image compression - modified 'compress'
551 *
552 * Based on: compress.c - File compression ala IEEE Computer, June 1984.
553 *
554 * By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
555 * Jim McKie (decvax!mcvax!jim)
556 * Steve Davies (decvax!vax135!petsd!peora!srd)
557 * Ken Turkowski (decvax!decwrl!turtlevax!ken)
558 * James A. Woods (decvax!ihnp4!ames!jaw)
559 * Joe Orost (decvax!vax135!petsd!joe)
560 *
561 */
562
563
564 static StringCode const maxCodeLimitLzw = (StringCode)1 << BITS;
565 /* One beyond the largest string code that can exist in GIF */
566 /* Used only in assertions */
567
568
569 struct HashTableEntry {
570 /* This is an entry in the string table, which is a hash table. It says
571 that the string code 'combinedString' represents the string which is
572 the single pixel 'additionalPixel' appended to 'baseString', where
573 'baseString' may represent a multi-pixel string.
574 */
575 bool present;
576 /* There is an entry here. Following members are meaningless if
577 not.
578 */
579 StringCode baseString;
580 StringCode additionalPixel;
581 StringCode combinedString;
582 };
583
584
585
586 /***************************************************************************
587 * BYTE OUTPUTTER
588 ***************************************************************************/
589
590 typedef struct {
591 FILE * fileP; /* The file to which to output */
592 unsigned int count;
593 /* Number of bytes so far in the current data block */
594 unsigned char buffer[256];
595 /* The current data block, under construction */
596 } ByteBuffer;
597
598
599
600 static ByteBuffer *
601 byteBuffer_create(FILE * const fileP) {
602
603 ByteBuffer * byteBufferP;
604
605 MALLOCVAR_NOFAIL(byteBufferP);
606
607 byteBufferP->fileP = fileP;
608 byteBufferP->count = 0;
609
610 return byteBufferP;
611 }
612
613
614
615 static void
616 byteBuffer_destroy(ByteBuffer * const byteBufferP) {
617
618 free(byteBufferP);
619 }
620
621
622
623 static void
624 byteBuffer_flush(ByteBuffer * const byteBufferP) {
625 /*----------------------------------------------------------------------------
626 Write the current data block to the output file, then reset the current
627 data block to empty.
628 -----------------------------------------------------------------------------*/
629 if (byteBufferP->count > 0 ) {
630 if (verbose)
631 pm_message("Writing %u byte block", byteBufferP->count);
632 fputc(byteBufferP->count, byteBufferP->fileP);
633 fwrite(byteBufferP->buffer, 1, byteBufferP->count, byteBufferP->fileP);
634 byteBufferP->count = 0;
635 }
636 }
637
638
639
640 static void
641 byteBuffer_flushFile(ByteBuffer * const byteBufferP) {
642
643 fflush(byteBufferP->fileP);
644
645 if (ferror(byteBufferP->fileP))
646 pm_error("error writing output file");
647 }
648
649
650
651 static void
652 byteBuffer_out(ByteBuffer * const byteBufferP,
653 unsigned char const c) {
654 /*----------------------------------------------------------------------------
655 Add a byte to the end of the current data block, and if it is now 255
656 characters, flush the data block to the output file.
657 -----------------------------------------------------------------------------*/
658 byteBufferP->buffer[byteBufferP->count++] = c;
659 if (byteBufferP->count >= 255)
660 byteBuffer_flush(byteBufferP);
661 }
662
663
664
665 /***************************************************************************
666 * GIF CODE OUTPUTTER
667 ***************************************************************************/
668
669 typedef struct {
670 ByteBuffer * byteBufferP;
671 unsigned int initBits;
672 unsigned int nBits;
673 /* Number of bits to put in output for each code */
674 StringCode maxCode; /* maximum code, given n_bits */
675 StringCode maxCodeLimit;
676 /* LZW: One beyond the largest string code that can exist in GIF.
677 Uncompressed: a ceiling to prevent code size from ratcheting up.
678 In either case, output code never reaches this value.
679 */
680 unsigned long curAccum;
681 unsigned int curBits;
682 unsigned int stringCount;
683 /* Number of strings that have been output to this buffer (by writing
684 a string code) since the last flush (or ever, if no last flush).
685 Note that this counts only strings that go into the buffer; it
686 doesn't matter if they have gone out the other side yet. The main
687 use of this is debugging -- when something fails, you can see in a
688 debugger where in the image it was, then set a trap for there.
689 */
690 } CodeBuffer;
691
692
693
694 static CodeBuffer *
695 codeBuffer_create(FILE * const ofP,
696 unsigned int const initBits,
697 bool const lzw) {
698
699 CodeBuffer * codeBufferP;
700
701 MALLOCVAR_NOFAIL(codeBufferP);
702
703 codeBufferP->initBits = initBits;
704 codeBufferP->nBits = codeBufferP->initBits;
705 codeBufferP->maxCode = (1 << codeBufferP->nBits) - 1;
706 codeBufferP->maxCodeLimit = lzw ?
707 (StringCode)1 << BITS : (StringCode) (1 << codeBufferP->nBits) - 1;
708 codeBufferP->byteBufferP = byteBuffer_create(ofP);
709 codeBufferP->curAccum = 0;
710 codeBufferP->curBits = 0;
711 codeBufferP->stringCount = 0;
712
713 return codeBufferP;
714 }
715
716
717
718 static void
719 codeBuffer_destroy(CodeBuffer * const codeBufferP) {
720
721 byteBuffer_destroy(codeBufferP->byteBufferP);
722
723 free(codeBufferP);
724 }
725
726
727
728 static void
729 codeBuffer_resetCodeSize(CodeBuffer * const codeBufferP) {
730
731 codeBufferP->nBits = codeBufferP->initBits;
732
733 assert(codeBufferP->nBits <= BITS);
734
735 codeBufferP->maxCode = (1 << codeBufferP->nBits) - 1;
736 }
737
738
739
740 static void
741 codeBuffer_increaseCodeSize(CodeBuffer * const codeBufferP) {
742
743 ++codeBufferP->nBits;
744
745 assert(codeBufferP->nBits <= BITS);
746
747 codeBufferP->maxCode = (1 << codeBufferP->nBits) - 1;
748 }
749
750
751
752 static void
753 codeBuffer_output(CodeBuffer * const codeBufferP,
754 StringCode const code) {
755 /*----------------------------------------------------------------------------
756 Output one GIF code to the file, through the code buffer.
757
758 The code is represented as N bits in the file -- the lower
759 N bits of 'code'. N is a the current code size of *codeBufferP.
760 -----------------------------------------------------------------------------*/
761 assert (code <= codeBufferP->maxCode);
762
763 codeBufferP->curAccum &= (1 << codeBufferP->curBits) - 1;
764
765 if (codeBufferP->curBits > 0)
766 codeBufferP->curAccum |= ((unsigned long)code << codeBufferP->curBits);
767 else
768 codeBufferP->curAccum = code;
769
770 codeBufferP->curBits += codeBufferP->nBits;
771
772 while (codeBufferP->curBits >= 8) {
773 byteBuffer_out(codeBufferP->byteBufferP,
774 codeBufferP->curAccum & 0xff);
775 codeBufferP->curAccum >>= 8;
776 codeBufferP->curBits -= 8;
777 }
778
779 ++codeBufferP->stringCount;
780 }
781
782
783
784 static void
785 codeBuffer_flush(CodeBuffer * const codeBufferP) {
786
787 /* Output the possible partial byte in the buffer */
788
789 if (codeBufferP->curBits > 0) {
790 byteBuffer_out(codeBufferP->byteBufferP,
791 codeBufferP->curAccum & 0xff);
792 codeBufferP->curBits = 0;
793 }
794 byteBuffer_flush(codeBufferP->byteBufferP);
795
796 byteBuffer_flushFile(codeBufferP->byteBufferP);
797
798 if (verbose)
799 pm_message("%u strings of pixels written to file",
800 codeBufferP->stringCount);
801 codeBufferP->stringCount = 0;
802 }
803
804
805
806 typedef struct {
807 CodeBuffer * codeBufferP;
808 /* The place to which we write our string codes.
809
810 Constant.
811 */
812 bool lzw;
813 /* We're actually doing LZW compression. False means we follow
814 the algorithm enough that an LZW decompressor will recover the
815 proper data, but always using one code per pixel, and therefore
816 not effecting any compression and not using the LZW patent.
817 */
818 bool noclear;
819 /* Never put a clear code in the output. Ergo don't recompute the
820 string table from current input. When the string table fills up,
821 continue using that table for the rest of the image.
822 */
823 unsigned int hsize;
824 /* The number of slots in the hash table. This variable to
825 enhance overall performance by reducing memory use when
826 encoding smaller gifs.
827 */
828 unsigned int hshift;
829 /* This is how many bits we shift left a string code in forming the
830 primary hash of the concatenation of that string with another.
831 Constant.
832 */
833
834 /* Codes less than 'clearCode' are singleton pixel codes - each
835 represents the pixel value equal to it.
836
837 Codes greater than 'eofCode' are multipixel string codes. Each
838 represents a string of pixels that is defined by the preceding
839 stream.
840 */
841 StringCode clearCode;
842 /* The code in an LZW stream that means to clear the string
843 dictionary and start fresh.
844
845 Constant.
846 */
847 StringCode eofCode;
848 /* The code in an LZW stream that means there's no more coming
849
850 Constant.
851 */
852 StringCode initCodeLimit;
853 /* The value of 'codeLimit' at the start of a block.
854
855 Constant.
856 */
857 StringCode codeLimit;
858 /* One beyond the maximum code possible with the current code
859 size.
860 */
861 struct HashTableEntry * hashTable;
862 StringCode nextCodeToDefine;
863 /* The next string code the GIF protocol will define. It will do this
864 the next time we emit a string code.
865 */
866 StringCode stringSoFar;
867 /* The code for the string we have built so far. This code indicates
868 one or more pixels that we have encoded but not yet output
869 because we're hoping to match an even longer string.
870
871 Valid only when 'buildingString' is true.
872
873 In the non-lzw case the single pixel to output.
874 */
875 bool buildingString;
876 /* We are in the middle of building a string; 'stringSoFar' describes
877 the pixels in it so far. The only time this is false is at the
878 very beginning of the stream.
879
880 Ignored in the non-lzw case.
881 */
882 bool reportedNoclear;
883 /* We have reported to Standard Error that the string table filled up
884 and we elected not to clear it.
885 */
886 } LzwCompressor;
887
888
889
890
891 static unsigned int
892 nSignificantBits(unsigned int const arg){
893
894 #if HAVE_GCC_BITCOUNT
895
896 return (arg == 0) ? 0 : 8 * sizeof(unsigned int) - __builtin_clz(arg);
897
898 #else
899
900 unsigned int i = 0;
901 while (arg >> i != 0)
902 ++i;
903
904 return i;
905 #endif
906 }
907
908
909
910 static LzwCompressor *
911 lzw_create(FILE * const ofP,
912 unsigned int const initBits,
913 bool const lzw,
914 bool const noclear,
915 unsigned int const pixelCount) {
916
917 unsigned int const hsizeTable[] = {257, 521, 1031, 2053, 4099, 5003};
918 /* If the image has 4096 or fewer pixels we use prime numbers slightly
919 above powers of two between 8 and 12. In this case the hash table
920 never fills up; clear code is never emitted.
921
922 Above that we use a table with 4096 slots plus 20% extra.
923 When this is not enough the clear code is emitted.
924 Because of the extra 20% the table itself never fills up.
925
926 lzw.hsize and lzw.hshift stay constant through the image.
927
928 Variable hsize is a performance enhancement based on the fact that
929 the encoder never needs more codes than the number of pixels in
930 the image. Typically, the ratio of pixels to codes is around
931 10:1 to 20:1.
932
933 Logic works with fixed values lzw.hsize=5003 and t=13.
934 */
935
936 LzwCompressor * lzwP;
937
938 MALLOCVAR_NOFAIL(lzwP);
939
940 /* Constants */
941 lzwP->lzw = lzw;
942 lzwP->noclear = noclear;
943
944 lzwP->clearCode = 1 << (initBits - 1);
945 lzwP->eofCode = lzwP->clearCode + 1;
946 lzwP->initCodeLimit = 1 << initBits;
947
948 if (lzw) {
949 unsigned int const t =
950 MIN(13, MAX(8, nSignificantBits(pixelCount +lzwP->eofCode - 2)));
951 /* Index into hsizeTable */
952
953 lzwP->hsize = hsizeTable[t-8];
954
955 lzwP->hshift = (t == 13 ? 12 : t) - nSignificantBits(MAXCMAPSIZE-1);
956
957 MALLOCARRAY(lzwP->hashTable, lzwP->hsize);
958
959 if (lzwP->hashTable == NULL)
960 pm_error("Couldn't get memory for %u-entry hash table.",
961 lzwP->hsize);
962 } else {
963 /* No LZW compression. We don't need a stringcode hash table */
964 lzwP->hashTable = NULL;
965 lzwP->hsize = 0;
966 }
967
968 lzwP->buildingString = FALSE;
969
970 lzwP->codeBufferP = codeBuffer_create(ofP, initBits, lzw);
971
972 lzwP->reportedNoclear = false;
973
974 return lzwP;
975 }
976
977
978
979 static void
980 lzw_destroy(LzwCompressor * const lzwP) {
981
982 codeBuffer_destroy(lzwP->codeBufferP);
983
984 free(lzwP->hashTable);
985
986 free(lzwP);
987 }
988
989
990
991 static void
992 lzwHashClear(LzwCompressor * const lzwP) {
993
994 /* Empty the code table */
995
996 unsigned int i;
997
998 for (i = 0; i < lzwP->hsize; ++i)
999 lzwP->hashTable[i].present = false;
1000
1001 lzwP->nextCodeToDefine = lzwP->clearCode + 2;
1002 }
1003
1004
1005
1006 static void
1007 lzw_reportNoclear(LzwCompressor * const lzwP) {
1008
1009 if (verbose && !lzwP->reportedNoclear) {
1010 pm_message("String table filled up. Not starting a new one "
1011 "because of noclear mode");
1012 lzwP->reportedNoclear = true;
1013 }
1014 }
1015
1016
1017
1018 static void
1019 lzw_clearBlock(LzwCompressor * const lzwP) {
1020 /*----------------------------------------------------------------------------
1021 Insert a string table clear in the stream. Clear our table and set it up to
1022 start building again, and emit the code to tell the decoder we're doing it
1023 so he can do the same.
1024 -----------------------------------------------------------------------------*/
1025 lzwHashClear(lzwP);
1026
1027 codeBuffer_output(lzwP->codeBufferP, lzwP->clearCode);
1028
1029 codeBuffer_resetCodeSize(lzwP->codeBufferP);
1030
1031 lzwP->codeLimit = lzwP->initCodeLimit;
1032 }
1033
1034
1035
1036 static void
1037 lzwAdjustCodeSize(LzwCompressor * const lzwP,
1038 StringCode const newCode) {
1039 /*----------------------------------------------------------------------------
1040 Assuming we just defined code 'newCode', increase the code size as
1041 required so that this code fits.
1042
1043 The decompressor is mimicking our assignment of that code, so knows that
1044 we are making this adjustment, so expects codes of the new size.
1045 -----------------------------------------------------------------------------*/
1046 assert(newCode <= lzwP->codeLimit);
1047
1048 if (newCode == lzwP->codeLimit) {
1049 lzwP->codeLimit *= 2;
1050 codeBuffer_increaseCodeSize(lzwP->codeBufferP);
1051
1052 assert(lzwP->codeLimit <= maxCodeLimitLzw);
1053 }
1054 }
1055
1056
1057
1058 static void
1059 lzwOutputCurrentString(LzwCompressor * const lzwP) {
1060 /*----------------------------------------------------------------------------
1061 Put a code for the currently built-up string in the output stream.
1062
1063 Doing this causes the protocol to define a new string code, defined as the
1064 string we put plus the first pixel of the next string we put. (It almost
1065 seems to violate causality, especially since the next string we put can
1066 legally be the very string code that gets defined here, but it actually
1067 works).
1068
1069 The code that gets defined is lzwP->nextCodeToDefine. Caller is
1070 responsible for figuring out the value for the code (i.e. what we just said
1071 above) so it can use the code in the future.
1072
1073 BUT: if the string table has reached its maximum size, issue a clear code
1074 instead to cause the protocol to forget all the defined string coes and
1075 start its table over (so Caller must start its own table over too).
1076 EXCEPT: if we're running in no-clear mode; then we skip the clear code (so
1077 the protocol maintains all the string code definitions and caller will have
1078 to do so as well).
1079
1080 Note that in the non-compressing case, the overall limit is small enough to
1081 prevent us from ever defining string codes; we'll always issue the clear
1082 code.
1083
1084 Note that there is a case where Caller can just ignore the fact that we
1085 cause the protocol to define a new string code: where the string we're
1086 outputting is the last one in the stream. In that case, the new string
1087 code we define is irrelevant; it will never be used.
1088 -----------------------------------------------------------------------------*/
1089 codeBuffer_output(lzwP->codeBufferP, lzwP->stringSoFar);
1090
1091 if (lzwP->nextCodeToDefine < lzwP->codeBufferP->maxCodeLimit) {
1092 /* Record that the protocol defined a new string code, to wit
1093 the numerically next one, when we did the output to the stream
1094 above, and adjust the code size if this code is too wide to
1095 fit in the current size.
1096 */
1097 StringCode const newCode = lzwP->nextCodeToDefine++;
1098
1099 lzwAdjustCodeSize(lzwP, newCode);
1100 } else {
1101 if (lzwP->noclear)
1102 lzw_reportNoclear(lzwP);
1103 else {
1104 /* Forget all the strings so far; start building again; tell
1105 decompressor to do the same.
1106 */
1107 lzw_clearBlock(lzwP);
1108
1109 if (verbose)
1110 pm_message("String table filled up. "
1111 "Clearing and starting over");
1112 }
1113 }
1114 }
1115
1116
1117
1118 static void
1119 lzw_flush(LzwCompressor * const lzwP) {
1120
1121 if (lzwP->lzw)
1122 lzwOutputCurrentString(lzwP);
1123 /* Put out the code for the final string. */
1124
1125 codeBuffer_output(lzwP->codeBufferP, lzwP->eofCode);
1126
1127 codeBuffer_flush(lzwP->codeBufferP);
1128 }
1129
1130
1131
1132 static unsigned int
1133 primaryHash(StringCode const baseString,
1134 StringCode const additionalPixel,
1135 unsigned int const hshift) {
1136
1137 unsigned int hash;
1138
1139 assert(baseString < maxCodeLimitLzw);
1140 assert(additionalPixel < MAXCMAPSIZE);
1141
1142 hash = (additionalPixel << hshift) ^ baseString;
1143
1144 return hash;
1145 }
1146
1147
1148
1149 static void
1150 lookupInHash(LzwCompressor * const lzwP,
1151 unsigned int const gifPixel,
1152 bool * const foundP,
1153 StringCode * const codeP,
1154 unsigned int * const hashP) {
1155
1156 unsigned int disp;
1157 /* secondary hash stride (after G. Knott) */
1158 unsigned int hash;
1159 /* Index into hash table */
1160
1161 hash = primaryHash(lzwP->stringSoFar, gifPixel, lzwP->hshift);
1162 assert(hash < lzwP->hsize);
1163 disp = (hash == 0) ? 1 : lzwP->hsize - hash;
1164
1165 while (lzwP->hashTable[hash].present &&
1166 (lzwP->hashTable[hash].baseString != lzwP->stringSoFar ||
1167 lzwP->hashTable[hash].additionalPixel != gifPixel)) {
1168 if (hash < disp)
1169 hash += lzwP->hsize;
1170 assert(hash >= disp);
1171 hash -= disp;
1172 assert(hash < lzwP->hsize);
1173 }
1174
1175 if (lzwP->hashTable[hash].present) {
1176 /* Found fcode in hash table */
1177 *foundP = true;
1178 *codeP = lzwP->hashTable[hash].combinedString;
1179 } else {
1180 /* Found where it _should_ be (but it's not) with primary hash */
1181 *foundP = false;
1182 *hashP = hash;
1183 }
1184 }
1185
1186
1187
1188 static void
1189 lzw_encodePixel(LzwCompressor * const lzwP,
1190 unsigned int const gifPixel) {
1191
1192 assert(gifPixel < 256);
1193
1194 if (!lzwP->buildingString) {
1195 /* Start a new string with just this pixel */
1196 lzwP->stringSoFar = gifPixel;
1197 lzwP->buildingString = true;
1198 } else {
1199 bool found;
1200 /* There's a code for the current string in the string table */
1201 StringCode code;
1202 /* Existing code for the current string in the string table, if
1203 any
1204 */
1205 unsigned int hash;
1206 /* Index into hash table where the entry for the new string code
1207 should go; meaningless if we don't need a new string code
1208 (because there's already one in the hash table for the
1209 current string)
1210 */
1211
1212 lookupInHash(lzwP, gifPixel, &found, &code, &hash);
1213
1214 if (found)
1215 /* With this new pixel, it is still a known string; 'code' is
1216 its code
1217 */
1218 lzwP->stringSoFar = code;
1219 else {
1220 /* We've found the longest prefix of the rest of the image for
1221 which we have a string code defined. Output the code for that
1222 prefix, thus defining a new string code in the protocol for
1223 possible later use. The new code is defined as this string
1224 plus the first pixel of the next string.
1225
1226 But if there aren't any unused string codes left, outputting
1227 our string doesn't define any new string code.
1228 */
1229
1230 if (lzwP->nextCodeToDefine < lzwP->codeBufferP->maxCodeLimit) {
1231 lzwP->hashTable[hash].present = true;
1232 lzwP->hashTable[hash].baseString = lzwP->stringSoFar;
1233 lzwP->hashTable[hash].additionalPixel = gifPixel;
1234 lzwP->hashTable[hash].combinedString = lzwP->nextCodeToDefine;
1235 }
1236
1237 lzwOutputCurrentString(lzwP);
1238
1239 /* This singleton pixel starts the next string */
1240 lzwP->stringSoFar = gifPixel;
1241 }
1242 }
1243 }
1244
1245
1246
1247 /*
1248 * Algorithm: use open addressing double hashing (no chaining) on the
1249 * prefix code / next character combination. We do a variant of Knuth's
1250 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
1251 * secondary probe. Here, the modular division first probe is gives way
1252 * to a faster exclusive-or manipulation. Also do block compression with
1253 * an adaptive reset, whereby the code table is cleared when the compression
1254 * ratio decreases, but after the table fills. The variable-length output
1255 * codes are re-sized at this point, and a special CLEAR code is generated
1256 * for the decompressor. Late addition: construct the table according to
1257 * file size for noticeable speed improvement on small files. Please direct
1258 * questions about this implementation to ames!jaw.
1259 */
1260
1261 static void
1262 writePixelUncompressed(LzwCompressor * const lzwP,
1263 unsigned int const gifPixel) {
1264
1265 lzwP->stringSoFar = gifPixel;
1266 lzwOutputCurrentString(lzwP);
1267
1268 }
1269
1270
1271
1272 static void
1273 writeGlobalColorMap(FILE * const ofP,
1274 const struct Cmap * const cmapP,
1275 unsigned int const bitsPerPixel) {
1276 /*----------------------------------------------------------------------------
1277 Write out the Global Color Map
1278
1279 Note that the Global Color Map is always a power of two colors
1280 in size, but *cmapP could be smaller than that. So we pad with
1281 black.
1282 -----------------------------------------------------------------------------*/
1283 unsigned int const colorMapSize = 1 << bitsPerPixel;
1284
1285 struct pam pam;
1286 unsigned int i;
1287 tuple tupleRgb255;
1288
1289 if (verbose)
1290 pm_message("Writing %u-entry global colormap for %u colors",
1291 colorMapSize, cmapP->cmapSize);
1292
1293 pam = cmapP->pam;
1294 pam.size = PAM_STRUCT_SIZE(allocation_depth);
1295 pam.len = pam.size;
1296 pnm_setminallocationdepth(&pam, 3);
1297
1298 tupleRgb255 = pnm_allocpamtuple(&pam);
1299
1300 for (i = 0; i < colorMapSize; ++i) {
1301 if (i < cmapP->cmapSize) {
1302 tuple const color = cmapP->color[i];
1303
1304 assert(i < cmapP->cmapSize);
1305
1306 pnm_scaletuple(&pam, tupleRgb255, color, 255);
1307 pnm_maketuplergb(&pam, tupleRgb255);
1308
1309 fputc(tupleRgb255[PAM_RED_PLANE], ofP);
1310 fputc(tupleRgb255[PAM_GRN_PLANE], ofP);
1311 fputc(tupleRgb255[PAM_BLU_PLANE], ofP);
1312 } else {
1313 fputc(0, ofP);
1314 fputc(0, ofP);
1315 fputc(0, ofP);
1316 }
1317 }
1318 pnm_freepamtuple(tupleRgb255);
1319 }
1320
1321
1322
1323 static void
1324 reportImageInfo(bool const interlace,
1325 unsigned int const background,
1326 unsigned int const bitsPerPixel) {
1327
1328 if (verbose) {
1329 if (interlace)
1330 pm_message("interlaced");
1331 else
1332 pm_message("not interlaced");
1333 pm_message("Background color index = %u", background);
1334 pm_message("%u bits per pixel", bitsPerPixel);
1335 }
1336 }
1337
1338
1339
1340 static void
1341 writeGifHeader(FILE * const ofP,
1342 unsigned int const width,
1343 unsigned int const height,
1344 unsigned int const background,
1345 unsigned int const bitsPerPixel,
1346 const struct Cmap * const cmapP,
1347 char const comment[],
1348 float const aspect) {
1349
1350 unsigned int const resolution = bitsPerPixel;
1351
1352 unsigned char b;
1353
1354 /* Write the Magic header */
1355 if (cmapP->haveTransparent || comment || aspect != 1.0 )
1356 fwrite("GIF89a", 1, 6, ofP);
1357 else
1358 fwrite("GIF87a", 1, 6, ofP);
1359
1360 /* Write out the screen width and height */
1361 Putword(width, ofP);
1362 Putword(height, ofP);
1363
1364 /* Indicate that there is a global color map */
1365 b = 0x80; /* Yes, there is a color map */
1366
1367 /* OR in the resolution */
1368 b |= (resolution - 1) << 4;
1369
1370 /* OR in the Bits per Pixel */
1371 b |= (bitsPerPixel - 1);
1372
1373 /* Write it out */
1374 fputc(b, ofP);
1375
1376 /* Write out the Background color */
1377 assert((unsigned char)background == background);
1378 fputc(background, ofP);
1379
1380 {
1381 int const aspectValue = aspect == 1.0 ? 0 : ROUND(aspect * 64) - 15;
1382 assert(0 <= aspectValue && aspectValue <= 255);
1383 fputc(aspectValue, ofP);
1384 }
1385 writeGlobalColorMap(ofP, cmapP, bitsPerPixel);
1386
1387 if (cmapP->haveTransparent)
1388 writeTransparentColorIndexExtension(ofP, cmapP->transparent);
1389
1390 if (comment)
1391 writeCommentExtension(ofP, comment);
1392 }
1393
1394
1395
1396 static void
1397 writeImageSeparator(FILE * const ofP) {
1398
1399 fputc(',', ofP);
1400
1401 }
1402
1403
1404
1405 static void
1406 writeImageHeader(FILE * const ofP,
1407 unsigned int const leftOffset,
1408 unsigned int const topOffset,
1409 unsigned int const gWidth,
1410 unsigned int const gHeight,
1411 bool const gInterlace,
1412 unsigned int const initCodeSize) {
1413
1414 Putword(leftOffset, ofP);
1415 Putword(topOffset, ofP);
1416 Putword(gWidth, ofP);
1417 Putword(gHeight, ofP);
1418
1419 /* Write out whether or not the image is interlaced */
1420 if (gInterlace)
1421 fputc(0x40, ofP);
1422 else
1423 fputc(0x00, ofP);
1424
1425 /* Write out the initial code size */
1426 fputc(initCodeSize, ofP);
1427 }
1428
1429
1430
1431 static void
1432 writeRaster(struct pam * const pamP,
1433 RowReader * const rowReaderP,
1434 unsigned int const alphaPlane,
1435 unsigned int const alphaThreshold,
1436 const struct Cmap * const cmapP,
1437 unsigned int const initBits,
1438 FILE * const ofP,
1439 bool const lzw,
1440 bool const noclear) {
1441 /*----------------------------------------------------------------------------
1442 Write the raster to file 'ofP'.
1443
1444 Get the raster to write from 'rowReaderP', which gives tuples whose
1445 format is described by 'pamP'.
1446
1447 'alphaPlane' is the number of the plane in the tuples supplied by
1448 'rowReaderP' that we should use for transparency information, and
1449 'alphaThreshold' is the value in that plane below which we should consider
1450 the pixel transparent for GIF purposes.
1451
1452 'alphaPlane' is zero to indicate we should not use any plane as an alpha
1453 plane (so it's not possible to specify Plane 0 as alpha).
1454
1455 Use the colormap 'cmapP' to generate the raster ('rowReaderP' gives
1456 pixel values as RGB samples; the GIF raster is colormap indices).
1457
1458 Write the raster using LZW compression, or uncompressed depending
1459 on 'lzw'.
1460
1461 If 'noclear', don't use any GIF clear codes in the output; i.e. don't
1462 recompute the string table from current input. Once the string table gets
1463 to maximum size, just keep using that table for the rest of the image.
1464 -----------------------------------------------------------------------------*/
1465 LzwCompressor * lzwP;
1466 tuple * tuplerow;
1467 unsigned int nRowsDone;
1468 /* Number of rows we have read so far from the the input (the
1469 last of which is the one we're working on now). Note that
1470 in case of interlace, this is not the same thing as the row
1471 number of the current row.
1472 */
1473
1474 lzwP = lzw_create(ofP, initBits, lzw, noclear, pamP->height * pamP->width);
1475
1476 tuplerow = pnm_allocpamrow(pamP);
1477
1478 lzw_clearBlock(lzwP);
1479
1480 nRowsDone = 0;
1481
1482 while (nRowsDone < pamP->height) {
1483 unsigned int col;
1484
1485 rowReader_read(rowReaderP, tuplerow);
1486
1487 for (col = 0; col < pamP->width; ++col) {
1488 unsigned int const colorIndex =
1489 gifPixel(pamP, tuplerow[col], alphaPlane, alphaThreshold,
1490 cmapP);
1491
1492 /* The value for the pixel in the GIF image. I.e. the colormap
1493 index.
1494 */
1495 if (lzw)
1496 lzw_encodePixel(lzwP, colorIndex);
1497 else
1498 writePixelUncompressed(lzwP, colorIndex);
1499 }
1500 ++nRowsDone;
1501 }
1502 /* Gif is no good with no pixels; fortunately, that's impossible: */
1503 assert(nRowsDone > 0);
1504
1505 lzw_flush(lzwP);
1506
1507 pnm_freepamrow(tuplerow);
1508
1509 lzw_destroy(lzwP);
1510 }
1511
1512
1513
1514 static void
1515 writeEndOfImage(FILE * const ofP) {
1516
1517 /* An empty block marks the end of a series of blocks */
1518
1519 fputc(0, ofP);
1520 }
1521
1522
1523
1524 static void
1525 writeGifImage(FILE * const ofP,
1526 unsigned int const leftOffset,
1527 unsigned int const topOffset,
1528 struct pam * const pamP,
1529 pm_filepos const rasterPos,
1530 bool const gInterlace,
1531 unsigned int const bitsPerPixel,
1532 bool const lzw,
1533 bool const noclear,
1534 bool const usingAlpha,
1535 const struct Cmap * const cmapP) {
1536
1537 unsigned int const initCodeSize = bitsPerPixel <= 1 ? 2 : bitsPerPixel;
1538 /* The initial code size */
1539
1540 sample const alphaThreshold = (pamP->maxval + 1) / 2;
1541 /* Levels below this in the alpha plane indicate transparent
1542 pixels in the output image.
1543 */
1544
1545 unsigned int const alphaPlane = usingAlpha ? pamAlphaPlane(pamP) : 0;
1546
1547 RowReader * rowReaderP;
1548
1549 writeImageSeparator(ofP);
1550
1551 writeImageHeader(ofP, leftOffset, topOffset, pamP->width, pamP->height,
1552 gInterlace, initCodeSize);
1553
1554 rowReaderP = rowReader_create(pamP, rasterPos, gInterlace);
1555
1556 writeRaster(pamP, rowReaderP, alphaPlane, alphaThreshold,
1557 cmapP, initCodeSize + 1, ofP, lzw, noclear);
1558
1559 rowReader_destroy(rowReaderP);
1560
1561 writeEndOfImage(ofP);
1562 }
1563
1564
1565
1566 static void
1567 writeGifStreamTerminator(FILE * const ofP) {
1568
1569 fputc(';', ofP);
1570 }
1571
1572
1573
1574 static void
1575 writeGif(struct pam * const pamP,
1576 FILE * const ofP,
1577 pm_filepos const rasterPos,
1578 bool const gInterlace,
1579 int const background,
1580 unsigned int const bitsPerPixel,
1581 const struct Cmap * const cmapP,
1582 char const comment[],
1583 float const aspect,
1584 bool const lzw,
1585 bool const noclear,
1586 bool const usingAlpha) {
1587 /*----------------------------------------------------------------------------
1588 'usingAlpha' means use the alpha (transparency) plane, if there is one, to
1589 determine which GIF pixels are transparent. When this is true, the
1590 colormap *cmapP must contain a transparent entry.
1591 -----------------------------------------------------------------------------*/
1592 unsigned int const leftOffset = 0;
1593 unsigned int const topOffset = 0;
1594
1595 reportImageInfo(gInterlace, background, bitsPerPixel);
1596
1597 if (pamP->width > 65535)
1598 pm_error("Image width %u too large for GIF format. (Max 65535)",
1599 pamP->width);
1600
1601 if (pamP->height > 65535)
1602 pm_error("Image height %u too large for GIF format. (Max 65535)",
1603 pamP->height);
1604
1605 writeGifHeader(ofP, pamP->width, pamP->height, background,
1606 bitsPerPixel, cmapP, comment, aspect);
1607
1608 writeGifImage(ofP, leftOffset, topOffset, pamP, rasterPos,
1609 gInterlace, bitsPerPixel, lzw, noclear, usingAlpha,
1610 cmapP);
1611
1612 writeGifStreamTerminator(ofP);
1613 }
1614
1615
1616
1617 static void
1618 reportTransparent(enum TransparencyType const transType,
1619 const struct Cmap * const cmapP) {
1620
1621 if (verbose) {
1622 switch (transType) {
1623 case TRANS_NONE:
1624 pm_message("Not making transparent pixels");
1625 break;
1626 case TRANS_COLOR:
1627 pm_message("Making pixels of a certain color transparent");
1628 break;
1629 case TRANS_ALPHA:
1630 pm_message("Making pixels transparent per input alpha mask");
1631 break;
1632 }
1633
1634 if (cmapP->haveTransparent) {
1635 tuple const color = cmapP->color[cmapP->transparent];
1636 pm_message("Color %u (%lu, %lu, %lu) is transparent",
1637 cmapP->transparent,
1638 color[PAM_RED_PLANE],
1639 color[PAM_GRN_PLANE],
1640 color[PAM_BLU_PLANE]);
1641 } else
1642 pm_message("No transparent color");
1643 }
1644 }
1645
1646
1647
1648 static void
1649 computeTransparent(enum TransparencyType const transType,
1650 char const colorarg[],
1651 unsigned int const fakeTransparent,
1652 struct Cmap * const cmapP) {
1653 /*----------------------------------------------------------------------------
1654 Figure out the color index (index into the colormap) of the color
1655 that is to be transparent in the GIF and set it in the colormap.
1656
1657 'transType' tells what the source of the transparency is.
1658
1659 If 'transType' says all pixels of a single foreground color are to be
1660 transparent:
1661
1662 'colorarg' is the specification of that color. Its
1663 maxval is the maxval of the colormap.
1664
1665 colorarg[] is a standard Netpbm color specification (e.g. "red",
1666 "#fefefe"), except that may have a "=" prefix, which means it specifies a
1667 particular exact color, as opposed to without the "=", which means "the
1668 color that is closest to this and actually in the image."
1669
1670 Establish no transparent color if colorarg[] specifies an exact
1671 color and that color is not in the image. Also issue an
1672 informational message.
1673
1674 If 'transType' says an input alpha channel will dtermine what pixels are
1675 transparent:
1676
1677 'fakeTransparent' is the special color map index for transparent pixels.
1678 -----------------------------------------------------------------------------*/
1679 switch (transType) {
1680 case TRANS_COLOR: {
1681 const char * colorspec;
1682 bool exact;
1683 tuple transcolor;
1684 int found;
1685 int colorindex;
1686
1687 assert(colorarg);
1688
1689 if (colorarg[0] == '=') {
1690 colorspec = &colorarg[1];
1691 exact = TRUE;
1692 } else {
1693 colorspec = colorarg;
1694 exact = FALSE;
1695 }
1696
1697 transcolor = pnm_parsecolor(colorspec, cmapP->pam.maxval);
1698 pnm_lookuptuple(&cmapP->pam, cmapP->tuplehash, transcolor, &found,
1699 &colorindex);
1700
1701 if (found) {
1702 cmapP->haveTransparent = TRUE;
1703 cmapP->transparent = colorindex;
1704 } else if (!exact) {
1705 cmapP->haveTransparent = TRUE;
1706 cmapP->transparent = closestColor(transcolor, &cmapP->pam, cmapP);
1707 } else {
1708 cmapP->haveTransparent = FALSE;
1709 pm_message("Warning: specified transparent color "
1710 "does not occur in image.");
1711 }
1712 } break;
1713 case TRANS_ALPHA: {
1714 cmapP->haveTransparent = TRUE;
1715 cmapP->transparent = fakeTransparent;
1716 } break;
1717 case TRANS_NONE: {
1718 cmapP->haveTransparent = FALSE;
1719 } break;
1720 } /* switch */
1721 reportTransparent(transType, cmapP);
1722 }
1723
1724
1725
1726 static unsigned int
1727 sortOrderColor(tuple const tuple) {
1728
1729 return ((tuple[PAM_RED_PLANE] * MAXCMAPSIZE) +
1730 tuple[PAM_GRN_PLANE]) * MAXCMAPSIZE +
1731 tuple[PAM_BLU_PLANE];
1732 }
1733
1734
1735
1736 #ifndef LITERAL_FN_DEF_MATCH
1737 static qsort_comparison_fn sortCompareColor;
1738 #endif
1739
1740 static int
1741 sortCompareColor(const void * const entry1P,
1742 const void * const entry2P) {
1743
1744 struct tupleint * const * const tupleint1PP = entry1P;
1745 struct tupleint * const * const tupleint2PP = entry2P;
1746
1747 return (sortOrderColor((*tupleint1PP)->tuple)
1748 - sortOrderColor((*tupleint2PP)->tuple));
1749 }
1750
1751
1752
1753 #ifndef LITERAL_FN_DEF_MATCH
1754 static qsort_comparison_fn sortCompareGray;
1755 #endif
1756
1757 static int
1758 sortCompareGray(const void * const entry1P,
1759 const void * const entry2P){
1760
1761 struct tupleint * const * const tupleint1PP = entry1P;
1762 struct tupleint * const * const tupleint2PP = entry2P;
1763
1764 return ((*tupleint1PP)->tuple[0] - (*tupleint2PP)->tuple[0]);
1765 }
1766
1767
1768
1769 static void
1770 sortTupletable(struct pam * const mapPamP,
1771 unsigned int const colors,
1772 tupletable const tuplefreq) {
1773 /*----------------------------------------------------------------------------
1774 Sort the colormap *cmapP.
1775
1776 Sort the colormap by red intensity, then by green intensity,
1777 then by blue intensity.
1778 -----------------------------------------------------------------------------*/
1779
1780 pm_message("sorting colormap");
1781
1782 if (mapPamP->depth < 3)
1783 qsort(tuplefreq, colors, sizeof(tuplefreq[0]), sortCompareGray);
1784 else
1785 qsort(tuplefreq, colors, sizeof(tuplefreq[0]), sortCompareColor);
1786
1787 }
1788
1789
1790
1791 static void
1792 addToColormap(struct Cmap * const cmapP,
1793 const char * const colorspec,
1794 unsigned int * const newIndexP) {
1795 /*----------------------------------------------------------------------------
1796 Add a new entry to the colormap. Make the color that specified by
1797 'colorspec', and return the index of the new entry as *newIndexP.
1798
1799 'colorspec' is a color specification given by the user, e.g.
1800 "red" or "rgb:ff/03/0d". The maxval for this color specification is
1801 that for the colormap *cmapP.
1802 -----------------------------------------------------------------------------*/
1803 tuple const transcolor = pnm_parsecolor(colorspec, cmapP->pam.maxval);
1804
1805 unsigned int const colorIndex = cmapP->cmapSize++;
1806
1807 cmapP->color[colorIndex] = pnm_allocpamtuple(&cmapP->pam);
1808
1809 if (cmapP->pam.depth < 3) {
1810 if (!pnm_rgbtupleisgray(transcolor))
1811 pm_error("Image is grayscale, but color '%s' is not gray. "
1812 "It is (%lu, %lu, %lu)",
1813 colorspec,
1814 transcolor[PAM_RED_PLANE],
1815 transcolor[PAM_GRN_PLANE],
1816 transcolor[PAM_BLU_PLANE]);
1817 else
1818 cmapP->color[colorIndex][0] = transcolor[0];
1819 } else {
1820 pnm_assigntuple(&cmapP->pam, cmapP->color[colorIndex], transcolor);
1821 }
1822 *newIndexP = colorIndex;
1823 }
1824
1825
1826
1827 static void
1828 colormapFromFile(char const filespec[],
1829 unsigned int const maxcolors,
1830 tupletable * const tupletableP,
1831 struct pam * const mapPamP,
1832 unsigned int * const colorCountP) {
1833 /*----------------------------------------------------------------------------
1834 Read a colormap from the Netpbm file filespec[]. Return a
1835 tupletable of the colors in it (which is practically a colormap) as
1836 *tupletableP and the format of those tuples as *mapPamP. Return
1837 the number of colors as *colorsCountP.
1838 -----------------------------------------------------------------------------*/
1839 FILE * mapfileP;
1840 tuple ** colors;
1841 unsigned int colorCount;
1842
1843 mapfileP = pm_openr(filespec);
1844 colors = pnm_readpam(mapfileP, mapPamP, PAM_STRUCT_SIZE(tuple_type));
1845 pm_close(mapfileP);
1846
1847 pm_message("computing other colormap ...");
1848
1849 *tupletableP =
1850 pnm_computetuplefreqtable(mapPamP, colors, maxcolors, &colorCount);
1851
1852 *colorCountP = colorCount;
1853
1854 pnm_freepamarray(colors, mapPamP);
1855 }
1856
1857
1858
1859 static void
1860 readAndValidateColormapFromFile(char const filename[],
1861 unsigned int const maxcolors,
1862 tupletable * const tuplefreqP,
1863 struct pam * const mapPamP,
1864 unsigned int * const colorCountP,
1865 unsigned int const nInputComp,
1866 sample const inputMaxval) {
1867 /*----------------------------------------------------------------------------
1868 Read the colormap from a separate colormap file named filename[],
1869 and make sure it's consistent with an image with 'nInputComp'
1870 color components (e.g. 3 for RGB) and a maxval of 'inputMaxval'.
1871 -----------------------------------------------------------------------------*/
1872 colormapFromFile(filename, maxcolors, tuplefreqP, mapPamP, colorCountP);
1873
1874 if (mapPamP->depth != nInputComp)
1875 pm_error("Depth of map file (%u) does not match number of "
1876 "color components in input file (%u)",
1877 mapPamP->depth, nInputComp);
1878 if (mapPamP->maxval != inputMaxval)
1879 pm_error("Maxval of map file (%lu) does not match maxval of "
1880 "input file (%lu)", mapPamP->maxval, inputMaxval);
1881 }
1882
1883
1884
1885 static void
1886 computeColormapBw(struct pam * const pamP,
1887 struct pam * const mapPamP,
1888 unsigned int * const colorCountP,
1889 tupletable * const tuplefreqP) {
1890 /*----------------------------------------------------------------------------
1891 Shortcut for black and white (e.g. PBM). We know that there are
1892 only two colors. Users who know that only one color is present in
1893 the image should specify -sort at the command line. Example:
1894
1895 $ pbmmake -w 600 400 | pamtogif -sort > canvas.gif
1896 -----------------------------------------------------------------------------*/
1897 tupletable const colormap = pnm_alloctupletable(pamP, 2);
1898
1899 *mapPamP = *pamP;
1900 mapPamP->depth = 1;
1901
1902 colormap[0]->value = 1;
1903 colormap[0]->tuple[0] = PAM_BLACK;
1904 colormap[1]->value = 1;
1905 colormap[1]->tuple[0] = PAM_BW_WHITE;
1906
1907 *tuplefreqP = colormap;
1908 *colorCountP = 2;
1909 }
1910
1911
1912
1913 static void
1914 computeColormapFromInput(struct pam * const pamP,
1915 unsigned int const maxcolors,
1916 unsigned int const nInputComp,
1917 struct pam * const mapPamP,
1918 unsigned int * const colorCountP,
1919 tupletable * const tuplefreqP) {
1920
1921 tupletable tuplefreq;
1922
1923 pm_message("computing colormap...");
1924
1925 tuplefreq = pnm_computetuplefreqtable3(
1926 pamP, NULL, maxcolors, nInputComp, pamP->maxval, colorCountP);
1927
1928 *mapPamP = *pamP;
1929 mapPamP->depth = nInputComp;
1930
1931 *tuplefreqP = tuplefreq;
1932 }
1933
1934
1935
1936 static void
1937 computeLibnetpbmColormap(struct pam * const pamP,
1938 enum TransparencyType const transType,
1939 const char * const mapfile,
1940 tuple * const color,
1941 tuplehash * const tuplehashP,
1942 struct pam * const mapPamP,
1943 unsigned int * const colorCountP,
1944 bool const sort) {
1945 /*----------------------------------------------------------------------------
1946 Compute a colormap, libnetpbm style, for the image described by
1947 'pamP', which is positioned to the raster.
1948
1949 If 'mapfile' is non-null, Use the colors in that (Netpbm) file for
1950 the color map instead of the colors in 'pamP'.
1951
1952 Return the colormap as color[] and *tuplehashP. Return the format
1953 of those tuples as *mapPamP.
1954
1955 The tuples of the color map have a meaningful depth of 1 (grayscale) or 3
1956 (color) and *mapPamP reflects that.
1957
1958 While we're at it, count the colors and validate that there aren't too
1959 many. Return the count as *colorCountP. In determining if there are too
1960 many, allow one slot for a fake transparency color if 'transType' is
1961 'TRANS_ALPHA'. If there are too many, issue an error message and abort the
1962 program.
1963
1964 'sort' means to sort the colormap by red intensity, then by green
1965 intensity, then by blue intensity, as opposed to arbitrary order.
1966 -----------------------------------------------------------------------------*/
1967 unsigned int const maxcolors =
1968 transType == TRANS_ALPHA ? MAXCMAPSIZE - 1 : MAXCMAPSIZE;
1969 /* The most colors we can tolerate in the image. If we have
1970 our own made-up entry in the colormap for transparency, it
1971 isn't included in this count.
1972 */
1973 unsigned int const nInputComp =
1974 pamAlphaPlane(pamP) ? pamP->depth - 1 : pamP->depth;
1975 /* Number of color components (not alpha) in the input image */
1976
1977 unsigned int i;
1978 tupletable tuplefreq;
1979 unsigned int colorCount;
1980
1981 if (mapfile)
1982 readAndValidateColormapFromFile(mapfile, maxcolors, &tuplefreq,
1983 mapPamP, &colorCount,
1984 nInputComp, pamP->maxval);
1985 else if (nInputComp == 1 && pamP->maxval == 1 && !sort &&
1986 pamP->height * pamP->width > 1)
1987 computeColormapBw(pamP, mapPamP, &colorCount, &tuplefreq);
1988 else
1989 computeColormapFromInput(pamP, maxcolors, nInputComp,
1990 mapPamP, &colorCount, &tuplefreq);
1991
1992 if (tuplefreq == NULL)
1993 pm_error("too many colors - try doing a 'pnmquant %u'", maxcolors);
1994
1995 pm_message("%u colors found", colorCount);
1996
1997 if (sort)
1998 sortTupletable(mapPamP, colorCount, tuplefreq);
1999
2000 for (i = 0; i < colorCount; ++i) {
2001 color[i] = pnm_allocpamtuple(mapPamP);
2002 pnm_assigntuple(mapPamP, color[i], tuplefreq[i]->tuple);
2003 }
2004
2005 /* And make a hash table for fast lookup. */
2006 *tuplehashP =
2007 pnm_computetupletablehash(mapPamP, tuplefreq, colorCount);
2008
2009 *colorCountP = colorCount;
2010
2011 pnm_freetupletable(mapPamP, tuplefreq);
2012 }
2013
2014
2015
2016 static void
2017 destroyCmap(struct Cmap * const cmapP) {
2018
2019 unsigned int colorIndex;
2020
2021 for (colorIndex = 0; colorIndex < cmapP->cmapSize; ++colorIndex)
2022 pnm_freepamtuple(cmapP->color[colorIndex]);
2023
2024 pnm_destroytuplehash(cmapP->tuplehash);
2025 }
2026
2027
2028
2029 int
2030 main(int argc, const char ** argv) {
2031
2032 struct CmdlineInfo cmdline;
2033 FILE * ifP;
2034 struct pam pam;
2035 unsigned int bitsPerPixel;
2036 pm_filepos rasterPos;
2037 struct Cmap cmap;
2038 /* The colormap, with all its accessories */
2039 enum TransparencyType transType;
2040 unsigned int fakeTransparent;
2041 /* colormap index of the fake transparency color we're using to
2042 implement the alpha mask. Defined only if 'transType' is
2043 TRANS_ALPHA.
2044 */
2045
2046 pm_proginit(&argc, argv);
2047
2048 parseCommandLine(argc, argv, &cmdline);
2049
2050 verbose = cmdline.verbose;
2051
2052 ifP = pm_openr_seekable(cmdline.input_filespec);
2053
2054 pnm_readpaminit(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
2055
2056 pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
2057
2058 transType = cmdline.transparent ? TRANS_COLOR :
2059 pamAlphaPlane(&pam) ? TRANS_ALPHA :
2060 TRANS_NONE;
2061
2062 computeLibnetpbmColormap(&pam, transType, cmdline.mapfile,
2063 cmap.color, &cmap.tuplehash,
2064 &cmap.pam, &cmap.cmapSize, cmdline.sort);
2065
2066 assert(cmap.pam.maxval == pam.maxval);
2067
2068 if (transType == TRANS_ALPHA) {
2069 /* Add a fake entry to the end of the colormap for transparency.
2070 Make its color black.
2071 */
2072 addToColormap(&cmap, cmdline.alphacolor, &fakeTransparent);
2073 }
2074
2075 bitsPerPixel = cmap.cmapSize == 1 ? 1 : nSignificantBits(cmap.cmapSize-1);
2076
2077 computeTransparent(transType, cmdline.transparent, fakeTransparent, &cmap);
2078
2079 writeGif(&pam, stdout, rasterPos,
2080 cmdline.interlace, 0, bitsPerPixel, &cmap, cmdline.comment,
2081 cmdline.aspect, !cmdline.nolzw, cmdline.noclear,
2082 transType==TRANS_ALPHA);
2083
2084 destroyCmap(&cmap);
2085
2086 pm_close(ifP);
2087 pm_close(stdout);
2088
2089 return 0;
2090 }
2091
2092
2093
2094 /*============================================================================
2095 Original version, named 'ppmgif' was by Jef Poskanzer in 1989, based
2096 on GIFENCOD by David Rowley <[email protected]>.A Lempel-Zim
2097 compression based on "compress".
2098
2099 Switched to use libnetpbm PAM facilities (ergo process PAM images)
2100 and renamed 'pamtogif' by Bryan Henderson November 2006.
2101
2102 The non-LZW GIF generation stuff was adapted from the Independent
2103 JPEG Group's djpeg on 2001.09.29. In 2006.12 the output subroutines
2104 were rewritten; now no uncompressed output subroutines are derived from
2105 the Independent JPEG Group's source code.
2106
2107 2007.01 Changed sort routine to qsort. (afu)
2108 2007.03 Implemented variable hash table size, PBM color table
2109 shortcut and "-aspect" command line option. (afu)
2110
2111
2112 Copyright (C) 1989 by Jef Poskanzer.
2113
2114 Permission to use, copy, modify, and distribute this software and its
2115 documentation for any purpose and without fee is hereby granted, provided
2116 that the above copyright notice appear in all copies and that both that
2117 copyright notice and this permission notice appear in supporting
2118 documentation. This software is provided "as is" without express or
2119 implied warranty.
2120
2121 The Graphics Interchange Format(c) is the Copyright property of
2122 CompuServe Incorporated. GIF(sm) is a Service Mark property of
2123 CompuServe Incorporated.
2124 ============================================================================*/
2125