1 /* $Id: tif_write.c,v 1.1 2005-06-17 13:54:52 vp153 Exp $ */
4 * Copyright (c) 1988-1997 Sam Leffler
5 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
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.
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.
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
30 * Scanline-oriented Write Support
35 #define STRIPINCR 20 /* expansion factor on strip array */
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))
45 static int TIFFGrowStrips(TIFF*, int, const char*);
46 static int TIFFAppendToStrip(TIFF*, tstrip_t, tidata_t, tsize_t);
49 TIFFWriteScanline(TIFF* tif, tdata_t buf, uint32 row, tsample_t sample)
51 static const char module[] = "TIFFWriteScanline";
52 register TIFFDirectory *td;
53 int status, imagegrew = 0;
56 if (!WRITECHECKSTRIPS(tif, module))
59 * Handle delayed allocation of data buffer. This
60 * permits it to be sized more intelligently (using
61 * directory information).
63 if (!BUFFERCHECK(tif))
67 * Extend image length if needed
68 * (but only for PlanarConfig=1).
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");
76 td->td_imagelength = row+1;
80 * Calculate strip and check for crossings.
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);
89 strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
91 strip = row / td->td_rowsperstrip;
92 if (strip != tif->tif_curstrip) {
94 * Changing strips -- flush any data present.
96 if (!TIFFFlushData(tif))
98 tif->tif_curstrip = strip;
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).
104 if (strip >= td->td_stripsperimage && imagegrew)
105 td->td_stripsperimage =
106 TIFFhowmany(td->td_imagelength,td->td_rowsperstrip);
108 (strip % td->td_stripsperimage) * td->td_rowsperstrip;
109 if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
110 if (!(*tif->tif_setupencode)(tif))
112 tif->tif_flags |= TIFF_CODERSETUP;
116 tif->tif_rawcp = tif->tif_rawdata;
118 if( td->td_stripbytecount[strip] > 0 )
120 /* if we are writing over existing tiles, zero length */
121 td->td_stripbytecount[strip] = 0;
123 /* this forces TIFFAppendToStrip() to do a seek */
127 if (!(*tif->tif_preencode)(tif, sample))
129 tif->tif_flags |= TIFF_POSTENCODE;
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
140 if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
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).
147 if (row != tif->tif_row) {
148 if (row < tif->tif_row) {
150 * Moving backwards within the same strip:
151 * backup to the start and then decode
154 tif->tif_row = (strip % td->td_stripsperimage) *
156 tif->tif_rawcp = tif->tif_rawdata;
159 * Seek forward to the desired row.
161 if (!(*tif->tif_seek)(tif, row - tif->tif_row))
166 /* swab if needed - note that source buffer will be altered */
167 tif->tif_postdecode( tif, (tidata_t) buf, tif->tif_scanlinesize );
169 status = (*tif->tif_encoderow)(tif, (tidata_t) buf,
170 tif->tif_scanlinesize, sample);
172 /* we are now poised at the beginning of the next row */
173 tif->tif_row = row + 1;
178 * Encode the supplied data and write it to the
181 * NB: Image length must be setup before writing.
184 TIFFWriteEncodedStrip(TIFF* tif, tstrip_t strip, tdata_t data, tsize_t cc)
186 static const char module[] = "TIFFWriteEncodedStrip";
187 TIFFDirectory *td = &tif->tif_dir;
190 if (!WRITECHECKSTRIPS(tif, module))
191 return ((tsize_t) -1);
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
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);
207 if (!TIFFGrowStrips(tif, 1, module))
208 return ((tsize_t) -1);
209 td->td_stripsperimage =
210 TIFFhowmany(td->td_imagelength, td->td_rowsperstrip);
213 * Handle delayed allocation of data buffer. This
214 * permits it to be sized according to the directory
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;
228 tif->tif_rawcp = tif->tif_rawdata;
230 if( td->td_stripbytecount[strip] > 0 )
232 /* if we are writing over existing tiles, zero length. */
233 td->td_stripbytecount[strip] = 0;
235 /* this forces TIFFAppendToStrip() to do a seek */
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);
244 /* swab if needed - note that source buffer will be altered */
245 tif->tif_postdecode( tif, (tidata_t) data, cc );
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);
258 tif->tif_rawcp = tif->tif_rawdata;
263 * Write the supplied data to the specified strip.
265 * NB: Image length must be setup before writing.
268 TIFFWriteRawStrip(TIFF* tif, tstrip_t strip, tdata_t data, tsize_t cc)
270 static const char module[] = "TIFFWriteRawStrip";
271 TIFFDirectory *td = &tif->tif_dir;
273 if (!WRITECHECKSTRIPS(tif, module))
274 return ((tsize_t) -1);
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
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);
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).
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);
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) ?
308 * Write and compress a tile of data. The
309 * tile is selected by the (x,y,z,s) coordinates.
312 TIFFWriteTile(TIFF* tif,
313 tdata_t buf, uint32 x, uint32 y, uint32 z, tsample_t s)
315 if (!TIFFCheckTile(tif, x, y, z, s))
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.
323 return (TIFFWriteEncodedTile(tif,
324 TIFFComputeTile(tif, x, y, z, s), buf, (tsize_t) -1));
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.
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).
340 TIFFWriteEncodedTile(TIFF* tif, ttile_t tile, tdata_t data, tsize_t cc)
342 static const char module[] = "TIFFWriteEncodedTile";
346 if (!WRITECHECKTILES(tif, module))
347 return ((tsize_t) -1);
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);
355 * Handle delayed allocation of data buffer. This
356 * permits it to be sized more intelligently (using
357 * directory information).
359 if (!BUFFERCHECK(tif))
360 return ((tsize_t) -1);
361 tif->tif_curtile = tile;
364 tif->tif_rawcp = tif->tif_rawdata;
366 if( td->td_stripbytecount[tile] > 0 )
368 /* if we are writing over existing tiles, zero length. */
369 td->td_stripbytecount[tile] = 0;
371 /* this forces TIFFAppendToStrip() to do a seek */
376 * Compute tiles per row & per column to compute
377 * current row and column
379 tif->tif_row = (tile % TIFFhowmany(td->td_imagelength, td->td_tilelength))
381 tif->tif_col = (tile % TIFFhowmany(td->td_imagewidth, td->td_tilewidth))
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;
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);
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.
398 if ( cc < 1 || cc > tif->tif_tilesize)
399 cc = tif->tif_tilesize;
401 /* swab if needed - note that source buffer will be altered */
402 tif->tif_postdecode( tif, (tidata_t) data, cc );
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);
415 tif->tif_rawcp = tif->tif_rawdata;
420 * Write the supplied data to the specified strip.
421 * There must be space for the data; we don't check
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).
429 TIFFWriteRawTile(TIFF* tif, ttile_t tile, tdata_t data, tsize_t cc)
431 static const char module[] = "TIFFWriteRawTile";
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);
441 return (TIFFAppendToStrip(tif, tile, (tidata_t) data, cc) ?
445 #define isUnspecified(tif, f) \
446 (TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0)
449 TIFFSetupStrips(TIFF* tif)
451 TIFFDirectory* td = &tif->tif_dir;
454 td->td_stripsperimage =
455 isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
456 td->td_samplesperpixel : TIFFNumberOfTiles(tif);
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)
471 * Place data at the end-of-file
472 * (by setting offsets to zero).
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);
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.
489 TIFFWriteCheck(TIFF* tif, int tiles, const char* module)
491 if (tif->tif_mode == O_RDONLY) {
492 TIFFError(module, "%s: File not open for writing",
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");
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).
513 if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
515 "%s: Must set \"ImageWidth\" before writing data",
519 if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
521 "%s: Must set \"PlanarConfiguration\" before writing data",
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");
531 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
532 tif->tif_scanlinesize = TIFFScanlineSize(tif);
533 tif->tif_flags |= TIFF_BEENWRITING;
538 * Setup the raw data buffer used for encoding.
541 TIFFWriteBufferSetup(TIFF* tif, tdata_t bp, tsize_t size)
543 static const char module[] = "TIFFWriteBufferSetup";
545 if (tif->tif_rawdata) {
546 if (tif->tif_flags & TIFF_MYBUFFER) {
547 _TIFFfree(tif->tif_rawdata);
548 tif->tif_flags &= ~TIFF_MYBUFFER;
550 tif->tif_rawdata = NULL;
552 if (size == (tsize_t) -1) {
553 size = (isTiled(tif) ?
554 tif->tif_tilesize : TIFFStripSize(tif));
556 * Make raw data buffer at least 8K
560 bp = NULL; /* NB: force malloc */
563 bp = _TIFFmalloc(size);
565 TIFFError(module, "%s: No space for output buffer",
569 tif->tif_flags |= TIFF_MYBUFFER;
571 tif->tif_flags &= ~TIFF_MYBUFFER;
572 tif->tif_rawdata = (tidata_t) bp;
573 tif->tif_rawdatasize = size;
575 tif->tif_rawcp = tif->tif_rawdata;
576 tif->tif_flags |= TIFF_BUFFERSETUP;
581 * Grow the strip data structures by delta strips.
584 TIFFGrowStrips(TIFF* tif, int delta, const char* module)
586 TIFFDirectory *td = &tif->tif_dir;
587 uint32 *new_stripoffset, *new_stripbytecount;
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) {
596 _TIFFfree(new_stripoffset);
597 if (new_stripbytecount)
598 _TIFFfree(new_stripbytecount);
600 TIFFError(module, "%s: No space to expand strip arrays",
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;
615 * Append the data to the specified strip.
618 TIFFAppendToStrip(TIFF* tif, tstrip_t strip, tidata_t data, tsize_t cc)
620 TIFFDirectory *td = &tif->tif_dir;
621 static const char module[] = "TIFFAppendToStrip";
623 if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) {
625 * No current offset, set the current strip.
627 assert(td->td_nstrips > 0);
628 if (td->td_stripoffset[strip] != 0) {
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.
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,
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] =
659 if (!SeekOK(tif, td->td_stripoffset[strip])) {
661 "%s: Seek error at scanline %lu",
663 (unsigned long)tif->tif_row);
667 td->td_stripoffset[strip] =
668 TIFFSeekFile(tif, (toff_t) 0, SEEK_END);
669 tif->tif_curoff = td->td_stripoffset[strip];
672 if (!WriteOK(tif, data, cc)) {
673 TIFFError(module, "%s: Write error at scanline %lu",
674 tif->tif_name, (unsigned long) tif->tif_row);
677 tif->tif_curoff += cc;
678 td->td_stripbytecount[strip] += cc;
683 * Internal version of TIFFFlushData that can be
684 * called by ``encodestrip routines'' w/o concern
685 * for infinite recursion.
688 TIFFFlushData1(TIFF* tif)
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,
695 if (!TIFFAppendToStrip(tif,
696 isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip,
697 tif->tif_rawdata, tif->tif_rawcc))
700 tif->tif_rawcp = tif->tif_rawdata;
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.
712 TIFFSetWriteOffset(TIFF* tif, toff_t off)
714 tif->tif_curoff = off;
717 /* vim: set ts=8 sts=8 sw=8 noet: */