Move the sources to trunk
[opencv] / otherlibs / _graphics / src / libtiff / tif_dir.c
1 /* $Id: tif_dir.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 Tag Get & Set Routines.
31  * (and also some miscellaneous stuff)
32  */
33 #include "tiffiop.h"
34
35 /*
36  * These are used in the backwards compatibility code...
37  */
38 #define DATATYPE_VOID           0       /* !untyped data */
39 #define DATATYPE_INT            1       /* !signed integer data */
40 #define DATATYPE_UINT           2       /* !unsigned integer data */
41 #define DATATYPE_IEEEFP         3       /* !IEEE floating point data */
42
43 static void
44 setByteArray(void** vpp, void* vp, size_t nmemb, size_t elem_size)
45 {
46         if (*vpp)
47                 _TIFFfree(*vpp), *vpp = 0;
48         if (vp) {
49                 tsize_t bytes = nmemb * elem_size;
50                 if (elem_size && bytes / elem_size == nmemb)
51                         *vpp = (void*) _TIFFmalloc(bytes);
52                 if (*vpp)
53                         _TIFFmemcpy(*vpp, vp, bytes);
54         }
55 }
56 void _TIFFsetByteArray(void** vpp, void* vp, long n)
57     { setByteArray(vpp, vp, n, 1); }
58 void _TIFFsetString(char** cpp, char* cp)
59     { setByteArray((void**) cpp, (void*) cp, strlen(cp)+1, 1); }
60 void _TIFFsetNString(char** cpp, char* cp, long n)
61     { setByteArray((void**) cpp, (void*) cp, n, 1); }
62 void _TIFFsetShortArray(uint16** wpp, uint16* wp, long n)
63     { setByteArray((void**) wpp, (void*) wp, n, sizeof (uint16)); }
64 void _TIFFsetLongArray(uint32** lpp, uint32* lp, long n)
65     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint32)); }
66 void _TIFFsetFloatArray(float** fpp, float* fp, long n)
67     { setByteArray((void**) fpp, (void*) fp, n, sizeof (float)); }
68 void _TIFFsetDoubleArray(double** dpp, double* dp, long n)
69     { setByteArray((void**) dpp, (void*) dp, n, sizeof (double)); }
70
71 /*
72  * Install extra samples information.
73  */
74 static int
75 setExtraSamples(TIFFDirectory* td, va_list ap, int* v)
76 {
77         uint16* va;
78         int i;
79
80         *v = va_arg(ap, int);
81         if ((uint16) *v > td->td_samplesperpixel)
82                 return (0);
83         va = va_arg(ap, uint16*);
84         if (*v > 0 && va == NULL)               /* typically missing param */
85                 return (0);
86         for (i = 0; i < *v; i++)
87                 if (va[i] > EXTRASAMPLE_UNASSALPHA)
88                         return (0);
89         td->td_extrasamples = (uint16) *v;
90         _TIFFsetShortArray(&td->td_sampleinfo, va, td->td_extrasamples);
91         return (1);
92 }
93
94 static int
95 checkInkNamesString(TIFF* tif, int slen, const char* s)
96 {
97         TIFFDirectory* td = &tif->tif_dir;
98         int i = td->td_samplesperpixel;
99
100         if (slen > 0) {
101                 const char* ep = s+slen;
102                 const char* cp = s;
103                 for (; i > 0; i--) {
104                         for (; *cp != '\0'; cp++)
105                                 if (cp >= ep)
106                                         goto bad;
107                         cp++;                           /* skip \0 */
108                 }
109                 return (cp-s);
110         }
111 bad:
112         TIFFError("TIFFSetField",
113             "%s: Invalid InkNames value; expecting %d names, found %d",
114             tif->tif_name,
115             td->td_samplesperpixel,
116             td->td_samplesperpixel-i);
117         return (0);
118 }
119
120 static int
121 _TIFFVSetField(TIFF* tif, ttag_t tag, va_list ap)
122 {
123         static const char module[] = "_TIFFVSetField";
124         
125         TIFFDirectory* td = &tif->tif_dir;
126         int status = 1;
127         uint32 v32;
128         int i, v;
129         double d;
130         char* s;
131
132         switch (tag) {
133         case TIFFTAG_SUBFILETYPE:
134                 td->td_subfiletype = va_arg(ap, uint32);
135                 break;
136         case TIFFTAG_IMAGEWIDTH:
137                 td->td_imagewidth = va_arg(ap, uint32);
138                 break;
139         case TIFFTAG_IMAGELENGTH:
140                 td->td_imagelength = va_arg(ap, uint32);
141                 break;
142         case TIFFTAG_BITSPERSAMPLE:
143                 td->td_bitspersample = (uint16) va_arg(ap, int);
144                 /*
145                  * If the data require post-decoding processing
146                  * to byte-swap samples, set it up here.  Note
147                  * that since tags are required to be ordered,
148                  * compression code can override this behaviour
149                  * in the setup method if it wants to roll the
150                  * post decoding work in with its normal work.
151                  */
152                 if (tif->tif_flags & TIFF_SWAB) {
153                         if (td->td_bitspersample == 16)
154                                 tif->tif_postdecode = _TIFFSwab16BitData;
155                         else if (td->td_bitspersample == 32)
156                                 tif->tif_postdecode = _TIFFSwab32BitData;
157                         else if (td->td_bitspersample == 64)
158                                 tif->tif_postdecode = _TIFFSwab64BitData;
159                 }
160                 break;
161         case TIFFTAG_COMPRESSION:
162                 v = va_arg(ap, int) & 0xffff;
163                 /*
164                  * If we're changing the compression scheme,
165                  * the notify the previous module so that it
166                  * can cleanup any state it's setup.
167                  */
168                 if (TIFFFieldSet(tif, FIELD_COMPRESSION)) {
169                         if (td->td_compression == v)
170                                 break;
171                         (*tif->tif_cleanup)(tif);
172                         tif->tif_flags &= ~TIFF_CODERSETUP;
173                 }
174                 /*
175                  * Setup new compression routine state.
176                  */
177                 if( (status = TIFFSetCompressionScheme(tif, v)) != 0 )
178                     td->td_compression = (uint16) v;
179                 else
180                     status = 0;
181                 break;
182         case TIFFTAG_PHOTOMETRIC:
183                 td->td_photometric = (uint16) va_arg(ap, int);
184                 break;
185         case TIFFTAG_THRESHHOLDING:
186                 td->td_threshholding = (uint16) va_arg(ap, int);
187                 break;
188         case TIFFTAG_FILLORDER:
189                 v = va_arg(ap, int);
190                 if (v != FILLORDER_LSB2MSB && v != FILLORDER_MSB2LSB)
191                         goto badvalue;
192                 td->td_fillorder = (uint16) v;
193                 break;
194         case TIFFTAG_DOCUMENTNAME:
195                 _TIFFsetString(&td->td_documentname, va_arg(ap, char*));
196                 break;
197         case TIFFTAG_ARTIST:
198                 _TIFFsetString(&td->td_artist, va_arg(ap, char*));
199                 break;
200         case TIFFTAG_DATETIME:
201                 _TIFFsetString(&td->td_datetime, va_arg(ap, char*));
202                 break;
203         case TIFFTAG_HOSTCOMPUTER:
204                 _TIFFsetString(&td->td_hostcomputer, va_arg(ap, char*));
205                 break;
206         case TIFFTAG_IMAGEDESCRIPTION:
207                 _TIFFsetString(&td->td_imagedescription, va_arg(ap, char*));
208                 break;
209         case TIFFTAG_MAKE:
210                 _TIFFsetString(&td->td_make, va_arg(ap, char*));
211                 break;
212         case TIFFTAG_MODEL:
213                 _TIFFsetString(&td->td_model, va_arg(ap, char*));
214                 break;
215         case TIFFTAG_COPYRIGHT:
216                 _TIFFsetString(&td->td_copyright, va_arg(ap, char*));
217                 break;
218         case TIFFTAG_ORIENTATION:
219                 v = va_arg(ap, int);
220                 if (v < ORIENTATION_TOPLEFT || ORIENTATION_LEFTBOT < v) {
221                         TIFFWarning(tif->tif_name,
222                             "Bad value %ld for \"%s\" tag ignored",
223                             v, _TIFFFieldWithTag(tif, tag)->field_name);
224                 } else
225                         td->td_orientation = (uint16) v;
226                 break;
227         case TIFFTAG_SAMPLESPERPIXEL:
228                 /* XXX should cross check -- e.g. if pallette, then 1 */
229                 v = va_arg(ap, int);
230                 if (v == 0)
231                         goto badvalue;
232                 td->td_samplesperpixel = (uint16) v;
233                 break;
234         case TIFFTAG_ROWSPERSTRIP:
235                 v32 = va_arg(ap, uint32);
236                 if (v32 == 0)
237                         goto badvalue32;
238                 td->td_rowsperstrip = v32;
239                 if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
240                         td->td_tilelength = v32;
241                         td->td_tilewidth = td->td_imagewidth;
242                 }
243                 break;
244         case TIFFTAG_MINSAMPLEVALUE:
245                 td->td_minsamplevalue = (uint16) va_arg(ap, int);
246                 break;
247         case TIFFTAG_MAXSAMPLEVALUE:
248                 td->td_maxsamplevalue = (uint16) va_arg(ap, int);
249                 break;
250         case TIFFTAG_SMINSAMPLEVALUE:
251                 td->td_sminsamplevalue = (double) va_arg(ap, dblparam_t);
252                 break;
253         case TIFFTAG_SMAXSAMPLEVALUE:
254                 td->td_smaxsamplevalue = (double) va_arg(ap, dblparam_t);
255                 break;
256         case TIFFTAG_XRESOLUTION:
257                 td->td_xresolution = (float) va_arg(ap, dblparam_t);
258                 break;
259         case TIFFTAG_YRESOLUTION:
260                 td->td_yresolution = (float) va_arg(ap, dblparam_t);
261                 break;
262         case TIFFTAG_PLANARCONFIG:
263                 v = va_arg(ap, int);
264                 if (v != PLANARCONFIG_CONTIG && v != PLANARCONFIG_SEPARATE)
265                         goto badvalue;
266                 td->td_planarconfig = (uint16) v;
267                 break;
268         case TIFFTAG_PAGENAME:
269                 _TIFFsetString(&td->td_pagename, va_arg(ap, char*));
270                 break;
271         case TIFFTAG_XPOSITION:
272                 td->td_xposition = (float) va_arg(ap, dblparam_t);
273                 break;
274         case TIFFTAG_YPOSITION:
275                 td->td_yposition = (float) va_arg(ap, dblparam_t);
276                 break;
277         case TIFFTAG_RESOLUTIONUNIT:
278                 v = va_arg(ap, int);
279                 if (v < RESUNIT_NONE || RESUNIT_CENTIMETER < v)
280                         goto badvalue;
281                 td->td_resolutionunit = (uint16) v;
282                 break;
283         case TIFFTAG_PAGENUMBER:
284                 td->td_pagenumber[0] = (uint16) va_arg(ap, int);
285                 td->td_pagenumber[1] = (uint16) va_arg(ap, int);
286                 break;
287         case TIFFTAG_HALFTONEHINTS:
288                 td->td_halftonehints[0] = (uint16) va_arg(ap, int);
289                 td->td_halftonehints[1] = (uint16) va_arg(ap, int);
290                 break;
291         case TIFFTAG_COLORMAP:
292                 v32 = (uint32)(1L<<td->td_bitspersample);
293                 _TIFFsetShortArray(&td->td_colormap[0], va_arg(ap, uint16*), v32);
294                 _TIFFsetShortArray(&td->td_colormap[1], va_arg(ap, uint16*), v32);
295                 _TIFFsetShortArray(&td->td_colormap[2], va_arg(ap, uint16*), v32);
296                 break;
297         case TIFFTAG_EXTRASAMPLES:
298                 if (!setExtraSamples(td, ap, &v))
299                         goto badvalue;
300                 break;
301         case TIFFTAG_MATTEING:
302                 td->td_extrasamples = (uint16) (va_arg(ap, int) != 0);
303                 if (td->td_extrasamples) {
304                         uint16 sv = EXTRASAMPLE_ASSOCALPHA;
305                         _TIFFsetShortArray(&td->td_sampleinfo, &sv, 1);
306                 }
307                 break;
308         case TIFFTAG_TILEWIDTH:
309                 v32 = va_arg(ap, uint32);
310                 if (v32 % 16) {
311                         if (tif->tif_mode != O_RDONLY)
312                                 goto badvalue32;
313                         TIFFWarning(tif->tif_name,
314                             "Nonstandard tile width %d, convert file", v32);
315                 }
316                 td->td_tilewidth = v32;
317                 tif->tif_flags |= TIFF_ISTILED;
318                 break;
319         case TIFFTAG_TILELENGTH:
320                 v32 = va_arg(ap, uint32);
321                 if (v32 % 16) {
322                         if (tif->tif_mode != O_RDONLY)
323                                 goto badvalue32;
324                         TIFFWarning(tif->tif_name,
325                             "Nonstandard tile length %d, convert file", v32);
326                 }
327                 td->td_tilelength = v32;
328                 tif->tif_flags |= TIFF_ISTILED;
329                 break;
330         case TIFFTAG_TILEDEPTH:
331                 v32 = va_arg(ap, uint32);
332                 if (v32 == 0)
333                         goto badvalue32;
334                 td->td_tiledepth = v32;
335                 break;
336         case TIFFTAG_DATATYPE:
337                 v = va_arg(ap, int);
338                 switch (v) {
339                 case DATATYPE_VOID:     v = SAMPLEFORMAT_VOID;  break;
340                 case DATATYPE_INT:      v = SAMPLEFORMAT_INT;   break;
341                 case DATATYPE_UINT:     v = SAMPLEFORMAT_UINT;  break;
342                 case DATATYPE_IEEEFP:   v = SAMPLEFORMAT_IEEEFP;break;
343                 default:                goto badvalue;
344                 }
345                 td->td_sampleformat = (uint16) v;
346                 break;
347         case TIFFTAG_SAMPLEFORMAT:
348                 v = va_arg(ap, int);
349                 if (v < SAMPLEFORMAT_UINT || SAMPLEFORMAT_COMPLEXIEEEFP < v)
350                         goto badvalue;
351                 td->td_sampleformat = (uint16) v;
352
353                 /*  Try to fix up the SWAB function for complex data. */
354                 if( td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT 
355                     && td->td_bitspersample == 32
356                     && tif->tif_postdecode == _TIFFSwab32BitData )
357                     tif->tif_postdecode = _TIFFSwab16BitData;
358                 else if( (td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT 
359                           || td->td_sampleformat == SAMPLEFORMAT_COMPLEXIEEEFP)
360                          && td->td_bitspersample == 64
361                          && tif->tif_postdecode == _TIFFSwab64BitData )
362                     tif->tif_postdecode = _TIFFSwab32BitData;
363                 else if( td->td_sampleformat == SAMPLEFORMAT_COMPLEXIEEEFP
364                          && td->td_bitspersample == 128
365                          && tif->tif_postdecode == NULL )
366                     tif->tif_postdecode = _TIFFSwab64BitData;
367                 break;
368         case TIFFTAG_IMAGEDEPTH:
369                 td->td_imagedepth = va_arg(ap, uint32);
370                 break;
371         case TIFFTAG_STONITS:
372                 d = va_arg(ap, dblparam_t);
373                 if (d <= 0.)
374                         goto badvaluedbl;
375                 td->td_stonits = d;
376                 break;
377         /* Begin Pixar Tags */
378         case TIFFTAG_PIXAR_IMAGEFULLWIDTH:
379                 td->td_imagefullwidth = va_arg(ap, uint32);
380                 break;
381         case TIFFTAG_PIXAR_IMAGEFULLLENGTH:
382                 td->td_imagefulllength = va_arg(ap, uint32);
383                 break;
384         case TIFFTAG_PIXAR_TEXTUREFORMAT:
385                 _TIFFsetString(&td->td_textureformat, va_arg(ap, char*));
386                 break;
387         case TIFFTAG_PIXAR_WRAPMODES:
388                 _TIFFsetString(&td->td_wrapmodes, va_arg(ap, char*));
389                 break;
390         case TIFFTAG_PIXAR_FOVCOT:
391                 td->td_fovcot = (float) va_arg(ap, dblparam_t);
392                 break;
393         case TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN:
394                 _TIFFsetFloatArray(&td->td_matrixWorldToScreen,
395                         va_arg(ap, float*), 16);
396                 break;
397         case TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA:
398                 _TIFFsetFloatArray(&td->td_matrixWorldToCamera,
399                         va_arg(ap, float*), 16);
400                 break;
401         /* End Pixar Tags */           
402
403         case TIFFTAG_SUBIFD:
404                 if ((tif->tif_flags & TIFF_INSUBIFD) == 0) {
405                         td->td_nsubifd = (uint16) va_arg(ap, int);
406                         _TIFFsetLongArray(&td->td_subifd, va_arg(ap, uint32*),
407                             (long) td->td_nsubifd);
408                 } else {
409                         TIFFError(module, "%s: Sorry, cannot nest SubIFDs",
410                                   tif->tif_name);
411                         status = 0;
412                 }
413                 break;
414         case TIFFTAG_YCBCRCOEFFICIENTS:
415                 _TIFFsetFloatArray(&td->td_ycbcrcoeffs, va_arg(ap, float*), 3);
416                 break;
417         case TIFFTAG_YCBCRPOSITIONING:
418                 td->td_ycbcrpositioning = (uint16) va_arg(ap, int);
419                 break;
420         case TIFFTAG_YCBCRSUBSAMPLING:
421                 td->td_ycbcrsubsampling[0] = (uint16) va_arg(ap, int);
422                 td->td_ycbcrsubsampling[1] = (uint16) va_arg(ap, int);
423                 break;
424         case TIFFTAG_WHITEPOINT:
425                 _TIFFsetFloatArray(&td->td_whitepoint, va_arg(ap, float*), 2);
426                 break;
427         case TIFFTAG_PRIMARYCHROMATICITIES:
428                 _TIFFsetFloatArray(&td->td_primarychromas, va_arg(ap, float*), 6);
429                 break;
430         case TIFFTAG_TRANSFERFUNCTION:
431                 v = (td->td_samplesperpixel - td->td_extrasamples) > 1 ? 3 : 1;
432                 for (i = 0; i < v; i++)
433                         _TIFFsetShortArray(&td->td_transferfunction[i],
434                             va_arg(ap, uint16*), 1L<<td->td_bitspersample);
435                 break;
436         case TIFFTAG_REFERENCEBLACKWHITE:
437                 /* XXX should check for null range */
438                 _TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6);
439                 break;
440         case TIFFTAG_INKSET:
441                 td->td_inkset = (uint16) va_arg(ap, int);
442                 break;
443         case TIFFTAG_DOTRANGE:
444                 /* XXX should check for null range */
445                 td->td_dotrange[0] = (uint16) va_arg(ap, int);
446                 td->td_dotrange[1] = (uint16) va_arg(ap, int);
447                 break;
448         case TIFFTAG_INKNAMES:
449                 i = va_arg(ap, int);
450                 s = va_arg(ap, char*);
451                 i = checkInkNamesString(tif, i, s);
452                 status = i > 0;
453                 if( i > 0 ) {
454                         _TIFFsetNString(&td->td_inknames, s, i);
455                         td->td_inknameslen = i;
456                 }
457                 break;
458         case TIFFTAG_NUMBEROFINKS:
459                 td->td_ninks = (uint16) va_arg(ap, int);
460                 break;
461         case TIFFTAG_TARGETPRINTER:
462                 _TIFFsetString(&td->td_targetprinter, va_arg(ap, char*));
463                 break;
464         case TIFFTAG_ICCPROFILE:
465                 td->td_profileLength = (uint32) va_arg(ap, uint32);
466                 _TIFFsetByteArray(&td->td_profileData, va_arg(ap, void*),
467                     td->td_profileLength);
468                 break;
469         case TIFFTAG_PHOTOSHOP:
470                 td->td_photoshopLength = (uint32) va_arg(ap, uint32);
471                 _TIFFsetByteArray (&td->td_photoshopData, va_arg(ap, void*),
472                         td->td_photoshopLength);
473                 break;
474         case TIFFTAG_RICHTIFFIPTC: 
475                 td->td_richtiffiptcLength = (uint32) va_arg(ap, uint32);
476                 _TIFFsetLongArray ((uint32**)&td->td_richtiffiptcData,
477                                    va_arg(ap, uint32*),
478                                    td->td_richtiffiptcLength);
479                 break;
480         case TIFFTAG_XMLPACKET:
481                 td->td_xmlpacketLength = (uint32) va_arg(ap, uint32);
482                 _TIFFsetByteArray(&td->td_xmlpacketData, va_arg(ap, void*),
483                     td->td_xmlpacketLength);
484                 break;
485         default: {
486             const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY);
487             TIFFTagValue *tv;
488             int tv_size, iCustom;
489
490             /*
491              * This can happen if multiple images are open with
492              * different codecs which have private tags.  The
493              * global tag information table may then have tags
494              * that are valid for one file but not the other. 
495              * If the client tries to set a tag that is not valid
496              * for the image's codec then we'll arrive here.  This
497              * happens, for example, when tiffcp is used to convert
498              * between compression schemes and codec-specific tags
499              * are blindly copied.
500              */
501             if( fip == NULL || fip->field_bit != FIELD_CUSTOM )
502             {
503                 TIFFError(module,
504                     "%s: Invalid %stag \"%s\" (not supported by codec)",
505                     tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "",
506                     _TIFFFieldWithTag(tif, tag)->field_name);
507                 status = 0;
508                 break;
509             }
510
511             /*
512              * Find the existing entry for this custom value.
513              */
514             tv = NULL;
515             for( iCustom = 0; iCustom < td->td_customValueCount; iCustom++ )
516             {
517                 if( td->td_customValues[iCustom].info == fip )
518                 {
519                     tv = td->td_customValues + iCustom;
520                     if( tv->value != NULL )
521                         _TIFFfree( tv->value );
522                     break;
523                 }
524             }
525
526             /*
527              * Grow the custom list if the entry was not found.
528              */
529             if( tv == NULL )
530             {
531                 TIFFTagValue    *new_customValues;
532                 
533                 td->td_customValueCount++;
534                 new_customValues = (TIFFTagValue *)
535                         _TIFFrealloc(td->td_customValues,
536                                      sizeof(TIFFTagValue) * td->td_customValueCount);
537                 if (!new_customValues) {
538                         TIFFError(module,
539                 "%s: Failed to allocate space for list of custom values",
540                                   tif->tif_name);
541                         status = 0;
542                         goto end;
543                 }
544
545                 td->td_customValues = new_customValues;
546
547                 tv = td->td_customValues + (td->td_customValueCount-1);
548                 tv->info = fip;
549                 tv->value = NULL;
550                 tv->count = 0;
551             }
552
553             /*
554              * Set custom value ... save a copy of the custom tag value.
555              */
556             switch (fip->field_type) {
557                     /*
558                      * XXX: We can't use TIFFDataWidth() to determine the
559                      * space needed to store the value. For TIFF_RATIONAL
560                      * values TIFFDataWidth() returns 8, but we use 4-byte
561                      * float to represent rationals.
562                      */
563                     case TIFF_BYTE:
564                     case TIFF_ASCII:
565                     case TIFF_SBYTE:
566                     case TIFF_UNDEFINED:
567                         tv_size = 1;
568                         break;
569
570                     case TIFF_SHORT:
571                     case TIFF_SSHORT:
572                         tv_size = 2;
573                         break;
574
575                     case TIFF_LONG:
576                     case TIFF_SLONG:
577                     case TIFF_FLOAT:
578                     case TIFF_IFD:
579                     case TIFF_RATIONAL:
580                     case TIFF_SRATIONAL:
581                         tv_size = 4;
582                         break;
583
584                     case TIFF_DOUBLE:
585                         tv_size = 8;
586                         break;
587
588                     default:
589                         status = 0;
590                         TIFFError(module, "%s: Bad field type %d for \"%s\"",
591                                   tif->tif_name, fip->field_type,
592                                   fip->field_name);
593                         goto end;
594                     
595             }
596             
597             if(fip->field_passcount)
598                 tv->count = (int) va_arg(ap, int);
599             else
600                 tv->count = 1;
601             
602             if (fip->field_passcount) {
603                 tv->value = _TIFFmalloc(tv_size * tv->count);
604                 if ( !tv->value ) {
605                         status = 0;
606                         goto end;
607                 }
608                 _TIFFmemcpy(tv->value, (void *) va_arg(ap,void*),
609                             tv->count * tv_size);
610             } else if (fip->field_type == TIFF_ASCII) {
611                 const char *value = (const char *) va_arg(ap,const char *);
612                 tv->count = strlen(value)+1;
613                 tv->value = _TIFFmalloc(tv->count);
614                 if (!tv->value) {
615                         status = 0;
616                         goto end;
617                 }
618                 strcpy(tv->value, value);
619             } else {
620                 /* not supporting "pass by value" types yet */
621                 TIFFError(module,
622                           "%s: Pass by value is not implemented.",
623                           tif->tif_name);
624
625                 tv->value = _TIFFmalloc(tv_size * tv->count);
626                 if (!tv->value) {
627                         status = 0;
628                         goto end;
629                 }
630                 _TIFFmemset(tv->value, 0, tv->count * tv_size);
631                 status = 0;
632             }
633           }
634         }
635         if (status) {
636             TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit);
637             tif->tif_flags |= TIFF_DIRTYDIRECT;
638         }
639
640 end:
641         va_end(ap);
642         return (status);
643 badvalue:
644         TIFFError(module, "%s: Bad value %d for \"%s\"",
645                   tif->tif_name, v, _TIFFFieldWithTag(tif, tag)->field_name);
646         va_end(ap);
647         return (0);
648 badvalue32:
649         TIFFError(module, "%s: Bad value %ld for \"%s\"",
650                    tif->tif_name, v32, _TIFFFieldWithTag(tif, tag)->field_name);
651         va_end(ap);
652         return (0);
653 badvaluedbl:
654         TIFFError(module, "%s: Bad value %f for \"%s\"",
655                   tif->tif_name, d, _TIFFFieldWithTag(tif, tag)->field_name);
656         va_end(ap);
657         return (0);
658 }
659
660 /*
661  * Return 1/0 according to whether or not
662  * it is permissible to set the tag's value.
663  * Note that we allow ImageLength to be changed
664  * so that we can append and extend to images.
665  * Any other tag may not be altered once writing
666  * has commenced, unless its value has no effect
667  * on the format of the data that is written.
668  */
669 static int
670 OkToChangeTag(TIFF* tif, ttag_t tag)
671 {
672         const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY);
673         if (!fip) {                     /* unknown tag */
674                 TIFFError("TIFFSetField", "%s: Unknown %stag %u",
675                     tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "", tag);
676                 return (0);
677         }
678         if (tag != TIFFTAG_IMAGELENGTH && (tif->tif_flags & TIFF_BEENWRITING) &&
679             !fip->field_oktochange) {
680                 /*
681                  * Consult info table to see if tag can be changed
682                  * after we've started writing.  We only allow changes
683                  * to those tags that don't/shouldn't affect the
684                  * compression and/or format of the data.
685                  */
686                 TIFFError("TIFFSetField",
687                     "%s: Cannot modify tag \"%s\" while writing",
688                     tif->tif_name, fip->field_name);
689                 return (0);
690         }
691         return (1);
692 }
693
694 /*
695  * Record the value of a field in the
696  * internal directory structure.  The
697  * field will be written to the file
698  * when/if the directory structure is
699  * updated.
700  */
701 int
702 TIFFSetField(TIFF* tif, ttag_t tag, ...)
703 {
704         va_list ap;
705         int status;
706
707         va_start(ap, tag);
708         status = TIFFVSetField(tif, tag, ap);
709         va_end(ap);
710         return (status);
711 }
712
713 /*
714  * Like TIFFSetField, but taking a varargs
715  * parameter list.  This routine is useful
716  * for building higher-level interfaces on
717  * top of the library.
718  */
719 int
720 TIFFVSetField(TIFF* tif, ttag_t tag, va_list ap)
721 {
722         return OkToChangeTag(tif, tag) ?
723             (*tif->tif_tagmethods.vsetfield)(tif, tag, ap) : 0;
724 }
725
726 static int
727 _TIFFVGetField(TIFF* tif, ttag_t tag, va_list ap)
728 {
729     TIFFDirectory* td = &tif->tif_dir;
730     int            ret_val = 1;
731
732     switch (tag) {
733         case TIFFTAG_SUBFILETYPE:
734             *va_arg(ap, uint32*) = td->td_subfiletype;
735             break;
736         case TIFFTAG_IMAGEWIDTH:
737             *va_arg(ap, uint32*) = td->td_imagewidth;
738             break;
739         case TIFFTAG_IMAGELENGTH:
740             *va_arg(ap, uint32*) = td->td_imagelength;
741             break;
742         case TIFFTAG_BITSPERSAMPLE:
743             *va_arg(ap, uint16*) = td->td_bitspersample;
744             break;
745         case TIFFTAG_COMPRESSION:
746             *va_arg(ap, uint16*) = td->td_compression;
747             break;
748         case TIFFTAG_PHOTOMETRIC:
749             *va_arg(ap, uint16*) = td->td_photometric;
750             break;
751         case TIFFTAG_THRESHHOLDING:
752             *va_arg(ap, uint16*) = td->td_threshholding;
753             break;
754         case TIFFTAG_FILLORDER:
755             *va_arg(ap, uint16*) = td->td_fillorder;
756             break;
757         case TIFFTAG_DOCUMENTNAME:
758             *va_arg(ap, char**) = td->td_documentname;
759             break;
760         case TIFFTAG_ARTIST:
761             *va_arg(ap, char**) = td->td_artist;
762             break;
763         case TIFFTAG_DATETIME:
764             *va_arg(ap, char**) = td->td_datetime;
765             break;
766         case TIFFTAG_HOSTCOMPUTER:
767             *va_arg(ap, char**) = td->td_hostcomputer;
768             break;
769         case TIFFTAG_IMAGEDESCRIPTION:
770             *va_arg(ap, char**) = td->td_imagedescription;
771             break;
772         case TIFFTAG_MAKE:
773             *va_arg(ap, char**) = td->td_make;
774             break;
775         case TIFFTAG_MODEL:
776             *va_arg(ap, char**) = td->td_model;
777             break;
778         case TIFFTAG_COPYRIGHT:
779             *va_arg(ap, char**) = td->td_copyright;
780             break;
781         case TIFFTAG_ORIENTATION:
782             *va_arg(ap, uint16*) = td->td_orientation;
783             break;
784         case TIFFTAG_SAMPLESPERPIXEL:
785             *va_arg(ap, uint16*) = td->td_samplesperpixel;
786             break;
787         case TIFFTAG_ROWSPERSTRIP:
788             *va_arg(ap, uint32*) = td->td_rowsperstrip;
789             break;
790         case TIFFTAG_MINSAMPLEVALUE:
791             *va_arg(ap, uint16*) = td->td_minsamplevalue;
792             break;
793         case TIFFTAG_MAXSAMPLEVALUE:
794             *va_arg(ap, uint16*) = td->td_maxsamplevalue;
795             break;
796         case TIFFTAG_SMINSAMPLEVALUE:
797             *va_arg(ap, double*) = td->td_sminsamplevalue;
798             break;
799         case TIFFTAG_SMAXSAMPLEVALUE:
800             *va_arg(ap, double*) = td->td_smaxsamplevalue;
801             break;
802         case TIFFTAG_XRESOLUTION:
803             *va_arg(ap, float*) = td->td_xresolution;
804             break;
805         case TIFFTAG_YRESOLUTION:
806             *va_arg(ap, float*) = td->td_yresolution;
807             break;
808         case TIFFTAG_PLANARCONFIG:
809             *va_arg(ap, uint16*) = td->td_planarconfig;
810             break;
811         case TIFFTAG_XPOSITION:
812             *va_arg(ap, float*) = td->td_xposition;
813             break;
814         case TIFFTAG_YPOSITION:
815             *va_arg(ap, float*) = td->td_yposition;
816             break;
817         case TIFFTAG_PAGENAME:
818             *va_arg(ap, char**) = td->td_pagename;
819             break;
820         case TIFFTAG_RESOLUTIONUNIT:
821             *va_arg(ap, uint16*) = td->td_resolutionunit;
822             break;
823         case TIFFTAG_PAGENUMBER:
824             *va_arg(ap, uint16*) = td->td_pagenumber[0];
825             *va_arg(ap, uint16*) = td->td_pagenumber[1];
826             break;
827         case TIFFTAG_HALFTONEHINTS:
828             *va_arg(ap, uint16*) = td->td_halftonehints[0];
829             *va_arg(ap, uint16*) = td->td_halftonehints[1];
830             break;
831         case TIFFTAG_COLORMAP:
832             *va_arg(ap, uint16**) = td->td_colormap[0];
833             *va_arg(ap, uint16**) = td->td_colormap[1];
834             *va_arg(ap, uint16**) = td->td_colormap[2];
835             break;
836         case TIFFTAG_STRIPOFFSETS:
837         case TIFFTAG_TILEOFFSETS:
838             *va_arg(ap, uint32**) = td->td_stripoffset;
839             break;
840         case TIFFTAG_STRIPBYTECOUNTS:
841         case TIFFTAG_TILEBYTECOUNTS:
842             *va_arg(ap, uint32**) = td->td_stripbytecount;
843             break;
844         case TIFFTAG_MATTEING:
845             *va_arg(ap, uint16*) =
846                 (td->td_extrasamples == 1 &&
847                  td->td_sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
848             break;
849         case TIFFTAG_EXTRASAMPLES:
850             *va_arg(ap, uint16*) = td->td_extrasamples;
851             *va_arg(ap, uint16**) = td->td_sampleinfo;
852             break;
853         case TIFFTAG_TILEWIDTH:
854             *va_arg(ap, uint32*) = td->td_tilewidth;
855             break;
856         case TIFFTAG_TILELENGTH:
857             *va_arg(ap, uint32*) = td->td_tilelength;
858             break;
859         case TIFFTAG_TILEDEPTH:
860             *va_arg(ap, uint32*) = td->td_tiledepth;
861             break;
862         case TIFFTAG_DATATYPE:
863             switch (td->td_sampleformat) {
864                 case SAMPLEFORMAT_UINT:
865                     *va_arg(ap, uint16*) = DATATYPE_UINT;
866                     break;
867                 case SAMPLEFORMAT_INT:
868                     *va_arg(ap, uint16*) = DATATYPE_INT;
869                     break;
870                 case SAMPLEFORMAT_IEEEFP:
871                     *va_arg(ap, uint16*) = DATATYPE_IEEEFP;
872                     break;
873                 case SAMPLEFORMAT_VOID:
874                     *va_arg(ap, uint16*) = DATATYPE_VOID;
875                     break;
876             }
877             break;
878         case TIFFTAG_SAMPLEFORMAT:
879             *va_arg(ap, uint16*) = td->td_sampleformat;
880             break;
881         case TIFFTAG_IMAGEDEPTH:
882             *va_arg(ap, uint32*) = td->td_imagedepth;
883             break;
884         case TIFFTAG_STONITS:
885             *va_arg(ap, double*) = td->td_stonits;
886             break;
887         case TIFFTAG_SUBIFD:
888             *va_arg(ap, uint16*) = td->td_nsubifd;
889             *va_arg(ap, uint32**) = td->td_subifd;
890             break;
891         case TIFFTAG_YCBCRCOEFFICIENTS:
892             *va_arg(ap, float**) = td->td_ycbcrcoeffs;
893             break;
894         case TIFFTAG_YCBCRPOSITIONING:
895             *va_arg(ap, uint16*) = td->td_ycbcrpositioning;
896             break;
897         case TIFFTAG_YCBCRSUBSAMPLING:
898             *va_arg(ap, uint16*) = td->td_ycbcrsubsampling[0];
899             *va_arg(ap, uint16*) = td->td_ycbcrsubsampling[1];
900             break;
901         case TIFFTAG_WHITEPOINT:
902             *va_arg(ap, float**) = td->td_whitepoint;
903             break;
904         case TIFFTAG_PRIMARYCHROMATICITIES:
905             *va_arg(ap, float**) = td->td_primarychromas;
906             break;
907         case TIFFTAG_TRANSFERFUNCTION:
908             *va_arg(ap, uint16**) = td->td_transferfunction[0];
909             if (td->td_samplesperpixel - td->td_extrasamples > 1) {
910                 *va_arg(ap, uint16**) = td->td_transferfunction[1];
911                 *va_arg(ap, uint16**) = td->td_transferfunction[2];
912             }
913             break;
914         case TIFFTAG_REFERENCEBLACKWHITE:
915             *va_arg(ap, float**) = td->td_refblackwhite;
916             break;
917         case TIFFTAG_INKSET:
918             *va_arg(ap, uint16*) = td->td_inkset;
919             break;
920         case TIFFTAG_DOTRANGE:
921             *va_arg(ap, uint16*) = td->td_dotrange[0];
922             *va_arg(ap, uint16*) = td->td_dotrange[1];
923             break;
924         case TIFFTAG_INKNAMES:
925             *va_arg(ap, char**) = td->td_inknames;
926             break;
927         case TIFFTAG_NUMBEROFINKS:
928             *va_arg(ap, uint16*) = td->td_ninks;
929             break;
930         case TIFFTAG_TARGETPRINTER:
931             *va_arg(ap, char**) = td->td_targetprinter;
932             break;
933         case TIFFTAG_ICCPROFILE:
934             *va_arg(ap, uint32*) = td->td_profileLength;
935             *va_arg(ap, void**) = td->td_profileData;
936             break;
937         case TIFFTAG_PHOTOSHOP:
938             *va_arg(ap, uint32*) = td->td_photoshopLength;
939             *va_arg(ap, void**) = td->td_photoshopData;
940             break;
941         case TIFFTAG_RICHTIFFIPTC:
942             *va_arg(ap, uint32*) = td->td_richtiffiptcLength;
943             *va_arg(ap, void**) = td->td_richtiffiptcData;
944             break;
945         case TIFFTAG_XMLPACKET:
946             *va_arg(ap, uint32*) = td->td_xmlpacketLength;
947             *va_arg(ap, void**) = td->td_xmlpacketData;
948             break;
949             /* Begin Pixar Tags */
950         case TIFFTAG_PIXAR_IMAGEFULLWIDTH:
951             *va_arg(ap, uint32*) = td->td_imagefullwidth;
952             break;
953         case TIFFTAG_PIXAR_IMAGEFULLLENGTH:
954             *va_arg(ap, uint32*) = td->td_imagefulllength;
955             break;
956         case TIFFTAG_PIXAR_TEXTUREFORMAT:
957             *va_arg(ap, char**) = td->td_textureformat;
958             break;
959         case TIFFTAG_PIXAR_WRAPMODES:
960             *va_arg(ap, char**) = td->td_wrapmodes;
961             break;
962         case TIFFTAG_PIXAR_FOVCOT:
963             *va_arg(ap, float*) = td->td_fovcot;
964             break;
965         case TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN:
966             *va_arg(ap, float**) = td->td_matrixWorldToScreen;
967             break;
968         case TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA:
969             *va_arg(ap, float**) = td->td_matrixWorldToCamera;
970             break;
971             /* End Pixar Tags */
972
973         default:
974         {
975             const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY);
976             int           i;
977             
978             /*
979              * This can happen if multiple images are open with
980              * different codecs which have private tags.  The
981              * global tag information table may then have tags
982              * that are valid for one file but not the other. 
983              * If the client tries to get a tag that is not valid
984              * for the image's codec then we'll arrive here.
985              */
986             if( fip == NULL || fip->field_bit != FIELD_CUSTOM )
987             {
988                 TIFFError("_TIFFVGetField",
989                           "%s: Invalid %stag \"%s\" (not supported by codec)",
990                           tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "",
991                           _TIFFFieldWithTag(tif, tag)->field_name);
992                 ret_val = 0;
993                 break;
994             }
995
996             /*
997             ** Do we have a custom value?
998             */
999             ret_val = 0;
1000             for (i = 0; i < td->td_customValueCount; i++)
1001             {
1002                 TIFFTagValue *tv = td->td_customValues + i;
1003
1004                 if (tv->info->field_tag != tag)
1005                         continue;
1006                 
1007                 if (fip->field_passcount) {
1008                         if (fip->field_readcount == TIFF_VARIABLE2) 
1009                                 *va_arg(ap, uint32*) = (uint32)tv->count;
1010                         else    /* Assume TIFF_VARIABLE */
1011                                 *va_arg(ap, uint16*) = (uint16)tv->count;
1012                         *va_arg(ap, void **) = tv->value;
1013                         ret_val = 1;
1014                         break;
1015                 } else if (fip->field_type == TIFF_ASCII) {
1016                         *va_arg(ap, void **) = tv->value;
1017                         ret_val = 1;
1018                         break;
1019                 } else {
1020                         TIFFError("_TIFFVGetField",
1021                                   "%s: Pass by value is not implemented.",
1022                                   tif->tif_name);
1023                         break;
1024                 }
1025             }
1026         }
1027     }
1028     return(ret_val);
1029 }
1030
1031 /*
1032  * Return the value of a field in the
1033  * internal directory structure.
1034  */
1035 int
1036 TIFFGetField(TIFF* tif, ttag_t tag, ...)
1037 {
1038         int status;
1039         va_list ap;
1040
1041         va_start(ap, tag);
1042         status = TIFFVGetField(tif, tag, ap);
1043         va_end(ap);
1044         return (status);
1045 }
1046
1047 /*
1048  * Like TIFFGetField, but taking a varargs
1049  * parameter list.  This routine is useful
1050  * for building higher-level interfaces on
1051  * top of the library.
1052  */
1053 int
1054 TIFFVGetField(TIFF* tif, ttag_t tag, va_list ap)
1055 {
1056         const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY);
1057         return (fip && (isPseudoTag(tag) || TIFFFieldSet(tif, fip->field_bit)) ?
1058             (*tif->tif_tagmethods.vgetfield)(tif, tag, ap) : 0);
1059 }
1060
1061 #define CleanupField(member) {          \
1062     if (td->member) {                   \
1063         _TIFFfree(td->member);          \
1064         td->member = 0;                 \
1065     }                                   \
1066 }
1067
1068 /*
1069  * Release storage associated with a directory.
1070  */
1071 void
1072 TIFFFreeDirectory(TIFF* tif)
1073 {
1074         TIFFDirectory *td = &tif->tif_dir;
1075         int            i;
1076
1077         CleanupField(td_colormap[0]);
1078         CleanupField(td_colormap[1]);
1079         CleanupField(td_colormap[2]);
1080         CleanupField(td_documentname);
1081         CleanupField(td_artist);
1082         CleanupField(td_datetime);
1083         CleanupField(td_hostcomputer);
1084         CleanupField(td_imagedescription);
1085         CleanupField(td_make);
1086         CleanupField(td_model);
1087         CleanupField(td_copyright);
1088         CleanupField(td_pagename);
1089         CleanupField(td_sampleinfo);
1090         CleanupField(td_subifd);
1091         CleanupField(td_ycbcrcoeffs);
1092         CleanupField(td_inknames);
1093         CleanupField(td_targetprinter);
1094         CleanupField(td_whitepoint);
1095         CleanupField(td_primarychromas);
1096         CleanupField(td_refblackwhite);
1097         CleanupField(td_transferfunction[0]);
1098         CleanupField(td_transferfunction[1]);
1099         CleanupField(td_transferfunction[2]);
1100         CleanupField(td_profileData);
1101         CleanupField(td_photoshopData);
1102         CleanupField(td_richtiffiptcData);
1103         CleanupField(td_xmlpacketData);
1104         CleanupField(td_stripoffset);
1105         CleanupField(td_stripbytecount);
1106         /* Begin Pixar Tags */
1107         CleanupField(td_textureformat);
1108         CleanupField(td_wrapmodes);
1109         CleanupField(td_matrixWorldToScreen);
1110         CleanupField(td_matrixWorldToCamera);
1111         /* End Pixar Tags */
1112
1113         /* Cleanup custom tag values */
1114         for( i = 0; i < td->td_customValueCount; i++ ) {
1115                 if (td->td_customValues[i].value)
1116                         _TIFFfree(td->td_customValues[i].value);
1117         }
1118
1119         td->td_customValueCount = 0;
1120         CleanupField(td_customValues);
1121 }
1122 #undef CleanupField
1123
1124 /*
1125  * Client Tag extension support (from Niles Ritter).
1126  */
1127 static TIFFExtendProc _TIFFextender = (TIFFExtendProc) NULL;
1128
1129 TIFFExtendProc
1130 TIFFSetTagExtender(TIFFExtendProc extender)
1131 {
1132         TIFFExtendProc prev = _TIFFextender;
1133         _TIFFextender = extender;
1134         return (prev);
1135 }
1136
1137 /*
1138  * Setup for a new directory.  Should we automatically call
1139  * TIFFWriteDirectory() if the current one is dirty?
1140  *
1141  * The newly created directory will not exist on the file till
1142  * TIFFWriteDirectory(), TIFFFlush() or TIFFClose() is called.
1143  */
1144 int
1145 TIFFCreateDirectory(TIFF* tif)
1146 {
1147     TIFFDefaultDirectory(tif);
1148     tif->tif_diroff = 0;
1149     tif->tif_nextdiroff = 0;
1150     tif->tif_curoff = 0;
1151     tif->tif_row = (uint32) -1;
1152     tif->tif_curstrip = (tstrip_t) -1;
1153
1154     return 0;
1155 }
1156
1157 /*
1158  * Setup a default directory structure.
1159  */
1160 int
1161 TIFFDefaultDirectory(TIFF* tif)
1162 {
1163         register TIFFDirectory* td = &tif->tif_dir;
1164
1165         _TIFFSetupFieldInfo(tif);
1166         _TIFFmemset(td, 0, sizeof (*td));
1167         td->td_fillorder = FILLORDER_MSB2LSB;
1168         td->td_bitspersample = 1;
1169         td->td_threshholding = THRESHHOLD_BILEVEL;
1170         td->td_orientation = ORIENTATION_TOPLEFT;
1171         td->td_samplesperpixel = 1;
1172         td->td_rowsperstrip = (uint32) -1;
1173         td->td_tilewidth = 0;
1174         td->td_tilelength = 0;
1175         td->td_tiledepth = 1;
1176         td->td_stripbytecountsorted = 1; /* Our own arrays always sorted. */
1177         td->td_resolutionunit = RESUNIT_INCH;
1178         td->td_sampleformat = SAMPLEFORMAT_UINT;
1179         td->td_imagedepth = 1;
1180         td->td_ycbcrsubsampling[0] = 2;
1181         td->td_ycbcrsubsampling[1] = 2;
1182         td->td_ycbcrpositioning = YCBCRPOSITION_CENTERED;
1183         td->td_inkset = INKSET_CMYK;
1184         td->td_ninks = 4;
1185         tif->tif_postdecode = _TIFFNoPostDecode;
1186         tif->tif_foundfield = NULL;
1187         tif->tif_tagmethods.vsetfield = _TIFFVSetField;
1188         tif->tif_tagmethods.vgetfield = _TIFFVGetField;
1189         tif->tif_tagmethods.printdir = NULL;
1190         /*
1191          *  Give client code a chance to install their own
1192          *  tag extensions & methods, prior to compression overloads.
1193          */
1194         if (_TIFFextender)
1195                 (*_TIFFextender)(tif);
1196         (void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
1197         /*
1198          * NB: The directory is marked dirty as a result of setting
1199          * up the default compression scheme.  However, this really
1200          * isn't correct -- we want TIFF_DIRTYDIRECT to be set only
1201          * if the user does something.  We could just do the setup
1202          * by hand, but it seems better to use the normal mechanism
1203          * (i.e. TIFFSetField).
1204          */
1205         tif->tif_flags &= ~TIFF_DIRTYDIRECT;
1206
1207         /*
1208          * As per http://bugzilla.remotesensing.org/show_bug.cgi?id=19
1209          * we clear the ISTILED flag when setting up a new directory.
1210          * Should we also be clearing stuff like INSUBIFD?
1211          */
1212         tif->tif_flags &= ~TIFF_ISTILED;
1213
1214         return (1);
1215 }
1216
1217 static int
1218 TIFFAdvanceDirectory(TIFF* tif, uint32* nextdir, toff_t* off)
1219 {
1220     static const char module[] = "TIFFAdvanceDirectory";
1221     uint16 dircount;
1222     if (isMapped(tif))
1223     {
1224         toff_t poff=*nextdir;
1225         if (poff+sizeof(uint16) > tif->tif_size)
1226         {
1227             TIFFError(module, "%s: Error fetching directory count",
1228                       tif->tif_name);
1229             return (0);
1230         }
1231         _TIFFmemcpy(&dircount, tif->tif_base+poff, sizeof (uint16));
1232         if (tif->tif_flags & TIFF_SWAB)
1233             TIFFSwabShort(&dircount);
1234         poff+=sizeof (uint16)+dircount*sizeof (TIFFDirEntry);
1235         if (off != NULL)
1236             *off = poff;
1237         if (((toff_t) (poff+sizeof (uint32))) > tif->tif_size)
1238         {
1239             TIFFError(module, "%s: Error fetching directory link",
1240                       tif->tif_name);
1241             return (0);
1242         }
1243         _TIFFmemcpy(nextdir, tif->tif_base+poff, sizeof (uint32));
1244         if (tif->tif_flags & TIFF_SWAB)
1245             TIFFSwabLong(nextdir);
1246         return (1);
1247     }
1248     else
1249     {
1250         if (!SeekOK(tif, *nextdir) ||
1251             !ReadOK(tif, &dircount, sizeof (uint16))) {
1252             TIFFError(module, "%s: Error fetching directory count",
1253                       tif->tif_name);
1254             return (0);
1255         }
1256         if (tif->tif_flags & TIFF_SWAB)
1257             TIFFSwabShort(&dircount);
1258         if (off != NULL)
1259             *off = TIFFSeekFile(tif,
1260                                 dircount*sizeof (TIFFDirEntry), SEEK_CUR);
1261         else
1262             (void) TIFFSeekFile(tif,
1263                                 dircount*sizeof (TIFFDirEntry), SEEK_CUR);
1264         if (!ReadOK(tif, nextdir, sizeof (uint32))) {
1265             TIFFError(module, "%s: Error fetching directory link",
1266                       tif->tif_name);
1267             return (0);
1268         }
1269         if (tif->tif_flags & TIFF_SWAB)
1270             TIFFSwabLong(nextdir);
1271         return (1);
1272     }
1273 }
1274
1275 /*
1276  * Count the number of directories in a file.
1277  */
1278 tdir_t
1279 TIFFNumberOfDirectories(TIFF* tif)
1280 {
1281     toff_t nextdir = tif->tif_header.tiff_diroff;
1282     tdir_t n = 0;
1283     
1284     while (nextdir != 0 && TIFFAdvanceDirectory(tif, &nextdir, NULL))
1285         n++;
1286     return (n);
1287 }
1288
1289 /*
1290  * Set the n-th directory as the current directory.
1291  * NB: Directories are numbered starting at 0.
1292  */
1293 int
1294 TIFFSetDirectory(TIFF* tif, tdir_t dirn)
1295 {
1296         toff_t nextdir;
1297         tdir_t n;
1298
1299         nextdir = tif->tif_header.tiff_diroff;
1300         for (n = dirn; n > 0 && nextdir != 0; n--)
1301                 if (!TIFFAdvanceDirectory(tif, &nextdir, NULL))
1302                         return (0);
1303         tif->tif_nextdiroff = nextdir;
1304         /*
1305          * Set curdir to the actual directory index.  The
1306          * -1 is because TIFFReadDirectory will increment
1307          * tif_curdir after successfully reading the directory.
1308          */
1309         tif->tif_curdir = (dirn - n) - 1;
1310         /*
1311          * Reset tif_dirnumber counter and start new list of seen directories.
1312          * We need this to prevent IFD loops.
1313          */
1314         tif->tif_dirnumber = 0;
1315         return (TIFFReadDirectory(tif));
1316 }
1317
1318 /*
1319  * Set the current directory to be the directory
1320  * located at the specified file offset.  This interface
1321  * is used mainly to access directories linked with
1322  * the SubIFD tag (e.g. thumbnail images).
1323  */
1324 int
1325 TIFFSetSubDirectory(TIFF* tif, uint32 diroff)
1326 {
1327         tif->tif_nextdiroff = diroff;
1328         /*
1329          * Reset tif_dirnumber counter and start new list of seen directories.
1330          * We need this to prevent IFD loops.
1331          */
1332         tif->tif_dirnumber = 0;
1333         return (TIFFReadDirectory(tif));
1334 }
1335
1336 /*
1337  * Return file offset of the current directory.
1338  */
1339 uint32
1340 TIFFCurrentDirOffset(TIFF* tif)
1341 {
1342         return (tif->tif_diroff);
1343 }
1344
1345 /*
1346  * Return an indication of whether or not we are
1347  * at the last directory in the file.
1348  */
1349 int
1350 TIFFLastDirectory(TIFF* tif)
1351 {
1352         return (tif->tif_nextdiroff == 0);
1353 }
1354
1355 /*
1356  * Unlink the specified directory from the directory chain.
1357  */
1358 int
1359 TIFFUnlinkDirectory(TIFF* tif, tdir_t dirn)
1360 {
1361         static const char module[] = "TIFFUnlinkDirectory";
1362         toff_t nextdir;
1363         toff_t off;
1364         tdir_t n;
1365
1366         if (tif->tif_mode == O_RDONLY) {
1367                 TIFFError(module, "Can not unlink directory in read-only file");
1368                 return (0);
1369         }
1370         /*
1371          * Go to the directory before the one we want
1372          * to unlink and nab the offset of the link
1373          * field we'll need to patch.
1374          */
1375         nextdir = tif->tif_header.tiff_diroff;
1376         off = sizeof (uint16) + sizeof (uint16);
1377         for (n = dirn-1; n > 0; n--) {
1378                 if (nextdir == 0) {
1379                         TIFFError(module, "Directory %d does not exist", dirn);
1380                         return (0);
1381                 }
1382                 if (!TIFFAdvanceDirectory(tif, &nextdir, &off))
1383                         return (0);
1384         }
1385         /*
1386          * Advance to the directory to be unlinked and fetch
1387          * the offset of the directory that follows.
1388          */
1389         if (!TIFFAdvanceDirectory(tif, &nextdir, NULL))
1390                 return (0);
1391         /*
1392          * Go back and patch the link field of the preceding
1393          * directory to point to the offset of the directory
1394          * that follows.
1395          */
1396         (void) TIFFSeekFile(tif, off, SEEK_SET);
1397         if (tif->tif_flags & TIFF_SWAB)
1398                 TIFFSwabLong(&nextdir);
1399         if (!WriteOK(tif, &nextdir, sizeof (uint32))) {
1400                 TIFFError(module, "Error writing directory link");
1401                 return (0);
1402         }
1403         /*
1404          * Leave directory state setup safely.  We don't have
1405          * facilities for doing inserting and removing directories,
1406          * so it's safest to just invalidate everything.  This
1407          * means that the caller can only append to the directory
1408          * chain.
1409          */
1410         (*tif->tif_cleanup)(tif);
1411         if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
1412                 _TIFFfree(tif->tif_rawdata);
1413                 tif->tif_rawdata = NULL;
1414                 tif->tif_rawcc = 0;
1415         }
1416         tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP|TIFF_POSTENCODE);
1417         TIFFFreeDirectory(tif);
1418         TIFFDefaultDirectory(tif);
1419         tif->tif_diroff = 0;                    /* force link on next write */
1420         tif->tif_nextdiroff = 0;                /* next write must be at end */
1421         tif->tif_curoff = 0;
1422         tif->tif_row = (uint32) -1;
1423         tif->tif_curstrip = (tstrip_t) -1;
1424         return (1);
1425 }
1426
1427 /*                      [BFC]
1428  *
1429  * Author: Bruce Cameron <cameron@petris.com>
1430  *
1431  * Set a table of tags that are to be replaced during directory process by the
1432  * 'IGNORE' state - or return TRUE/FALSE for the requested tag such that
1433  * 'ReadDirectory' can use the stored information.
1434  *
1435  * FIXME: this is never used properly. Should be removed in the future.
1436  */
1437 int
1438 TIFFReassignTagToIgnore (enum TIFFIgnoreSense task, int TIFFtagID)
1439 {
1440     static int TIFFignoretags [FIELD_LAST];
1441     static int tagcount = 0 ;
1442     int         i;                                      /* Loop index */
1443     int         j;                                      /* Loop index */
1444
1445     switch (task)
1446     {
1447       case TIS_STORE:
1448         if ( tagcount < (FIELD_LAST - 1) )
1449         {
1450             for ( j = 0 ; j < tagcount ; ++j )
1451             {                                   /* Do not add duplicate tag */
1452                 if ( TIFFignoretags [j] == TIFFtagID )
1453                     return (TRUE) ;
1454             }
1455             TIFFignoretags [tagcount++] = TIFFtagID ;
1456             return (TRUE) ;
1457         }
1458         break ;
1459         
1460       case TIS_EXTRACT:
1461         for ( i = 0 ; i < tagcount ; ++i )
1462         {
1463             if ( TIFFignoretags [i] == TIFFtagID )
1464                 return (TRUE) ;
1465         }
1466         break;
1467         
1468       case TIS_EMPTY:
1469         tagcount = 0 ;                  /* Clear the list */
1470         return (TRUE) ;
1471         
1472       default:
1473         break;
1474     }
1475     
1476     return (FALSE);
1477 }
1478
1479 /* vim: set ts=8 sts=8 sw=8 noet: */