1 /* $Id: ppm2tiff.c,v 1.19 2015-06-21 01:09:10 bfriesen Exp $ */
2 
3 /*
4  * Copyright (c) 1991-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  *
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24  * OF THIS SOFTWARE.
25  */
26 
27 #include "tif_config.h"
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <ctype.h>
33 
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37 
38 #ifdef HAVE_FCNTL_H
39 # include <fcntl.h>
40 #endif
41 
42 #ifdef HAVE_IO_H
43 # include <io.h>
44 #endif
45 
46 #ifdef NEED_LIBPORT
47 # include "libport.h"
48 #endif
49 
50 #include "tiffio.h"
51 
52 #ifndef HAVE_GETOPT
53 extern int getopt(int, char**, char*);
54 #endif
55 
56 #define	streq(a,b)	(strcmp(a,b) == 0)
57 #define	strneq(a,b,n)	(strncmp(a,b,n) == 0)
58 
59 static	uint16 compression = COMPRESSION_PACKBITS;
60 static	uint16 predictor = 0;
61 static	int quality = 75;	/* JPEG quality */
62 static	int jpegcolormode = JPEGCOLORMODE_RGB;
63 static  uint32 g3opts;
64 
65 static	void usage(void);
66 static	int processCompressOptions(char*);
67 
68 static void
BadPPM(char * file)69 BadPPM(char* file)
70 {
71 	fprintf(stderr, "%s: Not a PPM file.\n", file);
72 	exit(-2);
73 }
74 
75 
76 #define TIFF_SIZE_T_MAX ((size_t) ~ ((size_t)0))
77 #define TIFF_TMSIZE_T_MAX (tmsize_t)(TIFF_SIZE_T_MAX >> 1)
78 
79 static tmsize_t
multiply_ms(tmsize_t m1,tmsize_t m2)80 multiply_ms(tmsize_t m1, tmsize_t m2)
81 {
82         if( m1 == 0 || m2 > TIFF_TMSIZE_T_MAX / m1 )
83             return 0;
84         return m1 * m2;
85 }
86 
87 int
main(int argc,char * argv[])88 main(int argc, char* argv[])
89 {
90 	uint16 photometric = 0;
91 	uint32 rowsperstrip = (uint32) -1;
92 	double resolution = -1;
93 	unsigned char *buf = NULL;
94 	tmsize_t linebytes = 0;
95 	uint16 spp = 1;
96 	uint16 bpp = 8;
97 	TIFF *out;
98 	FILE *in;
99 	unsigned int w, h, prec, row;
100 	char *infile;
101 	int c;
102 #if !HAVE_DECL_OPTARG
103 	extern int optind;
104 	extern char* optarg;
105 #endif
106 	tmsize_t scanline_size;
107 
108 	if (argc < 2) {
109 	    fprintf(stderr, "%s: Too few arguments\n", argv[0]);
110 	    usage();
111 	}
112 	while ((c = getopt(argc, argv, "c:r:R:")) != -1)
113 		switch (c) {
114 		case 'c':		/* compression scheme */
115 			if (!processCompressOptions(optarg))
116 				usage();
117 			break;
118 		case 'r':		/* rows/strip */
119 			rowsperstrip = atoi(optarg);
120 			break;
121 		case 'R':		/* resolution */
122 			resolution = atof(optarg);
123 			break;
124 		case '?':
125 			usage();
126 			/*NOTREACHED*/
127 		}
128 
129 	if (optind + 2 < argc) {
130 	    fprintf(stderr, "%s: Too many arguments\n", argv[0]);
131 	    usage();
132 	}
133 
134 	/*
135 	 * If only one file is specified, read input from
136 	 * stdin; otherwise usage is: ppm2tiff input output.
137 	 */
138 	if (argc - optind > 1) {
139 		infile = argv[optind++];
140 		in = fopen(infile, "rb");
141 		if (in == NULL) {
142 			fprintf(stderr, "%s: Can not open.\n", infile);
143 			return (-1);
144 		}
145 	} else {
146 		infile = "<stdin>";
147 		in = stdin;
148 #if defined(HAVE_SETMODE) && defined(O_BINARY)
149 		setmode(fileno(stdin), O_BINARY);
150 #endif
151 	}
152 
153 	if (fgetc(in) != 'P')
154 		BadPPM(infile);
155 	switch (fgetc(in)) {
156 		case '4':			/* it's a PBM file */
157 			bpp = 1;
158 			spp = 1;
159 			photometric = PHOTOMETRIC_MINISWHITE;
160 			break;
161 		case '5':			/* it's a PGM file */
162 			bpp = 8;
163 			spp = 1;
164 			photometric = PHOTOMETRIC_MINISBLACK;
165 			break;
166 		case '6':			/* it's a PPM file */
167 			bpp = 8;
168 			spp = 3;
169 			photometric = PHOTOMETRIC_RGB;
170 			if (compression == COMPRESSION_JPEG &&
171 			    jpegcolormode == JPEGCOLORMODE_RGB)
172 				photometric = PHOTOMETRIC_YCBCR;
173 			break;
174 		default:
175 			BadPPM(infile);
176 	}
177 
178 	/* Parse header */
179 	while(1) {
180 		if (feof(in))
181 			BadPPM(infile);
182 		c = fgetc(in);
183 		/* Skip whitespaces (blanks, TABs, CRs, LFs) */
184 		if (strchr(" \t\r\n", c))
185 			continue;
186 
187 		/* Check for comment line */
188 		if (c == '#') {
189 			do {
190 			    c = fgetc(in);
191 			} while(!(strchr("\r\n", c) || feof(in)));
192 			continue;
193 		}
194 
195 		ungetc(c, in);
196 		break;
197 	}
198 	switch (bpp) {
199 	case 1:
200 		if (fscanf(in, " %u %u", &w, &h) != 2)
201 			BadPPM(infile);
202 		if (fgetc(in) != '\n')
203 			BadPPM(infile);
204 		break;
205 	case 8:
206 		if (fscanf(in, " %u %u %u", &w, &h, &prec) != 3)
207 			BadPPM(infile);
208 		if (fgetc(in) != '\n' || prec != 255)
209 			BadPPM(infile);
210 		break;
211 	}
212 	out = TIFFOpen(argv[optind], "w");
213 	if (out == NULL)
214 		return (-4);
215 	TIFFSetField(out, TIFFTAG_IMAGEWIDTH, (uint32) w);
216 	TIFFSetField(out, TIFFTAG_IMAGELENGTH, (uint32) h);
217 	TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
218 	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
219 	TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bpp);
220 	TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
221 	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
222 	TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
223 	switch (compression) {
224 	case COMPRESSION_JPEG:
225 		TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
226 		TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
227 		break;
228 	case COMPRESSION_LZW:
229 	case COMPRESSION_DEFLATE:
230 		if (predictor != 0)
231 			TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
232 		break;
233         case COMPRESSION_CCITTFAX3:
234 		TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
235 		break;
236 	}
237 	switch (bpp) {
238 		case 1:
239 			/* if round-up overflows, result will be zero, OK */
240 			linebytes = (multiply_ms(spp, w) + (8 - 1)) / 8;
241 			if (rowsperstrip == (uint32) -1) {
242 				TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, h);
243 			} else {
244 				TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
245 				    TIFFDefaultStripSize(out, rowsperstrip));
246 			}
247 			break;
248 		case 8:
249 			linebytes = multiply_ms(spp, w);
250 			TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
251 			    TIFFDefaultStripSize(out, rowsperstrip));
252 			break;
253 	}
254 	if (linebytes == 0) {
255 		fprintf(stderr, "%s: scanline size overflow\n", infile);
256 		(void) TIFFClose(out);
257 		exit(-2);
258 	}
259 	scanline_size = TIFFScanlineSize(out);
260 	if (scanline_size == 0) {
261 		/* overflow - TIFFScanlineSize already printed a message */
262 		(void) TIFFClose(out);
263 		exit(-2);
264 	}
265 	if (scanline_size < linebytes)
266 		buf = (unsigned char *)_TIFFmalloc(linebytes);
267 	else
268 		buf = (unsigned char *)_TIFFmalloc(scanline_size);
269 	if (buf == NULL) {
270 		fprintf(stderr, "%s: Not enough memory\n", infile);
271 		(void) TIFFClose(out);
272 		exit(-2);
273 	}
274 	if (resolution > 0) {
275 		TIFFSetField(out, TIFFTAG_XRESOLUTION, resolution);
276 		TIFFSetField(out, TIFFTAG_YRESOLUTION, resolution);
277 		TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
278 	}
279 	for (row = 0; row < h; row++) {
280 		if (fread(buf, linebytes, 1, in) != 1) {
281 			fprintf(stderr, "%s: scanline %lu: Read error.\n",
282 			    infile, (unsigned long) row);
283 			break;
284 		}
285 		if (TIFFWriteScanline(out, buf, row, 0) < 0)
286 			break;
287 	}
288 	(void) TIFFClose(out);
289 	if (buf)
290 		_TIFFfree(buf);
291 	return (0);
292 }
293 
294 static void
processG3Options(char * cp)295 processG3Options(char* cp)
296 {
297 	g3opts = 0;
298         if( (cp = strchr(cp, ':')) ) {
299                 do {
300                         cp++;
301                         if (strneq(cp, "1d", 2))
302                                 g3opts &= ~GROUP3OPT_2DENCODING;
303                         else if (strneq(cp, "2d", 2))
304                                 g3opts |= GROUP3OPT_2DENCODING;
305                         else if (strneq(cp, "fill", 4))
306                                 g3opts |= GROUP3OPT_FILLBITS;
307                         else
308                                 usage();
309                 } while( (cp = strchr(cp, ':')) );
310         }
311 }
312 
313 static int
processCompressOptions(char * opt)314 processCompressOptions(char* opt)
315 {
316 	if (streq(opt, "none"))
317 		compression = COMPRESSION_NONE;
318 	else if (streq(opt, "packbits"))
319 		compression = COMPRESSION_PACKBITS;
320 	else if (strneq(opt, "jpeg", 4)) {
321 		char* cp = strchr(opt, ':');
322 
323                 compression = COMPRESSION_JPEG;
324                 while (cp)
325                 {
326                     if (isdigit((int)cp[1]))
327 			quality = atoi(cp+1);
328                     else if (cp[1] == 'r' )
329 			jpegcolormode = JPEGCOLORMODE_RAW;
330                     else
331                         usage();
332 
333                     cp = strchr(cp+1,':');
334                 }
335 	} else if (strneq(opt, "g3", 2)) {
336 		processG3Options(opt);
337 		compression = COMPRESSION_CCITTFAX3;
338 	} else if (streq(opt, "g4")) {
339 		compression = COMPRESSION_CCITTFAX4;
340 	} else if (strneq(opt, "lzw", 3)) {
341 		char* cp = strchr(opt, ':');
342 		if (cp)
343 			predictor = atoi(cp+1);
344 		compression = COMPRESSION_LZW;
345 	} else if (strneq(opt, "zip", 3)) {
346 		char* cp = strchr(opt, ':');
347 		if (cp)
348 			predictor = atoi(cp+1);
349 		compression = COMPRESSION_DEFLATE;
350 	} else
351 		return (0);
352 	return (1);
353 }
354 
355 char* stuff[] = {
356 "usage: ppm2tiff [options] input.ppm output.tif",
357 "where options are:",
358 " -r #		make each strip have no more than # rows",
359 " -R #		set x&y resolution (dpi)",
360 "",
361 " -c jpeg[:opts]  compress output with JPEG encoding",
362 " -c lzw[:opts]	compress output with Lempel-Ziv & Welch encoding",
363 " -c zip[:opts]	compress output with deflate encoding",
364 " -c packbits	compress output with packbits encoding (the default)",
365 " -c g3[:opts]  compress output with CCITT Group 3 encoding",
366 " -c g4         compress output with CCITT Group 4 encoding",
367 " -c none	use no compression algorithm on output",
368 "",
369 "JPEG options:",
370 " #		set compression quality level (0-100, default 75)",
371 " r		output color image as RGB rather than YCbCr",
372 "LZW and deflate options:",
373 " #		set predictor value",
374 "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
375 NULL
376 };
377 
378 static void
usage(void)379 usage(void)
380 {
381 	char buf[BUFSIZ];
382 	int i;
383 
384 	setbuf(stderr, buf);
385         fprintf(stderr, "%s\n\n", TIFFGetVersion());
386 	for (i = 0; stuff[i] != NULL; i++)
387 		fprintf(stderr, "%s\n", stuff[i]);
388 	exit(-1);
389 }
390 
391 /* vim: set ts=8 sts=8 sw=8 noet: */
392 /*
393  * Local Variables:
394  * mode: c
395  * c-basic-offset: 8
396  * fill-column: 78
397  * End:
398  */
399