home *** CD-ROM | disk | FTP | other *** search
/ Practical Algorithms for Image Analysis / Practical Algorithms for Image Analysis.iso / TARFILE.GZ / tarfile / libtiff / tools / tiff2ps.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-09-11  |  34.8 KB  |  1,365 lines

  1. /* $Header: /usr/people/sam/tiff/tools/RCS/tiff2ps.c,v 1.48 1996/01/10 19:35:35 sam Rel $ */
  2.  
  3. /*
  4.  * Copyright (c) 1988-1996 Sam Leffler
  5.  * Copyright (c) 1991-1996 Silicon Graphics, Inc.
  6.  *
  7.  * Permission to use, copy, modify, distribute, and sell this software and 
  8.  * its documentation for any purpose is hereby granted without fee, provided
  9.  * that (i) the above copyright notices and this permission notice appear in
  10.  * all copies of the software and related documentation, and (ii) the names of
  11.  * Sam Leffler and Silicon Graphics may not be used in any advertising or
  12.  * publicity relating to the software without the specific, prior written
  13.  * permission of Sam Leffler and Silicon Graphics.
  14.  * 
  15.  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
  16.  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
  17.  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
  18.  * 
  19.  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  20.  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  21.  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  22.  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
  23.  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  24.  * OF THIS SOFTWARE.
  25.  */
  26.  
  27. #include <stdio.h>
  28. #include <stdlib.h>            /* for atof */
  29. #include <math.h>
  30. #include <time.h>
  31.  
  32. #include "tiffio.h"
  33.  
  34. /*
  35.  * NB: this code assumes uint32 works with printf's %l[ud].
  36.  */
  37. #ifndef TRUE
  38. #define    TRUE    1
  39. #define    FALSE    0
  40. #endif
  41.  
  42. int     ascii85 = FALSE;        /* use ASCII85 encoding */
  43. int    interpolate = TRUE;        /* interpolate level2 image */
  44. int    level2 = FALSE;            /* generate PostScript level 2 */
  45. int    printAll = FALSE;        /* print all images in file */
  46. int    generateEPSF = TRUE;        /* generate Encapsulated PostScript */
  47. int     PSduplex = FALSE;        /* enable duplex printing */
  48. int    PStumble = FALSE;        /* enable top edge binding */
  49. char    *filename;            /* input filename */
  50.  
  51. /*
  52.  * ASCII85 Encoding Support.
  53.  */
  54. unsigned char ascii85buf[10];
  55. int    ascii85count;
  56. int    ascii85breaklen;
  57.  
  58. int    TIFF2PS(FILE*, TIFF*, float, float);
  59. void    PSpage(FILE*, TIFF*, uint32, uint32);
  60. void    PSColorContigPreamble(FILE*, uint32, uint32, int);
  61. void    PSColorSeparatePreamble(FILE*, uint32, uint32, int);
  62. void    PSDataColorContig(FILE*, TIFF*, uint32, uint32, int);
  63. void    PSDataColorSeparate(FILE*, TIFF*, uint32, uint32, int);
  64. void    PSDataPalette(FILE*, TIFF*, uint32, uint32);
  65. void    PSDataBW(FILE*, TIFF*, uint32, uint32);
  66. void    PSRawDataBW(FILE*, TIFF*, uint32, uint32);
  67. void    Ascii85Init(void);
  68. void    Ascii85Put(unsigned char code, FILE* fd);
  69. void    Ascii85Flush(FILE* fd);
  70. void    PSHead(FILE*, TIFF*, uint32, uint32, float, float, float, float);
  71. void     PSTail(FILE*, int);
  72.  
  73. static    void usage(int);
  74.  
  75. int
  76. main(int argc, char* argv[])
  77. {
  78.     int dirnum = -1, c, np = 0;
  79.     float pageWidth = 0;
  80.     float pageHeight = 0;
  81.     uint32 diroff = 0;
  82.     extern char *optarg;
  83.     extern int optind;
  84.     FILE* output = stdout;
  85.  
  86.     while ((c = getopt(argc, argv, "h:w:d:o:O:aeps128DT")) != -1)
  87.         switch (c) {
  88.         case 'd':
  89.             dirnum = atoi(optarg);
  90.             break;
  91.             case 'D':
  92.             PSduplex = TRUE;
  93.             break;
  94.         case 'T':
  95.             PStumble = TRUE;
  96.             break;
  97.         case 'e':
  98.             generateEPSF = TRUE;
  99.             break;
  100.         case 'h':
  101.             pageHeight = atof(optarg);
  102.             break;
  103.         case 'o':
  104.             diroff = (uint32) strtoul(optarg, NULL, 0);
  105.             break;
  106.         case 'O':        /* XXX too bad -o is already taken */
  107.             output = fopen(optarg, "w");
  108.             if (output == NULL) {
  109.                 fprintf(stderr,
  110.                     "%s: %s: Cannot open output file.\n",
  111.                     argv[0], optarg);
  112.                 exit(-2);
  113.             }
  114.             break;
  115.         case 'a':
  116.             printAll = TRUE;
  117.             /* fall thru... */
  118.         case 'p':
  119.             generateEPSF = FALSE;
  120.             break;
  121.         case 's':
  122.             printAll = FALSE;
  123.             break;
  124.         case 'w':
  125.             pageWidth = atof(optarg);
  126.             break;
  127.         case '1':
  128.             level2 = FALSE;
  129.             ascii85 = FALSE;
  130.             break;
  131.         case '2':
  132.             level2 = TRUE;
  133.             ascii85 = TRUE;            /* default to yes */
  134.             break;
  135.         case '8':
  136.             ascii85 = FALSE;
  137.             break;
  138.         case '?':
  139.             usage(-1);
  140.         }
  141.     for (; argc - optind > 0; optind++) {
  142.         TIFF* tif = TIFFOpen(filename = argv[optind], "r");
  143.         if (tif != NULL) {
  144.             if (dirnum != -1 && !TIFFSetDirectory(tif, dirnum))
  145.                 return (-1);
  146.             else if (diroff != 0 &&
  147.                 !TIFFSetSubDirectory(tif, diroff))
  148.                 return (-1);
  149.             np = TIFF2PS(output, tif, pageWidth, pageHeight);
  150.             TIFFClose(tif);
  151.         }
  152.     }
  153.     if (np)
  154.             PSTail(output, np);
  155.     else
  156.             usage(-1);
  157.     if (output != stdout)
  158.         fclose(output);
  159.     return (0);
  160. }
  161.  
  162. static    uint16 samplesperpixel;
  163. static    uint16 bitspersample;
  164. static    uint16 planarconfiguration;
  165. static    uint16 photometric;
  166. static    uint16 compression;
  167. static    uint16 extrasamples;
  168. static    int alpha;
  169.  
  170. static int
  171. checkImage(TIFF* tif)
  172. {
  173.     switch (bitspersample) {
  174.     case 1: case 2:
  175.     case 4: case 8:
  176.         break;
  177.     default:
  178.         TIFFError(filename, "Can not handle %d-bit/sample image",
  179.             bitspersample);
  180.         return (0);
  181.     }
  182.     switch (photometric) {
  183.     case PHOTOMETRIC_YCBCR:
  184.         if (compression == COMPRESSION_JPEG &&
  185.             planarconfiguration == PLANARCONFIG_CONTIG) {
  186.             /* can rely on libjpeg to convert to RGB */
  187.             TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
  188.                      JPEGCOLORMODE_RGB);
  189.             photometric = PHOTOMETRIC_RGB;
  190.         } else {
  191.             if (level2)
  192.                 break;
  193.             TIFFError(filename, "Can not handle image with %s",
  194.                 "PhotometricInterpretation=YCbCr");
  195.             return (0);
  196.         }
  197.         /* fall thru... */
  198.     case PHOTOMETRIC_RGB:
  199.         if (alpha && bitspersample != 8) {
  200.             TIFFError(filename,
  201.                 "Can not handle %d-bit/sample RGB image with alpha",
  202.                 bitspersample);
  203.             return (0);
  204.         }
  205.         /* fall thru... */
  206.     case PHOTOMETRIC_SEPARATED:
  207.     case PHOTOMETRIC_PALETTE:
  208.     case PHOTOMETRIC_MINISBLACK:
  209.     case PHOTOMETRIC_MINISWHITE:
  210.         break;
  211.     case PHOTOMETRIC_CIELAB:
  212.         /* fall thru... */
  213.     default:
  214.         TIFFError(filename,
  215.             "Can not handle image with PhotometricInterpretation=%d",
  216.             photometric);
  217.         return (0);
  218.     }
  219.     if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
  220.         TIFFWarning(filename, "Ignoring extra samples");
  221.     return (1);
  222. }
  223.  
  224. #define PS_UNIT_SIZE    72.0
  225. #define    PSUNITS(npix,res)    ((npix) * (PS_UNIT_SIZE / (res)))
  226.  
  227. static    char RGBcolorimage[] = "\
  228. /bwproc {\n\
  229.     rgbproc\n\
  230.     dup length 3 idiv string 0 3 0\n\
  231.     5 -1 roll {\n\
  232.     add 2 1 roll 1 sub dup 0 eq {\n\
  233.         pop 3 idiv\n\
  234.         3 -1 roll\n\
  235.         dup 4 -1 roll\n\
  236.         dup 3 1 roll\n\
  237.         5 -1 roll put\n\
  238.         1 add 3 0\n\
  239.     } { 2 1 roll } ifelse\n\
  240.     } forall\n\
  241.     pop pop pop\n\
  242. } def\n\
  243. /colorimage where {pop} {\n\
  244.     /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
  245. } ifelse\n\
  246. ";
  247.  
  248. /*
  249.  * Adobe Photoshop requires a comment line of the form:
  250.  *
  251.  * %ImageData: <cols> <rows> <depth>  <main channels> <pad channels>
  252.  *    <block size> <1 for binary|2 for hex> "data start"
  253.  *
  254.  * It is claimed to be part of some future revision of the EPS spec.
  255.  */
  256. static void
  257. PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline)
  258. {
  259.     fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
  260.         (long) w, (long) h, bitspersample, nc, bs);
  261.     fprintf(fd, startline, nc);
  262.     fprintf(fd, "\"\n");
  263. }
  264.  
  265. static void
  266. setupPageState(TIFF* tif, uint32* pw, uint32* ph, float* pprw, float* pprh)
  267. {
  268.     uint16 res_unit;
  269.     float xres, yres;
  270.  
  271.     TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
  272.     TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
  273.     TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit);
  274.     /*
  275.      * Calculate printable area.
  276.      */
  277.     if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres))
  278.         xres = PS_UNIT_SIZE;
  279.     if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres))
  280.         yres = PS_UNIT_SIZE;
  281.     switch (res_unit) {
  282.     case RESUNIT_CENTIMETER:
  283.         xres /= 2.54, yres /= 2.54;
  284.         break;
  285.     case RESUNIT_NONE:
  286.         xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
  287.         break;
  288.     }
  289.     *pprh = PSUNITS(*ph, yres);
  290.     *pprw = PSUNITS(*pw, xres);
  291. }
  292.  
  293. static int
  294. isCCITTCompression(TIFF* tif)
  295. {
  296.     uint16 compress;
  297.     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
  298.     return (compress == COMPRESSION_CCITTFAX3 ||
  299.         compress == COMPRESSION_CCITTFAX4 ||
  300.         compress == COMPRESSION_CCITTRLE ||
  301.         compress == COMPRESSION_CCITTRLEW);
  302. }
  303.  
  304. static    tsize_t tf_bytesperrow;
  305. static    tsize_t ps_bytesperrow;
  306. static     tsize_t    tf_rowsperstrip;
  307. static    tsize_t    tf_numberstrips;
  308. static    char *hex = "0123456789abcdef";
  309.  
  310.  
  311. /* returns the sequence number of the page processed */
  312. int
  313. TIFF2PS(FILE* fd, TIFF* tif, float pw, float ph)
  314. {
  315.     uint32 w, h;
  316.     float ox, oy, prw, prh;
  317.     uint32 subfiletype;
  318.     uint16* sampleinfo;
  319.     static int npages = 0;
  320.  
  321.     if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
  322.         ox = 0;
  323.     if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
  324.         oy = 0;
  325.     setupPageState(tif, &w, &h, &prw, &prh);
  326.  
  327.     do {
  328.             tf_numberstrips = TIFFNumberOfStrips(tif);
  329.         TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP,
  330.             &tf_rowsperstrip);
  331.         setupPageState(tif, &w, &h, &prw, &prh);
  332.         if (!npages)
  333.                 PSHead(fd, tif, w, h, prw, prh, ox, oy);
  334.         tf_bytesperrow = TIFFScanlineSize(tif);
  335.         TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE,
  336.             &bitspersample);
  337.         TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL,
  338.             &samplesperpixel);
  339.         TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG,
  340.             &planarconfiguration);
  341.         TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
  342.         TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
  343.             &extrasamples, &sampleinfo);
  344.         alpha = (extrasamples == 1 &&
  345.              sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
  346.         if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) {
  347.             switch (samplesperpixel - extrasamples) {
  348.             case 1:
  349.                 if (isCCITTCompression(tif))
  350.                     photometric = PHOTOMETRIC_MINISWHITE;
  351.                 else
  352.                     photometric = PHOTOMETRIC_MINISBLACK;
  353.                 break;
  354.             case 3:
  355.                 photometric = PHOTOMETRIC_RGB;
  356.                 break;
  357.             }
  358.         }
  359.         if (checkImage(tif)) {
  360.             npages++;
  361.             fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
  362.             fprintf(fd, "gsave\n");
  363.             fprintf(fd, "100 dict begin\n");
  364.             if (pw != 0 && ph != 0)
  365.                 fprintf(fd, "%f %f scale\n",
  366.                     pw*PS_UNIT_SIZE, ph*PS_UNIT_SIZE);
  367.             else
  368.                 fprintf(fd, "%f %f scale\n", prw, prh);
  369.             PSpage(fd, tif, w, h);
  370.             fprintf(fd, "end\n");
  371.             fprintf(fd, "grestore\n");
  372.             fprintf(fd, "showpage\n");
  373.         }
  374.         if (generateEPSF)
  375.             break;
  376.         TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
  377.     } while (((subfiletype & FILETYPE_PAGE) || printAll) &&
  378.         TIFFReadDirectory(tif));
  379.  
  380.     return(npages);
  381. }
  382.  
  383.  
  384. static char DuplexPreamble[] = "\
  385. %%BeginFeature: *Duplex True\n\
  386. systemdict begin\n\
  387.   /languagelevel where { pop languagelevel } { 1 } ifelse\n\
  388.   2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
  389.   { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
  390.   } ifelse\n\
  391. end\n\
  392. %%EndFeature\n\
  393. ";
  394.  
  395. static char TumblePreamble[] = "\
  396. %%BeginFeature: *Tumble True\n\
  397. systemdict begin\n\
  398.   /languagelevel where { pop languagelevel } { 1 } ifelse\n\
  399.   2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
  400.   { statusdict /settumble known { statusdict begin settumble true end } if\n\
  401.   } ifelse\n\
  402. end\n\
  403. %%EndFeature\n\
  404. ";
  405.  
  406. void
  407. PSHead(FILE *fd, TIFF *tif, uint32 w, uint32 h, float pw, float ph,
  408.     float ox, float oy)
  409. {
  410.         time_t t;
  411.  
  412.     (void) tif; (void) w; (void) h;
  413.     t = time(0);
  414.     fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
  415.     fprintf(fd, "%%%%Creator: tiff2ps\n");
  416.     fprintf(fd, "%%%%Title: %s\n", filename);
  417.     fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
  418.     fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
  419.     fprintf(fd, "%%%%Origin: %ld %ld\n", (long) ox, (long) oy);
  420.     /* NB: should use PageBoundingBox */
  421.     fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
  422.         (long) ceil(pw), (long) ceil(ph));
  423.     fprintf(fd, "%%%%LanguageLevel: %d\n", level2 ? 2 : 1);
  424.     fprintf(fd, "%%%%Pages: (atend)\n");
  425.     fprintf(fd, "%%%%EndComments\n");
  426.     fprintf(fd, "%%%%BeginSetup\n");
  427.     if (PSduplex)
  428.             fprintf(fd, "%s", DuplexPreamble);
  429.     if (PStumble)
  430.             fprintf(fd, "%s", TumblePreamble);
  431.     fprintf(fd, "%%%%EndSetup\n");
  432. }
  433.  
  434. void
  435. PSTail(FILE *fd, int npages)
  436. {
  437.     fprintf(fd, "%%%%Trailer\n");
  438.         fprintf(fd, "%%%%Pages: %d\n", npages);
  439.     fprintf(fd, "%%%%EOF\n");
  440. }
  441.  
  442. static int
  443. checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
  444. {
  445.     (void) tif;
  446.     while (n-- > 0)
  447.         if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
  448.             return (16);
  449.     TIFFWarning(filename, "Assuming 8-bit colormap");
  450.     return (8);
  451. }
  452.  
  453. static void
  454. PS_Lvl2colorspace(FILE* fd, TIFF* tif)
  455. {
  456.     uint16 *rmap, *gmap, *bmap;
  457.     int i, num_colors;
  458.  
  459.     /*
  460.      * Set up PostScript Level 2 colorspace according to
  461.      * section 4.8 in the PostScript refenence manual.
  462.      */
  463.     fputs("% PostScript Level 2 only.\n", fd);
  464.     if (photometric != PHOTOMETRIC_PALETTE) {
  465.         if (photometric == PHOTOMETRIC_YCBCR) {
  466.             /* MORE CODE HERE */
  467.         }
  468.         fprintf(fd, "/Device%s",
  469.             samplesperpixel > 2 ? "RGB" : "Gray");
  470.         fputs(" setcolorspace\n", fd);
  471.         return;
  472.     }
  473.  
  474.     /*
  475.      * Set up an indexed/palette colorspace
  476.      */
  477.     num_colors = (1 << bitspersample);
  478.     if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
  479.         TIFFError(filename,
  480.             "Palette image w/o \"Colormap\" tag");
  481.         return;
  482.     }
  483.     if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
  484.         /*
  485.          * Convert colormap to 8-bits values.
  486.          */
  487. #define    CVT(x)        (((x) * 255) / ((1L<<16)-1))
  488.         for (i = 0; i < num_colors; i++) {
  489.             rmap[i] = CVT(rmap[i]);
  490.             gmap[i] = CVT(gmap[i]);
  491.             bmap[i] = CVT(bmap[i]);
  492.         }
  493. #undef CVT
  494.     }
  495.     fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
  496.     if (ascii85) {
  497.         Ascii85Init();
  498.         fputs("\n<~", fd);
  499.         ascii85breaklen -= 2;
  500.     } else
  501.         fputs(" <", fd);
  502.     for (i = 0; i < num_colors; i++) {
  503.         if (ascii85) {
  504.             Ascii85Put(rmap[i], fd);
  505.             Ascii85Put(gmap[i], fd);
  506.             Ascii85Put(bmap[i], fd);
  507.         } else {
  508.             fputs((i % 8) ? " " : "\n  ", fd);
  509.             fprintf(fd, "%02x%02x%02x",
  510.                 rmap[i], gmap[i], bmap[i]);
  511.         }
  512.     }
  513.     if (ascii85)
  514.         Ascii85Flush(fd);
  515.     else
  516.         fputs(">\n", fd);
  517.     fputs("] setcolorspace\n", fd);
  518. }
  519.  
  520. static int
  521. PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h)
  522. {
  523.     int use_rawdata;
  524.     uint32 tile_width, tile_height;
  525.     uint16 predictor, minsamplevalue, maxsamplevalue;
  526.     int repeat_count;
  527.     char im_h[64], im_x[64], im_y[64];
  528.  
  529.     (void)strcpy(im_x, "0");
  530.     (void)sprintf(im_y, "%lu", (long) h);
  531.     (void)sprintf(im_h, "%lu", (long) h);
  532.     tile_width = w;
  533.     tile_height = h;
  534.     if (TIFFIsTiled(tif)) {
  535.         repeat_count = TIFFNumberOfTiles(tif);
  536.         TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
  537.         TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
  538.         if (tile_width > w || tile_height > h ||
  539.             (w % tile_width) != 0 || (h % tile_height != 0)) {
  540.             /*
  541.              * The tiles does not fit image width and height.
  542.              * Set up a clip rectangle for the image unit square.
  543.              */
  544.             fputs("0 0 1 1 rectclip\n", fd);
  545.         }
  546.         if (tile_width < w) {
  547.             fputs("/im_x 0 def\n", fd);
  548.             (void)strcpy(im_x, "im_x neg");
  549.         }
  550.         if (tile_height < h) {
  551.             fputs("/im_y 0 def\n", fd);
  552.             (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
  553.         }
  554.     } else {
  555.         repeat_count = tf_numberstrips;
  556.         tile_height = tf_rowsperstrip;
  557.         if (tile_height > h)
  558.             tile_height = h;
  559.         if (repeat_count > 1) {
  560.             fputs("/im_y 0 def\n", fd);
  561.             fprintf(fd, "/im_h %lu def\n",
  562.                 (unsigned long) tile_height);
  563.             (void)strcpy(im_h, "im_h");
  564.             (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
  565.         }
  566.     }
  567.  
  568.     /*
  569.      * Output start of exec block
  570.      */
  571.     fputs("{ % exec\n", fd);
  572.  
  573.     if (repeat_count > 1)
  574.         fprintf(fd, "%d { %% repeat\n", repeat_count);
  575.  
  576.     /*
  577.      * Output filter options and image dictionary.
  578.      */
  579.     if (ascii85)
  580.         fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
  581.             fd);
  582.     fputs(" <<\n", fd);
  583.     fputs("  /ImageType 1\n", fd);
  584.     fprintf(fd, "  /Width %lu\n", (unsigned long) tile_width);
  585.     fprintf(fd, "  /Height %lu\n", (unsigned long) tile_height);
  586.     if (planarconfiguration == PLANARCONFIG_SEPARATE)
  587.         fputs("  /MultipleDataSources true\n", fd);
  588.     fprintf(fd, "  /ImageMatrix [ %lu 0 0 %ld %s %s ]\n",
  589.         (unsigned long) w, - (long)h, im_x, im_y);
  590.     fprintf(fd, "  /BitsPerComponent %d\n", bitspersample);
  591.     fprintf(fd, "  /Interpolate %s\n", interpolate ? "true" : "false");
  592.  
  593.     switch (samplesperpixel) {
  594.     case 1:
  595.         switch (photometric) {
  596.         case PHOTOMETRIC_MINISBLACK:
  597.             fputs("  /Decode [0 1]\n", fd);
  598.             break;
  599.         case PHOTOMETRIC_MINISWHITE:
  600.             switch (compression) {
  601.             case COMPRESSION_CCITTRLE:
  602.             case COMPRESSION_CCITTRLEW:
  603.             case COMPRESSION_CCITTFAX3:
  604.             case COMPRESSION_CCITTFAX4:
  605.                 /*
  606.                  * Manage inverting with /Blackis1 flag
  607.                  * since there migth be uncompressed parts
  608.                  */
  609.                 fputs("  /Decode [0 1]\n", fd);
  610.                 break;
  611.             default:
  612.                 /*
  613.                  * ERROR...
  614.                  */
  615.                 fputs("  /Decode [1 0]\n", fd);
  616.                 break;
  617.             }
  618.             break;
  619.         case PHOTOMETRIC_PALETTE:
  620.             TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
  621.                 &minsamplevalue);
  622.             TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
  623.                 &maxsamplevalue);
  624.             fprintf(fd, "  /Decode [%u %u]\n",
  625.                     minsamplevalue, maxsamplevalue);
  626.             break;
  627.         default:
  628.             /*
  629.              * ERROR ?
  630.              */
  631.             fputs("  /Decode [0 1]\n", fd);
  632.             break;
  633.         }
  634.         break;
  635.     case 3:
  636.         switch (photometric) {
  637.         case PHOTOMETRIC_RGB:
  638.             fputs("  /Decode [0 1 0 1 0 1]\n", fd);
  639.             break;
  640.         case PHOTOMETRIC_MINISWHITE:
  641.         case PHOTOMETRIC_MINISBLACK:
  642.         default:
  643.             /*
  644.              * ERROR??
  645.              */
  646.             fputs("  /Decode [0 1 0 1 0 1]\n", fd);
  647.             break;
  648.         }
  649.         break;
  650.     case 4:
  651.         /*
  652.          * ERROR??
  653.          */
  654.         fputs("  /Decode [0 1 0 1 0 1 0 1]\n", fd);
  655.         break;
  656.     }
  657.     fputs("  /DataSource", fd);
  658.     if (planarconfiguration == PLANARCONFIG_SEPARATE &&
  659.         samplesperpixel > 1)
  660.         fputs(" [", fd);
  661.     if (ascii85)
  662.         fputs(" im_stream", fd);
  663.     else
  664.         fputs(" currentfile /ASCIIHexDecode filter", fd);
  665.  
  666.     use_rawdata = TRUE;
  667.     switch (compression) {
  668.     case COMPRESSION_NONE:    /* 1: uncompressed */
  669.         break;
  670.     case COMPRESSION_CCITTRLE:    /* 2: CCITT modified Huffman RLE */
  671.     case COMPRESSION_CCITTRLEW:    /* 32771: #1 w/ word alignment */
  672.     case COMPRESSION_CCITTFAX3:    /* 3: CCITT Group 3 fax encoding */
  673.     case COMPRESSION_CCITTFAX4:    /* 4: CCITT Group 4 fax encoding */
  674.         fputs("\n\t<<\n", fd);
  675.         if (compression == COMPRESSION_CCITTFAX3) {
  676.             uint32 g3_options;
  677.  
  678.             fputs("\t /EndOfLine true\n", fd);
  679.             fputs("\t /EndOfBlock false\n", fd);
  680.             if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
  681.                         &g3_options))
  682.                 g3_options = 0;
  683.             if (g3_options & GROUP3OPT_2DENCODING)
  684.                 fprintf(fd, "\t /K %s\n", im_h);
  685.             if (g3_options & GROUP3OPT_UNCOMPRESSED)
  686.                 fputs("\t /Uncompressed true\n", fd);
  687.             if (g3_options & GROUP3OPT_FILLBITS)
  688.                 fputs("\t /EncodedByteAlign true\n", fd);
  689.         }
  690.         if (compression == COMPRESSION_CCITTFAX4) {
  691.             uint32 g4_options;
  692.  
  693.             fputs("\t /K -1\n", fd);
  694.             TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
  695.                            &g4_options);
  696.             if (g4_options & GROUP4OPT_UNCOMPRESSED)
  697.                 fputs("\t /Uncompressed true\n", fd);
  698.         }
  699.         if (!(tile_width == w && w == 1728U))
  700.             fprintf(fd, "\t /Columns %lu\n",
  701.                 (unsigned long) tile_width);
  702.         fprintf(fd, "\t /Rows %s\n", im_h);
  703.         if (compression == COMPRESSION_CCITTRLE ||
  704.             compression == COMPRESSION_CCITTRLEW) {
  705.             fputs("\t /EncodedByteAlign true\n", fd);
  706.             fputs("\t /EndOfBlock false\n", fd);
  707.         }
  708.         if (photometric == PHOTOMETRIC_MINISBLACK)
  709.             fputs("\t /BlackIs1 true\n", fd);
  710.         fprintf(fd, "\t>> /CCITTFaxDecode filter");
  711.         break;
  712.     case COMPRESSION_LZW:    /* 5: Lempel-Ziv  & Welch */
  713.         TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
  714.         if (predictor == 2) {
  715.             fputs("\n\t<<\n", fd);
  716.             fprintf(fd, "\t /Predictor %u\n", predictor);
  717.             fprintf(fd, "\t /Columns %lu\n",
  718.                 (unsigned long) tile_width);
  719.             fprintf(fd, "\t /Colors %u\n", samplesperpixel);
  720.             fprintf(fd, "\t /BitsPerComponent %u\n",
  721.                 bitspersample);
  722.             fputs("\t>>", fd);
  723.         }
  724.         fputs(" /LZWDecode filter", fd);
  725.         break;
  726.     case COMPRESSION_PACKBITS:        /* 32773: Macintosh RLE */
  727.         fputs(" /RunLengthDecode filter", fd);
  728.         use_rawdata = TRUE;
  729.         break;
  730.     case COMPRESSION_OJPEG:    /* 6: !6.0 JPEG */
  731.     case COMPRESSION_JPEG:    /* 7: %JPEG DCT compression */
  732. #ifdef notdef
  733.         /*
  734.          * Code not tested yet
  735.          */
  736.         fputs(" /DCTDecode filter", fd);
  737.         use_rawdata = TRUE;
  738. #else
  739.         use_rawdata = FALSE;
  740. #endif
  741.         break;
  742.     case COMPRESSION_NEXT:        /* 32766: NeXT 2-bit RLE */
  743.     case COMPRESSION_THUNDERSCAN:    /* 32809: ThunderScan RLE */
  744.     case COMPRESSION_PIXARFILM:    /* 32908: Pixar companded 10bit LZW */
  745.     case COMPRESSION_DEFLATE:    /* 32946: Deflate compression */
  746.     case COMPRESSION_JBIG:        /* 34661: ISO JBIG */
  747.         use_rawdata = FALSE;
  748.         break;
  749.     default:
  750.         /*
  751.          * ERROR...
  752.          */
  753.         use_rawdata = FALSE;
  754.         break;
  755.     }
  756.     if (planarconfiguration == PLANARCONFIG_SEPARATE &&
  757.         samplesperpixel > 1) {
  758.         uint16 i;
  759.  
  760.         /*
  761.          * NOTE: This code does not work yet...
  762.          */
  763.         for (i = 1; i < samplesperpixel; i++)
  764.             fputs(" dup", fd);
  765.         fputs(" ]", fd);
  766.     }
  767.     fputs("\n >> image\n", fd);
  768.     if (ascii85)
  769.         fputs(" im_stream flushfile\n", fd);
  770.     if (repeat_count > 1) {
  771.         if (tile_width < w) {
  772.             fprintf(fd, " /im_x im_x %lu add def\n",
  773.                 (unsigned long) tile_width);
  774.             if (tile_height < h) {
  775.                 fprintf(fd, " im_x %lu ge {\n",
  776.                     (unsigned long) w);
  777.                 fputs("  /im_x 0 def\n", fd);
  778.                 fprintf(fd, " /im_y im_y %lu add def\n",
  779.                     (unsigned long) tile_height);
  780.                 fputs(" } if\n", fd);
  781.             }
  782.         }
  783.         if (tile_height < h) {
  784.             if (tile_width >= w) {
  785.                 fprintf(fd, " /im_y im_y %lu add def\n",
  786.                     (unsigned long) tile_height);
  787.                 if (!TIFFIsTiled(tif)) {
  788.                     fprintf(fd, " /im_h %lu im_y sub",
  789.                         (unsigned long) h);
  790.                     fprintf(fd, " dup %lu gt { pop",
  791.                         (unsigned long) tile_height);
  792.                     fprintf(fd, " %lu } if def\n",
  793.                         (unsigned long) tile_height);
  794.                 }
  795.             }
  796.         }
  797.         fputs("} repeat\n", fd);
  798.     }
  799.     /*
  800.      * End of exec function
  801.      */
  802.     fputs("}\n", fd);
  803.  
  804.     return(use_rawdata);
  805. }
  806.  
  807. int
  808. PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h)
  809. {
  810.     uint16 fillorder;
  811.     int use_rawdata, tiled_image, breaklen;
  812.     uint32 chunk_no, num_chunks, *bc;
  813.     unsigned char *buf_data, *cp;
  814.     tsize_t chunk_size, byte_count;
  815.  
  816.     PS_Lvl2colorspace(fd, tif);
  817.     use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
  818.  
  819.     fputs("%%BeginData:\n", fd);
  820.     fputs("exec\n", fd);
  821.  
  822.     tiled_image = TIFFIsTiled(tif);
  823.     if (tiled_image) {
  824.         num_chunks = TIFFNumberOfTiles(tif);
  825.         TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
  826.     } else {
  827.         num_chunks = TIFFNumberOfStrips(tif);
  828.         TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
  829.     }
  830.  
  831.     if (use_rawdata) {
  832.         chunk_size = bc[0];
  833.         for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
  834.             if (bc[chunk_no] > chunk_size)
  835.                 chunk_size = bc[chunk_no];
  836.     } else {
  837.         if (tiled_image)
  838.             chunk_size = TIFFTileSize(tif);
  839.         else
  840.             chunk_size = TIFFStripSize(tif);
  841.     }
  842.     buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
  843.     if (!buf_data) {
  844.         TIFFError(filename, "Can't alloc %u bytes for %s.",
  845.             chunk_size, tiled_image ? "tiles" : "strips");
  846.         return(FALSE);
  847.     }
  848.  
  849.     TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
  850.     for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
  851.         if (ascii85)
  852.             Ascii85Init();
  853.         else
  854.             breaklen = 36;
  855.         if (use_rawdata) {
  856.             if (tiled_image)
  857.                 byte_count = TIFFReadRawTile(tif, chunk_no,
  858.                           buf_data, chunk_size);
  859.             else
  860.                 byte_count = TIFFReadRawStrip(tif, chunk_no,
  861.                           buf_data, chunk_size);
  862.             if (fillorder == FILLORDER_LSB2MSB)
  863.                 TIFFReverseBits(buf_data, byte_count);
  864.         } else {
  865.             if (tiled_image)
  866.                 byte_count = TIFFReadEncodedTile(tif,
  867.                         chunk_no, buf_data,
  868.                         chunk_size);
  869.             else
  870.                 byte_count = TIFFReadEncodedStrip(tif,
  871.                         chunk_no, buf_data,
  872.                         chunk_size);
  873.         }
  874.         if (byte_count < 0) {
  875.             TIFFError(filename, "Can't read %s %d.",
  876.                 tiled_image ? "tile" : "strip", chunk_no);
  877.             if (ascii85)
  878.                 Ascii85Put('\0', fd);
  879.         }
  880.         for (cp = buf_data; byte_count > 0; byte_count--) {
  881.             if (ascii85)
  882.                 Ascii85Put(*cp++, fd);
  883.             else {
  884.                 if (--breaklen <= 0) {
  885.                     putc('\n', fd);
  886.                     breaklen = 36;
  887.                 }
  888.                 putc(hex[((*cp)>>4)&0xf], fd);
  889.                 putc(hex[(*cp)&0xf], fd);
  890.                 cp++;
  891.             }
  892.         }
  893.         if (ascii85)
  894.             Ascii85Flush(fd);
  895.         else
  896.             putc('\n', fd);
  897.     }
  898.     _TIFFfree(buf_data);
  899.     fputs("%%EndData\n", fd);
  900.     return(TRUE);
  901. }
  902.  
  903. void
  904. PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h)
  905. {
  906.     if (level2 && PS_Lvl2page(fd, tif, w, h))
  907.         return;
  908.     ps_bytesperrow = tf_bytesperrow;
  909.     switch (photometric) {
  910.     case PHOTOMETRIC_RGB:
  911.         if (planarconfiguration == PLANARCONFIG_CONTIG) {
  912.             fprintf(fd, "%s", RGBcolorimage);
  913.             PSColorContigPreamble(fd, w, h, 3);
  914.             PSDataColorContig(fd, tif, w, h, 3);
  915.         } else {
  916.             PSColorSeparatePreamble(fd, w, h, 3);
  917.             PSDataColorSeparate(fd, tif, w, h, 3);
  918.         }
  919.         break;
  920.     case PHOTOMETRIC_SEPARATED:
  921.         /* XXX should emit CMYKcolorimage */
  922.         if (planarconfiguration == PLANARCONFIG_CONTIG) {
  923.             PSColorContigPreamble(fd, w, h, 4);
  924.             PSDataColorContig(fd, tif, w, h, 4);
  925.         } else {
  926.             PSColorSeparatePreamble(fd, w, h, 4);
  927.             PSDataColorSeparate(fd, tif, w, h, 4);
  928.         }
  929.         break;
  930.     case PHOTOMETRIC_PALETTE:
  931.         fprintf(fd, "%s", RGBcolorimage);
  932.         PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
  933.         fprintf(fd, "/scanLine %ld string def\n",
  934.             (long) ps_bytesperrow);
  935.         fprintf(fd, "%lu %lu 8\n",
  936.             (unsigned long) w, (unsigned long) h);
  937.         fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
  938.             (unsigned long) w, (unsigned long) h, (unsigned long) h);
  939.         fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
  940.         fprintf(fd, "false 3 colorimage\n");
  941.         PSDataPalette(fd, tif, w, h);
  942.         break;
  943.     case PHOTOMETRIC_MINISBLACK:
  944.     case PHOTOMETRIC_MINISWHITE:
  945.         PhotoshopBanner(fd, w, h, 1, 1, "image");
  946.         fprintf(fd, "/scanLine %ld string def\n",
  947.             (long) ps_bytesperrow);
  948.         fprintf(fd, "%lu %lu %d\n",
  949.             (unsigned long) w, (unsigned long) h, bitspersample);
  950.         fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
  951.             (unsigned long) w, (unsigned long) h, (unsigned long) h);
  952.         fprintf(fd,
  953.             "{currentfile scanLine readhexstring pop} bind\n");
  954.         fprintf(fd, "image\n");
  955.         PSDataBW(fd, tif, w, h);
  956.         break;
  957.     }
  958.     putc('\n', fd);
  959. }
  960.  
  961. void
  962. PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc)
  963. {
  964.     ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
  965.     PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
  966.     fprintf(fd, "/line %ld string def\n", (long) ps_bytesperrow);
  967.     fprintf(fd, "%lu %lu %d\n",
  968.         (unsigned long) w, (unsigned long) h, bitspersample);
  969.     fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
  970.         (unsigned long) w, (unsigned long) h, (unsigned long) h);
  971.     fprintf(fd, "{currentfile line readhexstring pop} bind\n");
  972.     fprintf(fd, "false %d colorimage\n", nc);
  973. }
  974.  
  975. void
  976. PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc)
  977. {
  978.     int i;
  979.  
  980.     PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
  981.     for (i = 0; i < nc; i++)
  982.         fprintf(fd, "/line%d %ld string def\n",
  983.             i, (long) ps_bytesperrow);
  984.     fprintf(fd, "%lu %lu %d\n",
  985.         (unsigned long) w, (unsigned long) h, bitspersample);
  986.     fprintf(fd, "[%lu 0 0 -%lu 0 %lu] \n",
  987.         (unsigned long) w, (unsigned long) h, (unsigned long) h);
  988.     for (i = 0; i < nc; i++)
  989.         fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
  990.     fprintf(fd, "true %d colorimage\n", nc);
  991. }
  992.  
  993. #define MAXLINE        36
  994. #define    DOBREAK(len, howmany, fd) \
  995.     if (((len) -= (howmany)) <= 0) {    \
  996.         putc('\n', fd);            \
  997.         (len) = MAXLINE-(howmany);    \
  998.     }
  999. #define    PUTHEX(c,fd)    putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
  1000.  
  1001. void
  1002. PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
  1003. {
  1004.     uint32 row;
  1005.     int breaklen = MAXLINE, cc, es = samplesperpixel - nc;
  1006.     unsigned char *tf_buf;
  1007.     unsigned char *cp, c;
  1008.  
  1009.     (void) w;
  1010.     tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
  1011.     if (tf_buf == NULL) {
  1012.         TIFFError(filename, "No space for scanline buffer");
  1013.         return;
  1014.     }
  1015.     for (row = 0; row < h; row++) {
  1016.         if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
  1017.             break;
  1018.         cp = tf_buf;
  1019.         if (alpha) {
  1020.             int adjust;
  1021.             cc = 0;
  1022.             for (; cc < tf_bytesperrow; cc += samplesperpixel) {
  1023.                 DOBREAK(breaklen, nc, fd);
  1024.                 /*
  1025.                  * For images with alpha, matte against
  1026.                  * a white background; i.e.
  1027.                  *    Cback * (1 - Aimage)
  1028.                  * where Cback = 1.
  1029.                  */
  1030.                 adjust = 255 - cp[nc];
  1031.                 switch (nc) {
  1032.                 case 4: c = *cp++ + adjust; PUTHEX(c,fd);
  1033.                 case 3: c = *cp++ + adjust; PUTHEX(c,fd);
  1034.                 case 2: c = *cp++ + adjust; PUTHEX(c,fd);
  1035.                 case 1: c = *cp++ + adjust; PUTHEX(c,fd);
  1036.                 }
  1037.                 cp += es;
  1038.             }
  1039.         } else {
  1040.             cc = 0;
  1041.             for (; cc < tf_bytesperrow; cc += samplesperpixel) {
  1042.                 DOBREAK(breaklen, nc, fd);
  1043.                 switch (nc) {
  1044.                 case 4: c = *cp++; PUTHEX(c,fd);
  1045.                 case 3: c = *cp++; PUTHEX(c,fd);
  1046.                 case 2: c = *cp++; PUTHEX(c,fd);
  1047.                 case 1: c = *cp++; PUTHEX(c,fd);
  1048.                 }
  1049.                 cp += es;
  1050.             }
  1051.         }
  1052.     }
  1053.     _TIFFfree((char *) tf_buf);
  1054. }
  1055.  
  1056. void
  1057. PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
  1058. {
  1059.     uint32 row;
  1060.     int breaklen = MAXLINE, cc, s, maxs;
  1061.     unsigned char *tf_buf;
  1062.     unsigned char *cp, c;
  1063.  
  1064.     (void) w;
  1065.     tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
  1066.     if (tf_buf == NULL) {
  1067.         TIFFError(filename, "No space for scanline buffer");
  1068.         return;
  1069.     }
  1070.     maxs = (samplesperpixel > nc ? nc : samplesperpixel);
  1071.     for (row = 0; row < h; row++) {
  1072.         for (s = 0; s < maxs; s++) {
  1073.             if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
  1074.                 break;
  1075.             for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
  1076.                 DOBREAK(breaklen, 1, fd);
  1077.                 c = *cp++;
  1078.                 PUTHEX(c,fd);
  1079.             }
  1080.         }
  1081.     }
  1082.     _TIFFfree((char *) tf_buf);
  1083. }
  1084.  
  1085. #define    PUTRGBHEX(c,fd) \
  1086.     PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
  1087.  
  1088. void
  1089. PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h)
  1090. {
  1091.     uint16 *rmap, *gmap, *bmap;
  1092.     uint32 row;
  1093.     int breaklen = MAXLINE, cc, nc;
  1094.     unsigned char *tf_buf;
  1095.     unsigned char *cp, c;
  1096.  
  1097.     (void) w;
  1098.     if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
  1099.         TIFFError(filename, "Palette image w/o \"Colormap\" tag");
  1100.         return;
  1101.     }
  1102.     switch (bitspersample) {
  1103.     case 8:    case 4: case 2: case 1:
  1104.         break;
  1105.     default:
  1106.         TIFFError(filename, "Depth %d not supported", bitspersample);
  1107.         return;
  1108.     }
  1109.     nc = 3 * (8 / bitspersample);
  1110.     tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
  1111.     if (tf_buf == NULL) {
  1112.         TIFFError(filename, "No space for scanline buffer");
  1113.         return;
  1114.     }
  1115.     if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) {
  1116.         int i;
  1117. #define    CVT(x)        (((x) * 255) / ((1U<<16)-1))
  1118.         for (i = (1<<bitspersample)-1; i >= 0; i--) {
  1119.             rmap[i] = CVT(rmap[i]);
  1120.             gmap[i] = CVT(gmap[i]);
  1121.             bmap[i] = CVT(bmap[i]);
  1122.         }
  1123. #undef CVT
  1124.     }
  1125.     for (row = 0; row < h; row++) {
  1126.         if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
  1127.             break;
  1128.         for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
  1129.             DOBREAK(breaklen, nc, fd);
  1130.             switch (bitspersample) {
  1131.             case 8:
  1132.                 c = *cp++; PUTRGBHEX(c, fd);
  1133.                 break;
  1134.             case 4:
  1135.                 c = *cp++; PUTRGBHEX(c&0xf, fd);
  1136.                 c >>= 4;   PUTRGBHEX(c, fd);
  1137.                 break;
  1138.             case 2:
  1139.                 c = *cp++; PUTRGBHEX(c&0x3, fd);
  1140.                 c >>= 2;   PUTRGBHEX(c&0x3, fd);
  1141.                 c >>= 2;   PUTRGBHEX(c&0x3, fd);
  1142.                 c >>= 2;   PUTRGBHEX(c, fd);
  1143.                 break;
  1144.             case 1:
  1145.                 c = *cp++; PUTRGBHEX(c&0x1, fd);
  1146.                 c >>= 1;   PUTRGBHEX(c&0x1, fd);
  1147.                 c >>= 1;   PUTRGBHEX(c&0x1, fd);
  1148.                 c >>= 1;   PUTRGBHEX(c&0x1, fd);
  1149.                 c >>= 1;   PUTRGBHEX(c&0x1, fd);
  1150.                 c >>= 1;   PUTRGBHEX(c&0x1, fd);
  1151.                 c >>= 1;   PUTRGBHEX(c&0x1, fd);
  1152.                 c >>= 1;   PUTRGBHEX(c, fd);
  1153.                 break;
  1154.             }
  1155.         }
  1156.     }
  1157.     _TIFFfree((char *) tf_buf);
  1158. }
  1159.  
  1160. void
  1161. PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
  1162. {
  1163.     int breaklen = MAXLINE;
  1164.     unsigned char* tf_buf;
  1165.     unsigned char* cp;
  1166.     tsize_t stripsize = TIFFStripSize(tif);
  1167.     tstrip_t s;
  1168.  
  1169.     (void) w; (void) h;
  1170.     tf_buf = (unsigned char *) _TIFFmalloc(stripsize);
  1171.     if (tf_buf == NULL) {
  1172.         TIFFError(filename, "No space for scanline buffer");
  1173.         return;
  1174.     }
  1175.     if (ascii85)
  1176.             Ascii85Init();
  1177.     for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
  1178.         int cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
  1179.         if (cc < 0) {
  1180.             TIFFError(filename, "Can't read strip");
  1181.             break;
  1182.         }
  1183.         cp = tf_buf;
  1184.         if (photometric == PHOTOMETRIC_MINISWHITE) {
  1185.             for (cp += cc; --cp >= tf_buf;)
  1186.                 *cp = ~*cp;
  1187.             cp++;
  1188.         }
  1189.         if (ascii85) {
  1190.             while (cc-- > 0)
  1191.                 Ascii85Put(*cp++, fd);
  1192.         } else {
  1193.             while (cc-- > 0) {
  1194.                 unsigned char c = *cp++;
  1195.                 DOBREAK(breaklen, 1, fd);
  1196.                 PUTHEX(c, fd);
  1197.             }
  1198.         }
  1199.     }
  1200.     if (ascii85)
  1201.             Ascii85Flush(fd);
  1202.     else if (level2)
  1203.             fputs(">\n", fd);
  1204.     _TIFFfree(tf_buf);
  1205. }
  1206.  
  1207. void
  1208. PSRawDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
  1209. {
  1210.     uint32 *bc;
  1211.     uint32 bufsize;
  1212.     int breaklen = MAXLINE, cc;
  1213.     uint16 fillorder;
  1214.     unsigned char *tf_buf;
  1215.     unsigned char *cp, c;
  1216.     tstrip_t s;
  1217.  
  1218.     (void) w; (void) h;
  1219.     TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
  1220.     TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
  1221.     bufsize = bc[0];
  1222.     tf_buf = (unsigned char*) _TIFFmalloc(bufsize);
  1223.     if (tf_buf == NULL) {
  1224.         TIFFError(filename, "No space for strip buffer");
  1225.         return;
  1226.     }
  1227.     for (s = 0; s < tf_numberstrips; s++) {
  1228.         if (bc[s] > bufsize) {
  1229.             tf_buf = (unsigned char *) _TIFFrealloc(tf_buf, bc[s]);
  1230.             if (tf_buf == NULL) {
  1231.                 TIFFError(filename,
  1232.                     "No space for strip buffer");
  1233.                 return;
  1234.             }
  1235.             bufsize = bc[s];
  1236.         }
  1237.         cc = TIFFReadRawStrip(tif, s, tf_buf, bc[s]);
  1238.         if (cc < 0) {
  1239.             TIFFError(filename, "Can't read strip");
  1240.             break;
  1241.         }
  1242.         if (fillorder == FILLORDER_LSB2MSB)
  1243.             TIFFReverseBits(tf_buf, cc);
  1244.         if (!ascii85) {
  1245.             for (cp = tf_buf; cc > 0; cc--) {
  1246.                 DOBREAK(breaklen, 1, fd);
  1247.                 c = *cp++;
  1248.                 PUTHEX(c, fd);
  1249.             }
  1250.             fputs(">\n", fd);
  1251.             breaklen = MAXLINE;
  1252.         } else {
  1253.                 Ascii85Init();
  1254.             for (cp = tf_buf; cc > 0; cc--)
  1255.                 Ascii85Put(*cp++, fd);
  1256.             Ascii85Flush(fd);
  1257.         }
  1258.     }
  1259.     _TIFFfree((char *) tf_buf);
  1260. }
  1261.  
  1262. void
  1263. Ascii85Init(void)
  1264. {
  1265.     ascii85breaklen = 2*MAXLINE;
  1266.     ascii85count = 0;
  1267. }
  1268.  
  1269. static char*
  1270. Ascii85Encode(unsigned char* raw)
  1271. {
  1272.     static char encoded[6];
  1273.     uint32 word;
  1274.  
  1275.     word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
  1276.     if (word != 0L) {
  1277.         uint32 q;
  1278.         uint16 w1;
  1279.  
  1280.         q = word / (85L*85*85*85);    /* actually only a byte */
  1281.         encoded[0] = q + '!';
  1282.  
  1283.         word -= q * (85L*85*85*85); q = word / (85L*85*85);
  1284.         encoded[1] = q + '!';
  1285.  
  1286.         word -= q * (85L*85*85); q = word / (85*85);
  1287.         encoded[2] = q + '!';
  1288.  
  1289.         w1 = (uint16) (word - q*(85L*85));
  1290.         encoded[3] = (w1 / 85) + '!';
  1291.         encoded[4] = (w1 % 85) + '!';
  1292.         encoded[5] = '\0';
  1293.     } else
  1294.         encoded[0] = 'z', encoded[1] = '\0';
  1295.     return (encoded);
  1296. }
  1297.  
  1298. void
  1299. Ascii85Put(unsigned char code, FILE* fd)
  1300. {
  1301.     ascii85buf[ascii85count++] = code;
  1302.     if (ascii85count >= 4) {
  1303.         unsigned char* p;
  1304.         int n;
  1305.  
  1306.         for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
  1307.             char* cp;
  1308.             for (cp = Ascii85Encode(p); *cp; cp++) {
  1309.                 putc(*cp, fd);
  1310.                 if (--ascii85breaklen == 0) {
  1311.                     putc('\n', fd);
  1312.                     ascii85breaklen = 2*MAXLINE;
  1313.                 }
  1314.             }
  1315.             p += 4;
  1316.         }
  1317.         _TIFFmemcpy(ascii85buf, p, n);
  1318.         ascii85count = n;
  1319.     }
  1320. }
  1321.  
  1322. void
  1323. Ascii85Flush(FILE* fd)
  1324. {
  1325.     if (ascii85count > 0) {
  1326.         char* res;
  1327.         _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
  1328.         res = Ascii85Encode(ascii85buf);
  1329.         fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
  1330.     }
  1331.     fputs("~>\n", fd);
  1332. }
  1333.  
  1334. char* stuff[] = {
  1335. "usage: tiff2ps [options] input.tif ...",
  1336. "where options are:",
  1337. " -1            generate PostScript Level I (default)",
  1338. " -2            generate PostScript Level II",
  1339. " -8            disable use of ASCII85 encoding with PostScript Level II",
  1340. " -d #          convert directory number #",
  1341. " -D            enable duplex printing (two pages per sheet of paper)",
  1342. " -e            generate Encapsulated PostScript (EPS)",
  1343. " -h #          assume printed page height is # inches (default 11)",
  1344. " -o #          convert directory at file offset #",
  1345. " -O file       write PostScript to file instead of standard output",
  1346. " -a            convert all directories in file (default is first)",
  1347. " -p            generate regular PostScript",
  1348. " -s            generate PostScript for a single image",
  1349. " -T            print pages for top edge binding",
  1350. " -w #          assume printed page width is # inches (default 8.5)",
  1351. NULL
  1352. };
  1353.  
  1354. static void
  1355. usage(int code)
  1356. {
  1357.     char buf[BUFSIZ];
  1358.     int i;
  1359.  
  1360.     setbuf(stderr, buf);
  1361.     for (i = 0; stuff[i] != NULL; i++)
  1362.         fprintf(stderr, "%s\n", stuff[i]);
  1363.     exit(code);
  1364. }
  1365.