]> www.fi.muni.cz Git - evince.git/blob - tiff/tiff2ps.c
58f67dafca35e28b6458f99434fce890c75beb78
[evince.git] / tiff / tiff2ps.c
1 /* $Id$ */
2
3 /*
4  * Copyright (c) 1988-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and 
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  * 
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
18  * 
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
24  * OF THIS SOFTWARE.
25  */
26
27 /*
28  * Modified for use as Evince TIFF ps exporter by
29  * Matthew S. Wilson <msw@rpath.com>
30  * Modifications Copyright (C) 2005 rpath, Inc.
31  *
32  * FIXME: refactor to remove use of global variables
33  */
34
35 #include <stdio.h>
36 #include <stdlib.h>                     /* for atof */
37 #include <math.h>
38 #include <time.h>
39 #include <string.h>
40 #include <unistd.h>
41
42 #include "tiff2ps.h"
43
44 /*
45  * Revision history
46  *
47  * 2001-Mar-21
48  *    I (Bruce A. Mallett) added this revision history comment ;)
49  *
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.
55  *
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 ...).
62  *
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
66  *    data.
67  *
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
72  *    CMYK TIFFs.
73  *
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.
78  *
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.
83  *
84  *    Added "-m" switch to ask tiff2ps to, where possible, use the
85  *    "imagemask" operator instead of the "image" operator.
86  *
87  *    Added the "-i #" switch to allow interpolation to be disabled.
88  *
89  *    Unrolled a loop or two to improve performance.
90  */
91
92 /*
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!
100  */
101
102 #define EXP_ASCII85ENCODER
103
104 /*
105  * NB: this code assumes uint32 works with printf's %l[ud].
106  */
107 #ifndef TRUE
108 #define TRUE    1
109 #define FALSE   0
110 #endif
111
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 = FALSE;           /* 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 */
127
128 /*
129  * ASCII85 Encoding Support.
130  */
131 static unsigned char ascii85buf[10];
132 static int      ascii85count;
133 static int      ascii85breaklen;
134
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);
146
147 #if     defined( EXP_ASCII85ENCODER)
148 static int Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, int raw_l );
149 #endif
150
151 static  uint16 samplesperpixel;
152 static  uint16 bitspersample;
153 static  uint16 planarconfiguration;
154 static  uint16 photometric;
155 static  uint16 compression;
156 static  uint16 extrasamples;
157 static  int alpha;
158
159 static int
160 checkImage(TIFF* tif)
161 {
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,
168                                      JPEGCOLORMODE_RGB);
169                         photometric = PHOTOMETRIC_RGB;
170                 } else {
171                         if (level2 || level3)
172                                 break;
173                         TIFFError(filename, "Can not handle image with %s",
174                             "PhotometricInterpretation=YCbCr");
175                         return (0);
176                 }
177                 /* fall thru... */
178         case PHOTOMETRIC_RGB:
179                 if (alpha && bitspersample != 8) {
180                         TIFFError(filename,
181                             "Can not handle %d-bit/sample RGB image with alpha",
182                             bitspersample);
183                         return (0);
184                 }
185                 /* fall thru... */
186         case PHOTOMETRIC_SEPARATED:
187         case PHOTOMETRIC_PALETTE:
188         case PHOTOMETRIC_MINISBLACK:
189         case PHOTOMETRIC_MINISWHITE:
190                 break;
191         case PHOTOMETRIC_LOGL:
192         case PHOTOMETRIC_LOGLUV:
193                 if (compression != COMPRESSION_SGILOG &&
194                     compression != COMPRESSION_SGILOG24) {
195                         TIFFError(filename,
196                     "Can not handle %s data with compression other than SGILog",
197                             (photometric == PHOTOMETRIC_LOGL) ?
198                                 "LogL" : "LogLuv"
199                         );
200                         return (0);
201                 }
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;
206                 bitspersample = 8;
207                 break;
208         case PHOTOMETRIC_CIELAB:
209                 /* fall thru... */
210         default:
211                 TIFFError(filename,
212                     "Can not handle image with PhotometricInterpretation=%d",
213                     photometric);
214                 return (0);
215         }
216         switch (bitspersample) {
217         case 1: case 2:
218         case 4: case 8:
219                 break;
220         default:
221                 TIFFError(filename, "Can not handle %d-bit/sample image",
222                     bitspersample);
223                 return (0);
224         }
225         if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
226                 TIFFWarning(filename, "Ignoring extra samples");
227         return (1);
228 }
229
230 #define PS_UNIT_SIZE    72.0F
231 #define PSUNITS(npix,res)       ((npix) * (PS_UNIT_SIZE / (res)))
232
233 static  char RGBcolorimage[] = "\
234 /bwproc {\n\
235     rgbproc\n\
236     dup length 3 idiv string 0 3 0\n\
237     5 -1 roll {\n\
238         add 2 1 roll 1 sub dup 0 eq {\n\
239             pop 3 idiv\n\
240             3 -1 roll\n\
241             dup 4 -1 roll\n\
242             dup 3 1 roll\n\
243             5 -1 roll put\n\
244             1 add 3 0\n\
245         } { 2 1 roll } ifelse\n\
246     } forall\n\
247     pop pop pop\n\
248 } def\n\
249 /colorimage where {pop} {\n\
250     /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
251 } ifelse\n\
252 ";
253
254 /*
255  * Adobe Photoshop requires a comment line of the form:
256  *
257  * %ImageData: <cols> <rows> <depth>  <main channels> <pad channels>
258  *      <block size> <1 for binary|2 for hex> "data start"
259  *
260  * It is claimed to be part of some future revision of the EPS spec.
261  */
262 static void
263 PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline)
264 {
265         fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
266             (long) w, (long) h, bitspersample, nc, bs);
267         fprintf(fd, startline, nc);
268         fprintf(fd, "\"\n");
269 }
270
271 /*
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)
276  */
277 static void
278 setupPageState(TIFF* tif, uint32* pw, uint32* ph, double* pprw, double* pprh)
279 {
280         float xres = 0.0F, yres = 0.0F;
281
282         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
283         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
284         if (res_unit == 0)
285                 TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit);
286         /*
287          * Calculate printable area.
288          */
289         if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
290             || fabs(xres) < 0.0000001)
291                 xres = PS_UNIT_SIZE;
292         if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
293             || fabs(yres) < 0.0000001)
294                 yres = PS_UNIT_SIZE;
295         switch (res_unit) {
296         case RESUNIT_CENTIMETER:
297                 xres *= 2.54F, yres *= 2.54F;
298                 break;
299         case RESUNIT_INCH:
300                 break;
301         case RESUNIT_NONE:
302         default:
303                 xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
304                 break;
305         }
306         *pprh = PSUNITS(*ph, yres);
307         *pprw = PSUNITS(*pw, xres);
308 }
309
310 static int
311 isCCITTCompression(TIFF* tif)
312 {
313     uint16 compress;
314     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
315     return (compress == COMPRESSION_CCITTFAX3 ||
316             compress == COMPRESSION_CCITTFAX4 ||
317             compress == COMPRESSION_CCITTRLE ||
318             compress == COMPRESSION_CCITTRLEW);
319 }
320
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";
326
327 /*
328  * imagewidth & imageheight are 1/72 inches
329  * pagewidth & pageheight are inches
330  */
331 static int
332 PlaceImage(FILE *fp, double pagewidth, double pageheight,
333            double imagewidth, double imageheight, int splitpage,
334            double lm, double bm, int cnt)
335 {
336         double xtran = 0;
337         double ytran = 0;
338         double xscale = 1;
339         double yscale = 1;
340         double left_offset = lm * PS_UNIT_SIZE;
341         double bottom_offset = bm * PS_UNIT_SIZE;
342         double subimageheight;
343         double splitheight;
344         double overlap;
345
346         pagewidth *= PS_UNIT_SIZE;
347         pageheight *= PS_UNIT_SIZE;
348
349         if (maxPageHeight==0)
350                 splitheight = 0;
351         else
352                 splitheight = maxPageHeight * PS_UNIT_SIZE;
353         overlap = splitOverlap * PS_UNIT_SIZE;
354
355         /*
356          * WIDTH:
357          *      if too wide, scrunch to fit
358          *      else leave it alone
359          */
360         if (imagewidth <= pagewidth) {
361                 xscale = imagewidth;
362         } else {
363                 xscale = pagewidth;
364         }
365
366         /* HEIGHT:
367          *      if too long, scrunch to fit
368          *      if too short, move to top of page
369          */
370         if (imageheight <= pageheight) {
371                 yscale = imageheight;
372                 ytran = pageheight - imageheight;
373         } else if (imageheight > pageheight &&
374                 (splitheight == 0 || imageheight <= splitheight)) {
375                 yscale = pageheight;
376         } else /* imageheight > splitheight */ {
377                 subimageheight = imageheight - (pageheight-overlap)*splitpage;
378                 if (subimageheight <= pageheight) {
379                         yscale = imageheight;
380                         ytran = pageheight - subimageheight;
381                         splitpage = 0;
382                 } else if ( subimageheight > pageheight && subimageheight <= splitheight) {
383                         yscale = imageheight * pageheight / subimageheight;
384                         ytran = 0;
385                         splitpage = 0;
386                 } else /* sumimageheight > splitheight */ {
387                         yscale = imageheight;
388                         ytran = pageheight - subimageheight;
389                         splitpage++;
390                 }
391         }
392
393         bottom_offset += ytran / (cnt?2:1);
394         if (cnt)
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);
398         if (rotate)
399             fputs ("1 1 translate 180 rotate\n", fp);
400
401         return splitpage;
402 }
403
404
405 void
406 TIFF2PS(FILE* fd, TIFF* tif,
407         double pw, double ph, double lm, double bm, int cnt, int *npages)
408 {
409         uint32 w, h;
410         float ox, oy;
411         double prw, prh;
412         double scale = 1.0;
413         double left_offset = lm * PS_UNIT_SIZE;
414         double bottom_offset = bm * PS_UNIT_SIZE;
415         uint32 subfiletype;
416         uint16* sampleinfo;
417         int split;
418
419         if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
420                 ox = 0;
421         if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
422                 oy = 0;
423         setupPageState(tif, &w, &h, &prw, &prh);
424
425         do {
426                 tf_numberstrips = TIFFNumberOfStrips(tif);
427                 TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP,
428                     &tf_rowsperstrip);
429                 setupPageState(tif, &w, &h, &prw, &prh);
430                 if (!*npages)
431                         PSHead(fd, tif, w, h, prw, prh, ox, oy);
432                 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE,
433                     &bitspersample);
434                 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL,
435                     &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) {
445                         case 1:
446                                 if (isCCITTCompression(tif))
447                                         photometric = PHOTOMETRIC_MINISWHITE;
448                                 else
449                                         photometric = PHOTOMETRIC_MINISBLACK;
450                                 break;
451                         case 3:
452                                 photometric = PHOTOMETRIC_RGB;
453                                 break;
454                         case 4:
455                                 photometric = PHOTOMETRIC_SEPARATED;
456                                 break;
457                         }
458                 }
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;
465                                 if (psw != 0.0) {
466                                         psw = pw * PS_UNIT_SIZE;
467                                         if (res_unit == RESUNIT_CENTIMETER)
468                                                 psw *= 2.54F;
469                                 } else
470                                         psw=rotate ? prh:prw;
471                                 if (psh != 0.0) {
472                                         psh = ph * PS_UNIT_SIZE;
473                                         if (res_unit == RESUNIT_CENTIMETER)
474                                                 psh *= 2.54F;
475                                 } else
476                                         psh=rotate ? prw:prh;
477                                 fprintf(fd,
478         "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
479                                         psw, psh);
480                                 fputs(
481         "<<\n  /Policies <<\n    /PageSize 3\n  >>\n>> setpagedevice\n",
482                                       fd);
483                         }
484                         fprintf(fd, "gsave\n");
485                         fprintf(fd, "100 dict begin\n");
486                         if (pw != 0 || ph != 0) {
487                                 if (!pw)
488                                         pw = prw;
489                                 if (!ph)
490                                         ph = prh;
491                                 if (maxPageHeight) { /* used -H option */
492                                         split = PlaceImage(fd,pw,ph,prw,prh,
493                                                            0,lm,bm,cnt);
494                                         while( split ) {
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",
501                                                     *npages, *npages);
502                                             fprintf(fd, "gsave\n");
503                                             fprintf(fd, "100 dict begin\n");
504                                             split = PlaceImage(fd,pw,ph,prw,prh,
505                                                                split,lm,bm,cnt);
506                                         }
507                                 } else {
508                                         pw *= PS_UNIT_SIZE;
509                                         ph *= PS_UNIT_SIZE;
510
511                                         /* NB: maintain image aspect ratio */
512                                         scale = pw/prw < ph/prh ?
513                                                 pw/prw : ph/prh;
514                                         if (scale > 1.0)
515                                                 scale = 1.0;
516                                         if (cnt) {
517                                                 bottom_offset +=
518                                                         (ph - prh * scale) / 2;
519                                                 left_offset +=
520                                                         (pw - prw * scale) / 2;
521                                         }
522                                         fprintf(fd, "%f %f translate\n",
523                                                 left_offset, bottom_offset);
524                                         fprintf(fd, "%f %f scale\n",
525                                                 prw * scale, prh * scale);
526                                         if (rotate)
527                                                 fputs ("1 1 translate 180 rotate\n", fd);
528                                 }
529                         } else {
530                                 fprintf(fd, "%f %f scale\n", prw, prh);
531                                 if (rotate)
532                                         fputs ("1 1 translate 180 rotate\n", fd);
533                         }
534                         PSpage(fd, tif, w, h);
535                         fprintf(fd, "end\n");
536                         fprintf(fd, "grestore\n");
537                         fprintf(fd, "showpage\n");
538                 }
539                 if (generateEPSF)
540                         break;
541                 TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
542         } while (((subfiletype & FILETYPE_PAGE) || printAll) &&
543             TIFFReadDirectory(tif));
544 }
545
546
547 static char DuplexPreamble[] = "\
548 %%BeginFeature: *Duplex True\n\
549 systemdict begin\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\
553   } ifelse\n\
554 end\n\
555 %%EndFeature\n\
556 ";
557
558 static char TumblePreamble[] = "\
559 %%BeginFeature: *Tumble True\n\
560 systemdict begin\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\
564   } ifelse\n\
565 end\n\
566 %%EndFeature\n\
567 ";
568
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\
577 ";
578
579 void
580 PSHead(FILE *fd, TIFF *tif, uint32 w, uint32 h,
581        double pw, double ph, double ox, double oy)
582 {
583         time_t t;
584
585         (void) tif; (void) w; (void) h;
586         t = time(0);
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");
599         if (PSduplex)
600                 fprintf(fd, "%s", DuplexPreamble);
601         if (PStumble)
602                 fprintf(fd, "%s", TumblePreamble);
603         if (PSavoiddeadzone && (level2 || level3))
604                 fprintf(fd, "%s", AvoidDeadZonePreamble);
605         fprintf(fd, "%%%%EndSetup\n");
606 }
607
608 void
609 TIFFPSTail(FILE *fd, int npages)
610 {
611         fprintf(fd, "%%%%Trailer\n");
612         fprintf(fd, "%%%%Pages: %d\n", npages);
613         fprintf(fd, "%%%%EOF\n");
614 }
615
616 static int
617 checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
618 {
619         (void) tif;
620         while (n-- > 0)
621                 if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
622                         return (16);
623         TIFFWarning(filename, "Assuming 8-bit colormap");
624         return (8);
625 }
626
627 static void
628 PS_Lvl2colorspace(FILE* fd, TIFF* tif)
629 {
630         uint16 *rmap, *gmap, *bmap;
631         int i, num_colors;
632         const char * colorspace_p;
633
634         switch ( photometric )
635         {
636         case PHOTOMETRIC_SEPARATED:
637                 colorspace_p = "CMYK";
638                 break;
639
640         case PHOTOMETRIC_RGB:
641                 colorspace_p = "RGB";
642                 break;
643
644         default:
645                 colorspace_p = "Gray";
646         }
647
648         /*
649          * Set up PostScript Level 2 colorspace according to
650          * section 4.8 in the PostScript refenence manual.
651          */
652         fputs("% PostScript Level 2 only.\n", fd);
653         if (photometric != PHOTOMETRIC_PALETTE) {
654                 if (photometric == PHOTOMETRIC_YCBCR) {
655                     /* MORE CODE HERE */
656                 }
657                 fprintf(fd, "/Device%s setcolorspace\n", colorspace_p );
658                 return;
659         }
660
661         /*
662          * Set up an indexed/palette colorspace
663          */
664         num_colors = (1 << bitspersample);
665         if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
666                 TIFFError(filename,
667                         "Palette image w/o \"Colormap\" tag");
668                 return;
669         }
670         if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
671                 /*
672                  * Convert colormap to 8-bits values.
673                  */
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]);
679                 }
680 #undef CVT
681         }
682         fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
683         if (ascii85) {
684                 Ascii85Init();
685                 fputs("\n<~", fd);
686                 ascii85breaklen -= 2;
687         } else
688                 fputs(" <", fd);
689         for (i = 0; i < num_colors; i++) {
690                 if (ascii85) {
691                         Ascii85Put((unsigned char)rmap[i], fd);
692                         Ascii85Put((unsigned char)gmap[i], fd);
693                         Ascii85Put((unsigned char)bmap[i], fd);
694                 } else {
695                         fputs((i % 8) ? " " : "\n  ", fd);
696                         fprintf(fd, "%02x%02x%02x",
697                             rmap[i], gmap[i], bmap[i]);
698                 }
699         }
700         if (ascii85)
701                 Ascii85Flush(fd);
702         else
703                 fputs(">\n", fd);
704         fputs("] setcolorspace\n", fd);
705 }
706
707 static int
708 PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h)
709 {
710         int use_rawdata;
711         uint32 tile_width, tile_height;
712         uint16 predictor, minsamplevalue, maxsamplevalue;
713         int repeat_count;
714         char im_h[64], im_x[64], im_y[64];
715         char * imageOp = "image";
716
717         if ( useImagemask && (bitspersample == 1) )
718                 imageOp = "imagemask";
719
720         (void)strcpy(im_x, "0");
721         (void)sprintf(im_y, "%lu", (long) h);
722         (void)sprintf(im_h, "%lu", (long) h);
723         tile_width = w;
724         tile_height = 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)) {
731                         /*
732                          * The tiles does not fit image width and height.
733                          * Set up a clip rectangle for the image unit square.
734                          */
735                         fputs("0 0 1 1 rectclip\n", fd);
736                 }
737                 if (tile_width < w) {
738                         fputs("/im_x 0 def\n", fd);
739                         (void)strcpy(im_x, "im_x neg");
740                 }
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);
744                 }
745         } else {
746                 repeat_count = tf_numberstrips;
747                 tile_height = tf_rowsperstrip;
748                 if (tile_height > h)
749                         tile_height = h;
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);
756                 }
757         }
758
759         /*
760          * Output start of exec block
761          */
762         fputs("{ % exec\n", fd);
763
764         if (repeat_count > 1)
765                 fprintf(fd, "%d { %% repeat\n", repeat_count);
766
767         /*
768          * Output filter options and image dictionary.
769          */
770         if (ascii85)
771                 fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
772                     fd);
773         fputs(" <<\n", fd);
774         fputs("  /ImageType 1\n", fd);
775         fprintf(fd, "  /Width %lu\n", (unsigned long) tile_width);
776         /*
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).
785          */
786         if (TIFFIsTiled(tif) || tf_numberstrips == 1)
787                 fprintf(fd, "  /Height %lu\n", (unsigned long) tile_height);
788         else
789                 fprintf(fd, "  /Height im_h\n");
790
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");
797
798         switch (samplesperpixel - extrasamples) {
799         case 1:
800                 switch (photometric) {
801                 case PHOTOMETRIC_MINISBLACK:
802                         fputs("  /Decode [0 1]\n", fd);
803                         break;
804                 case PHOTOMETRIC_MINISWHITE:
805                         switch (compression) {
806                         case COMPRESSION_CCITTRLE:
807                         case COMPRESSION_CCITTRLEW:
808                         case COMPRESSION_CCITTFAX3:
809                         case COMPRESSION_CCITTFAX4:
810                                 /*
811                                  * Manage inverting with /Blackis1 flag
812                                  * since there migth be uncompressed parts
813                                  */
814                                 fputs("  /Decode [0 1]\n", fd);
815                                 break;
816                         default:
817                                 /*
818                                  * ERROR...
819                                  */
820                                 fputs("  /Decode [1 0]\n", fd);
821                                 break;
822                         }
823                         break;
824                 case PHOTOMETRIC_PALETTE:
825                         TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
826                             &minsamplevalue);
827                         TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
828                             &maxsamplevalue);
829                         fprintf(fd, "  /Decode [%u %u]\n",
830                                     minsamplevalue, maxsamplevalue);
831                         break;
832                 default:
833                         /*
834                          * ERROR ?
835                          */
836                         fputs("  /Decode [0 1]\n", fd);
837                         break;
838                 }
839                 break;
840         case 3:
841                 switch (photometric) {
842                 case PHOTOMETRIC_RGB:
843                         fputs("  /Decode [0 1 0 1 0 1]\n", fd);
844                         break;
845                 case PHOTOMETRIC_MINISWHITE:
846                 case PHOTOMETRIC_MINISBLACK:
847                 default:
848                         /*
849                          * ERROR??
850                          */
851                         fputs("  /Decode [0 1 0 1 0 1]\n", fd);
852                         break;
853                 }
854                 break;
855         case 4:
856                 /*
857                  * ERROR??
858                  */
859                 fputs("  /Decode [0 1 0 1 0 1 0 1]\n", fd);
860                 break;
861         }
862         fputs("  /DataSource", fd);
863         if (planarconfiguration == PLANARCONFIG_SEPARATE &&
864             samplesperpixel > 1)
865                 fputs(" [", fd);
866         if (ascii85)
867                 fputs(" im_stream", fd);
868         else
869                 fputs(" currentfile /ASCIIHexDecode filter", fd);
870
871         use_rawdata = TRUE;
872         switch (compression) {
873         case COMPRESSION_NONE:          /* 1: uncompressed */
874                 break;
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) {
881                         uint32 g3_options;
882
883                         fputs("\t /EndOfLine true\n", fd);
884                         fputs("\t /EndOfBlock false\n", fd);
885                         if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
886                                             &g3_options))
887                                 g3_options = 0;
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);
894                 }
895                 if (compression == COMPRESSION_CCITTFAX4) {
896                         uint32 g4_options;
897
898                         fputs("\t /K -1\n", fd);
899                         TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
900                                                &g4_options);
901                         if (g4_options & GROUP4OPT_UNCOMPRESSED)
902                                 fputs("\t /Uncompressed true\n", fd);
903                 }
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);
912                 }
913                 if (photometric == PHOTOMETRIC_MINISBLACK)
914                         fputs("\t /BlackIs1 true\n", fd);
915                 fprintf(fd, "\t>> /CCITTFaxDecode filter");
916                 break;
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",
926                             bitspersample);
927                         fputs("\t>>", fd);
928                 }
929                 fputs(" /LZWDecode filter", fd);
930                 break;
931         case COMPRESSION_DEFLATE:       /* 5: ZIP */
932         case COMPRESSION_ADOBE_DEFLATE:
933                 if ( level3 ) {
934                          TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
935                          if (predictor > 1) {
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",
943                                         bitspersample);
944                                 fputs("\t>>", fd);
945                          }
946                          fputs(" /FlateDecode filter", fd);
947                 } else {
948                         use_rawdata = FALSE ;
949                 }
950                 break;
951         case COMPRESSION_PACKBITS:      /* 32773: Macintosh RLE */
952                 fputs(" /RunLengthDecode filter", fd);
953                 use_rawdata = TRUE;
954             break;
955         case COMPRESSION_OJPEG:         /* 6: !6.0 JPEG */
956         case COMPRESSION_JPEG:          /* 7: %JPEG DCT compression */
957 #ifdef notdef
958                 /*
959                  * Code not tested yet
960                  */
961                 fputs(" /DCTDecode filter", fd);
962                 use_rawdata = TRUE;
963 #else
964                 use_rawdata = FALSE;
965 #endif
966                 break;
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 */
971                 use_rawdata = FALSE;
972                 break;
973         case COMPRESSION_SGILOG:        /* 34676: SGI LogL or LogLuv */
974         case COMPRESSION_SGILOG24:      /* 34677: SGI 24-bit LogLuv */
975                 use_rawdata = FALSE;
976                 break;
977         default:
978                 /*
979                  * ERROR...
980                  */
981                 use_rawdata = FALSE;
982                 break;
983         }
984         if (planarconfiguration == PLANARCONFIG_SEPARATE &&
985             samplesperpixel > 1) {
986                 uint16 i;
987
988                 /*
989                  * NOTE: This code does not work yet...
990                  */
991                 for (i = 1; i < samplesperpixel; i++)
992                         fputs(" dup", fd);
993                 fputs(" ]", fd);
994         }
995
996         fprintf( fd, "\n >> %s\n", imageOp );
997         if (ascii85)
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",
1005                                     (unsigned long) w);
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);
1010                         }
1011                 }
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",
1018                                             (unsigned long) h);
1019                                         fprintf(fd, " dup %lu gt { pop",
1020                                             (unsigned long) tile_height);
1021                                         fprintf(fd, " %lu } if def\n",
1022                                             (unsigned long) tile_height);
1023                                 }
1024                         }
1025                 }
1026                 fputs("} repeat\n", fd);
1027         }
1028         /*
1029          * End of exec function
1030          */
1031         fputs("}\n", fd);
1032
1033         return(use_rawdata);
1034 }
1035
1036 #define MAXLINE         36
1037
1038 static int
1039 PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1040 {
1041         uint16 fillorder;
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;
1046
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 */
1050 #endif
1051
1052         PS_Lvl2colorspace(fd, tif);
1053         use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
1054
1055 /* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
1056 #ifdef ENABLE_BROKEN_BEGINENDDATA
1057         fputs("%%BeginData:\n", fd);
1058 #endif
1059         fputs("exec\n", fd);
1060
1061         tiled_image = TIFFIsTiled(tif);
1062         if (tiled_image) {
1063                 num_chunks = TIFFNumberOfTiles(tif);
1064                 TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
1065         } else {
1066                 num_chunks = TIFFNumberOfStrips(tif);
1067                 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
1068         }
1069
1070         if (use_rawdata) {
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];
1075         } else {
1076                 if (tiled_image)
1077                         chunk_size = TIFFTileSize(tif);
1078                 else
1079                         chunk_size = TIFFStripSize(tif);
1080         }
1081         buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
1082         if (!buf_data) {
1083                 TIFFError(filename, "Can't alloc %u bytes for %s.",
1084                         chunk_size, tiled_image ? "tiles" : "strips");
1085                 return(FALSE);
1086         }
1087
1088 #if defined( EXP_ASCII85ENCODER )
1089         if ( ascii85 ) {
1090             /*
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
1096              * 5*chunk_size/4.
1097              */
1098
1099             ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 );
1100
1101             if ( !ascii85_p ) {
1102                 _TIFFfree( buf_data );
1103
1104                 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
1105                 return ( FALSE );
1106             }
1107         }
1108 #endif
1109
1110         TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
1111         for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
1112                 if (ascii85)
1113                         Ascii85Init();
1114                 else
1115                         breaklen = MAXLINE;
1116                 if (use_rawdata) {
1117                         if (tiled_image)
1118                                 byte_count = TIFFReadRawTile(tif, chunk_no,
1119                                                   buf_data, chunk_size);
1120                         else
1121                                 byte_count = TIFFReadRawStrip(tif, chunk_no,
1122                                                   buf_data, chunk_size);
1123                         if (fillorder == FILLORDER_LSB2MSB)
1124                             TIFFReverseBits(buf_data, byte_count);
1125                 } else {
1126                         if (tiled_image)
1127                                 byte_count = TIFFReadEncodedTile(tif,
1128                                                 chunk_no, buf_data,
1129                                                 chunk_size);
1130                         else
1131                                 byte_count = TIFFReadEncodedStrip(tif,
1132                                                 chunk_no, buf_data,
1133                                                 chunk_size);
1134                 }
1135                 if (byte_count < 0) {
1136                         TIFFError(filename, "Can't read %s %d.",
1137                                 tiled_image ? "tile" : "strip", chunk_no);
1138                         if (ascii85)
1139                                 Ascii85Put('\0', fd);
1140                 }
1141                 /*
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.
1145                  *
1146                  * XXX: needs better solution
1147                  */
1148                 if (alpha) {
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];
1153                                 switch (ncomps) {
1154                                         case 1:
1155                                                 buf_data[j++] = buf_data[i] + adjust;
1156                                                 break;
1157                                         case 2:
1158                                                 buf_data[j++] = buf_data[i] + adjust;
1159                                                 buf_data[j++] = buf_data[i+1] + adjust;
1160                                                 break;
1161                                         case 3:
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;
1165                                                 break;
1166                                 }
1167                         }
1168                         byte_count -= j;
1169                 }
1170
1171                 if (ascii85) {
1172 #if defined( EXP_ASCII85ENCODER )
1173                         ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count );
1174
1175                         if ( ascii85_l > 0 )
1176                                 fwrite( ascii85_p, ascii85_l, 1, fd );
1177 #else
1178                         for (cp = buf_data; byte_count > 0; byte_count--)
1179                                 Ascii85Put(*cp++, fd);
1180 #endif
1181                 }
1182                 else
1183                 {
1184                         for (cp = buf_data; byte_count > 0; byte_count--) {
1185                                 putc(hex[((*cp)>>4)&0xf], fd);
1186                                 putc(hex[(*cp)&0xf], fd);
1187                                 cp++;
1188
1189                                 if (--breaklen <= 0) {
1190                                         putc('\n', fd);
1191                                         breaklen = MAXLINE;
1192                                 }
1193                         }
1194                 }
1195
1196                 if ( !ascii85 ) {
1197                         if ( level2 || level3 )
1198                                 putc( '>', fd );
1199                         putc('\n', fd);
1200                 }
1201 #if !defined( EXP_ASCII85ENCODER )
1202                 else
1203                         Ascii85Flush(fd);
1204 #endif
1205         }
1206
1207 #if defined( EXP_ASCII85ENCODER )
1208         if ( ascii85_p )
1209             _TIFFfree( ascii85_p );
1210 #endif
1211         _TIFFfree(buf_data);
1212 #ifdef ENABLE_BROKEN_BEGINENDDATA
1213         fputs("%%EndData\n", fd);
1214 #endif
1215         return(TRUE);
1216 }
1217
1218 void
1219 PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1220 {
1221         char    *       imageOp = "image";
1222
1223         if ( useImagemask && (bitspersample == 1) )
1224                 imageOp = "imagemask";
1225
1226         if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
1227                 return;
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);
1235                 } else {
1236                         PSColorSeparatePreamble(fd, w, h, 3);
1237                         PSDataColorSeparate(fd, tif, w, h, 3);
1238                 }
1239                 break;
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);
1245                 } else {
1246                         PSColorSeparatePreamble(fd, w, h, 4);
1247                         PSDataColorSeparate(fd, tif, w, h, 4);
1248                 }
1249                 break;
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);
1262                 break;
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);
1272                 fprintf(fd,
1273                     "{currentfile scanLine readhexstring pop} bind\n");
1274                 fprintf(fd, "%s\n", imageOp);
1275                 PSDataBW(fd, tif, w, h);
1276                 break;
1277         }
1278         putc('\n', fd);
1279 }
1280
1281 void
1282 PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc)
1283 {
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);
1293 }
1294
1295 void
1296 PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc)
1297 {
1298         int i;
1299
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);
1311 }
1312
1313 #define DOBREAK(len, howmany, fd) \
1314         if (((len) -= (howmany)) <= 0) {        \
1315                 putc('\n', fd);                 \
1316                 (len) = MAXLINE-(howmany);      \
1317         }
1318 #define PUTHEX(c,fd)    putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
1319
1320 void
1321 PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
1322 {
1323         uint32 row;
1324         int breaklen = MAXLINE, cc, es = samplesperpixel - nc;
1325         unsigned char *tf_buf;
1326         unsigned char *cp, c;
1327
1328         (void) w;
1329         tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1330         if (tf_buf == NULL) {
1331                 TIFFError(filename, "No space for scanline buffer");
1332                 return;
1333         }
1334         for (row = 0; row < h; row++) {
1335                 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1336                         break;
1337                 cp = tf_buf;
1338                 if (alpha) {
1339                         int adjust;
1340                         cc = 0;
1341                         for (; cc < tf_bytesperrow; cc += samplesperpixel) {
1342                                 DOBREAK(breaklen, nc, fd);
1343                                 /*
1344                                  * For images with alpha, matte against
1345                                  * a white background; i.e.
1346                                  *    Cback * (1 - Aimage)
1347                                  * where Cback = 1.
1348                                  */
1349                                 adjust = 255 - cp[nc];
1350                                 switch (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);
1355                                 }
1356                                 cp += es;
1357                         }
1358                 } else {
1359                         cc = 0;
1360                         for (; cc < tf_bytesperrow; cc += samplesperpixel) {
1361                                 DOBREAK(breaklen, nc, fd);
1362                                 switch (nc) {
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);
1367                                 }
1368                                 cp += es;
1369                         }
1370                 }
1371         }
1372         _TIFFfree((char *) tf_buf);
1373 }
1374
1375 void
1376 PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
1377 {
1378         uint32 row;
1379         int breaklen = MAXLINE, cc;
1380         tsample_t s, maxs;
1381         unsigned char *tf_buf;
1382         unsigned char *cp, c;
1383
1384         (void) w;
1385         tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
1386         if (tf_buf == NULL) {
1387                 TIFFError(filename, "No space for scanline buffer");
1388                 return;
1389         }
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)
1394                                 break;
1395                         for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
1396                                 DOBREAK(breaklen, 1, fd);
1397                                 c = *cp++;
1398                                 PUTHEX(c,fd);
1399                         }
1400                 }
1401         }
1402         _TIFFfree((char *) tf_buf);
1403 }
1404
1405 #define PUTRGBHEX(c,fd) \
1406         PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
1407
1408 void
1409 PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1410 {
1411         uint16 *rmap, *gmap, *bmap;
1412         uint32 row;
1413         int breaklen = MAXLINE, cc, nc;
1414         unsigned char *tf_buf;
1415         unsigned char *cp, c;
1416
1417         (void) w;
1418         if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
1419                 TIFFError(filename, "Palette image w/o \"Colormap\" tag");
1420                 return;
1421         }
1422         switch (bitspersample) {
1423         case 8: case 4: case 2: case 1:
1424                 break;
1425         default:
1426                 TIFFError(filename, "Depth %d not supported", bitspersample);
1427                 return;
1428         }
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");
1433                 return;
1434         }
1435         if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) {
1436                 int i;
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]);
1442                 }
1443 #undef CVT
1444         }
1445         for (row = 0; row < h; row++) {
1446                 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1447                         break;
1448                 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
1449                         DOBREAK(breaklen, nc, fd);
1450                         switch (bitspersample) {
1451                         case 8:
1452                                 c = *cp++; PUTRGBHEX(c, fd);
1453                                 break;
1454                         case 4:
1455                                 c = *cp++; PUTRGBHEX(c&0xf, fd);
1456                                 c >>= 4;   PUTRGBHEX(c, fd);
1457                                 break;
1458                         case 2:
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);
1463                                 break;
1464                         case 1:
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);
1473                                 break;
1474                         }
1475                 }
1476         }
1477         _TIFFfree((char *) tf_buf);
1478 }
1479
1480 void
1481 PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1482 {
1483         int breaklen = MAXLINE;
1484         unsigned char* tf_buf;
1485         unsigned char* cp;
1486         tsize_t stripsize = TIFFStripSize(tif);
1487         tstrip_t s;
1488
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 */
1492 #endif
1493
1494         (void) w; (void) h;
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");
1499                 return;
1500         }
1501
1502 #if defined( EXP_ASCII85ENCODER )
1503         if ( ascii85 ) {
1504             /*
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
1510              * 5*stripsize/4.
1511              */
1512
1513             ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 );
1514
1515             if ( !ascii85_p ) {
1516                 _TIFFfree( tf_buf );
1517
1518                 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
1519                 return;
1520             }
1521         }
1522 #endif
1523
1524         if (ascii85)
1525                 Ascii85Init();
1526
1527         for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
1528                 int cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
1529                 if (cc < 0) {
1530                         TIFFError(filename, "Can't read strip");
1531                         break;
1532                 }
1533                 cp = tf_buf;
1534                 if (photometric == PHOTOMETRIC_MINISWHITE) {
1535                         for (cp += cc; --cp >= tf_buf;)
1536                                 *cp = ~*cp;
1537                         cp++;
1538                 }
1539                 if (ascii85) {
1540 #if defined( EXP_ASCII85ENCODER )
1541                         if (alpha) {
1542                                 int adjust, i;
1543                                 for (i = 0; i < cc; i+=2) {
1544                                         adjust = 255 - cp[i + 1];
1545                                     cp[i / 2] = cp[i] + adjust;
1546                                 }
1547                                 cc /= 2;
1548                         }
1549
1550                         ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc );
1551
1552                         if ( ascii85_l > 0 )
1553                             fwrite( ascii85_p, ascii85_l, 1, fd );
1554 #else
1555                         while (cc-- > 0)
1556                                 Ascii85Put(*cp++, fd);
1557 #endif /* EXP_ASCII85_ENCODER */
1558                 } else {
1559                         unsigned char c;
1560
1561                         if (alpha) {
1562                                 int adjust;
1563                                 while (cc-- > 0) {
1564                                         DOBREAK(breaklen, 1, fd);
1565                                         /*
1566                                          * For images with alpha, matte against
1567                                          * a white background; i.e.
1568                                          *    Cback * (1 - Aimage)
1569                                          * where Cback = 1.
1570                                          */
1571                                         adjust = 255 - cp[1];
1572                                         c = *cp++ + adjust; PUTHEX(c,fd);
1573                                         cp++, cc--;
1574                                 }
1575                         } else {
1576                                 while (cc-- > 0) {
1577                                         c = *cp++;
1578                                         DOBREAK(breaklen, 1, fd);
1579                                         PUTHEX(c, fd);
1580                                 }
1581                         }
1582                 }
1583         }
1584
1585         if ( !ascii85 )
1586         {
1587             if ( level2 || level3)
1588                 fputs(">\n", fd);
1589         }
1590 #if !defined( EXP_ASCII85ENCODER )
1591         else
1592             Ascii85Flush(fd);
1593 #else
1594         if ( ascii85_p )
1595             _TIFFfree( ascii85_p );
1596 #endif
1597
1598         _TIFFfree(tf_buf);
1599 }
1600
1601 static void
1602 Ascii85Init(void)
1603 {
1604         ascii85breaklen = 2*MAXLINE;
1605         ascii85count = 0;
1606 }
1607
1608 static char*
1609 Ascii85Encode(unsigned char* raw)
1610 {
1611         static char encoded[6];
1612         uint32 word;
1613
1614         word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
1615         if (word != 0L) {
1616                 uint32 q;
1617                 uint16 w1;
1618
1619                 q = word / (85L*85*85*85);      /* actually only a byte */
1620                 encoded[0] = (char) (q + '!');
1621
1622                 word -= q * (85L*85*85*85); q = word / (85L*85*85);
1623                 encoded[1] = (char) (q + '!');
1624
1625                 word -= q * (85L*85*85); q = word / (85*85);
1626                 encoded[2] = (char) (q + '!');
1627
1628                 w1 = (uint16) (word - q*(85L*85));
1629                 encoded[3] = (char) ((w1 / 85) + '!');
1630                 encoded[4] = (char) ((w1 % 85) + '!');
1631                 encoded[5] = '\0';
1632         } else
1633                 encoded[0] = 'z', encoded[1] = '\0';
1634         return (encoded);
1635 }
1636
1637 void
1638 Ascii85Put(unsigned char code, FILE* fd)
1639 {
1640         ascii85buf[ascii85count++] = code;
1641         if (ascii85count >= 4) {
1642                 unsigned char* p;
1643                 int n;
1644
1645                 for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
1646                         char* cp;
1647                         for (cp = Ascii85Encode(p); *cp; cp++) {
1648                                 putc(*cp, fd);
1649                                 if (--ascii85breaklen == 0) {
1650                                         putc('\n', fd);
1651                                         ascii85breaklen = 2*MAXLINE;
1652                                 }
1653                         }
1654                 }
1655                 _TIFFmemcpy(ascii85buf, p, n);
1656                 ascii85count = n;
1657         }
1658 }
1659
1660 void
1661 Ascii85Flush(FILE* fd)
1662 {
1663         if (ascii85count > 0) {
1664                 char* res;
1665                 _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
1666                 res = Ascii85Encode(ascii85buf);
1667                 fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
1668         }
1669         fputs("~>\n", fd);
1670 }
1671 #if     defined( EXP_ASCII85ENCODER)
1672 \f
1673 #define A85BREAKCNTR    ascii85breaklen
1674 #define A85BREAKLEN     (2*MAXLINE)
1675
1676 /*****************************************************************************
1677 *
1678 * Name:         Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
1679 *
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.
1683 *
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
1690 *
1691 * Returns:      (int)   <   0   Error, see errno
1692 *                       >=  0   Number of bytes written to ascii85_p[].
1693 *
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
1703 *                          5 characters.
1704 *
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.
1711 *
1712 *****************************************************************************/
1713
1714 int Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, int raw_l )
1715
1716 {
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 */
1721
1722     ascii85_l = 0;                              /* Nothing written yet */
1723
1724     if ( raw_p )
1725     {
1726         --raw_p;                                /* Prepare for pre-increment fetches */
1727
1728         for ( ; raw_l > 3; raw_l -= 4 )
1729         {
1730             val32  = *(++raw_p) << 24;
1731             val32 += *(++raw_p) << 16;
1732             val32 += *(++raw_p) <<  8;
1733             val32 += *(++raw_p);
1734
1735             if ( val32 == 0 )                   /* Special case */
1736             {
1737                 ascii85_p[ascii85_l] = 'z';
1738                 rc = 1;
1739             }
1740
1741             else
1742             {
1743                 ascii85[4] = (char) ((val32 % 85) + 33);
1744                 val32 /= 85;
1745
1746                 ascii85[3] = (char) ((val32 % 85) + 33);
1747                 val32 /= 85;
1748
1749                 ascii85[2] = (char) ((val32 % 85) + 33);
1750                 val32 /= 85;
1751
1752                 ascii85[1] = (char) ((val32 % 85) + 33);
1753                 ascii85[0] = (char) ((val32 / 85) + 33);
1754
1755                 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
1756                 rc = sizeof(ascii85);
1757             }
1758
1759             ascii85_l += rc;
1760
1761             if ( (A85BREAKCNTR -= rc) <= 0 )
1762             {
1763                 ascii85_p[ascii85_l] = '\n';
1764                 ++ascii85_l;
1765                 A85BREAKCNTR = A85BREAKLEN;
1766             }
1767         }
1768
1769         /*
1770          * Output any straggler bytes:
1771          */
1772
1773         if ( raw_l > 0 )
1774         {
1775             int             len;                /* Output this many bytes */
1776
1777             len = raw_l + 1;
1778             val32 = *++raw_p << 24;             /* Prime the pump */
1779
1780             if ( --raw_l > 0 )  val32 += *(++raw_p) << 16;
1781             if ( --raw_l > 0 )  val32 += *(++raw_p) <<  8;
1782
1783             val32 /= 85;
1784
1785             ascii85[3] = (char) ((val32 % 85) + 33);
1786             val32 /= 85;
1787
1788             ascii85[2] = (char) ((val32 % 85) + 33);
1789             val32 /= 85;
1790
1791             ascii85[1] = (char) ((val32 % 85) + 33);
1792             ascii85[0] = (char) ((val32 / 85) + 33);
1793
1794             _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
1795             ascii85_l += len;
1796         }
1797     }
1798
1799     /*
1800      * If requested add an ASCII85 End Of Data marker:
1801      */
1802
1803     if ( f_eod )
1804     {
1805         ascii85_p[ascii85_l++] = '~';
1806         ascii85_p[ascii85_l++] = '>';
1807         ascii85_p[ascii85_l++] = '\n';
1808     }
1809
1810     return ( ascii85_l );
1811
1812 }   /* Ascii85EncodeBlock() */
1813
1814 #endif  /* EXP_ASCII85ENCODER */
1815
1816 /* vim: set ts=8 sts=8 sw=8 noet: */