Debian Codegraph @

texk/xdvipsk/thirdparty/libtiff/tools/tiff2ps.c

raw
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 "libport.h"
26 #include "tif_config.h"
27
28 #include <math.h>
29 #include <stdio.h>
30 #include <stdlib.h> /* for atof */
31 #include <string.h>
32 #include <time.h>
33
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #include "tiffio.h"
39
40 #ifndef EXIT_SUCCESS
41 #define EXIT_SUCCESS 0
42 #endif
43 #ifndef EXIT_FAILURE
44 #define EXIT_FAILURE 1
45 #endif
46
47 /*
48 * Revision history
49 * 2013-Jan-21
50 * Richard Nolde: Fix bug in auto rotate option code. Once a
51 * rotation angle was set by the auto rotate check, it was
52 * retained for all pages that followed instead of being
53 * retested for each page.
54 *
55 * 2010-Sep-17
56 * Richard Nolde: Reinstate code from Feb 2009 that never got
57 * accepted into CVS with major modifications to handle -H and -W
58 * options. Replaced original PlaceImage function with several
59 * new functions that make support for multiple output pages
60 * from a single image easier to understand. Added additional
61 * warning messages for incompatible command line options.
62 * Add new command line options to specify PageOrientation
63 * Document Structuring Comment for landscape or portrait
64 * and code to determine the values from output width and height
65 * if not specified on the command line.
66 * Add new command line option to specify document creator
67 * as an alterntive to the string "tiff2ps" following model
68 * of patch submitted by Thomas Jarosch for specifying a
69 * document title which is also supported now.
70 *
71 * 2009-Feb-11
72 * Richard Nolde: Added support for rotations of 90, 180, 270
73 * and auto using -r <90|180|270|auto>. Auto picks the best
74 * fit for the image on the specified paper size (eg portrait
75 * or landscape) if -h or -w is specified. Rotation is in
76 * degrees counterclockwise since that is how Postscript does
77 * it. The auto opption rotates the image 90 degrees ccw to
78 * produce landscape if that is a better fit than portrait.
79 *
80 * Cleaned up code in TIFF2PS and broke into smaller functions
81 * to simplify rotations.
82 *
83 * Identified incompatible options and returned errors, eg
84 * -i for imagemask operator is only available for Level2 or
85 * Level3 Postscript in the current implementation since there
86 * is a difference in the way the operands are called for Level1
87 * and there is no function to provide the Level1 version.
88 * -H was not handled properly if -h and/or -w were specified.
89 * It should only clip the masked images if the scaled image
90 * exceeds the maxPageHeight specified with -H.
91 *
92 * New design allows for all of the following combinations:
93 * Conversion of TIFF to Postscript with optional rotations
94 * of 90, 180, 270, or auto degrees counterclockwise
95 * Conversion of TIFF to Postscript with entire image scaled
96 * to maximum of values specified with -h or -w while
97 * maintaining aspect ratio. Same rotations apply.
98 * Conversion of TIFF to Postscript with clipping of output
99 * viewport to height specified with -H, producing multiple
100 * pages at this height and original width as needed.
101 * Same rotations apply.
102 * Conversion of TIFF to Postscript with image scaled to
103 * maximum specified by -h and -w and the resulting scaled
104 * image is presented in an output viewport clipped by -H height.
105 * The same rotations apply.
106 *
107 * Added maxPageWidth option using -W flag. MaxPageHeight and
108 * MaxPageWidth are mutually exclusive since the aspect ratio
109 * cannot be maintained if you set both.
110 * Rewrote PlaceImage to allow maxPageHeight and maxPageWidth
111 * options to work with values smaller or larger than the
112 * physical paper size and still preserve the aspect ratio.
113 * This is accomplished by creating multiple pages across
114 * as well as down if need be.
115 *
116 * 2001-Mar-21
117 * I (Bruce A. Mallett) added this revision history comment ;)
118 *
119 * Fixed PS_Lvl2page() code which outputs non-ASCII85 raw
120 * data. Moved test for when to output a line break to
121 * *after* the output of a character. This just serves
122 * to fix an eye-nuisance where the first line of raw
123 * data was one character shorter than subsequent lines.
124 *
125 * Added an experimental ASCII85 encoder which can be used
126 * only when there is a single buffer of bytes to be encoded.
127 * This version is much faster at encoding a straight-line
128 * buffer of data because it can avoid a lot of the loop
129 * overhead of the byte-by-byte version. To use this version
130 * you need to define EXP_ASCII85ENCODER (experimental ...).
131 *
132 * Added bug fix given by Michael Schmidt to PS_Lvl2page()
133 * in which an end-of-data marker ('>') was not being output
134 * when producing non-ASCII85 encoded PostScript Level 2
135 * data.
136 *
137 * Fixed PS_Lvl2colorspace() so that it no longer assumes that
138 * a TIFF having more than 2 planes is a CMYK. This routine
139 * no longer looks at the samples per pixel but instead looks
140 * at the "photometric" value. This change allows support of
141 * CMYK TIFFs.
142 *
143 * Modified the PostScript L2 imaging loop so as to test if
144 * the input stream is still open before attempting to do a
145 * flushfile on it. This was done because some RIPs close
146 * the stream after doing the image operation.
147 *
148 * Got rid of the realloc() being done inside a loop in the
149 * PSRawDataBW() routine. The code now walks through the
150 * byte-size array outside the loop to determine the largest
151 * size memory block that will be needed.
152 *
153 * Added "-m" switch to ask tiff2ps to, where possible, use the
154 * "imagemask" operator instead of the "image" operator.
155 *
156 * Added the "-i #" switch to allow interpolation to be disabled.
157 *
158 * Unrolled a loop or two to improve performance.
159 */
160
161 /*
162 * Define EXP_ASCII85ENCODER if you want to use an experimental
163 * version of the ASCII85 encoding routine. The advantage of
164 * using this routine is that tiff2ps will convert to ASCII85
165 * encoding at between 3 and 4 times the speed as compared to
166 * using the old (non-experimental) encoder. The disadvantage
167 * is that you will be using a new (and unproven) encoding
168 * routine. So user beware, you have been warned!
169 */
170
171 #define EXP_ASCII85ENCODER
172
173 #ifndef TRUE
174 #define TRUE 1
175 #define FALSE 0
176 #endif
177
178 #define DEFAULT_MAX_MALLOC (256 * 1024 * 1024)
179
180 /* malloc size limit (in bytes)
181 * disabled when set to 0 */
182 static tmsize_t maxMalloc = DEFAULT_MAX_MALLOC;
183
184 int ascii85_g = FALSE; /* use ASCII85 encoding */
185 int interpolate = TRUE; /* interpolate level2 image */
186 int level2 = FALSE; /* generate PostScript level 2 */
187 int level3 = FALSE; /* generate PostScript level 3 */
188 int printAll = FALSE; /* print all images in file */
189 int generateEPSF = TRUE; /* generate Encapsulated PostScript */
190 int PSduplex = FALSE; /* enable duplex printing */
191 int PStumble = FALSE; /* enable top edge binding */
192 int PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */
193 double maxPageHeight =
194 0; /* maximum height to select from image and print per page */
195 double maxPageWidth =
196 0; /* maximum width to select from image and print per page */
197 double splitOverlap = 0; /* amount for split pages to overlag */
198 int rotation_g = 0; /* optional value for rotation angle */
199 int auto_rotate_g = 0; /* rotate image for best fit on the page */
200 char *filename = NULL; /* input filename */
201 char *title = NULL; /* optional document title string */
202 char *creator = NULL; /* optional document creator string */
203 char pageOrientation[12]; /* set optional PageOrientation DSC to Landscape or
204 Portrait */
205 int useImagemask = FALSE; /* Use imagemask instead of image operator */
206 uint16_t res_unit = 0; /* Resolution units: 2 - inches, 3 - cm */
207
208 /*
209 * ASCII85 Encoding Support.
210 */
211 unsigned char ascii85buf[10];
212 int ascii85count;
213 int ascii85breaklen;
214
215 int TIFF2PS(FILE *, TIFF *, double, double, double, double, int);
216 void PSpage(FILE *, TIFF *, uint32_t, uint32_t);
217 void PSColorContigPreamble(FILE *, uint32_t, uint32_t, int);
218 void PSColorSeparatePreamble(FILE *, uint32_t, uint32_t, int);
219 void PSDataColorContig(FILE *, TIFF *, uint32_t, uint32_t, int);
220 void PSDataColorSeparate(FILE *, TIFF *, uint32_t, uint32_t, int);
221 void PSDataPalette(FILE *, TIFF *, uint32_t, uint32_t);
222 void PSDataBW(FILE *, TIFF *, uint32_t, uint32_t);
223 void PSRawDataBW(FILE *, TIFF *, uint32_t, uint32_t);
224 void Ascii85Init(void);
225 void Ascii85Put(unsigned char code, FILE *fd);
226 void Ascii85Flush(FILE *fd);
227 void PSHead(FILE *, double, double, double, double);
228 void PSTail(FILE *, int);
229 int psStart(FILE *, int, int, int *, double *, double, double, double, double,
230 double, double, double, double, double, double);
231 int psPageSize(FILE *, int, double, double, double, double, double, double);
232 int psRotateImage(FILE *, int, double, double, double, double);
233 int psMaskImage(FILE *, TIFF *, int, int, int *, double, double, double, double,
234 double, double, double, double, double);
235 int psScaleImage(FILE *, double, int, int, double, double, double, double,
236 double, double);
237 int get_viewport(double, double, double, double, double *, double *, int);
238 int exportMaskedImage(FILE *, double, double, double, double, int, int, double,
239 double, double, int, int);
240
241 #if defined(EXP_ASCII85ENCODER)
242 tsize_t Ascii85EncodeBlock(uint8_t *ascii85_p, unsigned f_eod,
243 const uint8_t *raw_p, tsize_t raw_l);
244 #endif
245
246 static void usage(int);
247
248 /**
249 * This custom malloc function enforce a maximum allocation size
250 */
251 static void *limitMalloc(tmsize_t s)
252 {
253 /* tmsize_t is signed and _TIFFmalloc() converts s to size_t. Therefore
254 * check for negative s. */
255 if (maxMalloc && ((s > maxMalloc) || (s < 0)))
256 {
257 fprintf(stderr,
258 "MemoryLimitError: allocation of %" TIFF_SSIZE_FORMAT
259 " bytes is forbidden. Limit is %" TIFF_SSIZE_FORMAT ".\n",
260 s, maxMalloc);
261 fprintf(stderr, " use -M option to change limit.\n");
262 return NULL;
263 }
264 return _TIFFmalloc(s);
265 }
266
267 int main(int argc, char *argv[])
268 {
269 int dirnum = -1, c, np = 0;
270 int centered = 0;
271 double bottommargin = 0;
272 double leftmargin = 0;
273 double pageWidth = 0;
274 double pageHeight = 0;
275 uint32_t diroff = 0;
276 #if !HAVE_DECL_OPTARG
277 extern char *optarg;
278 extern int optind;
279 #endif
280 FILE *output = stdout;
281
282 pageOrientation[0] = '\0';
283
284 while ((c = getopt(argc, argv,
285 "b:d:h:H:W:L:M:i:w:l:o:O:P:C:r:t:acemxyzps1238DT")) !=
286 -1)
287 switch (c)
288 {
289 case 'M':
290 maxMalloc = (tmsize_t)strtoul(optarg, NULL, 0) << 20;
291 break;
292 case 'b':
293 bottommargin = atof(optarg);
294 break;
295 case 'c':
296 centered = 1;
297 break;
298 case 'C':
299 creator = optarg;
300 break;
301 case 'd': /* without -a, this only processes one image at this IFD
302 */
303 dirnum = atoi(optarg);
304 break;
305 case 'D':
306 PSduplex = TRUE;
307 break;
308 case 'i':
309 interpolate = atoi(optarg) ? TRUE : FALSE;
310 break;
311 case 'T':
312 PStumble = TRUE;
313 break;
314 case 'e':
315 PSavoiddeadzone = FALSE;
316 generateEPSF = TRUE;
317 break;
318 case 'h':
319 pageHeight = atof(optarg);
320 break;
321 case 'H':
322 maxPageHeight = atof(optarg);
323 break;
324 case 'W':
325 maxPageWidth = atof(optarg);
326 break;
327 case 'L':
328 splitOverlap = atof(optarg);
329 break;
330 case 'm':
331 useImagemask = TRUE;
332 break;
333 case 'o':
334 switch (optarg[0])
335 {
336 case '0':
337 case '1':
338 case '2':
339 case '3':
340 case '4':
341 case '5':
342 case '6':
343 case '7':
344 case '8':
345 case '9':
346 diroff = (uint32_t)strtoul(optarg, NULL, 0);
347 break;
348 default:
349 TIFFError("-o", "Offset must be a numeric value.");
350 exit(EXIT_FAILURE);
351 }
352 break;
353 case 'O': /* XXX too bad -o is already taken */
354 output = fopen(optarg, "w");
355 if (output == NULL)
356 {
357 fprintf(stderr, "%s: %s: Cannot open output file.\n",
358 argv[0], optarg);
359 exit(EXIT_FAILURE);
360 }
361 break;
362 case 'P':
363 switch (optarg[0])
364 {
365 case 'l':
366 case 'L':
367 strcpy(pageOrientation, "Landscape");
368 break;
369 case 'p':
370 case 'P':
371 strcpy(pageOrientation, "Portrait");
372 break;
373 default:
374 TIFFError(
375 "-P",
376 "Page orientation must be Landscape or Portrait");
377 exit(EXIT_FAILURE);
378 }
379 break;
380 case 'l':
381 leftmargin = atof(optarg);
382 break;
383 case 'a': /* removed fall through to generate warning below, R Nolde
384 09-01-2010 */
385 printAll = TRUE;
386 break;
387 case 'p':
388 generateEPSF = FALSE;
389 break;
390 case 'r':
391 if (strcmp(optarg, "auto") == 0)
392 {
393 rotation_g = 0;
394 auto_rotate_g = TRUE;
395 }
396 else
397 {
398 rotation_g = atoi(optarg);
399 auto_rotate_g = FALSE;
400 }
401 switch (rotation_g)
402 {
403 case 0:
404 case 90:
405 case 180:
406 case 270:
407 break;
408 default:
409 fprintf(stderr, "Rotation angle must be 90, 180, 270 "
410 "(degrees ccw) or auto\n");
411 exit(EXIT_FAILURE);
412 }
413 break;
414 case 's':
415 printAll = FALSE;
416 break;
417 case 't':
418 title = optarg;
419 break;
420 case 'w':
421 pageWidth = atof(optarg);
422 break;
423 case 'z':
424 PSavoiddeadzone = FALSE;
425 break;
426 case '1':
427 level2 = FALSE;
428 level3 = FALSE;
429 ascii85_g = FALSE;
430 break;
431 case '2':
432 level2 = TRUE;
433 ascii85_g = TRUE; /* default to yes */
434 break;
435 case '3':
436 level3 = TRUE;
437 ascii85_g = TRUE; /* default to yes */
438 break;
439 case '8':
440 ascii85_g = FALSE;
441 break;
442 case 'x':
443 res_unit = RESUNIT_CENTIMETER;
444 break;
445 case 'y':
446 res_unit = RESUNIT_INCH;
447 break;
448 case '?':
449 usage(EXIT_FAILURE);
450 }
451
452 if (useImagemask == TRUE)
453 {
454 if ((level2 == FALSE) && (level3 == FALSE))
455 {
456 TIFFError(
457 "-m ",
458 " imagemask operator requires Postscript Level2 or Level3");
459 exit(EXIT_FAILURE);
460 }
461 }
462
463 if (pageWidth && (maxPageWidth > pageWidth))
464 {
465 TIFFError("-W", "Max viewport width cannot exceed page width");
466 exit(EXIT_FAILURE);
467 }
468
469 /* auto rotate requires a specified page width and height */
470 if (auto_rotate_g == TRUE)
471 {
472 /*
473 if ((pageWidth == 0) || (pageHeight == 0))
474 TIFFWarning ("-r auto", " requires page height and width specified with
475 -h and -w");
476 */
477 if ((maxPageWidth > 0) || (maxPageHeight > 0))
478 {
479 TIFFError("-r auto", " is incompatible with maximum page "
480 "width/height specified by -H or -W");
481 exit(EXIT_FAILURE);
482 }
483 }
484 if ((maxPageWidth > 0) && (maxPageHeight > 0))
485 {
486 TIFFError("-H and -W",
487 " Use only one of -H or -W to define a viewport");
488 exit(EXIT_FAILURE);
489 }
490
491 if ((generateEPSF == TRUE) && (printAll == TRUE))
492 {
493 TIFFError(" -e and -a", "Warning: Cannot generate Encapsulated "
494 "Postscript for multiple images");
495 generateEPSF = FALSE;
496 }
497
498 if ((generateEPSF == TRUE) && (PSduplex == TRUE))
499 {
500 TIFFError(
501 " -e and -D",
502 "Warning: Encapsulated Postscript does not support Duplex option");
503 PSduplex = FALSE;
504 }
505
506 if ((generateEPSF == TRUE) && (PStumble == TRUE))
507 {
508 TIFFError(" -e and -T", "Warning: Encapsulated Postscript does not "
509 "support Top Edge Binding option");
510 PStumble = FALSE;
511 }
512
513 if ((generateEPSF == TRUE) && (PSavoiddeadzone == TRUE))
514 PSavoiddeadzone = FALSE;
515
516 for (; argc - optind > 0; optind++)
517 {
518 TIFFOpenOptions *opts = TIFFOpenOptionsAlloc();
519 if (opts == NULL)
520 {
521 return EXIT_FAILURE;
522 }
523 TIFFOpenOptionsSetMaxSingleMemAlloc(opts, maxMalloc);
524 TIFF *tif = TIFFOpenExt(filename = argv[optind], "r", opts);
525 TIFFOpenOptionsFree(opts);
526 if (tif != NULL)
527 {
528 if (dirnum != -1 && !TIFFSetDirectory(tif, (tdir_t)dirnum))
529 {
530 TIFFClose(tif);
531 return (EXIT_FAILURE);
532 }
533 else if (diroff != 0 && !TIFFSetSubDirectory(tif, diroff))
534 {
535 TIFFClose(tif);
536 return (EXIT_FAILURE);
537 }
538 np = TIFF2PS(output, tif, pageWidth, pageHeight, leftmargin,
539 bottommargin, centered);
540 if (np < 0)
541 {
542 TIFFError("Error", "Unable to process %s", filename);
543 }
544 TIFFClose(tif);
545 }
546 }
547 if (np)
548 PSTail(output, np);
549 else
550 usage(EXIT_FAILURE);
551 if (output != stdout)
552 fclose(output);
553 return (EXIT_SUCCESS);
554 }
555
556 static uint16_t samplesperpixel;
557 static uint16_t bitspersample;
558 static uint16_t planarconfiguration;
559 static uint16_t photometric;
560 static uint16_t compression;
561 static uint16_t extrasamples;
562 static int alpha;
563
564 static int checkImage(TIFF *tif)
565 {
566 switch (photometric)
567 {
568 case PHOTOMETRIC_YCBCR:
569 if ((compression == COMPRESSION_JPEG ||
570 compression == COMPRESSION_OJPEG) &&
571 planarconfiguration == PLANARCONFIG_CONTIG)
572 {
573 /* can rely on libjpeg to convert to RGB */
574 TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
575 photometric = PHOTOMETRIC_RGB;
576 }
577 else
578 {
579 if (level2 || level3)
580 break;
581 TIFFError(filename, "Can not handle image with %s",
582 "PhotometricInterpretation=YCbCr");
583 return (0);
584 }
585 /* fall through... */
586 case PHOTOMETRIC_RGB:
587 if (alpha && bitspersample != 8)
588 {
589 TIFFError(filename,
590 "Can not handle %" PRIu16
591 "-bit/sample RGB image with alpha",
592 bitspersample);
593 return (0);
594 }
595 /* fall through... */
596 case PHOTOMETRIC_SEPARATED:
597 case PHOTOMETRIC_PALETTE:
598 case PHOTOMETRIC_MINISBLACK:
599 case PHOTOMETRIC_MINISWHITE:
600 break;
601 case PHOTOMETRIC_LOGL:
602 case PHOTOMETRIC_LOGLUV:
603 if (compression != COMPRESSION_SGILOG &&
604 compression != COMPRESSION_SGILOG24)
605 {
606 TIFFError(
607 filename,
608 "Can not handle %s data with compression other than SGILog",
609 (photometric == PHOTOMETRIC_LOGL) ? "LogL" : "LogLuv");
610 return (0);
611 }
612 /* rely on library to convert to RGB/greyscale */
613 TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
614 photometric = (photometric == PHOTOMETRIC_LOGL)
615 ? PHOTOMETRIC_MINISBLACK
616 : PHOTOMETRIC_RGB;
617 bitspersample = 8;
618 break;
619 case PHOTOMETRIC_CIELAB:
620 /* fall through... */
621 default:
622 TIFFError(
623 filename,
624 "Can not handle image with PhotometricInterpretation=%" PRIu16,
625 photometric);
626 return (0);
627 }
628 switch (bitspersample)
629 {
630 case 1:
631 case 2:
632 case 4:
633 case 8:
634 case 16:
635 break;
636 default:
637 TIFFError(filename, "Can not handle %" PRIu16 "-bit/sample image",
638 bitspersample);
639 return (0);
640 }
641 if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
642 TIFFWarning(filename, "Ignoring extra samples");
643 return (1);
644 }
645
646 #define PS_UNIT_SIZE 72.0F
647 #define PSUNITS(npix, res) ((npix) * (PS_UNIT_SIZE / (res)))
648
649 static const char RGBcolorimage[] = "\
650 /bwproc {\n\
651 rgbproc\n\
652 dup length 3 idiv string 0 3 0\n\
653 5 -1 roll {\n\
654 add 2 1 roll 1 sub dup 0 eq {\n\
655 pop 3 idiv\n\
656 3 -1 roll\n\
657 dup 4 -1 roll\n\
658 dup 3 1 roll\n\
659 5 -1 roll put\n\
660 1 add 3 0\n\
661 } { 2 1 roll } ifelse\n\
662 } forall\n\
663 pop pop pop\n\
664 } def\n\
665 /colorimage where {pop} {\n\
666 /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
667 } ifelse\n\
668 ";
669
670 /*
671 * Adobe Photoshop requires a comment line of the form:
672 *
673 * %ImageData: <cols> <rows> <depth> <main channels> <pad channels>
674 * <block size> <1 for binary|2 for hex> "data start"
675 *
676 * It is claimed to be part of some future revision of the EPS spec.
677 */
678 static void PhotoshopBanner(FILE *fd, uint32_t w, uint32_t h, int bs, int nc,
679 const char *startline)
680 {
681 fprintf(fd, "%%ImageData: %" PRIu32 " %" PRIu32 " %" PRIu16 " %d 0 %d 2 \"",
682 w, h, bitspersample, nc, bs);
683 fprintf(fd, startline, nc);
684 fprintf(fd, "\"\n");
685 }
686
687 /* Convert pixel width and height pw, ph, to points pprw, pprh
688 * using image resolution and resolution units from TIFF tags.
689 * pw : image width in pixels
690 * ph : image height in pixels
691 * pprw : image width in PS units (72 dpi)
692 * pprh : image height in PS units (72 dpi)
693 */
694 static void setupPageState(TIFF *tif, uint32_t *pw, uint32_t *ph, double *pprw,
695 double *pprh)
696 {
697 float xres = 0.0F, yres = 0.0F;
698
699 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
700 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
701 if (res_unit == 0) /* Not specified as command line option */
702 if (!TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit))
703 res_unit = RESUNIT_INCH;
704 /*
705 * Calculate printable area.
706 */
707 if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) ||
708 fabs(xres) < 0.0000001)
709 xres = PS_UNIT_SIZE;
710 if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) ||
711 fabs(yres) < 0.0000001)
712 yres = PS_UNIT_SIZE;
713 switch (res_unit)
714 {
715 case RESUNIT_CENTIMETER:
716 xres *= 2.54F, yres *= 2.54F;
717 break;
718 case RESUNIT_INCH:
719 break;
720 case RESUNIT_NONE: /* Subsequent code assumes we have converted to
721 inches! */
722 res_unit = RESUNIT_INCH;
723 break;
724 default: /* Last ditch guess for unspecified RESUNIT case
725 * check that the resolution is not inches before scaling it.
726 * Moved to end of function with additional check, RJN,
727 * 08-31-2010 if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE)
728 * xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
729 */
730 break;
731 }
732 /* This is a hack to deal with images that have no meaningful Resolution
733 * Size but may have x and/or y resolutions of 1 pixel per undefined unit.
734 */
735 if ((xres > 1.0) && (xres != PS_UNIT_SIZE))
736 *pprw = PSUNITS(*pw, xres);
737 else
738 *pprw = PSUNITS(*pw, PS_UNIT_SIZE);
739 if ((yres > 1.0) && (yres != PS_UNIT_SIZE))
740 *pprh = PSUNITS(*ph, yres);
741 else
742 *pprh = PSUNITS(*ph, PS_UNIT_SIZE);
743 }
744
745 static int isCCITTCompression(TIFF *tif)
746 {
747 uint16_t compress;
748 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
749 return (compress == COMPRESSION_CCITTFAX3 ||
750 compress == COMPRESSION_CCITTFAX4 ||
751 compress == COMPRESSION_CCITTRLE ||
752 compress == COMPRESSION_CCITTRLEW);
753 }
754
755 static tsize_t tf_bytesperrow;
756 static tsize_t ps_bytesperrow;
757 static uint32_t tf_rowsperstrip;
758 static uint32_t tf_numberstrips;
759 static char *hex = "0123456789abcdef";
760
761 /*
762 * Pagewidth and pageheight are the output size in points,
763 * may refer to values specified with -h and -w, or to
764 * values read from the image if neither -h nor -w are used.
765 * Imagewidth and imageheight are image size in points.
766 * Ximages and Yimages are number of pages across and down.
767 * Only one of maxPageHeight or maxPageWidth can be used.
768 * These are global variables unfortunately.
769 */
770 int get_subimage_count(double pagewidth, double pageheight, double imagewidth,
771 double imageheight, int *ximages, int *yimages,
772 int rotation, double scale)
773 {
774 int pages = 1;
775 double splitheight = 0; /* Requested Max Height in points */
776 double splitwidth = 0; /* Requested Max Width in points */
777 double overlap = 0; /* Repeated edge width in points */
778
779 splitheight = maxPageHeight * PS_UNIT_SIZE;
780 splitwidth = maxPageWidth * PS_UNIT_SIZE;
781 overlap = splitOverlap * PS_UNIT_SIZE;
782 pagewidth *= PS_UNIT_SIZE;
783 pageheight *= PS_UNIT_SIZE;
784
785 if ((imagewidth < 1.0) || (imageheight < 1.0))
786 {
787 TIFFError("get_subimage_count", "Invalid image width or height");
788 return (0);
789 }
790
791 switch (rotation)
792 {
793 case 0:
794 case 180:
795 if (splitheight > 0) /* -H maxPageHeight */
796 {
797 if (imageheight >
798 splitheight) /* More than one vertical image segment */
799 {
800 if (pagewidth)
801 *ximages = (int)ceil((scale * imagewidth) /
802 (pagewidth - overlap));
803 else
804 *ximages = 1;
805 *yimages = (int)ceil(
806 (scale * imageheight) /
807 (splitheight - overlap)); /* Max vert pages needed */
808 }
809 else
810 {
811 if (pagewidth)
812 *ximages = (int)ceil(
813 (scale * imagewidth) /
814 (pagewidth - overlap)); /* Max horz pages needed */
815 else
816 *ximages = 1;
817 *yimages = 1; /* Max vert pages needed */
818 }
819 }
820 else
821 {
822 if (splitwidth > 0) /* -W maxPageWidth */
823 {
824 if (imagewidth > splitwidth)
825 {
826 *ximages = (int)ceil(
827 (scale * imagewidth) /
828 (splitwidth - overlap)); /* Max horz pages needed */
829 if (pageheight)
830 *yimages = (int)ceil(
831 (scale * imageheight) /
832 (pageheight -
833 overlap)); /* Max vert pages needed */
834 else
835 *yimages = 1;
836 }
837 else
838 {
839 *ximages = 1; /* Max vert pages needed */
840 if (pageheight)
841 *yimages = (int)ceil(
842 (scale * imageheight) /
843 (pageheight -
844 overlap)); /* Max vert pages needed */
845 else
846 *yimages = 1;
847 }
848 }
849 else
850 {
851 *ximages = 1;
852 *yimages = 1;
853 }
854 }
855 break;
856 case 90:
857 case 270:
858 if (splitheight > 0) /* -H maxPageHeight */
859 {
860 if (imagewidth >
861 splitheight) /* More than one vertical image segment */
862 {
863 *yimages = (int)ceil(
864 (scale * imagewidth) /
865 (splitheight - overlap)); /* Max vert pages needed */
866 if (pagewidth)
867 *ximages = (int)ceil(
868 (scale * imageheight) /
869 (pagewidth - overlap)); /* Max horz pages needed */
870 else
871 *ximages = 1;
872 }
873 else
874 {
875 *yimages = 1; /* Max vert pages needed */
876 if (pagewidth)
877 *ximages = (int)ceil(
878 (scale * imageheight) /
879 (pagewidth - overlap)); /* Max horz pages needed */
880 else
881 *ximages = 1;
882 }
883 }
884 else
885 {
886 if (splitwidth > 0) /* -W maxPageWidth */
887 {
888 if (imageheight > splitwidth)
889 {
890 if (pageheight)
891 *yimages = (int)ceil(
892 (scale * imagewidth) /
893 (pageheight -
894 overlap)); /* Max vert pages needed */
895 else
896 *yimages = 1;
897 *ximages = (int)ceil(
898 (scale * imageheight) /
899 (splitwidth - overlap)); /* Max horz pages needed */
900 }
901 else
902 {
903 if (pageheight)
904 *yimages = (int)ceil(
905 (scale * imagewidth) /
906 (pageheight -
907 overlap)); /* Max horz pages needed */
908 else
909 *yimages = 1;
910 *ximages = 1; /* Max vert pages needed */
911 }
912 }
913 else
914 {
915 *ximages = 1;
916 *yimages = 1;
917 }
918 }
919 break;
920 default:
921 *ximages = 1;
922 *yimages = 1;
923 }
924 pages = (*ximages) * (*yimages);
925 return (pages);
926 }
927
928 /* New version of PlaceImage that handles only the translation and rotation
929 * for a single output page.
930 */
931 int exportMaskedImage(FILE *fp, double pagewidth, double pageheight,
932 double imagewidth, double imageheight, int row,
933 int column, double left_offset, double bott_offset,
934 double scale, int center, int rotation)
935 {
936 double xtran = 0.0;
937 double ytran = 0.0;
938
939 double xscale = 1.0;
940 double yscale = 1.0;
941
942 double splitheight = 0; /* Requested Max Height in points */
943 double splitwidth = 0; /* Requested Max Width in points */
944 double overlap = 0; /* Repeated edge width in points */
945 double subimage_height = 0.0;
946
947 splitheight = maxPageHeight * PS_UNIT_SIZE;
948 splitwidth = maxPageWidth * PS_UNIT_SIZE;
949 overlap = splitOverlap * PS_UNIT_SIZE;
950 xscale = scale * imagewidth;
951 yscale = scale * imageheight;
952
953 if ((xscale < 0.0) || (yscale < 0.0))
954 {
955 TIFFError("exportMaskedImage", "Invalid parameters.");
956 return (-1);
957 }
958
959 /* If images are cropped to a vewport with -H or -W, the output pages are
960 * shifted to the top of each output page rather than the Postscript default
961 * lower edge.
962 */
963 switch (rotation)
964 {
965 case 0:
966 case 180:
967 if (splitheight > 0) /* -H maxPageHeight */
968 {
969 if (splitheight <
970 imageheight) /* More than one vertical image segments */
971 {
972 /* Intra2net: Keep correct apspect ratio */
973 xscale = (imagewidth + overlap) *
974 (pageheight / splitheight) * scale;
975
976 xtran = -1.0 * column * (pagewidth - overlap);
977 subimage_height =
978 imageheight - ((splitheight - overlap) * row);
979 ytran = pageheight -
980 subimage_height * (pageheight / splitheight);
981 }
982 else /* Only one page in vertical direction */
983 {
984 xtran = -1.0 * column * (pagewidth - overlap);
985 ytran = splitheight - imageheight;
986 }
987 }
988 else
989 {
990 if (splitwidth > 0) /* maxPageWidth */
991 {
992 if (splitwidth < imagewidth)
993 {
994 xtran = -1.0 * column * splitwidth;
995 ytran = -1.0 * row * (pageheight - overlap);
996 }
997 else /* Only one page in horizontal direction */
998 {
999 ytran = -1.0 * row * (pageheight - overlap);
1000 xtran = 0;
1001 }
1002 }
1003 else /* Simple case, no splitting */
1004 {
1005 ytran = pageheight - imageheight;
1006 xtran = 0;
1007 }
1008 }
1009
1010 if (imagewidth <= pagewidth)
1011 {
1012 /* Intra2net: Crop page at the bottom instead of the top (->
1013 output starts at the top). Only do this in non-page-split
1014 mode */
1015 if (imageheight <= splitheight)
1016 {
1017 ytran = pageheight -
1018 imageheight; /* Note: Will be negative for images
1019 longer than page size */
1020 }
1021 }
1022 bott_offset += ytran / (center ? 2 : 1);
1023 left_offset += xtran / (center ? 2 : 1);
1024 break;
1025 case 90:
1026 case 270:
1027 if (splitheight > 0) /* -H maxPageHeight */
1028 {
1029 if (splitheight <
1030 imagewidth) /* More than one vertical image segments */
1031 {
1032 xtran = -1.0 * column * (pageheight - overlap);
1033 /* Commented code places image at bottom of page instead of
1034 top. ytran = -1.0 * row * splitheight;
1035 */
1036 if (row == 0)
1037 ytran = -1.0 * (imagewidth - splitheight);
1038 else
1039 ytran = -1.0 * (imagewidth -
1040 (splitheight - overlap) * (row + 1));
1041 }
1042 else /* Only one page in vertical direction */
1043 {
1044 xtran = -1.0 * column * (pageheight - overlap);
1045 ytran = splitheight - imagewidth;
1046 }
1047 }
1048 else
1049 {
1050 if (splitwidth > 0) /* maxPageWidth */
1051 {
1052 if (splitwidth < imageheight)
1053 {
1054 xtran = -1.0 * column * splitwidth;
1055 ytran = -1.0 * row * (pagewidth - overlap);
1056 }
1057 else /* Only one page in horizontal direction */
1058 {
1059 ytran = -1.0 * row * (pagewidth - overlap);
1060 xtran = 0;
1061 }
1062 }
1063 else /* Simple case, no splitting */
1064 {
1065 ytran = pageheight - imageheight;
1066 xtran = 0; /* pagewidth - imagewidth; */
1067 }
1068 }
1069 bott_offset += ytran / (center ? 2 : 1);
1070 left_offset += xtran / (center ? 2 : 1);
1071 break;
1072 default:
1073 xtran = 0;
1074 ytran = 0;
1075 }
1076
1077 switch (rotation)
1078 {
1079 case 0:
1080 fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
1081 fprintf(fp, "%f %f scale\n", xscale, yscale);
1082 break;
1083 case 180:
1084 fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
1085 fprintf(fp, "%f %f scale\n1 1 translate 180 rotate\n", xscale,
1086 yscale);
1087 break;
1088 case 90:
1089 fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
1090 fprintf(fp, "%f %f scale\n1 0 translate 90 rotate\n", yscale,
1091 xscale);
1092 break;
1093 case 270:
1094 fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
1095 fprintf(fp, "%f %f scale\n0 1 translate 270 rotate\n", yscale,
1096 xscale);
1097 break;
1098 default:
1099 TIFFError("exportMaskedImage",
1100 "Unsupported rotation angle %d. No rotation", rotation);
1101 fprintf(fp, "%f %f scale\n", xscale, yscale);
1102 break;
1103 }
1104
1105 return (0);
1106 }
1107
1108 /* Rotate an image without scaling or clipping */
1109 int psRotateImage(FILE *fd, int rotation, double pswidth, double psheight,
1110 double left_offset, double bottom_offset)
1111 {
1112 if ((left_offset != 0.0) || (bottom_offset != 0))
1113 fprintf(fd, "%f %f translate\n", left_offset, bottom_offset);
1114
1115 /* Exchange width and height for 90/270 rotations */
1116 switch (rotation)
1117 {
1118 case 0:
1119 fprintf(fd, "%f %f scale\n", pswidth, psheight);
1120 break;
1121 case 90:
1122 fprintf(fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight,
1123 pswidth);
1124 break;
1125 case 180:
1126 fprintf(fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth,
1127 psheight);
1128 break;
1129 case 270:
1130 fprintf(fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight,
1131 pswidth);
1132 break;
1133 default:
1134 TIFFError("psRotateImage", "Unsupported rotation %d.", rotation);
1135 fprintf(fd, "%f %f scale\n", pswidth, psheight);
1136 return (1);
1137 }
1138 return (0);
1139 }
1140
1141 /* Scale and rotate an image to a single output page. */
1142 int psScaleImage(FILE *fd, double scale, int rotation, int center,
1143 double reqwidth, double reqheight, double pswidth,
1144 double psheight, double left_offset, double bottom_offset)
1145 {
1146 double hcenter = 0.0, vcenter = 0.0;
1147
1148 /* Adjust offsets for centering */
1149 if (center)
1150 {
1151 switch (rotation)
1152 {
1153 case 90:
1154 vcenter = (reqheight - pswidth * scale) / 2;
1155 hcenter = (reqwidth - psheight * scale) / 2;
1156 fprintf(fd, "%f %f translate\n", hcenter, vcenter);
1157 fprintf(fd, "%f %f scale\n1 0 translate 90 rotate\n",
1158 psheight * scale, pswidth * scale);
1159 break;
1160 case 180:
1161 hcenter = (reqwidth - pswidth * scale) / 2;
1162 vcenter = (reqheight - psheight * scale) / 2;
1163 fprintf(fd, "%f %f translate\n", hcenter, vcenter);
1164 fprintf(fd, "%f %f scale\n1 1 translate 180 rotate\n",
1165 pswidth * scale, psheight * scale);
1166 break;
1167 case 270:
1168 vcenter = (reqheight - pswidth * scale) / 2;
1169 hcenter = (reqwidth - psheight * scale) / 2;
1170 fprintf(fd, "%f %f translate\n", hcenter, vcenter);
1171 fprintf(fd, "%f %f scale\n0 1 translate 270 rotate\n",
1172 psheight * scale, pswidth * scale);
1173 break;
1174 case 0:
1175 default:
1176 hcenter = (reqwidth - pswidth * scale) / 2;
1177 vcenter = (reqheight - psheight * scale) / 2;
1178 fprintf(fd, "%f %f translate\n", hcenter, vcenter);
1179 fprintf(fd, "%f %f scale\n", pswidth * scale, psheight * scale);
1180 break;
1181 }
1182 }
1183 else /* Not centered */
1184 {
1185 switch (rotation)
1186 {
1187 case 0:
1188 fprintf(fd, "%f %f translate\n",
1189 left_offset ? left_offset : 0.0,
1190 bottom_offset ? bottom_offset
1191 : reqheight - (psheight * scale));
1192 fprintf(fd, "%f %f scale\n", pswidth * scale, psheight * scale);
1193 break;
1194 case 90:
1195 fprintf(fd, "%f %f translate\n",
1196 left_offset ? left_offset : 0.0,
1197 bottom_offset ? bottom_offset
1198 : reqheight - (pswidth * scale));
1199 fprintf(fd, "%f %f scale\n1 0 translate 90 rotate\n",
1200 psheight * scale, pswidth * scale);
1201 break;
1202 case 180:
1203 fprintf(fd, "%f %f translate\n",
1204 left_offset ? left_offset : 0.0,
1205 bottom_offset ? bottom_offset
1206 : reqheight - (psheight * scale));
1207 fprintf(fd, "%f %f scale\n1 1 translate 180 rotate\n",
1208 pswidth * scale, psheight * scale);
1209 break;
1210 case 270:
1211 fprintf(fd, "%f %f translate\n",
1212 left_offset ? left_offset : 0.0,
1213 bottom_offset ? bottom_offset
1214 : reqheight - (pswidth * scale));
1215 fprintf(fd, "%f %f scale\n0 1 translate 270 rotate\n",
1216 psheight * scale, pswidth * scale);
1217 break;
1218 default:
1219 TIFFError("psScaleImage", "Unsupported rotation %d", rotation);
1220 fprintf(fd, "%f %f scale\n", pswidth * scale, psheight * scale);
1221 return (1);
1222 }
1223 }
1224
1225 return (0);
1226 }
1227
1228 /* This controls the visible portion of the page which is displayed.
1229 * N.B. Setting maxPageHeight no longer sets pageheight if not set explicitly
1230 */
1231 int psPageSize(FILE *fd, int rotation, double pgwidth, double pgheight,
1232 double reqwidth, double reqheight, double pswidth,
1233 double psheight)
1234 {
1235 double xscale = 1.0, yscale = 1.0, scale = 1.0;
1236 double splitheight;
1237 double splitwidth;
1238 double new_width;
1239 double new_height;
1240
1241 splitheight = maxPageHeight * PS_UNIT_SIZE;
1242 splitwidth = maxPageWidth * PS_UNIT_SIZE;
1243
1244 switch (rotation)
1245 {
1246 case 0:
1247 case 180:
1248 if ((splitheight > 0) || (splitwidth > 0))
1249 {
1250 if (pgwidth != 0 || pgheight != 0)
1251 {
1252 xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
1253 yscale = reqheight / (splitheight ? splitheight : psheight);
1254 scale = (xscale < yscale) ? xscale : yscale;
1255 }
1256 new_width = splitwidth ? splitwidth : scale * pswidth;
1257 new_height = splitheight ? splitheight : scale * psheight;
1258 if (strlen(pageOrientation))
1259 fprintf(fd, "%%%%PageOrientation: %s\n", pageOrientation);
1260 else
1261 fprintf(fd, "%%%%PageOrientation: %s\n",
1262 (new_width > new_height) ? "Landscape"
1263 : "Portrait");
1264 fprintf(fd,
1265 "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32 "\n",
1266 (int32_t)new_width, (int32_t)new_height);
1267 fprintf(fd,
1268 "1 dict begin /PageSize [ %f %f ] def currentdict end "
1269 "setpagedevice\n",
1270 new_width, new_height);
1271 }
1272 else /* No viewport defined with -H or -W */
1273 {
1274 if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
1275 {
1276 if (strlen(pageOrientation))
1277 fprintf(fd, "%%%%PageOrientation: %s\n",
1278 pageOrientation);
1279 else
1280 fprintf(fd, "%%%%PageOrientation: %s\n",
1281 (pswidth > psheight) ? "Landscape"
1282 : "Portrait");
1283 fprintf(fd,
1284 "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
1285 "\n",
1286 (int32_t)pswidth, (int32_t)psheight);
1287 fprintf(fd,
1288 "1 dict begin /PageSize [ %f %f ] def currentdict "
1289 "end setpagedevice\n",
1290 pswidth, psheight);
1291 }
1292 else /* Image scaled */
1293 {
1294 if (strlen(pageOrientation))
1295 fprintf(fd, "%%%%PageOrientation: %s\n",
1296 pageOrientation);
1297 else
1298 fprintf(fd, "%%%%PageOrientation: %s\n",
1299 (reqwidth > reqheight) ? "Landscape"
1300 : "Portrait");
1301 fprintf(fd,
1302 "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
1303 "\n",
1304 (int32_t)reqwidth, (int32_t)reqheight);
1305 fprintf(fd,
1306 "1 dict begin /PageSize [ %f %f ] def currentdict "
1307 "end setpagedevice\n",
1308 reqwidth, reqheight);
1309 }
1310 }
1311 break;
1312 case 90:
1313 case 270:
1314 if ((splitheight > 0) || (splitwidth > 0))
1315 {
1316 if (pgwidth != 0 || pgheight != 0)
1317 {
1318 xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
1319 yscale = reqheight / (splitheight ? splitheight : psheight);
1320 scale = (xscale < yscale) ? xscale : yscale;
1321 }
1322 new_width = splitwidth ? splitwidth : scale * psheight;
1323 new_height = splitheight ? splitheight : scale * pswidth;
1324
1325 if (strlen(pageOrientation))
1326 fprintf(fd, "%%%%PageOrientation: %s\n", pageOrientation);
1327 else
1328 fprintf(fd, "%%%%PageOrientation: %s\n",
1329 (new_width > new_height) ? "Landscape"
1330 : "Portrait");
1331 fprintf(fd,
1332 "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32 "\n",
1333 (int32_t)new_width, (int32_t)new_height);
1334 fprintf(fd,
1335 "1 dict begin /PageSize [ %f %f ] def currentdict end "
1336 "setpagedevice\n",
1337 new_width, new_height);
1338 }
1339 else
1340 {
1341 if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
1342 {
1343 if (strlen(pageOrientation))
1344 fprintf(fd, "%%%%PageOrientation: %s\n",
1345 pageOrientation);
1346 else
1347 fprintf(fd, "%%%%PageOrientation: %s\n",
1348 (psheight > pswidth) ? "Landscape"
1349 : "Portrait");
1350 fprintf(fd,
1351 "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
1352 "\n",
1353 (int32_t)psheight, (int32_t)pswidth);
1354 fprintf(fd,
1355 "1 dict begin /PageSize [ %f %f ] def currentdict "
1356 "end setpagedevice\n",
1357 psheight, pswidth);
1358 }
1359 else /* Image scaled */
1360 {
1361 if (strlen(pageOrientation))
1362 fprintf(fd, "%%%%PageOrientation: %s\n",
1363 pageOrientation);
1364 else
1365 fprintf(fd, "%%%%PageOrientation: %s\n",
1366 (reqwidth > reqheight) ? "Landscape"
1367 : "Portrait");
1368 fprintf(fd,
1369 "%%%%PageBoundingBox: 0 0 %" PRId32 " %" PRId32
1370 "\n",
1371 (int32_t)reqwidth, (int32_t)reqheight);
1372 fprintf(fd,
1373 "1 dict begin /PageSize [ %f %f ] def currentdict "
1374 "end setpagedevice\n",
1375 reqwidth, reqheight);
1376 }
1377 }
1378 break;
1379 default:
1380 TIFFError("psPageSize", "Invalid rotation %d", rotation);
1381 return (1);
1382 }
1383 fputs("<<\n /Policies <<\n /PageSize 3\n >>\n>> setpagedevice\n", fd);
1384
1385 return (0);
1386 } /* end psPageSize */
1387
1388 /* Mask an image as a series of pages, each only showing a section defined
1389 * by the maxPageHeight or maxPageWidth options.
1390 */
1391 int psMaskImage(FILE *fd, TIFF *tif, int rotation, int center, int *npages,
1392 double pixwidth, double pixheight, double left_margin,
1393 double bottom_margin, double pgwidth, double pgheight,
1394 double pswidth, double psheight, double scale)
1395 {
1396 int i, j;
1397 int ximages = 1, yimages = 1;
1398 int pages = *npages;
1399 double view_width = 0;
1400 double view_height = 0;
1401
1402 if (get_viewport(pgwidth, pgheight, pswidth, psheight, &view_width,
1403 &view_height, rotation))
1404 {
1405 TIFFError("get_viewport", "Unable to set image viewport");
1406 return (-1);
1407 }
1408
1409 if (get_subimage_count(pgwidth, pgheight, pswidth, psheight, &ximages,
1410 &yimages, rotation, scale) < 1)
1411 {
1412 TIFFError("get_subimage_count",
1413 "Invalid image count: %d columns, %d rows", ximages, yimages);
1414 return (-1);
1415 }
1416
1417 for (i = 0; i < yimages; i++)
1418 {
1419 for (j = 0; j < ximages; j++)
1420 {
1421 pages++;
1422 *npages = pages;
1423 fprintf(fd, "%%%%Page: %d %d\n", pages, pages);
1424
1425 /* Write out the PageSize info for non EPS files */
1426 if (!generateEPSF && (level2 || level3))
1427 {
1428 if (psPageSize(fd, rotation, pgwidth, pgheight, view_width,
1429 view_height, pswidth, psheight))
1430 return (-1);
1431 }
1432 fprintf(fd, "gsave\n");
1433 fprintf(fd, "100 dict begin\n");
1434 if (exportMaskedImage(fd, view_width, view_height, pswidth,
1435 psheight, i, j, left_margin, bottom_margin,
1436 scale, center, rotation))
1437 {
1438 TIFFError("exportMaskedImage", "Invalid image parameters.");
1439 return (-1);
1440 }
1441 PSpage(fd, tif, (uint32_t)pixwidth, (uint32_t)pixheight);
1442 fprintf(fd, "end\n");
1443 fprintf(fd, "grestore\n");
1444 fprintf(fd, "showpage\n");
1445 }
1446 }
1447
1448 return (pages);
1449 }
1450
1451 /* Compute scale factor and write out file header */
1452 int psStart(FILE *fd, int npages, int auto_rotate, int *rotation, double *scale,
1453 double ox, double oy, double pgwidth, double pgheight,
1454 double reqwidth, double reqheight, double pswidth, double psheight,
1455 double left_offset, double bottom_offset)
1456 {
1457 double maxsource = 0.0; /* Used for auto rotations */
1458 double maxtarget = 0.0;
1459 double xscale = 1.0, yscale = 1.0;
1460 double splitheight;
1461 double splitwidth;
1462 double view_width = 0.0, view_height = 0.0;
1463 double page_width = 0.0, page_height = 0.0;
1464
1465 /* Splitheight and splitwidth are in inches */
1466 splitheight = maxPageHeight * PS_UNIT_SIZE;
1467 splitwidth = maxPageWidth * PS_UNIT_SIZE;
1468
1469 page_width = pgwidth * PS_UNIT_SIZE;
1470 page_height = pgheight * PS_UNIT_SIZE;
1471
1472 /* If user has specified a page width and height and requested the
1473 * image to be auto-rotated to fit on that media, we match the
1474 * longest dimension of the image to the longest dimension of the
1475 * target media but we have to ignore auto rotate if user specified
1476 * maxPageHeight since this makes life way too complicated. */
1477 if (auto_rotate)
1478 {
1479 if ((splitheight != 0) || (splitwidth != 0))
1480 {
1481 TIFFError("psStart",
1482 "Auto-rotate is incompatible with page splitting ");
1483 return (1);
1484 }
1485
1486 /* Find longest edges in image and output media */
1487 maxsource = (pswidth >= psheight) ? pswidth : psheight;
1488 maxtarget = (reqwidth >= reqheight) ? reqwidth : reqheight;
1489
1490 if (((maxsource == pswidth) && (maxtarget != reqwidth)) ||
1491 ((maxsource == psheight) && (maxtarget != reqheight)))
1492 { /* optimal orientation does not match input orientation */
1493 *rotation = 90;
1494 xscale = (reqwidth - left_offset) / psheight;
1495 yscale = (reqheight - bottom_offset) / pswidth;
1496 }
1497 else /* optimal orientation matches input orientation */
1498 {
1499 xscale = (reqwidth - left_offset) / pswidth;
1500 yscale = (reqheight - bottom_offset) / psheight;
1501 }
1502 *scale = (xscale < yscale) ? xscale : yscale;
1503
1504 /* Do not scale image beyond original size */
1505 if (*scale > 1.0)
1506 *scale = 1.0;
1507
1508 /* Set the size of the displayed image to requested page size
1509 * and optimal orientation.
1510 */
1511 if (!npages)
1512 PSHead(fd, reqwidth, reqheight, ox, oy);
1513
1514 return (0);
1515 }
1516
1517 /* N.B. If pgwidth or pgheight are set from maxPageHeight/Width,
1518 * we have a problem with the tests below under splitheight.
1519 */
1520
1521 switch (*rotation) /* Auto rotate has NOT been specified */
1522 {
1523 case 0:
1524 case 180:
1525 if ((splitheight != 0) || (splitwidth != 0))
1526 { /* Viewport clipped to maxPageHeight or maxPageWidth */
1527 if ((page_width != 0) || (page_height != 0)) /* Image scaled */
1528 {
1529 xscale = (reqwidth - left_offset) /
1530 (page_width ? page_width : pswidth);
1531 yscale = (reqheight - bottom_offset) /
1532 (page_height ? page_height : psheight);
1533 *scale = (xscale < yscale) ? xscale : yscale;
1534 /*
1535 if (*scale > 1.0)
1536 *scale = 1.0;
1537 */
1538 }
1539 else /* Image clipped but not scaled */
1540 *scale = 1.0;
1541
1542 view_width = splitwidth ? splitwidth : *scale * pswidth;
1543 view_height = splitheight ? splitheight : *scale * psheight;
1544 }
1545 else /* Viewport not clipped to maxPageHeight or maxPageWidth */
1546 {
1547 if ((page_width != 0) || (page_height != 0))
1548 { /* Image scaled */
1549 xscale = (reqwidth - left_offset) / pswidth;
1550 yscale = (reqheight - bottom_offset) / psheight;
1551
1552 view_width = reqwidth;
1553 view_height = reqheight;
1554 }
1555 else
1556 { /* Image not scaled */
1557 xscale = (pswidth - left_offset) / pswidth;
1558 yscale = (psheight - bottom_offset) / psheight;
1559
1560 view_width = pswidth;
1561 view_height = psheight;
1562 }
1563 }
1564 break;
1565 case 90:
1566 case 270:
1567 if ((splitheight != 0) || (splitwidth != 0))
1568 { /* Viewport clipped to maxPageHeight or maxPageWidth */
1569 if ((page_width != 0) || (page_height != 0)) /* Image scaled */
1570 {
1571 xscale = (reqwidth - left_offset) / psheight;
1572 yscale = (reqheight - bottom_offset) / pswidth;
1573 *scale = (xscale < yscale) ? xscale : yscale;
1574 /*
1575 if (*scale > 1.0)
1576 *scale = 1.0;
1577 */
1578 }
1579 else /* Image clipped but not scaled */
1580 *scale = 1.0;
1581 view_width = splitwidth ? splitwidth : *scale * psheight;
1582 view_height = splitheight ? splitheight : *scale * pswidth;
1583 }
1584 else /* Viewport not clipped to maxPageHeight or maxPageWidth */
1585 {
1586 if ((page_width != 0) || (page_height != 0)) /* Image scaled */
1587 {
1588 xscale = (reqwidth - left_offset) / psheight;
1589 yscale = (reqheight - bottom_offset) / pswidth;
1590
1591 view_width = reqwidth;
1592 view_height = reqheight;
1593 }
1594 else
1595 {
1596 xscale = (pswidth - left_offset) / psheight;
1597 yscale = (psheight - bottom_offset) / pswidth;
1598
1599 view_width = psheight;
1600 view_height = pswidth;
1601 }
1602 }
1603 break;
1604 default:
1605 TIFFError("psPageSize", "Invalid rotation %d", *rotation);
1606 return (1);
1607 }
1608
1609 if (!npages)
1610 PSHead(fd, (page_width ? page_width : view_width),
1611 (page_height ? page_height : view_height), ox, oy);
1612
1613 *scale = (xscale < yscale) ? xscale : yscale;
1614 if (*scale > 1.0)
1615 *scale = 1.0;
1616
1617 return (0);
1618 }
1619
1620 int get_viewport(double pgwidth, double pgheight, double pswidth,
1621 double psheight, double *view_width, double *view_height,
1622 int rotation)
1623 {
1624 /* Only one of maxPageHeight or maxPageWidth can be specified */
1625 if (maxPageHeight !=
1626 0) /* Clip the viewport to maxPageHeight on each page */
1627 {
1628 if (pgheight != 0 && pgheight < maxPageHeight)
1629 *view_height = pgheight * PS_UNIT_SIZE;
1630 else
1631 *view_height = maxPageHeight * PS_UNIT_SIZE;
1632 /*
1633 * if (res_unit == RESUNIT_CENTIMETER)
1634 * *view_height /= 2.54F;
1635 */
1636 }
1637 else
1638 {
1639 if (pgheight != 0) /* User has set PageHeight with -h flag */
1640 {
1641 *view_height =
1642 pgheight *
1643 PS_UNIT_SIZE; /* Postscript size for Page Height in inches */
1644 /* if (res_unit == RESUNIT_CENTIMETER)
1645 * *view_height /= 2.54F;
1646 */
1647 }
1648 else /* If no width or height are specified, use the original size from
1649 image */
1650 switch (rotation)
1651 {
1652 default:
1653 case 0:
1654 case 180:
1655 *view_height = psheight;
1656 break;
1657 case 90:
1658 case 270:
1659 *view_height = pswidth;
1660 break;
1661 }
1662 }
1663
1664 if (maxPageWidth != 0) /* Clip the viewport to maxPageWidth on each page */
1665 {
1666 if (pgwidth != 0 && pgwidth < maxPageWidth)
1667 *view_width = pgwidth * PS_UNIT_SIZE;
1668 else
1669 *view_width = maxPageWidth * PS_UNIT_SIZE;
1670 /* if (res_unit == RESUNIT_CENTIMETER)
1671 * *view_width /= 2.54F;
1672 */
1673 }
1674 else
1675 {
1676 if (pgwidth != 0) /* User has set PageWidth with -w flag */
1677 {
1678 *view_width =
1679 pgwidth *
1680 PS_UNIT_SIZE; /* Postscript size for Page Width in inches */
1681 /* if (res_unit == RESUNIT_CENTIMETER)
1682 * *view_width /= 2.54F;
1683 */
1684 }
1685 else /* If no width or height are specified, use the original size from
1686 image */
1687 switch (rotation)
1688 {
1689 default:
1690 case 0:
1691 case 180:
1692 *view_width = pswidth;
1693 break;
1694 case 90:
1695 case 270:
1696 *view_width =
1697 psheight; /* (*view_height / psheight) * psheight; */
1698 break;
1699 }
1700 }
1701
1702 return (0);
1703 }
1704
1705 /* pgwidth and pgheight specify page width and height in inches from -h and -w
1706 * flags lm and bm are the LeftMargin and BottomMargin in inches center causes
1707 * the image to be centered on the page if the paper size is larger than the
1708 * image size returns the sequence number of the page processed or -1 on error
1709 */
1710
1711 int TIFF2PS(FILE *fd, TIFF *tif, double pgwidth, double pgheight, double lm,
1712 double bm, int center)
1713 {
1714 uint32_t pixwidth = 0, pixheight = 0; /* Image width and height in pixels */
1715 double ox = 0.0, oy = 0.0; /* Offset from current Postscript origin */
1716 double pswidth,
1717 psheight; /* Original raw image width and height in points */
1718 double view_width, view_height; /* Viewport width and height in points */
1719 double scale = 1.0;
1720 double left_offset = lm * PS_UNIT_SIZE;
1721 double bottom_offset = bm * PS_UNIT_SIZE;
1722 uint32_t subfiletype;
1723 uint16_t *sampleinfo;
1724 static int npages = 0;
1725
1726 if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
1727 ox = 0;
1728 if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
1729 oy = 0;
1730
1731 /* Consolidated all the tag information into one code segment, Richard Nolde
1732 */
1733 do
1734 {
1735 tf_numberstrips = TIFFNumberOfStrips(tif);
1736 TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &tf_rowsperstrip);
1737 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
1738 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
1739 TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfiguration);
1740 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
1741 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples,
1742 &sampleinfo);
1743 alpha = (extrasamples == 1 && sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
1744 if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))
1745 {
1746 switch (samplesperpixel - extrasamples)
1747 {
1748 case 1:
1749 if (isCCITTCompression(tif))
1750 photometric = PHOTOMETRIC_MINISWHITE;
1751 else
1752 photometric = PHOTOMETRIC_MINISBLACK;
1753 break;
1754 case 3:
1755 photometric = PHOTOMETRIC_RGB;
1756 break;
1757 case 4:
1758 photometric = PHOTOMETRIC_SEPARATED;
1759 break;
1760 }
1761 }
1762
1763 /* Read image tags for width and height in pixels pixwidth, pixheight,
1764 * and convert to points pswidth, psheight
1765 */
1766 setupPageState(tif, &pixwidth, &pixheight, &pswidth, &psheight);
1767 view_width = pswidth;
1768 view_height = psheight;
1769
1770 if (get_viewport(pgwidth, pgheight, pswidth, psheight, &view_width,
1771 &view_height, rotation_g))
1772 {
1773 TIFFError("get_viewport", "Unable to set image viewport");
1774 return (1);
1775 }
1776
1777 /* Write the Postscript file header with Bounding Box and Page Size
1778 * definitions */
1779 if (psStart(fd, npages, auto_rotate_g, &rotation_g, &scale, ox, oy,
1780 pgwidth, pgheight, view_width, view_height, pswidth,
1781 psheight, left_offset, bottom_offset))
1782 return (-1);
1783
1784 if (checkImage(tif)) /* Aborts if unsupported image parameters */
1785 {
1786 tf_bytesperrow = TIFFScanlineSize(tif);
1787
1788 /* Set viewport clipping and scaling options */
1789 if ((maxPageHeight) || (maxPageWidth) || (pgwidth != 0) ||
1790 (pgheight != 0))
1791 {
1792 if ((maxPageHeight) ||
1793 (maxPageWidth)) /* used -H or -W option */
1794 {
1795 if (psMaskImage(fd, tif, rotation_g, center, &npages,
1796 pixwidth, pixheight, left_offset,
1797 bottom_offset, pgwidth, pgheight, pswidth,
1798 psheight, scale) < 0)
1799 return (-1);
1800 }
1801 else /* N.B. Setting maxPageHeight no longer sets pgheight */
1802 {
1803 if (pgwidth != 0 || pgheight != 0)
1804 {
1805 /* User did not specify a maximum page height or width
1806 * using -H or -W flag but did use -h or -w flag to
1807 * scale to a specific size page.
1808 */
1809 npages++;
1810 fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
1811
1812 if (!generateEPSF && (level2 || level3))
1813 {
1814 /* Write out the PageSize info for non EPS files */
1815 if (psPageSize(fd, rotation_g, pgwidth, pgheight,
1816 view_width, view_height, pswidth,
1817 psheight))
1818 return (-1);
1819 }
1820 fprintf(fd, "gsave\n");
1821 fprintf(fd, "100 dict begin\n");
1822 if (psScaleImage(fd, scale, rotation_g, center,
1823 view_width, view_height, pswidth,
1824 psheight, left_offset, bottom_offset))
1825 return (-1);
1826
1827 PSpage(fd, tif, pixwidth, pixheight);
1828 fprintf(fd, "end\n");
1829 fprintf(fd, "grestore\n");
1830 fprintf(fd, "showpage\n");
1831 }
1832 }
1833 }
1834 else /* Simple rotation: user did not use -H, -W, -h or -w */
1835 {
1836 npages++;
1837 fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
1838
1839 if (!generateEPSF && (level2 || level3))
1840 {
1841 /* Write out the PageSize info for non EPS files */
1842 if (psPageSize(fd, rotation_g, pgwidth, pgheight,
1843 view_width, view_height, pswidth, psheight))
1844 return (-1);
1845 }
1846 fprintf(fd, "gsave\n");
1847 fprintf(fd, "100 dict begin\n");
1848 if (psRotateImage(fd, rotation_g, pswidth, psheight,
1849 left_offset, bottom_offset))
1850 return (-1);
1851
1852 PSpage(fd, tif, pixwidth, pixheight);
1853 fprintf(fd, "end\n");
1854 fprintf(fd, "grestore\n");
1855 fprintf(fd, "showpage\n");
1856 }
1857 }
1858 if (generateEPSF)
1859 break;
1860 if (auto_rotate_g)
1861 rotation_g = 0;
1862 TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
1863 } while (((subfiletype & FILETYPE_PAGE) || printAll) &&
1864 TIFFReadDirectory(tif));
1865
1866 return (npages);
1867 }
1868
1869 static const char DuplexPreamble[] = "\
1870 %%BeginFeature: *Duplex True\n\
1871 systemdict begin\n\
1872 /languagelevel where { pop languagelevel } { 1 } ifelse\n\
1873 2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
1874 { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
1875 } ifelse\n\
1876 end\n\
1877 %%EndFeature\n\
1878 ";
1879
1880 static const char TumblePreamble[] = "\
1881 %%BeginFeature: *Tumble True\n\
1882 systemdict begin\n\
1883 /languagelevel where { pop languagelevel } { 1 } ifelse\n\
1884 2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
1885 { statusdict /settumble known { statusdict begin true settumble end } if\n\
1886 } ifelse\n\
1887 end\n\
1888 %%EndFeature\n\
1889 ";
1890
1891 static const char AvoidDeadZonePreamble[] = "\
1892 gsave newpath clippath pathbbox grestore\n\
1893 4 2 roll 2 copy translate\n\
1894 exch 3 1 roll sub 3 1 roll sub exch\n\
1895 currentpagedevice /PageSize get aload pop\n\
1896 exch 3 1 roll div 3 1 roll div abs exch abs\n\
1897 2 copy gt { exch } if pop\n\
1898 dup 1 lt { dup scale } { pop } ifelse\n\
1899 ";
1900
1901 void PSHead(FILE *fd, double pagewidth, double pageheight, double xoff,
1902 double yoff)
1903 {
1904 time_t t;
1905
1906 t = time(0);
1907 fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
1908 fprintf(fd, "%%%%Creator: %s\n", creator ? creator : "tiff2ps");
1909 fprintf(fd, "%%%%Title: %s\n", title ? title : filename);
1910 fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
1911 fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
1912 /* NB: should use PageBoundingBox for each page instead of BoundingBox *
1913 * PageBoundingBox DSC added in PSPageSize function, R Nolde 09-01-2010
1914 */
1915 fprintf(fd, "%%%%Origin: %" PRId32 " %" PRId32 "\n", (int32_t)xoff,
1916 (int32_t)yoff);
1917 fprintf(fd, "%%%%BoundingBox: 0 0 %" PRId32 " %" PRId32 "\n",
1918 (int32_t)ceil(pagewidth), (int32_t)ceil(pageheight));
1919
1920 fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
1921 if (generateEPSF == TRUE)
1922 fprintf(fd, "%%%%Pages: 1 1\n");
1923 else
1924 fprintf(fd, "%%%%Pages: (atend)\n");
1925 fprintf(fd, "%%%%EndComments\n");
1926 if (generateEPSF == FALSE)
1927 {
1928 fprintf(fd, "%%%%BeginSetup\n");
1929 if (PSduplex)
1930 fprintf(fd, "%s", DuplexPreamble);
1931 if (PStumble)
1932 fprintf(fd, "%s", TumblePreamble);
1933 if (PSavoiddeadzone && (level2 || level3))
1934 fprintf(fd, "%s", AvoidDeadZonePreamble);
1935 fprintf(fd, "%%%%EndSetup\n");
1936 }
1937 }
1938
1939 void PSTail(FILE *fd, int npages)
1940 {
1941 fprintf(fd, "%%%%Trailer\n");
1942 if (generateEPSF == FALSE)
1943 fprintf(fd, "%%%%Pages: %d\n", npages);
1944 fprintf(fd, "%%%%EOF\n");
1945 }
1946
1947 static int checkcmap(TIFF *tif, int n, uint16_t *r, uint16_t *g, uint16_t *b)
1948 {
1949 (void)tif;
1950 while (n-- > 0)
1951 if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
1952 return (16);
1953 TIFFWarning(filename, "Assuming 8-bit colormap");
1954 return (8);
1955 }
1956
1957 static void PS_Lvl2colorspace(FILE *fd, TIFF *tif)
1958 {
1959 uint16_t *rmap, *gmap, *bmap;
1960 int i, num_colors;
1961 const char *colorspace_p;
1962
1963 switch (photometric)
1964 {
1965 case PHOTOMETRIC_SEPARATED:
1966 colorspace_p = "CMYK";
1967 break;
1968
1969 case PHOTOMETRIC_RGB:
1970 colorspace_p = "RGB";
1971 break;
1972
1973 default:
1974 colorspace_p = "Gray";
1975 }
1976
1977 /*
1978 * Set up PostScript Level 2 colorspace according to
1979 * section 4.8 in the PostScript reference manual.
1980 */
1981 fputs("% PostScript Level 2 only.\n", fd);
1982 if (photometric != PHOTOMETRIC_PALETTE)
1983 {
1984 if (photometric == PHOTOMETRIC_YCBCR)
1985 {
1986 /* MORE CODE HERE */
1987 }
1988 fprintf(fd, "/Device%s setcolorspace\n", colorspace_p);
1989 return;
1990 }
1991
1992 /*
1993 * Set up an indexed/palette colorspace
1994 */
1995 num_colors = (1 << bitspersample);
1996 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
1997 {
1998 TIFFError(filename, "Palette image w/o \"Colormap\" tag");
1999 return;
2000 }
2001 if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16)
2002 {
2003 /*
2004 * Convert colormap to 8-bits values.
2005 */
2006 #define CVT(x) (((x)*255) / ((1L << 16) - 1))
2007 for (i = 0; i < num_colors; i++)
2008 {
2009 rmap[i] = CVT(rmap[i]);
2010 gmap[i] = CVT(gmap[i]);
2011 bmap[i] = CVT(bmap[i]);
2012 }
2013 #undef CVT
2014 }
2015 fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
2016 if (ascii85_g)
2017 {
2018 Ascii85Init();
2019 fputs("\n<~", fd);
2020 ascii85breaklen -= 2;
2021 }
2022 else
2023 fputs(" <", fd);
2024 for (i = 0; i < num_colors; i++)
2025 {
2026 if (ascii85_g)
2027 {
2028 Ascii85Put((unsigned char)rmap[i], fd);
2029 Ascii85Put((unsigned char)gmap[i], fd);
2030 Ascii85Put((unsigned char)bmap[i], fd);
2031 }
2032 else
2033 {
2034 fputs((i % 8) ? " " : "\n ", fd);
2035 fprintf(fd, "%02" PRIx16 "%02" PRIx16 "%02" PRIx16 "", rmap[i],
2036 gmap[i], bmap[i]);
2037 }
2038 }
2039 if (ascii85_g)
2040 Ascii85Flush(fd);
2041 else
2042 fputs(">\n", fd);
2043 fputs("] setcolorspace\n", fd);
2044 }
2045
2046 static int PS_Lvl2ImageDict(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
2047 {
2048 int use_rawdata;
2049 uint32_t tile_width, tile_height;
2050 uint16_t predictor, minsamplevalue, maxsamplevalue;
2051 uint32_t repeat_count;
2052 char im_h[64], im_x[64], im_y[64];
2053 const char *imageOp = "image";
2054
2055 if (useImagemask && (bitspersample == 1))
2056 imageOp = "imagemask";
2057
2058 (void)strcpy(im_x, "0");
2059 (void)snprintf(im_y, sizeof(im_y), "%" PRIu32, h);
2060 (void)snprintf(im_h, sizeof(im_h), "%" PRIu32, h);
2061 tile_width = w;
2062 tile_height = h;
2063 if (TIFFIsTiled(tif))
2064 {
2065 repeat_count = TIFFNumberOfTiles(tif);
2066 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
2067 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
2068 if (tile_width > w || tile_height > h || (w % tile_width) != 0 ||
2069 (h % tile_height != 0))
2070 {
2071 /*
2072 * The tiles does not fit image width and height.
2073 * Set up a clip rectangle for the image unit square.
2074 */
2075 fputs("0 0 1 1 rectclip\n", fd);
2076 }
2077 if (tile_width < w)
2078 {
2079 fputs("/im_x 0 def\n", fd);
2080 (void)strcpy(im_x, "im_x neg");
2081 }
2082 if (tile_height < h)
2083 {
2084 fputs("/im_y 0 def\n", fd);
2085 (void)snprintf(im_y, sizeof(im_y), "%" PRIu32 " im_y sub", h);
2086 }
2087 }
2088 else
2089 {
2090 repeat_count = tf_numberstrips;
2091 tile_height = tf_rowsperstrip;
2092 if (tile_height > h)
2093 tile_height = h;
2094 if (repeat_count > 1)
2095 {
2096 fputs("/im_y 0 def\n", fd);
2097 fprintf(fd, "/im_h %" PRIu32 " def\n", tile_height);
2098 (void)strcpy(im_h, "im_h");
2099 (void)snprintf(im_y, sizeof(im_y), "%" PRIu32 " im_y sub", h);
2100 }
2101 }
2102
2103 /*
2104 * Output start of exec block
2105 */
2106 fputs("{ % exec\n", fd);
2107
2108 if (repeat_count > 1)
2109 fprintf(fd, "%" PRIu32 " { %% repeat\n", repeat_count);
2110
2111 /*
2112 * Output filter options and image dictionary.
2113 */
2114 if (ascii85_g)
2115 fputs(" /im_stream currentfile /ASCII85Decode filter def\n", fd);
2116 fputs(" <<\n", fd);
2117 fputs(" /ImageType 1\n", fd);
2118 fprintf(fd, " /Width %" PRIu32 "\n", tile_width);
2119 /*
2120 * Workaround for some software that may crash when last strip
2121 * of image contains fewer number of scanlines than specified
2122 * by the `/Height' variable. So for stripped images with multiple
2123 * strips we will set `/Height' as `im_h', because one is
2124 * recalculated for each strip - including the (smaller) final strip.
2125 * For tiled images and images with only one strip `/Height' will
2126 * contain number of scanlines in tile (or image height in case of
2127 * one-stripped image).
2128 */
2129 if (TIFFIsTiled(tif) || tf_numberstrips == 1)
2130 fprintf(fd, " /Height %" PRIu32 "\n", tile_height);
2131 else
2132 fprintf(fd, " /Height im_h\n");
2133
2134 if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
2135 fputs(" /MultipleDataSources true\n", fd);
2136 fprintf(fd, " /ImageMatrix [ %" PRIu32 " 0 0 %" PRId32 " %s %s ]\n", w,
2137 -(int32_t)h, im_x, im_y);
2138 fprintf(fd, " /BitsPerComponent %" PRIu16 "\n", bitspersample);
2139 fprintf(fd, " /Interpolate %s\n", interpolate ? "true" : "false");
2140
2141 switch (samplesperpixel - extrasamples)
2142 {
2143 case 1:
2144 switch (photometric)
2145 {
2146 case PHOTOMETRIC_MINISBLACK:
2147 fputs(" /Decode [0 1]\n", fd);
2148 break;
2149 case PHOTOMETRIC_MINISWHITE:
2150 switch (compression)
2151 {
2152 case COMPRESSION_CCITTRLE:
2153 case COMPRESSION_CCITTRLEW:
2154 case COMPRESSION_CCITTFAX3:
2155 case COMPRESSION_CCITTFAX4:
2156 /*
2157 * Manage inverting with /Blackis1 flag
2158 * since there might be uncompressed parts
2159 */
2160 fputs(" /Decode [0 1]\n", fd);
2161 break;
2162 default:
2163 /*
2164 * ERROR...
2165 */
2166 fputs(" /Decode [1 0]\n", fd);
2167 break;
2168 }
2169 break;
2170 case PHOTOMETRIC_PALETTE:
2171 TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
2172 &minsamplevalue);
2173 TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
2174 &maxsamplevalue);
2175 fprintf(fd, " /Decode [%" PRIu16 " %" PRIu16 "]\n",
2176 minsamplevalue, maxsamplevalue);
2177 break;
2178 default:
2179 /*
2180 * ERROR ?
2181 */
2182 fputs(" /Decode [0 1]\n", fd);
2183 break;
2184 }
2185 break;
2186 case 3:
2187 switch (photometric)
2188 {
2189 case PHOTOMETRIC_RGB:
2190 fputs(" /Decode [0 1 0 1 0 1]\n", fd);
2191 break;
2192 case PHOTOMETRIC_MINISWHITE:
2193 case PHOTOMETRIC_MINISBLACK:
2194 default:
2195 /*
2196 * ERROR??
2197 */
2198 fputs(" /Decode [0 1 0 1 0 1]\n", fd);
2199 break;
2200 }
2201 break;
2202 case 4:
2203 /*
2204 * ERROR??
2205 */
2206 fputs(" /Decode [0 1 0 1 0 1 0 1]\n", fd);
2207 break;
2208 }
2209 fputs(" /DataSource", fd);
2210 if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
2211 fputs(" [", fd);
2212 if (ascii85_g)
2213 fputs(" im_stream", fd);
2214 else
2215 fputs(" currentfile /ASCIIHexDecode filter", fd);
2216
2217 use_rawdata = TRUE;
2218 switch (compression)
2219 {
2220 case COMPRESSION_NONE: /* 1: uncompressed */
2221 break;
2222 case COMPRESSION_CCITTRLE: /* 2: CCITT modified Huffman RLE */
2223 case COMPRESSION_CCITTRLEW: /* 32771: #1 w/ word alignment */
2224 case COMPRESSION_CCITTFAX3: /* 3: CCITT Group 3 fax encoding */
2225 case COMPRESSION_CCITTFAX4: /* 4: CCITT Group 4 fax encoding */
2226 fputs("\n\t<<\n", fd);
2227 if (compression == COMPRESSION_CCITTFAX3)
2228 {
2229 uint32_t g3_options;
2230
2231 fputs("\t /EndOfLine true\n", fd);
2232 fputs("\t /EndOfBlock false\n", fd);
2233 if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS, &g3_options))
2234 g3_options = 0;
2235 if (g3_options & GROUP3OPT_2DENCODING)
2236 fprintf(fd, "\t /K %s\n", im_h);
2237 if (g3_options & GROUP3OPT_UNCOMPRESSED)
2238 fputs("\t /Uncompressed true\n", fd);
2239 if (g3_options & GROUP3OPT_FILLBITS)
2240 fputs("\t /EncodedByteAlign true\n", fd);
2241 }
2242 if (compression == COMPRESSION_CCITTFAX4)
2243 {
2244 uint32_t g4_options;
2245
2246 fputs("\t /K -1\n", fd);
2247 TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS, &g4_options);
2248 if (g4_options & GROUP4OPT_UNCOMPRESSED)
2249 fputs("\t /Uncompressed true\n", fd);
2250 }
2251 if (!(tile_width == w && w == 1728U))
2252 fprintf(fd, "\t /Columns %" PRIu32 "\n", tile_width);
2253 fprintf(fd, "\t /Rows %s\n", im_h);
2254 if (compression == COMPRESSION_CCITTRLE ||
2255 compression == COMPRESSION_CCITTRLEW)
2256 {
2257 fputs("\t /EncodedByteAlign true\n", fd);
2258 fputs("\t /EndOfBlock false\n", fd);
2259 }
2260 if (photometric == PHOTOMETRIC_MINISBLACK)
2261 fputs("\t /BlackIs1 true\n", fd);
2262 fprintf(fd, "\t>> /CCITTFaxDecode filter");
2263 break;
2264 case COMPRESSION_LZW: /* 5: Lempel-Ziv & Welch */
2265 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
2266 if (predictor == 2)
2267 {
2268 fputs("\n\t<<\n", fd);
2269 fprintf(fd, "\t /Predictor %" PRIu16 "\n", predictor);
2270 fprintf(fd, "\t /Columns %" PRIu32 "\n", tile_width);
2271 fprintf(fd, "\t /Colors %" PRIu16 "\n", samplesperpixel);
2272 fprintf(fd, "\t /BitsPerComponent %" PRIu16 "\n",
2273 bitspersample);
2274 fputs("\t>>", fd);
2275 }
2276 fputs(" /LZWDecode filter", fd);
2277 break;
2278 case COMPRESSION_DEFLATE: /* 5: ZIP */
2279 case COMPRESSION_ADOBE_DEFLATE:
2280 if (level3)
2281 {
2282 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
2283 if (predictor > 1)
2284 {
2285 fprintf(fd, "\t %% PostScript Level 3 only.");
2286 fputs("\n\t<<\n", fd);
2287 fprintf(fd, "\t /Predictor %" PRIu16 "\n", predictor);
2288 fprintf(fd, "\t /Columns %" PRIu32 "\n", tile_width);
2289 fprintf(fd, "\t /Colors %" PRIu16 "\n", samplesperpixel);
2290 fprintf(fd, "\t /BitsPerComponent %" PRIu16 "\n",
2291 bitspersample);
2292 fputs("\t>>", fd);
2293 }
2294 fputs(" /FlateDecode filter", fd);
2295 }
2296 else
2297 {
2298 use_rawdata = FALSE;
2299 }
2300 break;
2301 case COMPRESSION_PACKBITS: /* 32773: Macintosh RLE */
2302 fputs(" /RunLengthDecode filter", fd);
2303 use_rawdata = TRUE;
2304 break;
2305 case COMPRESSION_OJPEG: /* 6: !6.0 JPEG */
2306 case COMPRESSION_JPEG: /* 7: %JPEG DCT compression */
2307 #ifdef notdef
2308 /*
2309 * Code not tested yet
2310 */
2311 fputs(" /DCTDecode filter", fd);
2312 use_rawdata = TRUE;
2313 #else
2314 use_rawdata = FALSE;
2315 #endif
2316 break;
2317 case COMPRESSION_NEXT: /* 32766: NeXT 2-bit RLE */
2318 case COMPRESSION_THUNDERSCAN: /* 32809: ThunderScan RLE */
2319 case COMPRESSION_PIXARFILM: /* 32908: Pixar companded 10bit LZW */
2320 case COMPRESSION_JBIG: /* 34661: ISO JBIG */
2321 use_rawdata = FALSE;
2322 break;
2323 case COMPRESSION_SGILOG: /* 34676: SGI LogL or LogLuv */
2324 case COMPRESSION_SGILOG24: /* 34677: SGI 24-bit LogLuv */
2325 use_rawdata = FALSE;
2326 break;
2327 default:
2328 /*
2329 * ERROR...
2330 */
2331 use_rawdata = FALSE;
2332 break;
2333 }
2334 if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
2335 {
2336 uint16_t i;
2337
2338 /*
2339 * NOTE: This code does not work yet...
2340 */
2341 for (i = 1; i < samplesperpixel; i++)
2342 fputs(" dup", fd);
2343 fputs(" ]", fd);
2344 }
2345
2346 fprintf(fd, "\n >> %s\n", imageOp);
2347 if (ascii85_g)
2348 fputs(" im_stream status { im_stream flushfile } if\n", fd);
2349 if (repeat_count > 1)
2350 {
2351 if (tile_width < w)
2352 {
2353 fprintf(fd, " /im_x im_x %" PRIu32 " add def\n", tile_width);
2354 if (tile_height < h)
2355 {
2356 fprintf(fd, " im_x %" PRIu32 " ge {\n", w);
2357 fputs(" /im_x 0 def\n", fd);
2358 fprintf(fd, " /im_y im_y %" PRIu32 " add def\n", tile_height);
2359 fputs(" } if\n", fd);
2360 }
2361 }
2362 if (tile_height < h)
2363 {
2364 if (tile_width >= w)
2365 {
2366 fprintf(fd, " /im_y im_y %" PRIu32 " add def\n", tile_height);
2367 if (!TIFFIsTiled(tif))
2368 {
2369 fprintf(fd, " /im_h %" PRIu32 " im_y sub", h);
2370 fprintf(fd, " dup %" PRIu32 " gt { pop", tile_height);
2371 fprintf(fd, " %" PRIu32 " } if def\n", tile_height);
2372 }
2373 }
2374 }
2375 fputs("} repeat\n", fd);
2376 }
2377 /*
2378 * End of exec function
2379 */
2380 fputs("}\n", fd);
2381
2382 return (use_rawdata);
2383 }
2384
2385 /* Flip the byte order of buffers with 16 bit samples */
2386 static void PS_FlipBytes(unsigned char *buf, tsize_t count)
2387 {
2388 int i;
2389 unsigned char temp;
2390
2391 if (count <= 0 || bitspersample <= 8)
2392 {
2393 return;
2394 }
2395
2396 count--;
2397
2398 for (i = 0; i < count; i += 2)
2399 {
2400 temp = buf[i];
2401 buf[i] = buf[i + 1];
2402 buf[i + 1] = temp;
2403 }
2404 }
2405
2406 #define MAXLINE 36
2407
2408 int PS_Lvl2page(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
2409 {
2410 uint16_t fillorder;
2411 int use_rawdata, tiled_image, breaklen = MAXLINE;
2412 uint32_t chunk_no, num_chunks;
2413 uint64_t *bc;
2414 unsigned char *buf_data, *cp;
2415 tsize_t chunk_size, byte_count;
2416
2417 #if defined(EXP_ASCII85ENCODER)
2418 tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
2419 uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
2420 #endif
2421
2422 PS_Lvl2colorspace(fd, tif);
2423 use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
2424
2425 /* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
2426 #ifdef ENABLE_BROKEN_BEGINENDDATA
2427 fputs("%%BeginData:\n", fd);
2428 #endif
2429 fputs("exec\n", fd);
2430
2431 tiled_image = TIFFIsTiled(tif);
2432 if (tiled_image)
2433 {
2434 num_chunks = TIFFNumberOfTiles(tif);
2435 TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
2436 }
2437 else
2438 {
2439 num_chunks = TIFFNumberOfStrips(tif);
2440 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
2441 }
2442
2443 if (use_rawdata)
2444 {
2445 chunk_size = (tsize_t)bc[0];
2446 for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
2447 if ((tsize_t)bc[chunk_no] > chunk_size)
2448 chunk_size = (tsize_t)bc[chunk_no];
2449 }
2450 else
2451 {
2452 if (tiled_image)
2453 chunk_size = TIFFTileSize(tif);
2454 else
2455 chunk_size = TIFFStripSize(tif);
2456 }
2457 buf_data = (unsigned char *)limitMalloc(chunk_size);
2458 if (!buf_data)
2459 {
2460 TIFFError(filename, "Can't alloc %" TIFF_SSIZE_FORMAT " bytes for %s.",
2461 chunk_size, tiled_image ? "tiles" : "strips");
2462 return (FALSE);
2463 }
2464
2465 #if defined(EXP_ASCII85ENCODER)
2466 if (ascii85_g)
2467 {
2468 /*
2469 * Allocate a buffer to hold the ASCII85 encoded data. Note
2470 * that it is allocated with sufficient room to hold the
2471 * encoded data (5*chunk_size/4) plus the EOD marker (+8)
2472 * and formatting line breaks. The line breaks are more
2473 * than taken care of by using 6*chunk_size/4 rather than
2474 * 5*chunk_size/4.
2475 */
2476
2477 ascii85_p = limitMalloc((chunk_size + (chunk_size / 2)) + 8);
2478
2479 if (!ascii85_p)
2480 {
2481 _TIFFfree(buf_data);
2482
2483 TIFFError(filename, "Cannot allocate ASCII85 encoding buffer.");
2484 return (FALSE);
2485 }
2486 }
2487 #endif
2488
2489 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
2490 for (chunk_no = 0; chunk_no < num_chunks; chunk_no++)
2491 {
2492 if (ascii85_g)
2493 Ascii85Init();
2494 else
2495 breaklen = MAXLINE;
2496 if (use_rawdata)
2497 {
2498 if (tiled_image)
2499 byte_count =
2500 TIFFReadRawTile(tif, chunk_no, buf_data, chunk_size);
2501 else
2502 byte_count =
2503 TIFFReadRawStrip(tif, chunk_no, buf_data, chunk_size);
2504 if (fillorder == FILLORDER_LSB2MSB)
2505 TIFFReverseBits(buf_data, byte_count);
2506 }
2507 else
2508 {
2509 if (tiled_image)
2510 byte_count =
2511 TIFFReadEncodedTile(tif, chunk_no, buf_data, chunk_size);
2512 else
2513 byte_count =
2514 TIFFReadEncodedStrip(tif, chunk_no, buf_data, chunk_size);
2515 }
2516 if (byte_count < 0)
2517 {
2518 TIFFError(filename, "Can't read %s %" PRIu32 ".",
2519 tiled_image ? "tile" : "strip", chunk_no);
2520 if (ascii85_g)
2521 Ascii85Put('\0', fd);
2522 }
2523 /*
2524 * for 16 bits, the two bytes must be most significant
2525 * byte first
2526 */
2527 if (bitspersample == 16 && !TIFFIsBigEndian(tif))
2528 {
2529 PS_FlipBytes(buf_data, byte_count);
2530 }
2531 /*
2532 * For images with alpha, matte against a white background;
2533 * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
2534 * lower part of the buffer with the modified values.
2535 *
2536 * XXX: needs better solution
2537 */
2538 if (alpha)
2539 {
2540 int adjust, i, j = 0;
2541 int ncomps = samplesperpixel - extrasamples;
2542 for (i = 0; (i + ncomps) < byte_count; i += samplesperpixel)
2543 {
2544 adjust = 255 - buf_data[i + ncomps];
2545 switch (ncomps)
2546 {
2547 case 1:
2548 buf_data[j++] = buf_data[i] + adjust;
2549 break;
2550 case 2:
2551 buf_data[j++] = buf_data[i] + adjust;
2552 buf_data[j++] = buf_data[i + 1] + adjust;
2553 break;
2554 case 3:
2555 buf_data[j++] = buf_data[i] + adjust;
2556 buf_data[j++] = buf_data[i + 1] + adjust;
2557 buf_data[j++] = buf_data[i + 2] + adjust;
2558 break;
2559 }
2560 }
2561 byte_count -= j;
2562 }
2563
2564 if (ascii85_g)
2565 {
2566 #if defined(EXP_ASCII85ENCODER)
2567 ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count);
2568
2569 if (ascii85_l > 0)
2570 fwrite(ascii85_p, ascii85_l, 1, fd);
2571 #else
2572 for (cp = buf_data; byte_count > 0; byte_count--)
2573 Ascii85Put(*cp++, fd);
2574 #endif
2575 }
2576 else
2577 {
2578 for (cp = buf_data; byte_count > 0; byte_count--)
2579 {
2580 putc(hex[((*cp) >> 4) & 0xf], fd);
2581 putc(hex[(*cp) & 0xf], fd);
2582 cp++;
2583
2584 if (--breaklen <= 0)
2585 {
2586 putc('\n', fd);
2587 breaklen = MAXLINE;
2588 }
2589 }
2590 }
2591
2592 if (!ascii85_g)
2593 {
2594 if (level2 || level3)
2595 putc('>', fd);
2596 putc('\n', fd);
2597 }
2598 #if !defined(EXP_ASCII85ENCODER)
2599 else
2600 Ascii85Flush(fd);
2601 #endif
2602 }
2603
2604 #if defined(EXP_ASCII85ENCODER)
2605 if (ascii85_p)
2606 _TIFFfree(ascii85_p);
2607 #endif
2608
2609 _TIFFfree(buf_data);
2610 #ifdef ENABLE_BROKEN_BEGINENDDATA
2611 fputs("%%EndData\n", fd);
2612 #endif
2613 return (TRUE);
2614 }
2615
2616 void PSpage(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
2617 {
2618 char *imageOp = "image";
2619
2620 if (useImagemask && (bitspersample == 1))
2621 imageOp = "imagemask";
2622
2623 if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
2624 return;
2625 ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8) * w;
2626 switch (photometric)
2627 {
2628 case PHOTOMETRIC_RGB:
2629 if (planarconfiguration == PLANARCONFIG_CONTIG)
2630 {
2631 fprintf(fd, "%s", RGBcolorimage);
2632 PSColorContigPreamble(fd, w, h, 3);
2633 PSDataColorContig(fd, tif, w, h, 3);
2634 }
2635 else
2636 {
2637 PSColorSeparatePreamble(fd, w, h, 3);
2638 PSDataColorSeparate(fd, tif, w, h, 3);
2639 }
2640 break;
2641 case PHOTOMETRIC_SEPARATED:
2642 /* XXX should emit CMYKcolorimage */
2643 if (planarconfiguration == PLANARCONFIG_CONTIG)
2644 {
2645 PSColorContigPreamble(fd, w, h, 4);
2646 PSDataColorContig(fd, tif, w, h, 4);
2647 }
2648 else
2649 {
2650 PSColorSeparatePreamble(fd, w, h, 4);
2651 PSDataColorSeparate(fd, tif, w, h, 4);
2652 }
2653 break;
2654 case PHOTOMETRIC_PALETTE:
2655 fprintf(fd, "%s", RGBcolorimage);
2656 PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
2657 fprintf(fd, "/scanLine %" TIFF_SSIZE_FORMAT " string def\n",
2658 ps_bytesperrow * 3);
2659 fprintf(fd, "%" PRIu32 " %" PRIu32 " 8\n", w, h);
2660 fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "]\n", w, h,
2661 h);
2662 fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
2663 fprintf(fd, "false 3 colorimage\n");
2664 PSDataPalette(fd, tif, w, h);
2665 break;
2666 case PHOTOMETRIC_MINISBLACK:
2667 case PHOTOMETRIC_MINISWHITE:
2668 PhotoshopBanner(fd, w, h, 1, 1, imageOp);
2669 fprintf(fd, "/scanLine %" TIFF_SSIZE_FORMAT " string def\n",
2670 ps_bytesperrow);
2671 fprintf(fd, "%" PRIu32 " %" PRIu32 " %" PRIu16 "\n", w, h,
2672 bitspersample);
2673 fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "]\n", w, h,
2674 h);
2675 fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
2676 fprintf(fd, "%s\n", imageOp);
2677 PSDataBW(fd, tif, w, h);
2678 break;
2679 }
2680 putc('\n', fd);
2681 }
2682
2683 void PSColorContigPreamble(FILE *fd, uint32_t w, uint32_t h, int nc)
2684 {
2685 ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
2686 PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
2687 fprintf(fd, "/line %" TIFF_SSIZE_FORMAT " string def\n", ps_bytesperrow);
2688 fprintf(fd, "%" PRIu32 " %" PRIu32 " %" PRIu16 "\n", w, h, bitspersample);
2689 fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "]\n", w, h, h);
2690 fprintf(fd, "{currentfile line readhexstring pop} bind\n");
2691 fprintf(fd, "false %d colorimage\n", nc);
2692 }
2693
2694 void PSColorSeparatePreamble(FILE *fd, uint32_t w, uint32_t h, int nc)
2695 {
2696 int i;
2697
2698 PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
2699 for (i = 0; i < nc; i++)
2700 fprintf(fd, "/line%d %" TIFF_SSIZE_FORMAT " string def\n", i,
2701 ps_bytesperrow);
2702 fprintf(fd, "%" PRIu32 " %" PRIu32 " %" PRIu16 "\n", w, h, bitspersample);
2703 fprintf(fd, "[%" PRIu32 " 0 0 -%" PRIu32 " 0 %" PRIu32 "] \n", w, h, h);
2704 for (i = 0; i < nc; i++)
2705 fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
2706 fprintf(fd, "true %d colorimage\n", nc);
2707 }
2708
2709 #define DOBREAK(len, howmany, fd) \
2710 if (((len) -= (howmany)) <= 0) \
2711 { \
2712 putc('\n', fd); \
2713 (len) = MAXLINE - (howmany); \
2714 }
2715
2716 static inline void puthex(unsigned int c, FILE *fd)
2717 {
2718 putc(hex[((c) >> 4) & 0xf], fd);
2719 putc(hex[(c)&0xf], fd);
2720 }
2721
2722 void PSDataColorContig(FILE *fd, TIFF *tif, uint32_t w, uint32_t h, int nc)
2723 {
2724 uint32_t row;
2725 int breaklen = MAXLINE, es = samplesperpixel - nc;
2726 tsize_t cc;
2727 unsigned char *tf_buf;
2728 unsigned char *cp, c;
2729
2730 (void)w;
2731 if (es < 0)
2732 {
2733 TIFFError(filename,
2734 "Inconsistent value of es: %d (samplesperpixel=%" PRIu16
2735 ", nc=%d)",
2736 es, samplesperpixel, nc);
2737 return;
2738 }
2739 tf_buf = (unsigned char *)limitMalloc(tf_bytesperrow);
2740 if (tf_buf == NULL)
2741 {
2742 TIFFError(filename, "No space for scanline buffer");
2743 return;
2744 }
2745 for (row = 0; row < h; row++)
2746 {
2747 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
2748 break;
2749 cp = tf_buf;
2750 /*
2751 * for 16 bits, the two bytes must be most significant
2752 * byte first
2753 */
2754 if (bitspersample == 16 && !HOST_BIGENDIAN)
2755 {
2756 PS_FlipBytes(cp, tf_bytesperrow);
2757 }
2758 if (alpha)
2759 {
2760 int adjust;
2761 /*
2762 * the code inside this loop reads nc bytes + 1 extra byte (for
2763 * adjust)
2764 */
2765 for (cc = 0; (cc + nc) < tf_bytesperrow; cc += samplesperpixel)
2766 {
2767 DOBREAK(breaklen, nc, fd);
2768 /*
2769 * For images with alpha, matte against
2770 * a white background; i.e.
2771 * Cback * (1 - Aimage)
2772 * where Cback = 1.
2773 */
2774 adjust = 255 - cp[nc];
2775 for (int i = 0; i < nc; ++i)
2776 {
2777 c = *cp++ + adjust;
2778 puthex(c, fd);
2779 }
2780 cp += es;
2781 }
2782 }
2783 else
2784 {
2785 /*
2786 * the code inside this loop reads nc bytes per iteration
2787 */
2788 for (cc = 0; (cc + nc) <= tf_bytesperrow; cc += samplesperpixel)
2789 {
2790 DOBREAK(breaklen, nc, fd);
2791 for (int i = 0; i < nc; ++i)
2792 {
2793 c = *cp++;
2794 puthex(c, fd);
2795 }
2796 cp += es;
2797 }
2798 }
2799 }
2800 _TIFFfree((char *)tf_buf);
2801 }
2802
2803 void PSDataColorSeparate(FILE *fd, TIFF *tif, uint32_t w, uint32_t h, int nc)
2804 {
2805 uint32_t row;
2806 int breaklen = MAXLINE;
2807 tsize_t cc;
2808 tsample_t s, maxs;
2809 unsigned char *tf_buf;
2810 unsigned char *cp, c;
2811
2812 (void)w;
2813 tf_buf = (unsigned char *)limitMalloc(tf_bytesperrow);
2814 if (tf_buf == NULL)
2815 {
2816 TIFFError(filename, "No space for scanline buffer");
2817 return;
2818 }
2819 maxs = (samplesperpixel > nc ? nc : samplesperpixel);
2820 for (row = 0; row < h; row++)
2821 {
2822 for (s = 0; s < maxs; s++)
2823 {
2824 if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
2825 goto end_loop;
2826 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++)
2827 {
2828 DOBREAK(breaklen, 1, fd);
2829 c = *cp++;
2830 puthex(c, fd);
2831 }
2832 }
2833 }
2834 end_loop:
2835 _TIFFfree((char *)tf_buf);
2836 }
2837
2838 #define PUTRGBHEX(c, fd) \
2839 puthex(rmap[c], fd); \
2840 puthex(gmap[c], fd); \
2841 puthex(bmap[c], fd)
2842
2843 void PSDataPalette(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
2844 {
2845 uint16_t *rmap, *gmap, *bmap;
2846 uint32_t row;
2847 int breaklen = MAXLINE, nc;
2848 tsize_t cc;
2849 unsigned char *tf_buf;
2850 unsigned char *cp, c;
2851
2852 (void)w;
2853 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
2854 {
2855 TIFFError(filename, "Palette image w/o \"Colormap\" tag");
2856 return;
2857 }
2858 switch (bitspersample)
2859 {
2860 case 8:
2861 case 4:
2862 case 2:
2863 case 1:
2864 break;
2865 default:
2866 TIFFError(filename, "Depth %" PRIu16 " not supported",
2867 bitspersample);
2868 return;
2869 }
2870 nc = 3 * (8 / bitspersample);
2871 tf_buf = (unsigned char *)limitMalloc(tf_bytesperrow);
2872 if (tf_buf == NULL)
2873 {
2874 TIFFError(filename, "No space for scanline buffer");
2875 return;
2876 }
2877 if (checkcmap(tif, 1 << bitspersample, rmap, gmap, bmap) == 16)
2878 {
2879 int i;
2880 #define CVT(x) ((unsigned short)(((x)*255) / ((1U << 16) - 1)))
2881 for (i = (1 << bitspersample) - 1; i >= 0; i--)
2882 {
2883 rmap[i] = CVT(rmap[i]);
2884 gmap[i] = CVT(gmap[i]);
2885 bmap[i] = CVT(bmap[i]);
2886 }
2887 #undef CVT
2888 }
2889 for (row = 0; row < h; row++)
2890 {
2891 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
2892 goto end_loop;
2893 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++)
2894 {
2895 DOBREAK(breaklen, nc, fd);
2896 switch (bitspersample)
2897 {
2898 case 8:
2899 c = *cp++;
2900 PUTRGBHEX(c, fd);
2901 break;
2902 case 4:
2903 c = *cp++;
2904 PUTRGBHEX(c & 0xf, fd);
2905 c >>= 4;
2906 PUTRGBHEX(c, fd);
2907 break;
2908 case 2:
2909 c = *cp++;
2910 PUTRGBHEX(c & 0x3, fd);
2911 c >>= 2;
2912 PUTRGBHEX(c & 0x3, fd);
2913 c >>= 2;
2914 PUTRGBHEX(c & 0x3, fd);
2915 c >>= 2;
2916 PUTRGBHEX(c, fd);
2917 break;
2918 case 1:
2919 c = *cp++;
2920 PUTRGBHEX(c & 0x1, fd);
2921 c >>= 1;
2922 PUTRGBHEX(c & 0x1, fd);
2923 c >>= 1;
2924 PUTRGBHEX(c & 0x1, fd);
2925 c >>= 1;
2926 PUTRGBHEX(c & 0x1, fd);
2927 c >>= 1;
2928 PUTRGBHEX(c & 0x1, fd);
2929 c >>= 1;
2930 PUTRGBHEX(c & 0x1, fd);
2931 c >>= 1;
2932 PUTRGBHEX(c & 0x1, fd);
2933 c >>= 1;
2934 PUTRGBHEX(c, fd);
2935 break;
2936 }
2937 }
2938 }
2939 end_loop:
2940 _TIFFfree((char *)tf_buf);
2941 }
2942
2943 void PSDataBW(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
2944 {
2945 int breaklen = MAXLINE;
2946 unsigned char *tf_buf;
2947 unsigned char *cp;
2948 tsize_t stripsize = TIFFStripSize(tif);
2949 tstrip_t s;
2950
2951 #if defined(EXP_ASCII85ENCODER)
2952 tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
2953 uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
2954 #endif
2955
2956 (void)w;
2957 (void)h;
2958 tf_buf = (unsigned char *)limitMalloc(stripsize);
2959 if (tf_buf == NULL)
2960 {
2961 TIFFError(filename, "No space for scanline buffer");
2962 return;
2963 }
2964
2965 // FIXME
2966 memset(tf_buf, 0, stripsize);
2967
2968 #if defined(EXP_ASCII85ENCODER)
2969 if (ascii85_g)
2970 {
2971 /*
2972 * Allocate a buffer to hold the ASCII85 encoded data. Note
2973 * that it is allocated with sufficient room to hold the
2974 * encoded data (5*stripsize/4) plus the EOD marker (+8)
2975 * and formatting line breaks. The line breaks are more
2976 * than taken care of by using 6*stripsize/4 rather than
2977 * 5*stripsize/4.
2978 */
2979
2980 ascii85_p = limitMalloc((stripsize + (stripsize / 2)) + 8);
2981
2982 if (!ascii85_p)
2983 {
2984 _TIFFfree(tf_buf);
2985
2986 TIFFError(filename, "Cannot allocate ASCII85 encoding buffer.");
2987 return;
2988 }
2989 }
2990 #endif
2991
2992 if (ascii85_g)
2993 Ascii85Init();
2994
2995 for (s = 0; s < TIFFNumberOfStrips(tif); s++)
2996 {
2997 tmsize_t cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
2998 if (cc < 0)
2999 {
3000 TIFFError(filename, "Can't read strip");
3001 break;
3002 }
3003 cp = tf_buf;
3004 if (photometric == PHOTOMETRIC_MINISWHITE)
3005 {
3006 for (cp += cc; --cp >= tf_buf;)
3007 *cp = ~*cp;
3008 cp++;
3009 }
3010 /*
3011 * for 16 bits, the two bytes must be most significant
3012 * byte first
3013 */
3014 if (bitspersample == 16 && !HOST_BIGENDIAN)
3015 {
3016 PS_FlipBytes(cp, cc);
3017 }
3018 if (ascii85_g)
3019 {
3020 #if defined(EXP_ASCII85ENCODER)
3021 if (alpha)
3022 {
3023 int adjust, i;
3024 for (i = 0; i < (cc - 1); i += 2)
3025 {
3026 adjust = 255 - cp[i + 1];
3027 cp[i / 2] = cp[i] + adjust;
3028 }
3029 cc /= 2;
3030 }
3031
3032 ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, cp, cc);
3033
3034 if (ascii85_l > 0)
3035 fwrite(ascii85_p, ascii85_l, 1, fd);
3036 #else
3037 while (cc-- > 0)
3038 Ascii85Put(*cp++, fd);
3039 #endif /* EXP_ASCII85_ENCODER */
3040 }
3041 else
3042 {
3043 unsigned char c;
3044
3045 if (alpha)
3046 {
3047 int adjust;
3048 while (cc-- > 1)
3049 {
3050 DOBREAK(breaklen, 1, fd);
3051 /*
3052 * For images with alpha, matte against
3053 * a white background; i.e.
3054 * Cback * (1 - Aimage)
3055 * where Cback = 1.
3056 */
3057 adjust = 255 - cp[1];
3058 c = *cp++ + adjust;
3059 puthex(c, fd);
3060 cp++, cc--;
3061 }
3062 }
3063 else
3064 {
3065 while (cc-- > 0)
3066 {
3067 c = *cp++;
3068 DOBREAK(breaklen, 1, fd);
3069 puthex(c, fd);
3070 }
3071 }
3072 }
3073 }
3074
3075 if (!ascii85_g)
3076 {
3077 if (level2 || level3)
3078 fputs(">\n", fd);
3079 }
3080 #if !defined(EXP_ASCII85ENCODER)
3081 else
3082 Ascii85Flush(fd);
3083 #else
3084 if (ascii85_p)
3085 _TIFFfree(ascii85_p);
3086 #endif
3087
3088 _TIFFfree(tf_buf);
3089 }
3090
3091 void PSRawDataBW(FILE *fd, TIFF *tif, uint32_t w, uint32_t h)
3092 {
3093 uint64_t *bc;
3094 uint32_t bufsize;
3095 int breaklen = MAXLINE;
3096 tmsize_t cc;
3097 uint16_t fillorder;
3098 unsigned char *tf_buf;
3099 unsigned char *cp, c;
3100 tstrip_t s;
3101
3102 #if defined(EXP_ASCII85ENCODER)
3103 tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
3104 uint8_t *ascii85_p = 0; /* Holds ASCII85 encoded data */
3105 #endif
3106
3107 (void)w;
3108 (void)h;
3109 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
3110 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
3111
3112 /*
3113 * Find largest strip:
3114 */
3115
3116 bufsize = (uint32_t)bc[0];
3117
3118 for (s = 0; ++s < tf_numberstrips;)
3119 {
3120 if (bc[s] > bufsize)
3121 bufsize = (uint32_t)bc[s];
3122 }
3123
3124 tf_buf = (unsigned char *)limitMalloc(bufsize);
3125 if (tf_buf == NULL)
3126 {
3127 TIFFError(filename, "No space for strip buffer");
3128 return;
3129 }
3130
3131 #if defined(EXP_ASCII85ENCODER)
3132 if (ascii85_g)
3133 {
3134 /*
3135 * Allocate a buffer to hold the ASCII85 encoded data. Note
3136 * that it is allocated with sufficient room to hold the
3137 * encoded data (5*bufsize/4) plus the EOD marker (+8)
3138 * and formatting line breaks. The line breaks are more
3139 * than taken care of by using 6*bufsize/4 rather than
3140 * 5*bufsize/4.
3141 */
3142
3143 ascii85_p = limitMalloc((bufsize + (bufsize / 2)) + 8);
3144
3145 if (!ascii85_p)
3146 {
3147 _TIFFfree(tf_buf);
3148
3149 TIFFError(filename, "Cannot allocate ASCII85 encoding buffer.");
3150 return;
3151 }
3152 }
3153 #endif
3154
3155 for (s = 0; s < tf_numberstrips; s++)
3156 {
3157 cc = TIFFReadRawStrip(tif, s, tf_buf, (tmsize_t)bc[s]);
3158 if (cc < 0)
3159 {
3160 TIFFError(filename, "Can't read strip");
3161 break;
3162 }
3163 if (fillorder == FILLORDER_LSB2MSB)
3164 TIFFReverseBits(tf_buf, cc);
3165 if (!ascii85_g)
3166 {
3167 for (cp = tf_buf; cc > 0; cc--)
3168 {
3169 DOBREAK(breaklen, 1, fd);
3170 c = *cp++;
3171 puthex(c, fd);
3172 }
3173 fputs(">\n", fd);
3174 breaklen = MAXLINE;
3175 }
3176 else
3177 {
3178 Ascii85Init();
3179 #if defined(EXP_ASCII85ENCODER)
3180 ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, tf_buf, cc);
3181
3182 if (ascii85_l > 0)
3183 fwrite(ascii85_p, ascii85_l, 1, fd);
3184 #else
3185 for (cp = tf_buf; cc > 0; cc--)
3186 Ascii85Put(*cp++, fd);
3187 Ascii85Flush(fd);
3188 #endif /* EXP_ASCII85ENCODER */
3189 }
3190 }
3191 _TIFFfree((char *)tf_buf);
3192
3193 #if defined(EXP_ASCII85ENCODER)
3194 if (ascii85_p)
3195 _TIFFfree(ascii85_p);
3196 #endif
3197 }
3198
3199 void Ascii85Init(void)
3200 {
3201 ascii85breaklen = 2 * MAXLINE;
3202 ascii85count = 0;
3203 }
3204
3205 static char *Ascii85Encode(unsigned char *raw)
3206 {
3207 static char encoded[6];
3208 uint32_t word;
3209
3210 word = (((raw[0] << 8) + raw[1]) << 16) + (raw[2] << 8) + raw[3];
3211 if (word != 0L)
3212 {
3213 uint32_t q;
3214 uint16_t w1;
3215
3216 q = word / (85L * 85 * 85 * 85); /* actually only a byte */
3217 encoded[0] = (char)(q + '!');
3218
3219 word -= q * (85L * 85 * 85 * 85);
3220 q = word / (85L * 85 * 85);
3221 encoded[1] = (char)(q + '!');
3222
3223 word -= q * (85L * 85 * 85);
3224 q = word / (85 * 85);
3225 encoded[2] = (char)(q + '!');
3226
3227 w1 = (uint16_t)(word - q * (85L * 85));
3228 encoded[3] = (char)((w1 / 85) + '!');
3229 encoded[4] = (char)((w1 % 85) + '!');
3230 encoded[5] = '\0';
3231 }
3232 else
3233 encoded[0] = 'z', encoded[1] = '\0';
3234 return (encoded);
3235 }
3236
3237 void Ascii85Put(unsigned char code, FILE *fd)
3238 {
3239 ascii85buf[ascii85count++] = code;
3240 if (ascii85count >= 4)
3241 {
3242 unsigned char *p;
3243 int n;
3244
3245 for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4)
3246 {
3247 char *cp;
3248 for (cp = Ascii85Encode(p); *cp; cp++)
3249 {
3250 putc(*cp, fd);
3251 if (--ascii85breaklen == 0)
3252 {
3253 putc('\n', fd);
3254 ascii85breaklen = 2 * MAXLINE;
3255 }
3256 }
3257 }
3258 _TIFFmemcpy(ascii85buf, p, n);
3259 ascii85count = n;
3260 }
3261 }
3262
3263 void Ascii85Flush(FILE *fd)
3264 {
3265 if (ascii85count > 0)
3266 {
3267 char *res;
3268 _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
3269 res = Ascii85Encode(ascii85buf);
3270 fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
3271 }
3272 fputs("~>\n", fd);
3273 }
3274 #if defined(EXP_ASCII85ENCODER)
3275
3276 #define A85BREAKCNTR ascii85breaklen
3277 #define A85BREAKLEN (2 * MAXLINE)
3278
3279 /*****************************************************************************
3280 *
3281 * Name: Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
3282 *
3283 * Description: This routine will encode the raw data in the buffer described
3284 * by raw_p and raw_l into ASCII85 format and store the encoding
3285 * in the buffer given by ascii85_p.
3286 *
3287 * Parameters: ascii85_p - A buffer supplied by the caller which will
3288 * contain the encoded ASCII85 data.
3289 * f_eod - Flag: Nz means to end the encoded buffer with
3290 * an End-Of-Data marker.
3291 * raw_p - Pointer to the buffer of data to be encoded
3292 * raw_l - Number of bytes in raw_p[] to be encoded
3293 *
3294 * Returns: (int) < 0 Error, see errno
3295 * >= 0 Number of bytes written to ascii85_p[].
3296 *
3297 * Notes: An external variable given by A85BREAKCNTR is used to
3298 * determine when to insert newline characters into the
3299 * encoded data. As each byte is placed into ascii85_p this
3300 * external is decremented. If the variable is decrement to
3301 * or past zero then a newline is inserted into ascii85_p
3302 * and the A85BREAKCNTR is then reset to A85BREAKLEN.
3303 * Note: for efficiency reasons the A85BREAKCNTR variable
3304 * is not actually checked on *every* character
3305 * placed into ascii85_p but often only for every
3306 * 5 characters.
3307 *
3308 * THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
3309 * SUFFICIENTLY LARGE TO THE ENCODED DATA!
3310 * You will need at least 5 * (raw_l/4) bytes plus space for
3311 * newline characters and space for an EOD marker (if
3312 * requested). A safe calculation is to use 6*(raw_l/4) + 8
3313 * to size ascii85_p.
3314 *
3315 *****************************************************************************/
3316
3317 tsize_t Ascii85EncodeBlock(uint8_t *ascii85_p, unsigned f_eod,
3318 const uint8_t *raw_p, tsize_t raw_l)
3319
3320 {
3321 char ascii85[5]; /* Encoded 5 tuple */
3322 tsize_t ascii85_l; /* Number of bytes written to ascii85_p[] */
3323 int rc; /* Return code */
3324 uint32_t val32; /* Unencoded 4 tuple */
3325
3326 ascii85_l = 0; /* Nothing written yet */
3327
3328 if (raw_p)
3329 {
3330 --raw_p; /* Prepare for pre-increment fetches */
3331
3332 for (; raw_l > 3; raw_l -= 4)
3333 {
3334 val32 = (uint32_t) * (++raw_p) << 24;
3335 val32 += (uint32_t) * (++raw_p) << 16;
3336 val32 += (uint32_t) * (++raw_p) << 8;
3337 val32 += (uint32_t) * (++raw_p);
3338
3339 if (val32 == 0) /* Special case */
3340 {
3341 ascii85_p[ascii85_l] = 'z';
3342 rc = 1;
3343 }
3344
3345 else
3346 {
3347 ascii85[4] = (char)((val32 % 85) + 33);
3348 val32 /= 85;
3349
3350 ascii85[3] = (char)((val32 % 85) + 33);
3351 val32 /= 85;
3352
3353 ascii85[2] = (char)((val32 % 85) + 33);
3354 val32 /= 85;
3355
3356 ascii85[1] = (char)((val32 % 85) + 33);
3357 ascii85[0] = (char)((val32 / 85) + 33);
3358
3359 _TIFFmemcpy(&ascii85_p[ascii85_l], ascii85, sizeof(ascii85));
3360 rc = sizeof(ascii85);
3361 }
3362
3363 ascii85_l += rc;
3364
3365 if ((A85BREAKCNTR -= rc) <= 0)
3366 {
3367 ascii85_p[ascii85_l] = '\n';
3368 ++ascii85_l;
3369 A85BREAKCNTR = A85BREAKLEN;
3370 }
3371 }
3372
3373 /*
3374 * Output any straggler bytes:
3375 */
3376
3377 if (raw_l > 0)
3378 {
3379 tsize_t len; /* Output this many bytes */
3380
3381 len = raw_l + 1;
3382 val32 = (uint32_t) * ++raw_p << 24; /* Prime the pump */
3383
3384 if (--raw_l > 0)
3385 val32 += *(++raw_p) << 16;
3386 if (--raw_l > 0)
3387 val32 += *(++raw_p) << 8;
3388
3389 val32 /= 85;
3390
3391 ascii85[3] = (char)((val32 % 85) + 33);
3392 val32 /= 85;
3393
3394 ascii85[2] = (char)((val32 % 85) + 33);
3395 val32 /= 85;
3396
3397 ascii85[1] = (char)((val32 % 85) + 33);
3398 ascii85[0] = (char)((val32 / 85) + 33);
3399
3400 _TIFFmemcpy(&ascii85_p[ascii85_l], ascii85, len);
3401 ascii85_l += len;
3402 }
3403 }
3404
3405 /*
3406 * If requested add an ASCII85 End Of Data marker:
3407 */
3408
3409 if (f_eod)
3410 {
3411 ascii85_p[ascii85_l++] = '~';
3412 ascii85_p[ascii85_l++] = '>';
3413 ascii85_p[ascii85_l++] = '\n';
3414 }
3415
3416 return (ascii85_l);
3417
3418 } /* Ascii85EncodeBlock() */
3419
3420 #endif /* EXP_ASCII85ENCODER */
3421
3422 static const char usage_info[] =
3423 "Convert a TIFF image to PostScript\n\n"
3424 "usage: tiff2ps [options] input.tif ...\n"
3425 "where options are:\n"
3426 " -1 generate PostScript Level 1 (default)\n"
3427 " -2 generate PostScript Level 2\n"
3428 " -3 generate PostScript Level 3\n"
3429 " -8 disable use of ASCII85 encoding with PostScript Level 2/3\n"
3430 " -a convert all directories in file (default is first), Not "
3431 "EPS\n"
3432 " -b # set the bottom margin to # inches\n"
3433 " -c center image (-b and -l still add to this)\n"
3434 " -C name set postscript document creator name\n"
3435 " -d # set initial directory to # counting from zero\n"
3436 " -D enable duplex printing (two pages per sheet of paper)\n"
3437 " -e generate Encapsulated PostScript (EPS) (implies -z)\n"
3438 " -h # set printed page height to # inches (no default)\n"
3439 " -w # set printed page width to # inches (no default)\n"
3440 " -H # split image if height is more than # inches\n"
3441 " -W # split image if width is more than # inches\n"
3442 " -L # overLap split images by # inches\n"
3443 " -i # enable/disable (Nz/0) pixel interpolation (default: "
3444 "enable)\n"
3445 " -l # set the left margin to # inches\n"
3446 " -m use \"imagemask\" operator instead of \"image\"\n"
3447 " -M size set the memory allocation limit in MiB. 0 to disable "
3448 "limit\n"
3449 " -o # convert directory at file offset # bytes\n"
3450 " -O file write PostScript to file instead of standard output\n"
3451 " -p generate regular (non-encapsulated) PostScript\n"
3452 " -P L or P set optional PageOrientation DSC comment to Landscape or "
3453 "Portrait\n"
3454 " -r # or auto rotate by 90, 180, 270 degrees or auto\n"
3455 " -s generate PostScript for a single image\n"
3456 " -t name set postscript document title. Otherwise the filename is "
3457 "used\n"
3458 " -T print pages for top edge binding\n"
3459 " -x override resolution units as centimeters\n"
3460 " -y override resolution units as inches\n"
3461 " -z enable printing in the deadzone (only for PostScript Level "
3462 "2/3)\n";
3463
3464 static void usage(int code)
3465 {
3466 FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
3467
3468 fprintf(out, "%s\n\n", TIFFGetVersion());
3469 fprintf(out, "%s", usage_info);
3470 exit(code);
3471 }