home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / gbmsrc.zip / gbmtif.c < prev    next >
C/C++ Source or Header  |  1999-01-21  |  39KB  |  1,532 lines

  1. /*
  2.  
  3. gbmtif.c - Microsoft/Aldus Tagged Image File Format support
  4.  
  5. Reads and writes 1,4,8 and 24 bit colour files.
  6. Supports uncompressed, Packbits and LZW compressed files only.
  7. Input option: index=N (default is 0)
  8. Output options: artist=,software=,make=,model=,host=,documentname=,pagename=,
  9.         imagedescription=,pal1bpp
  10.  
  11. Added support to allow SamplePerPixel>=3 for RGB data (TIFF 6.0 new feature).
  12. Added rejection test of FillOrder!=1.
  13. Added rejection test of PlanarConfiguration!=1.
  14. Added support for CMYK images.
  15. Changed write of 1bpp data to Baseline black and white write.
  16. Added pal1bpp output option meaning don't force Baseline write of 1bpp data.
  17. Improved error messages substantially.
  18. Fixed Packbits compression.
  19. Added support for PlanarConfiguration==2 for RGB images only.
  20. Added Predictor==2 support for bps==8, spp=1 case.
  21. Added Predictor==2 support for bps==8, spp>=3 case.
  22. Removed Too Many Strips limitation.
  23. Faster LZW code.
  24. Fixes to LZW compressor (and #ifdef DEBUG debug code).
  25.  
  26. */
  27.  
  28. /*...sincludes:0:*/
  29. #include <stdio.h>
  30. #include <ctype.h>
  31. #include <stddef.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <memory.h>
  35. #include <malloc.h>
  36. #include "gbm.h"
  37. #include "gbmhelp.h"
  38. #include "gbmtifh.h"
  39.  
  40. /*...vgbm\46\h:0:*/
  41. /*...vgbmhelp\46\h:0:*/
  42. /*...vgbmtifh\46\h:0:*/
  43.  
  44. #ifndef min
  45. #define    min(a,b)    (((a)<(b))?(a):(b))
  46. #endif
  47. /*...e*/
  48.  
  49. /* #define DEBUG */
  50.  
  51. static GBMFT tif_gbmft =
  52.     {
  53.     "TIFF",
  54.     "Tagged Image File Format support (almost TIFF 6.0 Baseline)",
  55.     "TIF TIFF",
  56.     GBM_FT_R1|GBM_FT_R4|GBM_FT_R8|GBM_FT_R24|
  57.     GBM_FT_W1|GBM_FT_W4|GBM_FT_W8|GBM_FT_W24,
  58.     };
  59.  
  60. /*...serror codes:0:*/
  61. #define    GBM_ERR_TIF_VERSION        ((GBM_ERR) 800)
  62. #define    GBM_ERR_TIF_N_TAGS        ((GBM_ERR) 801)
  63. #define    GBM_ERR_TIF_TAG_TYPE        ((GBM_ERR) 802)
  64. #define    GBM_ERR_TIF_HEADER        ((GBM_ERR) 803)
  65. #define    GBM_ERR_TIF_MISSING_TAG        ((GBM_ERR) 804)
  66. #define    GBM_ERR_TIF_SPP_BIT        ((GBM_ERR) 805)
  67. #define    GBM_ERR_TIF_BPS_BIT        ((GBM_ERR) 806)
  68. #define    GBM_ERR_TIF_SPP_RGB        ((GBM_ERR) 807)
  69. #define    GBM_ERR_TIF_BPS_RGB        ((GBM_ERR) 808)
  70. #define    GBM_ERR_TIF_SPP_PAL        ((GBM_ERR) 809)
  71. #define    GBM_ERR_TIF_BPS_PAL        ((GBM_ERR) 810)
  72. #define    GBM_ERR_TIF_SPP_CMYK        ((GBM_ERR) 811)
  73. #define    GBM_ERR_TIF_BPS_CMYK        ((GBM_ERR) 812)
  74. #define    GBM_ERR_TIF_COMP_1D_MH        ((GBM_ERR) 813)
  75. #define    GBM_ERR_TIF_COMP_T4        ((GBM_ERR) 814)
  76. #define    GBM_ERR_TIF_COMP_T6        ((GBM_ERR) 815)
  77. #define    GBM_ERR_TIF_COMP        ((GBM_ERR) 816)
  78. #define    GBM_ERR_TIF_COLORMAP        ((GBM_ERR) 817)
  79. #define    GBM_ERR_TIF_CORRUPT        ((GBM_ERR) 818)
  80. #define    GBM_ERR_TIF_PREDICTOR        ((GBM_ERR) 819)
  81. #define    GBM_ERR_TIF_PHOTO_TRANS        ((GBM_ERR) 821)
  82. #define    GBM_ERR_TIF_PHOTO_Y_Cb_Cr    ((GBM_ERR) 822)
  83. #define    GBM_ERR_TIF_PHOTO        ((GBM_ERR) 823)
  84. #define    GBM_ERR_TIF_FILLORDER        ((GBM_ERR) 824)
  85. #define    GBM_ERR_TIF_PLANARCONFIG_1    ((GBM_ERR) 825)
  86. #define    GBM_ERR_TIF_PLANARCONFIG_12    ((GBM_ERR) 826)
  87. #define    GBM_ERR_TIF_INKSET        ((GBM_ERR) 827)
  88. #define    GBM_ERR_TIF_ORIENT        ((GBM_ERR) 828)
  89. #define    GBM_ERR_TIF_INDEX        ((GBM_ERR) 829)
  90. /*...e*/
  91.  
  92. /*...sdefns:0:*/
  93. /*
  94. #define MAX_STRIPS    200
  95. */
  96. #define    MAX_STRIPS    ((PRIV_SIZE-9*sizeof(int)-0x100*sizeof(GBMRGB))/sizeof(long))
  97.  
  98. typedef struct
  99.     {
  100.     GBMRGB gbmrgb[0x100];
  101.     int rps, spp, bps, comp, photo, orient, planar, predictor, inx;
  102.     long so[MAX_STRIPS];
  103.     } TIF_PRIV;
  104.  
  105. #define    ENC_NONE    ((int) 1)
  106. #define    ENC_G3_1D_MH    ((int) 2)
  107. #define    ENC_T4        ((int) 3)
  108. #define    ENC_T6        ((int) 4)
  109. #define    ENC_LZW        ((int) 5)
  110. #define    ENC_PACKBITS    ((int) 32773)
  111.  
  112. #define    PHOTO_BIT0    0
  113. #define    PHOTO_BIT1    1
  114. #define    PHOTO_RGB    2
  115. #define    PHOTO_PAL    3
  116. #define    PHOTO_TRANS    4
  117. #define    PHOTO_CMYK    5
  118. #define    PHOTO_Y_Cb_Cr    6
  119. /*...e*/
  120.  
  121. /*...srgb_bgr:0:*/
  122. static void rgb_bgr(const byte *p, byte *q, int n)
  123.     {
  124.     while ( n-- )
  125.         {
  126.         byte    r = *p++;
  127.         byte    g = *p++;
  128.         byte    b = *p++;
  129.  
  130.         *q++ = b;
  131.         *q++ = g;
  132.         *q++ = r;
  133.         }
  134.     }
  135. /*...e*/
  136.  
  137. typedef unsigned int cword;
  138.  
  139. #ifdef DEBUG
  140. #define LOG(args) printf args
  141. #else
  142. #define    LOG(args)
  143. #endif
  144.  
  145. /*...stif_qft:0:*/
  146. GBM_ERR tif_qft(GBMFT *gbmft)
  147.     {
  148.     *gbmft = tif_gbmft;
  149.     return GBM_ERR_OK;
  150.     }
  151. /*...e*/
  152. /*...stif_rhdr:0:*/
  153. /*...svalue_of_tag_def:0:*/
  154. static long value_of_tag_def(IFD *ifd, short type, long def)
  155.     {
  156.     TAG *tag;
  157.  
  158.     if ( (tag = locate_tag(ifd, type)) != NULL )
  159.         return value_of_tag(tag);
  160.     else
  161.         return def;
  162.     }
  163. /*...e*/
  164.  
  165. GBM_ERR tif_rhdr(const char *fn, int fd, GBM *gbm, const char *opt)
  166.     {
  167.     TIF_PRIV *tif_priv = (TIF_PRIV *) gbm->priv;
  168.     TAG *tag_w, *tag_h, *tag_so;
  169.     GBM_ERR rc;
  170.     IFH *ifh;
  171.     IFD *ifd;
  172.     int inx = 0, strip, n_strips, fillorder;
  173.     const char *index;
  174.  
  175.     if ( (index = gbm_find_word_prefix(opt, "index=")) != NULL )
  176.         sscanf(index + 6, "%d", &inx);
  177.     tif_priv->inx = inx;
  178.  
  179.     fn=fn; /* Suppress 'unref arg' compiler warnings */
  180.  
  181.     switch ( read_ifh_and_ifd(fd, inx, &ifh) )
  182.         {
  183.         case TE_OK:        rc = GBM_ERR_OK;        break;
  184.         case TE_MEM:        rc = GBM_ERR_MEM;        break;
  185.         case TE_VERSION:    rc = GBM_ERR_TIF_VERSION;    break;
  186.         case TE_N_TAGS:        rc = GBM_ERR_TIF_N_TAGS;    break;
  187.         case TE_TAG_TYPE:    rc = GBM_ERR_TIF_TAG_TYPE;    break;
  188.         case TE_N_IFD:        rc = GBM_ERR_TIF_INDEX;        break;
  189.         default:        rc = GBM_ERR_TIF_HEADER;    break;
  190.         }
  191.  
  192.     if ( rc != GBM_ERR_OK )
  193.         return rc;
  194.  
  195.     ifd = ifh->ifd;
  196.  
  197.     if ( (tag_w  = locate_tag(ifd, T_IMAGEWIDTH  )) == NULL ||
  198.          (tag_h  = locate_tag(ifd, T_IMAGELENGTH )) == NULL ||
  199.          (tag_so = locate_tag(ifd, T_STRIPOFFSETS)) == NULL )
  200.         {
  201.         free_ifh(ifh);
  202.         return GBM_ERR_TIF_MISSING_TAG;
  203.         }
  204.  
  205.     gbm->w           = (int) value_of_tag(tag_w);
  206.     gbm->h           = (int) value_of_tag(tag_h);
  207.     tif_priv->photo  = (int) value_of_tag_def(ifd, T_PHOTOMETRIC    , 1L);
  208.     tif_priv->rps    = (int) value_of_tag_def(ifd, T_ROWSPERSTRIP   , (long) gbm->h);
  209.     tif_priv->spp    = (int) value_of_tag_def(ifd, T_SAMPLESPERPIXEL, 1L);
  210.     tif_priv->bps    = (int) value_of_tag_def(ifd, T_BITSPERSAMPLE  , 1L);
  211.     tif_priv->comp   = (int) value_of_tag_def(ifd, T_COMPRESSION    , 1L);
  212.     tif_priv->orient = (int) value_of_tag_def(ifd, T_ORIENTATION    , 1L);
  213.     tif_priv->planar = (int) value_of_tag_def(ifd, T_PLANARCONFIG   , 1L);
  214.  
  215.     rc = GBM_ERR_OK;
  216.     switch ( tif_priv->photo )
  217.         {
  218. /*...sPHOTO_BITx    \45\ bitmap or greyscale:16:*/
  219. case PHOTO_BIT0:
  220. case PHOTO_BIT1:
  221.     if ( tif_priv->spp != 1 )
  222.         rc = GBM_ERR_TIF_SPP_BIT;
  223.     else if ( tif_priv->bps != 1 && tif_priv->bps != 4 && tif_priv->bps != 8 )
  224.         rc = GBM_ERR_TIF_BPS_BIT;
  225.     else
  226.         {
  227.         int    i, n_pal;
  228.  
  229.         n_pal = ( 1 << tif_priv->bps );
  230.         for ( i = 0; i < n_pal; i++ )
  231.             {
  232.             tif_priv->gbmrgb[i].r =
  233.             tif_priv->gbmrgb[i].g =
  234.             tif_priv->gbmrgb[i].b = (byte) ((0xff * i) / (n_pal - 1));
  235.             }
  236.         if ( tif_priv->photo == PHOTO_BIT0 )
  237.             for ( i = 0; i < n_pal; i++ )
  238.                 {
  239.                 tif_priv->gbmrgb[i].r ^= 0xff;
  240.                 tif_priv->gbmrgb[i].g ^= 0xff;
  241.                 tif_priv->gbmrgb[i].b ^= 0xff;
  242.                 }
  243.         }
  244.     gbm->bpp = tif_priv->bps;
  245.     break;
  246. /*...e*/
  247. /*...sPHOTO_RGB     \45\ 24 bit data:16:*/
  248. /* It is possible for sample per pixel to be greater than 3.
  249.    This implies there are extra samples (which we will ignore).
  250.    This is a new TIFF 6.0 feature. */
  251.  
  252. case PHOTO_RGB:
  253.     if ( tif_priv->spp < 3 )
  254.         rc = GBM_ERR_TIF_SPP_RGB;
  255.     else if ( tif_priv->bps != 8 )
  256.         rc = GBM_ERR_TIF_BPS_RGB;
  257.     gbm->bpp = 24;
  258.     break;
  259. /*...e*/
  260. /*...sPHOTO_PAL     \45\ palettised:16:*/
  261. /*
  262. There are 2 known bugs in commonly available TIFF files today.
  263. UBU will only write a ColorMap tag with a length field of 256 (not 256 * 3).
  264. This bug is fixed inside my TIFF library itself!
  265. OS/2 Image Support will write all palette entrys as bytes!
  266. */
  267.  
  268. case PHOTO_PAL:
  269.     if ( tif_priv->spp != 1 )
  270.         rc = GBM_ERR_TIF_SPP_PAL;
  271.     else if ( tif_priv->bps != 1 && tif_priv->bps != 4 && tif_priv->bps != 8 )
  272.         rc = GBM_ERR_TIF_BPS_PAL;
  273.     else
  274.         {
  275.         int    i, n_pal;
  276.         TAG    *tag_cm;
  277.  
  278.         n_pal = (1 << tif_priv->bps);
  279.         if ( (tag_cm = locate_tag(ifd, T_COLORMAP)) != NULL )
  280.             {
  281.             GBMRGB    *gbmrgb;
  282.  
  283.             for ( i = 0, gbmrgb = tif_priv->gbmrgb; i < n_pal; i++, gbmrgb++ )
  284.                 {
  285.                 gbmrgb->r = (byte) ((unsigned)value_of_tag_n(tag_cm,             i) >> 8);
  286.                 gbmrgb->g = (byte) ((unsigned)value_of_tag_n(tag_cm,     n_pal + i) >> 8);
  287.                 gbmrgb->b = (byte) ((unsigned)value_of_tag_n(tag_cm, 2 * n_pal + i) >> 8);
  288.                 }
  289. /*...sfix for OS\47\2 Image Support \40\and others\41\:40:*/
  290. {
  291. byte bugfix = 0;
  292.  
  293. for ( i = 0, gbmrgb = tif_priv->gbmrgb; i < n_pal; i++, gbmrgb++ )
  294.     bugfix |= (gbmrgb->r | gbmrgb->g | gbmrgb->b);
  295.  
  296. if ( bugfix == 0 )
  297.     for ( i = 0, gbmrgb = tif_priv->gbmrgb; i < n_pal; i++, gbmrgb++ )
  298.         {
  299.         gbmrgb->r = (byte) value_of_tag_n(tag_cm,             i);
  300.         gbmrgb->g = (byte) value_of_tag_n(tag_cm,     n_pal + i);
  301.         gbmrgb->b = (byte) value_of_tag_n(tag_cm, 2 * n_pal + i);
  302.         }
  303. }
  304. /*...e*/
  305.             }
  306.         else
  307.             rc = GBM_ERR_TIF_COLORMAP;
  308.         }
  309.     gbm->bpp = tif_priv->bps;
  310.     break;
  311. /*...e*/
  312. /*...sPHOTO_TRANS   \45\ transparency mask:16:*/
  313. case PHOTO_TRANS:
  314.     rc = GBM_ERR_TIF_PHOTO_TRANS;
  315.     break;
  316. /*...e*/
  317. /*...sPHOTO_CMYK    \45\ CMYK or other seperated image:16:*/
  318. /* This is a colour seperated image.
  319.    Typically expect 4 seperations, for CMYK.
  320.    Can be other numbers, and possibly 4 with non standard ink colours.
  321.    Ignore all but 4 seperations which are CMYK.
  322.    Consider this a 24 bit RGB, mapping will occur from CMYK to RGB. */
  323.  
  324. case PHOTO_CMYK:
  325.     if ( tif_priv->spp != 4 )
  326.         rc = GBM_ERR_TIF_SPP_CMYK;
  327.     else if ( tif_priv->bps != 8 )
  328.         rc = GBM_ERR_TIF_BPS_CMYK;
  329.     else if ( value_of_tag_def(ifd, T_INKSET, 1L) != 1 )
  330.         rc = GBM_ERR_TIF_INKSET;
  331.     else
  332.         gbm->bpp = 24;
  333.     break;
  334. /*...e*/
  335. /*...sPHOTO_Y_Cb_Cr \45\ Y\45\Cb\45\Cr colour space:16:*/
  336. case PHOTO_Y_Cb_Cr:
  337.     rc = GBM_ERR_TIF_PHOTO_Y_Cb_Cr;
  338.     break;
  339. /*...e*/
  340. /*...sdefault       \45\ wierd PhotometricInterpretation:16:*/
  341. default:
  342.     rc = GBM_ERR_TIF_PHOTO;
  343.     break;
  344. /*...e*/
  345.         }
  346.  
  347.     if ( rc != GBM_ERR_OK )
  348.         { free_ifh(ifh); return rc; }
  349.  
  350.     /* Remember where strips are, and how big they are */
  351.  
  352.     n_strips = (gbm->h + (tif_priv->rps - 1)) / tif_priv->rps;
  353.     if ( tif_priv->photo == PHOTO_RGB && tif_priv->planar == 2 )
  354.         n_strips *= 3;
  355.  
  356.     if ( n_strips <= MAX_STRIPS )
  357.         for ( strip = 0; strip < n_strips; strip++ )
  358.             tif_priv->so[strip] = value_of_tag_n(tag_so, strip);
  359.  
  360.     if ( tif_priv->comp != ENC_NONE     &&
  361.          tif_priv->comp != ENC_PACKBITS &&
  362.          tif_priv->comp != ENC_LZW      )
  363. /*...sreject compression type:16:*/
  364. {
  365. free_ifh(ifh);
  366. switch ( tif_priv->comp )
  367.     {
  368.     case ENC_G3_1D_MH:    return GBM_ERR_TIF_COMP_1D_MH;
  369.     case ENC_T4:        return GBM_ERR_TIF_COMP_T4   ;
  370.     case ENC_T6:        return GBM_ERR_TIF_COMP_T6   ;
  371.     default:        return GBM_ERR_TIF_COMP      ;
  372.     }
  373. }
  374. /*...e*/
  375.  
  376.     if ( tif_priv->orient != 1 && tif_priv->orient != 4 )
  377.         { free_ifh(ifh); return GBM_ERR_TIF_ORIENT; }
  378.  
  379.     fillorder = (int) value_of_tag_def(ifd, T_FILLORDER, 1L);
  380.     if ( fillorder != 1 )
  381.         { free_ifh(ifh); return GBM_ERR_TIF_FILLORDER; }
  382.  
  383.     if ( tif_priv->photo == PHOTO_RGB )
  384.         /* Allow photo of 1 or 2 */
  385.         {
  386.         if ( tif_priv->planar != 1 && tif_priv->planar != 2 )
  387.             { free_ifh(ifh); return GBM_ERR_TIF_PLANARCONFIG_12; }
  388.         }
  389.     else
  390.         /* Allow photo of 1 only */
  391.         {
  392.         if ( tif_priv->planar != 1 )
  393.             { free_ifh(ifh); return GBM_ERR_TIF_PLANARCONFIG_1; }
  394.         }
  395.  
  396.     tif_priv->predictor = (int) value_of_tag_def(ifd, T_PREDICTOR, 1L);
  397.  
  398.     /* Only allow predictor of 1, unless a special case we handle */
  399.     if ( tif_priv->predictor != 1 &&
  400.          !(tif_priv->comp == ENC_LZW &&
  401.            tif_priv->bps == 8 &&
  402.            (tif_priv->spp == 1 || tif_priv->spp >= 3)) )
  403.         { free_ifh(ifh); return GBM_ERR_TIF_PREDICTOR; }
  404.  
  405.     free_ifh(ifh);
  406.  
  407.     return GBM_ERR_OK;
  408.     }
  409. /*...e*/
  410. /*...stif_rpal:0:*/
  411. GBM_ERR tif_rpal(int fd, GBM *gbm, GBMRGB *gbmrgb)
  412.     {
  413.     TIF_PRIV *tif_priv = (TIF_PRIV *) gbm->priv;
  414.  
  415.     fd=fd; /* Suppress 'unref arg' compiler warning */
  416.  
  417.     if ( gbm->bpp != 24 )
  418.         memcpy(gbmrgb, tif_priv->gbmrgb, (1 << gbm->bpp) * sizeof(GBMRGB));
  419.  
  420.     return GBM_ERR_OK;
  421.     }
  422. /*...e*/
  423. /*...stif_rdata:0:*/
  424. /*
  425. TIFF data is usually stored top-left-origin based.
  426. ie: We ignore the private "Orientation" tag.
  427. Our data format in memory has bigger padding than TIFF.
  428. It has 'istride' bytes per line, GBM uses/requires 'stride' bytes per line.
  429. Therefore we read it to the part of the strip area and then expand downwards.
  430. */
  431.  
  432. /*...sget_strip_packbits \45\ get bytes with packbits decompression:0:*/
  433. static GBM_ERR get_strip_packbits(int fd, byte *dest, long n_bytes)
  434.     {
  435.     AHEAD *ahead;
  436.  
  437.     if ( (ahead = gbm_create_ahead(fd)) == NULL )
  438.         return GBM_ERR_MEM;
  439.  
  440.     while ( n_bytes > 0 )
  441.         {
  442.         byte b = (byte) gbm_read_ahead(ahead);
  443.  
  444.         if ( b < 0x80 )
  445.             {
  446.             unsigned int count = b + 1;
  447.  
  448.             do
  449.                 *dest++ = (byte) gbm_read_ahead(ahead);
  450.             while ( --count > 0 );
  451.             n_bytes -= (b + 1);
  452.             }
  453.         else if ( b > 0x80 )
  454.             {
  455.             unsigned int count = 0x101 - (unsigned int) b;
  456.             byte c = (byte) gbm_read_ahead(ahead);
  457.  
  458.             memset(dest, c, count);
  459.             dest += count;
  460.             n_bytes -= count;
  461.             }
  462.         }
  463.  
  464.     gbm_destroy_ahead(ahead);
  465.     return GBM_ERR_OK;
  466.     }
  467. /*...e*/
  468. /*...sget_strip_lzw      \45\ get bytes with TIFF style LZW decompression:0:*/
  469. /*
  470. This code run on output of FotoTouch and some sample TIFFs from an afs
  471. directory on the IBM IP-network.
  472. */
  473.  
  474. /*...sread context:0:*/
  475. typedef struct
  476.     {
  477.     int fd;                /* File descriptor to read */
  478.     int inx, size;            /* Index and size in bits */
  479.     byte buf[255+3];        /* Buffer holding bits */
  480.     int code_size;            /* Number of bits to return at once */
  481.     cword read_mask;        /* 2^code_size-1 */
  482.     } READ_CONTEXT;
  483.  
  484. static cword read_code(READ_CONTEXT *c)
  485.     {
  486.     dword raw_code; int byte_inx;
  487.  
  488.     while ( c->inx + c->code_size > c->size )
  489. /*...snot enough bits in buffer\44\ refill it:16:*/
  490. /* Not very efficient, but infrequently called */
  491.  
  492. {
  493. int bytes_to_lose = ((unsigned)c->inx >> 3);
  494. int bytes;
  495.  
  496. /* Note biggest code size is 12 bits */
  497. /* And this can at worst span 3 bytes */
  498. memcpy(c->buf, c->buf + bytes_to_lose, 3);
  499. (c->inx) &= 7;
  500. (c->size) -= (bytes_to_lose << 3);
  501. bytes = 255 - ( (unsigned)c->size >> 3 );
  502. if ( (bytes = gbm_file_read(c->fd, c->buf + ((unsigned)c->size >> 3), bytes)) <= 0 )
  503.     return 0xffff;
  504. (c->size) += (bytes << 3);
  505. }
  506. /*...e*/
  507.  
  508.     byte_inx = ((unsigned)c->inx >> 3);
  509.     raw_code = ((c->buf[byte_inx    ]) << 16) +
  510.            ((c->buf[byte_inx + 1]) <<  8) +
  511.                ( c->buf[byte_inx + 2]       ) ;
  512.     raw_code <<= ((c->inx) & 7);
  513.     (c->inx) += (byte) (c->code_size);
  514.     raw_code >>= ( 24 - c->code_size );
  515.     return (cword) raw_code & c->read_mask;
  516.     }
  517. /*...e*/
  518.  
  519. #define    INIT_CODE_SIZE    9
  520.  
  521. static GBM_ERR get_strip_lzw(int fd, byte *dest, long n_bytes)
  522.     {
  523.     cword max_code;            /* 1 << code_size */
  524.     cword clear_code;        /* Code to clear table */
  525.     cword eoi_code;            /* End of information code */
  526.     cword first_free_code;        /* First free code */
  527.     cword free_code;        /* Next available free code slot */
  528.     int i, out_count = 0;
  529.     cword code, cur_code, old_code, in_code, fin_char;
  530.     cword *prefix, *suffix, *outcode;
  531.     READ_CONTEXT c;
  532.     BOOLEAN table_full = FALSE;
  533.  
  534.     n_bytes=n_bytes; /* Suppress 'unref arg' compiler warning */
  535.  
  536.     if ( (prefix = (cword *) malloc((size_t) (4096 * sizeof(cword)))) == NULL )
  537.         return GBM_ERR_MEM;
  538.     if ( (suffix = (cword *) malloc((size_t) (4096 * sizeof(cword)))) == NULL )
  539.         {
  540.         free(prefix);
  541.         return GBM_ERR_MEM;
  542.         }
  543.     if ( (outcode = (cword *) malloc((size_t) (4097 * sizeof(cword)))) == NULL )
  544.         {
  545.         free(suffix);
  546.         free(prefix);
  547.         return GBM_ERR_MEM;
  548.         }
  549.  
  550.     /* Initial read context */
  551.  
  552.     c.inx            = 0;
  553.     c.size           = 0;
  554.     c.fd             = fd;
  555.     c.code_size      = INIT_CODE_SIZE;
  556.     c.read_mask      = (cword) ( (1 << INIT_CODE_SIZE) - 1 );
  557.  
  558.     /* 2^min_code size accounts for all colours in file */
  559.  
  560.     clear_code = (cword) ( 1 << (INIT_CODE_SIZE - 1) );
  561.     eoi_code = (cword) (clear_code + 1);
  562.     free_code = first_free_code = (cword) (clear_code + 2);
  563.  
  564.     max_code = (cword) ( 1 << INIT_CODE_SIZE );
  565.  
  566.     while ( (code = read_code(&c)) != eoi_code && code != 0xffff )
  567.         {
  568.         if ( code == clear_code )
  569.             {
  570.             c.code_size = INIT_CODE_SIZE;
  571.             c.read_mask = (cword) ( (1 << INIT_CODE_SIZE) - 1);
  572.             max_code = (cword) ( 1 << INIT_CODE_SIZE );
  573.             free_code = first_free_code;
  574.             cur_code = old_code = code = read_code(&c);
  575.             if ( code == eoi_code || code == 0xffff )
  576.                 break;
  577.             fin_char = cur_code;
  578.             *dest++ = (byte) fin_char;
  579.             LOG(("%02x ", (byte) fin_char));
  580.             LOG(("%03x:%u\n", code, c.code_size));
  581.             table_full = FALSE;
  582.             }
  583.         else
  584.             {
  585.             cur_code = in_code = code;
  586.             if ( cur_code >= free_code )
  587.                 {
  588.                 cur_code = old_code;
  589.                 outcode[out_count++] = fin_char;
  590.                 }
  591.             while ( cur_code > 0xff )
  592.                 {
  593.                 if ( out_count > 4096 )
  594.                     {
  595.                     free(outcode);
  596.                     free(suffix);
  597.                     free(prefix);
  598.                     return GBM_ERR_TIF_CORRUPT;
  599.                     }
  600.                 outcode[out_count++] = suffix[cur_code];
  601.                 cur_code = prefix[cur_code];
  602.                 }
  603.             fin_char = cur_code;
  604.             outcode[out_count++] = fin_char;
  605.             for ( i = out_count - 1; i >= 0; i-- )
  606.                 {
  607.                 *dest++ = (byte) outcode[i];
  608.                 LOG(("%02x ", (byte) outcode[i]));
  609.                 }
  610.             LOG(("%03x:%u\n", code, c.code_size));
  611.             out_count = 0;
  612.  
  613.             /* Update dictionary */
  614.  
  615.             if ( !table_full )
  616.                 {
  617.                 prefix[free_code] = old_code;
  618.                 suffix[free_code] = fin_char;
  619.  
  620.                 /* Advance to next free slot */
  621.  
  622.                 if ( ++free_code >= max_code - 1 )
  623.                     {
  624.                     if ( c.code_size < 12 )
  625.                         {
  626.                         c.code_size++;
  627.                         max_code <<= 1;
  628.                         c.read_mask = (cword) (( 1 << c.code_size ) - 1);
  629.                         }
  630.                     else
  631.                         table_full = TRUE;
  632.                     }
  633.                 }
  634.             old_code = in_code;
  635.             }
  636.         }
  637.  
  638.     free(outcode);
  639.     free(suffix);
  640.     free(prefix);
  641.  
  642.     if ( code == 0xffff )
  643.         return GBM_ERR_READ;
  644.  
  645.     return GBM_ERR_OK;
  646.     }
  647. /*...e*/
  648. /*...sget_strip_lzw_pred \45\ get_strip_lzw with non 1 predictor fixup:0:*/
  649. static GBM_ERR get_strip_lzw_pred(
  650.     int fd,
  651.     byte *dest,
  652.     long n_bytes,
  653.     TIF_PRIV *tif_priv,
  654.     int w, int h
  655.     )
  656.     {
  657.     GBM_ERR rc;
  658.  
  659.     if ( (rc = get_strip_lzw(fd, dest, n_bytes)) != GBM_ERR_OK )
  660.         return rc;
  661.  
  662.     if ( tif_priv->predictor == 2 )
  663.         /* Note: This is only allowed if bps==8 */
  664.             {
  665.             int x, y, spp = tif_priv->spp;
  666.             for ( y = 0; y < h; y++, dest += w * spp )
  667.                 for ( x = spp; x < w * spp; x++ )
  668.                     dest[x] += dest[x - spp];
  669.             }
  670.  
  671.     return GBM_ERR_OK;
  672.     }
  673. /*...e*/
  674. /*...sget_strip_comp     \45\ get strip\44\ dealing with any compression:0:*/
  675. /* n_bytes is passed in as istride * n_lines */
  676.  
  677. static GBM_ERR get_strip_comp(
  678.     int fd,
  679.     byte *dest,
  680.     long so, long n_bytes,
  681.     TIF_PRIV *tif_priv,
  682.     int w, int h
  683.     )
  684.     {
  685.     gbm_file_lseek(fd, so, SEEK_SET);
  686.     switch ( tif_priv->comp )
  687.         {
  688. /*...sENC_NONE     \45\ no compression:16:*/
  689. case ENC_NONE:
  690.     return ( (int) n_bytes == gbm_file_read(fd, dest, (int) n_bytes) ) ?
  691.             GBM_ERR_OK : GBM_ERR_READ;
  692. /*...e*/
  693. /*...sENC_PACKBITS \45\ packbits:16:*/
  694. case ENC_PACKBITS:
  695.     return get_strip_packbits(fd, dest, n_bytes);
  696. /*...e*/
  697. /*...sENC_LZW      \45\ lzw:16:*/
  698. case ENC_LZW:
  699.     return get_strip_lzw_pred(fd, dest, n_bytes, tif_priv, w, h);
  700. /*...e*/
  701.         }
  702.     return GBM_ERR_NOT_SUPP;
  703.     }
  704. /*...e*/
  705. /*...sget_strip          \45\ get strip\44\ discarding extra samples\44\ and CMYK mapping:0:*/
  706. /*
  707. If there are too many samples per pixel, this code can ignore the extra ones.
  708. Also, if CMYK data is being read, it will read the CMYK, and convert.
  709. This requires a temporary buffer, to read the original data in.
  710. The original data is then 'converted'.
  711. */
  712.  
  713. static GBM_ERR get_strip(
  714.     int fd,
  715.     byte *dest,
  716.     long so, long n_bytes,
  717.     TIF_PRIV *tif_priv,
  718.     int w, int h
  719.     )
  720.     {
  721.     byte *buf = dest;
  722.     GBM_ERR rc;
  723.  
  724.     if ( tif_priv->photo == PHOTO_CMYK )
  725. /*...sallocate space for CMYK image:16:*/
  726. {
  727. n_bytes = (long) w * 4L * (long) h;
  728. if ( (buf = malloc((size_t) n_bytes)) == NULL )
  729.     return GBM_ERR_MEM;
  730. }
  731. /*...e*/
  732.     else if ( tif_priv->photo == PHOTO_RGB && tif_priv->spp > 3 )
  733. /*...sallocate space for image \43\ extra samples:16:*/
  734. {
  735. n_bytes = (long) w * tif_priv->spp * (long) h;
  736. if ( (buf = malloc((size_t) n_bytes)) == NULL )
  737.     return GBM_ERR_MEM;
  738. }
  739. /*...e*/
  740.  
  741.     if ( (rc = get_strip_comp(fd, buf, so, n_bytes, tif_priv, w, h)) != GBM_ERR_OK )
  742.         {
  743.         if ( buf != dest )
  744.             free(buf);
  745.         return rc;
  746.         }
  747.  
  748.     if ( tif_priv->photo == PHOTO_CMYK )
  749. /*...sconvert from CMYK to RGB:16:*/
  750. {
  751. int x, yy;
  752. byte *buf_p = buf, *dest_p = dest;
  753. for ( yy = 0; yy < h; yy++ )
  754.     for ( x = 0; x < w; x++ )
  755.         {
  756.         word c = *buf_p++;
  757.         word m = *buf_p++;
  758.         word y = *buf_p++;
  759.         word k = *buf_p++;
  760.  
  761.         /* Exploit 8 bit modulo arithmetic by biasing by + 0x100 */
  762.  
  763.         word r = 0x1ff - (c + k);
  764.         word g = 0x1ff - (m + k);
  765.         word b = 0x1ff - (y + k);
  766.  
  767.         if ( r < 0x100 ) r = 0x100;
  768.         if ( g < 0x100 ) g = 0x100;
  769.         if ( b < 0x100 ) b = 0x100;
  770.  
  771.         *dest_p++ = (byte) r;
  772.         *dest_p++ = (byte) g;
  773.         *dest_p++ = (byte) b;
  774.         }
  775.  
  776. free(buf);
  777. }
  778. /*...e*/
  779.     else if ( tif_priv->photo == PHOTO_RGB && tif_priv->spp > 3 )
  780. /*...sextract\44\ ignoring extra\45\samples:16:*/
  781. {
  782. int x, y, skip = tif_priv->spp - 2;
  783. byte *buf_p = buf, *dest_p = dest;
  784. for ( y = 0; y < h; y++ )
  785.     for ( x = 0; x < w; x++ )
  786.         {
  787.         *dest_p++ = *buf_p++;
  788.         *dest_p++ = *buf_p++;
  789.         *dest_p++ = *buf_p  ;
  790.         buf_p += skip;
  791.         }
  792.  
  793. free(buf);
  794. }
  795. /*...e*/
  796.  
  797.     return GBM_ERR_OK;
  798.     }
  799. /*...e*/
  800. /*...sget_image          \45\ get all strips\44\ result is whole image:0:*/
  801. /*
  802. This routine calls get_strip() to get strips data one after another until it
  803. has read the entire images worth of data. Of course, scan lines are aligned on
  804. byte boundaries, and the data is usually considered to be image top to bottom.
  805. */
  806.  
  807. static GBM_ERR get_image(
  808.     int fd,
  809.     byte *dest,
  810.     TIF_PRIV *tif_priv,
  811.     long *so,
  812.     GBM *gbm,
  813.     int *strip
  814.     )
  815.     {
  816.     GBM_ERR    rc;
  817.     int y, istride = ((gbm->w * gbm->bpp + 7) / 8);
  818.  
  819.     for ( y = 0; y < gbm->h; y += tif_priv->rps, (*strip)++ )
  820.         {
  821.         int n_lines = min(tif_priv->rps, gbm->h - y);
  822.         if ( (rc = get_strip(fd, dest + y * istride,
  823.                      so[*strip],
  824.                      (long) n_lines * (long) istride,
  825.                      tif_priv,
  826.                      gbm->w, n_lines)) != GBM_ERR_OK )
  827.             return rc;
  828.         }
  829.  
  830.     return GBM_ERR_OK;
  831.     }
  832. /*...e*/
  833. /*...sget_image_planar   \45\ get all strips\44\ allowing for PlanarConfiguration:0:*/
  834. /*
  835. get_image() will assume the data is in PlanarConfiguration==1, ie: chunky
  836. pixel mode. This is TRUE most of the time. But sometimes we will actually
  837. allow PlanarConfiguration==2. In this case, use get_image() and then fix-up
  838. the results.
  839. */
  840.  
  841. static GBM_ERR get_image_planar(
  842.     int fd,
  843.     byte *dest,
  844.     TIF_PRIV *tif_priv,
  845.     long *so,
  846.     GBM *gbm
  847.     )
  848.     {
  849.     int strip = 0;
  850.  
  851.     if ( tif_priv->photo == PHOTO_RGB &&
  852.          tif_priv->planar == 2 )
  853. /*...sread 3 seperate planes\44\ and combine them:16:*/
  854. /*
  855. If PhotometricInterpretation==RGB and
  856.    SamplesPerPixel>=3 and
  857.    BitsPerSample==8 then
  858.     we allow PlanarConfiguration==2
  859.  
  860. I have successfully read in a PlanarConfiguration==2 RGB TIFF file by using
  861. the "read 3 images" logic below. This image had RowsPerStrip==1, and so
  862. technically either fold below would have worked. I think the read 3 images
  863. logic is a better interpretation of the TIFF 6.0 spec., but until I find
  864. some other images I can handle, I will keep the alternative peice of code.
  865. */
  866.  
  867. {
  868. GBM_ERR rc;
  869. GBM gbm_planar;
  870. int saved_spp = tif_priv->spp;
  871. int n_bytes = gbm->w * gbm->h;
  872. int x, y;
  873. byte *buf, *p[3];
  874.  
  875. if ( (buf = malloc((size_t) (n_bytes * 3))) == NULL )
  876.     return GBM_ERR_MEM;
  877. p[0] = buf;
  878. p[1] = p[0] + n_bytes;
  879. p[2] = p[1] + n_bytes;
  880.  
  881. tif_priv->spp = 1;
  882. /*...sread 3 images:16:*/
  883. {
  884. int i;
  885.  
  886. gbm_planar.w   = gbm->w;
  887. gbm_planar.h   = gbm->h;
  888. gbm_planar.bpp = 8;
  889. for ( i = 0; i < 3; i++ )
  890.     if ( (rc = get_image(fd, p[i], tif_priv, so, &gbm_planar, &strip)) != GBM_ERR_OK )
  891.         {
  892.         tif_priv->spp = saved_spp;
  893.         free(buf);
  894.         return rc;
  895.         }
  896. }
  897. /*...e*/
  898. #ifdef NEVER
  899. /*...sread single image 3x too high:16:*/
  900. gbm_planar.w   = gbm->w;
  901. gbm_planar.h   = gbm->h * 3;
  902. gbm_planar.bpp = 8;
  903. if ( (rc = get_image(fd, buf, tif_priv, so, &gbm_planar, &strip)) != GBM_ERR_OK )
  904.     {
  905.     tif_priv->spp = saved_spp;
  906.     free(buf);
  907.     return rc;
  908.     }
  909. /*...e*/
  910. #endif
  911. tif_priv->spp = saved_spp;
  912.  
  913. for ( y = 0; y < gbm->h; y++ )
  914.     for ( x = 0; x < gbm->w; x++ )
  915.         {
  916.         *dest++ = *(p[0])++;
  917.         *dest++ = *(p[1])++;
  918.         *dest++ = *(p[2])++;
  919.         }
  920. free(buf);
  921. return GBM_ERR_OK;
  922. }
  923. /*...e*/
  924.     else
  925.         return get_image(fd, dest, tif_priv, so, gbm, &strip);
  926.     }
  927. /*...e*/
  928. /*...sget_image_orient   \45\ get all strips\44\ correctly orientated:0:*/
  929. static GBM_ERR get_image_orient(
  930.     int fd,
  931.     byte *dest,
  932.     TIF_PRIV *tif_priv,
  933.     long *so,
  934.     GBM *gbm
  935.     )
  936.     {
  937.     switch ( tif_priv->orient )
  938.         {
  939. /*...s1 \45\ usual Baseline required case:16:*/
  940. /*
  941. File has array[scanlines_down] of array[pixels_across] of pixel.
  942. GBMs bitmap data is array[scanlines_up] of array[pixels_across] of pixel.
  943. So call get_image_planar(), and vertically reflect resulting data.
  944. */
  945.  
  946. case 1:
  947.     {
  948.     int istride = ((gbm->bpp * gbm->w + 7) / 8);
  949.     byte *p0, *p1, *p2;
  950.     GBM_ERR rc;
  951.     if ( (rc = get_image_planar(fd, dest, tif_priv, so, gbm)) != GBM_ERR_OK )
  952.         return rc;
  953.     if ( (p0 = malloc((size_t) istride)) == NULL )
  954.         return GBM_ERR_MEM;
  955.     for ( p1 = dest, p2 = p1 + (gbm->h - 1) * istride;
  956.           p1 < p2;
  957.           p1 += istride, p2 -= istride )
  958.         {
  959.         memcpy(p0, p1, istride);
  960.         memcpy(p1, p2, istride);
  961.         memcpy(p2, p0, istride);
  962.         }
  963.     free(p0);
  964.     return GBM_ERR_OK;
  965.     }
  966. /*...e*/
  967. /*...s4 \45\ vertically swapped case we can easily handle:16:*/
  968. /*
  969. File has array[scanlines_up] of array[pixels_across] of pixel.
  970. Exactly matches GBMs layout of a bitmap.
  971. So simply call get_image() and be done with.
  972. */
  973.  
  974. case 4:
  975.     return get_image_planar(fd, dest, tif_priv, so, gbm);
  976. /*...e*/
  977.         }
  978.     return GBM_ERR_NOT_SUPP; /* Shouldn't get here */
  979.     }
  980. /*...e*/
  981. /*...sget_image_strippy  \45\ get all strips\44\ when there are loads of them:0:*/
  982. static GBM_ERR get_image_strippy(
  983.     int fd,
  984.     byte *dest,
  985.     TIF_PRIV *tif_priv,
  986.     GBM *gbm
  987.     )
  988.     {
  989.     int n_strips = (gbm->h + (tif_priv->rps - 1)) / tif_priv->rps;
  990.     long *so = tif_priv->so;
  991.  
  992.     if ( n_strips > MAX_STRIPS )
  993. /*...sre\45\read TIFF file header:16:*/
  994. {
  995. GBM_ERR rc;
  996. int strip;
  997. IFH *ifh;
  998. IFD *ifd;
  999. TAG *tag_so;
  1000.  
  1001. if ( (so = malloc((size_t) (n_strips * sizeof(long)))) == NULL )
  1002.     return GBM_ERR_MEM;
  1003.  
  1004. gbm_file_lseek(fd, 0L, SEEK_SET);
  1005. if ( read_ifh_and_ifd(fd, tif_priv->inx, &ifh) != TE_OK )
  1006.     {
  1007.     free(so);
  1008.     return GBM_ERR_MEM;
  1009.     }
  1010. ifd = ifh->ifd;
  1011. tag_so = locate_tag(ifd, T_STRIPOFFSETS);
  1012. for ( strip = 0; strip < n_strips; strip++ )
  1013.     so[strip] = value_of_tag_n(tag_so, strip);
  1014. free_ifh(ifh);
  1015.  
  1016. rc = get_image_orient(fd, dest, tif_priv, so, gbm);
  1017.  
  1018. free(so);
  1019. return rc;
  1020. }
  1021. /*...e*/
  1022.     else
  1023.         return get_image_orient(fd, dest, tif_priv, so, gbm);
  1024.     }
  1025. /*...e*/
  1026.  
  1027. GBM_ERR tif_rdata(int fd, GBM *gbm, byte *data)
  1028.     {
  1029.     TIF_PRIV *tif_priv = (TIF_PRIV *) gbm->priv;
  1030.     int stride = ((gbm->bpp * gbm->w + 31) / 32) * 4;
  1031.     int istride = ((gbm->bpp * gbm->w + 7) / 8);
  1032.     int bias = gbm->h * (stride - istride);
  1033.     GBM_ERR    rc;
  1034.  
  1035.     /* Read in data, packed close, and upside down */
  1036.  
  1037.     if ( (rc = get_image_strippy(fd, data + bias, tif_priv, gbm)) != GBM_ERR_OK )
  1038.         return rc;
  1039.  
  1040. /*...snow expand out from byte padding to dword padding:8:*/
  1041. if ( bias )
  1042.     {
  1043.     int y;
  1044.     byte *dest = data, *src  = data + bias;
  1045.  
  1046.     for ( y = 0; y < gbm->h; y++, dest += stride, src += istride )
  1047.         memcpy(dest, src, istride);
  1048.     }
  1049. /*...e*/
  1050. /*...snow RGB\45\\62\BGR if 24 bit data returned:8:*/
  1051. if ( gbm->bpp == 24 )
  1052.     {
  1053.     int y;
  1054.     byte *p = data;
  1055.  
  1056.     for ( y = 0; y < gbm->h; y++, p += stride )
  1057.         rgb_bgr(p, p, gbm->w);
  1058.     }
  1059. /*...e*/
  1060.  
  1061.     return GBM_ERR_OK;
  1062.     }
  1063. /*...e*/
  1064. /*...stif_w:0:*/
  1065. /*
  1066. Write out data in a single large strip for now.
  1067. Note that the palette entrys are written as ((r << 8) | r).
  1068. This means they are 257/256 too big (insignificant).
  1069. Most programs only look at the top 8 bits (ie: no error).
  1070. A few (incorrectly) look at the bottom 8 bits.
  1071. Therefore we cater for all programs, with minimal fuss.
  1072. */
  1073.  
  1074. /*...suser_tag:0:*/
  1075. static BOOLEAN user_tag(IFD *ifd, char *name, short type, const char *opt, char *def)
  1076.     {
  1077.     char buf[200+1];
  1078.     const char *s;
  1079.  
  1080.     if ( (s = gbm_find_word_prefix(opt, name)) != NULL )
  1081.         sscanf(s + strlen(name), "%s", buf);
  1082.     else
  1083.         strcpy(buf, def);
  1084.  
  1085.     if ( *buf == '\0' )
  1086.         return TRUE;
  1087.  
  1088.     return add_ascii_tag(ifd, type, buf);
  1089.     }
  1090. /*...e*/
  1091. /*...swrite_strip:0:*/
  1092. static GBM_ERR write_strip(int fd, int w, int h, int bpp, const byte *data)
  1093.     {
  1094.     int stride = ((bpp * w + 31) / 32) * 4;
  1095.     int ostride = ((bpp * w + 7) / 8);
  1096.     int y;
  1097.     data += ((h - 1) * stride);
  1098.     if ( bpp == 24 )
  1099. /*...sreverse rgb\47\bgr ordering and write:16:*/
  1100. {
  1101. byte *line;
  1102.  
  1103. if ( (line = malloc((size_t) ostride)) == NULL )
  1104.     return GBM_ERR_MEM;
  1105. for ( y = 0; y < h; y++, data -= stride )
  1106.     {
  1107.     rgb_bgr(data, line, w);
  1108.     if ( gbm_file_write(fd, line, ostride) != ostride )
  1109.         {
  1110.         free(line);
  1111.         return GBM_ERR_WRITE;
  1112.         }
  1113.     }
  1114. free(line);
  1115. }
  1116. /*...e*/
  1117.     else
  1118. /*...swrite:16:*/
  1119. for ( y = 0; y < h; y++, data -= stride )
  1120.     if ( gbm_file_write(fd, data, ostride) != ostride )
  1121.         return GBM_ERR_WRITE;
  1122. /*...e*/
  1123.     return GBM_ERR_OK;
  1124.     }
  1125. /*...e*/
  1126. /*...swrite_strip_lzw \45\ new fast tail\43\col lookup version:0:*/
  1127. /*
  1128. This is a tricky bit of code to get right.
  1129. This code blantantly copied and hacked from that in gbmgif.c!
  1130. hashvalue is calculated from a string of pixels cumulatively.
  1131. hashtable is searched starting at index hashvalue for to find the entry.
  1132. hashtable is big enough so that MAX_HASH > 4*MAX_DICT.
  1133. */
  1134.  
  1135. /*...swrite context:0:*/
  1136. #define    L_BUF 1024
  1137.  
  1138. typedef struct
  1139.     {
  1140.     int fd;                /* Open file descriptor to write to */
  1141.     int inx;            /* Bit index into buf */
  1142.     int code_size;            /* Code size in bits */
  1143.     byte buf[L_BUF+2];        /* Biggest block + overflow space */
  1144.     } WRITE_CONTEXT;
  1145.  
  1146. static BOOLEAN write_code(cword code, WRITE_CONTEXT *w)
  1147.     {
  1148.     byte *buf = w->buf + ((unsigned)w->inx >> 3);
  1149.  
  1150.     LOG(("%03x:%u\n", code, w->code_size));
  1151.     code <<= (24-w->code_size);
  1152.     code >>= (w->inx&7U);
  1153.     *buf++ |= (byte) (code >> 16);
  1154.     *buf++  = (byte) (code >>  8);
  1155.     *buf    = (byte)  code       ;
  1156.  
  1157.     (w->inx) += (w->code_size);
  1158.     if ( w->inx >= L_BUF * 8 )
  1159.         /* Flush out full buffer */
  1160.         {
  1161.         if ( gbm_file_write(w->fd, w->buf, L_BUF) != L_BUF )
  1162.             return FALSE;
  1163.         memcpy(w->buf, w->buf + L_BUF, 2);
  1164.         memset(w->buf + 2, 0, L_BUF);
  1165.         (w->inx) -= (L_BUF * 8);
  1166.         }
  1167.  
  1168.     return TRUE;
  1169.     }
  1170.  
  1171. static BOOLEAN flush_code(WRITE_CONTEXT *w)
  1172.     {
  1173.     int bytes = (((unsigned)w->inx + 7) >> 3);
  1174.  
  1175.     if ( bytes )
  1176.         {
  1177.         if ( gbm_file_write(w->fd, w->buf, bytes) != bytes )
  1178.             return FALSE;
  1179.         }
  1180.  
  1181.     return TRUE;
  1182.     }
  1183. /*...e*/
  1184.  
  1185. #define    MAX_HASH    17777        /* Probably prime, and > 4096        */
  1186. #define    MAX_DICT    4096        /* Dictionary size                   */
  1187. #define    INIT_HASH(p)    (((p)+3)*301)    /* Initial hash value                */
  1188. #define    INIT_CODE_SIZE    9
  1189. #define    CLEAR_CODE    ((cword) 0x100)
  1190. #define    EOI_CODE    ((cword) 0x101)
  1191.  
  1192. typedef struct { cword tail; byte col; } DICT;
  1193.  
  1194. static GBM_ERR write_strip_lzw(int fd, int w, int h, int bpp, const byte *data)
  1195.     {
  1196.     int stride = ((bpp * w + 31) / 32) * 4;
  1197.     int ostride = ((bpp * w + 7) / 8);
  1198.     WRITE_CONTEXT wc;
  1199.     cword last_code, max_code, tail;
  1200.     int x, y;
  1201.     unsigned int hashvalue, lenstring, j;
  1202.     DICT *dict, **hashtable;
  1203.  
  1204.     if ( (dict = (DICT *) malloc((size_t) (MAX_DICT * sizeof(DICT)))) == NULL )
  1205.         return GBM_ERR_MEM;
  1206.  
  1207.     if ( (hashtable = (DICT **) malloc((size_t) (MAX_HASH * sizeof(DICT *)))) == NULL )
  1208.         {
  1209.         free(dict);
  1210.         return GBM_ERR_MEM;
  1211.         }
  1212.  
  1213.     /* Setup write context */
  1214.  
  1215.     wc.fd        = fd;
  1216.     wc.inx       = 0;
  1217.     wc.code_size = INIT_CODE_SIZE;
  1218.     memset(wc.buf, 0, sizeof(wc.buf));
  1219.  
  1220.     if ( !write_code(CLEAR_CODE, &wc) )
  1221.         {
  1222.         free(hashtable);
  1223.         free(dict);
  1224.         return GBM_ERR_WRITE;
  1225.         }
  1226.  
  1227.     last_code = EOI_CODE;
  1228.     max_code  = ( 1 << INIT_CODE_SIZE );
  1229.     lenstring = 0;
  1230.  
  1231.     for ( j = 0; j < MAX_HASH; j++ )
  1232.         hashtable[j] = NULL;
  1233.  
  1234.     data += ( (h - 1) * stride );
  1235.     for ( y = h - 1; y >= 0; y--, data -= stride )
  1236.         {
  1237.         int inx1 = 0, inx2 = 2;
  1238.         for ( x = 0; x < ostride; x++ )
  1239.             {
  1240.             byte col;
  1241. /*...sget byte to write to col:24:*/
  1242. if ( bpp == 24 )
  1243.     /* Have to handle rgb/bgr reverse as we go along */
  1244.     {
  1245.     col = data[inx1+inx2];
  1246.     if ( --inx2 < 0 )
  1247.         {
  1248.         inx1 += 3; inx2 = 2;
  1249.         }
  1250.     }
  1251. else
  1252.     col = data[x];
  1253. /*...e*/
  1254. /*...sLZW encode:24:*/
  1255. if ( ++lenstring == 1 )
  1256.     {
  1257.     tail      = col;
  1258.     hashvalue = INIT_HASH(col);
  1259.     }
  1260. else
  1261.     {
  1262.     hashvalue *= ( col + lenstring + 4 );
  1263.     j = ( hashvalue %= MAX_HASH );
  1264.     while ( hashtable[j] != NULL &&
  1265.         ( hashtable[j]->tail != tail ||
  1266.           hashtable[j]->col  != col  ) )
  1267.         if ( ++j >= MAX_HASH )
  1268.             j = 0;
  1269.     if ( hashtable[j] != NULL )
  1270.         /* Found in the strings table */
  1271.         {
  1272.         tail = (hashtable[j]-dict);
  1273.         LOG(("%02x ", col));
  1274.         }
  1275.     else
  1276.         /* Not found */
  1277.         {
  1278.         if ( !write_code(tail, &wc) )
  1279.             {
  1280.             free(hashtable);
  1281.             free(dict);
  1282.             return GBM_ERR_WRITE;
  1283.             }
  1284.         hashtable[j]       = dict + ++last_code;
  1285.         hashtable[j]->tail = tail;
  1286.         hashtable[j]->col  = col;
  1287.         LOG(("%02x ", col));
  1288.         tail               = col;
  1289.         hashvalue          = INIT_HASH(col);
  1290.         lenstring          = 1;
  1291.  
  1292. /* Note: Things change 1 earlier than in the GIF LZW case, hence -1. */
  1293.         if ( last_code >= max_code -1 )
  1294.             /* Next code will be written longer */
  1295.             {
  1296.             max_code <<= 1;
  1297.             wc.code_size++;
  1298.             }
  1299.         else if ( last_code >= MAX_DICT-2 )
  1300.             /* Reset tables */
  1301.             {
  1302.             if ( !write_code(tail      , &wc) ||
  1303.                  !write_code(CLEAR_CODE, &wc) )
  1304.                 {
  1305.                 free(hashtable);
  1306.                 free(dict);
  1307.                 return GBM_ERR_WRITE;
  1308.                 }
  1309.             lenstring    = 0;
  1310.             last_code    = EOI_CODE;
  1311.             wc.code_size = INIT_CODE_SIZE;
  1312.             max_code     = ( 1 << INIT_CODE_SIZE );
  1313.             for ( j = 0; j < MAX_HASH; j++ )
  1314.                 hashtable[j] = NULL;
  1315.             }
  1316.         }
  1317.     }
  1318. /*...e*/
  1319.             }
  1320.         }
  1321.  
  1322.     free(hashtable);
  1323.     free(dict);
  1324.  
  1325.     if ( lenstring != 0 )
  1326.         /* Only write tail if no code written for some input */
  1327.         {
  1328.         if ( !write_code(tail, &wc) )
  1329.             return GBM_ERR_WRITE;
  1330.         if ( ++last_code >= max_code -1 )
  1331.             /* Next code will be written longer */
  1332.             wc.code_size++;
  1333.         }
  1334.  
  1335.     if ( !write_code(EOI_CODE, &wc) ||
  1336.          !flush_code(          &wc) )
  1337.         return GBM_ERR_WRITE;
  1338.  
  1339.     return GBM_ERR_OK;
  1340.     }
  1341. /*...e*/
  1342.  
  1343. GBM_ERR tif_w(const char *fn, int fd, const GBM *gbm, const GBMRGB *gbmrgb, const byte *data, const char *opt)
  1344.     {
  1345.     BOOLEAN    baseline = ( gbm_find_word(opt, "pal1bpp") == NULL );
  1346.     BOOLEAN lzw      = ( gbm_find_word(opt, "lzw"    ) != NULL );
  1347.     IFH    *ifh;
  1348.     IFD    *ifd;
  1349.     long    w = gbm->w;
  1350.     long    h = gbm->h;
  1351.     long    stripoffset, stripbytecount;
  1352.     short    samplesperpixel, bitspersample[3], photo, comp;
  1353.     short    colormap[0x100+0x100+0x100];
  1354.     BOOLEAN    ok;
  1355.     GBM_ERR    rc;
  1356.  
  1357.     fn=fn; /* Suppress 'unref arg' compiler warning */
  1358.  
  1359.     if ( (ifh = make_ifh()) == NULL )
  1360.         return GBM_ERR_MEM;
  1361.  
  1362.     ifd = ifh->ifd;
  1363.  
  1364.     if ( gbm->bpp == 1 && baseline )
  1365.         {
  1366.         word k0 = (word) gbmrgb[0].r + (word) gbmrgb[0].g + (word) gbmrgb[0].b;
  1367.         word k1 = (word) gbmrgb[1].r + (word) gbmrgb[1].g + (word) gbmrgb[1].b;
  1368.         samplesperpixel   = 1;
  1369.         bitspersample[0] = 1;
  1370.         photo = ( k0 < k1 ) ? PHOTO_BIT1 : PHOTO_BIT0; /* Black is zero : White is zero */
  1371.         }
  1372.     else if ( gbm->bpp == 24 )
  1373.         {
  1374.         samplesperpixel   = 3;
  1375.         bitspersample[0] = 
  1376.         bitspersample[1] = 
  1377.         bitspersample[2] = 8;
  1378.         photo = PHOTO_RGB;
  1379.         }
  1380.     else
  1381.         {
  1382.         samplesperpixel   = 1;
  1383.         bitspersample[0] = (short) gbm->bpp;
  1384.         photo = PHOTO_PAL;
  1385.         }
  1386.  
  1387.     comp = ( lzw ) ? ENC_LZW : ENC_NONE;
  1388.  
  1389.     ok = add_long_tag(ifd, T_IMAGEWIDTH, &w, 1) &&
  1390.          add_long_tag(ifd, T_IMAGELENGTH, &h, 1) &&
  1391.          add_long_tag(ifd, T_STRIPOFFSETS, &stripoffset, 1) &&
  1392.          add_long_tag(ifd, T_STRIPBYTECOUNTS, &stripbytecount, 1) &&
  1393.          add_short_tag(ifd, T_SAMPLESPERPIXEL, &samplesperpixel, 1) &&
  1394.          add_short_tag(ifd, T_BITSPERSAMPLE, bitspersample, samplesperpixel) &&
  1395.          add_short_tag(ifd, T_PHOTOMETRIC, &photo, 1) &&
  1396.          add_short_tag(ifd, T_COMPRESSION, &comp, 1) &&
  1397.          user_tag(ifd, "artist=", T_ARTIST, opt, "") &&
  1398.          user_tag(ifd, "software=", T_MAKE, opt, "") &&
  1399.          user_tag(ifd, "make=", T_MAKE, opt, "") &&
  1400.          user_tag(ifd, "model=", T_MODEL, opt, "") &&
  1401.          user_tag(ifd, "hostcomputer=", T_HOSTCOMPUTER, opt, "") &&
  1402.          user_tag(ifd, "documentname=", T_DOCNAME, opt, "") &&
  1403.          user_tag(ifd, "pagename=", T_PAGENAME, opt, "") &&
  1404.          user_tag(ifd, "imagedescription=", T_DESCRIPTION, opt, "");
  1405.  
  1406.     if ( gbm->bpp != 24 )
  1407.         {
  1408.         int    i, n_cols = (1 << gbm->bpp);
  1409.  
  1410.         for ( i = 0; i < n_cols; i++ )
  1411.             {
  1412.             short    r = (short) gbmrgb[i].r;
  1413.             short    g = (short) gbmrgb[i].g;
  1414.             short    b = (short) gbmrgb[i].b;
  1415.  
  1416.             colormap[             i] = ((r << 8) | r);
  1417.             colormap[    n_cols + i] = ((g << 8) | g);
  1418.             colormap[2 * n_cols + i] = ((b << 8) | b);
  1419.             }
  1420.         if ( gbm->bpp != 1 || !baseline )
  1421.             ok &= add_short_tag(ifd, T_COLORMAP, colormap, n_cols * 3);
  1422.         }
  1423.  
  1424.     if ( !ok )
  1425.         {
  1426.         free_ifh(ifh);
  1427.         return GBM_ERR_MEM;
  1428.         }
  1429.  
  1430.     if ( !write_ifh_and_ifd(ifh, fd) )
  1431.         {
  1432.         free_ifh(ifh);
  1433.         return GBM_ERR_WRITE;
  1434.         }
  1435.  
  1436.     stripoffset = gbm_file_lseek(fd, 0L, SEEK_CUR);
  1437.  
  1438.     if ( lzw )
  1439.         rc = write_strip_lzw(fd, gbm->w, gbm->h, gbm->bpp, data);
  1440.     else
  1441.         rc = write_strip(fd, gbm->w, gbm->h, gbm->bpp, data);
  1442.     
  1443.     if ( rc != GBM_ERR_OK )
  1444.         {
  1445.         free_ifh(ifh);
  1446.         return rc;
  1447.         }
  1448.  
  1449.     stripbytecount = gbm_file_lseek(fd, 0L, SEEK_CUR) - stripoffset;
  1450.  
  1451.     update_long_tag(ifd, T_STRIPOFFSETS, &stripoffset);
  1452.     update_long_tag(ifd, T_STRIPBYTECOUNTS, &stripbytecount);
  1453.  
  1454.     if ( !update_ifd(ifd, fd) )
  1455.         {
  1456.         free_ifh(ifh);
  1457.         return GBM_ERR_WRITE;
  1458.         }
  1459.  
  1460.     free_ifh(ifh);
  1461.  
  1462.     return GBM_ERR_OK;
  1463.     }
  1464. /*...e*/
  1465. /*...stif_err:0:*/
  1466. const char *tif_err(GBM_ERR rc)
  1467.     {
  1468.     switch ( (int) rc )
  1469.         {
  1470.         case GBM_ERR_TIF_VERSION:
  1471.             return "version number not 42";
  1472.         case GBM_ERR_TIF_N_TAGS:
  1473.             return "too many tags in file";
  1474.         case GBM_ERR_TIF_TAG_TYPE:
  1475.             return "bad tag type";
  1476.         case GBM_ERR_TIF_HEADER:
  1477.             return "corrupt header";
  1478.         case GBM_ERR_TIF_MISSING_TAG:
  1479.             return "ImageWidth, ImageLength or StripOffsets tag missing";
  1480.         case GBM_ERR_TIF_SPP_BIT:
  1481.             return "SamplesPerPixel tag must be 1 for bitmap or greyscale file";
  1482.         case GBM_ERR_TIF_BPS_BIT:
  1483.             return "BitsPerSample tag must be 1,4 or 8 for bitmap or greyscale file";
  1484.         case GBM_ERR_TIF_SPP_RGB:
  1485.             return "SamplesPerPixel tag must be 3 or more for RGB file";
  1486.         case GBM_ERR_TIF_BPS_RGB:
  1487.             return "BitsPerSample tag must be 8 for RGB file";
  1488.         case GBM_ERR_TIF_SPP_PAL:
  1489.             return "SamplesPerPixel tag must be 1 for palettised file";
  1490.         case GBM_ERR_TIF_BPS_PAL:
  1491.             return "BitsPerSample tag must be 1,4 or 8 for palettised file";
  1492.         case GBM_ERR_TIF_SPP_CMYK:
  1493.             return "SamplesPerPixel tag must be 4 for CMYK file";
  1494.         case GBM_ERR_TIF_BPS_CMYK:
  1495.             return "BitsPerSample tag must be 8 for CMYK file";
  1496.         case GBM_ERR_TIF_COMP_1D_MH:
  1497.             return "Compression tag is CCITT 1D Modified Huffman, not supported";
  1498.         case GBM_ERR_TIF_COMP_T4:
  1499.             return "Compression tag is CCITT T.4 G3 Facsimile, not supported";
  1500.         case GBM_ERR_TIF_COMP_T6:
  1501.             return "Compression tag is CCITT T.6 G4 Facsimile, not supported";
  1502.         case GBM_ERR_TIF_COMP:
  1503.             return "Compression tag not uncompressed, PackBits or LZW, not supported";
  1504.         case GBM_ERR_TIF_COLORMAP:
  1505.             return "ColorMap tag missing";
  1506.         case GBM_ERR_TIF_CORRUPT:
  1507.             return "encoded data is corrupt";
  1508.         case GBM_ERR_TIF_PREDICTOR:
  1509.             return "Predictor tag bad";
  1510.         case GBM_ERR_TIF_PHOTO_TRANS:
  1511.             return "PhotometricInterpretation tag is transparency mask, not supported";
  1512.         case GBM_ERR_TIF_PHOTO_Y_Cb_Cr:
  1513.             return "PhotometricInterpreation tag is Y-Cb-Cr colour space, not supported";
  1514.         case GBM_ERR_TIF_PHOTO:
  1515.             return "PhotometricInterpretation tag unsupported/bad";
  1516.         case GBM_ERR_TIF_FILLORDER:
  1517.             return "FillOrder tag must be 1";
  1518.         case GBM_ERR_TIF_PLANARCONFIG_1:
  1519.             return "PlanarConfiguration tag must be 1 for non RGB files";
  1520.         case GBM_ERR_TIF_PLANARCONFIG_12:
  1521.             return "PlanarConfiguration tag must be 1 or 2 for RGB files";
  1522.         case GBM_ERR_TIF_INKSET:
  1523.             return "InkSet tag indicates non-CMYK colour seperations";
  1524.         case GBM_ERR_TIF_ORIENT:
  1525.             return "Orientation tag must be 1 or 4";
  1526.         case GBM_ERR_TIF_INDEX:
  1527.             return "less bitmaps in file than index requested";
  1528.         }
  1529.     return NULL;
  1530.     }
  1531. /*...e*/
  1532.