Update to 2.0.0 tree from current Fremantle build
[opencv] / 3rdparty / libtiff / tif_write.c
1 /* $Id: tif_write.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  * Scanline-oriented Write Support
31  */
32 #include "tiffiop.h"
33 #include <stdio.h>
34
35 #define STRIPINCR       20              /* expansion factor on strip array */
36
37 #define WRITECHECKSTRIPS(tif, module)                           \
38         (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module))
39 #define WRITECHECKTILES(tif, module)                            \
40         (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module))
41 #define BUFFERCHECK(tif)                                        \
42         ((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \
43             TIFFWriteBufferSetup((tif), NULL, (tsize_t) -1))
44
45 static  int TIFFGrowStrips(TIFF*, int, const char*);
46 static  int TIFFAppendToStrip(TIFF*, tstrip_t, tidata_t, tsize_t);
47
48 int
49 TIFFWriteScanline(TIFF* tif, tdata_t buf, uint32 row, tsample_t sample)
50 {
51         static const char module[] = "TIFFWriteScanline";
52         register TIFFDirectory *td;
53         int status, imagegrew = 0;
54         tstrip_t strip;
55
56         if (!WRITECHECKSTRIPS(tif, module))
57                 return (-1);
58         /*
59          * Handle delayed allocation of data buffer.  This
60          * permits it to be sized more intelligently (using
61          * directory information).
62          */
63         if (!BUFFERCHECK(tif))
64                 return (-1);
65         td = &tif->tif_dir;
66         /*
67          * Extend image length if needed
68          * (but only for PlanarConfig=1).
69          */
70         if (row >= td->td_imagelength) {        /* extend image */
71                 if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
72                         TIFFError(tif->tif_name,
73                 "Can not change \"ImageLength\" when using separate planes");
74                         return (-1);
75                 }
76                 td->td_imagelength = row+1;
77                 imagegrew = 1;
78         }
79         /*
80          * Calculate strip and check for crossings.
81          */
82         if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
83                 if (sample >= td->td_samplesperpixel) {
84                         TIFFError(tif->tif_name,
85                             "%d: Sample out of range, max %d",
86                             sample, td->td_samplesperpixel);
87                         return (-1);
88                 }
89                 strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
90         } else
91                 strip = row / td->td_rowsperstrip;
92         if (strip != tif->tif_curstrip) {
93                 /*
94                  * Changing strips -- flush any data present.
95                  */
96                 if (!TIFFFlushData(tif))
97                         return (-1);
98                 tif->tif_curstrip = strip;
99                 /*
100                  * Watch out for a growing image.  The value of
101                  * strips/image will initially be 1 (since it
102                  * can't be deduced until the imagelength is known).
103                  */
104                 if (strip >= td->td_stripsperimage && imagegrew)
105                         td->td_stripsperimage =
106                             TIFFhowmany(td->td_imagelength,td->td_rowsperstrip);
107                 tif->tif_row =
108                     (strip % td->td_stripsperimage) * td->td_rowsperstrip;
109                 if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
110                         if (!(*tif->tif_setupencode)(tif))
111                                 return (-1);
112                         tif->tif_flags |= TIFF_CODERSETUP;
113                 }
114         
115                 tif->tif_rawcc = 0;
116                 tif->tif_rawcp = tif->tif_rawdata;
117
118                 if( td->td_stripbytecount[strip] > 0 )
119                 {
120                         /* if we are writing over existing tiles, zero length */
121                         td->td_stripbytecount[strip] = 0;
122
123                         /* this forces TIFFAppendToStrip() to do a seek */
124                         tif->tif_curoff = 0;
125                 }
126
127                 if (!(*tif->tif_preencode)(tif, sample))
128                         return (-1);
129                 tif->tif_flags |= TIFF_POSTENCODE;
130         }
131         /*
132          * Check strip array to make sure there's space.
133          * We don't support dynamically growing files that
134          * have data organized in separate bitplanes because
135          * it's too painful.  In that case we require that
136          * the imagelength be set properly before the first
137          * write (so that the strips array will be fully
138          * allocated above).
139          */
140         if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
141                 return (-1);
142         /*
143          * Ensure the write is either sequential or at the
144          * beginning of a strip (or that we can randomly
145          * access the data -- i.e. no encoding).
146          */
147         if (row != tif->tif_row) {
148                 if (row < tif->tif_row) {
149                         /*
150                          * Moving backwards within the same strip:
151                          * backup to the start and then decode
152                          * forward (below).
153                          */
154                         tif->tif_row = (strip % td->td_stripsperimage) *
155                             td->td_rowsperstrip;
156                         tif->tif_rawcp = tif->tif_rawdata;
157                 }
158                 /*
159                  * Seek forward to the desired row.
160                  */
161                 if (!(*tif->tif_seek)(tif, row - tif->tif_row))
162                         return (-1);
163                 tif->tif_row = row;
164         }
165
166         /* swab if needed - note that source buffer will be altered */
167         tif->tif_postdecode( tif, (tidata_t) buf, tif->tif_scanlinesize );
168
169         status = (*tif->tif_encoderow)(tif, (tidata_t) buf,
170             tif->tif_scanlinesize, sample);
171
172         /* we are now poised at the beginning of the next row */
173         tif->tif_row = row + 1;
174         return (status);
175 }
176
177 /*
178  * Encode the supplied data and write it to the
179  * specified strip.
180  *
181  * NB: Image length must be setup before writing.
182  */
183 tsize_t
184 TIFFWriteEncodedStrip(TIFF* tif, tstrip_t strip, tdata_t data, tsize_t cc)
185 {
186         static const char module[] = "TIFFWriteEncodedStrip";
187         TIFFDirectory *td = &tif->tif_dir;
188         tsample_t sample;
189
190         if (!WRITECHECKSTRIPS(tif, module))
191                 return ((tsize_t) -1);
192         /*
193          * Check strip array to make sure there's space.
194          * We don't support dynamically growing files that
195          * have data organized in separate bitplanes because
196          * it's too painful.  In that case we require that
197          * the imagelength be set properly before the first
198          * write (so that the strips array will be fully
199          * allocated above).
200          */
201         if (strip >= td->td_nstrips) {
202                 if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
203                         TIFFError(tif->tif_name,
204                 "Can not grow image by strips when using separate planes");
205                         return ((tsize_t) -1);
206                 }
207                 if (!TIFFGrowStrips(tif, 1, module))
208                         return ((tsize_t) -1);
209                 td->td_stripsperimage =
210                     TIFFhowmany(td->td_imagelength, td->td_rowsperstrip);
211         }
212         /*
213          * Handle delayed allocation of data buffer.  This
214          * permits it to be sized according to the directory
215          * info.
216          */
217         if (!BUFFERCHECK(tif))
218                 return ((tsize_t) -1);
219         tif->tif_curstrip = strip;
220         tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
221         if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
222                 if (!(*tif->tif_setupencode)(tif))
223                         return ((tsize_t) -1);
224                 tif->tif_flags |= TIFF_CODERSETUP;
225         }
226         
227         tif->tif_rawcc = 0;
228         tif->tif_rawcp = tif->tif_rawdata;
229
230         if( td->td_stripbytecount[strip] > 0 )
231         {
232             /* if we are writing over existing tiles, zero length. */
233             td->td_stripbytecount[strip] = 0;
234
235             /* this forces TIFFAppendToStrip() to do a seek */
236             tif->tif_curoff = 0;
237         }
238         
239         tif->tif_flags &= ~TIFF_POSTENCODE;
240         sample = (tsample_t)(strip / td->td_stripsperimage);
241         if (!(*tif->tif_preencode)(tif, sample))
242                 return ((tsize_t) -1);
243
244         /* swab if needed - note that source buffer will be altered */
245         tif->tif_postdecode( tif, (tidata_t) data, cc );
246
247         if (!(*tif->tif_encodestrip)(tif, (tidata_t) data, cc, sample))
248                 return ((tsize_t) 0);
249         if (!(*tif->tif_postencode)(tif))
250                 return ((tsize_t) -1);
251         if (!isFillOrder(tif, td->td_fillorder) &&
252             (tif->tif_flags & TIFF_NOBITREV) == 0)
253                 TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
254         if (tif->tif_rawcc > 0 &&
255             !TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
256                 return ((tsize_t) -1);
257         tif->tif_rawcc = 0;
258         tif->tif_rawcp = tif->tif_rawdata;
259         return (cc);
260 }
261
262 /*
263  * Write the supplied data to the specified strip.
264  *
265  * NB: Image length must be setup before writing.
266  */
267 tsize_t
268 TIFFWriteRawStrip(TIFF* tif, tstrip_t strip, tdata_t data, tsize_t cc)
269 {
270         static const char module[] = "TIFFWriteRawStrip";
271         TIFFDirectory *td = &tif->tif_dir;
272
273         if (!WRITECHECKSTRIPS(tif, module))
274                 return ((tsize_t) -1);
275         /*
276          * Check strip array to make sure there's space.
277          * We don't support dynamically growing files that
278          * have data organized in separate bitplanes because
279          * it's too painful.  In that case we require that
280          * the imagelength be set properly before the first
281          * write (so that the strips array will be fully
282          * allocated above).
283          */
284         if (strip >= td->td_nstrips) {
285                 if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
286                         TIFFError(tif->tif_name,
287                 "Can not grow image by strips when using separate planes");
288                         return ((tsize_t) -1);
289                 }
290                 /*
291                  * Watch out for a growing image.  The value of
292                  * strips/image will initially be 1 (since it
293                  * can't be deduced until the imagelength is known).
294                  */
295                 if (strip >= td->td_stripsperimage)
296                         td->td_stripsperimage =
297                             TIFFhowmany(td->td_imagelength,td->td_rowsperstrip);
298                 if (!TIFFGrowStrips(tif, 1, module))
299                         return ((tsize_t) -1);
300         }
301         tif->tif_curstrip = strip;
302         tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
303         return (TIFFAppendToStrip(tif, strip, (tidata_t) data, cc) ?
304             cc : (tsize_t) -1);
305 }
306
307 /*
308  * Write and compress a tile of data.  The
309  * tile is selected by the (x,y,z,s) coordinates.
310  */
311 tsize_t
312 TIFFWriteTile(TIFF* tif,
313     tdata_t buf, uint32 x, uint32 y, uint32 z, tsample_t s)
314 {
315         if (!TIFFCheckTile(tif, x, y, z, s))
316                 return (-1);
317         /*
318          * NB: A tile size of -1 is used instead of tif_tilesize knowing
319          *     that TIFFWriteEncodedTile will clamp this to the tile size.
320          *     This is done because the tile size may not be defined until
321          *     after the output buffer is setup in TIFFWriteBufferSetup.
322          */
323         return (TIFFWriteEncodedTile(tif,
324             TIFFComputeTile(tif, x, y, z, s), buf, (tsize_t) -1));
325 }
326
327 /*
328  * Encode the supplied data and write it to the
329  * specified tile.  There must be space for the
330  * data.  The function clamps individual writes
331  * to a tile to the tile size, but does not (and
332  * can not) check that multiple writes to the same
333  * tile do not write more than tile size data.
334  *
335  * NB: Image length must be setup before writing; this
336  *     interface does not support automatically growing
337  *     the image on each write (as TIFFWriteScanline does).
338  */
339 tsize_t
340 TIFFWriteEncodedTile(TIFF* tif, ttile_t tile, tdata_t data, tsize_t cc)
341 {
342         static const char module[] = "TIFFWriteEncodedTile";
343         TIFFDirectory *td;
344         tsample_t sample;
345
346         if (!WRITECHECKTILES(tif, module))
347                 return ((tsize_t) -1);
348         td = &tif->tif_dir;
349         if (tile >= td->td_nstrips) {
350                 TIFFError(module, "%s: Tile %lu out of range, max %lu",
351                     tif->tif_name, (unsigned long) tile, (unsigned long) td->td_nstrips);
352                 return ((tsize_t) -1);
353         }
354         /*
355          * Handle delayed allocation of data buffer.  This
356          * permits it to be sized more intelligently (using
357          * directory information).
358          */
359         if (!BUFFERCHECK(tif))
360                 return ((tsize_t) -1);
361         tif->tif_curtile = tile;
362
363         tif->tif_rawcc = 0;
364         tif->tif_rawcp = tif->tif_rawdata;
365
366         if( td->td_stripbytecount[tile] > 0 )
367         {
368             /* if we are writing over existing tiles, zero length. */
369             td->td_stripbytecount[tile] = 0;
370
371             /* this forces TIFFAppendToStrip() to do a seek */
372             tif->tif_curoff = 0;
373         }
374         
375         /* 
376          * Compute tiles per row & per column to compute
377          * current row and column
378          */
379         tif->tif_row = (tile % TIFFhowmany(td->td_imagelength, td->td_tilelength))
380                 * td->td_tilelength;
381         tif->tif_col = (tile % TIFFhowmany(td->td_imagewidth, td->td_tilewidth))
382                 * td->td_tilewidth;
383
384         if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
385                 if (!(*tif->tif_setupencode)(tif))
386                         return ((tsize_t) -1);
387                 tif->tif_flags |= TIFF_CODERSETUP;
388         }
389         tif->tif_flags &= ~TIFF_POSTENCODE;
390         sample = (tsample_t)(tile/td->td_stripsperimage);
391         if (!(*tif->tif_preencode)(tif, sample))
392                 return ((tsize_t) -1);
393         /*
394          * Clamp write amount to the tile size.  This is mostly
395          * done so that callers can pass in some large number
396          * (e.g. -1) and have the tile size used instead.
397          */
398         if ( cc < 1 || cc > tif->tif_tilesize)
399                 cc = tif->tif_tilesize;
400
401         /* swab if needed - note that source buffer will be altered */
402         tif->tif_postdecode( tif, (tidata_t) data, cc );
403
404         if (!(*tif->tif_encodetile)(tif, (tidata_t) data, cc, sample))
405                 return ((tsize_t) 0);
406         if (!(*tif->tif_postencode)(tif))
407                 return ((tsize_t) -1);
408         if (!isFillOrder(tif, td->td_fillorder) &&
409             (tif->tif_flags & TIFF_NOBITREV) == 0)
410                 TIFFReverseBits((unsigned char *)tif->tif_rawdata, tif->tif_rawcc);
411         if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,
412             tif->tif_rawdata, tif->tif_rawcc))
413                 return ((tsize_t) -1);
414         tif->tif_rawcc = 0;
415         tif->tif_rawcp = tif->tif_rawdata;
416         return (cc);
417 }
418
419 /*
420  * Write the supplied data to the specified strip.
421  * There must be space for the data; we don't check
422  * if strips overlap!
423  *
424  * NB: Image length must be setup before writing; this
425  *     interface does not support automatically growing
426  *     the image on each write (as TIFFWriteScanline does).
427  */
428 tsize_t
429 TIFFWriteRawTile(TIFF* tif, ttile_t tile, tdata_t data, tsize_t cc)
430 {
431         static const char module[] = "TIFFWriteRawTile";
432
433         if (!WRITECHECKTILES(tif, module))
434                 return ((tsize_t) -1);
435         if (tile >= tif->tif_dir.td_nstrips) {
436                 TIFFError(module, "%s: Tile %lu out of range, max %lu",
437                     tif->tif_name, (unsigned long) tile,
438                     (unsigned long) tif->tif_dir.td_nstrips);
439                 return ((tsize_t) -1);
440         }
441         return (TIFFAppendToStrip(tif, tile, (tidata_t) data, cc) ?
442             cc : (tsize_t) -1);
443 }
444
445 #define isUnspecified(tif, f) \
446     (TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
447
448 int
449 TIFFSetupStrips(TIFF* tif)
450 {
451         TIFFDirectory* td = &tif->tif_dir;
452
453         if (isTiled(tif))
454                 td->td_stripsperimage =
455                     isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
456                         td->td_samplesperpixel : TIFFNumberOfTiles(tif);
457         else
458                 td->td_stripsperimage =
459                     isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
460                         td->td_samplesperpixel : TIFFNumberOfStrips(tif);
461         td->td_nstrips = td->td_stripsperimage;
462         if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
463                 td->td_stripsperimage /= td->td_samplesperpixel;
464         td->td_stripoffset = (uint32 *)
465             _TIFFmalloc(td->td_nstrips * sizeof (uint32));
466         td->td_stripbytecount = (uint32 *)
467             _TIFFmalloc(td->td_nstrips * sizeof (uint32));
468         if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
469                 return (0);
470         /*
471          * Place data at the end-of-file
472          * (by setting offsets to zero).
473          */
474         _TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint32));
475         _TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint32));
476         TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
477         TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
478         return (1);
479 }
480 #undef isUnspecified
481
482 /*
483  * Verify file is writable and that the directory
484  * information is setup properly.  In doing the latter
485  * we also "freeze" the state of the directory so
486  * that important information is not changed.
487  */
488 int
489 TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
490 {
491         if (tif->tif_mode == O_RDONLY) {
492                 TIFFError(module, "%s: File not open for writing",
493                     tif->tif_name);
494                 return (0);
495         }
496         if (tiles ^ isTiled(tif)) {
497                 TIFFError(tif->tif_name, tiles ?
498                     "Can not write tiles to a stripped image" :
499                     "Can not write scanlines to a tiled image");
500                 return (0);
501         }
502         
503         /*
504          * On the first write verify all the required information
505          * has been setup and initialize any data structures that
506          * had to wait until directory information was set.
507          * Note that a lot of our work is assumed to remain valid
508          * because we disallow any of the important parameters
509          * from changing after we start writing (i.e. once
510          * TIFF_BEENWRITING is set, TIFFSetField will only allow
511          * the image's length to be changed).
512          */
513         if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
514                 TIFFError(module,
515                     "%s: Must set \"ImageWidth\" before writing data",
516                     tif->tif_name);
517                 return (0);
518         }
519         if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
520                 TIFFError(module,
521             "%s: Must set \"PlanarConfiguration\" before writing data",
522                     tif->tif_name);
523                 return (0);
524         }
525         if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) {
526                 tif->tif_dir.td_nstrips = 0;
527                 TIFFError(module, "%s: No space for %s arrays",
528                     tif->tif_name, isTiled(tif) ? "tile" : "strip");
529                 return (0);
530         }
531         tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
532         tif->tif_scanlinesize = TIFFScanlineSize(tif);
533         tif->tif_flags |= TIFF_BEENWRITING;
534         return (1);
535 }
536
537 /*
538  * Setup the raw data buffer used for encoding.
539  */
540 int
541 TIFFWriteBufferSetup(TIFF* tif, tdata_t bp, tsize_t size)
542 {
543         static const char module[] = "TIFFWriteBufferSetup";
544
545         if (tif->tif_rawdata) {
546                 if (tif->tif_flags & TIFF_MYBUFFER) {
547                         _TIFFfree(tif->tif_rawdata);
548                         tif->tif_flags &= ~TIFF_MYBUFFER;
549                 }
550                 tif->tif_rawdata = NULL;
551         }
552         if (size == (tsize_t) -1) {
553                 size = (isTiled(tif) ?
554                     tif->tif_tilesize : TIFFStripSize(tif));
555                 /*
556                  * Make raw data buffer at least 8K
557                  */
558                 if (size < 8*1024)
559                         size = 8*1024;
560                 bp = NULL;                      /* NB: force malloc */
561         }
562         if (bp == NULL) {
563                 bp = _TIFFmalloc(size);
564                 if (bp == NULL) {
565                         TIFFError(module, "%s: No space for output buffer",
566                             tif->tif_name);
567                         return (0);
568                 }
569                 tif->tif_flags |= TIFF_MYBUFFER;
570         } else
571                 tif->tif_flags &= ~TIFF_MYBUFFER;
572         tif->tif_rawdata = (tidata_t) bp;
573         tif->tif_rawdatasize = size;
574         tif->tif_rawcc = 0;
575         tif->tif_rawcp = tif->tif_rawdata;
576         tif->tif_flags |= TIFF_BUFFERSETUP;
577         return (1);
578 }
579
580 /*
581  * Grow the strip data structures by delta strips.
582  */
583 static int
584 TIFFGrowStrips(TIFF* tif, int delta, const char* module)
585 {
586         TIFFDirectory   *td = &tif->tif_dir;
587         uint32          *new_stripoffset, *new_stripbytecount;
588
589         assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
590         new_stripoffset = (uint32*)_TIFFrealloc(td->td_stripoffset,
591                 (td->td_nstrips + delta) * sizeof (uint32));
592         new_stripbytecount = (uint32*)_TIFFrealloc(td->td_stripbytecount,
593                 (td->td_nstrips + delta) * sizeof (uint32));
594         if (new_stripoffset == NULL || new_stripbytecount == NULL) {
595                 if (new_stripoffset)
596                         _TIFFfree(new_stripoffset);
597                 if (new_stripbytecount)
598                         _TIFFfree(new_stripbytecount);
599                 td->td_nstrips = 0;
600                 TIFFError(module, "%s: No space to expand strip arrays",
601                           tif->tif_name);
602                 return (0);
603         }
604         td->td_stripoffset = new_stripoffset;
605         td->td_stripbytecount = new_stripbytecount;
606         _TIFFmemset(td->td_stripoffset + td->td_nstrips,
607                     0, delta*sizeof (uint32));
608         _TIFFmemset(td->td_stripbytecount + td->td_nstrips,
609                     0, delta*sizeof (uint32));
610         td->td_nstrips += delta;
611         return (1);
612 }
613
614 /*
615  * Append the data to the specified strip.
616  */
617 static int
618 TIFFAppendToStrip(TIFF* tif, tstrip_t strip, tidata_t data, tsize_t cc)
619 {
620         TIFFDirectory *td = &tif->tif_dir;
621         static const char module[] = "TIFFAppendToStrip";
622
623         if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
624                 /*
625                  * No current offset, set the current strip.
626                  */
627                 assert(td->td_nstrips > 0);
628                 if (td->td_stripoffset[strip] != 0) {
629                         /*
630                          * Prevent overlapping of the data chunks. We need
631                          * this to enable in place updating of the compressed
632                          * images. Larger blocks will be moved at the end of
633                          * the file without any optimization of the spare
634                          * space, so such scheme is not too much effective.
635                          */
636                         if (td->td_stripbytecountsorted) {
637                                 if (strip == td->td_nstrips - 1
638                                     || td->td_stripoffset[strip + 1] <
639                                         td->td_stripoffset[strip] + cc) {
640                                         td->td_stripoffset[strip] =
641                                                 TIFFSeekFile(tif, (toff_t)0,
642                                                              SEEK_END);
643                                 }
644                         } else {
645                                 tstrip_t i;
646                                 for (i = 0; i < td->td_nstrips; i++) {
647                                         if (td->td_stripoffset[i] > 
648                                                 td->td_stripoffset[strip]
649                                             && td->td_stripoffset[i] <
650                                                 td->td_stripoffset[strip] + cc) {
651                                                 td->td_stripoffset[strip] =
652                                                         TIFFSeekFile(tif,
653                                                                      (toff_t)0,
654                                                                      SEEK_END);
655                                         }
656                                 }
657                         }
658
659                         if (!SeekOK(tif, td->td_stripoffset[strip])) {
660                                 TIFFError(module,
661                                           "%s: Seek error at scanline %lu",
662                                           tif->tif_name,
663                                           (unsigned long)tif->tif_row);
664                                 return (0);
665                         }
666                 } else
667                         td->td_stripoffset[strip] =
668                             TIFFSeekFile(tif, (toff_t) 0, SEEK_END);
669                 tif->tif_curoff = td->td_stripoffset[strip];
670         }
671
672         if (!WriteOK(tif, data, cc)) {
673                 TIFFError(module, "%s: Write error at scanline %lu",
674                     tif->tif_name, (unsigned long) tif->tif_row);
675                 return (0);
676         }
677         tif->tif_curoff += cc;
678         td->td_stripbytecount[strip] += cc;
679         return (1);
680 }
681
682 /*
683  * Internal version of TIFFFlushData that can be
684  * called by ``encodestrip routines'' w/o concern
685  * for infinite recursion.
686  */
687 int
688 TIFFFlushData1(TIFF* tif)
689 {
690         if (tif->tif_rawcc > 0) {
691                 if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
692                     (tif->tif_flags & TIFF_NOBITREV) == 0)
693                         TIFFReverseBits((unsigned char *)tif->tif_rawdata,
694                             tif->tif_rawcc);
695                 if (!TIFFAppendToStrip(tif,
696                     isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
697                     tif->tif_rawdata, tif->tif_rawcc))
698                         return (0);
699                 tif->tif_rawcc = 0;
700                 tif->tif_rawcp = tif->tif_rawdata;
701         }
702         return (1);
703 }
704
705 /*
706  * Set the current write offset.  This should only be
707  * used to set the offset to a known previous location
708  * (very carefully), or to 0 so that the next write gets
709  * appended to the end of the file.
710  */
711 void
712 TIFFSetWriteOffset(TIFF* tif, toff_t off)
713 {
714         tif->tif_curoff = off;
715 }
716
717 /* vim: set ts=8 sts=8 sw=8 noet: */