4 * Copyright (c) 1988-1997 Sam Leffler
5 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
28 * Modified for use as Evince TIFF ps exporter by
29 * Matthew S. Wilson <msw@rpath.com>
30 * Modifications Copyright (C) 2005 rpath, Inc.
32 * FIXME: refactor to remove use of global variables
36 #include <stdlib.h> /* for atof */
48 * I (Bruce A. Mallett) added this revision history comment ;)
50 * Fixed PS_Lvl2page() code which outputs non-ASCII85 raw
51 * data. Moved test for when to output a line break to
52 * *after* the output of a character. This just serves
53 * to fix an eye-nuisance where the first line of raw
54 * data was one character shorter than subsequent lines.
56 * Added an experimental ASCII85 encoder which can be used
57 * only when there is a single buffer of bytes to be encoded.
58 * This version is much faster at encoding a straight-line
59 * buffer of data because it can avoid alot of the loop
60 * overhead of the byte-by-bye version. To use this version
61 * you need to define EXP_ASCII85ENCODER (experimental ...).
63 * Added bug fix given by Michael Schmidt to PS_Lvl2page()
64 * in which an end-of-data marker ('>') was not being output
65 * when producing non-ASCII85 encoded PostScript Level 2
68 * Fixed PS_Lvl2colorspace() so that it no longer assumes that
69 * a TIFF having more than 2 planes is a CMYK. This routine
70 * no longer looks at the samples per pixel but instead looks
71 * at the "photometric" value. This change allows support of
74 * Modified the PostScript L2 imaging loop so as to test if
75 * the input stream is still open before attempting to do a
76 * flushfile on it. This was done because some RIPs close
77 * the stream after doing the image operation.
79 * Got rid of the realloc() being done inside a loop in the
80 * PSRawDataBW() routine. The code now walks through the
81 * byte-size array outside the loop to determine the largest
82 * size memory block that will be needed.
84 * Added "-m" switch to ask tiff2ps to, where possible, use the
85 * "imagemask" operator instead of the "image" operator.
87 * Added the "-i #" switch to allow interpolation to be disabled.
89 * Unrolled a loop or two to improve performance.
93 * Define EXP_ASCII85ENCODER if you want to use an experimental
94 * version of the ASCII85 encoding routine. The advantage of
95 * using this routine is that tiff2ps will convert to ASCII85
96 * encoding at between 3 and 4 times the speed as compared to
97 * using the old (non-experimental) encoder. The disadvantage
98 * is that you will be using a new (and unproven) encoding
99 * routine. So user beware, you have been warned!
102 #define EXP_ASCII85ENCODER
105 * NB: this code assumes uint32 works with printf's %l[ud].
112 static int ascii85 = FALSE; /* use ASCII85 encoding */
113 static int interpolate = TRUE; /* interpolate level2 image */
114 static int level2 = FALSE; /* generate PostScript level 2 */
115 static int level3 = FALSE; /* generate PostScript level 3 */
116 static int printAll = FALSE; /* print all images in file */
117 static int generateEPSF = TRUE; /* generate Encapsulated PostScript */
118 static int PSduplex = FALSE; /* enable duplex printing */
119 static int PStumble = FALSE; /* enable top edge binding */
120 static int PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */
121 static double maxPageHeight = 0; /* maximum size to fit on page */
122 static double splitOverlap = 0; /* amount for split pages to overlag */
123 static int rotate = FALSE; /* rotate image by 180 degrees */
124 static char *filename = NULL; /* input filename */
125 static int useImagemask = FALSE; /* Use imagemask instead of image operator */
126 static uint16 res_unit = 0; /* Resolution units: 2 - inches, 3 - cm */
129 * ASCII85 Encoding Support.
131 static unsigned char ascii85buf[10];
132 static int ascii85count;
133 static int ascii85breaklen;
135 static void PSpage(FILE*, TIFF*, uint32, uint32);
136 static void PSColorContigPreamble(FILE*, uint32, uint32, int);
137 static void PSColorSeparatePreamble(FILE*, uint32, uint32, int);
138 static void PSDataColorContig(FILE*, TIFF*, uint32, uint32, int);
139 static void PSDataColorSeparate(FILE*, TIFF*, uint32, uint32, int);
140 static void PSDataPalette(FILE*, TIFF*, uint32, uint32);
141 static void PSDataBW(FILE*, TIFF*, uint32, uint32);
142 static void Ascii85Init(void);
143 static void Ascii85Put(unsigned char code, FILE* fd);
144 static void Ascii85Flush(FILE* fd);
145 static void PSHead(FILE*, TIFF*, uint32, uint32, double, double, double, double);
147 #if defined( EXP_ASCII85ENCODER)
148 static int Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, int raw_l );
151 static uint16 samplesperpixel;
152 static uint16 bitspersample;
153 static uint16 planarconfiguration;
154 static uint16 photometric;
155 static uint16 compression;
156 static uint16 extrasamples;
160 checkImage(TIFF* tif)
162 switch (photometric) {
163 case PHOTOMETRIC_YCBCR:
164 if ((compression == COMPRESSION_JPEG || compression == COMPRESSION_OJPEG)
165 && planarconfiguration == PLANARCONFIG_CONTIG) {
166 /* can rely on libjpeg to convert to RGB */
167 TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
169 photometric = PHOTOMETRIC_RGB;
171 if (level2 || level3)
173 TIFFError(filename, "Can not handle image with %s",
174 "PhotometricInterpretation=YCbCr");
178 case PHOTOMETRIC_RGB:
179 if (alpha && bitspersample != 8) {
181 "Can not handle %d-bit/sample RGB image with alpha",
186 case PHOTOMETRIC_SEPARATED:
187 case PHOTOMETRIC_PALETTE:
188 case PHOTOMETRIC_MINISBLACK:
189 case PHOTOMETRIC_MINISWHITE:
191 case PHOTOMETRIC_LOGL:
192 case PHOTOMETRIC_LOGLUV:
193 if (compression != COMPRESSION_SGILOG &&
194 compression != COMPRESSION_SGILOG24) {
196 "Can not handle %s data with compression other than SGILog",
197 (photometric == PHOTOMETRIC_LOGL) ?
202 /* rely on library to convert to RGB/greyscale */
203 TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
204 photometric = (photometric == PHOTOMETRIC_LOGL) ?
205 PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB;
208 case PHOTOMETRIC_CIELAB:
212 "Can not handle image with PhotometricInterpretation=%d",
216 switch (bitspersample) {
221 TIFFError(filename, "Can not handle %d-bit/sample image",
225 if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
226 TIFFWarning(filename, "Ignoring extra samples");
230 #define PS_UNIT_SIZE 72.0F
231 #define PSUNITS(npix,res) ((npix) * (PS_UNIT_SIZE / (res)))
233 static char RGBcolorimage[] = "\
236 dup length 3 idiv string 0 3 0\n\
238 add 2 1 roll 1 sub dup 0 eq {\n\
245 } { 2 1 roll } ifelse\n\
249 /colorimage where {pop} {\n\
250 /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
255 * Adobe Photoshop requires a comment line of the form:
257 * %ImageData: <cols> <rows> <depth> <main channels> <pad channels>
258 * <block size> <1 for binary|2 for hex> "data start"
260 * It is claimed to be part of some future revision of the EPS spec.
263 PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline)
265 fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
266 (long) w, (long) h, bitspersample, nc, bs);
267 fprintf(fd, startline, nc);
272 * pw : image width in pixels
273 * ph : image height in pixels
274 * pprw : image width in PS units (72 dpi)
275 * pprh : image height in PS units (72 dpi)
278 setupPageState(TIFF* tif, uint32* pw, uint32* ph, double* pprw, double* pprh)
280 float xres = 0.0F, yres = 0.0F;
282 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
283 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
285 TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit);
287 * Calculate printable area.
289 if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
290 || fabs(xres) < 0.0000001)
292 if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
293 || fabs(yres) < 0.0000001)
296 case RESUNIT_CENTIMETER:
297 xres *= 2.54F, yres *= 2.54F;
303 xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
306 *pprh = PSUNITS(*ph, yres);
307 *pprw = PSUNITS(*pw, xres);
311 isCCITTCompression(TIFF* tif)
314 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
315 return (compress == COMPRESSION_CCITTFAX3 ||
316 compress == COMPRESSION_CCITTFAX4 ||
317 compress == COMPRESSION_CCITTRLE ||
318 compress == COMPRESSION_CCITTRLEW);
321 static tsize_t tf_bytesperrow;
322 static tsize_t ps_bytesperrow;
323 static tsize_t tf_rowsperstrip;
324 static tsize_t tf_numberstrips;
325 static char *hex = "0123456789abcdef";
328 * imagewidth & imageheight are 1/72 inches
329 * pagewidth & pageheight are inches
332 PlaceImage(FILE *fp, double pagewidth, double pageheight,
333 double imagewidth, double imageheight, int splitpage,
334 double lm, double bm, int cnt)
340 double left_offset = lm * PS_UNIT_SIZE;
341 double bottom_offset = bm * PS_UNIT_SIZE;
342 double subimageheight;
346 pagewidth *= PS_UNIT_SIZE;
347 pageheight *= PS_UNIT_SIZE;
349 if (maxPageHeight==0)
352 splitheight = maxPageHeight * PS_UNIT_SIZE;
353 overlap = splitOverlap * PS_UNIT_SIZE;
357 * if too wide, scrunch to fit
358 * else leave it alone
360 if (imagewidth <= pagewidth) {
367 * if too long, scrunch to fit
368 * if too short, move to top of page
370 if (imageheight <= pageheight) {
371 yscale = imageheight;
372 ytran = pageheight - imageheight;
373 } else if (imageheight > pageheight &&
374 (splitheight == 0 || imageheight <= splitheight)) {
376 } else /* imageheight > splitheight */ {
377 subimageheight = imageheight - (pageheight-overlap)*splitpage;
378 if (subimageheight <= pageheight) {
379 yscale = imageheight;
380 ytran = pageheight - subimageheight;
382 } else if ( subimageheight > pageheight && subimageheight <= splitheight) {
383 yscale = imageheight * pageheight / subimageheight;
386 } else /* sumimageheight > splitheight */ {
387 yscale = imageheight;
388 ytran = pageheight - subimageheight;
393 bottom_offset += ytran / (cnt?2:1);
395 left_offset += xtran / 2;
396 fprintf(fp, "%f %f translate\n", left_offset, bottom_offset);
397 fprintf(fp, "%f %f scale\n", xscale, yscale);
399 fputs ("1 1 translate 180 rotate\n", fp);
406 TIFF2PS(FILE* fd, TIFF* tif,
407 double pw, double ph, double lm, double bm, int cnt, int *npages)
413 double left_offset = lm * PS_UNIT_SIZE;
414 double bottom_offset = bm * PS_UNIT_SIZE;
419 if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
421 if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
423 setupPageState(tif, &w, &h, &prw, &prh);
426 tf_numberstrips = TIFFNumberOfStrips(tif);
427 TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP,
429 setupPageState(tif, &w, &h, &prw, &prh);
431 PSHead(fd, tif, w, h, prw, prh, ox, oy);
432 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE,
434 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL,
436 TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG,
437 &planarconfiguration);
438 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
439 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
440 &extrasamples, &sampleinfo);
441 alpha = (extrasamples == 1 &&
442 sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
443 if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) {
444 switch (samplesperpixel - extrasamples) {
446 if (isCCITTCompression(tif))
447 photometric = PHOTOMETRIC_MINISWHITE;
449 photometric = PHOTOMETRIC_MINISBLACK;
452 photometric = PHOTOMETRIC_RGB;
455 photometric = PHOTOMETRIC_SEPARATED;
459 if (checkImage(tif)) {
460 tf_bytesperrow = TIFFScanlineSize(tif);
461 *npages = *npages + 1;
462 fprintf(fd, "%%%%Page: %d %d\n", *npages, *npages);
463 if (!generateEPSF && ( level2 || level3 )) {
464 double psw = 0.0, psh = 0.0;
466 psw = pw * PS_UNIT_SIZE;
467 if (res_unit == RESUNIT_CENTIMETER)
470 psw=rotate ? prh:prw;
472 psh = ph * PS_UNIT_SIZE;
473 if (res_unit == RESUNIT_CENTIMETER)
476 psh=rotate ? prw:prh;
478 "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
481 "<<\n /Policies <<\n /PageSize 3\n >>\n>> setpagedevice\n",
484 fprintf(fd, "gsave\n");
485 fprintf(fd, "100 dict begin\n");
486 if (pw != 0 || ph != 0) {
491 if (maxPageHeight) { /* used -H option */
492 split = PlaceImage(fd,pw,ph,prw,prh,
495 PSpage(fd, tif, w, h);
496 fprintf(fd, "end\n");
497 fprintf(fd, "grestore\n");
498 fprintf(fd, "showpage\n");
499 *npages = *npages + 1;
500 fprintf(fd, "%%%%Page: %d %d\n",
502 fprintf(fd, "gsave\n");
503 fprintf(fd, "100 dict begin\n");
504 split = PlaceImage(fd,pw,ph,prw,prh,
511 /* NB: maintain image aspect ratio */
512 scale = pw/prw < ph/prh ?
518 (ph - prh * scale) / 2;
520 (pw - prw * scale) / 2;
522 fprintf(fd, "%f %f translate\n",
523 left_offset, bottom_offset);
524 fprintf(fd, "%f %f scale\n",
525 prw * scale, prh * scale);
527 fputs ("1 1 translate 180 rotate\n", fd);
530 fprintf(fd, "%f %f scale\n", prw, prh);
532 fputs ("1 1 translate 180 rotate\n", fd);
534 PSpage(fd, tif, w, h);
535 fprintf(fd, "end\n");
536 fprintf(fd, "grestore\n");
537 fprintf(fd, "showpage\n");
541 TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
542 } while (((subfiletype & FILETYPE_PAGE) || printAll) &&
543 TIFFReadDirectory(tif));
547 static char DuplexPreamble[] = "\
548 %%BeginFeature: *Duplex True\n\
550 /languagelevel where { pop languagelevel } { 1 } ifelse\n\
551 2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
552 { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
558 static char TumblePreamble[] = "\
559 %%BeginFeature: *Tumble True\n\
561 /languagelevel where { pop languagelevel } { 1 } ifelse\n\
562 2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
563 { statusdict /settumble known { statusdict begin true settumble end } if\n\
569 static char AvoidDeadZonePreamble[] = "\
570 gsave newpath clippath pathbbox grestore\n\
571 4 2 roll 2 copy translate\n\
572 exch 3 1 roll sub 3 1 roll sub exch\n\
573 currentpagedevice /PageSize get aload pop\n\
574 exch 3 1 roll div 3 1 roll div abs exch abs\n\
575 2 copy gt { exch } if pop\n\
576 dup 1 lt { dup scale } { pop } ifelse\n\
580 PSHead(FILE *fd, TIFF *tif, uint32 w, uint32 h,
581 double pw, double ph, double ox, double oy)
585 (void) tif; (void) w; (void) h;
587 fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
588 fprintf(fd, "%%%%Creator: Evince\n");
589 fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
590 fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
591 fprintf(fd, "%%%%Origin: %ld %ld\n", (long) ox, (long) oy);
592 /* NB: should use PageBoundingBox */
593 fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
594 (long) ceil(pw), (long) ceil(ph));
595 fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
596 fprintf(fd, "%%%%Pages: (atend)\n");
597 fprintf(fd, "%%%%EndComments\n");
598 fprintf(fd, "%%%%BeginSetup\n");
600 fprintf(fd, "%s", DuplexPreamble);
602 fprintf(fd, "%s", TumblePreamble);
603 if (PSavoiddeadzone && (level2 || level3))
604 fprintf(fd, "%s", AvoidDeadZonePreamble);
605 fprintf(fd, "%%%%EndSetup\n");
609 TIFFPSTail(FILE *fd, int npages)
611 fprintf(fd, "%%%%Trailer\n");
612 fprintf(fd, "%%%%Pages: %d\n", npages);
613 fprintf(fd, "%%%%EOF\n");
617 checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
621 if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
623 TIFFWarning(filename, "Assuming 8-bit colormap");
628 PS_Lvl2colorspace(FILE* fd, TIFF* tif)
630 uint16 *rmap, *gmap, *bmap;
632 const char * colorspace_p;
634 switch ( photometric )
636 case PHOTOMETRIC_SEPARATED:
637 colorspace_p = "CMYK";
640 case PHOTOMETRIC_RGB:
641 colorspace_p = "RGB";
645 colorspace_p = "Gray";
649 * Set up PostScript Level 2 colorspace according to
650 * section 4.8 in the PostScript refenence manual.
652 fputs("% PostScript Level 2 only.\n", fd);
653 if (photometric != PHOTOMETRIC_PALETTE) {
654 if (photometric == PHOTOMETRIC_YCBCR) {
657 fprintf(fd, "/Device%s setcolorspace\n", colorspace_p );
662 * Set up an indexed/palette colorspace
664 num_colors = (1 << bitspersample);
665 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
667 "Palette image w/o \"Colormap\" tag");
670 if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
672 * Convert colormap to 8-bits values.
674 #define CVT(x) (((x) * 255) / ((1L<<16)-1))
675 for (i = 0; i < num_colors; i++) {
676 rmap[i] = CVT(rmap[i]);
677 gmap[i] = CVT(gmap[i]);
678 bmap[i] = CVT(bmap[i]);
682 fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
686 ascii85breaklen -= 2;
689 for (i = 0; i < num_colors; i++) {
691 Ascii85Put((unsigned char)rmap[i], fd);
692 Ascii85Put((unsigned char)gmap[i], fd);
693 Ascii85Put((unsigned char)bmap[i], fd);
695 fputs((i % 8) ? " " : "\n ", fd);
696 fprintf(fd, "%02x%02x%02x",
697 rmap[i], gmap[i], bmap[i]);
704 fputs("] setcolorspace\n", fd);
708 PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h)
711 uint32 tile_width, tile_height;
712 uint16 predictor, minsamplevalue, maxsamplevalue;
714 char im_h[64], im_x[64], im_y[64];
715 char * imageOp = "image";
717 if ( useImagemask && (bitspersample == 1) )
718 imageOp = "imagemask";
720 (void)strcpy(im_x, "0");
721 (void)sprintf(im_y, "%lu", (long) h);
722 (void)sprintf(im_h, "%lu", (long) h);
725 if (TIFFIsTiled(tif)) {
726 repeat_count = TIFFNumberOfTiles(tif);
727 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
728 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
729 if (tile_width > w || tile_height > h ||
730 (w % tile_width) != 0 || (h % tile_height != 0)) {
732 * The tiles does not fit image width and height.
733 * Set up a clip rectangle for the image unit square.
735 fputs("0 0 1 1 rectclip\n", fd);
737 if (tile_width < w) {
738 fputs("/im_x 0 def\n", fd);
739 (void)strcpy(im_x, "im_x neg");
741 if (tile_height < h) {
742 fputs("/im_y 0 def\n", fd);
743 (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
746 repeat_count = tf_numberstrips;
747 tile_height = tf_rowsperstrip;
750 if (repeat_count > 1) {
751 fputs("/im_y 0 def\n", fd);
752 fprintf(fd, "/im_h %lu def\n",
753 (unsigned long) tile_height);
754 (void)strcpy(im_h, "im_h");
755 (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
760 * Output start of exec block
762 fputs("{ % exec\n", fd);
764 if (repeat_count > 1)
765 fprintf(fd, "%d { %% repeat\n", repeat_count);
768 * Output filter options and image dictionary.
771 fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
774 fputs(" /ImageType 1\n", fd);
775 fprintf(fd, " /Width %lu\n", (unsigned long) tile_width);
777 * Workaround for some software that may crash when last strip
778 * of image contains fewer number of scanlines than specified
779 * by the `/Height' variable. So for stripped images with multiple
780 * strips we will set `/Height' as `im_h', because one is
781 * recalculated for each strip - including the (smaller) final strip.
782 * For tiled images and images with only one strip `/Height' will
783 * contain number of scanlines in tile (or image height in case of
784 * one-stripped image).
786 if (TIFFIsTiled(tif) || tf_numberstrips == 1)
787 fprintf(fd, " /Height %lu\n", (unsigned long) tile_height);
789 fprintf(fd, " /Height im_h\n");
791 if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
792 fputs(" /MultipleDataSources true\n", fd);
793 fprintf(fd, " /ImageMatrix [ %lu 0 0 %ld %s %s ]\n",
794 (unsigned long) w, - (long)h, im_x, im_y);
795 fprintf(fd, " /BitsPerComponent %d\n", bitspersample);
796 fprintf(fd, " /Interpolate %s\n", interpolate ? "true" : "false");
798 switch (samplesperpixel - extrasamples) {
800 switch (photometric) {
801 case PHOTOMETRIC_MINISBLACK:
802 fputs(" /Decode [0 1]\n", fd);
804 case PHOTOMETRIC_MINISWHITE:
805 switch (compression) {
806 case COMPRESSION_CCITTRLE:
807 case COMPRESSION_CCITTRLEW:
808 case COMPRESSION_CCITTFAX3:
809 case COMPRESSION_CCITTFAX4:
811 * Manage inverting with /Blackis1 flag
812 * since there migth be uncompressed parts
814 fputs(" /Decode [0 1]\n", fd);
820 fputs(" /Decode [1 0]\n", fd);
824 case PHOTOMETRIC_PALETTE:
825 TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
827 TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
829 fprintf(fd, " /Decode [%u %u]\n",
830 minsamplevalue, maxsamplevalue);
836 fputs(" /Decode [0 1]\n", fd);
841 switch (photometric) {
842 case PHOTOMETRIC_RGB:
843 fputs(" /Decode [0 1 0 1 0 1]\n", fd);
845 case PHOTOMETRIC_MINISWHITE:
846 case PHOTOMETRIC_MINISBLACK:
851 fputs(" /Decode [0 1 0 1 0 1]\n", fd);
859 fputs(" /Decode [0 1 0 1 0 1 0 1]\n", fd);
862 fputs(" /DataSource", fd);
863 if (planarconfiguration == PLANARCONFIG_SEPARATE &&
867 fputs(" im_stream", fd);
869 fputs(" currentfile /ASCIIHexDecode filter", fd);
872 switch (compression) {
873 case COMPRESSION_NONE: /* 1: uncompressed */
875 case COMPRESSION_CCITTRLE: /* 2: CCITT modified Huffman RLE */
876 case COMPRESSION_CCITTRLEW: /* 32771: #1 w/ word alignment */
877 case COMPRESSION_CCITTFAX3: /* 3: CCITT Group 3 fax encoding */
878 case COMPRESSION_CCITTFAX4: /* 4: CCITT Group 4 fax encoding */
879 fputs("\n\t<<\n", fd);
880 if (compression == COMPRESSION_CCITTFAX3) {
883 fputs("\t /EndOfLine true\n", fd);
884 fputs("\t /EndOfBlock false\n", fd);
885 if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
888 if (g3_options & GROUP3OPT_2DENCODING)
889 fprintf(fd, "\t /K %s\n", im_h);
890 if (g3_options & GROUP3OPT_UNCOMPRESSED)
891 fputs("\t /Uncompressed true\n", fd);
892 if (g3_options & GROUP3OPT_FILLBITS)
893 fputs("\t /EncodedByteAlign true\n", fd);
895 if (compression == COMPRESSION_CCITTFAX4) {
898 fputs("\t /K -1\n", fd);
899 TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
901 if (g4_options & GROUP4OPT_UNCOMPRESSED)
902 fputs("\t /Uncompressed true\n", fd);
904 if (!(tile_width == w && w == 1728U))
905 fprintf(fd, "\t /Columns %lu\n",
906 (unsigned long) tile_width);
907 fprintf(fd, "\t /Rows %s\n", im_h);
908 if (compression == COMPRESSION_CCITTRLE ||
909 compression == COMPRESSION_CCITTRLEW) {
910 fputs("\t /EncodedByteAlign true\n", fd);
911 fputs("\t /EndOfBlock false\n", fd);
913 if (photometric == PHOTOMETRIC_MINISBLACK)
914 fputs("\t /BlackIs1 true\n", fd);
915 fprintf(fd, "\t>> /CCITTFaxDecode filter");
917 case COMPRESSION_LZW: /* 5: Lempel-Ziv & Welch */
918 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
919 if (predictor == 2) {
920 fputs("\n\t<<\n", fd);
921 fprintf(fd, "\t /Predictor %u\n", predictor);
922 fprintf(fd, "\t /Columns %lu\n",
923 (unsigned long) tile_width);
924 fprintf(fd, "\t /Colors %u\n", samplesperpixel);
925 fprintf(fd, "\t /BitsPerComponent %u\n",
929 fputs(" /LZWDecode filter", fd);
931 case COMPRESSION_DEFLATE: /* 5: ZIP */
932 case COMPRESSION_ADOBE_DEFLATE:
934 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
936 fprintf(fd, "\t %% PostScript Level 3 only.");
937 fputs("\n\t<<\n", fd);
938 fprintf(fd, "\t /Predictor %u\n", predictor);
939 fprintf(fd, "\t /Columns %lu\n",
940 (unsigned long) tile_width);
941 fprintf(fd, "\t /Colors %u\n", samplesperpixel);
942 fprintf(fd, "\t /BitsPerComponent %u\n",
946 fputs(" /FlateDecode filter", fd);
948 use_rawdata = FALSE ;
951 case COMPRESSION_PACKBITS: /* 32773: Macintosh RLE */
952 fputs(" /RunLengthDecode filter", fd);
955 case COMPRESSION_OJPEG: /* 6: !6.0 JPEG */
956 case COMPRESSION_JPEG: /* 7: %JPEG DCT compression */
959 * Code not tested yet
961 fputs(" /DCTDecode filter", fd);
967 case COMPRESSION_NEXT: /* 32766: NeXT 2-bit RLE */
968 case COMPRESSION_THUNDERSCAN: /* 32809: ThunderScan RLE */
969 case COMPRESSION_PIXARFILM: /* 32908: Pixar companded 10bit LZW */
970 case COMPRESSION_JBIG: /* 34661: ISO JBIG */
973 case COMPRESSION_SGILOG: /* 34676: SGI LogL or LogLuv */
974 case COMPRESSION_SGILOG24: /* 34677: SGI 24-bit LogLuv */
984 if (planarconfiguration == PLANARCONFIG_SEPARATE &&
985 samplesperpixel > 1) {
989 * NOTE: This code does not work yet...
991 for (i = 1; i < samplesperpixel; i++)
996 fprintf( fd, "\n >> %s\n", imageOp );
998 fputs(" im_stream status { im_stream flushfile } if\n", fd);
999 if (repeat_count > 1) {
1000 if (tile_width < w) {
1001 fprintf(fd, " /im_x im_x %lu add def\n",
1002 (unsigned long) tile_width);
1003 if (tile_height < h) {
1004 fprintf(fd, " im_x %lu ge {\n",
1006 fputs(" /im_x 0 def\n", fd);
1007 fprintf(fd, " /im_y im_y %lu add def\n",
1008 (unsigned long) tile_height);
1009 fputs(" } if\n", fd);
1012 if (tile_height < h) {
1013 if (tile_width >= w) {
1014 fprintf(fd, " /im_y im_y %lu add def\n",
1015 (unsigned long) tile_height);
1016 if (!TIFFIsTiled(tif)) {
1017 fprintf(fd, " /im_h %lu im_y sub",
1019 fprintf(fd, " dup %lu gt { pop",
1020 (unsigned long) tile_height);
1021 fprintf(fd, " %lu } if def\n",
1022 (unsigned long) tile_height);
1026 fputs("} repeat\n", fd);
1029 * End of exec function
1033 return(use_rawdata);
1039 PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1042 int use_rawdata, tiled_image, breaklen = MAXLINE;
1043 uint32 chunk_no, num_chunks, *bc;
1044 unsigned char *buf_data, *cp;
1045 tsize_t chunk_size, byte_count;
1047 #if defined( EXP_ASCII85ENCODER )
1048 int ascii85_l; /* Length, in bytes, of ascii85_p[] data */
1049 uint8 * ascii85_p = 0; /* Holds ASCII85 encoded data */
1052 PS_Lvl2colorspace(fd, tif);
1053 use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
1055 /* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
1056 #ifdef ENABLE_BROKEN_BEGINENDDATA
1057 fputs("%%BeginData:\n", fd);
1059 fputs("exec\n", fd);
1061 tiled_image = TIFFIsTiled(tif);
1063 num_chunks = TIFFNumberOfTiles(tif);
1064 TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
1066 num_chunks = TIFFNumberOfStrips(tif);
1067 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
1071 chunk_size = (tsize_t) bc[0];
1072 for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
1073 if ((tsize_t) bc[chunk_no] > chunk_size)
1074 chunk_size = (tsize_t) bc[chunk_no];
1077 chunk_size = TIFFTileSize(tif);
1079 chunk_size = TIFFStripSize(tif);
1081 buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
1083 TIFFError(filename, "Can't alloc %u bytes for %s.",
1084 chunk_size, tiled_image ? "tiles" : "strips");
1088 #if defined( EXP_ASCII85ENCODER )
1091 * Allocate a buffer to hold the ASCII85 encoded data. Note
1092 * that it is allocated with sufficient room to hold the
1093 * encoded data (5*chunk_size/4) plus the EOD marker (+8)
1094 * and formatting line breaks. The line breaks are more
1095 * than taken care of by using 6*chunk_size/4 rather than
1099 ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 );
1102 _TIFFfree( buf_data );
1104 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
1110 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
1111 for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
1118 byte_count = TIFFReadRawTile(tif, chunk_no,
1119 buf_data, chunk_size);
1121 byte_count = TIFFReadRawStrip(tif, chunk_no,
1122 buf_data, chunk_size);
1123 if (fillorder == FILLORDER_LSB2MSB)
1124 TIFFReverseBits(buf_data, byte_count);
1127 byte_count = TIFFReadEncodedTile(tif,
1131 byte_count = TIFFReadEncodedStrip(tif,
1135 if (byte_count < 0) {
1136 TIFFError(filename, "Can't read %s %d.",
1137 tiled_image ? "tile" : "strip", chunk_no);
1139 Ascii85Put('\0', fd);
1142 * For images with alpha, matte against a white background;
1143 * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
1144 * lower part of the buffer with the modified values.
1146 * XXX: needs better solution
1149 int adjust, i, j = 0;
1150 int ncomps = samplesperpixel - extrasamples;
1151 for (i = 0; i < byte_count; i+=samplesperpixel) {
1152 adjust = 255 - buf_data[i + ncomps];
1155 buf_data[j++] = buf_data[i] + adjust;
1158 buf_data[j++] = buf_data[i] + adjust;
1159 buf_data[j++] = buf_data[i+1] + adjust;
1162 buf_data[j++] = buf_data[i] + adjust;
1163 buf_data[j++] = buf_data[i+1] + adjust;
1164 buf_data[j++] = buf_data[i+2] + adjust;
1172 #if defined( EXP_ASCII85ENCODER )
1173 ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count );
1175 if ( ascii85_l > 0 )
1176 fwrite( ascii85_p, ascii85_l, 1, fd );
1178 for (cp = buf_data; byte_count > 0; byte_count--)
1179 Ascii85Put(*cp++, fd);
1184 for (cp = buf_data; byte_count > 0; byte_count--) {
1185 putc(hex[((*cp)>>4)&0xf], fd);
1186 putc(hex[(*cp)&0xf], fd);
1189 if (--breaklen <= 0) {
1197 if ( level2 || level3 )
1201 #if !defined( EXP_ASCII85ENCODER )
1207 #if defined( EXP_ASCII85ENCODER )
1209 _TIFFfree( ascii85_p );
1211 _TIFFfree(buf_data);
1212 #ifdef ENABLE_BROKEN_BEGINENDDATA
1213 fputs("%%EndData\n", fd);
1219 PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1221 char * imageOp = "image";
1223 if ( useImagemask && (bitspersample == 1) )
1224 imageOp = "imagemask";
1226 if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
1228 ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8)*w;
1229 switch (photometric) {
1230 case PHOTOMETRIC_RGB:
1231 if (planarconfiguration == PLANARCONFIG_CONTIG) {
1232 fprintf(fd, "%s", RGBcolorimage);
1233 PSColorContigPreamble(fd, w, h, 3);
1234 PSDataColorContig(fd, tif, w, h, 3);
1236 PSColorSeparatePreamble(fd, w, h, 3);
1237 PSDataColorSeparate(fd, tif, w, h, 3);
1240 case PHOTOMETRIC_SEPARATED:
1241 /* XXX should emit CMYKcolorimage */
1242 if (planarconfiguration == PLANARCONFIG_CONTIG) {
1243 PSColorContigPreamble(fd, w, h, 4);
1244 PSDataColorContig(fd, tif, w, h, 4);
1246 PSColorSeparatePreamble(fd, w, h, 4);
1247 PSDataColorSeparate(fd, tif, w, h, 4);
1250 case PHOTOMETRIC_PALETTE:
1251 fprintf(fd, "%s", RGBcolorimage);
1252 PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
1253 fprintf(fd, "/scanLine %ld string def\n",
1254 (long) ps_bytesperrow * 3L);
1255 fprintf(fd, "%lu %lu 8\n",
1256 (unsigned long) w, (unsigned long) h);
1257 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
1258 (unsigned long) w, (unsigned long) h, (unsigned long) h);
1259 fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
1260 fprintf(fd, "false 3 colorimage\n");
1261 PSDataPalette(fd, tif, w, h);
1263 case PHOTOMETRIC_MINISBLACK:
1264 case PHOTOMETRIC_MINISWHITE:
1265 PhotoshopBanner(fd, w, h, 1, 1, imageOp);
1266 fprintf(fd, "/scanLine %ld string def\n",
1267 (long) ps_bytesperrow);
1268 fprintf(fd, "%lu %lu %d\n",
1269 (unsigned long) w, (unsigned long) h, bitspersample);
1270 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
1271 (unsigned long) w, (unsigned long) h, (unsigned long) h);
1273 "{currentfile scanLine readhexstring pop} bind\n");
1274 fprintf(fd, "%s\n", imageOp);
1275 PSDataBW(fd, tif, w, h);
1282 PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc)
1284 ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
1285 PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
1286 fprintf(fd, "/line %ld string def\n", (long) ps_bytesperrow);
1287 fprintf(fd, "%lu %lu %d\n",
1288 (unsigned long) w, (unsigned long) h, bitspersample);
1289 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
1290 (unsigned long) w, (unsigned long) h, (unsigned long) h);
1291 fprintf(fd, "{currentfile line readhexstring pop} bind\n");
1292 fprintf(fd, "false %d colorimage\n", nc);
1296 PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc)
1300 PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
1301 for (i = 0; i < nc; i++)
1302 fprintf(fd, "/line%d %ld string def\n",
1303 i, (long) ps_bytesperrow);
1304 fprintf(fd, "%lu %lu %d\n",
1305 (unsigned long) w, (unsigned long) h, bitspersample);
1306 fprintf(fd, "[%lu 0 0 -%lu 0 %lu] \n",
1307 (unsigned long) w, (unsigned long) h, (unsigned long) h);
1308 for (i = 0; i < nc; i++)
1309 fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
1310 fprintf(fd, "true %d colorimage\n", nc);
1313 #define DOBREAK(len, howmany, fd) \
1314 if (((len) -= (howmany)) <= 0) { \
1316 (len) = MAXLINE-(howmany); \
1318 #define PUTHEX(c,fd) putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
1321 PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
1324 int breaklen = MAXLINE, cc, es = samplesperpixel - nc;
1325 unsigned char *tf_buf;
1326 unsigned char *cp, c;
1329 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1330 if (tf_buf == NULL) {
1331 TIFFError(filename, "No space for scanline buffer");
1334 for (row = 0; row < h; row++) {
1335 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1341 for (; cc < tf_bytesperrow; cc += samplesperpixel) {
1342 DOBREAK(breaklen, nc, fd);
1344 * For images with alpha, matte against
1345 * a white background; i.e.
1346 * Cback * (1 - Aimage)
1349 adjust = 255 - cp[nc];
1351 case 4: c = *cp++ + adjust; PUTHEX(c,fd);
1352 case 3: c = *cp++ + adjust; PUTHEX(c,fd);
1353 case 2: c = *cp++ + adjust; PUTHEX(c,fd);
1354 case 1: c = *cp++ + adjust; PUTHEX(c,fd);
1360 for (; cc < tf_bytesperrow; cc += samplesperpixel) {
1361 DOBREAK(breaklen, nc, fd);
1363 case 4: c = *cp++; PUTHEX(c,fd);
1364 case 3: c = *cp++; PUTHEX(c,fd);
1365 case 2: c = *cp++; PUTHEX(c,fd);
1366 case 1: c = *cp++; PUTHEX(c,fd);
1372 _TIFFfree((char *) tf_buf);
1376 PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
1379 int breaklen = MAXLINE, cc;
1381 unsigned char *tf_buf;
1382 unsigned char *cp, c;
1385 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1386 if (tf_buf == NULL) {
1387 TIFFError(filename, "No space for scanline buffer");
1390 maxs = (samplesperpixel > nc ? nc : samplesperpixel);
1391 for (row = 0; row < h; row++) {
1392 for (s = 0; s < maxs; s++) {
1393 if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
1395 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
1396 DOBREAK(breaklen, 1, fd);
1402 _TIFFfree((char *) tf_buf);
1405 #define PUTRGBHEX(c,fd) \
1406 PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
1409 PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1411 uint16 *rmap, *gmap, *bmap;
1413 int breaklen = MAXLINE, cc, nc;
1414 unsigned char *tf_buf;
1415 unsigned char *cp, c;
1418 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
1419 TIFFError(filename, "Palette image w/o \"Colormap\" tag");
1422 switch (bitspersample) {
1423 case 8: case 4: case 2: case 1:
1426 TIFFError(filename, "Depth %d not supported", bitspersample);
1429 nc = 3 * (8 / bitspersample);
1430 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1431 if (tf_buf == NULL) {
1432 TIFFError(filename, "No space for scanline buffer");
1435 if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) {
1437 #define CVT(x) ((unsigned short) (((x) * 255) / ((1U<<16)-1)))
1438 for (i = (1<<bitspersample)-1; i >= 0; i--) {
1439 rmap[i] = CVT(rmap[i]);
1440 gmap[i] = CVT(gmap[i]);
1441 bmap[i] = CVT(bmap[i]);
1445 for (row = 0; row < h; row++) {
1446 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1448 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
1449 DOBREAK(breaklen, nc, fd);
1450 switch (bitspersample) {
1452 c = *cp++; PUTRGBHEX(c, fd);
1455 c = *cp++; PUTRGBHEX(c&0xf, fd);
1456 c >>= 4; PUTRGBHEX(c, fd);
1459 c = *cp++; PUTRGBHEX(c&0x3, fd);
1460 c >>= 2; PUTRGBHEX(c&0x3, fd);
1461 c >>= 2; PUTRGBHEX(c&0x3, fd);
1462 c >>= 2; PUTRGBHEX(c, fd);
1465 c = *cp++; PUTRGBHEX(c&0x1, fd);
1466 c >>= 1; PUTRGBHEX(c&0x1, fd);
1467 c >>= 1; PUTRGBHEX(c&0x1, fd);
1468 c >>= 1; PUTRGBHEX(c&0x1, fd);
1469 c >>= 1; PUTRGBHEX(c&0x1, fd);
1470 c >>= 1; PUTRGBHEX(c&0x1, fd);
1471 c >>= 1; PUTRGBHEX(c&0x1, fd);
1472 c >>= 1; PUTRGBHEX(c, fd);
1477 _TIFFfree((char *) tf_buf);
1481 PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1483 int breaklen = MAXLINE;
1484 unsigned char* tf_buf;
1486 tsize_t stripsize = TIFFStripSize(tif);
1489 #if defined( EXP_ASCII85ENCODER )
1490 int ascii85_l; /* Length, in bytes, of ascii85_p[] data */
1491 uint8 *ascii85_p = 0; /* Holds ASCII85 encoded data */
1495 tf_buf = (unsigned char *) _TIFFmalloc(stripsize);
1496 memset(tf_buf, 0, stripsize);
1497 if (tf_buf == NULL) {
1498 TIFFError(filename, "No space for scanline buffer");
1502 #if defined( EXP_ASCII85ENCODER )
1505 * Allocate a buffer to hold the ASCII85 encoded data. Note
1506 * that it is allocated with sufficient room to hold the
1507 * encoded data (5*stripsize/4) plus the EOD marker (+8)
1508 * and formatting line breaks. The line breaks are more
1509 * than taken care of by using 6*stripsize/4 rather than
1513 ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 );
1516 _TIFFfree( tf_buf );
1518 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
1527 for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
1528 int cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
1530 TIFFError(filename, "Can't read strip");
1534 if (photometric == PHOTOMETRIC_MINISWHITE) {
1535 for (cp += cc; --cp >= tf_buf;)
1540 #if defined( EXP_ASCII85ENCODER )
1543 for (i = 0; i < cc; i+=2) {
1544 adjust = 255 - cp[i + 1];
1545 cp[i / 2] = cp[i] + adjust;
1550 ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc );
1552 if ( ascii85_l > 0 )
1553 fwrite( ascii85_p, ascii85_l, 1, fd );
1556 Ascii85Put(*cp++, fd);
1557 #endif /* EXP_ASCII85_ENCODER */
1564 DOBREAK(breaklen, 1, fd);
1566 * For images with alpha, matte against
1567 * a white background; i.e.
1568 * Cback * (1 - Aimage)
1571 adjust = 255 - cp[1];
1572 c = *cp++ + adjust; PUTHEX(c,fd);
1578 DOBREAK(breaklen, 1, fd);
1587 if ( level2 || level3)
1590 #if !defined( EXP_ASCII85ENCODER )
1595 _TIFFfree( ascii85_p );
1604 ascii85breaklen = 2*MAXLINE;
1609 Ascii85Encode(unsigned char* raw)
1611 static char encoded[6];
1614 word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
1619 q = word / (85L*85*85*85); /* actually only a byte */
1620 encoded[0] = (char) (q + '!');
1622 word -= q * (85L*85*85*85); q = word / (85L*85*85);
1623 encoded[1] = (char) (q + '!');
1625 word -= q * (85L*85*85); q = word / (85*85);
1626 encoded[2] = (char) (q + '!');
1628 w1 = (uint16) (word - q*(85L*85));
1629 encoded[3] = (char) ((w1 / 85) + '!');
1630 encoded[4] = (char) ((w1 % 85) + '!');
1633 encoded[0] = 'z', encoded[1] = '\0';
1638 Ascii85Put(unsigned char code, FILE* fd)
1640 ascii85buf[ascii85count++] = code;
1641 if (ascii85count >= 4) {
1645 for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
1647 for (cp = Ascii85Encode(p); *cp; cp++) {
1649 if (--ascii85breaklen == 0) {
1651 ascii85breaklen = 2*MAXLINE;
1655 _TIFFmemcpy(ascii85buf, p, n);
1661 Ascii85Flush(FILE* fd)
1663 if (ascii85count > 0) {
1665 _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
1666 res = Ascii85Encode(ascii85buf);
1667 fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
1671 #if defined( EXP_ASCII85ENCODER)
1673 #define A85BREAKCNTR ascii85breaklen
1674 #define A85BREAKLEN (2*MAXLINE)
1676 /*****************************************************************************
1678 * Name: Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
1680 * Description: This routine will encode the raw data in the buffer described
1681 * by raw_p and raw_l into ASCII85 format and store the encoding
1682 * in the buffer given by ascii85_p.
1684 * Parameters: ascii85_p - A buffer supplied by the caller which will
1685 * contain the encoded ASCII85 data.
1686 * f_eod - Flag: Nz means to end the encoded buffer with
1687 * an End-Of-Data marker.
1688 * raw_p - Pointer to the buffer of data to be encoded
1689 * raw_l - Number of bytes in raw_p[] to be encoded
1691 * Returns: (int) < 0 Error, see errno
1692 * >= 0 Number of bytes written to ascii85_p[].
1694 * Notes: An external variable given by A85BREAKCNTR is used to
1695 * determine when to insert newline characters into the
1696 * encoded data. As each byte is placed into ascii85_p this
1697 * external is decremented. If the variable is decrement to
1698 * or past zero then a newline is inserted into ascii85_p
1699 * and the A85BREAKCNTR is then reset to A85BREAKLEN.
1700 * Note: for efficiency reasons the A85BREAKCNTR variable
1701 * is not actually checked on *every* character
1702 * placed into ascii85_p but often only for every
1705 * THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
1706 * SUFFICIENTLY LARGE TO THE ENCODED DATA!
1707 * You will need at least 5 * (raw_l/4) bytes plus space for
1708 * newline characters and space for an EOD marker (if
1709 * requested). A safe calculation is to use 6*(raw_l/4) + 8
1710 * to size ascii85_p.
1712 *****************************************************************************/
1714 int Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, int raw_l )
1717 char ascii85[5]; /* Encoded 5 tuple */
1718 int ascii85_l; /* Number of bytes written to ascii85_p[] */
1719 int rc; /* Return code */
1720 uint32 val32; /* Unencoded 4 tuple */
1722 ascii85_l = 0; /* Nothing written yet */
1726 --raw_p; /* Prepare for pre-increment fetches */
1728 for ( ; raw_l > 3; raw_l -= 4 )
1730 val32 = *(++raw_p) << 24;
1731 val32 += *(++raw_p) << 16;
1732 val32 += *(++raw_p) << 8;
1733 val32 += *(++raw_p);
1735 if ( val32 == 0 ) /* Special case */
1737 ascii85_p[ascii85_l] = 'z';
1743 ascii85[4] = (char) ((val32 % 85) + 33);
1746 ascii85[3] = (char) ((val32 % 85) + 33);
1749 ascii85[2] = (char) ((val32 % 85) + 33);
1752 ascii85[1] = (char) ((val32 % 85) + 33);
1753 ascii85[0] = (char) ((val32 / 85) + 33);
1755 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
1756 rc = sizeof(ascii85);
1761 if ( (A85BREAKCNTR -= rc) <= 0 )
1763 ascii85_p[ascii85_l] = '\n';
1765 A85BREAKCNTR = A85BREAKLEN;
1770 * Output any straggler bytes:
1775 int len; /* Output this many bytes */
1778 val32 = *++raw_p << 24; /* Prime the pump */
1780 if ( --raw_l > 0 ) val32 += *(++raw_p) << 16;
1781 if ( --raw_l > 0 ) val32 += *(++raw_p) << 8;
1785 ascii85[3] = (char) ((val32 % 85) + 33);
1788 ascii85[2] = (char) ((val32 % 85) + 33);
1791 ascii85[1] = (char) ((val32 % 85) + 33);
1792 ascii85[0] = (char) ((val32 / 85) + 33);
1794 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
1800 * If requested add an ASCII85 End Of Data marker:
1805 ascii85_p[ascii85_l++] = '~';
1806 ascii85_p[ascii85_l++] = '>';
1807 ascii85_p[ascii85_l++] = '\n';
1810 return ( ascii85_l );
1812 } /* Ascii85EncodeBlock() */
1814 #endif /* EXP_ASCII85ENCODER */
1816 /* vim: set ts=8 sts=8 sw=8 noet: */