1/* PDFlib GmbH cvsid: $Id: tif_read.c 14574 2005-10-29 16:27:43Z bonefish $ */
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 * Scanline-oriented Read Support
30 */
31#include "tiffiop.h"
32#include <stdio.h>
33#include <assert.h>
34
35static	int TIFFFillStrip(TIFF*, tstrip_t);
36static	int TIFFFillTile(TIFF*, ttile_t);
37static	int TIFFStartStrip(TIFF*, tstrip_t);
38static	int TIFFStartTile(TIFF*, ttile_t);
39static	int TIFFCheckRead(TIFF*, int);
40
41#define	NOSTRIP	((tstrip_t) -1)			/* undefined state */
42#define	NOTILE	((ttile_t) -1)			/* undefined state */
43
44/*
45 * Seek to a random row+sample in a file.
46 */
47static int
48TIFFSeek(TIFF* tif, uint32 row, tsample_t sample)
49{
50	register TIFFDirectory *td = &tif->tif_dir;
51	tstrip_t strip;
52
53	if (row >= td->td_imagelength) {	/* out of range */
54		TIFFError(tif->tif_name, "%lu: Row out of range, max %lu",
55		    (tif_long) row, (tif_long) td->td_imagelength);
56		return (0);
57	}
58	if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
59		if (sample >= td->td_samplesperpixel) {
60			TIFFError(tif->tif_name,
61			    "%lu: Sample out of range, max %lu",
62			    (tif_long)sample,(tif_long)td->td_samplesperpixel);
63			return (0);
64		}
65		strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip;
66	} else
67		strip = row / td->td_rowsperstrip;
68	if (strip != tif->tif_curstrip) { 	/* different strip, refill */
69		if (!TIFFFillStrip(tif, strip))
70			return (0);
71	} else if (row < tif->tif_row) {
72		/*
73		 * Moving backwards within the same strip: backup
74		 * to the start and then decode forward (below).
75		 *
76		 * NB: If you're planning on lots of random access within a
77		 * strip, it's better to just read and decode the entire
78		 * strip, and then access the decoded data in a random fashion.
79		 */
80		if (!TIFFStartStrip(tif, strip))
81			return (0);
82	}
83	if (row != tif->tif_row) {
84		/*
85		 * Seek forward to the desired row.
86		 */
87		if (!(*tif->tif_seek)(tif, row - tif->tif_row))
88			return (0);
89		tif->tif_row = row;
90	}
91	return (1);
92}
93
94int
95TIFFReadScanline(TIFF* tif, tdata_t buf, uint32 row, tsample_t sample)
96{
97	int e;
98
99	if (!TIFFCheckRead(tif, 0))
100		return (-1);
101	if( (e = TIFFSeek(tif, row, sample)) != 0) {
102		/*
103		 * Decompress desired row into user buffer.
104		 */
105		e = (*tif->tif_decoderow)
106		    (tif, (tidata_t) buf, tif->tif_scanlinesize, sample);
107		tif->tif_row++;
108		if (e)
109			(*tif->tif_postdecode)(tif, (tidata_t) buf,
110			    tif->tif_scanlinesize);
111	}
112	return (e > 0 ? 1 : -1);
113}
114
115/*
116 * Read a strip of data and decompress the specified
117 * amount into the user-supplied buffer.
118 */
119tsize_t
120TIFFReadEncodedStrip(TIFF* tif, tstrip_t strip, tdata_t buf, tsize_t size)
121{
122	TIFFDirectory *td = &tif->tif_dir;
123	uint32 nrows;
124	tsize_t stripsize;
125        tstrip_t sep_strip, strips_per_sep;
126
127	if (!TIFFCheckRead(tif, 0))
128		return (-1);
129	if (strip >= td->td_nstrips) {
130		TIFFError(tif->tif_name, "%ld: Strip out of range, max %ld",
131		    (long) strip, (long) td->td_nstrips);
132		return (-1);
133	}
134	/*
135	 * Calculate the strip size according to the number of
136	 * rows in the strip (check for truncated last strip on any
137         * of the separations).
138	 */
139        if( td->td_rowsperstrip >= td->td_imagelength )
140            strips_per_sep = 1;
141        else
142            strips_per_sep = (td->td_imagelength+td->td_rowsperstrip-1)
143                / td->td_rowsperstrip;
144
145        sep_strip = strip % strips_per_sep;
146
147	if (sep_strip != strips_per_sep-1 ||
148	    (nrows = td->td_imagelength % td->td_rowsperstrip) == 0)
149		nrows = td->td_rowsperstrip;
150
151	stripsize = TIFFVStripSize(tif, nrows);
152	if (size == (tsize_t) -1)
153		size = stripsize;
154	else if (size > stripsize)
155		size = stripsize;
156	if (TIFFFillStrip(tif, strip) && (*tif->tif_decodestrip)(tif,
157	    (tidata_t) buf, size, (tsample_t)(strip / td->td_stripsperimage))) {
158		(*tif->tif_postdecode)(tif, (tidata_t) buf, size);
159		return (size);
160	} else
161		return ((tsize_t) -1);
162}
163
164static tsize_t
165TIFFReadRawStrip1(TIFF* tif,
166    tstrip_t strip, tdata_t buf, tsize_t size, const char* module)
167{
168	TIFFDirectory *td = &tif->tif_dir;
169
170	if (!isMapped(tif)) {
171		tsize_t cc;
172
173		if (!SeekOK(tif, td->td_stripoffset[strip])) {
174			TIFFError(module,
175			    "%s: Seek error at scanline %lu, strip %lu",
176			    tif->tif_name,
177			    (tif_long) tif->tif_row, (tif_long) strip);
178			return (-1);
179		}
180		cc = TIFFReadFile(tif, buf, size);
181		if (cc != size) {
182			TIFFError(module,
183		"%s: Read error at scanline %lu; got %lu bytes, expected %lu",
184			    tif->tif_name,
185			    (tif_long) tif->tif_row,
186			    (tif_long) cc,
187			    (tif_long) size);
188			return (-1);
189		}
190	} else {
191		if (td->td_stripoffset[strip] + size > tif->tif_size) {
192			TIFFError(module,
193    "%s: Read error at scanline %lu, strip %lu; got %lu bytes, expected %lu",
194			    tif->tif_name,
195			    (tif_long) tif->tif_row,
196			    (tif_long) strip,
197			    (tif_long)tif->tif_size-td->td_stripoffset[strip],
198			    (tif_long) size);
199			return (-1);
200		}
201		_TIFFmemcpy(buf, tif->tif_base+td->td_stripoffset[strip], size);
202	}
203	return (size);
204}
205
206/*
207 * Read a strip of data from the file.
208 */
209tsize_t
210TIFFReadRawStrip(TIFF* tif, tstrip_t strip, tdata_t buf, tsize_t size)
211{
212	static const char module[] = "TIFFReadRawStrip";
213	TIFFDirectory *td = &tif->tif_dir;
214	tsize_t bytecount;
215
216	if (!TIFFCheckRead(tif, 0))
217		return ((tsize_t) -1);
218	if (strip >= td->td_nstrips) {
219		TIFFError(tif->tif_name, "%lu: Strip out of range, max %lu",
220		    (tif_long) strip, (tif_long) td->td_nstrips);
221		return ((tsize_t) -1);
222	}
223	bytecount = td->td_stripbytecount[strip];
224	if (bytecount <= 0) {
225		TIFFError(tif->tif_name,
226		    "%lu: Invalid strip byte count, strip %lu",
227		    (tif_long) bytecount, (tif_long) strip);
228		return ((tsize_t) -1);
229	}
230	if (size != (tsize_t)-1 && size < bytecount)
231		bytecount = size;
232	return (TIFFReadRawStrip1(tif, strip, buf, bytecount, module));
233}
234
235/*
236 * Read the specified strip and setup for decoding.
237 * The data buffer is expanded, as necessary, to
238 * hold the strip's data.
239 */
240static int
241TIFFFillStrip(TIFF* tif, tstrip_t strip)
242{
243	static const char module[] = "TIFFFillStrip";
244	TIFFDirectory *td = &tif->tif_dir;
245	tsize_t bytecount;
246
247	bytecount = td->td_stripbytecount[strip];
248	if (bytecount <= 0) {
249		TIFFError(tif->tif_name,
250		    "%lu: Invalid strip byte count, strip %lu",
251		    (tif_long) bytecount, (tif_long) strip);
252		return (0);
253	}
254	if (isMapped(tif) &&
255	    (isFillOrder(tif, td->td_fillorder)
256	    || (tif->tif_flags & TIFF_NOBITREV))) {
257		/*
258		 * The image is mapped into memory and we either don't
259		 * need to flip bits or the compression routine is going
260		 * to handle this operation itself.  In this case, avoid
261		 * copying the raw data and instead just reference the
262		 * data from the memory mapped file image.  This assumes
263		 * that the decompression routines do not modify the
264		 * contents of the raw data buffer (if they try to,
265		 * the application will get a fault since the file is
266		 * mapped read-only).
267		 */
268		if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
269			_TIFFfree(tif, tif->tif_rawdata);
270		tif->tif_flags &= ~TIFF_MYBUFFER;
271		if ( td->td_stripoffset[strip] + bytecount > tif->tif_size) {
272			/*
273			 * This error message might seem strange, but it's
274			 * what would happen if a read were done instead.
275			 */
276			TIFFError(module,
277		    "%s: Read error on strip %lu; got %lu bytes, expected %lu",
278			    tif->tif_name,
279			    (tif_long) strip,
280			    (tif_long)tif->tif_size-td->td_stripoffset[strip],
281			    (tif_long) bytecount);
282			tif->tif_curstrip = NOSTRIP;
283			return (0);
284		}
285		tif->tif_rawdatasize = bytecount;
286		tif->tif_rawdata = tif->tif_base + td->td_stripoffset[strip];
287	} else {
288		/*
289		 * Expand raw data buffer, if needed, to
290		 * hold data strip coming from file
291		 * (perhaps should set upper bound on
292		 *  the size of a buffer we'll use?).
293		 */
294		if (bytecount > tif->tif_rawdatasize) {
295			tif->tif_curstrip = NOSTRIP;
296			if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
297				TIFFError(module,
298				"%s: Data buffer too small to hold strip %lu",
299				    tif->tif_name, (tif_long) strip);
300				return (0);
301			}
302			if (!TIFFReadBufferSetup(tif, 0,
303			    TIFFroundup(bytecount, 1024)))
304				return (0);
305		}
306		if (TIFFReadRawStrip1(tif, strip, (tif_char *)tif->tif_rawdata,
307		    bytecount, module) != bytecount)
308			return (0);
309		if (!isFillOrder(tif, td->td_fillorder) &&
310		    (tif->tif_flags & TIFF_NOBITREV) == 0)
311			TIFFReverseBits(tif->tif_rawdata, bytecount);
312	}
313	return (TIFFStartStrip(tif, strip));
314}
315
316/*
317 * Tile-oriented Read Support
318 * Contributed by Nancy Cam (Silicon Graphics).
319 */
320
321/*
322 * Read and decompress a tile of data.  The
323 * tile is selected by the (x,y,z,s) coordinates.
324 */
325tsize_t
326TIFFReadTile(TIFF* tif,
327    tdata_t buf, uint32 x, uint32 y, uint32 z, tsample_t s)
328{
329	if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s))
330		return (-1);
331	return (TIFFReadEncodedTile(tif,
332	    TIFFComputeTile(tif, x, y, z, s), buf, (tsize_t) -1));
333}
334
335/*
336 * Read a tile of data and decompress the specified
337 * amount into the user-supplied buffer.
338 */
339tsize_t
340TIFFReadEncodedTile(TIFF* tif, ttile_t tile, tdata_t buf, tsize_t size)
341{
342	TIFFDirectory *td = &tif->tif_dir;
343	tsize_t tilesize = tif->tif_tilesize;
344
345	if (!TIFFCheckRead(tif, 1))
346		return (-1);
347	if (tile >= td->td_nstrips) {
348		TIFFError(tif->tif_name, "%ld: Tile out of range, max %ld",
349		    (long) tile, (tif_long) td->td_nstrips);
350		return (-1);
351	}
352	if (size == (tsize_t) -1)
353		size = tilesize;
354	else if (size > tilesize)
355		size = tilesize;
356	if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif,
357	    (tidata_t) buf, size, (tsample_t)(tile/td->td_stripsperimage))) {
358		(*tif->tif_postdecode)(tif, (tidata_t) buf, size);
359		return (size);
360	} else
361		return (-1);
362}
363
364static tsize_t
365TIFFReadRawTile1(TIFF* tif,
366    ttile_t tile, tdata_t buf, tsize_t size, const char* module)
367{
368	TIFFDirectory *td = &tif->tif_dir;
369
370	if (!isMapped(tif)) {
371		tsize_t cc;
372
373		if (!SeekOK(tif, td->td_stripoffset[tile])) {
374			TIFFError(module,
375			    "%s: Seek error at row %ld, col %ld, tile %ld",
376			    tif->tif_name,
377			    (long) tif->tif_row,
378			    (long) tif->tif_col,
379			    (long) tile);
380			return ((tsize_t) -1);
381		}
382		cc = TIFFReadFile(tif, buf, size);
383		if (cc != size) {
384			TIFFError(module,
385	    "%s: Read error at row %ld, col %ld; got %lu bytes, expected %lu",
386			    tif->tif_name,
387			    (long) tif->tif_row,
388			    (long) tif->tif_col,
389			    (tif_long) cc,
390			    (tif_long) size);
391			return ((tsize_t) -1);
392		}
393	} else {
394		if (td->td_stripoffset[tile] + size > tif->tif_size) {
395			TIFFError(module,
396    "%s: Read error at row %ld, col %ld, tile %ld; got %lu bytes, expected %lu",
397			    tif->tif_name,
398			    (long) tif->tif_row,
399			    (long) tif->tif_col,
400			    (long) tile,
401			    (tif_long) tif->tif_size - td->td_stripoffset[tile],
402			    (tif_long) size);
403			return ((tsize_t) -1);
404		}
405		_TIFFmemcpy(buf, tif->tif_base+td->td_stripoffset[tile], size);
406	}
407	return (size);
408}
409
410/*
411 * Read a tile of data from the file.
412 */
413tsize_t
414TIFFReadRawTile(TIFF* tif, ttile_t tile, tdata_t buf, tsize_t size)
415{
416	static const char module[] = "TIFFReadRawTile";
417	TIFFDirectory *td = &tif->tif_dir;
418	tsize_t bytecount;
419
420	if (!TIFFCheckRead(tif, 1))
421		return ((tsize_t) -1);
422	if (tile >= td->td_nstrips) {
423		TIFFError(tif->tif_name, "%lu: Tile out of range, max %lu",
424		    (tif_long) tile, (tif_long) td->td_nstrips);
425		return ((tsize_t) -1);
426	}
427	bytecount = td->td_stripbytecount[tile];
428	if (size != (tsize_t) -1 && size < bytecount)
429		bytecount = size;
430	return (TIFFReadRawTile1(tif, tile, buf, bytecount, module));
431}
432
433/*
434 * Read the specified tile and setup for decoding.
435 * The data buffer is expanded, as necessary, to
436 * hold the tile's data.
437 */
438static int
439TIFFFillTile(TIFF* tif, ttile_t tile)
440{
441	static const char module[] = "TIFFFillTile";
442	TIFFDirectory *td = &tif->tif_dir;
443	tsize_t bytecount;
444
445	bytecount = td->td_stripbytecount[tile];
446	if (bytecount <= 0) {
447		TIFFError(tif->tif_name,
448		    "%lu: Invalid tile byte count, tile %lu",
449		    (tif_long) bytecount, (tif_long) tile);
450		return (0);
451	}
452	if (isMapped(tif) &&
453	    (isFillOrder(tif, td->td_fillorder) ||
454	    (tif->tif_flags & TIFF_NOBITREV))) {
455		/*
456		 * The image is mapped into memory and we either don't
457		 * need to flip bits or the compression routine is going
458		 * to handle this operation itself.  In this case, avoid
459		 * copying the raw data and instead just reference the
460		 * data from the memory mapped file image.  This assumes
461		 * that the decompression routines do not modify the
462		 * contents of the raw data buffer (if they try to,
463		 * the application will get a fault since the file is
464		 * mapped read-only).
465		 */
466		if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
467			_TIFFfree(tif, tif->tif_rawdata);
468		tif->tif_flags &= ~TIFF_MYBUFFER;
469		if ( td->td_stripoffset[tile] + bytecount > tif->tif_size) {
470			tif->tif_curtile = NOTILE;
471			return (0);
472		}
473		tif->tif_rawdatasize = bytecount;
474		tif->tif_rawdata = tif->tif_base + td->td_stripoffset[tile];
475	} else {
476		/*
477		 * Expand raw data buffer, if needed, to
478		 * hold data tile coming from file
479		 * (perhaps should set upper bound on
480		 *  the size of a buffer we'll use?).
481		 */
482		if (bytecount > tif->tif_rawdatasize) {
483			tif->tif_curtile = NOTILE;
484			if ((tif->tif_flags & TIFF_MYBUFFER) == 0) {
485				TIFFError(module,
486				"%s: Data buffer too small to hold tile %ld",
487				    tif->tif_name, (long) tile);
488				return (0);
489			}
490			if (!TIFFReadBufferSetup(tif, 0,
491			    TIFFroundup(bytecount, 1024)))
492				return (0);
493		}
494		if (TIFFReadRawTile1(tif, tile, (tif_char *)tif->tif_rawdata,
495		    bytecount, module) != bytecount)
496			return (0);
497		if (!isFillOrder(tif, td->td_fillorder) &&
498		    (tif->tif_flags & TIFF_NOBITREV) == 0)
499			TIFFReverseBits(tif->tif_rawdata, bytecount);
500	}
501	return (TIFFStartTile(tif, tile));
502}
503
504/*
505 * Setup the raw data buffer in preparation for
506 * reading a strip of raw data.  If the buffer
507 * is specified as zero, then a buffer of appropriate
508 * size is allocated by the library.  Otherwise,
509 * the client must guarantee that the buffer is
510 * large enough to hold any individual strip of
511 * raw data.
512 */
513int
514TIFFReadBufferSetup(TIFF* tif, tdata_t bp, tsize_t size)
515{
516	static const char module[] = "TIFFReadBufferSetup";
517
518	if (tif->tif_rawdata) {
519		if (tif->tif_flags & TIFF_MYBUFFER)
520			_TIFFfree(tif, tif->tif_rawdata);
521		tif->tif_rawdata = NULL;
522	}
523	if (bp) {
524		tif->tif_rawdatasize = size;
525		tif->tif_rawdata = (tidata_t) bp;
526		tif->tif_flags &= ~TIFF_MYBUFFER;
527	} else {
528		tif->tif_rawdatasize = TIFFroundup(size, 1024);
529		tif->tif_rawdata =
530			(tidata_t) _TIFFmalloc(tif, tif->tif_rawdatasize);
531		tif->tif_flags |= TIFF_MYBUFFER;
532	}
533	if (tif->tif_rawdata == NULL) {
534		TIFFError(module,
535		    "%s: No space for data buffer at scanline %ld",
536		    tif->tif_name, (long) tif->tif_row);
537		tif->tif_rawdatasize = 0;
538		return (0);
539	}
540	return (1);
541}
542
543/*
544 * Set state to appear as if a
545 * strip has just been read in.
546 */
547static int
548TIFFStartStrip(TIFF* tif, tstrip_t strip)
549{
550	TIFFDirectory *td = &tif->tif_dir;
551
552	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
553		if (!(*tif->tif_setupdecode)(tif))
554			return (0);
555		tif->tif_flags |= TIFF_CODERSETUP;
556	}
557	tif->tif_curstrip = strip;
558	tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
559	tif->tif_rawcp = tif->tif_rawdata;
560	tif->tif_rawcc = td->td_stripbytecount[strip];
561	return ((*tif->tif_predecode)(tif,
562			(tsample_t)(strip / td->td_stripsperimage)));
563}
564
565/*
566 * Set state to appear as if a
567 * tile has just been read in.
568 */
569static int
570TIFFStartTile(TIFF* tif, ttile_t tile)
571{
572	TIFFDirectory *td = &tif->tif_dir;
573
574	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
575		if (!(*tif->tif_setupdecode)(tif))
576			return (0);
577		tif->tif_flags |= TIFF_CODERSETUP;
578	}
579	tif->tif_curtile = tile;
580	tif->tif_row =
581	    (tile % TIFFhowmany(td->td_imagewidth, td->td_tilewidth)) *
582		td->td_tilelength;
583	tif->tif_col =
584	    (tile % TIFFhowmany(td->td_imagelength, td->td_tilelength)) *
585		td->td_tilewidth;
586	tif->tif_rawcp = tif->tif_rawdata;
587	tif->tif_rawcc = td->td_stripbytecount[tile];
588	return ((*tif->tif_predecode)(tif,
589			(tsample_t)(tile/td->td_stripsperimage)));
590}
591
592static int
593TIFFCheckRead(TIFF* tif, int tiles)
594{
595	if (tif->tif_mode == O_WRONLY) {
596		TIFFError(tif->tif_name, "File not open for reading");
597		return (0);
598	}
599	if (tiles ^ isTiled(tif)) {
600		TIFFError(tif->tif_name, tiles ?
601		    "Can not read tiles from a stripped image" :
602		    "Can not read scanlines from a tiled image");
603		return (0);
604	}
605	return (1);
606}
607
608void
609_TIFFNoPostDecode(TIFF* tif, tidata_t buf, tsize_t cc)
610{
611    (void) tif; (void) buf; (void) cc;
612}
613
614void
615_TIFFSwab16BitData(TIFF* tif, tidata_t buf, tsize_t cc)
616{
617    (void) tif;
618    assert((cc & 1) == 0);
619    TIFFSwabArrayOfShort((uint16*) buf, cc/2);
620}
621
622void
623_TIFFSwab32BitData(TIFF* tif, tidata_t buf, tsize_t cc)
624{
625    (void) tif;
626    assert((cc & 3) == 0);
627    TIFFSwabArrayOfLong((uint32*) buf, cc/4);
628}
629
630void
631_TIFFSwab64BitData(TIFF* tif, tidata_t buf, tsize_t cc)
632{
633    (void) tif;
634    assert((cc & 7) == 0);
635    TIFFSwabArrayOfDouble((double*) buf, cc/8);
636}
637