]> www.fi.muni.cz Git - evince.git/blob - backend/tiff/tiff2ps.c
Updated Slovak translation
[evince.git] / backend / tiff / tiff2ps.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */
2 /* $Id$ */
3
4 /*
5  * Copyright (c) 1988-1997 Sam Leffler
6  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
7  *
8  * Permission to use, copy, modify, distribute, and sell this software and 
9  * its documentation for any purpose is hereby granted without fee, provided
10  * that (i) the above copyright notices and this permission notice appear in
11  * all copies of the software and related documentation, and (ii) the names of
12  * Sam Leffler and Silicon Graphics may not be used in any advertising or
13  * publicity relating to the software without the specific, prior written
14  * permission of Sam Leffler and Silicon Graphics.
15  * 
16  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
17  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
18  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
19  * 
20  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
21  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
22  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
23  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
24  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
25  * OF THIS SOFTWARE.
26  */
27
28 /*
29  * Modified for use as Evince TIFF ps exporter by
30  * Matthew S. Wilson <msw@rpath.com>
31  * Modifications Copyright (C) 2005 rpath, Inc.
32  *
33  */
34
35 #include <config.h>
36 #include <stdio.h>
37 #include <stdlib.h>                     /* for atof */
38 #include <math.h>
39 #include <time.h>
40 #include <string.h>
41 #include <unistd.h>
42
43 #include <glib.h>
44 #include <glib/gstdio.h>
45
46 #include "tiff2ps.h"
47
48 /*
49  * Revision history
50  *
51  * 2001-Mar-21
52  *    I (Bruce A. Mallett) added this revision history comment ;)
53  *
54  *    Fixed PS_Lvl2page() code which outputs non-ASCII85 raw
55  *    data.  Moved test for when to output a line break to
56  *    *after* the output of a character.  This just serves
57  *    to fix an eye-nuisance where the first line of raw
58  *    data was one character shorter than subsequent lines.
59  *
60  *    Added an experimental ASCII85 encoder which can be used
61  *    only when there is a single buffer of bytes to be encoded.
62  *    This version is much faster at encoding a straight-line
63  *    buffer of data because it can avoid alot of the loop
64  *    overhead of the byte-by-bye version.  To use this version
65  *    you need to define EXP_ASCII85ENCODER (experimental ...).
66  *
67  *    Added bug fix given by Michael Schmidt to PS_Lvl2page()
68  *    in which an end-of-data marker ('>') was not being output
69  *    when producing non-ASCII85 encoded PostScript Level 2
70  *    data.
71  *
72  *    Fixed PS_Lvl2colorspace() so that it no longer assumes that
73  *    a TIFF having more than 2 planes is a CMYK.  This routine
74  *    no longer looks at the samples per pixel but instead looks
75  *    at the "photometric" value.  This change allows support of
76  *    CMYK TIFFs.
77  *
78  *    Modified the PostScript L2 imaging loop so as to test if
79  *    the input stream is still open before attempting to do a
80  *    flushfile on it.  This was done because some RIPs close
81  *    the stream after doing the image operation.
82  *
83  *    Got rid of the realloc() being done inside a loop in the
84  *    PSRawDataBW() routine.  The code now walks through the
85  *    byte-size array outside the loop to determine the largest
86  *    size memory block that will be needed.
87  *
88  *    Added "-m" switch to ask tiff2ps to, where possible, use the
89  *    "imagemask" operator instead of the "image" operator.
90  *
91  *    Added the "-i #" switch to allow interpolation to be disabled.
92  *
93  *    Unrolled a loop or two to improve performance.
94  */
95
96 /*
97  * Define EXP_ASCII85ENCODER if you want to use an experimental
98  * version of the ASCII85 encoding routine.  The advantage of
99  * using this routine is that tiff2ps will convert to ASCII85
100  * encoding at between 3 and 4 times the speed as compared to
101  * using the old (non-experimental) encoder.  The disadvantage
102  * is that you will be using a new (and unproven) encoding
103  * routine.  So user beware, you have been warned!
104  */
105
106 #define EXP_ASCII85ENCODER
107
108 /*
109  * NB: this code assumes uint32 works with printf's %l[ud].
110  */
111
112 struct _TIFF2PSContext
113 {
114         char *filename;         /* input filename */
115         FILE *fd;               /* output file stream */
116         int ascii85;            /* use ASCII85 encoding */
117         int interpolate;        /* interpolate level2 image */
118         int level2;             /* generate PostScript level 2 */
119         int level3;             /* generate PostScript level 3 */
120         int generateEPSF;       /* generate Encapsulated PostScript */
121         int PSduplex;           /* enable duplex printing */
122         int PStumble;           /* enable top edge binding */
123         int PSavoiddeadzone;    /* enable avoiding printer deadzone */
124         double maxPageHeight;   /* maximum size to fit on page */
125         double splitOverlap;    /* amount for split pages to overlag */
126         int rotate;             /* rotate image by 180 degrees */
127         int useImagemask;       /* Use imagemask instead of image operator */
128         uint16 res_unit;        /* Resolution units: 2 - inches, 3 - cm */
129         int npages;             /* number of pages processed */
130
131         tsize_t tf_bytesperrow;
132         tsize_t ps_bytesperrow;
133         tsize_t tf_rowsperstrip;
134         tsize_t tf_numberstrips;
135
136         /*
137          * ASCII85 Encoding Support.
138          */
139         unsigned char ascii85buf[10];
140         int ascii85count;
141         int ascii85breaklen;
142         uint16 samplesperpixel;
143         uint16 bitspersample;
144         uint16 planarconfiguration;
145         uint16 photometric;
146         uint16 compression;
147         uint16 extrasamples;
148         int alpha;
149 };
150
151 static void PSpage(TIFF2PSContext*, TIFF*, uint32, uint32);
152 static void PSColorContigPreamble(TIFF2PSContext*, uint32, uint32, int);
153 static void PSColorSeparatePreamble(TIFF2PSContext*, uint32, uint32, int);
154 static void PSDataColorContig(TIFF2PSContext*, TIFF*, uint32, uint32, int);
155 static void PSDataColorSeparate(TIFF2PSContext*, TIFF*, uint32, uint32, int);
156 static void PSDataPalette(TIFF2PSContext*, TIFF*, uint32, uint32);
157 static void PSDataBW(TIFF2PSContext*, TIFF*, uint32, uint32);
158 static void Ascii85Init(TIFF2PSContext*);
159 static void Ascii85Put(TIFF2PSContext*, unsigned char);
160 static void Ascii85Flush(TIFF2PSContext*);
161 static void PSHead(TIFF2PSContext*, TIFF*, uint32, uint32,
162                    double, double, double, double);
163 static void PSTail(TIFF2PSContext*);
164
165 #if defined( EXP_ASCII85ENCODER )
166 static int Ascii85EncodeBlock(TIFF2PSContext*, uint8 * ascii85_p,
167                               unsigned f_eod, const uint8 * raw_p, int raw_l);
168 #endif
169
170 TIFF2PSContext* tiff2ps_context_new(const gchar *filename) {
171         TIFF2PSContext* ctx;
172
173         ctx = g_new0(TIFF2PSContext, 1);
174         ctx->filename = g_strdup(filename);
175         ctx->fd = g_fopen(ctx->filename, "w");
176         if (ctx->fd == NULL) {
177                 g_free (ctx->filename);
178                 g_free (ctx);
179                 return NULL;
180         }
181         ctx->interpolate = TRUE;     /* interpolate level2 image */
182         ctx->PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */
183         return ctx;
184 }
185
186 void tiff2ps_context_finalize(TIFF2PSContext *ctx) {
187         PSTail(ctx);
188         fclose(ctx->fd);
189         g_free(ctx->filename);
190         g_free(ctx);
191 }
192
193 static int
194 checkImage(TIFF2PSContext *ctx, TIFF* tif)
195 {
196         switch (ctx->photometric) {
197         case PHOTOMETRIC_YCBCR:
198                 if ((ctx->compression == COMPRESSION_JPEG
199                      || ctx->compression == COMPRESSION_OJPEG)
200                     && ctx->planarconfiguration == PLANARCONFIG_CONTIG) {
201                         /* can rely on libjpeg to convert to RGB */
202                         TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
203                                      JPEGCOLORMODE_RGB);
204                         ctx->photometric = PHOTOMETRIC_RGB;
205                 } else {
206                         if (ctx->level2 || ctx->level3)
207                                 break;
208                         TIFFError(ctx->filename, "Can not handle image with %s",
209                             "Ctx->PhotometricInterpretation=YCbCr");
210                         return (0);
211                 }
212                 /* fall thru... */
213         case PHOTOMETRIC_RGB:
214                 if (ctx->alpha && ctx->bitspersample != 8) {
215                         TIFFError(ctx->filename,
216                             "Can not handle %d-bit/sample RGB image with ctx->alpha",
217                             ctx->bitspersample);
218                         return (0);
219                 }
220                 /* fall thru... */
221         case PHOTOMETRIC_SEPARATED:
222         case PHOTOMETRIC_PALETTE:
223         case PHOTOMETRIC_MINISBLACK:
224         case PHOTOMETRIC_MINISWHITE:
225                 break;
226         case PHOTOMETRIC_LOGL:
227         case PHOTOMETRIC_LOGLUV:
228                 if (ctx->compression != COMPRESSION_SGILOG &&
229                     ctx->compression != COMPRESSION_SGILOG24) {
230                         TIFFError(ctx->filename,
231                     "Can not handle %s data with ctx->compression other than SGILog",
232                             (ctx->photometric == PHOTOMETRIC_LOGL) ?
233                                 "LogL" : "LogLuv"
234                         );
235                         return (0);
236                 }
237                 /* rely on library to convert to RGB/greyscale */
238                 TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
239                 ctx->photometric = (ctx->photometric == PHOTOMETRIC_LOGL) ?
240                     PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB;
241                 ctx->bitspersample = 8;
242                 break;
243         case PHOTOMETRIC_CIELAB:
244                 /* fall thru... */
245         default:
246                 TIFFError(ctx->filename,
247                     "Can not handle image with Ctx->PhotometricInterpretation=%d",
248                     ctx->photometric);
249                 return (0);
250         }
251         switch (ctx->bitspersample) {
252         case 1: case 2:
253         case 4: case 8:
254                 break;
255         default:
256                 TIFFError(ctx->filename, "Can not handle %d-bit/sample image",
257                     ctx->bitspersample);
258                 return (0);
259         }
260         if (ctx->planarconfiguration == PLANARCONFIG_SEPARATE &&
261             ctx->extrasamples > 0)
262                 TIFFWarning(ctx->filename, "Ignoring extra samples");
263         return (1);
264 }
265
266 #define PS_UNIT_SIZE    72.0F
267 #define PSUNITS(npix,res)       ((npix) * (PS_UNIT_SIZE / (res)))
268
269 static  char RGBcolorimage[] = "\
270 /bwproc {\n\
271     rgbproc\n\
272     dup length 3 idiv string 0 3 0\n\
273     5 -1 roll {\n\
274         add 2 1 roll 1 sub dup 0 eq {\n\
275             pop 3 idiv\n\
276             3 -1 roll\n\
277             dup 4 -1 roll\n\
278             dup 3 1 roll\n\
279             5 -1 roll put\n\
280             1 add 3 0\n\
281         } { 2 1 roll } ifelse\n\
282     } forall\n\
283     pop pop pop\n\
284 } def\n\
285 /colorimage where {pop} {\n\
286     /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
287 } ifelse\n\
288 ";
289
290 /*
291  * Adobe Photoshop requires a comment line of the form:
292  *
293  * %ImageData: <cols> <rows> <depth>  <main channels> <pad channels>
294  *      <block size> <1 for binary|2 for hex> "data start"
295  *
296  * It is claimed to be part of some future revision of the EPS spec.
297  */
298 static void
299 PhotoshopBanner(TIFF2PSContext* ctx, uint32 w, uint32 h, int bs, int nc,
300                 char* startline)
301 {
302         fprintf(ctx->fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
303             (long) w, (long) h, ctx->bitspersample, nc, bs);
304         fprintf(ctx->fd, startline, nc);
305         fprintf(ctx->fd, "\"\n");
306 }
307
308 /*
309  *   pw : image width in pixels
310  *   ph : image height in pixels
311  * pprw : image width in PS units (72 dpi)
312  * pprh : image height in PS units (72 dpi)
313  */
314 static void
315 setupPageState(TIFF2PSContext *ctx, TIFF* tif, uint32* pw, uint32* ph,
316                double* pprw, double* pprh)
317 {
318         float xres = 0.0F, yres = 0.0F;
319
320         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
321         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
322         if (ctx->res_unit == 0)
323                 TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &ctx->res_unit);
324         /*
325          * Calculate printable area.
326          */
327         if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
328             || fabs(xres) < 0.0000001)
329                 xres = PS_UNIT_SIZE;
330         if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
331             || fabs(yres) < 0.0000001)
332                 yres = PS_UNIT_SIZE;
333         switch (ctx->res_unit) {
334         case RESUNIT_CENTIMETER:
335                 xres *= 2.54F, yres *= 2.54F;
336                 break;
337         case RESUNIT_INCH:
338                 break;
339         case RESUNIT_NONE:
340         default:
341                 xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
342                 break;
343         }
344         *pprh = PSUNITS(*ph, yres);
345         *pprw = PSUNITS(*pw, xres);
346 }
347
348 static int
349 isCCITTCompression(TIFF* tif)
350 {
351     uint16 compress;
352     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
353     return (compress == COMPRESSION_CCITTFAX3 ||
354             compress == COMPRESSION_CCITTFAX4 ||
355             compress == COMPRESSION_CCITTRLE ||
356             compress == COMPRESSION_CCITTRLEW);
357 }
358
359 static  char *hex = "0123456789abcdef";
360
361 /*
362  * imagewidth & imageheight are 1/72 inches
363  * pagewidth & pageheight are inches
364  */
365 static int
366 PlaceImage(TIFF2PSContext *ctx, double pagewidth, double pageheight,
367            double imagewidth, double imageheight, int splitpage,
368            double lm, double bm, int cnt)
369 {
370         double xtran = 0;
371         double ytran = 0;
372         double xscale = 1;
373         double yscale = 1;
374         double left_offset = lm * PS_UNIT_SIZE;
375         double bottom_offset = bm * PS_UNIT_SIZE;
376         double subimageheight;
377         double splitheight;
378         double overlap;
379         /* buffers for locale-insitive number formatting */
380         gchar buf[2][G_ASCII_DTOSTR_BUF_SIZE];
381
382         pagewidth *= PS_UNIT_SIZE;
383         pageheight *= PS_UNIT_SIZE;
384
385         if (ctx->maxPageHeight==0)
386                 splitheight = 0;
387         else
388                 splitheight = ctx->maxPageHeight * PS_UNIT_SIZE;
389         overlap = ctx->splitOverlap * PS_UNIT_SIZE;
390
391         /*
392          * WIDTH:
393          *      if too wide, scrunch to fit
394          *      else leave it alone
395          */
396         if (imagewidth <= pagewidth) {
397                 xscale = imagewidth;
398         } else {
399                 xscale = pagewidth;
400         }
401
402         /* HEIGHT:
403          *      if too long, scrunch to fit
404          *      if too short, move to top of page
405          */
406         if (imageheight <= pageheight) {
407                 yscale = imageheight;
408                 ytran = pageheight - imageheight;
409         } else if (imageheight > pageheight &&
410                 (splitheight == 0 || imageheight <= splitheight)) {
411                 yscale = pageheight;
412         } else /* imageheight > splitheight */ {
413                 subimageheight = imageheight - (pageheight-overlap)*splitpage;
414                 if (subimageheight <= pageheight) {
415                         yscale = imageheight;
416                         ytran = pageheight - subimageheight;
417                         splitpage = 0;
418                 } else if ( subimageheight > pageheight && subimageheight <= splitheight) {
419                         yscale = imageheight * pageheight / subimageheight;
420                         ytran = 0;
421                         splitpage = 0;
422                 } else /* sumimageheight > splitheight */ {
423                         yscale = imageheight;
424                         ytran = pageheight - subimageheight;
425                         splitpage++;
426                 }
427         }
428
429         bottom_offset += ytran / (cnt?2:1);
430         if (cnt)
431                 left_offset += xtran / 2;
432
433         fprintf(ctx->fd, "%s %s translate\n",
434                 g_ascii_dtostr(buf[0], sizeof(buf[0]), left_offset),
435                 g_ascii_dtostr(buf[1], sizeof(buf[1]), bottom_offset));
436         fprintf(ctx->fd, "%s %s scale\n",
437                 g_ascii_dtostr(buf[0], sizeof(buf[0]), xscale),
438                 g_ascii_dtostr(buf[1], sizeof(buf[1]), yscale));
439         if (ctx->rotate)
440                 fputs ("1 1 translate 180 ctx->rotate\n", ctx->fd);
441
442         return splitpage;
443 }
444
445
446 void
447 tiff2ps_process_page(TIFF2PSContext* ctx, TIFF* tif, double pw, double ph,
448                      double lm, double bm, gboolean cnt)
449 {
450         uint32 w, h;
451         float ox, oy;
452         double prw, prh;
453         double scale = 1.0;
454         double left_offset = lm * PS_UNIT_SIZE;
455         double bottom_offset = bm * PS_UNIT_SIZE;
456         uint16* sampleinfo;
457         int split;
458         /* buffers for locale-insitive number formatting */
459         gchar buf[2][G_ASCII_DTOSTR_BUF_SIZE];
460
461         if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
462                 ox = 0;
463         if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
464                 oy = 0;
465         setupPageState(ctx, tif, &w, &h, &prw, &prh);
466
467         ctx->tf_numberstrips = TIFFNumberOfStrips(tif);
468         TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP,
469                               &ctx->tf_rowsperstrip);
470         setupPageState(ctx, tif, &w, &h, &prw, &prh);
471         if (!ctx->npages)
472                 PSHead(ctx, tif, w, h, prw, prh, ox, oy);
473         TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE,
474                               &ctx->bitspersample);
475         TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL,
476                               &ctx->samplesperpixel);
477         TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG,
478                               &ctx->planarconfiguration);
479         TIFFGetField(tif, TIFFTAG_COMPRESSION, &ctx->compression);
480         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
481                               &ctx->extrasamples, &sampleinfo);
482         ctx->alpha = (ctx->extrasamples == 1 &&
483                       sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
484         if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &ctx->photometric)) {
485                 switch (ctx->samplesperpixel - ctx->extrasamples) {
486                 case 1:
487                         if (isCCITTCompression(tif))
488                                 ctx->photometric = PHOTOMETRIC_MINISWHITE;
489                         else
490                                 ctx->photometric = PHOTOMETRIC_MINISBLACK;
491                         break;
492                 case 3:
493                         ctx->photometric = PHOTOMETRIC_RGB;
494                         break;
495                 case 4:
496                         ctx->photometric = PHOTOMETRIC_SEPARATED;
497                         break;
498                 }
499         }
500         if (checkImage(ctx, tif)) {
501                 ctx->tf_bytesperrow = TIFFScanlineSize(tif);
502                 ctx->npages++;
503                 fprintf(ctx->fd, "%%%%Page: %d %d\n", ctx->npages,
504                         ctx->npages);
505                 if (!ctx->generateEPSF && ( ctx->level2 || ctx->level3 )) {
506                         double psw = 0.0, psh = 0.0;
507                         if (psw != 0.0) {
508                                 psw = pw * PS_UNIT_SIZE;
509                                 if (ctx->res_unit == RESUNIT_CENTIMETER)
510                                         psw *= 2.54F;
511                         } else
512                                 psw=ctx->rotate ? prh:prw;
513                         if (psh != 0.0) {
514                                 psh = ph * PS_UNIT_SIZE;
515                                 if (ctx->res_unit == RESUNIT_CENTIMETER)
516                                         psh *= 2.54F;
517                         } else
518                                 psh=ctx->rotate ? prw:prh;
519                         fprintf(ctx->fd,
520                                 "1 dict begin /PageSize [ %s %s ] def currentdict end setpagedevice\n",
521                                 g_ascii_dtostr(buf[0], sizeof(buf[0]), psw),
522                                 g_ascii_dtostr(buf[1], sizeof(buf[1]), psh));
523                         fputs(
524                               "<<\n  /Policies <<\n    /PageSize 3\n  >>\n>> setpagedevice\n",
525                               ctx->fd);
526                 }
527                 fprintf(ctx->fd, "gsave\n");
528                 fprintf(ctx->fd, "100 dict begin\n");
529                 if (pw != 0 || ph != 0) {
530                         if (!pw)
531                                 pw = prw;
532                         if (!ph)
533                                 ph = prh;
534                         if (ctx->maxPageHeight) { /* used -H option */
535                                 split = PlaceImage(ctx,pw,ph,prw,prh,
536                                                    0,lm,bm,cnt);
537                                 while( split ) {
538                                         PSpage(ctx, tif, w, h);
539                                         fprintf(ctx->fd, "end\n");
540                                         fprintf(ctx->fd, "grestore\n");
541                                         fprintf(ctx->fd, "showpage\n");
542                                         ctx->npages++;
543                                         fprintf(ctx->fd, "%%%%Page: %d %d\n",
544                                                 ctx->npages, ctx->npages);
545                                         fprintf(ctx->fd, "gsave\n");
546                                         fprintf(ctx->fd, "100 dict begin\n");
547                                         split = PlaceImage(ctx,pw,ph,prw,prh,
548                                                            split,lm,bm,cnt);
549                                 }
550                         } else {
551                                 pw *= PS_UNIT_SIZE;
552                                 ph *= PS_UNIT_SIZE;
553
554                                 /* NB: maintain image aspect ratio */
555                                 scale = pw/prw < ph/prh ?
556                                         pw/prw : ph/prh;
557                                 if (scale > 1.0)
558                                         scale = 1.0;
559                                 if (cnt) {
560                                         bottom_offset +=
561                                                 (ph - prh * scale) / 2;
562                                         left_offset +=
563                                                 (pw - prw * scale) / 2;
564                                 }
565                                 fprintf(ctx->fd, "%s %s translate\n",
566                                         g_ascii_dtostr(buf[0], sizeof(buf[0]), left_offset),
567                                         g_ascii_dtostr(buf[1], sizeof(buf[1]), bottom_offset));
568                                 fprintf(ctx->fd, "%s %s scale\n",
569                                         g_ascii_dtostr(buf[0], sizeof(buf[0]), prw * scale),
570                                         g_ascii_dtostr(buf[1], sizeof(buf[1]), prh * scale));
571                                 if (ctx->rotate)
572                                         fputs ("1 1 translate 180 ctx->rotate\n", ctx->fd);
573                         }
574                 } else {
575                         fprintf(ctx->fd, "%s %s scale\n",
576                                 g_ascii_dtostr(buf[0], sizeof(buf[0]), prw),
577                                 g_ascii_dtostr(buf[1], sizeof(buf[1]), prh));
578                         if (ctx->rotate)
579                                 fputs ("1 1 translate 180 ctx->rotate\n", ctx->fd);
580                 }
581                 PSpage(ctx, tif, w, h);
582                 fprintf(ctx->fd, "end\n");
583                 fprintf(ctx->fd, "grestore\n");
584                 fprintf(ctx->fd, "showpage\n");
585         }
586 }
587
588
589 static char DuplexPreamble[] = "\
590 %%BeginFeature: *Duplex True\n\
591 systemdict begin\n\
592   /languagelevel where { pop languagelevel } { 1 } ifelse\n\
593   2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
594   { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
595   } ifelse\n\
596 end\n\
597 %%EndFeature\n\
598 ";
599
600 static char TumblePreamble[] = "\
601 %%BeginFeature: *Tumble True\n\
602 systemdict begin\n\
603   /languagelevel where { pop languagelevel } { 1 } ifelse\n\
604   2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
605   { statusdict /settumble known { statusdict begin true settumble end } if\n\
606   } ifelse\n\
607 end\n\
608 %%EndFeature\n\
609 ";
610
611 static char AvoidDeadZonePreamble[] = "\
612 gsave newpath clippath pathbbox grestore\n\
613   4 2 roll 2 copy translate\n\
614   exch 3 1 roll sub 3 1 roll sub exch\n\
615   currentpagedevice /PageSize get aload pop\n\
616   exch 3 1 roll div 3 1 roll div abs exch abs\n\
617   2 copy gt { exch } if pop\n\
618   dup 1 lt { dup scale } { pop } ifelse\n\
619 ";
620
621 void
622 PSHead(TIFF2PSContext *ctx, TIFF *tif, uint32 w, uint32 h,
623        double pw, double ph, double ox, double oy)
624 {
625         time_t t;
626
627         (void) tif; (void) w; (void) h;
628         t = time(0);
629         fprintf(ctx->fd, "%%!PS-Adobe-3.0%s\n",
630                 ctx->generateEPSF ? " EPSF-3.0" : "");
631         fprintf(ctx->fd, "%%%%Creator: Evince\n");
632         fprintf(ctx->fd, "%%%%CreationDate: %s", ctime(&t));
633         fprintf(ctx->fd, "%%%%DocumentData: Clean7Bit\n");
634         fprintf(ctx->fd, "%%%%Origin: %ld %ld\n", (long) ox, (long) oy);
635         /* NB: should use PageBoundingBox */
636         fprintf(ctx->fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
637                 (long) ceil(pw), (long) ceil(ph));
638         fprintf(ctx->fd, "%%%%LanguageLevel: %d\n",
639                 (ctx->level3 ? 3 : (ctx->level2 ? 2 : 1)));
640         fprintf(ctx->fd, "%%%%Pages: (atend)\n");
641         fprintf(ctx->fd, "%%%%EndComments\n");
642         fprintf(ctx->fd, "%%%%BeginSetup\n");
643         if (ctx->PSduplex)
644                 fprintf(ctx->fd, "%s", DuplexPreamble);
645         if (ctx->PStumble)
646                 fprintf(ctx->fd, "%s", TumblePreamble);
647         if (ctx->PSavoiddeadzone && (ctx->level2 || ctx->level3))
648                 fprintf(ctx->fd, "%s", AvoidDeadZonePreamble);
649         fprintf(ctx->fd, "%%%%EndSetup\n");
650 }
651
652 static void
653 PSTail(TIFF2PSContext *ctx)
654 {
655         if (!ctx->npages)
656                 return;
657         fprintf(ctx->fd, "%%%%Trailer\n");
658         fprintf(ctx->fd, "%%%%Pages: %d\n", ctx->npages);
659         fprintf(ctx->fd, "%%%%EOF\n");
660 }
661
662 static int
663 checkcmap(TIFF2PSContext* ctx, TIFF* tif, int n,
664           uint16* r, uint16* g, uint16* b)
665 {
666         (void) tif;
667         while (n-- > 0)
668                 if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
669                         return (16);
670         TIFFWarning(ctx->filename, "Assuming 8-bit colormap");
671         return (8);
672 }
673
674 static void
675 PS_Lvl2colorspace(TIFF2PSContext* ctx, TIFF* tif)
676 {
677         uint16 *rmap, *gmap, *bmap;
678         int i, num_colors;
679         const char * colorspace_p;
680
681         switch ( ctx->photometric )
682         {
683         case PHOTOMETRIC_SEPARATED:
684                 colorspace_p = "CMYK";
685                 break;
686
687         case PHOTOMETRIC_RGB:
688                 colorspace_p = "RGB";
689                 break;
690
691         default:
692                 colorspace_p = "Gray";
693         }
694
695         /*
696          * Set up PostScript Level 2 colorspace according to
697          * section 4.8 in the PostScript refenence manual.
698          */
699         fputs("% PostScript Level 2 only.\n", ctx->fd);
700         if (ctx->photometric != PHOTOMETRIC_PALETTE) {
701                 if (ctx->photometric == PHOTOMETRIC_YCBCR) {
702                     /* MORE CODE HERE */
703                 }
704                 fprintf(ctx->fd, "/Device%s setcolorspace\n", colorspace_p );
705                 return;
706         }
707
708         /*
709          * Set up an indexed/palette colorspace
710          */
711         num_colors = (1 << ctx->bitspersample);
712         if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
713                 TIFFError(ctx->filename,
714                         "Palette image w/o \"Colormap\" tag");
715                 return;
716         }
717         if (checkcmap(ctx, tif, num_colors, rmap, gmap, bmap) == 16) {
718                 /*
719                  * Convert colormap to 8-bits values.
720                  */
721 #define CVT(x)          (((x) * 255) / ((1L<<16)-1))
722                 for (i = 0; i < num_colors; i++) {
723                         rmap[i] = CVT(rmap[i]);
724                         gmap[i] = CVT(gmap[i]);
725                         bmap[i] = CVT(bmap[i]);
726                 }
727 #undef CVT
728         }
729         fprintf(ctx->fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
730         if (ctx->ascii85) {
731                 Ascii85Init(ctx);
732                 fputs("\n<~", ctx->fd);
733                 ctx->ascii85breaklen -= 2;
734         } else
735                 fputs(" <", ctx->fd);
736         for (i = 0; i < num_colors; i++) {
737                 if (ctx->ascii85) {
738                         Ascii85Put(ctx, (unsigned char)rmap[i]);
739                         Ascii85Put(ctx, (unsigned char)gmap[i]);
740                         Ascii85Put(ctx, (unsigned char)bmap[i]);
741                 } else {
742                         fputs((i % 8) ? " " : "\n  ", ctx->fd);
743                         fprintf(ctx->fd, "%02x%02x%02x",
744                             rmap[i], gmap[i], bmap[i]);
745                 }
746         }
747         if (ctx->ascii85)
748                 Ascii85Flush(ctx);
749         else
750                 fputs(">\n", ctx->fd);
751         fputs("] setcolorspace\n", ctx->fd);
752 }
753
754 static int
755 PS_Lvl2ImageDict(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h)
756 {
757         int use_rawdata;
758         uint32 tile_width, tile_height;
759         uint16 predictor, minsamplevalue, maxsamplevalue;
760         int repeat_count;
761         char im_h[64], im_x[64], im_y[64];
762         char * imageOp = "image";
763
764         if ( ctx->useImagemask && (ctx->bitspersample == 1) )
765                 imageOp = "imagemask";
766
767         (void)strcpy(im_x, "0");
768         (void)sprintf(im_y, "%lu", (long) h);
769         (void)sprintf(im_h, "%lu", (long) h);
770         tile_width = w;
771         tile_height = h;
772         if (TIFFIsTiled(tif)) {
773                 repeat_count = TIFFNumberOfTiles(tif);
774                 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
775                 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
776                 if (tile_width > w || tile_height > h ||
777                     (w % tile_width) != 0 || (h % tile_height != 0)) {
778                         /*
779                          * The tiles does not fit image width and height.
780                          * Set up a clip rectangle for the image unit square.
781                          */
782                         fputs("0 0 1 1 rectclip\n", ctx->fd);
783                 }
784                 if (tile_width < w) {
785                         fputs("/im_x 0 def\n", ctx->fd);
786                         (void)strcpy(im_x, "im_x neg");
787                 }
788                 if (tile_height < h) {
789                         fputs("/im_y 0 def\n", ctx->fd);
790                         (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
791                 }
792         } else {
793                 repeat_count = ctx->tf_numberstrips;
794                 tile_height = ctx->tf_rowsperstrip;
795                 if (tile_height > h)
796                         tile_height = h;
797                 if (repeat_count > 1) {
798                         fputs("/im_y 0 def\n", ctx->fd);
799                         fprintf(ctx->fd, "/im_h %lu def\n",
800                             (unsigned long) tile_height);
801                         (void)strcpy(im_h, "im_h");
802                         (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
803                 }
804         }
805
806         /*
807          * Output start of exec block
808          */
809         fputs("{ % exec\n", ctx->fd);
810
811         if (repeat_count > 1)
812                 fprintf(ctx->fd, "%d { %% repeat\n", repeat_count);
813
814         /*
815          * Output filter options and image dictionary.
816          */
817         if (ctx->ascii85)
818                 fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
819                       ctx->fd);
820         fputs(" <<\n", ctx->fd);
821         fputs("  /ImageType 1\n", ctx->fd);
822         fprintf(ctx->fd, "  /Width %lu\n", (unsigned long) tile_width);
823         /*
824          * Workaround for some software that may crash when last strip
825          * of image contains fewer number of scanlines than specified
826          * by the `/Height' variable. So for stripped images with multiple
827          * strips we will set `/Height' as `im_h', because one is 
828          * recalculated for each strip - including the (smaller) final strip.
829          * For tiled images and images with only one strip `/Height' will
830          * contain number of scanlines in tile (or image height in case of
831          * one-stripped image).
832          */
833         if (TIFFIsTiled(tif) || ctx->tf_numberstrips == 1)
834                 fprintf(ctx->fd, "  /Height %lu\n", (unsigned long) tile_height);
835         else
836                 fprintf(ctx->fd, "  /Height im_h\n");
837
838         if (ctx->planarconfiguration == PLANARCONFIG_SEPARATE && ctx->samplesperpixel > 1)
839                 fputs("  /MultipleDataSources true\n", ctx->fd);
840         fprintf(ctx->fd, "  /ImageMatrix [ %lu 0 0 %ld %s %s ]\n",
841             (unsigned long) w, - (long)h, im_x, im_y);
842         fprintf(ctx->fd, "  /BitsPerComponent %d\n", ctx->bitspersample);
843         fprintf(ctx->fd, "  /Ctx->Interpolate %s\n", ctx->interpolate ? "true" : "false");
844
845         switch (ctx->samplesperpixel - ctx->extrasamples) {
846         case 1:
847                 switch (ctx->photometric) {
848                 case PHOTOMETRIC_MINISBLACK:
849                         fputs("  /Decode [0 1]\n", ctx->fd);
850                         break;
851                 case PHOTOMETRIC_MINISWHITE:
852                         switch (ctx->compression) {
853                         case COMPRESSION_CCITTRLE:
854                         case COMPRESSION_CCITTRLEW:
855                         case COMPRESSION_CCITTFAX3:
856                         case COMPRESSION_CCITTFAX4:
857                                 /*
858                                  * Manage inverting with /Blackis1 flag
859                                  * since there migth be uncompressed parts
860                                  */
861                                 fputs("  /Decode [0 1]\n", ctx->fd);
862                                 break;
863                         default:
864                                 /*
865                                  * ERROR...
866                                  */
867                                 fputs("  /Decode [1 0]\n", ctx->fd);
868                                 break;
869                         }
870                         break;
871                 case PHOTOMETRIC_PALETTE:
872                         TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
873                             &minsamplevalue);
874                         TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
875                             &maxsamplevalue);
876                         fprintf(ctx->fd, "  /Decode [%u %u]\n",
877                                     minsamplevalue, maxsamplevalue);
878                         break;
879                 default:
880                         /*
881                          * ERROR ?
882                          */
883                         fputs("  /Decode [0 1]\n", ctx->fd);
884                         break;
885                 }
886                 break;
887         case 3:
888                 switch (ctx->photometric) {
889                 case PHOTOMETRIC_RGB:
890                         fputs("  /Decode [0 1 0 1 0 1]\n", ctx->fd);
891                         break;
892                 case PHOTOMETRIC_MINISWHITE:
893                 case PHOTOMETRIC_MINISBLACK:
894                 default:
895                         /*
896                          * ERROR??
897                          */
898                         fputs("  /Decode [0 1 0 1 0 1]\n", ctx->fd);
899                         break;
900                 }
901                 break;
902         case 4:
903                 /*
904                  * ERROR??
905                  */
906                 fputs("  /Decode [0 1 0 1 0 1 0 1]\n", ctx->fd);
907                 break;
908         }
909         fputs("  /DataSource", ctx->fd);
910         if (ctx->planarconfiguration == PLANARCONFIG_SEPARATE &&
911             ctx->samplesperpixel > 1)
912                 fputs(" [", ctx->fd);
913         if (ctx->ascii85)
914                 fputs(" im_stream", ctx->fd);
915         else
916                 fputs(" currentfile /ASCIIHexDecode filter", ctx->fd);
917
918         use_rawdata = TRUE;
919         switch (ctx->compression) {
920         case COMPRESSION_NONE:          /* 1: uncompressed */
921                 break;
922         case COMPRESSION_CCITTRLE:      /* 2: CCITT modified Huffman RLE */
923         case COMPRESSION_CCITTRLEW:     /* 32771: #1 w/ word alignment */
924         case COMPRESSION_CCITTFAX3:     /* 3: CCITT Group 3 fax encoding */
925         case COMPRESSION_CCITTFAX4:     /* 4: CCITT Group 4 fax encoding */
926                 fputs("\n\t<<\n", ctx->fd);
927                 if (ctx->compression == COMPRESSION_CCITTFAX3) {
928                         uint32 g3_options;
929
930                         fputs("\t /EndOfLine true\n", ctx->fd);
931                         fputs("\t /EndOfBlock false\n", ctx->fd);
932                         if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
933                                             &g3_options))
934                                 g3_options = 0;
935                         if (g3_options & GROUP3OPT_2DENCODING)
936                                 fprintf(ctx->fd, "\t /K %s\n", im_h);
937                         if (g3_options & GROUP3OPT_UNCOMPRESSED)
938                                 fputs("\t /Uncompressed true\n", ctx->fd);
939                         if (g3_options & GROUP3OPT_FILLBITS)
940                                 fputs("\t /EncodedByteAlign true\n", ctx->fd);
941                 }
942                 if (ctx->compression == COMPRESSION_CCITTFAX4) {
943                         uint32 g4_options;
944
945                         fputs("\t /K -1\n", ctx->fd);
946                         TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
947                                                &g4_options);
948                         if (g4_options & GROUP4OPT_UNCOMPRESSED)
949                                 fputs("\t /Uncompressed true\n", ctx->fd);
950                 }
951                 if (!(tile_width == w && w == 1728U))
952                         fprintf(ctx->fd, "\t /Columns %lu\n",
953                             (unsigned long) tile_width);
954                 fprintf(ctx->fd, "\t /Rows %s\n", im_h);
955                 if (ctx->compression == COMPRESSION_CCITTRLE ||
956                     ctx->compression == COMPRESSION_CCITTRLEW) {
957                         fputs("\t /EncodedByteAlign true\n", ctx->fd);
958                         fputs("\t /EndOfBlock false\n", ctx->fd);
959                 }
960                 if (ctx->photometric == PHOTOMETRIC_MINISBLACK)
961                         fputs("\t /BlackIs1 true\n", ctx->fd);
962                 fprintf(ctx->fd, "\t>> /CCITTFaxDecode filter");
963                 break;
964         case COMPRESSION_LZW:   /* 5: Lempel-Ziv & Welch */
965                 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
966                 if (predictor == 2) {
967                         fputs("\n\t<<\n", ctx->fd);
968                         fprintf(ctx->fd, "\t /Predictor %u\n", predictor);
969                         fprintf(ctx->fd, "\t /Columns %lu\n",
970                             (unsigned long) tile_width);
971                         fprintf(ctx->fd, "\t /Colors %u\n", ctx->samplesperpixel);
972                         fprintf(ctx->fd, "\t /BitsPerComponent %u\n",
973                             ctx->bitspersample);
974                         fputs("\t>>", ctx->fd);
975                 }
976                 fputs(" /LZWDecode filter", ctx->fd);
977                 break;
978         case COMPRESSION_DEFLATE:       /* 5: ZIP */
979         case COMPRESSION_ADOBE_DEFLATE:
980                 if ( ctx->level3 ) {
981                          TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
982                          if (predictor > 1) {
983                                 fprintf(ctx->fd, "\t %% PostScript Level 3 only.");
984                                 fputs("\n\t<<\n", ctx->fd);
985                                 fprintf(ctx->fd, "\t /Predictor %u\n", predictor);
986                                 fprintf(ctx->fd, "\t /Columns %lu\n",
987                                         (unsigned long) tile_width);
988                                 fprintf(ctx->fd, "\t /Colors %u\n", ctx->samplesperpixel);
989                                         fprintf(ctx->fd, "\t /BitsPerComponent %u\n",
990                                         ctx->bitspersample);
991                                 fputs("\t>>", ctx->fd);
992                          }
993                          fputs(" /FlateDecode filter", ctx->fd);
994                 } else {
995                         use_rawdata = FALSE ;
996                 }
997                 break;
998         case COMPRESSION_PACKBITS:      /* 32773: Macintosh RLE */
999                 fputs(" /RunLengthDecode filter", ctx->fd);
1000                 use_rawdata = TRUE;
1001             break;
1002         case COMPRESSION_OJPEG:         /* 6: !6.0 JPEG */
1003         case COMPRESSION_JPEG:          /* 7: %JPEG DCT ctx->compression */
1004 #ifdef notdef
1005                 /*
1006                  * Code not tested yet
1007                  */
1008                 fputs(" /DCTDecode filter", ctx->fd);
1009                 use_rawdata = TRUE;
1010 #else
1011                 use_rawdata = FALSE;
1012 #endif
1013                 break;
1014         case COMPRESSION_NEXT:          /* 32766: NeXT 2-bit RLE */
1015         case COMPRESSION_THUNDERSCAN:   /* 32809: ThunderScan RLE */
1016         case COMPRESSION_PIXARFILM:     /* 32908: Pixar companded 10bit LZW */
1017         case COMPRESSION_JBIG:          /* 34661: ISO JBIG */
1018                 use_rawdata = FALSE;
1019                 break;
1020         case COMPRESSION_SGILOG:        /* 34676: SGI LogL or LogLuv */
1021         case COMPRESSION_SGILOG24:      /* 34677: SGI 24-bit LogLuv */
1022                 use_rawdata = FALSE;
1023                 break;
1024         default:
1025                 /*
1026                  * ERROR...
1027                  */
1028                 use_rawdata = FALSE;
1029                 break;
1030         }
1031         if (ctx->planarconfiguration == PLANARCONFIG_SEPARATE &&
1032             ctx->samplesperpixel > 1) {
1033                 uint16 i;
1034
1035                 /*
1036                  * NOTE: This code does not work yet...
1037                  */
1038                 for (i = 1; i < ctx->samplesperpixel; i++)
1039                         fputs(" dup", ctx->fd);
1040                 fputs(" ]", ctx->fd);
1041         }
1042
1043         fprintf( ctx->fd, "\n >> %s\n", imageOp );
1044         if (ctx->ascii85)
1045                 fputs(" im_stream status { im_stream flushfile } if\n", ctx->fd);
1046         if (repeat_count > 1) {
1047                 if (tile_width < w) {
1048                         fprintf(ctx->fd, " /im_x im_x %lu add def\n",
1049                             (unsigned long) tile_width);
1050                         if (tile_height < h) {
1051                                 fprintf(ctx->fd, " im_x %lu ge {\n",
1052                                     (unsigned long) w);
1053                                 fputs("  /im_x 0 def\n", ctx->fd);
1054                                 fprintf(ctx->fd, " /im_y im_y %lu add def\n",
1055                                     (unsigned long) tile_height);
1056                                 fputs(" } if\n", ctx->fd);
1057                         }
1058                 }
1059                 if (tile_height < h) {
1060                         if (tile_width >= w) {
1061                                 fprintf(ctx->fd, " /im_y im_y %lu add def\n",
1062                                     (unsigned long) tile_height);
1063                                 if (!TIFFIsTiled(tif)) {
1064                                         fprintf(ctx->fd, " /im_h %lu im_y sub",
1065                                             (unsigned long) h);
1066                                         fprintf(ctx->fd, " dup %lu gt { pop",
1067                                             (unsigned long) tile_height);
1068                                         fprintf(ctx->fd, " %lu } if def\n",
1069                                             (unsigned long) tile_height);
1070                                 }
1071                         }
1072                 }
1073                 fputs("} repeat\n", ctx->fd);
1074         }
1075         /*
1076          * End of exec function
1077          */
1078         fputs("}\n", ctx->fd);
1079
1080         return(use_rawdata);
1081 }
1082
1083 #define MAXLINE         36
1084
1085 static int
1086 PS_Lvl2page(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h)
1087 {
1088         uint16 fillorder;
1089         int use_rawdata, tiled_image, breaklen = MAXLINE;
1090         uint32 chunk_no, num_chunks, *bc;
1091         unsigned char *buf_data, *cp;
1092         tsize_t chunk_size, byte_count;
1093
1094 #if defined( EXP_ASCII85ENCODER )
1095         int                     ascii85_l;      /* Length, in bytes, of ascii85_p[] data */
1096         uint8           *       ascii85_p = 0;  /* Holds ASCII85 encoded data */
1097 #endif
1098
1099         PS_Lvl2colorspace(ctx, tif);
1100         use_rawdata = PS_Lvl2ImageDict(ctx, tif, w, h);
1101
1102 /* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
1103 #ifdef ENABLE_BROKEN_BEGINENDDATA
1104         fputs("%%BeginData:\n", ctx->fd);
1105 #endif
1106         fputs("exec\n", ctx->fd);
1107
1108         tiled_image = TIFFIsTiled(tif);
1109         if (tiled_image) {
1110                 num_chunks = TIFFNumberOfTiles(tif);
1111                 TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
1112         } else {
1113                 num_chunks = TIFFNumberOfStrips(tif);
1114                 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
1115         }
1116
1117         if (use_rawdata) {
1118                 chunk_size = (tsize_t) bc[0];
1119                 for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
1120                         if ((tsize_t) bc[chunk_no] > chunk_size)
1121                                 chunk_size = (tsize_t) bc[chunk_no];
1122         } else {
1123                 if (tiled_image)
1124                         chunk_size = TIFFTileSize(tif);
1125                 else
1126                         chunk_size = TIFFStripSize(tif);
1127         }
1128         buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
1129         if (!buf_data) {
1130                 TIFFError(ctx->filename, "Can't alloc %u bytes for %s.",
1131                         chunk_size, tiled_image ? "tiles" : "strips");
1132                 return(FALSE);
1133         }
1134
1135 #if defined( EXP_ASCII85ENCODER )
1136         if ( ctx->ascii85 ) {
1137             /*
1138              * Allocate a buffer to hold the ASCII85 encoded data.  Note
1139              * that it is allocated with sufficient room to hold the
1140              * encoded data (5*chunk_size/4) plus the EOD marker (+8)
1141              * and formatting line breaks.  The line breaks are more
1142              * than taken care of by using 6*chunk_size/4 rather than
1143              * 5*chunk_size/4.
1144              */
1145
1146             ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 );
1147
1148             if ( !ascii85_p ) {
1149                 _TIFFfree( buf_data );
1150
1151                 TIFFError( ctx->filename,
1152                            "Cannot allocate ASCII85 encoding buffer." );
1153                 return ( FALSE );
1154             }
1155         }
1156 #endif
1157
1158         TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
1159         for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
1160                 if (ctx->ascii85)
1161                         Ascii85Init(ctx);
1162                 else
1163                         breaklen = MAXLINE;
1164                 if (use_rawdata) {
1165                         if (tiled_image)
1166                                 byte_count = TIFFReadRawTile(tif, chunk_no,
1167                                                   buf_data, chunk_size);
1168                         else
1169                                 byte_count = TIFFReadRawStrip(tif, chunk_no,
1170                                                   buf_data, chunk_size);
1171                         if (fillorder == FILLORDER_LSB2MSB)
1172                             TIFFReverseBits(buf_data, byte_count);
1173                 } else {
1174                         if (tiled_image)
1175                                 byte_count = TIFFReadEncodedTile(tif,
1176                                                 chunk_no, buf_data,
1177                                                 chunk_size);
1178                         else
1179                                 byte_count = TIFFReadEncodedStrip(tif,
1180                                                 chunk_no, buf_data,
1181                                                 chunk_size);
1182                 }
1183                 if (byte_count < 0) {
1184                         TIFFError(ctx->filename, "Can't read %s %d.",
1185                                 tiled_image ? "tile" : "strip", chunk_no);
1186                         if (ctx->ascii85)
1187                                 Ascii85Put(ctx, '\0');
1188                 }
1189                 /*
1190                  * For images with ctx->alpha, matte against a white background;
1191                  * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
1192                  * lower part of the buffer with the modified values.
1193                  *
1194                  * XXX: needs better solution
1195                  */
1196                 if (ctx->alpha) {
1197                         int adjust, i, j = 0;
1198                         int ncomps = ctx->samplesperpixel - ctx->extrasamples;
1199                         for (i = 0; i < byte_count; i+=ctx->samplesperpixel) {
1200                                 adjust = 255 - buf_data[i + ncomps];
1201                                 switch (ncomps) {
1202                                         case 1:
1203                                                 buf_data[j++] = buf_data[i] + adjust;
1204                                                 break;
1205                                         case 2:
1206                                                 buf_data[j++] = buf_data[i] + adjust;
1207                                                 buf_data[j++] = buf_data[i+1] + adjust;
1208                                                 break;
1209                                         case 3:
1210                                                 buf_data[j++] = buf_data[i] + adjust;
1211                                                 buf_data[j++] = buf_data[i+1] + adjust;
1212                                                 buf_data[j++] = buf_data[i+2] + adjust;
1213                                                 break;
1214                                 }
1215                         }
1216                         byte_count -= j;
1217                 }
1218
1219                 if (ctx->ascii85) {
1220 #if defined( EXP_ASCII85ENCODER )
1221                         ascii85_l = Ascii85EncodeBlock(ctx, ascii85_p, 1,
1222                                                        buf_data, byte_count);
1223
1224                         if ( ascii85_l > 0 )
1225                                 fwrite( ascii85_p, ascii85_l, 1, ctx->fd );
1226 #else
1227                         for (cp = buf_data; byte_count > 0; byte_count--)
1228                                 Ascii85Put(ctx, *cp++);
1229 #endif
1230                 }
1231                 else
1232                 {
1233                         for (cp = buf_data; byte_count > 0; byte_count--) {
1234                                 putc(hex[((*cp)>>4)&0xf], ctx->fd);
1235                                 putc(hex[(*cp)&0xf], ctx->fd);
1236                                 cp++;
1237
1238                                 if (--breaklen <= 0) {
1239                                         putc('\n', ctx->fd);
1240                                         breaklen = MAXLINE;
1241                                 }
1242                         }
1243                 }
1244
1245                 if ( !ctx->ascii85 ) {
1246                         if ( ctx->level2 || ctx->level3 )
1247                                 putc( '>', ctx->fd );
1248                         putc('\n', ctx->fd);
1249                 }
1250 #if !defined( EXP_ASCII85ENCODER )
1251                 else
1252                         Ascii85Flush(ctx);
1253 #endif
1254         }
1255
1256 #if defined( EXP_ASCII85ENCODER )
1257         if ( ascii85_p )
1258             _TIFFfree( ascii85_p );
1259 #endif
1260         _TIFFfree(buf_data);
1261 #ifdef ENABLE_BROKEN_BEGINENDDATA
1262         fputs("%%EndData\n", ctx->fd);
1263 #endif
1264         return(TRUE);
1265 }
1266
1267 void
1268 PSpage(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h)
1269 {
1270         char *imageOp = "image";
1271
1272         if ( ctx->useImagemask && (ctx->bitspersample == 1) )
1273                 imageOp = "imagemask";
1274
1275         if ((ctx->level2 || ctx->level3) && PS_Lvl2page(ctx, tif, w, h))
1276                 return;
1277         ctx->ps_bytesperrow = ctx->tf_bytesperrow - (ctx->extrasamples * ctx->bitspersample / 8)*w;
1278         switch (ctx->photometric) {
1279         case PHOTOMETRIC_RGB:
1280                 if (ctx->planarconfiguration == PLANARCONFIG_CONTIG) {
1281                         fprintf(ctx->fd, "%s", RGBcolorimage);
1282                         PSColorContigPreamble(ctx, w, h, 3);
1283                         PSDataColorContig(ctx, tif, w, h, 3);
1284                 } else {
1285                         PSColorSeparatePreamble(ctx, w, h, 3);
1286                         PSDataColorSeparate(ctx, tif, w, h, 3);
1287                 }
1288                 break;
1289         case PHOTOMETRIC_SEPARATED:
1290                 /* XXX should emit CMYKcolorimage */
1291                 if (ctx->planarconfiguration == PLANARCONFIG_CONTIG) {
1292                         PSColorContigPreamble(ctx, w, h, 4);
1293                         PSDataColorContig(ctx, tif, w, h, 4);
1294                 } else {
1295                         PSColorSeparatePreamble(ctx, w, h, 4);
1296                         PSDataColorSeparate(ctx, tif, w, h, 4);
1297                 }
1298                 break;
1299         case PHOTOMETRIC_PALETTE:
1300                 fprintf(ctx->fd, "%s", RGBcolorimage);
1301                 PhotoshopBanner(ctx, w, h, 1, 3, "false 3 colorimage");
1302                 fprintf(ctx->fd, "/scanLine %ld string def\n",
1303                         (long) ctx->ps_bytesperrow * 3L);
1304                 fprintf(ctx->fd, "%lu %lu 8\n",
1305                         (unsigned long) w, (unsigned long) h);
1306                 fprintf(ctx->fd, "[%lu 0 0 -%lu 0 %lu]\n",
1307                         (unsigned long) w, (unsigned long) h,
1308                         (unsigned long) h);
1309                 fprintf(ctx->fd,
1310                         "{currentfile scanLine readhexstring pop} bind\n");
1311                 fprintf(ctx->fd, "false 3 colorimage\n");
1312                 PSDataPalette(ctx, tif, w, h);
1313                 break;
1314         case PHOTOMETRIC_MINISBLACK:
1315         case PHOTOMETRIC_MINISWHITE:
1316                 PhotoshopBanner(ctx, w, h, 1, 1, imageOp);
1317                 fprintf(ctx->fd, "/scanLine %ld string def\n",
1318                     (long) ctx->ps_bytesperrow);
1319                 fprintf(ctx->fd, "%lu %lu %d\n",
1320                     (unsigned long) w, (unsigned long) h, ctx->bitspersample);
1321                 fprintf(ctx->fd, "[%lu 0 0 -%lu 0 %lu]\n",
1322                     (unsigned long) w, (unsigned long) h, (unsigned long) h);
1323                 fprintf(ctx->fd,
1324                     "{currentfile scanLine readhexstring pop} bind\n");
1325                 fprintf(ctx->fd, "%s\n", imageOp);
1326                 PSDataBW(ctx, tif, w, h);
1327                 break;
1328         }
1329         putc('\n', ctx->fd);
1330 }
1331
1332 void
1333 PSColorContigPreamble(TIFF2PSContext* ctx, uint32 w, uint32 h, int nc)
1334 {
1335         ctx->ps_bytesperrow = nc * (ctx->tf_bytesperrow / ctx->samplesperpixel);
1336         PhotoshopBanner(ctx, w, h, 1, nc, "false %d colorimage");
1337         fprintf(ctx->fd, "/line %ld string def\n", (long) ctx->ps_bytesperrow);
1338         fprintf(ctx->fd, "%lu %lu %d\n",
1339             (unsigned long) w, (unsigned long) h, ctx->bitspersample);
1340         fprintf(ctx->fd, "[%lu 0 0 -%lu 0 %lu]\n",
1341             (unsigned long) w, (unsigned long) h, (unsigned long) h);
1342         fprintf(ctx->fd, "{currentfile line readhexstring pop} bind\n");
1343         fprintf(ctx->fd, "false %d colorimage\n", nc);
1344 }
1345
1346 void
1347 PSColorSeparatePreamble(TIFF2PSContext* ctx, uint32 w, uint32 h, int nc)
1348 {
1349         int i;
1350
1351         PhotoshopBanner(ctx, w, h, ctx->ps_bytesperrow, nc, "true %d colorimage");
1352         for (i = 0; i < nc; i++)
1353                 fprintf(ctx->fd, "/line%d %ld string def\n",
1354                     i, (long) ctx->ps_bytesperrow);
1355         fprintf(ctx->fd, "%lu %lu %d\n",
1356             (unsigned long) w, (unsigned long) h, ctx->bitspersample);
1357         fprintf(ctx->fd, "[%lu 0 0 -%lu 0 %lu] \n",
1358             (unsigned long) w, (unsigned long) h, (unsigned long) h);
1359         for (i = 0; i < nc; i++)
1360                 fprintf(ctx->fd, "{currentfile line%d readhexstring pop}bind\n", i);
1361         fprintf(ctx->fd, "true %d colorimage\n", nc);
1362 }
1363
1364 #define DOBREAK(len, howmany, fd) \
1365         if (((len) -= (howmany)) <= 0) {        \
1366                 putc('\n', fd);                 \
1367                 (len) = MAXLINE-(howmany);      \
1368         }
1369 #define PUTHEX(c,fd)    putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
1370
1371 void
1372 PSDataColorContig(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h, int nc)
1373 {
1374         uint32 row;
1375         int breaklen = MAXLINE, cc, es = ctx->samplesperpixel - nc;
1376         unsigned char *tf_buf;
1377         unsigned char *cp, c;
1378
1379         (void) w;
1380         tf_buf = (unsigned char *) _TIFFmalloc(ctx->tf_bytesperrow);
1381         if (tf_buf == NULL) {
1382                 TIFFError(ctx->filename, "No space for scanline buffer");
1383                 return;
1384         }
1385         for (row = 0; row < h; row++) {
1386                 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1387                         break;
1388                 cp = tf_buf;
1389                 if (ctx->alpha) {
1390                         int adjust;
1391                         cc = 0;
1392                         for (; cc < ctx->tf_bytesperrow; cc += ctx->samplesperpixel) {
1393                                 DOBREAK(breaklen, nc, ctx->fd);
1394                                 /*
1395                                  * For images with ctx->alpha, matte against
1396                                  * a white background; i.e.
1397                                  *    Cback * (1 - Aimage)
1398                                  * where Cback = 1.
1399                                  */
1400                                 adjust = 255 - cp[nc];
1401                                 switch (nc) {
1402                                 case 4: c = *cp++ + adjust; PUTHEX(c,ctx->fd);
1403                                 case 3: c = *cp++ + adjust; PUTHEX(c,ctx->fd);
1404                                 case 2: c = *cp++ + adjust; PUTHEX(c,ctx->fd);
1405                                 case 1: c = *cp++ + adjust; PUTHEX(c,ctx->fd);
1406                                 }
1407                                 cp += es;
1408                         }
1409                 } else {
1410                         cc = 0;
1411                         for (; cc < ctx->tf_bytesperrow; cc += ctx->samplesperpixel) {
1412                                 DOBREAK(breaklen, nc, ctx->fd);
1413                                 switch (nc) {
1414                                 case 4: c = *cp++; PUTHEX(c,ctx->fd);
1415                                 case 3: c = *cp++; PUTHEX(c,ctx->fd);
1416                                 case 2: c = *cp++; PUTHEX(c,ctx->fd);
1417                                 case 1: c = *cp++; PUTHEX(c,ctx->fd);
1418                                 }
1419                                 cp += es;
1420                         }
1421                 }
1422         }
1423         _TIFFfree((char *) tf_buf);
1424 }
1425
1426 void
1427 PSDataColorSeparate(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h, int nc)
1428 {
1429         uint32 row;
1430         int breaklen = MAXLINE, cc;
1431         tsample_t s, maxs;
1432         unsigned char *tf_buf;
1433         unsigned char *cp, c;
1434
1435         (void) w;
1436         tf_buf = (unsigned char *) _TIFFmalloc(ctx->tf_bytesperrow);
1437         if (tf_buf == NULL) {
1438                 TIFFError(ctx->filename, "No space for scanline buffer");
1439                 return;
1440         }
1441         maxs = (ctx->samplesperpixel > nc ? nc : ctx->samplesperpixel);
1442         for (row = 0; row < h; row++) {
1443                 for (s = 0; s < maxs; s++) {
1444                         if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
1445                                 break;
1446                         for (cp = tf_buf, cc = 0; cc < ctx->tf_bytesperrow; cc++) {
1447                                 DOBREAK(breaklen, 1, ctx->fd);
1448                                 c = *cp++;
1449                                 PUTHEX(c,ctx->fd);
1450                         }
1451                 }
1452         }
1453         _TIFFfree((char *) tf_buf);
1454 }
1455
1456 #define PUTRGBHEX(c,fd) \
1457         PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
1458
1459 void
1460 PSDataPalette(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h)
1461 {
1462         uint16 *rmap, *gmap, *bmap;
1463         uint32 row;
1464         int breaklen = MAXLINE, cc, nc;
1465         unsigned char *tf_buf;
1466         unsigned char *cp, c;
1467
1468         (void) w;
1469         if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
1470                 TIFFError(ctx->filename, "Palette image w/o \"Colormap\" tag");
1471                 return;
1472         }
1473         switch (ctx->bitspersample) {
1474         case 8: case 4: case 2: case 1:
1475                 break;
1476         default:
1477                 TIFFError(ctx->filename, "Depth %d not supported", ctx->bitspersample);
1478                 return;
1479         }
1480         nc = 3 * (8 / ctx->bitspersample);
1481         tf_buf = (unsigned char *) _TIFFmalloc(ctx->tf_bytesperrow);
1482         if (tf_buf == NULL) {
1483                 TIFFError(ctx->filename, "No space for scanline buffer");
1484                 return;
1485         }
1486         if (checkcmap(ctx, tif, 1<<ctx->bitspersample, rmap, gmap, bmap) == 16) {
1487                 int i;
1488 #define CVT(x)          ((unsigned short) (((x) * 255) / ((1U<<16)-1)))
1489                 for (i = (1<<ctx->bitspersample)-1; i >= 0; i--) {
1490                         rmap[i] = CVT(rmap[i]);
1491                         gmap[i] = CVT(gmap[i]);
1492                         bmap[i] = CVT(bmap[i]);
1493                 }
1494 #undef CVT
1495         }
1496         for (row = 0; row < h; row++) {
1497                 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
1498                         break;
1499                 for (cp = tf_buf, cc = 0; cc < ctx->tf_bytesperrow; cc++) {
1500                         DOBREAK(breaklen, nc, ctx->fd);
1501                         switch (ctx->bitspersample) {
1502                         case 8:
1503                                 c = *cp++; PUTRGBHEX(c, ctx->fd);
1504                                 break;
1505                         case 4:
1506                                 c = *cp++; PUTRGBHEX(c&0xf, ctx->fd);
1507                                 c >>= 4;   PUTRGBHEX(c, ctx->fd);
1508                                 break;
1509                         case 2:
1510                                 c = *cp++; PUTRGBHEX(c&0x3, ctx->fd);
1511                                 c >>= 2;   PUTRGBHEX(c&0x3, ctx->fd);
1512                                 c >>= 2;   PUTRGBHEX(c&0x3, ctx->fd);
1513                                 c >>= 2;   PUTRGBHEX(c, ctx->fd);
1514                                 break;
1515                         case 1:
1516                                 c = *cp++; PUTRGBHEX(c&0x1, ctx->fd);
1517                                 c >>= 1;   PUTRGBHEX(c&0x1, ctx->fd);
1518                                 c >>= 1;   PUTRGBHEX(c&0x1, ctx->fd);
1519                                 c >>= 1;   PUTRGBHEX(c&0x1, ctx->fd);
1520                                 c >>= 1;   PUTRGBHEX(c&0x1, ctx->fd);
1521                                 c >>= 1;   PUTRGBHEX(c&0x1, ctx->fd);
1522                                 c >>= 1;   PUTRGBHEX(c&0x1, ctx->fd);
1523                                 c >>= 1;   PUTRGBHEX(c, ctx->fd);
1524                                 break;
1525                         }
1526                 }
1527         }
1528         _TIFFfree((char *) tf_buf);
1529 }
1530
1531 void
1532 PSDataBW(TIFF2PSContext* ctx, TIFF* tif, uint32 w, uint32 h)
1533 {
1534         int breaklen = MAXLINE;
1535         unsigned char* tf_buf;
1536         unsigned char* cp;
1537         tsize_t stripsize = TIFFStripSize(tif);
1538         tstrip_t s;
1539
1540 #if defined( EXP_ASCII85ENCODER )
1541         int     ascii85_l;              /* Length, in bytes, of ascii85_p[] data */
1542         uint8   *ascii85_p = 0;         /* Holds ASCII85 encoded data */
1543 #endif
1544
1545         (void) w; (void) h;
1546         tf_buf = (unsigned char *) _TIFFmalloc(stripsize);
1547         memset(tf_buf, 0, stripsize);
1548         if (tf_buf == NULL) {
1549                 TIFFError(ctx->filename, "No space for scanline buffer");
1550                 return;
1551         }
1552
1553 #if defined( EXP_ASCII85ENCODER )
1554         if ( ctx->ascii85 ) {
1555             /*
1556              * Allocate a buffer to hold the ASCII85 encoded data.  Note
1557              * that it is allocated with sufficient room to hold the
1558              * encoded data (5*stripsize/4) plus the EOD marker (+8)
1559              * and formatting line breaks.  The line breaks are more
1560              * than taken care of by using 6*stripsize/4 rather than
1561              * 5*stripsize/4.
1562              */
1563
1564             ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 );
1565
1566             if ( !ascii85_p ) {
1567                 _TIFFfree( tf_buf );
1568
1569                 TIFFError( ctx->filename,
1570                            "Cannot allocate ASCII85 encoding buffer." );
1571                 return;
1572             }
1573         }
1574 #endif
1575
1576         if (ctx->ascii85)
1577                 Ascii85Init(ctx);
1578
1579         for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
1580                 int cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
1581                 if (cc < 0) {
1582                         TIFFError(ctx->filename, "Can't read strip");
1583                         break;
1584                 }
1585                 cp = tf_buf;
1586                 if (ctx->photometric == PHOTOMETRIC_MINISWHITE) {
1587                         for (cp += cc; --cp >= tf_buf;)
1588                                 *cp = ~*cp;
1589                         cp++;
1590                 }
1591                 if (ctx->ascii85) {
1592 #if defined( EXP_ASCII85ENCODER )
1593                         if (ctx->alpha) {
1594                                 int adjust, i;
1595                                 for (i = 0; i < cc; i+=2) {
1596                                         adjust = 255 - cp[i + 1];
1597                                     cp[i / 2] = cp[i] + adjust;
1598                                 }
1599                                 cc /= 2;
1600                         }
1601
1602                         ascii85_l = Ascii85EncodeBlock(ctx, ascii85_p, 1, cp,
1603                                                        cc);
1604
1605                         if ( ascii85_l > 0 )
1606                             fwrite( ascii85_p, ascii85_l, 1, ctx->fd );
1607 #else
1608                         while (cc-- > 0)
1609                                 Ascii85Put(ctx, *cp++);
1610 #endif /* EXP_ASCII85_ENCODER */
1611                 } else {
1612                         unsigned char c;
1613
1614                         if (ctx->alpha) {
1615                                 int adjust;
1616                                 while (cc-- > 0) {
1617                                         DOBREAK(breaklen, 1, ctx->fd);
1618                                         /*
1619                                          * For images with ctx->alpha, matte against
1620                                          * a white background; i.e.
1621                                          *    Cback * (1 - Aimage)
1622                                          * where Cback = 1.
1623                                          */
1624                                         adjust = 255 - cp[1];
1625                                         c = *cp++ + adjust; PUTHEX(c,ctx->fd);
1626                                         cp++, cc--;
1627                                 }
1628                         } else {
1629                                 while (cc-- > 0) {
1630                                         c = *cp++;
1631                                         DOBREAK(breaklen, 1, ctx->fd);
1632                                         PUTHEX(c, ctx->fd);
1633                                 }
1634                         }
1635                 }
1636         }
1637
1638         if ( !ctx->ascii85 )
1639         {
1640             if ( ctx->level2 || ctx->level3)
1641                 fputs(">\n", ctx->fd);
1642         }
1643 #if !defined( EXP_ASCII85ENCODER )
1644         else
1645             Ascii85Flush(ctx);
1646 #else
1647         if ( ascii85_p )
1648             _TIFFfree( ascii85_p );
1649 #endif
1650
1651         _TIFFfree(tf_buf);
1652 }
1653
1654 static void
1655 Ascii85Init(TIFF2PSContext *ctx)
1656 {
1657         ctx->ascii85breaklen = 2*MAXLINE;
1658         ctx->ascii85count = 0;
1659 }
1660
1661 static void
1662 Ascii85Encode(unsigned char* raw, char *buf)
1663 {
1664         uint32 word;
1665
1666         word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
1667         if (word != 0L) {
1668                 uint32 q;
1669                 uint16 w1;
1670
1671                 q = word / (85L*85*85*85);      /* actually only a byte */
1672                 buf[0] = (char) (q + '!');
1673
1674                 word -= q * (85L*85*85*85); q = word / (85L*85*85);
1675                 buf[1] = (char) (q + '!');
1676
1677                 word -= q * (85L*85*85); q = word / (85*85);
1678                 buf[2] = (char) (q + '!');
1679
1680                 w1 = (uint16) (word - q*(85L*85));
1681                 buf[3] = (char) ((w1 / 85) + '!');
1682                 buf[4] = (char) ((w1 % 85) + '!');
1683                 buf[5] = '\0';
1684         } else
1685                 buf[0] = 'z', buf[1] = '\0';
1686 }
1687
1688 void
1689 Ascii85Put(TIFF2PSContext *ctx, unsigned char code)
1690 {
1691         ctx->ascii85buf[ctx->ascii85count++] = code;
1692         if (ctx->ascii85count >= 4) {
1693                 unsigned char* p;
1694                 int n;
1695                 char buf[6];
1696
1697                 for (n = ctx->ascii85count, p = ctx->ascii85buf;
1698                      n >= 4; n -= 4, p += 4) {
1699                         char* cp;
1700                         Ascii85Encode(p, buf);
1701                         for (cp = buf; *cp; cp++) {
1702                                 putc(*cp, ctx->fd);
1703                                 if (--ctx->ascii85breaklen == 0) {
1704                                         putc('\n', ctx->fd);
1705                                         ctx->ascii85breaklen = 2*MAXLINE;
1706                                 }
1707                         }
1708                 }
1709                 _TIFFmemcpy(ctx->ascii85buf, p, n);
1710                 ctx->ascii85count = n;
1711         }
1712 }
1713
1714 void
1715 Ascii85Flush(TIFF2PSContext* ctx)
1716 {
1717         if (ctx->ascii85count > 0) {
1718                 char res[6];
1719                 _TIFFmemset(&ctx->ascii85buf[ctx->ascii85count], 0, 3);
1720                 Ascii85Encode(ctx->ascii85buf, res);
1721                 fwrite(res[0] == 'z' ? "!!!!" : res, ctx->ascii85count + 1, 1, ctx->fd);
1722         }
1723         fputs("~>\n", ctx->fd);
1724 }
1725 #if     defined( EXP_ASCII85ENCODER)
1726 \f
1727 #define A85BREAKCNTR    ctx->ascii85breaklen
1728 #define A85BREAKLEN     (2*MAXLINE)
1729
1730 /*****************************************************************************
1731 *
1732 * Name:         Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
1733 *
1734 * Description:  This routine will encode the raw data in the buffer described
1735 *               by raw_p and raw_l into ASCII85 format and store the encoding
1736 *               in the buffer given by ascii85_p.
1737 *
1738 * Parameters:   ctx         -   TIFF2PS context
1739 *               ascii85_p   -   A buffer supplied by the caller which will
1740 *                               contain the encoded ASCII85 data.
1741 *               f_eod       -   Flag: Nz means to end the encoded buffer with
1742 *                               an End-Of-Data marker.
1743 *               raw_p       -   Pointer to the buffer of data to be encoded
1744 *               raw_l       -   Number of bytes in raw_p[] to be encoded
1745 *
1746 * Returns:      (int)   <   0   Error, see errno
1747 *                       >=  0   Number of bytes written to ascii85_p[].
1748 *
1749 * Notes:        An external variable given by A85BREAKCNTR is used to
1750 *               determine when to insert newline characters into the
1751 *               encoded data.  As each byte is placed into ascii85_p this
1752 *               external is decremented.  If the variable is decrement to
1753 *               or past zero then a newline is inserted into ascii85_p
1754 *               and the A85BREAKCNTR is then reset to A85BREAKLEN.
1755 *                   Note:  for efficiency reasons the A85BREAKCNTR variable
1756 *                          is not actually checked on *every* character
1757 *                          placed into ascii85_p but often only for every
1758 *                          5 characters.
1759 *
1760 *               THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
1761 *               SUFFICIENTLY LARGE TO THE ENCODED DATA!
1762 *                   You will need at least 5 * (raw_l/4) bytes plus space for
1763 *                   newline characters and space for an EOD marker (if
1764 *                   requested).  A safe calculation is to use 6*(raw_l/4) + 8
1765 *                   to size ascii85_p.
1766 *
1767 *****************************************************************************/
1768
1769 int Ascii85EncodeBlock( TIFF2PSContext *ctx, uint8 * ascii85_p,
1770                         unsigned f_eod, const uint8 * raw_p, int raw_l )
1771
1772 {
1773     char                        ascii85[5];     /* Encoded 5 tuple */
1774     int                         ascii85_l;      /* Number of bytes written to ascii85_p[] */
1775     int                         rc;             /* Return code */
1776     uint32                      val32;          /* Unencoded 4 tuple */
1777
1778     ascii85_l = 0;                              /* Nothing written yet */
1779
1780     if ( raw_p )
1781     {
1782         --raw_p;                                /* Prepare for pre-increment fetches */
1783
1784         for ( ; raw_l > 3; raw_l -= 4 )
1785         {
1786             val32  = *(++raw_p) << 24;
1787             val32 += *(++raw_p) << 16;
1788             val32 += *(++raw_p) <<  8;
1789             val32 += *(++raw_p);
1790
1791             if ( val32 == 0 )                   /* Special case */
1792             {
1793                 ascii85_p[ascii85_l] = 'z';
1794                 rc = 1;
1795             }
1796
1797             else
1798             {
1799                 ascii85[4] = (char) ((val32 % 85) + 33);
1800                 val32 /= 85;
1801
1802                 ascii85[3] = (char) ((val32 % 85) + 33);
1803                 val32 /= 85;
1804
1805                 ascii85[2] = (char) ((val32 % 85) + 33);
1806                 val32 /= 85;
1807
1808                 ascii85[1] = (char) ((val32 % 85) + 33);
1809                 ascii85[0] = (char) ((val32 / 85) + 33);
1810
1811                 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
1812                 rc = sizeof(ascii85);
1813             }
1814
1815             ascii85_l += rc;
1816
1817             if ( (A85BREAKCNTR -= rc) <= 0 )
1818             {
1819                 ascii85_p[ascii85_l] = '\n';
1820                 ++ascii85_l;
1821                 A85BREAKCNTR = A85BREAKLEN;
1822             }
1823         }
1824
1825         /*
1826          * Output any straggler bytes:
1827          */
1828
1829         if ( raw_l > 0 )
1830         {
1831             int             len;                /* Output this many bytes */
1832
1833             len = raw_l + 1;
1834             val32 = *++raw_p << 24;             /* Prime the pump */
1835
1836             if ( --raw_l > 0 )  val32 += *(++raw_p) << 16;
1837             if ( --raw_l > 0 )  val32 += *(++raw_p) <<  8;
1838
1839             val32 /= 85;
1840
1841             ascii85[3] = (char) ((val32 % 85) + 33);
1842             val32 /= 85;
1843
1844             ascii85[2] = (char) ((val32 % 85) + 33);
1845             val32 /= 85;
1846
1847             ascii85[1] = (char) ((val32 % 85) + 33);
1848             ascii85[0] = (char) ((val32 / 85) + 33);
1849
1850             _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
1851             ascii85_l += len;
1852         }
1853     }
1854
1855     /*
1856      * If requested add an ASCII85 End Of Data marker:
1857      */
1858
1859     if ( f_eod )
1860     {
1861         ascii85_p[ascii85_l++] = '~';
1862         ascii85_p[ascii85_l++] = '>';
1863         ascii85_p[ascii85_l++] = '\n';
1864     }
1865
1866     return ( ascii85_l );
1867
1868 }   /* Ascii85EncodeBlock() */
1869
1870 #endif  /* EXP_ASCII85ENCODER */
1871
1872 /* vim: set ts=8 sts=8 sw=8 noet: */