Debian Codegraph @

converter/other/tifftopnm.c

raw
1 /*
2 ** tifftopnm.c - converts a Tagged Image File to a portable anymap
3 **
4 ** Derived by Jef Poskanzer from tif2ras.c, which is:
5 **
6 ** Copyright (c) 1990 by Sun Microsystems, Inc.
7 **
8 ** Author: Patrick J. Naughton
9 ** [email protected]
10 **
11 ** Permission to use, copy, modify, and distribute this software and its
12 ** documentation for any purpose and without fee is hereby granted,
13 ** provided that the above copyright notice appear in all copies and that
14 ** both that copyright notice and this permission notice appear in
15 ** supporting documentation.
16 **
17 ** This file is provided AS IS with no warranties of any kind. The author
18 ** shall have no liability with respect to the infringement of copyrights,
19 ** trade secrets or any patents by this file or any part thereof. In no
20 ** event will the author be liable for any lost revenue or profits or
21 ** other special, indirect and consequential damages.
22 */
23
24 /* Design note:
25
26 We have two different ways of converting from Tiff, as provided by the
27 Tiff library:
28
29 1) decode the entire image into memory at once, using
30 TIFFRGBAImageGet(), then convert to PNM and output row by row.
31
32 2) read, convert, and output one row at a time using TIFFReadScanline().
33
34 (1) is preferable because the Tiff library does more of the work, which
35 means it understands more of the Tiff format possibilities now and in
36 the future. Also, some compressed TIFF formats don't allow you to
37 extract an individual row.
38
39 (2) uses far less memory, and because our code does more of the work,
40 it's possible that it can be more flexible or at least give better
41 diagnostic information if there's something wrong with the TIFF.
42
43 In Netpbm, we stress function over performance, so by default we
44 try (1) first, and if we can't get enough memory for the decoded
45 image or TIFFRGBAImageGet() fails, we fall back to (2). But we
46 give the user the -byrow option to order (2) only.
47 */
48
49 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
50 #define _BSD_SOURCE 1 /* Make sure strdup() is in string.h */
51 #define _XOPEN_SOURCE 500 /* Make sure strdup() is in string.h */
52
53 #include <assert.h>
54 #include <string.h>
55 #include <stdio.h>
56 #include <sys/wait.h> /* WIFSIGNALED, etc. */
57
58 #include "pm_c_util.h"
59 #include "shhopt.h"
60 #include "mallocvar.h"
61 #include "nstring.h"
62 #include "pnm.h"
63
64 /* See warning about tiffio.h in pamtotiff.c */
65 #include <tiffio.h>
66
67 /* The following are in current tiff.h, but so that we can compile against
68 older tiff libraries, we define them here.
69 */
70
71 #ifndef PHOTOMETRIC_LOGL
72 #define PHOTOMETRIC_LOGL 32844
73 #endif
74 #ifndef PHOTOMETRIC_LOGLUV
75 #define PHOTOMETRIC_LOGLUV 32845
76 #endif
77
78 #define MAXCOLORS 1024
79 #ifndef PHOTOMETRIC_DEPTH
80 #define PHOTOMETRIC_DEPTH 32768
81 #endif
82
83 struct CmdlineInfo {
84 /* All the information the user supplied in the command line,
85 in a form easy for the program to use.
86 */
87 char * inputFilename;
88 unsigned int headerdump;
89 char * alphaFilename;
90 bool alphaStdout;
91 unsigned int respectfillorder; /* -respectfillorder option */
92 unsigned int byrow;
93 unsigned int orientraw;
94 unsigned int verbose;
95 };
96
97
98
99 static void
100 parseCommandLine(int argc, const char ** const argv,
101 struct CmdlineInfo * const cmdlineP) {
102 /*----------------------------------------------------------------------------
103 Note that many of the strings that this function returns in the
104 *cmdlineP structure are actually in the supplied argv array. And
105 sometimes, one of these strings is actually just a suffix of an entry
106 in argv!
107 -----------------------------------------------------------------------------*/
108 optEntry * option_def;
109 optStruct3 opt;
110 unsigned int option_def_index;
111 unsigned int alphaSpec;
112
113 MALLOCARRAY_NOFAIL(option_def, 100);
114
115 opt.opt_table = option_def;
116 opt.short_allowed = FALSE;
117 opt.allowNegNum = FALSE;
118
119 option_def_index = 0; /* incremented by OPTENT3 */
120 OPTENT3(0, "verbose",
121 OPT_FLAG, NULL, &cmdlineP->verbose, 0);
122 OPTENT3(0, "respectfillorder",
123 OPT_FLAG, NULL, &cmdlineP->respectfillorder, 0);
124 OPTENT3(0, "byrow",
125 OPT_FLAG, NULL, &cmdlineP->byrow, 0);
126 OPTENT3(0, "orientraw",
127 OPT_FLAG, NULL, &cmdlineP->orientraw, 0);
128 OPTENT3('h', "headerdump",
129 OPT_FLAG, NULL, &cmdlineP->headerdump, 0);
130 OPTENT3(0, "alphaout",
131 OPT_STRING, &cmdlineP->alphaFilename, &alphaSpec, 0);
132
133 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
134
135 if (argc - 1 == 0)
136 cmdlineP->inputFilename = strdup("-"); /* he wants stdin */
137 else if (argc - 1 == 1)
138 cmdlineP->inputFilename = strdup(argv[1]);
139 else
140 pm_error("Too many arguments. The only argument accepted "
141 "is the input file name");
142
143 if (alphaSpec) {
144 if (streq(cmdlineP->alphaFilename, "-"))
145 cmdlineP->alphaStdout = TRUE;
146 else
147 cmdlineP->alphaStdout = FALSE;
148 } else {
149 cmdlineP->alphaFilename = NULL;
150 cmdlineP->alphaStdout = FALSE;
151 }
152 }
153
154
155
156 static TIFF *
157 newTiffImageObject(const char * const inputFileName) {
158 /*----------------------------------------------------------------------------
159 Create a TIFF library object for accessing the TIFF input in file
160 named 'inputFileName'. If 'inputFileName' is "-", that means
161 Standard Input.
162 -----------------------------------------------------------------------------*/
163 const char * const tiffSourceName =
164 streq(inputFileName, "-") ? "Standard Input" : inputFileName;
165
166 TIFF * retval;
167
168 retval = TIFFFdOpen(fileno(pm_openr_seekable(inputFileName)),
169 tiffSourceName,
170 "r");
171
172 if (retval == NULL)
173 pm_error("Failed to access input file. The OS opened the file fine, "
174 "but the TIFF library's TIFFFdOpen rejected the open file.");
175
176 return retval;
177 }
178
179
180
181 static void
182 getBps(TIFF * const tif,
183 unsigned short * const bpsP) {
184
185 unsigned short tiffBps;
186 unsigned short bps;
187 int fldPresent;
188
189 fldPresent = TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &tiffBps);
190 bps = fldPresent ? tiffBps : 1;
191
192 if (bps < 1 || (bps > 8 && bps != 16 && bps != 32))
193 pm_error("This program can process Tiff images with only "
194 "1-8 or 16 or 32 bits per sample. The input Tiff image "
195 "has %hu bits per sample.", bps);
196 else
197 *bpsP = bps;
198 }
199
200
201
202 struct tiffDirInfo {
203 /* 'width' and 'height' are the dimensions of the raster matrix in
204 the TIFF stream -- what the TIFF spec calls the image. The
205 dimensions of the actual visual image represented may be the
206 reverse, because the raster can represent the visual image in
207 various orientations, as described by 'orientation'.
208 */
209 unsigned int width;
210 unsigned int height;
211 unsigned short bps;
212 unsigned short spp;
213 unsigned short photomet;
214 unsigned short planarconfig;
215 unsigned short fillorder;
216 unsigned short orientation;
217 };
218
219
220
221 static void
222 tiffToImageDim(unsigned int const tiffWidth,
223 unsigned int const tiffHeight,
224 unsigned short const orientation,
225 unsigned int * const imageColsP,
226 unsigned int * const imageRowsP) {
227 /*----------------------------------------------------------------------------
228 Determine the image dimensions (as *imageColsP and *imageRowsP) from the
229 width, height, and orientation of the TIFF raster ('tiffWidth',
230 'tiffHeight', and 'orientation', respectively.
231 -----------------------------------------------------------------------------*/
232 switch (orientation) {
233 case ORIENTATION_TOPLEFT:
234 case ORIENTATION_TOPRIGHT:
235 case ORIENTATION_BOTRIGHT:
236 case ORIENTATION_BOTLEFT:
237 *imageColsP = tiffWidth;
238 *imageRowsP = tiffHeight;
239 break;
240 case ORIENTATION_LEFTTOP:
241 case ORIENTATION_RIGHTTOP:
242 case ORIENTATION_RIGHTBOT:
243 case ORIENTATION_LEFTBOT:
244 *imageColsP = tiffHeight;
245 *imageRowsP = tiffWidth;
246 break;
247 default:
248 pm_error("Invalid value for orientation tag in TIFF directory: %u",
249 orientation);
250 }
251 }
252
253
254
255 static void
256 getTiffDimensions(TIFF * const tiffP,
257 unsigned int * const colsP,
258 unsigned int * const rowsP) {
259 /*----------------------------------------------------------------------------
260 Return the dimensions of the image represented by *tiffP. Not the
261 dimensions of the internal raster matrix -- the dimensions of the
262 actual visual image.
263 -----------------------------------------------------------------------------*/
264 int fldPresent;
265
266 unsigned int width, length;
267 unsigned short tiffOrientation;
268 unsigned short orientation;
269
270 fldPresent = TIFFGetField(tiffP, TIFFTAG_IMAGEWIDTH, &width);
271 if (!fldPresent)
272 pm_error("Input Tiff file is invalid. It has no IMAGEWIDTH tag.");
273 fldPresent = TIFFGetField(tiffP, TIFFTAG_IMAGELENGTH, &length);
274 if (!fldPresent)
275 pm_error("Input Tiff file is invalid. It has no IMAGELENGTH tag.");
276
277 fldPresent = TIFFGetField(tiffP, TIFFTAG_ORIENTATION, &tiffOrientation);
278 orientation = fldPresent ? tiffOrientation : ORIENTATION_TOPLEFT;
279
280 tiffToImageDim(width, length, orientation, colsP, rowsP);
281 }
282
283
284
285 static unsigned short
286 planarConfigFmTiff(TIFF * const tiffP) {
287
288 int fldPresent;
289 unsigned short retval;
290
291 fldPresent = TIFFGetField(tiffP, TIFFTAG_PLANARCONFIG, &retval);
292
293 if (!fldPresent)
294 pm_error("PLANARCONFIG tag is not in Tiff file, though it "
295 "has more than one sample per pixel. "
296 "TIFFGetField() of it failed. This means the input "
297 "is not valid Tiff.");
298
299 return retval;
300 }
301
302
303
304 static void
305 validatePlanarConfig(unsigned short const planarconfig,
306 unsigned short const photomet) {
307
308 switch (planarconfig) {
309 case PLANARCONFIG_CONTIG:
310 break;
311 case PLANARCONFIG_SEPARATE:
312 if (photomet != PHOTOMETRIC_RGB &&
313 photomet != PHOTOMETRIC_SEPARATED)
314 pm_error("This program can handle separate planes only "
315 "with RGB (PHOTOMETRIC tag = %u) or SEPARATED "
316 "(PHOTOMETRIC tag = %u) data. The input Tiff file "
317 "has PHOTOMETRIC tag = %hu.",
318 PHOTOMETRIC_RGB, PHOTOMETRIC_SEPARATED,
319 photomet);
320 break;
321 default:
322 pm_error("Unrecognized PLANARCONFIG tag value in Tiff input: %u",
323 planarconfig);
324 }
325 }
326
327
328
329 static unsigned short
330 orientationFmTiff(TIFF * const tiffP) {
331
332 unsigned short tiffOrientation;
333 int fldPresent;
334
335 fldPresent = TIFFGetField(tiffP, TIFFTAG_ORIENTATION, &tiffOrientation);
336
337 return fldPresent ? tiffOrientation : ORIENTATION_TOPLEFT;
338 }
339
340
341
342 static void
343 dumpHeader(const struct tiffDirInfo * const headerP) {
344
345 pm_message("%ux%ux%u raster matrix, oriented %u",
346 headerP->width, headerP->height,
347 headerP->bps * headerP->spp, headerP->orientation);
348 pm_message("%hu bits/sample, %hu samples/pixel",
349 headerP->bps, headerP->spp);
350 }
351
352
353
354 static void
355 readDirectory(TIFF * const tiffP,
356 bool const headerdump,
357 struct tiffDirInfo * const headerP) {
358 /*----------------------------------------------------------------------------
359 Read various values of TIFF tags from the TIFF directory, and
360 default them if not in there and make guesses where values are
361 invalid. Exit program with error message if required tags aren't
362 there or values are inconsistent or beyond our capabilities. If
363 'headerdump' is true, issue informational messages about what we
364 find.
365
366 The TIFF library is capable of returning invalid values (if the
367 input file contains invalid values). We generally return those
368 invalid values to our caller.
369 -----------------------------------------------------------------------------*/
370 int fldPresent;
371 unsigned short tiffSpp;
372
373 if (headerdump)
374 TIFFPrintDirectory(tiffP, stderr, TIFFPRINT_NONE);
375
376 getBps(tiffP, &headerP->bps);
377
378 fldPresent =
379 TIFFGetFieldDefaulted(tiffP, TIFFTAG_FILLORDER, &headerP->fillorder);
380 fldPresent = TIFFGetField(tiffP, TIFFTAG_SAMPLESPERPIXEL, &tiffSpp);
381 headerP->spp = fldPresent ? tiffSpp: 1;
382
383 fldPresent = TIFFGetField(tiffP, TIFFTAG_PHOTOMETRIC, &headerP->photomet);
384 if (!fldPresent)
385 pm_error("PHOTOMETRIC tag is not in Tiff file. "
386 "TIFFGetField() of it failed.\n"
387 "This means the input is not valid Tiff.");
388
389 if (headerP->spp > 1)
390 headerP->planarconfig = planarConfigFmTiff(tiffP);
391 else
392 headerP->planarconfig = PLANARCONFIG_CONTIG;
393
394 validatePlanarConfig(headerP->planarconfig, headerP->photomet);
395
396 fldPresent = TIFFGetField(tiffP, TIFFTAG_IMAGEWIDTH, &headerP->width);
397 if (!fldPresent)
398 pm_error("Input Tiff file is invalid. It has no IMAGEWIDTH tag.");
399 fldPresent = TIFFGetField(tiffP, TIFFTAG_IMAGELENGTH, &headerP->height);
400 if (!fldPresent)
401 pm_error("Input Tiff file is invalid. It has no IMAGELENGTH tag.");
402
403 headerP->orientation = orientationFmTiff(tiffP);
404
405 if (headerdump)
406 dumpHeader(headerP);
407 }
408
409
410
411 static void
412 readscanline(TIFF * const tif,
413 unsigned char * const scanbuf,
414 int const row,
415 int const plane,
416 unsigned int const cols,
417 unsigned short const bps,
418 unsigned short const spp,
419 unsigned short const fillorder,
420 unsigned int * const samplebuf) {
421 /*----------------------------------------------------------------------------
422 Read one scanline out of the Tiff input and store it into samplebuf[].
423 Unlike the scanline returned by the Tiff library function, samplebuf[]
424 is composed of one sample per array element, which makes it easier for
425 our caller to process.
426
427 scanbuf[] is a scratch array for our use, which is big enough to hold
428 a Tiff scanline.
429 -----------------------------------------------------------------------------*/
430 int rc;
431 unsigned int const bpsmask = (1 << bps) - 1;
432 /* A mask for taking the lowest 'bps' bits of a number */
433
434 /* The TIFFReadScanline man page doesn't tell the format of its
435 'buf' return value, but it is exactly the same format as the 'buf'
436 input to TIFFWriteScanline. The man page for that doesn't say
437 anything either, but the source code for Pamtotiff contains a
438 specification.
439 */
440
441 rc = TIFFReadScanline(tif, scanbuf, row, plane);
442
443 if (rc < 0)
444 pm_error( "Unable to read row %d, plane %d of input Tiff image. "
445 "TIFFReadScanline() failed.",
446 row, plane);
447 else if (bps == 8) {
448 unsigned int sample;
449 for (sample = 0; sample < cols * spp; ++sample)
450 samplebuf[sample] = scanbuf[sample];
451 } else if (bps < 8) {
452 /* Note that in this format, samples do not span bytes. Rather,
453 each byte may have don't-care bits in the right-end positions.
454 At least that's how I infer the format from reading pnmtotiff.c
455 -Bryan 00.11.18
456 */
457 unsigned int sample;
458 unsigned int bitsleft;
459 unsigned char * inP;
460
461 for (sample = 0, bitsleft = 8, inP = scanbuf;
462 sample < cols * spp;
463 ++sample) {
464 if (bitsleft == 0) {
465 ++inP;
466 bitsleft = 8;
467 }
468 switch (fillorder) {
469 case FILLORDER_MSB2LSB:
470 samplebuf[sample] = (*inP >> (bitsleft-bps)) & bpsmask;
471 break;
472 case FILLORDER_LSB2MSB:
473 samplebuf[sample] = (*inP >> (8-bitsleft)) & bpsmask;
474 break;
475 default:
476 pm_error("Internal error: invalid value for fillorder: %u",
477 fillorder);
478 }
479 assert(bitsleft >= bps);
480 bitsleft -= bps;
481 if (bitsleft < bps)
482 /* Don't count dregs at end of byte */
483 bitsleft = 0;
484 }
485 } else if (bps == 16) {
486 /* Before Netpbm 9.17, this program assumed that scanbuf[]
487 contained an array of bytes as read from the Tiff file. In
488 fact, in this bps == 16 case, it's an array of "shorts",
489 each stored in whatever format this platform uses (which is
490 none of our concern). The pre-9.17 code also presumed that
491 the TIFF "FILLORDER" tag determined the order in which the
492 bytes of each sample appear in a TIFF file, which is
493 contrary to the TIFF spec.
494 */
495 const uint16_t * const scanbuf16 = (const uint16_t *) scanbuf;
496 unsigned int sample;
497
498 for (sample = 0; sample < cols*spp; ++sample)
499 samplebuf[sample] = scanbuf16[sample];
500 } else if (bps == 32) {
501 const uint32_t * const scanbuf32 = (const uint32_t *) scanbuf;
502 unsigned int sample;
503
504 for (sample = 0; sample < cols * spp; ++sample)
505 samplebuf[sample] = scanbuf32[sample];
506 } else
507 pm_error("Internal error: invalid bits per sample passed to "
508 "readscanline()");
509 }
510
511
512
513 static void
514 pick_cmyk_pixel(unsigned int const samplebuf[],
515 int const sampleCursor,
516 xelval * const redP,
517 xelval * const bluP,
518 xelval * const grnP) {
519
520 /* Note that the TIFF spec does not say which of the 4 samples is
521 which, but common sense says they're in order C,M,Y,K. Before
522 Netpbm 10.21 (March 2004), we assumed C,Y,M,K for some reason.
523 But combined with a compensating error in the CMYK->RGB
524 calculation, it had the same effect as C,M,Y,K.
525 */
526 unsigned int const c = samplebuf[sampleCursor + 0];
527 unsigned int const m = samplebuf[sampleCursor + 1];
528 unsigned int const y = samplebuf[sampleCursor + 2];
529 unsigned int const k = samplebuf[sampleCursor + 3];
530
531 /* The CMYK->RGB formula used by TIFFRGBAImageGet() in the TIFF
532 library is the following, (with some apparent confusion with
533 the names of the yellow and magenta pigments being reversed).
534
535 R = (1-K)*(1-C) (with C,Y,M,K normalized to 0..1)
536 G = (1-K)*(1-M)
537 B = (1-K)*(1-Y)
538
539 We used that too before Netpbm 10.21 (March 2004).
540
541 Now we use the inverse of what Pnmtotiffcmyk has always used, which
542 makes sense as follows: A microliter of black ink is simply a
543 substitute for a microliter each of cyan, magenta, and yellow ink.
544 Yellow ink removes blue light from what the white paper reflects.
545 */
546
547 *redP = 255 - MIN(255, c + k);
548 *grnP = 255 - MIN(255, m + k);
549 *bluP = 255 - MIN(255, y + k);
550 }
551
552
553
554 static void
555 computeFillorder(unsigned short const fillorderTag,
556 unsigned short * const fillorderP,
557 bool const respectfillorder) {
558
559 if (respectfillorder) {
560 if (fillorderTag != FILLORDER_MSB2LSB &&
561 fillorderTag != FILLORDER_LSB2MSB)
562 pm_error("Invalid value in Tiff input for the FILLORDER tag: %u. "
563 "Valid values are %u and %u. Try omitting the "
564 "-respectfillorder option.",
565 fillorderTag, FILLORDER_MSB2LSB, FILLORDER_LSB2MSB);
566 else
567 *fillorderP = fillorderTag;
568 } else {
569 *fillorderP = FILLORDER_MSB2LSB;
570 if (fillorderTag != *fillorderP)
571 pm_message("Warning: overriding FILLORDER tag in the tiff input "
572 "and assuming msb-to-lsb. Consider the "
573 "-respectfillorder option.");
574 }
575 }
576
577
578
579 static void
580 analyzeImageType(TIFF * const tiffP,
581 unsigned short const bps,
582 unsigned short const spp,
583 unsigned short const photomet,
584 xelval * const maxvalP,
585 int * const formatP,
586 xel * const colormap,
587 bool const headerdump,
588 struct CmdlineInfo const cmdline) {
589 /*----------------------------------------------------------------------------
590 Determine from the TIFF header in *tif certain properties of the image
591 as well as the proper format of PNM image for the conversion.
592
593 *formatP and *maxvalP are the basic PNM parameters.
594 -----------------------------------------------------------------------------*/
595 switch (photomet) {
596 case PHOTOMETRIC_MINISBLACK:
597 case PHOTOMETRIC_MINISWHITE:
598 if (spp != 1)
599 pm_error("This grayscale image has %d samples per pixel. "
600 "We understand only 1.", spp);
601
602 *formatP = bps == 1 ? PBM_TYPE : PGM_TYPE;
603
604 *maxvalP = pm_bitstomaxval(MIN(bps, 16));
605
606 if (headerdump)
607 pm_message("grayscale image, (min=%s) output maxval %u ",
608 photomet == PHOTOMETRIC_MINISBLACK ?
609 "black" : "white",
610 *maxvalP
611 );
612 break;
613
614 case PHOTOMETRIC_PALETTE: {
615 int fldPresent;
616 int i;
617 int numcolors;
618 unsigned short* redcolormap;
619 unsigned short* greencolormap;
620 unsigned short* bluecolormap;
621
622 if (headerdump)
623 pm_message("colormapped");
624
625 if (spp != 1)
626 pm_error("This paletted image has %d samples per pixel. "
627 "We understand only 1.", spp);
628
629 fldPresent = TIFFGetField(
630 tiffP, TIFFTAG_COLORMAP,
631 &redcolormap, &greencolormap, &bluecolormap);
632
633 if (!fldPresent)
634 pm_error("error getting colormaps");
635
636 numcolors = 1 << bps;
637 if (numcolors > MAXCOLORS)
638 pm_error("too many colors");
639
640 *formatP = PPM_TYPE;
641
642 *maxvalP = PNM_MAXMAXVAL;
643
644 for (i = 0; i < numcolors; ++i) {
645 xelval r, g, b;
646 r = (long) redcolormap[i] * PNM_MAXMAXVAL / 65535L;
647 g = (long) greencolormap[i] * PNM_MAXMAXVAL / 65535L;
648 b = (long) bluecolormap[i] * PNM_MAXMAXVAL / 65535L;
649 PPM_ASSIGN(colormap[i], r, g, b);
650 }
651 }
652 break;
653
654 case PHOTOMETRIC_SEPARATED: {
655 unsigned short inkset;
656 int fldPresent;
657
658 if (headerdump)
659 pm_message("color separation");
660
661 fldPresent = TIFFGetField(tiffP, TIFFTAG_INKNAMES, &inkset);
662 if (fldPresent && inkset != INKSET_CMYK)
663 pm_error("This color separation file uses an inkset (%d) "
664 "we can't handle. We handle only CMYK.", inkset);
665 if (spp != 4)
666 pm_error("This CMYK color separation file is %d samples per "
667 "pixel. "
668 "We need 4 samples, though: C, M, Y, and K. ",
669 spp);
670
671 *formatP = PPM_TYPE;
672
673 *maxvalP = (1 << bps) - 1;
674 }
675 break;
676
677 case PHOTOMETRIC_RGB:
678 if (headerdump)
679 pm_message("RGB truecolor");
680
681 if (spp != 3 && spp != 4)
682 pm_error("This RGB image has %d samples per pixel. "
683 "We understand only 3 or 4.", spp);
684
685 *formatP = PPM_TYPE;
686
687 *maxvalP = (1 << bps) - 1;
688 break;
689
690 case PHOTOMETRIC_MASK:
691 pm_error("don't know how to handle PHOTOMETRIC_MASK");
692
693 case PHOTOMETRIC_DEPTH:
694 pm_error("don't know how to handle PHOTOMETRIC_DEPTH");
695
696 case PHOTOMETRIC_YCBCR:
697 pm_error("don't know how to handle PHOTOMETRIC_YCBCR");
698
699 case PHOTOMETRIC_CIELAB:
700 pm_error("don't know how to handle PHOTOMETRIC_CIELAB");
701
702 case PHOTOMETRIC_LOGL:
703 pm_error("don't know how to handle PHOTOMETRIC_LOGL");
704
705 case PHOTOMETRIC_LOGLUV:
706 pm_error("don't know how to handle PHOTOMETRIC_LOGLUV");
707
708 default:
709 pm_error("unknown photometric: %d", photomet);
710 }
711 if (*maxvalP > PNM_OVERALLMAXVAL)
712 pm_error("bits/sample (%u) in the input image is too large.", bps);
713 }
714
715
716
717 typedef struct {
718 FILE * imageoutFileP;
719 /* The stream to which we write the PNM image. Null for none. */
720 FILE * alphaFileP;
721 /* The stream to which we write the alpha channel. Null for none. */
722 unsigned int inCols;
723 /* Width of each row that gets passed to this object */
724 unsigned int inRows;
725 /* Number of rows that get passed to this object */
726 unsigned int outCols;
727 /* Width of each row this object writes out to the file */
728 unsigned int outRows;
729 /* Number of rows this object writes out */
730 xelval maxval;
731 /* Maxval of the output image */
732 int format;
733 /* Format of the output image */
734 gray alphaMaxval;
735 /* Maxval of the alpha channel */
736 bool flipping;
737 /* We're passing rows through a Pamflip process, rather than writing
738 them directly to *imageoutFileP, *alphaFileP.
739 */
740 FILE * imagePipeP;
741 /* Stream hooked up to pipe that goes to a Pamflip process.
742 Meaningful only when 'flipping' is true.
743 */
744 FILE * alphaPipeP;
745 /* Stream hooked up to pipe that goes to a Pamflip process.
746 Meaningful only when 'flipping' is true.
747 */
748 pid_t imageFlipPid;
749 /* Process ID of the Pamflip process.
750 Meaningful only when 'flipping' is true.
751 */
752 pid_t alphaFlipPid;
753 /* Process ID of the Pamflip process.
754 Meaningful only when 'flipping' is true.
755 */
756 } pnmOut;
757
758
759
760 static const char *
761 xformNeeded(unsigned short const tiffOrientation) {
762 /*----------------------------------------------------------------------------
763 Return the value of the Pamflip -xform option that causes Pamflip
764 to change a raster from orientation 'tiffOrientation' to Row 0 top,
765 Column 0 left.
766 -----------------------------------------------------------------------------*/
767 switch (tiffOrientation) {
768 case ORIENTATION_TOPLEFT: return "";
769 case ORIENTATION_TOPRIGHT: return "leftright";
770 case ORIENTATION_BOTRIGHT: return "topbottom,leftright";
771 case ORIENTATION_BOTLEFT: return "topbottom";
772 case ORIENTATION_LEFTTOP: return "transpose";
773 case ORIENTATION_RIGHTTOP: return "transpose,leftright";
774 case ORIENTATION_RIGHTBOT: return "transpose,topbottom,leftright";
775 case ORIENTATION_LEFTBOT: return "transpose,topbottom";
776 default:
777 pm_error("Invalid value for orientation tag in TIFF directory: %u",
778 tiffOrientation);
779 return "";
780 }
781 }
782
783
784
785 /* File descriptors array indices for use with pipe() */
786 #define PIPE_READ 0
787 #define PIPE_WRITE 1
788
789 static void
790 spawnWithInputPipe(const char * const shellCmd,
791 FILE ** const pipePP,
792 pid_t * const pidP,
793 const char ** const errorP) {
794
795 int fd[2];
796 int rc;
797
798 rc = pm_pipe(fd);
799
800 if (rc != 0)
801 pm_asprintf(errorP, "Failed to create pipe for process input. "
802 "Errno=%d (%s)", errno, strerror(errno));
803 else {
804 int iAmParent;
805 pid_t childPid;
806
807 pm_fork(&iAmParent, &childPid, errorP);
808
809 if (!*errorP) {
810 if (iAmParent) {
811 close(fd[PIPE_READ]);
812
813 *pidP = childPid;
814 *pipePP = fdopen(fd[PIPE_WRITE], "w");
815
816 if (*pipePP == NULL)
817 pm_asprintf(errorP,"Unable to create stream from pipe. "
818 "fdopen() fails with errno=%d (%s)",
819 errno, strerror(errno));
820 else
821 *errorP = NULL;
822 } else {
823 int terminationStatus;
824 close(fd[PIPE_WRITE]);
825 close(STDIN_FILENO);
826 dup2(fd[PIPE_READ], STDIN_FILENO);
827
828 terminationStatus = system(shellCmd);
829
830 if (WIFSIGNALED(terminationStatus))
831 pm_error("Shell process was killed "
832 "by a Class %u signal.",
833 WTERMSIG(terminationStatus));
834 else if (!WIFEXITED(terminationStatus))
835 pm_error("Shell process died, but its termination status "
836 "0x%x doesn't make sense", terminationStatus);
837 else
838 exit(WEXITSTATUS(terminationStatus));
839 }
840 }
841 }
842 }
843
844
845
846 static void
847 createFlipProcess(FILE * const outFileP,
848 unsigned short const orientation,
849 bool const verbose,
850 FILE ** const inPipePP,
851 pid_t * const pidP) {
852 /*----------------------------------------------------------------------------
853 Create a process that runs the program Pamflip and writes its output
854 to *imageoutFileP.
855
856 The process takes its input from a pipe that we create. We return as
857 *inPipePP a file stream connected to the other end of that pipe.
858
859 I.e. Caller will write a Netpbm file stream to **inPipePP and a flipped
860 version of it will go to *outFileP.
861
862 The flipping it does turns the input from orientation 'orientation'
863 to Netpbm orientation, i.e. raster row 0 top, raster column 0 left,
864 where the raster stream is divided into rows, with row 0 being first
865 in the stream, and column 0 being first within each row.
866
867 Caller must close *inPipePP when he is done.
868 -----------------------------------------------------------------------------*/
869 const char * pamflipCmd;
870 const char * error;
871
872 /* Hooking up the process to the output stream is kind of tricky
873 because the stream (FILE *) is an entity local to this process.
874 We just assume that nothing in this process actually touches
875 the stream so that having the process write to the underlying
876 file descriptor is equivalent to writing to the stream.
877 */
878
879 pm_asprintf(&pamflipCmd, "pamflip -xform=%s >&%u",
880 xformNeeded(orientation), fileno(outFileP));
881
882 if (verbose)
883 pm_message("Reorienting raster with shell command '%s'", pamflipCmd);
884
885 spawnWithInputPipe(pamflipCmd, inPipePP, pidP, &error);
886
887 if (error) {
888 pm_error("Shell command '%s', to reorient the TIFF "
889 "raster, failed. %s. To work around this, you can use "
890 "the -orientraw option.", pamflipCmd, error);
891
892 pm_strfree(error);
893 }
894 }
895
896
897
898 static void
899 setupFlipper(pnmOut * const pnmOutP,
900 unsigned short const orientation,
901 bool const flipIfNeeded,
902 bool const orientraw,
903 bool const verbose,
904 bool * const flipOkP,
905 bool * const noflipOkP) {
906 /*----------------------------------------------------------------------------
907 Set up the Pamflip processes to flip the raster, where needed.
908
909 Whether we need a Pamflip process is a complex decision. For
910 reasons of efficiency and robustness, we don't want one unless
911 flipping is actually required. Flipping is not required if the
912 TIFF image is already oriented like a PNM. It also isn't required
913 if the user explicitly asks for raw orientation. Finally, it's not
914 required when the user is using the TIFF library whole-image
915 conversion services, because they do the flipping and thus the
916 'pnmOut' object will see properly oriented pixels as input.
917
918 'flipIfNeeded' says to set up the flipping pipe if 'orientation'
919 indicates something other than standard PNM orientation.
920
921 'orientation' is the orientation of the TIFF raster.
922
923 'orientraw' says the final output should be in the same
924 orientation, 'orientation', not the proper PNM orientation.
925
926 *flipOkP means that as we set up the pnmOut object,
927 it is OK if Caller flips the raster on his own. *noflipOk means
928 is is OK if Caller does not flip the raster on his own. Note
929 that they are both true if the raster is already in the PNM
930 orientation, because then flipping is idempotent.
931 -----------------------------------------------------------------------------*/
932
933 if (orientation == ORIENTATION_TOPLEFT) {
934 /* Ah, the easy case. Flipping and not flipping are identical,
935 so none of the other parameters matter. Just write directly
936 to the output file and let Caller flip or not flip as he
937 wishes.
938 */
939 pnmOutP->flipping = FALSE;
940 *flipOkP = TRUE;
941 *noflipOkP = TRUE;
942 } else {
943 if (orientraw) {
944 /* Raster is not to be flipped, so go directly to file,
945 and tell Caller not to flip it either.
946 */
947 pnmOutP->flipping = FALSE;
948 *flipOkP = FALSE;
949 *noflipOkP = TRUE;
950 } else {
951 if (flipIfNeeded) {
952 if (verbose)
953 pm_message("Transforming raster with Pamflip");
954
955 if (pnmOutP->alphaFileP)
956 createFlipProcess(pnmOutP->alphaFileP, orientation,
957 verbose,
958 &pnmOutP->alphaPipeP,
959 &pnmOutP->alphaFlipPid);
960 if (pnmOutP->imageoutFileP)
961 createFlipProcess(pnmOutP->imageoutFileP, orientation,
962 verbose,
963 &pnmOutP->imagePipeP,
964 &pnmOutP->imageFlipPid);
965
966 /* The stream will flip it, so Caller must not: */
967 pnmOutP->flipping = TRUE;
968 *flipOkP = FALSE;
969 *noflipOkP = TRUE;
970 } else {
971 /* It needs flipping, but Caller doesn't want us to do it.
972 So Caller must do it:
973 */
974 pnmOutP->flipping = FALSE;
975 *flipOkP = TRUE;
976 *noflipOkP = FALSE;
977 }
978 }
979 }
980 }
981
982
983
984 static void
985 computeOutputDimensions(unsigned int const tiffCols,
986 unsigned int const tiffRows,
987 unsigned short const orientation,
988 bool const orientraw,
989 unsigned int * const colsP,
990 unsigned int * const rowsP,
991 bool const verbose) {
992 /*----------------------------------------------------------------------------
993 Compute the dimensions of the image. We're talking about the
994 actual image, not what the TIFF spec calls the image. What the
995 TIFF spec calls the image is matrix of pixels within the TIFF file.
996 That matrix can represent the actual image in various ways.
997 E.g. the first row of the matrix might be the right edge of the
998 image.
999
1000 'tiffCols' and 'tiffRows' are the images of the TIFF matrix and
1001 'orientation' is the orientation of that matrix.
1002
1003 'orientraw' says we want to output the matrix in its natural
1004 orientation, not the true image.
1005 -----------------------------------------------------------------------------*/
1006 if (orientraw) {
1007 *colsP = tiffCols;
1008 *rowsP = tiffRows;
1009 } else
1010 tiffToImageDim(tiffCols, tiffRows, orientation, colsP, rowsP);
1011
1012 if (verbose)
1013 pm_message("Generating %uw x %uh PNM image", *colsP, *rowsP);
1014 }
1015
1016
1017
1018 static void
1019 pnmOut_init(FILE * const imageoutFileP,
1020 FILE * const alphaFileP,
1021 unsigned int const cols,
1022 unsigned int const rows,
1023 unsigned short const orientation,
1024 xelval const maxval,
1025 int const format,
1026 gray const alphaMaxval,
1027 bool const flipIfNeeded,
1028 bool const orientraw,
1029 bool const verbose,
1030 bool * const flipOkP,
1031 bool * const noflipOkP,
1032 pnmOut * const pnmOutP) {
1033 /*----------------------------------------------------------------------------
1034 'cols' and 'rows' are the dimensions of the raster matrix which is
1035 oriented according to 'orientation' with respect to the image.
1036
1037 If the user flips the data before giving it to the pnmOut object,
1038 pnmOut may see the inverse dimensions; if the pnmOut object flips the
1039 data, pnmOut get 'cols' x 'rows' data, but its output file may be
1040 'rows x cols'.
1041
1042 Because we must set up the pnmOut object either to receive flipped or not
1043 flipped input, we have *flipOkP and *noflipOkP outputs that tell Caller
1044 whether he has to flip or not. Note that Caller also influences which way
1045 we set up pnmOut, with his 'flipIfNeeded' argument. In the unique case
1046 that the TIFF matrix is already oriented the way the output PNM file needs
1047 to be, flipping is idempotent, so both *flipOkP and *noflipOkP are true.
1048 -----------------------------------------------------------------------------*/
1049 pnmOutP->imageoutFileP = imageoutFileP;
1050 pnmOutP->alphaFileP = alphaFileP;
1051 pnmOutP->maxval = maxval;
1052 pnmOutP->format = format;
1053 pnmOutP->alphaMaxval = alphaMaxval;
1054
1055 setupFlipper(pnmOutP, orientation, flipIfNeeded, orientraw, verbose,
1056 flipOkP, noflipOkP);
1057
1058 computeOutputDimensions(cols, rows, orientation, orientraw,
1059 &pnmOutP->outCols, &pnmOutP->outRows, verbose);
1060
1061 if (pnmOutP->flipping) {
1062 pnmOutP->inCols = cols; /* Caller won't flip */
1063 pnmOutP->inRows = rows;
1064 } else {
1065 pnmOutP->inCols = pnmOutP->outCols; /* Caller will flip */
1066 pnmOutP->inRows = pnmOutP->outRows;
1067 }
1068 if (pnmOutP->flipping) {
1069 if (pnmOutP->imagePipeP != NULL)
1070 pnm_writepnminit(pnmOutP->imagePipeP,
1071 pnmOutP->inCols, pnmOutP->inRows,
1072 pnmOutP->maxval, pnmOutP->format, 0);
1073 if (pnmOutP->alphaPipeP != NULL)
1074 pgm_writepgminit(pnmOutP->alphaPipeP,
1075 pnmOutP->inCols, pnmOutP->inRows,
1076 pnmOutP->alphaMaxval, 0);
1077 } else {
1078 if (imageoutFileP != NULL)
1079 pnm_writepnminit(pnmOutP->imageoutFileP,
1080 pnmOutP->outCols, pnmOutP->outRows,
1081 pnmOutP->maxval, pnmOutP->format, 0);
1082 if (alphaFileP != NULL)
1083 pgm_writepgminit(pnmOutP->alphaFileP,
1084 pnmOutP->outCols, pnmOutP->outRows,
1085 pnmOutP->alphaMaxval, 0);
1086 }
1087 }
1088
1089
1090
1091 static void
1092 pnmOut_term(pnmOut * const pnmOutP,
1093 bool const verbose) {
1094
1095 if (pnmOutP->flipping) {
1096 /* Closing the pipes also causes the Pamflip processes to terminate
1097 and they consequently flush their output to pnmOutP->imageoutFileP
1098 and pnmOutP->alphaFileP and close those file descriptors.
1099
1100 We wait for the processes to exit before returning so that we
1101 know everything is flushed, so the invoker of Tifftopnm is free
1102 to use its output.
1103 */
1104 if (verbose)
1105 pm_message("Flushing data through Pamflip process, "
1106 "waiting for Pamflip to terminate");
1107
1108 if (pnmOutP->imagePipeP) {
1109 fclose(pnmOutP->imagePipeP);
1110 pm_waitpidSimple(pnmOutP->imageFlipPid);
1111 }
1112 if (pnmOutP->alphaPipeP) {
1113 fclose(pnmOutP->alphaPipeP);
1114 pm_waitpidSimple(pnmOutP->alphaFlipPid);
1115 }
1116 } else {
1117 if (pnmOutP->imageoutFileP)
1118 fflush(pnmOutP->imageoutFileP);
1119 if (pnmOutP->alphaFileP)
1120 fflush(pnmOutP->alphaFileP);
1121 }
1122 }
1123
1124
1125
1126 static void
1127 pnmOut_writeRow(pnmOut * const pnmOutP,
1128 unsigned int const cols,
1129 const xel * const imageRow,
1130 const gray * const alphaRow) {
1131
1132 assert(cols == pnmOutP->inCols);
1133
1134 if (pnmOutP->flipping) {
1135 if (pnmOutP->imagePipeP != NULL)
1136 pnm_writepnmrow(pnmOutP->imagePipeP, (xel *)imageRow,
1137 pnmOutP->inCols, pnmOutP->maxval,
1138 pnmOutP->format, 0);
1139 if (pnmOutP->alphaPipeP != NULL)
1140 pgm_writepgmrow(pnmOutP->alphaPipeP, alphaRow,
1141 pnmOutP->inCols, pnmOutP->alphaMaxval, 0);
1142 } else {
1143 if (pnmOutP->imageoutFileP != NULL)
1144 pnm_writepnmrow(pnmOutP->imageoutFileP, (xel *)imageRow,
1145 pnmOutP->outCols, pnmOutP->maxval,
1146 pnmOutP->format, 0);
1147 if (pnmOutP->alphaFileP != NULL)
1148 pgm_writepgmrow(pnmOutP->alphaFileP, alphaRow,
1149 pnmOutP->outCols, pnmOutP->alphaMaxval, 0);
1150 }
1151 }
1152
1153
1154
1155 static void
1156 convertRow(unsigned int const samplebuf[],
1157 xel * const xelrow,
1158 gray * const alpharow,
1159 int const cols,
1160 xelval const maxval,
1161 unsigned short const photomet,
1162 unsigned short const spp,
1163 xel const colormap[]) {
1164 /*----------------------------------------------------------------------------
1165 Assuming samplebuf[] is an array of raster values as returned by the Tiff
1166 library, convert it to a libnetpbm row in xelrow[] and alpharow[].
1167 -----------------------------------------------------------------------------*/
1168 switch (photomet) {
1169 case PHOTOMETRIC_MINISBLACK: {
1170 int col;
1171 for (col = 0; col < cols; ++col) {
1172 PNM_ASSIGN1(xelrow[col], samplebuf[col]);
1173 alpharow[col] = 0;
1174 }
1175 }
1176 break;
1177
1178 case PHOTOMETRIC_MINISWHITE: {
1179 int col;
1180 for (col = 0; col < cols; ++col) {
1181 PNM_ASSIGN1(xelrow[col], maxval - samplebuf[col]);
1182 alpharow[col] = 0;
1183 }
1184 }
1185 break;
1186
1187 case PHOTOMETRIC_PALETTE: {
1188 int col;
1189 for ( col = 0; col < cols; ++col ) {
1190 /* We know the following array index is in bounds because
1191 we filled samplebuf with samples of 'bps' bits each and
1192 we verified that the largest number that fits in 'bps'
1193 bits is less than MAXCOLORS, the dimension of the array.
1194 */
1195 xelrow[col] = colormap[samplebuf[col]];
1196 alpharow[col] = 0;
1197 }
1198 }
1199 break;
1200
1201 case PHOTOMETRIC_SEPARATED: {
1202 int col, sample;
1203 for (col = 0, sample = 0; col < cols; ++col, sample+=spp) {
1204 xelval r, g, b;
1205 pick_cmyk_pixel(samplebuf, sample, &r, &b, &g);
1206
1207 PPM_ASSIGN(xelrow[col], r, g, b);
1208 alpharow[col] = 0;
1209 }
1210 }
1211 break;
1212
1213 case PHOTOMETRIC_RGB: {
1214 int col, sample;
1215 for (col = 0, sample = 0; col < cols; ++col, sample+=spp) {
1216 PPM_ASSIGN(xelrow[col], samplebuf[sample+0],
1217 samplebuf[sample+1], samplebuf[sample+2]);
1218 if (spp >= 4)
1219 alpharow[col] = samplebuf[sample+3];
1220 else
1221 alpharow[col] = 0;
1222 }
1223 break;
1224 }
1225 default:
1226 pm_error("internal error: unknown photometric in the picking "
1227 "routine: %d", photomet);
1228 }
1229 }
1230
1231
1232
1233 static void
1234 scale32to16(unsigned int * const samplebuf,
1235 unsigned int const cols,
1236 unsigned int const spp) {
1237 /*----------------------------------------------------------------------------
1238 Convert every sample in samplebuf[] to something that can be expressed
1239 in 16 bits, assuming it takes 32 bits now.
1240 -----------------------------------------------------------------------------*/
1241 unsigned int i;
1242 for (i = 0; i < cols * spp; ++i)
1243 samplebuf[i] >>= 16;
1244 }
1245
1246
1247
1248 static void
1249 convertMultiPlaneRow(TIFF * const tif,
1250 xel * const xelrow,
1251 gray * const alpharow,
1252 int const cols,
1253 xelval const maxval,
1254 int const row,
1255 unsigned short const photomet,
1256 unsigned short const bps,
1257 unsigned short const spp,
1258 unsigned short const fillorder,
1259 unsigned char * const scanbuf,
1260 unsigned int * const samplebuf) {
1261
1262 /* The input is in separate planes, so we need to read one
1263 scanline for the reds, another for the greens, then another
1264 for the blues.
1265 */
1266
1267 if (photomet != PHOTOMETRIC_RGB)
1268 pm_error("This is a multiple-plane file, but is not an RGB "
1269 "file. This program does not know how to handle that.");
1270 else {
1271 unsigned int col;
1272
1273 /* First, clear the buffer so we can add red, green,
1274 and blue one at a time.
1275 */
1276 for (col = 0; col < cols; ++col)
1277 PPM_ASSIGN(xelrow[col], 0, 0, 0);
1278
1279 /* Read the reds */
1280 readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder,
1281 samplebuf);
1282 if (bps == 32)
1283 scale32to16(samplebuf, cols, spp);
1284 for (col = 0; col < cols; ++col)
1285 PPM_PUTR(xelrow[col], samplebuf[col]);
1286
1287 /* Next the greens */
1288 readscanline(tif, scanbuf, row, 1, cols, bps, spp, fillorder,
1289 samplebuf);
1290 if (bps == 32)
1291 scale32to16(samplebuf, cols, spp);
1292 for (col = 0; col < cols; ++col)
1293 PPM_PUTG( xelrow[col], samplebuf[col] );
1294
1295 /* And finally the blues */
1296 readscanline(tif, scanbuf, row, 2, cols, bps, spp, fillorder,
1297 samplebuf);
1298 if (bps == 32)
1299 scale32to16(samplebuf, cols, spp);
1300 for (col = 0; col < cols; ++col)
1301 PPM_PUTB(xelrow[col], samplebuf[col]);
1302
1303 /* Could there be an alpha plane? (We assume no. But if so,
1304 here is where to read it)
1305 */
1306 for (col = 0; col < cols; ++col)
1307 alpharow[col] = 0;
1308 }
1309 }
1310
1311
1312
1313 static void
1314 convertRasterByRows(pnmOut * const pnmOutP,
1315 unsigned int const cols,
1316 unsigned int const rows,
1317 xelval const maxval,
1318 TIFF * const tif,
1319 unsigned short const photomet,
1320 unsigned short const planarconfig,
1321 unsigned short const bps,
1322 unsigned short const spp,
1323 unsigned short const fillorder,
1324 xel const colormap[],
1325 bool const verbose) {
1326 /*----------------------------------------------------------------------------
1327 With the TIFF header all processed (and relevant information from it in
1328 our arguments), write out the TIFF raster to the Netpbm output files
1329 as described by *pnmOutP.
1330
1331 Do this one row at a time, employing the TIFF library's
1332 TIFFReadScanline.
1333 -----------------------------------------------------------------------------*/
1334 unsigned char * scanbuf;
1335 /* Buffer for a raster line in the format returned by TIFF library's
1336 TIFFReadScanline
1337 */
1338 unsigned int * samplebuf;
1339 /* Same info as 'scanbuf' above, but with each raster column (sample)
1340 represented as single array element, so it's easy to work with.
1341 */
1342 xel * xelrow;
1343 /* The ppm-format row of the image row we are currently converting */
1344 gray * alpharow;
1345 /* The pgm-format row representing the alpha values for the image
1346 row we are currently converting.
1347 */
1348
1349 unsigned int row;
1350
1351 if (verbose)
1352 pm_message("Converting row by row ...");
1353
1354 MALLOCARRAY(scanbuf, TIFFScanlineSize(tif));
1355 if (scanbuf == NULL)
1356 pm_error("can't allocate memory for scanline buffer");
1357
1358 if (UINT_MAX/cols < spp)
1359 pm_error("Image is too wide/deep (%u x %u) for computations",
1360 cols, spp);
1361 MALLOCARRAY(samplebuf, cols * spp);
1362 if (samplebuf == NULL)
1363 pm_error("can't allocate memory for row buffer");
1364
1365 xelrow = pnm_allocrow(cols);
1366 alpharow = pgm_allocrow(cols);
1367
1368 for (row = 0; row < rows; ++row) {
1369 /* Read one row of samples into samplebuf[] */
1370
1371 if (planarconfig == PLANARCONFIG_CONTIG) {
1372 readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder,
1373 samplebuf);
1374 if (bps == 32)
1375 scale32to16(samplebuf, cols, spp);
1376 convertRow(samplebuf, xelrow, alpharow, cols, maxval,
1377 photomet, spp, colormap);
1378 } else
1379 convertMultiPlaneRow(tif, xelrow, alpharow, cols, maxval, row,
1380 photomet, bps, spp, fillorder,
1381 scanbuf, samplebuf);
1382
1383 pnmOut_writeRow(pnmOutP, cols, xelrow, alpharow);
1384 }
1385 pgm_freerow(alpharow);
1386 pnm_freerow(xelrow);
1387
1388 free(samplebuf);
1389 free(scanbuf);
1390 }
1391
1392
1393
1394 static void
1395 warnBrokenTiffLibrary(TIFF * const tiffP) {
1396
1397 /* TIFF library bug:
1398
1399 In every version of the TIFF library we've seen, TIFFRGBAImageGet()
1400 fails when the raster orientation (per the TIFF_ORIENTATION tag)
1401 requires a transposition, e.g. ORIENTATION_LEFTBOT. It simply omits
1402 the transposition part, so e.g. it treats ORIENTATION_LEFTBOT as
1403 ORIENTATION_BOTLEFT. And because we provide a raster buffer dimensioned
1404 for the properly transposed image, the result is somewhat of a mess.
1405
1406 We have found no documentation of the TIFF library that suggests
1407 this behavior is as designed, so it's probably not a good idea to
1408 work around it; it might be fixed somewhere.
1409
1410 The user can of course work around just by using -byrow and therefore
1411 not using TIFFRGBAImageGet().
1412
1413 There is some evidence of an interface in the TIFF library that
1414 lets you request that TIFFRGBAImageGet() produce a raster in the
1415 same orientation as the one in the TIFF image.
1416 (tiff.req_orientation). We could conceivably use that and then do
1417 a Pamflip to get the proper orientation, but that somewhat defeats
1418 the philosophy of using TIFFRGBAImageGet(), so I would like to wait
1419 until there's a good practical reason to do it.
1420 */
1421
1422 unsigned short tiffOrientation;
1423 int fldPresent;
1424 fldPresent = TIFFGetField(tiffP, TIFFTAG_ORIENTATION, &tiffOrientation);
1425 if (fldPresent) {
1426 switch (tiffOrientation) {
1427 case ORIENTATION_LEFTTOP:
1428 case ORIENTATION_RIGHTTOP:
1429 case ORIENTATION_RIGHTBOT:
1430 case ORIENTATION_LEFTBOT:
1431 pm_message("WARNING: This TIFF image has an orientation that "
1432 "most TIFF libraries convert incorrectly. "
1433 "Use -byrow to circumvent.");
1434 break;
1435 }
1436 }
1437 }
1438
1439
1440
1441 static void
1442 convertTiffRaster(uint32_t * const raster,
1443 unsigned int const cols,
1444 unsigned int const rows,
1445 xelval const maxval,
1446 pnmOut * const pnmOutP) {
1447 /*----------------------------------------------------------------------------
1448 Convert the raster 'raster' from the format generated by the TIFF library
1449 to PPM (plus PGM alpha mask where applicable) and output it to
1450 the object *pnmOutP. The raster is 'cols' wide by 'rows' high.
1451 -----------------------------------------------------------------------------*/
1452 xel * xelrow;
1453 /* The ppm-format row of the image row we are
1454 currently converting
1455 */
1456 gray * alpharow;
1457 /* The pgm-format row representing the alpha values
1458 for the image row we are currently converting.
1459 */
1460 unsigned int row;
1461
1462 xelrow = pnm_allocrow(cols);
1463 alpharow = pgm_allocrow(cols);
1464
1465 for (row = 0; row < rows; ++row) {
1466 uint32_t * rp;
1467 /* Address of pixel in 'raster' we are currently converting */
1468 unsigned int col;
1469
1470 /* Start at beginning of row: */
1471 rp = raster + (rows - row - 1) * cols;
1472
1473 for (col = 0; col < cols; ++col) {
1474 uint32_t const tiffPixel = *rp++;
1475
1476 PPM_ASSIGN(xelrow[col],
1477 TIFFGetR(tiffPixel) * maxval / 255,
1478 TIFFGetG(tiffPixel) * maxval / 255,
1479 TIFFGetB(tiffPixel) * maxval / 255);
1480 alpharow[col] = TIFFGetA(tiffPixel) * maxval / 255 ;
1481 }
1482 pnmOut_writeRow(pnmOutP, cols, xelrow, alpharow);
1483 }
1484
1485 pgm_freerow(alpharow);
1486 pnm_freerow(xelrow);
1487 }
1488
1489
1490
1491 enum convertDisp {CONV_DONE,
1492 CONV_OOM,
1493 CONV_UNABLE,
1494 CONV_FAILED,
1495 CONV_NOTATTEMPTED};
1496
1497
1498 static void
1499 convertRasterIntoProvidedMemory(pnmOut * const pnmOutP,
1500 unsigned int const cols,
1501 unsigned int const rows,
1502 xelval const maxval,
1503 TIFF * const tif,
1504 bool const verbose,
1505 uint32_t * const raster,
1506 enum convertDisp * const statusP) {
1507
1508 int const stopOnErrorFalse = false;
1509
1510 TIFFRGBAImage img;
1511 char emsg[1024];
1512 int ok;
1513
1514 ok = TIFFRGBAImageBegin(&img, tif, stopOnErrorFalse, emsg);
1515 if (!ok) {
1516 pm_message("%s", emsg);
1517 *statusP = CONV_FAILED;
1518 } else {
1519 int ok;
1520 ok = TIFFRGBAImageGet(&img, raster, cols, rows);
1521 TIFFRGBAImageEnd(&img) ;
1522 if (!ok) {
1523 pm_message("%s", emsg);
1524 *statusP = CONV_FAILED;
1525 } else {
1526 *statusP = CONV_DONE;
1527 convertTiffRaster(raster, cols, rows, maxval, pnmOutP);
1528 }
1529 }
1530 }
1531
1532
1533
1534 static void
1535 convertRasterInMemory(pnmOut * const pnmOutP,
1536 xelval const maxval,
1537 TIFF * const tif,
1538 bool const verbose,
1539 enum convertDisp * const statusP) {
1540 /*----------------------------------------------------------------------------
1541 With the TIFF header all processed (and relevant information from
1542 it in our arguments), write out the TIFF raster to the file images
1543 *imageoutFileP and *alphaFileP.
1544
1545 Do this by reading the entire TIFF image into memory at once and formatting
1546 it with the TIFF library's TIFFRGBAImageGet().
1547
1548 'cols' and 'rows' are the dimensions of the actual image, not of the
1549 TIFF raster matrix; ('tif' knows the TIFF raster matrix dimensions).
1550
1551 Return *statusP == CONV_OOM iff we are unable to proceed because we cannot
1552 get memory to store the entire raster. This means Caller may still be able
1553 to do the conversion using a row-by-row strategy. Like typical Netpbm
1554 programs, we simply abort the program if we are unable to allocate
1555 memory for other things.
1556 -----------------------------------------------------------------------------*/
1557 char emsg[1024];
1558 int ok;
1559
1560 if (verbose)
1561 pm_message("Converting in memory ...");
1562
1563 warnBrokenTiffLibrary(tif);
1564
1565 ok = TIFFRGBAImageOK(tif, emsg);
1566 if (!ok) {
1567 pm_message("%s", emsg);
1568 *statusP = CONV_UNABLE;
1569 } else {
1570 unsigned int cols, rows; /* Dimensions of output image */
1571 getTiffDimensions(tif, &cols, &rows);
1572
1573 if (rows == 0 || cols == 0)
1574 *statusP = CONV_DONE;
1575 else {
1576 if (cols > UINT_MAX/rows) {
1577 pm_message("%u rows of %u columns is too large to compute",
1578 rows, cols);
1579 *statusP = CONV_OOM;
1580 } else {
1581 unsigned int const pixelCt = rows * cols;
1582
1583 uint32_t * raster;
1584
1585 /* Note that TIFFRGBAImageGet() converts any bits per sample
1586 to 8. Maxval of the raster it returns is always 255.
1587 */
1588 MALLOCARRAY(raster, pixelCt);
1589 if (raster == NULL) {
1590 pm_message("Unable to allocate space for a raster of %u "
1591 "pixels.", pixelCt);
1592 *statusP = CONV_OOM;
1593 } else {
1594 convertRasterIntoProvidedMemory(
1595 pnmOutP, cols, rows, maxval, tif, verbose,
1596 raster, statusP);
1597
1598 free(raster);
1599 }
1600 }
1601 }
1602 }
1603 }
1604
1605
1606
1607 static void
1608 convertRaster(pnmOut * const pnmOutP,
1609 TIFF * const tifP,
1610 struct tiffDirInfo const tiffDir,
1611 xelval const maxval,
1612 unsigned short const fillorder,
1613 const xel * const colormap,
1614 bool const byrow,
1615 bool const flipOk,
1616 bool const noflipOk,
1617 bool const verbose) {
1618
1619 enum convertDisp status;
1620
1621 if (byrow || !flipOk)
1622 status = CONV_NOTATTEMPTED;
1623 else {
1624 convertRasterInMemory(pnmOutP, maxval, tifP, verbose, &status);
1625 }
1626 if (status == CONV_DONE) {
1627 if (tiffDir.bps > 8)
1628 pm_message("actual resolution has been reduced to 24 bits "
1629 "per pixel in the conversion. You can get the "
1630 "full %u bits that are in the TIFF with the "
1631 "-byrow option.", tiffDir.bps);
1632 } else {
1633 if (status != CONV_NOTATTEMPTED) {
1634 pm_message("In-memory conversion failed; "
1635 "using more primitive row-by-row conversion.");
1636
1637 if (!noflipOk)
1638 pm_error("TIFF raster is in nonstandard orientation, "
1639 "and we already committed to in-memory "
1640 "conversion. To avoid this failure, "
1641 "use -byrow .");
1642 }
1643 convertRasterByRows(
1644 pnmOutP, tiffDir.width, tiffDir.height, maxval,
1645 tifP, tiffDir.photomet, tiffDir.planarconfig,
1646 tiffDir.bps, tiffDir.spp, fillorder, colormap, verbose);
1647 }
1648 }
1649
1650
1651
1652 static void
1653 convertImage(TIFF * const tifP,
1654 FILE * const alphaFileP,
1655 FILE * const imageoutFileP,
1656 struct CmdlineInfo const cmdline) {
1657
1658 struct tiffDirInfo tiffDir;
1659 int format;
1660 xelval maxval;
1661 xel colormap[MAXCOLORS];
1662 unsigned short fillorder;
1663 bool flipOk, noflipOk;
1664 pnmOut pnmOut;
1665
1666 readDirectory(tifP, cmdline.headerdump, &tiffDir);
1667
1668 computeFillorder(tiffDir.fillorder, &fillorder, cmdline.respectfillorder);
1669
1670 analyzeImageType(tifP, tiffDir.bps, tiffDir.spp, tiffDir.photomet,
1671 &maxval, &format, colormap, cmdline.headerdump, cmdline);
1672
1673 pm_message("writing %s file", pnm_formattypenm(format));
1674
1675 pnmOut_init(imageoutFileP, alphaFileP, tiffDir.width, tiffDir.height,
1676 tiffDir.orientation, maxval, format, maxval,
1677 cmdline.byrow, cmdline.orientraw,
1678 cmdline.verbose,
1679 &flipOk, &noflipOk,
1680 &pnmOut);
1681
1682 convertRaster(&pnmOut, tifP, tiffDir, maxval,
1683 fillorder, colormap, cmdline.byrow, flipOk, noflipOk,
1684 cmdline.verbose);
1685
1686 pnmOut_term(&pnmOut, cmdline.verbose);
1687 }
1688
1689
1690
1691 static void
1692 convertIt(TIFF * const tifP,
1693 FILE * const alphaFile,
1694 FILE * const imageoutFile,
1695 struct CmdlineInfo const cmdline) {
1696
1697 unsigned int imageSeq;
1698 bool eof;
1699
1700 imageSeq = 0;
1701 eof = FALSE;
1702
1703 while (!eof) {
1704 bool success;
1705
1706 if (cmdline.verbose)
1707 pm_message("Converting Image %u", imageSeq);
1708 convertImage(tifP, alphaFile, imageoutFile, cmdline);
1709 success = TIFFReadDirectory(tifP);
1710 eof = !success;
1711 ++imageSeq;
1712 }
1713 }
1714
1715
1716
1717 int
1718 main(int argc, const char * argv[]) {
1719
1720 struct CmdlineInfo cmdline;
1721 TIFF * tiffP;
1722 FILE * alphaFile;
1723 FILE * imageoutFile;
1724
1725 pm_proginit(&argc, argv);
1726
1727 parseCommandLine(argc, argv, &cmdline);
1728
1729 tiffP = newTiffImageObject(cmdline.inputFilename);
1730
1731 if (cmdline.alphaStdout)
1732 alphaFile = stdout;
1733 else if (cmdline.alphaFilename == NULL)
1734 alphaFile = NULL;
1735 else
1736 alphaFile = pm_openw(cmdline.alphaFilename);
1737
1738 if (cmdline.alphaStdout)
1739 imageoutFile = NULL;
1740 else
1741 imageoutFile = stdout;
1742
1743 convertIt(tiffP, alphaFile, imageoutFile, cmdline);
1744
1745 if (imageoutFile != NULL)
1746 pm_close( imageoutFile );
1747 if (alphaFile != NULL)
1748 pm_close( alphaFile );
1749
1750 TIFFClose(tiffP);
1751
1752 pm_strfree(cmdline.inputFilename);
1753
1754 /* If the program failed, it previously aborted with nonzero completion
1755 code, via various function calls.
1756 */
1757 return 0;
1758 }
1759
1760
1761