home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 4 / DATAFILE_PDCD4.iso / utilities / utilsf / libtiff / c / tif_dirrea < prev    next >
Encoding:
Text File  |  1995-10-12  |  37.3 KB  |  1,374 lines

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