1 /*
2  * Copyright (c) 1988-1997 Sam Leffler
3  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and
6  * its documentation for any purpose is hereby granted without fee, provided
7  * that (i) the above copyright notices and this permission notice appear in
8  * all copies of the software and related documentation, and (ii) the names of
9  * Sam Leffler and Silicon Graphics may not be used in any advertising or
10  * publicity relating to the software without the specific, prior written
11  * permission of Sam Leffler and Silicon Graphics.
12  *
13  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22  * OF THIS SOFTWARE.
23  */
24 
25 #include "tif_config.h"
26 
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <ctype.h>
31 
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 
36 #ifdef NEED_LIBPORT
37 # include "libport.h"
38 #endif
39 
40 #include "tiffio.h"
41 
42 #define	streq(a,b)	(strcmp(a,b) == 0)
43 #define	strneq(a,b,n)	(strncmp(a,b,n) == 0)
44 
45 static	void usage(void);
46 static	void cpTags(TIFF* in, TIFF* out);
47 
48 static int
checkcmap(int n,uint16 * r,uint16 * g,uint16 * b)49 checkcmap(int n, uint16* r, uint16* g, uint16* b)
50 {
51 	while (n-- > 0)
52 	    if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
53 		return (16);
54 	fprintf(stderr, "Warning, assuming 8-bit colormap.\n");
55 	return (8);
56 }
57 
58 #define	CopyField(tag, v) \
59     if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
60 #define	CopyField3(tag, v1, v2, v3) \
61     if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
62 
63 static	uint16 compression = (uint16) -1;
64 static	uint16 predictor = 0;
65 static	int quality = 75;	/* JPEG quality */
66 static	int jpegcolormode = JPEGCOLORMODE_RGB;
67 static	int processCompressOptions(char*);
68 
69 int
main(int argc,char * argv[])70 main(int argc, char* argv[])
71 {
72 	uint16 bitspersample, shortv;
73 	uint32 imagewidth, imagelength;
74 	uint16 config = PLANARCONFIG_CONTIG;
75 	uint32 rowsperstrip = (uint32) -1;
76 	uint16 photometric = PHOTOMETRIC_RGB;
77 	uint16 *rmap, *gmap, *bmap;
78 	uint32 row;
79 	int cmap = -1;
80 	TIFF *in, *out;
81 	int c;
82 
83 #if !HAVE_DECL_OPTARG
84 	extern int optind;
85 	extern char* optarg;
86 #endif
87 
88 	while ((c = getopt(argc, argv, "C:c:p:r:")) != -1)
89 		switch (c) {
90 		case 'C':		/* force colormap interpretation */
91 			cmap = atoi(optarg);
92 			break;
93 		case 'c':		/* compression scheme */
94 			if (!processCompressOptions(optarg))
95 				usage();
96 			break;
97 		case 'p':		/* planar configuration */
98 			if (streq(optarg, "separate"))
99 				config = PLANARCONFIG_SEPARATE;
100 			else if (streq(optarg, "contig"))
101 				config = PLANARCONFIG_CONTIG;
102 			else
103 				usage();
104 			break;
105 		case 'r':		/* rows/strip */
106 			rowsperstrip = atoi(optarg);
107 			break;
108 		case '?':
109 			usage();
110 			/*NOTREACHED*/
111 		}
112 	if (argc - optind != 2)
113 		usage();
114 	in = TIFFOpen(argv[optind], "r");
115 	if (in == NULL)
116 		return (-1);
117 	if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) ||
118 	    shortv != PHOTOMETRIC_PALETTE) {
119 		fprintf(stderr, "%s: Expecting a palette image.\n",
120 		    argv[optind]);
121 		(void) TIFFClose(in);
122 		return (-1);
123 	}
124 	if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
125 		fprintf(stderr,
126 		    "%s: No colormap (not a valid palette image).\n",
127 		    argv[optind]);
128 		(void) TIFFClose(in);
129 		return (-1);
130 	}
131 	bitspersample = 0;
132 	TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
133 	if (bitspersample != 8) {
134 		fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n",
135 		    argv[optind]);
136 		(void) TIFFClose(in);
137 		return (-1);
138 	}
139 	out = TIFFOpen(argv[optind+1], "w");
140 	if (out == NULL) {
141 		(void) TIFFClose(in);
142 		return (-2);
143 	}
144 	cpTags(in, out);
145 	TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
146 	TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
147 	if (compression != (uint16)-1)
148 		TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
149 	else
150 		TIFFGetField(in, TIFFTAG_COMPRESSION, &compression);
151 	switch (compression) {
152 	case COMPRESSION_JPEG:
153 		if (jpegcolormode == JPEGCOLORMODE_RGB)
154 			photometric = PHOTOMETRIC_YCBCR;
155 		else
156 			photometric = PHOTOMETRIC_RGB;
157 		TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
158 		TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
159 		break;
160 	case COMPRESSION_LZW:
161 	case COMPRESSION_DEFLATE:
162 		if (predictor != 0)
163 			TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
164 		break;
165 	}
166 	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
167 	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
168 	TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
169 	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
170 	    rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip));
171 	(void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
172 	if (cmap == -1)
173 		cmap = checkcmap(1<<bitspersample, rmap, gmap, bmap);
174 	if (cmap == 16) {
175 		/*
176 		 * Convert 16-bit colormap to 8-bit.
177 		 */
178 		int i;
179 
180 		for (i = (1<<bitspersample)-1; i >= 0; i--) {
181 #define	CVT(x)		(((x) * 255) / ((1L<<16)-1))
182 			rmap[i] = CVT(rmap[i]);
183 			gmap[i] = CVT(gmap[i]);
184 			bmap[i] = CVT(bmap[i]);
185 		}
186 	}
187 	{ unsigned char *ibuf, *obuf;
188 	  register unsigned char* pp;
189 	  register uint32 x;
190 	  tmsize_t tss_in = TIFFScanlineSize(in);
191 	  tmsize_t tss_out = TIFFScanlineSize(out);
192 	  if (tss_out / tss_in < 3) {
193 		/*
194 		 * BUG 2750: The following code does not know about chroma
195 		 * subsampling of JPEG data. It assumes that the output buffer is 3x
196 		 * the length of the input buffer due to exploding the palette into
197 		 * RGB tuples. If this assumption is incorrect, it could lead to a
198 		 * buffer overflow. Go ahead and fail now to prevent that.
199 		 */
200 		fprintf(stderr, "Could not determine correct image size for output. Exiting.\n");
201 		return -1;
202       }
203 	  ibuf = (unsigned char*)_TIFFmalloc(tss_in);
204 	  obuf = (unsigned char*)_TIFFmalloc(tss_out);
205 	  switch (config) {
206 	  case PLANARCONFIG_CONTIG:
207 		for (row = 0; row < imagelength; row++) {
208 			if (!TIFFReadScanline(in, ibuf, row, 0))
209 				goto done;
210 			pp = obuf;
211 			for (x = 0; x < imagewidth; x++) {
212 				*pp++ = (unsigned char) rmap[ibuf[x]];
213 				*pp++ = (unsigned char) gmap[ibuf[x]];
214 				*pp++ = (unsigned char) bmap[ibuf[x]];
215 			}
216 			if (!TIFFWriteScanline(out, obuf, row, 0))
217 				goto done;
218 		}
219 		break;
220 	  case PLANARCONFIG_SEPARATE:
221 		for (row = 0; row < imagelength; row++) {
222 			if (!TIFFReadScanline(in, ibuf, row, 0))
223 				goto done;
224 			for (pp = obuf, x = 0; x < imagewidth; x++)
225 				*pp++ = (unsigned char) rmap[ibuf[x]];
226 			if (!TIFFWriteScanline(out, obuf, row, 0))
227 				goto done;
228 			for (pp = obuf, x = 0; x < imagewidth; x++)
229 				*pp++ = (unsigned char) gmap[ibuf[x]];
230 			if (!TIFFWriteScanline(out, obuf, row, 0))
231 				goto done;
232 			for (pp = obuf, x = 0; x < imagewidth; x++)
233 				*pp++ = (unsigned char) bmap[ibuf[x]];
234 			if (!TIFFWriteScanline(out, obuf, row, 0))
235 				goto done;
236 		}
237 		break;
238 	  }
239 	  _TIFFfree(ibuf);
240 	  _TIFFfree(obuf);
241 	}
242 done:
243 	(void) TIFFClose(in);
244 	(void) TIFFClose(out);
245 	return (0);
246 }
247 
248 static int
processCompressOptions(char * opt)249 processCompressOptions(char* opt)
250 {
251 	if (streq(opt, "none"))
252 		compression = COMPRESSION_NONE;
253 	else if (streq(opt, "packbits"))
254 		compression = COMPRESSION_PACKBITS;
255 	else if (strneq(opt, "jpeg", 4)) {
256 		char* cp = strchr(opt, ':');
257 
258                 compression = COMPRESSION_JPEG;
259                 while( cp )
260                 {
261                     if (isdigit((int)cp[1]))
262 			quality = atoi(cp+1);
263                     else if (cp[1] == 'r' )
264 			jpegcolormode = JPEGCOLORMODE_RAW;
265                     else
266                         usage();
267 
268                     cp = strchr(cp+1,':');
269                 }
270 	} else if (strneq(opt, "lzw", 3)) {
271 		char* cp = strchr(opt, ':');
272 		if (cp)
273 			predictor = atoi(cp+1);
274 		compression = COMPRESSION_LZW;
275 	} else if (strneq(opt, "zip", 3)) {
276 		char* cp = strchr(opt, ':');
277 		if (cp)
278 			predictor = atoi(cp+1);
279 		compression = COMPRESSION_DEFLATE;
280 	} else
281 		return (0);
282 	return (1);
283 }
284 
285 #define	CopyField(tag, v) \
286     if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
287 #define	CopyField2(tag, v1, v2) \
288     if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
289 #define	CopyField3(tag, v1, v2, v3) \
290     if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
291 #define	CopyField4(tag, v1, v2, v3, v4) \
292     if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
293 
294 static void
cpTag(TIFF * in,TIFF * out,uint16 tag,uint16 count,TIFFDataType type)295 cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
296 {
297 	switch (type) {
298 	case TIFF_SHORT:
299 		if (count == 1) {
300 			uint16 shortv;
301 			CopyField(tag, shortv);
302 		} else if (count == 2) {
303 			uint16 shortv1, shortv2;
304 			CopyField2(tag, shortv1, shortv2);
305 		} else if (count == 4) {
306 			uint16 *tr, *tg, *tb, *ta;
307 			CopyField4(tag, tr, tg, tb, ta);
308 		} else if (count == (uint16) -1) {
309 			uint16 shortv1;
310 			uint16* shortav;
311 			CopyField2(tag, shortv1, shortav);
312 		}
313 		break;
314 	case TIFF_LONG:
315 		{ uint32 longv;
316 		  CopyField(tag, longv);
317 		}
318 		break;
319 	case TIFF_RATIONAL:
320 		if (count == 1) {
321 			float floatv;
322 			CopyField(tag, floatv);
323 		} else if (count == (uint16) -1) {
324 			float* floatav;
325 			CopyField(tag, floatav);
326 		}
327 		break;
328 	case TIFF_ASCII:
329 		{ char* stringv;
330 		  CopyField(tag, stringv);
331 		}
332 		break;
333 	case TIFF_DOUBLE:
334 		if (count == 1) {
335 			double doublev;
336 			CopyField(tag, doublev);
337 		} else if (count == (uint16) -1) {
338 			double* doubleav;
339 			CopyField(tag, doubleav);
340 		}
341 		break;
342           default:
343                 TIFFError(TIFFFileName(in),
344                           "Data type %d is not supported, tag %d skipped.",
345                           tag, type);
346 	}
347 }
348 
349 #undef CopyField4
350 #undef CopyField3
351 #undef CopyField2
352 #undef CopyField
353 
354 static struct cpTag {
355     uint16	tag;
356     uint16	count;
357     TIFFDataType type;
358 } tags[] = {
359     { TIFFTAG_IMAGEWIDTH,		1, TIFF_LONG },
360     { TIFFTAG_IMAGELENGTH,		1, TIFF_LONG },
361     { TIFFTAG_BITSPERSAMPLE,		1, TIFF_SHORT },
362     { TIFFTAG_COMPRESSION,		1, TIFF_SHORT },
363     { TIFFTAG_FILLORDER,		1, TIFF_SHORT },
364     { TIFFTAG_ROWSPERSTRIP,		1, TIFF_LONG },
365     { TIFFTAG_GROUP3OPTIONS,		1, TIFF_LONG },
366     { TIFFTAG_SUBFILETYPE,		1, TIFF_LONG },
367     { TIFFTAG_THRESHHOLDING,		1, TIFF_SHORT },
368     { TIFFTAG_DOCUMENTNAME,		1, TIFF_ASCII },
369     { TIFFTAG_IMAGEDESCRIPTION,		1, TIFF_ASCII },
370     { TIFFTAG_MAKE,			1, TIFF_ASCII },
371     { TIFFTAG_MODEL,			1, TIFF_ASCII },
372     { TIFFTAG_ORIENTATION,		1, TIFF_SHORT },
373     { TIFFTAG_MINSAMPLEVALUE,		1, TIFF_SHORT },
374     { TIFFTAG_MAXSAMPLEVALUE,		1, TIFF_SHORT },
375     { TIFFTAG_XRESOLUTION,		1, TIFF_RATIONAL },
376     { TIFFTAG_YRESOLUTION,		1, TIFF_RATIONAL },
377     { TIFFTAG_PAGENAME,			1, TIFF_ASCII },
378     { TIFFTAG_XPOSITION,		1, TIFF_RATIONAL },
379     { TIFFTAG_YPOSITION,		1, TIFF_RATIONAL },
380     { TIFFTAG_GROUP4OPTIONS,		1, TIFF_LONG },
381     { TIFFTAG_RESOLUTIONUNIT,		1, TIFF_SHORT },
382     { TIFFTAG_PAGENUMBER,		2, TIFF_SHORT },
383     { TIFFTAG_SOFTWARE,			1, TIFF_ASCII },
384     { TIFFTAG_DATETIME,			1, TIFF_ASCII },
385     { TIFFTAG_ARTIST,			1, TIFF_ASCII },
386     { TIFFTAG_HOSTCOMPUTER,		1, TIFF_ASCII },
387     { TIFFTAG_WHITEPOINT,		2, TIFF_RATIONAL },
388     { TIFFTAG_PRIMARYCHROMATICITIES,	(uint16) -1,TIFF_RATIONAL },
389     { TIFFTAG_HALFTONEHINTS,		2, TIFF_SHORT },
390     { TIFFTAG_BADFAXLINES,		1, TIFF_LONG },
391     { TIFFTAG_CLEANFAXDATA,		1, TIFF_SHORT },
392     { TIFFTAG_CONSECUTIVEBADFAXLINES,	1, TIFF_LONG },
393     { TIFFTAG_INKSET,			1, TIFF_SHORT },
394     /*{ TIFFTAG_INKNAMES,			1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */
395     { TIFFTAG_DOTRANGE,			2, TIFF_SHORT },
396     { TIFFTAG_TARGETPRINTER,		1, TIFF_ASCII },
397     { TIFFTAG_SAMPLEFORMAT,		1, TIFF_SHORT },
398     { TIFFTAG_YCBCRCOEFFICIENTS,	(uint16) -1,TIFF_RATIONAL },
399     { TIFFTAG_YCBCRSUBSAMPLING,		2, TIFF_SHORT },
400     { TIFFTAG_YCBCRPOSITIONING,		1, TIFF_SHORT },
401     { TIFFTAG_REFERENCEBLACKWHITE,	(uint16) -1,TIFF_RATIONAL },
402 };
403 #define	NTAGS	(sizeof (tags) / sizeof (tags[0]))
404 
405 static void
cpTags(TIFF * in,TIFF * out)406 cpTags(TIFF* in, TIFF* out)
407 {
408     struct cpTag *p;
409     for (p = tags; p < &tags[NTAGS]; p++)
410     {
411         if( p->tag == TIFFTAG_GROUP3OPTIONS )
412         {
413             uint16 compression;
414             if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
415                     compression != COMPRESSION_CCITTFAX3 )
416                 continue;
417         }
418         if( p->tag == TIFFTAG_GROUP4OPTIONS )
419         {
420             uint16 compression;
421             if( !TIFFGetField(in, TIFFTAG_COMPRESSION, &compression) ||
422                     compression != COMPRESSION_CCITTFAX4 )
423                 continue;
424         }
425         cpTag(in, out, p->tag, p->count, p->type);
426     }
427 }
428 #undef NTAGS
429 
430 char* stuff[] = {
431 "usage: pal2rgb [options] input.tif output.tif",
432 "where options are:",
433 " -p contig	pack samples contiguously (e.g. RGBRGB...)",
434 " -p separate	store samples separately (e.g. RRR...GGG...BBB...)",
435 " -r #		make each strip have no more than # rows",
436 " -C 8		assume 8-bit colormap values (instead of 16-bit)",
437 " -C 16		assume 16-bit colormap values",
438 "",
439 " -c lzw[:opts]	compress output with Lempel-Ziv & Welch encoding",
440 " -c zip[:opts]	compress output with deflate encoding",
441 " -c packbits	compress output with packbits encoding",
442 " -c none	use no compression algorithm on output",
443 "",
444 "LZW and deflate options:",
445 " #		set predictor value",
446 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
447 NULL
448 };
449 
450 static void
usage(void)451 usage(void)
452 {
453 	char buf[BUFSIZ];
454 	int i;
455 
456 	setbuf(stderr, buf);
457         fprintf(stderr, "%s\n\n", TIFFGetVersion());
458 	for (i = 0; stuff[i] != NULL; i++)
459 		fprintf(stderr, "%s\n", stuff[i]);
460 	exit(-1);
461 }
462 
463 /* vim: set ts=8 sts=8 sw=8 noet: */
464 /*
465  * Local Variables:
466  * mode: c
467  * c-basic-offset: 8
468  * fill-column: 78
469  * End:
470  */
471