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