home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 February / PCWorld_2002-02_cd.bin / Software / Vyzkuste / pdflib / pdflib-4.0.1.sit / pdflib-4.0.1 / tiff / tif_dirread.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-07-04  |  38.1 KB  |  1,381 lines  |  [TEXT/CWIE]

  1. /*
  2.  * Copyright (c) 1988-1997 Sam Leffler
  3.  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
  4.  *
  5.  * Permission to use, copy, modify, distribute, and sell this software and 
  6.  * its documentation for any purpose is hereby granted without fee, provided
  7.  * that (i) the above copyright notices and this permission notice appear in
  8.  * all copies of the software and related documentation, and (ii) the names of
  9.  * Sam Leffler and Silicon Graphics may not be used in any advertising or
  10.  * publicity relating to the software without the specific, prior written
  11.  * permission of Sam Leffler and Silicon Graphics.
  12.  * 
  13.  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
  14.  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
  15.  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
  16.  * 
  17.  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  18.  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  19.  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  20.  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
  21.  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  22.  * OF THIS SOFTWARE.
  23.  */
  24.  
  25. /*
  26.  * TIFF Library.
  27.  *
  28.  * Directory Read Support Routines.
  29.  */
  30.  
  31. /* $Id: tif_dirread.c,v 1.5 2001/04/01 11:37:53 tm Exp $ */
  32.  
  33. #include "tiffiop.h"
  34.  
  35. #define    IGNORE    0        /* tag placeholder used below */
  36.  
  37. #if HAVE_IEEEFP
  38. #define    TIFFCvtIEEEFloatToNative(tif, n, fp)
  39. #define    TIFFCvtIEEEDoubleToNative(tif, n, dp)
  40. #else
  41. extern    void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*);
  42. extern    void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*);
  43. #endif
  44.  
  45. static    void EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16);
  46. static    void MissingRequired(TIFF*, const char*);
  47. static    int CheckDirCount(TIFF*, TIFFDirEntry*, uint32);
  48. static    tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*);
  49. static    tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*);
  50. static    float TIFFFetchRational(TIFF*, TIFFDirEntry*);
  51. static    int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*);
  52. static    int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, int*);
  53. static    int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*);
  54. static    int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*);
  55. static    int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**);
  56. static    int TIFFFetchExtraSamples(TIFF*, TIFFDirEntry*);
  57. static    int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*);
  58. static    float TIFFFetchFloat(TIFF*, TIFFDirEntry*);
  59. static    int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*);
  60. static    int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*);
  61. static    int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*);
  62. static    int TIFFFetchShortPair(TIFF*, TIFFDirEntry*);
  63. static    void ChopUpSingleUncompressedStrip(TIFF*);
  64.  
  65. static char *
  66. CheckMalloc(TIFF* tif, tsize_t n, const char* what)
  67. {
  68.     char *cp = (char*)_TIFFmalloc(tif, n);
  69.     if (cp == NULL)
  70.         TIFFError(tif->tif_name, "No space %s", what);
  71.     return (cp);
  72. }
  73.  
  74. /*
  75.  * Read the next TIFF directory from a file
  76.  * and convert it to the internal format.
  77.  * We read directories sequentially.
  78.  */
  79. int
  80. TIFFReadDirectory(TIFF* tif)
  81. {
  82.     register TIFFDirEntry* dp;
  83.     register int n;
  84.     register TIFFDirectory* td;
  85.     TIFFDirEntry* dir;
  86.     int iv;
  87.     long v;
  88.     double dv;
  89.     const TIFFFieldInfo* fip;
  90.     int fix;
  91.     uint16 dircount;
  92.     toff_t nextdiroff;
  93.     char* cp;
  94.     int diroutoforderwarning = 0;
  95.  
  96.     tif->tif_diroff = tif->tif_nextdiroff;
  97.     if (tif->tif_diroff == 0)        /* no more directories */
  98.         return (0);
  99.     /*
  100.      * Cleanup any previous compression state.
  101.      */
  102.     (*tif->tif_cleanup)(tif);
  103.     tif->tif_curdir++;
  104.     nextdiroff = 0;
  105.     if (!isMapped(tif)) {
  106.         if (!SeekOK(tif, tif->tif_diroff)) {
  107.             TIFFError(tif->tif_name,
  108.                 "Seek error accessing TIFF directory");
  109.             return (0);
  110.         }
  111.         if (!ReadOK(tif, &dircount, sizeof (uint16))) {
  112.             TIFFError(tif->tif_name,
  113.                 "Can not read TIFF directory count");
  114.             return (0);
  115.         }
  116.         if (tif->tif_flags & TIFF_SWAB)
  117.             TIFFSwabShort(&dircount);
  118.         dir = (TIFFDirEntry *)CheckMalloc(tif,
  119.             dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
  120.         if (dir == NULL)
  121.             return (0);
  122.         if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) {
  123.             TIFFError(tif->tif_name, "Can not read TIFF directory");
  124.             goto bad;
  125.         }
  126.         /*
  127.          * Read offset to next directory for sequential scans.
  128.          */
  129.         /* PDFlib GmbH: this generates an unnecessary warning.
  130.         (void) ReadOK(tif, &nextdiroff, sizeof (uint32));
  131.         */
  132.         TIFFReadFile(tif, (tdata_t) &nextdiroff,
  133.             (tsize_t)(sizeof(uint32)));
  134.     } else {
  135.         toff_t off = tif->tif_diroff;
  136.  
  137.         if (off + sizeof (uint16) > tif->tif_size) {
  138.             TIFFError(tif->tif_name,
  139.                 "Can not read TIFF directory count");
  140.             return (0);
  141.         } else
  142.             _TIFFmemcpy(&dircount,tif->tif_base + off, sizeof(uint16));
  143.         off += sizeof (uint16);
  144.         if (tif->tif_flags & TIFF_SWAB)
  145.             TIFFSwabShort(&dircount);
  146.         dir = (TIFFDirEntry *)CheckMalloc(tif,
  147.             dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
  148.         if (dir == NULL)
  149.             return (0);
  150.         if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) {
  151.             TIFFError(tif->tif_name, "Can not read TIFF directory");
  152.             goto bad;
  153.         } else
  154.             _TIFFmemcpy(dir, tif->tif_base + off,
  155.                 dircount*sizeof (TIFFDirEntry));
  156.         off += dircount* sizeof (TIFFDirEntry);
  157.         if (off + sizeof (uint32) <= tif->tif_size)
  158.             _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof(uint32));
  159.     }
  160.     if (tif->tif_flags & TIFF_SWAB)
  161.         TIFFSwabLong(&nextdiroff);
  162.     tif->tif_nextdiroff = nextdiroff;
  163.  
  164.     tif->tif_flags &= ~TIFF_BEENWRITING;    /* reset before new dir */
  165.     /*
  166.      * Setup default value and then make a pass over
  167.      * the fields to check type and tag information,
  168.      * and to extract info required to size data
  169.      * structures.  A second pass is made afterwards
  170.      * to read in everthing not taken in the first pass.
  171.      */
  172.     td = &tif->tif_dir;
  173.     /* free any old stuff and reinit */
  174.     TIFFFreeDirectory(tif);
  175.     TIFFDefaultDirectory(tif);
  176.     /*
  177.      * Electronic Arts writes gray-scale TIFF files
  178.      * without a PlanarConfiguration directory entry.
  179.      * Thus we setup a default value here, even though
  180.      * the TIFF spec says there is no default value.
  181.      */
  182.     TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  183.  
  184.     /*
  185.      * Sigh, we must make a separate pass through the
  186.      * directory for the following reason:
  187.      *
  188.      * We must process the Compression tag in the first pass
  189.      * in order to merge in codec-private tag definitions (otherwise
  190.      * we may get complaints about unknown tags).  However, the
  191.      * Compression tag may be dependent on the SamplesPerPixel
  192.      * tag value because older TIFF specs permited Compression
  193.      * to be written as a SamplesPerPixel-count tag entry.
  194.      * Thus if we don't first figure out the correct SamplesPerPixel
  195.      * tag value then we may end up ignoring the Compression tag
  196.      * value because it has an incorrect count value (if the
  197.      * true value of SamplesPerPixel is not 1).
  198.      *
  199.      * It sure would have been nice if Aldus had really thought
  200.      * this stuff through carefully.
  201.      */ 
  202.     for (dp = dir, n = dircount; n > 0; n--, dp++) {
  203.         if (tif->tif_flags & TIFF_SWAB) {
  204.             TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
  205.             TIFFSwabArrayOfLong(&dp->tdir_count, 2);
  206.         }
  207.         if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) {
  208.             if (!TIFFFetchNormalTag(tif, dp))
  209.                 goto bad;
  210.             dp->tdir_tag = IGNORE;
  211.         }
  212.     }
  213.     /*
  214.      * First real pass over the directory.
  215.      */
  216.     fix = 0;
  217.     for (dp = dir, n = dircount; n > 0; n--, dp++) {
  218.  
  219.                 /*
  220.                  * Find the field information entry for this tag.
  221.          * Added check for tags to ignore ... [BFC]
  222.                  */
  223.         if( TIFFReassignTagToIgnore(TIS_EXTRACT, dp->tdir_tag) )
  224.                     dp->tdir_tag = IGNORE;
  225.  
  226.         if (dp->tdir_tag == IGNORE)
  227.                     continue;
  228.                 
  229.         /*
  230.          * Silicon Beach (at least) writes unordered
  231.          * directory tags (violating the spec).  Handle
  232.          * it here, but be obnoxious (maybe they'll fix it?).
  233.          */
  234.         if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) {
  235.             if (!diroutoforderwarning) {
  236.                 TIFFWarning(tif->tif_name,
  237.     "invalid TIFF directory; tags are not sorted in ascending order");
  238.                 diroutoforderwarning = 1;
  239.             }
  240.             fix = 0;            /* O(n^2) */
  241.         }
  242.         while (fix < tif->tif_nfields &&
  243.             tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag)
  244.             fix++;
  245.         if (fix == tif->tif_nfields ||
  246.             tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) {
  247.             TIFFWarning(tif->tif_name,
  248.                 "unknown field with tag %d (0x%x) ignored",
  249.                 dp->tdir_tag,  dp->tdir_tag);
  250.             dp->tdir_tag = IGNORE;
  251.             fix = 0;            /* restart search */
  252.             continue;
  253.         }
  254.         /*
  255.          * Null out old tags that we ignore.
  256.          */
  257.         if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) {
  258.     ignore:
  259.             dp->tdir_tag = IGNORE;
  260.             continue;
  261.         }
  262.         /*
  263.          * Check data type.
  264.          */
  265.         fip = tif->tif_fieldinfo[fix];
  266.         while (dp->tdir_type != (u_short) fip->field_type) {
  267.             if (fip->field_type == TIFF_ANY)    /* wildcard */
  268.                 break;
  269.             fip++, fix++;
  270.             if (fix == tif->tif_nfields ||
  271.                 fip->field_tag != dp->tdir_tag) {
  272.                 TIFFWarning(tif->tif_name,
  273.                    "wrong data type %d for \"%s\"; tag ignored",
  274.                     dp->tdir_type, fip[-1].field_name);
  275.                 goto ignore;
  276.             }
  277.         }
  278.         /*
  279.          * Check count if known in advance.
  280.          */
  281.         if (fip->field_readcount != TIFF_VARIABLE) {
  282.             uint32 expected = (fip->field_readcount == TIFF_SPP) ?
  283.                 (uint32) td->td_samplesperpixel :
  284.                 (uint32) fip->field_readcount;
  285.             if (!CheckDirCount(tif, dp, expected))
  286.                 goto ignore;
  287.         }
  288.  
  289.         switch (dp->tdir_tag) {
  290.         case TIFFTAG_COMPRESSION:
  291.             /*
  292.              * The 5.0 spec says the Compression tag has
  293.              * one value, while earlier specs say it has
  294.              * one value per sample.  Because of this, we
  295.              * accept the tag if one value is supplied.
  296.              */
  297.             if (dp->tdir_count == 1) {
  298.                 v = TIFFExtractData(tif,
  299.                     dp->tdir_type, dp->tdir_offset);
  300.                 if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
  301.                     goto bad;
  302.                 break;
  303.             }
  304.             if (!TIFFFetchPerSampleShorts(tif, dp, &iv) ||
  305.                 !TIFFSetField(tif, dp->tdir_tag, iv))
  306.                 goto bad;
  307.             dp->tdir_tag = IGNORE;
  308.             break;
  309.         case TIFFTAG_STRIPOFFSETS:
  310.         case TIFFTAG_STRIPBYTECOUNTS:
  311.         case TIFFTAG_TILEOFFSETS:
  312.         case TIFFTAG_TILEBYTECOUNTS:
  313.             TIFFSetFieldBit(tif, fip->field_bit);
  314.             break;
  315.         case TIFFTAG_IMAGEWIDTH:
  316.         case TIFFTAG_IMAGELENGTH:
  317.         case TIFFTAG_IMAGEDEPTH:
  318.         case TIFFTAG_TILELENGTH:
  319.         case TIFFTAG_TILEWIDTH:
  320.         case TIFFTAG_TILEDEPTH:
  321.         case TIFFTAG_PLANARCONFIG:
  322.         case TIFFTAG_ROWSPERSTRIP:
  323.             if (!TIFFFetchNormalTag(tif, dp))
  324.                 goto bad;
  325.             dp->tdir_tag = IGNORE;
  326.             break;
  327.         case TIFFTAG_EXTRASAMPLES:
  328.             (void) TIFFFetchExtraSamples(tif, dp);
  329.             dp->tdir_tag = IGNORE;
  330.             break;
  331.         }
  332.     }
  333.  
  334.     /*
  335.      * Allocate directory structure and setup defaults.
  336.      */
  337.     if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
  338.         MissingRequired(tif, "ImageLength");
  339.         goto bad;
  340.     }
  341.     if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
  342.         MissingRequired(tif, "PlanarConfiguration");
  343.         goto bad;
  344.     }
  345.     /* 
  346.       * Setup appropriate structures (by strip or by tile)
  347.      */
  348.     if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
  349.         td->td_nstrips = TIFFNumberOfStrips(tif);
  350.         td->td_tilewidth = td->td_imagewidth;
  351.         td->td_tilelength = td->td_rowsperstrip;
  352.         td->td_tiledepth = td->td_imagedepth;
  353.         tif->tif_flags &= ~TIFF_ISTILED;
  354.     } else {
  355.         td->td_nstrips = TIFFNumberOfTiles(tif);
  356.         tif->tif_flags |= TIFF_ISTILED;
  357.     }
  358.     td->td_stripsperimage = td->td_nstrips;
  359.     if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
  360.         td->td_stripsperimage /= td->td_samplesperpixel;
  361.     if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
  362.         MissingRequired(tif,
  363.             isTiled(tif) ? "TileOffsets" : "StripOffsets");
  364.         goto bad;
  365.     }
  366.  
  367.     /*
  368.      * Second pass: extract other information.
  369.      */
  370.     for (dp = dir, n = dircount; n > 0; n--, dp++) {
  371.         if (dp->tdir_tag == IGNORE)
  372.             continue;
  373.         switch (dp->tdir_tag) {
  374.         case TIFFTAG_MINSAMPLEVALUE:
  375.         case TIFFTAG_MAXSAMPLEVALUE:
  376.         case TIFFTAG_BITSPERSAMPLE:
  377.             /*
  378.              * The 5.0 spec says the Compression tag has
  379.              * one value, while earlier specs say it has
  380.              * one value per sample.  Because of this, we
  381.              * accept the tag if one value is supplied.
  382.              *
  383.              * The MinSampleValue, MaxSampleValue and
  384.              * BitsPerSample tags are supposed to be written
  385.              * as one value/sample, but some vendors incorrectly
  386.              * write one value only -- so we accept that
  387.              * as well (yech).
  388.              */
  389.             if (dp->tdir_count == 1) {
  390.                 v = TIFFExtractData(tif,
  391.                     dp->tdir_type, dp->tdir_offset);
  392.                 if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
  393.                     goto bad;
  394.                 break;
  395.             }
  396.             /* fall thru... */
  397.         case TIFFTAG_DATATYPE:
  398.         case TIFFTAG_SAMPLEFORMAT:
  399.             if (!TIFFFetchPerSampleShorts(tif, dp, &iv) ||
  400.                 !TIFFSetField(tif, dp->tdir_tag, iv))
  401.                 goto bad;
  402.             break;
  403.         case TIFFTAG_SMINSAMPLEVALUE:
  404.         case TIFFTAG_SMAXSAMPLEVALUE:
  405.             if (!TIFFFetchPerSampleAnys(tif, dp, &dv) ||
  406.                 !TIFFSetField(tif, dp->tdir_tag, dv))
  407.                 goto bad;
  408.             break;
  409.         case TIFFTAG_STRIPOFFSETS:
  410.         case TIFFTAG_TILEOFFSETS:
  411.             if (!TIFFFetchStripThing(tif, dp,
  412.                 td->td_nstrips, &td->td_stripoffset))
  413.                 goto bad;
  414.             break;
  415.         case TIFFTAG_STRIPBYTECOUNTS:
  416.         case TIFFTAG_TILEBYTECOUNTS:
  417.             if (!TIFFFetchStripThing(tif, dp,
  418.                 td->td_nstrips, &td->td_stripbytecount))
  419.                 goto bad;
  420.             break;
  421.         case TIFFTAG_COLORMAP:
  422.         case TIFFTAG_TRANSFERFUNCTION:
  423.             /*
  424.              * TransferFunction can have either 1x or 3x data
  425.              * values; Colormap can have only 3x items.
  426.              */
  427.             v = 1L<<td->td_bitspersample;
  428.             if (dp->tdir_tag == TIFFTAG_COLORMAP ||
  429.                 dp->tdir_count != (uint32) v) {
  430.                 if (!CheckDirCount(tif, dp, (uint32)(3*v)))
  431.                     break;
  432.             }
  433.             v *= sizeof (uint16);
  434.             cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16),
  435.                 "to read \"TransferFunction\" tag");
  436.             if (cp != NULL) {
  437.                 if (TIFFFetchData(tif, dp, cp)) {
  438.                     /*
  439.                      * This deals with there being only
  440.                      * one array to apply to all samples.
  441.                      */
  442.                     uint32 c =
  443.                         (uint32)1 << td->td_bitspersample;
  444.                     if (dp->tdir_count == c)
  445.                         v = 0;
  446.                     TIFFSetField(tif, dp->tdir_tag,
  447.                         cp, cp+v, cp+2*v);
  448.                 }
  449.                 _TIFFfree(tif, cp);
  450.             }
  451.             break;
  452.         case TIFFTAG_PAGENUMBER:
  453.         case TIFFTAG_HALFTONEHINTS:
  454.         case TIFFTAG_YCBCRSUBSAMPLING:
  455.         case TIFFTAG_DOTRANGE:
  456.             (void) TIFFFetchShortPair(tif, dp);
  457.             break;
  458. #ifdef COLORIMETRY_SUPPORT
  459.         case TIFFTAG_REFERENCEBLACKWHITE:
  460.             (void) TIFFFetchRefBlackWhite(tif, dp);
  461.             break;
  462. #endif
  463. /* BEGIN REV 4.0 COMPATIBILITY */
  464.         case TIFFTAG_OSUBFILETYPE:
  465.             v = 0;
  466.             switch (TIFFExtractData(tif, dp->tdir_type,
  467.                 dp->tdir_offset)) {
  468.             case OFILETYPE_REDUCEDIMAGE:
  469.                 v = FILETYPE_REDUCEDIMAGE;
  470.                 break;
  471.             case OFILETYPE_PAGE:
  472.                 v = FILETYPE_PAGE;
  473.                 break;
  474.             }
  475.             if (v)
  476.                 (void) TIFFSetField(tif,
  477.                     TIFFTAG_SUBFILETYPE, (int)v);
  478.             break;
  479. /* END REV 4.0 COMPATIBILITY */
  480.         default:
  481.             (void) TIFFFetchNormalTag(tif, dp);
  482.             break;
  483.         }
  484.     }
  485.     /*
  486.      * Verify Palette image has a Colormap.
  487.      */
  488.     if (td->td_photometric == PHOTOMETRIC_PALETTE &&
  489.         !TIFFFieldSet(tif, FIELD_COLORMAP)) {
  490.         MissingRequired(tif, "Colormap");
  491.         goto bad;
  492.     }
  493.     /*
  494.      * Attempt to deal with a missing StripByteCounts tag.
  495.      */
  496.     if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
  497.         /*
  498.          * Some manufacturers violate the spec by not giving
  499.          * the size of the strips.  In this case, assume there
  500.          * is one uncompressed strip of data.
  501.          */
  502.         if ((td->td_planarconfig == PLANARCONFIG_CONTIG &&
  503.             td->td_nstrips > 1) ||
  504.             (td->td_planarconfig == PLANARCONFIG_SEPARATE &&
  505.              td->td_nstrips != td->td_samplesperpixel)) {
  506.             MissingRequired(tif, "StripByteCounts");
  507.             goto bad;
  508.         }
  509.         TIFFWarning(tif->tif_name,
  510. "TIFF directory is missing required \"%s\" field, calculating from imagelength",
  511.             _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
  512.         EstimateStripByteCounts(tif, dir, dircount);
  513. #define    BYTECOUNTLOOKSBAD \
  514.     ((td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \
  515.     (td->td_compression == COMPRESSION_NONE && \
  516.      td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]))
  517.     } else if (td->td_nstrips == 1 && BYTECOUNTLOOKSBAD) {
  518.         /*
  519.          * Plexus (and others) sometimes give a value
  520.          * of zero for a tag when they don't know what
  521.          * the correct value is!  Try and handle the
  522.          * simple case of estimating the size of a one
  523.          * strip image.
  524.          */
  525.         TIFFWarning(tif->tif_name,
  526.         "Bogus \"%s\" field, ignoring and calculating from imagelength",
  527.             _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
  528.         EstimateStripByteCounts(tif, dir, dircount);
  529.     }
  530.     if (dir)
  531.         _TIFFfree(tif, (char *)dir);
  532.     if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
  533.         td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1);
  534.     /*
  535.      * Setup default compression scheme.
  536.      */
  537.     if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
  538.         TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  539.         /*
  540.          * Some manufacturers make life difficult by writing
  541.      * large amounts of uncompressed data as a single strip.
  542.      * This is contrary to the recommendations of the spec.
  543.          * The following makes an attempt at breaking such images
  544.      * into strips closer to the recommended 8k bytes.  A
  545.      * side effect, however, is that the RowsPerStrip tag
  546.      * value may be changed.
  547.          */
  548.     if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE &&
  549.         (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP)
  550.         ChopUpSingleUncompressedStrip(tif);
  551.     /*
  552.      * Reinitialize i/o since we are starting on a new directory.
  553.      */
  554.     tif->tif_row = (uint32) -1;
  555.     tif->tif_curstrip = (tstrip_t) -1;
  556.     tif->tif_col = (uint32) -1;
  557.     tif->tif_curtile = (ttile_t) -1;
  558.     tif->tif_tilesize = TIFFTileSize(tif);
  559.     tif->tif_scanlinesize = TIFFScanlineSize(tif);
  560.     return (1);
  561. bad:
  562.     if (dir)
  563.         _TIFFfree(tif, dir);
  564.     return (0);
  565. }
  566.  
  567. static void
  568. EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
  569. {
  570.     register TIFFDirEntry *dp;
  571.     register TIFFDirectory *td = &tif->tif_dir;
  572.     uint16 i;
  573.  
  574.     if (td->td_stripbytecount)
  575.         _TIFFfree(tif, td->td_stripbytecount);
  576.     td->td_stripbytecount = (uint32*)
  577.         CheckMalloc(tif, td->td_nstrips * sizeof (uint32),
  578.         "for \"StripByteCounts\" array");
  579.     if (td->td_compression != COMPRESSION_NONE) {
  580.         uint32 space = (uint32)(sizeof (TIFFHeader)
  581.             + sizeof (uint16)
  582.             + (dircount * sizeof (TIFFDirEntry))
  583.             + sizeof (uint32));
  584.         toff_t filesize = TIFFGetFileSize(tif);
  585.         uint16 n;
  586.  
  587.         /* calculate amount of space used by indirect values */
  588.         for (dp = dir, n = dircount; n > 0; n--, dp++) {
  589.             uint32 cc = dp->tdir_count*tiffDataWidth[dp->tdir_type];
  590.             if (cc > sizeof (uint32))
  591.                 space += cc;
  592.         }
  593.         space = filesize - space;
  594.         if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
  595.             space /= td->td_samplesperpixel;
  596.         for (i = 0; i < td->td_nstrips; i++)
  597.             td->td_stripbytecount[i] = space;
  598.         /*
  599.          * This gross hack handles the case were the offset to
  600.          * the last strip is past the place where we think the strip
  601.          * should begin.  Since a strip of data must be contiguous,
  602.          * it's safe to assume that we've overestimated the amount
  603.          * of data in the strip and trim this number back accordingly.
  604.          */ 
  605.         i--;
  606.         if (((toff_t)(td->td_stripoffset[i]+td->td_stripbytecount[i]))
  607.                                                                > filesize)
  608.             td->td_stripbytecount[i] =
  609.                 filesize - td->td_stripoffset[i];
  610.     } else {
  611.         uint32 rowbytes = TIFFScanlineSize(tif);
  612.         uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage;
  613.         for (i = 0; i < td->td_nstrips; i++)
  614.             td->td_stripbytecount[i] = rowbytes*rowsperstrip;
  615.     }
  616.     TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
  617.     if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
  618.         td->td_rowsperstrip = td->td_imagelength;
  619. }
  620.  
  621. static void
  622. MissingRequired(TIFF* tif, const char* tagname)
  623. {
  624.     TIFFError(tif->tif_name,
  625.         "TIFF directory is missing required \"%s\" field", tagname);
  626. }
  627.  
  628. /*
  629.  * Check the count field of a directory
  630.  * entry against a known value.  The caller
  631.  * is expected to skip/ignore the tag if
  632.  * there is a mismatch.
  633.  */
  634. static int
  635. CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count)
  636. {
  637.     if (count != dir->tdir_count) {
  638.         TIFFWarning(tif->tif_name,
  639.     "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored",
  640.             _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name,
  641.             dir->tdir_count, count);
  642.         return (0);
  643.     }
  644.     return (1);
  645. }
  646.  
  647. /*
  648.  * Fetch a contiguous directory item.
  649.  */
  650. static tsize_t
  651. TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp)
  652. {
  653.     int w = tiffDataWidth[dir->tdir_type];
  654.     tsize_t cc = dir->tdir_count * w;
  655.  
  656.     if (!isMapped(tif)) {
  657.         if (!SeekOK(tif, dir->tdir_offset))
  658.             goto bad;
  659.         if (!ReadOK(tif, cp, cc))
  660.             goto bad;
  661.     } else {
  662.         if (dir->tdir_offset + cc > tif->tif_size)
  663.             goto bad;
  664.         _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc);
  665.     }
  666.     if (tif->tif_flags & TIFF_SWAB) {
  667.         switch (dir->tdir_type) {
  668.         case TIFF_SHORT:
  669.         case TIFF_SSHORT:
  670.             TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count);
  671.             break;
  672.         case TIFF_LONG:
  673.         case TIFF_SLONG:
  674.         case TIFF_FLOAT:
  675.             TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count);
  676.             break;
  677.         case TIFF_RATIONAL:
  678.         case TIFF_SRATIONAL:
  679.             TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count);
  680.             break;
  681.         case TIFF_DOUBLE:
  682.             TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count);
  683.             break;
  684.         }
  685.     }
  686.     return (cc);
  687. bad:
  688.     TIFFError(tif->tif_name, "Error fetching data for field \"%s\"",
  689.         _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
  690.     return ((tsize_t) 0);
  691. }
  692.  
  693. /*
  694.  * Fetch an ASCII item from the file.
  695.  */
  696. static tsize_t
  697. TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp)
  698. {
  699.     if (dir->tdir_count <= 4) {
  700.         uint32 l = dir->tdir_offset;
  701.         if (tif->tif_flags & TIFF_SWAB)
  702.             TIFFSwabLong(&l);
  703.         _TIFFmemcpy(cp, &l, dir->tdir_count);
  704.         return (1);
  705.     }
  706.     return (TIFFFetchData(tif, dir, cp));
  707. }
  708.  
  709. /*
  710.  * Convert numerator+denominator to float.
  711.  */
  712. static int
  713. cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv)
  714. {
  715.     if (denom == 0) {
  716.         TIFFError(tif->tif_name,
  717.             "%s: Rational with zero denominator (num = %lu)",
  718.             _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num);
  719.         return (0);
  720.     } else {
  721.         if (dir->tdir_type == TIFF_RATIONAL)
  722.             *rv = ((float)num / (float)denom);
  723.         else
  724.             *rv = ((float)(int32)num / (float)(int32)denom);
  725.         return (1);
  726.     }
  727. }
  728.  
  729. /*
  730.  * Fetch a rational item from the file
  731.  * at offset off and return the value
  732.  * as a floating point number.
  733.  */
  734. static float
  735. TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir)
  736. {
  737.     uint32 l[2];
  738.     float v;
  739.  
  740.     return (!TIFFFetchData(tif, dir, (char *)l) ||
  741.         !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v);
  742. }
  743.  
  744. /*
  745.  * Fetch a single floating point value
  746.  * from the offset field and return it
  747.  * as a native float.
  748.  */
  749. static float
  750. TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir)
  751. {
  752.     long l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset);
  753.     float v = *(float*) &l;
  754.     TIFFCvtIEEEFloatToNative(tif, 1, &v);
  755.     return (v);
  756. }
  757.  
  758. /*
  759.  * Fetch an array of BYTE or SBYTE values.
  760.  */
  761. static int
  762. TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint16* v)
  763. {
  764.     if (dir->tdir_count <= 4) {
  765.         /*
  766.          * Extract data from offset field.
  767.          */
  768.         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  769.             switch (dir->tdir_count) {
  770.                 case 4: v[3] = (uint16)(dir->tdir_offset & 0xff);
  771.                 case 3: v[2] = (uint16)((dir->tdir_offset >> 8) & 0xff);
  772.                 case 2: v[1] = (uint16)((dir->tdir_offset >> 16) & 0xff);
  773.                 case 1: v[0] = (uint16)(dir->tdir_offset >> 24);
  774.             }
  775.         } else {
  776.             switch (dir->tdir_count) {
  777.                 case 4: v[3] = (uint16)(dir->tdir_offset >> 24);
  778.                 case 3: v[2] = (uint16)((dir->tdir_offset >> 16) & 0xff);
  779.                 case 2: v[1] = (uint16)((dir->tdir_offset >> 8) & 0xff);
  780.                 case 1: v[0] = (uint16)(dir->tdir_offset & 0xff);
  781.             }
  782.         }
  783.         return (1);
  784.     } else
  785.         return (TIFFFetchData(tif, dir, (char*) v) != 0);    /* XXX */
  786. }
  787.  
  788. /*
  789.  * Fetch an array of SHORT or SSHORT values.
  790.  */
  791. static int
  792. TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v)
  793. {
  794.     if (dir->tdir_count <= 2) {
  795.         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  796.             switch (dir->tdir_count) {
  797.             case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff);
  798.             case 1: v[0] = (uint16) (dir->tdir_offset >> 16);
  799.             }
  800.         } else {
  801.             switch (dir->tdir_count) {
  802.             case 2: v[1] = (uint16) (dir->tdir_offset >> 16);
  803.             case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff);
  804.             }
  805.         }
  806.         return (1);
  807.     } else
  808.         return (TIFFFetchData(tif, dir, (char *)v) != 0);
  809. }
  810.  
  811. /*
  812.  * Fetch a pair of SHORT or BYTE values.
  813.  */
  814. static int
  815. TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir)
  816. {
  817.     uint16 v[2];
  818.     int ok = 0;
  819.  
  820.     switch (dir->tdir_type) {
  821.     case TIFF_SHORT:
  822.     case TIFF_SSHORT:
  823.         ok = TIFFFetchShortArray(tif, dir, v);
  824.         break;
  825.     case TIFF_BYTE:
  826.     case TIFF_SBYTE:
  827.         ok  = TIFFFetchByteArray(tif, dir, v);
  828.         break;
  829.     }
  830.     if (ok)
  831.         TIFFSetField(tif, dir->tdir_tag, v[0], v[1]);
  832.     return (ok);
  833. }
  834.  
  835. /*
  836.  * Fetch an array of LONG or SLONG values.
  837.  */
  838. static int
  839. TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v)
  840. {
  841.     if (dir->tdir_count == 1) {
  842.         v[0] = dir->tdir_offset;
  843.         return (1);
  844.     } else
  845.         return (TIFFFetchData(tif, dir, (char*) v) != 0);
  846. }
  847.  
  848. /*
  849.  * Fetch an array of RATIONAL or SRATIONAL values.
  850.  */
  851. static int
  852. TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v)
  853. {
  854.     int ok = 0;
  855.     uint32* l;
  856.  
  857.     l = (uint32*)CheckMalloc(tif,
  858.         dir->tdir_count*tiffDataWidth[dir->tdir_type],
  859.         "to fetch array of rationals");
  860.     if (l) {
  861.         if (TIFFFetchData(tif, dir, (char *)l)) {
  862.             uint32 i;
  863.             for (i = 0; i < dir->tdir_count; i++) {
  864.                 ok = cvtRational(tif, dir,
  865.                     l[2*i+0], l[2*i+1], &v[i]);
  866.                 if (!ok)
  867.                     break;
  868.             }
  869.         }
  870.         _TIFFfree(tif, (char *)l);
  871.     }
  872.     return (ok);
  873. }
  874.  
  875. /*
  876.  * Fetch an array of FLOAT values.
  877.  */
  878. static int
  879. TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v)
  880. {
  881.  
  882.     if (dir->tdir_count == 1) {
  883.         v[0] = *(float*) &dir->tdir_offset;
  884.         TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v);
  885.         return (1);
  886.     } else    if (TIFFFetchData(tif, dir, (char*) v)) {
  887.         TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v);
  888.         return (1);
  889.     } else
  890.         return (0);
  891. }
  892.  
  893. /*
  894.  * Fetch an array of DOUBLE values.
  895.  */
  896. static int
  897. TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v)
  898. {
  899.     if (TIFFFetchData(tif, dir, (char*) v)) {
  900.         TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v);
  901.         return (1);
  902.     } else
  903.         return (0);
  904. }
  905.  
  906. /*
  907.  * Fetch an array of ANY values.  The actual values are
  908.  * returned as doubles which should be able hold all the
  909.  * types.  Yes, there really should be an tany_t to avoid
  910.  * this potential non-portability ...  Note in particular
  911.  * that we assume that the double return value vector is
  912.  * large enough to read in any fundamental type.  We use
  913.  * that vector as a buffer to read in the base type vector
  914.  * and then convert it in place to double (from end
  915.  * to front of course).
  916.  */
  917. static int
  918. TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v)
  919. {
  920.     int i;
  921.  
  922.     switch (dir->tdir_type) {
  923.     case TIFF_BYTE:
  924.     case TIFF_SBYTE:
  925.         if (!TIFFFetchByteArray(tif, dir, (uint16*) v))
  926.             return (0);
  927.         if (dir->tdir_type == TIFF_BYTE) {
  928.             uint16* vp = (uint16*) v;
  929.             for (i = dir->tdir_count-1; i >= 0; i--)
  930.                 v[i] = vp[i];
  931.         } else {
  932.             int16* vp = (int16*) v;
  933.             for (i = dir->tdir_count-1; i >= 0; i--)
  934.                 v[i] = vp[i];
  935.         }
  936.         break;
  937.     case TIFF_SHORT:
  938.     case TIFF_SSHORT:
  939.         if (!TIFFFetchShortArray(tif, dir, (uint16*) v))
  940.             return (0);
  941.         if (dir->tdir_type == TIFF_SHORT) {
  942.             uint16* vp = (uint16*) v;
  943.             for (i = dir->tdir_count-1; i >= 0; i--)
  944.                 v[i] = vp[i];
  945.         } else {
  946.             int16* vp = (int16*) v;
  947.             for (i = dir->tdir_count-1; i >= 0; i--)
  948.                 v[i] = vp[i];
  949.         }
  950.         break;
  951.     case TIFF_LONG:
  952.     case TIFF_SLONG:
  953.         if (!TIFFFetchLongArray(tif, dir, (uint32*) v))
  954.             return (0);
  955.         if (dir->tdir_type == TIFF_LONG) {
  956.             uint32* vp = (uint32*) v;
  957.             for (i = dir->tdir_count-1; i >= 0; i--)
  958.                 v[i] = vp[i];
  959.         } else {
  960.             int32* vp = (int32*) v;
  961.             for (i = dir->tdir_count-1; i >= 0; i--)
  962.                 v[i] = vp[i];
  963.         }
  964.         break;
  965.     case TIFF_RATIONAL:
  966.     case TIFF_SRATIONAL:
  967.         if (!TIFFFetchRationalArray(tif, dir, (float*) v))
  968.             return (0);
  969.         { float* vp = (float*) v;
  970.           for (i = dir->tdir_count-1; i >= 0; i--)
  971.             v[i] = vp[i];
  972.         }
  973.         break;
  974.     case TIFF_FLOAT:
  975.         if (!TIFFFetchFloatArray(tif, dir, (float*) v))
  976.             return (0);
  977.         { float* vp = (float*) v;
  978.           for (i = dir->tdir_count-1; i >= 0; i--)
  979.             v[i] = vp[i];
  980.         }
  981.         break;
  982.     case TIFF_DOUBLE:
  983.         return (TIFFFetchDoubleArray(tif, dir, (double*) v));
  984.     default:
  985.         /* TIFF_NOTYPE */
  986.         /* TIFF_ASCII */
  987.         /* TIFF_UNDEFINED */
  988.         TIFFError(tif->tif_name,
  989.             "Cannot read TIFF_ANY type %d for field \"%s\"",
  990.             _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
  991.         return (0);
  992.     }
  993.     return (1);
  994. }
  995.  
  996. /*
  997.  * Fetch a tag that is not handled by special case code.
  998.  */
  999. static int
  1000. TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp)
  1001. {
  1002.     static const char mesg[] = "to fetch tag value";
  1003.     int ok = 0;
  1004.     const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag);
  1005.  
  1006.     if (dp->tdir_count > 1) {        /* array of values */
  1007.         char* cp = NULL;
  1008.  
  1009.         switch (dp->tdir_type) {
  1010.         case TIFF_BYTE:
  1011.         case TIFF_SBYTE:
  1012.             /* NB: always expand BYTE values to shorts */
  1013.             cp = CheckMalloc(tif,
  1014.                 dp->tdir_count * sizeof (uint16), mesg);
  1015.             ok = cp && TIFFFetchByteArray(tif, dp, (uint16*) cp);
  1016.             break;
  1017.         case TIFF_SHORT:
  1018.         case TIFF_SSHORT:
  1019.             cp = CheckMalloc(tif,
  1020.                 dp->tdir_count * sizeof (uint16), mesg);
  1021.             ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp);
  1022.             break;
  1023.         case TIFF_LONG:
  1024.         case TIFF_SLONG:
  1025.             cp = CheckMalloc(tif,
  1026.                 dp->tdir_count * sizeof (uint32), mesg);
  1027.             ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp);
  1028.             break;
  1029.         case TIFF_RATIONAL:
  1030.         case TIFF_SRATIONAL:
  1031.             cp = CheckMalloc(tif,
  1032.                 dp->tdir_count * sizeof (float), mesg);
  1033.             ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp);
  1034.             break;
  1035.         case TIFF_FLOAT:
  1036.             cp = CheckMalloc(tif,
  1037.                 dp->tdir_count * sizeof (float), mesg);
  1038.             ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp);
  1039.             break;
  1040.         case TIFF_DOUBLE:
  1041.             cp = CheckMalloc(tif,
  1042.                 dp->tdir_count * sizeof (double), mesg);
  1043.             ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp);
  1044.             break;
  1045.         case TIFF_ASCII:
  1046.         case TIFF_UNDEFINED:        /* bit of a cheat... */
  1047.             /*
  1048.              * Some vendors write strings w/o the trailing
  1049.              * NULL byte, so always append one just in case.
  1050.              */
  1051.             cp = CheckMalloc(tif, dp->tdir_count+1, mesg);
  1052.             if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 )
  1053.                 cp[dp->tdir_count] = '\0';    /* XXX */
  1054.             break;
  1055.         }
  1056.         if (ok) {
  1057.             ok = (fip->field_passcount ?
  1058.                 TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp)
  1059.               : TIFFSetField(tif, dp->tdir_tag, cp));
  1060.         }
  1061.         if (cp != NULL)
  1062.             _TIFFfree(tif, cp);
  1063.     } else if (CheckDirCount(tif, dp, 1)) {    /* singleton value */
  1064.         switch (dp->tdir_type) {
  1065.         case TIFF_BYTE:
  1066.         case TIFF_SBYTE:
  1067.         case TIFF_SHORT:
  1068.         case TIFF_SSHORT:
  1069.             /*
  1070.              * If the tag is also acceptable as a LONG or SLONG
  1071.              * then TIFFSetField will expect an uint32 parameter
  1072.              * passed to it (through varargs).  Thus, for machines
  1073.              * where sizeof (int) != sizeof (uint32) we must do
  1074.              * a careful check here.  It's hard to say if this
  1075.              * is worth optimizing.
  1076.              *
  1077.              * NB: We use TIFFFieldWithTag here knowing that
  1078.              *     it returns us the first entry in the table
  1079.              *     for the tag and that that entry is for the
  1080.              *     widest potential data type the tag may have.
  1081.              */
  1082.             { TIFFDataType type = fip->field_type;
  1083.               if (type != TIFF_LONG && type != TIFF_SLONG) {
  1084.                 uint16 v = (uint16)
  1085.                TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
  1086.                 ok = (fip->field_passcount ?
  1087.                     TIFFSetField(tif, dp->tdir_tag, 1, &v)
  1088.                   : TIFFSetField(tif, dp->tdir_tag, v));
  1089.                 break;
  1090.               }
  1091.             }
  1092.             /* fall thru... */
  1093.         case TIFF_LONG:
  1094.         case TIFF_SLONG:
  1095.             { uint32 v32 =
  1096.             TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
  1097.               ok = (fip->field_passcount ? 
  1098.                   TIFFSetField(tif, dp->tdir_tag, 1, &v32)
  1099.                 : TIFFSetField(tif, dp->tdir_tag, v32));
  1100.             }
  1101.             break;
  1102.         case TIFF_RATIONAL:
  1103.         case TIFF_SRATIONAL:
  1104.         case TIFF_FLOAT:
  1105.             { float v = (dp->tdir_type == TIFF_FLOAT ? 
  1106.                   TIFFFetchFloat(tif, dp)
  1107.                 : TIFFFetchRational(tif, dp));
  1108.               ok = (fip->field_passcount ?
  1109.                   TIFFSetField(tif, dp->tdir_tag, 1, &v)
  1110.                 : TIFFSetField(tif, dp->tdir_tag, v));
  1111.             }
  1112.             break;
  1113.         case TIFF_DOUBLE:
  1114.             { double v;
  1115.               ok = (TIFFFetchDoubleArray(tif, dp, &v) &&
  1116.                 (fip->field_passcount ?
  1117.                   TIFFSetField(tif, dp->tdir_tag, 1, &v)
  1118.                 : TIFFSetField(tif, dp->tdir_tag, v))
  1119.               );
  1120.             }
  1121.             break;
  1122.         case TIFF_ASCII:
  1123.         case TIFF_UNDEFINED:        /* bit of a cheat... */
  1124.             { char c[2];
  1125.               if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ){
  1126.                 c[1] = '\0';        /* XXX paranoid */
  1127.                 ok = TIFFSetField(tif, dp->tdir_tag, c);
  1128.               }
  1129.             }
  1130.             break;
  1131.         }
  1132.     }
  1133.     return (ok);
  1134. }
  1135.  
  1136. #define    NITEMS(x)    (sizeof (x) / sizeof (x[0]))
  1137. /*
  1138.  * Fetch samples/pixel short values for 
  1139.  * the specified tag and verify that
  1140.  * all values are the same.
  1141.  */
  1142. static int
  1143. TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, int* pl)
  1144. {
  1145.     int samples = tif->tif_dir.td_samplesperpixel;
  1146.     int status = 0;
  1147.  
  1148.     if (CheckDirCount(tif, dir, (uint32) samples)) {
  1149.         uint16 buf[10];
  1150.         uint16* v = buf;
  1151.  
  1152.         if (samples > NITEMS(buf))
  1153.             v = (uint16*) _TIFFmalloc(tif, samples * sizeof (uint16));
  1154.         if (TIFFFetchShortArray(tif, dir, v)) {
  1155.             int i;
  1156.             for (i = 1; i < samples; i++)
  1157.                 if (v[i] != v[0]) {
  1158.                     TIFFError(tif->tif_name,
  1159.         "Cannot handle different per-sample values for field \"%s\"",
  1160.                _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
  1161.                     goto bad;
  1162.                 }
  1163.             *pl = v[0];
  1164.             status = 1;
  1165.         }
  1166.     bad:
  1167.         if (v != buf)
  1168.             _TIFFfree(tif, (char*) v);
  1169.     }
  1170.     return (status);
  1171. }
  1172.  
  1173. /*
  1174.  * Fetch samples/pixel ANY values for 
  1175.  * the specified tag and verify that
  1176.  * all values are the same.
  1177.  */
  1178. static int
  1179. TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl)
  1180. {
  1181.     int samples = (int) tif->tif_dir.td_samplesperpixel;
  1182.     int status = 0;
  1183.  
  1184.     if (CheckDirCount(tif, dir, (uint32) samples)) {
  1185.         double buf[10];
  1186.         double* v = buf;
  1187.  
  1188.         if (samples > NITEMS(buf))
  1189.             v = (double*) _TIFFmalloc(tif, samples*sizeof (double));
  1190.         if (TIFFFetchAnyArray(tif, dir, v)) {
  1191.             int i;
  1192.             for (i = 1; i < samples; i++)
  1193.                 if (v[i] != v[0]) {
  1194.                     TIFFError(tif->tif_name,
  1195.         "Cannot handle different per-sample values for field \"%s\"",
  1196.                _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
  1197.                     goto bad;
  1198.                 }
  1199.             *pl = v[0];
  1200.             status = 1;
  1201.         }
  1202.     bad:
  1203.         if (v != buf)
  1204.             _TIFFfree(tif, v);
  1205.     }
  1206.     return (status);
  1207. }
  1208. #undef NITEMS
  1209.  
  1210. /*
  1211.  * Fetch a set of offsets or lengths.
  1212.  * While this routine says "strips",
  1213.  * in fact it's also used for tiles.
  1214.  */
  1215. static int
  1216. TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp)
  1217. {
  1218.     register uint32* lp;
  1219.     int status;
  1220.  
  1221.     if (!CheckDirCount(tif, dir, (uint32) nstrips))
  1222.         return (0);
  1223.     /*
  1224.      * Allocate space for strip information.
  1225.      */
  1226.     if (*lpp == NULL &&
  1227.         (*lpp = (uint32 *)CheckMalloc(tif,
  1228.           nstrips * sizeof (uint32), "for strip array")) == NULL)
  1229.         return (0);
  1230.     lp = *lpp;
  1231.     if (dir->tdir_type == (int)TIFF_SHORT) {
  1232.         /*
  1233.          * Handle uint16->uint32 expansion.
  1234.          */
  1235.         uint16* dp = (uint16*) CheckMalloc(tif,
  1236.             dir->tdir_count* sizeof (uint16), "to fetch strip tag");
  1237.         if (dp == NULL)
  1238.             return (0);
  1239.         if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) {
  1240.             register uint16* wp = dp;
  1241.             while (nstrips-- > 0)
  1242.                 *lp++ = *wp++;
  1243.         }
  1244.         _TIFFfree(tif, (char*) dp);
  1245.     } else
  1246.         status = TIFFFetchLongArray(tif, dir, lp);
  1247.     return (status);
  1248. }
  1249.  
  1250. #define    NITEMS(x)    (sizeof (x) / sizeof (x[0]))
  1251. /*
  1252.  * Fetch and set the ExtraSamples tag.
  1253.  */
  1254. static int
  1255. TIFFFetchExtraSamples(TIFF* tif, TIFFDirEntry* dir)
  1256. {
  1257.     uint16 buf[10];
  1258.     uint16* v = buf;
  1259.     int status;
  1260.  
  1261.     if (dir->tdir_count > NITEMS(buf))
  1262.         v = (uint16*) _TIFFmalloc(tif, dir->tdir_count*sizeof (uint16));
  1263.     if (dir->tdir_type == TIFF_BYTE)
  1264.         status = TIFFFetchByteArray(tif, dir, v);
  1265.     else
  1266.         status = TIFFFetchShortArray(tif, dir, v);
  1267.     if (status)
  1268.         status = TIFFSetField(tif, dir->tdir_tag, dir->tdir_count, v);
  1269.     if (v != buf)
  1270.         _TIFFfree(tif, (char*) v);
  1271.     return (status);
  1272. }
  1273. #undef NITEMS
  1274.  
  1275. #ifdef COLORIMETRY_SUPPORT
  1276. /*
  1277.  * Fetch and set the RefBlackWhite tag.
  1278.  */
  1279. static int
  1280. TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir)
  1281. {
  1282.     static const char mesg[] = "for \"ReferenceBlackWhite\" array";
  1283.     char* cp;
  1284.     int ok;
  1285.  
  1286.     if (dir->tdir_type == TIFF_RATIONAL)
  1287.         return (TIFFFetchNormalTag(tif, dir));
  1288.     /*
  1289.      * Handle LONG's for backward compatibility.
  1290.      */
  1291.     cp = CheckMalloc(tif, dir->tdir_count * sizeof (uint32), mesg);
  1292.     if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) {
  1293.         float* fp = (float*)
  1294.             CheckMalloc(tif, dir->tdir_count * sizeof (float), mesg);
  1295.         if( (ok = (fp != NULL)) != 0 ) {
  1296.             uint32 i;
  1297.             for (i = 0; i < dir->tdir_count; i++)
  1298.                 fp[i] = (float)((uint32*) cp)[i];
  1299.             ok = TIFFSetField(tif, dir->tdir_tag, fp);
  1300.             _TIFFfree(tif, (char*) fp);
  1301.         }
  1302.     }
  1303.     if (cp)
  1304.         _TIFFfree(tif, cp);
  1305.     return (ok);
  1306. }
  1307. #endif
  1308.  
  1309. /*
  1310.  * Replace a single strip (tile) of uncompressed data by
  1311.  * multiple strips (tiles), each approximately 8Kbytes.
  1312.  * This is useful for dealing with large images or
  1313.  * for dealing with machines with a limited amount
  1314.  * memory.
  1315.  */
  1316. static void
  1317. ChopUpSingleUncompressedStrip(TIFF* tif)
  1318. {
  1319.     register TIFFDirectory *td = &tif->tif_dir;
  1320.     uint32 bytecount = td->td_stripbytecount[0];
  1321.     uint32 offset = td->td_stripoffset[0];
  1322.     tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes;
  1323.     tstrip_t strip, nstrips, rowsperstrip;
  1324.     uint32* newcounts;
  1325.     uint32* newoffsets;
  1326.  
  1327.     /*
  1328.      * Make the rows hold at least one
  1329.      * scanline, but fill 8k if possible.
  1330.      */
  1331.     if (rowbytes > 8192) {
  1332.         stripbytes = rowbytes;
  1333.         rowsperstrip = 1;
  1334.     } else {
  1335.         rowsperstrip = 8192 / rowbytes;
  1336.         stripbytes = rowbytes * rowsperstrip;
  1337.     }
  1338.     /* never increase the number of strips in an image */
  1339.     if (rowsperstrip >= td->td_rowsperstrip)
  1340.         return;
  1341.     nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes);
  1342.     newcounts = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32),
  1343.                 "for chopped \"StripByteCounts\" array");
  1344.     newoffsets = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32),
  1345.                 "for chopped \"StripOffsets\" array");
  1346.     if (newcounts == NULL || newoffsets == NULL) {
  1347.             /*
  1348.          * Unable to allocate new strip information, give
  1349.          * up and use the original one strip information.
  1350.          */
  1351.         if (newcounts != NULL)
  1352.             _TIFFfree(tif, newcounts);
  1353.         if (newoffsets != NULL)
  1354.             _TIFFfree(tif, newoffsets);
  1355.         return;
  1356.     }
  1357.     /*
  1358.      * Fill the strip information arrays with
  1359.      * new bytecounts and offsets that reflect
  1360.      * the broken-up format.
  1361.      */
  1362.     for (strip = 0; strip < nstrips; strip++) {
  1363.         if (stripbytes > (tsize_t) bytecount)
  1364.             stripbytes = bytecount;
  1365.         newcounts[strip] = stripbytes;
  1366.         newoffsets[strip] = offset;
  1367.         offset += stripbytes;
  1368.         bytecount -= stripbytes;
  1369.     }
  1370.     /*
  1371.      * Replace old single strip info with multi-strip info.
  1372.      */
  1373.     td->td_stripsperimage = td->td_nstrips = nstrips;
  1374.     TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
  1375.  
  1376.     _TIFFfree(tif, td->td_stripbytecount);
  1377.     _TIFFfree(tif, td->td_stripoffset);
  1378.     td->td_stripbytecount = newcounts;
  1379.     td->td_stripoffset = newoffsets;
  1380. }
  1381.