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